NoSQL injection
NoSQL injection manipulates NoSQL query operators to bypass authentication and extract data from non-relational databases.
Material
NoSQL injection happens when an application builds a non-relational database query straight from user input without enforcing types. Because MongoDB and similar engines accept documents as objects, operators such as $ne or $regex end up inside the condition itself.
How it works
In a login flow, fragile code typically writes a query like findOne({username: req.body.username, password: req.body.password}). If req.body.password holds an operator object rather than text, that object is merged into the query document unchanged.
POST /login HTTP/1.1
Host: target.website
Content-Type: application/json
{"username":"admin","password":{"$ne":""}}A 302 response toward the dashboard means the password check was bypassed. The $ne operator compares the password field against an empty string, so every account with a non-empty password matches and the first document found can be used as-is.
const express = require("express");
const app = express();
app.use(express.json());
app.post("/login", async (req, res) => {
const user = await db.collection("users").findOne({
username: req.body.username,
password: req.body.password, // objek operator ikut terbawa ke kueri
});
res.json(user ? { ok: true } : { ok: false });
});Attack forms
- Authentication bypass with $ne, $gt, or $exists to find a document without ever knowing the password.
- Character-by-character guessing with $regex, since a pattern can be retried until it matches.
- Reading other collections through the $where operator or an aggregation stage, which pushes the injection well past a single endpoint.
- Injection into a wrongly typed column, for example $regex on a numeric field or $ne on a date field.
- Driver-specific variants, since some drivers only accept operators at the top level and the payload shape must match the calling layer.
Prevention
- Enforce types at the application boundary: cast the input into the expected shape, text for instance, before the query is built.
- Never forward a user-supplied object into the query layer; use a driver with parameterization so field names and values stay separated.
- Validate the body schema with a library such as Joi, Zod, or Marshmallow and reject unknown properties.
- Turn off server-side JavaScript execution in MongoDB so the $where operator cannot be used.
- Restrict the privileges of the application database account: use a user without write rights on unrelated collections and no access to system databases.
import re
from pymongo import MongoClient
USERNAME = re.compile(r"^[a-z0-9_]{3,32}$")
def login(username: str, password: str):
if not isinstance(username, str) or not USERNAME.match(username):
raise ValueError("username tidak valid")
client = MongoClient("mongodb://app:app@localhost:27017")
db = client["appdb"]
return db.users.find_one({
"username": username,
# nilai selalu string hasil hashing, bukan objek dari pengguna
"password": hash_password(password),
})Because JSON is a legitimate input format, testing has to tell plain strings from operator objects on every parameter. Probe each parameter that logically should only ever hold text.
Labs in this topic
Labs run on a domain separate from this site, so a payload cannot reach your account session.
Labs for this category land in Phase 2. The material is readable now.
Challenges in this category
Challenges from the PortSwigger Web Security Academy. The original labs run on PortSwigger domains, so the link opens there.