NoSQL Injection — Security

Apa itu NoSQL Injection? Meskipun NoSQL database seperti MongoDB tidak menggunakan SQL, mereka tetap rentan terhadap injection attacks. NoSQL Injection memanfaa

Apa itu NoSQL Injection?

Meskipun NoSQL database seperti MongoDB tidak menggunakan SQL, mereka tetap rentan terhadap injection attacks. NoSQL Injection memanfaatkan operator query khusus yang disisipkan melalui input pengguna.

Contoh Serangan pada MongoDB

// Kode yang vulnerable
app.post("/login", async (req, res) => {
    const user = await db.collection("users").findOne({
        username: req.body.username,
        password: req.body.password
    });
    if (user) res.json({ success: true });
});

// Serangan: kirim JSON dengan operator
// POST /login
// {
//   "username": "admin",
//   "password": { "$ne": "" }
// }
// Query menjadi: find({ username: "admin", password: { $ne: "" } })
// Ini cocok dengan semua password yang bukan string kosong!

Operator MongoDB yang Sering Disalahgunakan

Pencegahan NoSQL Injection

1. Validasi Tipe Input

// Pastikan input adalah string, bukan object
app.post("/login", async (req, res) => {
    const { username, password } = req.body;

    if (typeof username !== "string" || typeof password !== "string") {
        return res.status(400).json({ error: "Invalid input" });
    }

    const user = await db.collection("users").findOne({
        username,
        password
    });
});

2. Gunakan Schema Validation

// Mongoose schema memaksa tipe data
const userSchema = new mongoose.Schema({
    username: { type: String, required: true },
    password: { type: String, required: true }
});

3. Sanitize Input

// Library: express-mongo-sanitize
const mongoSanitize = require("express-mongo-sanitize");
app.use(mongoSanitize()); // Menghapus karakter $ dan . dari input

4. Nonaktifkan $where dan mapReduce

Jika tidak dibutuhkan, nonaktifkan kemampuan menjalankan JavaScript di server MongoDB untuk mengurangi attack surface.

Yang akan kamu pelajari