The scanner sent {"$ne": null} and the login returned 200. What else does that prove? NoSQL injection against MongoDB as a DAST finding: JSON bodies versus query-string brackets, null and missing fields, $regex extraction, $where and server-side JavaScript, and what type checks, key stripping and sanitizeFilter actually stopped

DedSec Security Research ·

Here is a hypothetical. A dynamic scan of two Node.js services that use MongoDB returns four results. The first is "NoSQL injection: authentication bypass", rated critical, on the JSON login of the first service: the scanner sent {"username": "admin", "password": {"$ne": null}} and got a 200 with a session. The team adds a middleware that strips keys beginning with $, the retest gets a 401, and the finding is closed. The second service sets Express's query parser to simple. The scanner sent password[$ne]=x in the query string and got a 200 as admin. The team knows the simple parser cannot build an object, reasons that no $ne reached the database, and closes the finding as a scanner false positive. The third is "possible NoSQL injection (error-based)", rated high, on a third login route that answered {"$ne": null} with a 500. The fourth is "time-based NoSQL injection" on a user lookup, where a sleep(500) payload delayed the response by ten seconds.

As in the earlier posts in this series, each decision rests on the title, not on what the scanner observed and what that observation can prove. In our lab, built to reproduce this scenario, the first finding was real, and the fix closed the operator payload while leaving a bypass that needs no operator at all: sending "password": null logged in an account that had no password field, with the middleware in place. On the second service the team's reasoning about the parser was right, and the finding was still real. Its MongoDB driver was configured with ignoreUndefined: true. The parser turned password[$ne]=x into a missing password, the driver dropped the missing field, and the filter that reached the database held only the username. Leaving the password out entirely did the same. The 500 on the third route came from a .trim() call on a non-string, and the database was never queried. The fourth was a true positive, and its ten seconds were twenty documents times 500 milliseconds. The delay scales with the collection, so the same probe against a large collection is a denial of service.

This post is for whoever is holding a NoSQL injection finding against MongoDB from a dynamic scan, or a clean result they are about to rely on. It covers:

It is the nineteenth post in a series about confirming DAST findings. The earlier ones cover reflected XSS, SQL injection, OS command injection, Nuclei template matches, ffuf content discovery, path traversal, open redirect, SSRF through URL-fetch parameters, XXE, CRLF header injection, Host header injection, HTTP request smuggling, CORS misconfiguration, JWT validation, Arjun parameter discovery, server-side template injection, CSRF and GraphQL. The nearest neighbour is the SQL injection post, which covers the same boolean, error and time evidence for a query language that is built from strings. MongoDB queries are built from objects, and most of what is different follows from that.

Sources, and how each was checked. We made the measurements below on our test machine early on 7 November 2026, India time (the evening of 6 November UTC). It runs Ubuntu 24.04.4 on a virtual machine with two vCPUs of an AMD EPYC 9354P. Every database, server and client ran as a non-root user inside a Linux network namespace whose only interface was loopback. Before each run we checked the isolation: the name example.com did not resolve and a TCP connection to 1.1.1.1 failed. The packages were installed once beforehand from the npm registry, on the host network and with install scripts disabled; nothing in the lab itself reached any other host. The software was:

The vulnerable handlers are deliberate lab constructs. The main login builds its filter as { username: body.username, password: body.password } and compares plaintext passwords. No real application should store passwords that way, and the post says where hashing changes the picture. The other routes are variations, each written to reproduce one pattern on purpose: a hashed login, a reset-token check, a type-checked login, a login that throws on non-strings, the same login behind express-mongo-sanitize, a $where lookup built by string concatenation, a lookup that echoes its input, a login with a lockout, and Mongoose routes with and without sanitizeFilter. Every handler logs the filter it hands to the driver, so each result below is matched to the query that produced it.

We read the behaviour of Express, body-parser, express-mongo-sanitize, Mongoose and bson from their installed source, and the quotations from them below were checked against those files. We did not fetch MongoDB's documentation for this post. Where we describe what MongoDB 8.0.20 does, it is what the server did and logged in the lab. We did not run any scanner, Nuclei template or NoSQL injection tool. We did not test MongoDB Atlas, replica sets, access control, any driver other than Node.js, any framework other than Express, aggregation pipelines built from input, $function, $accumulator, mapReduce, update or insert operators supplied by a client, or any database other than MongoDB. The opening scenario is hypothetical. The numbers measure our lab, one server build and one set of package versions, and none of them measures AppSecD or how any product tests for NoSQL injection.

What MongoDB operator injection is, in mechanism

A SQL query is a string, and SQL injection is input that changes the string's grammar. A MongoDB query is a document. The filter { username: "admin", password: "x" } means "username equals admin and password equals x". The filter { username: "admin", password: { $ne: null } } means "username equals admin and password is not null". MongoDB reads an object whose keys start with $ as a set of operators, so the second filter matches admin whatever the password is.

The application does not build that object by concatenating anything. It writes password: body.password and expects a string. The injection is that body.password arrives as an object, because something between the network and the handler, a JSON parser or a query-string parser, built one. That makes it a type confusion. No character needs escaping, because there is no string to escape. It is filed under CWE-943, improper neutralization of special elements in data query logic.

Against e4, the JSON login answered as follows. Each line is one request:

The e5 profile gave identical results for all of them, because express.json() builds the same objects on both versions. The last line matters for triage. An unknown-operator error proves that an object from the request reached the database as part of a filter. It does not prove a bypass, but it is strong evidence that one is a payload away.

Two JSON requests did not reach the query at all. A truncated body got a 400 with SyntaxError: Unexpected end of JSON input from the parser. The same $ne document sent as text/plain got a 401, because express.json() only parses application/json, so the handler saw no username and no password.

Where the object comes from: parsers, measured

A JSON body is the obvious way to deliver an object. The less obvious way is the query string or a form body, where password[$ne]=x means nothing to HTTP. Whether it becomes { $ne: "x" } depends entirely on which parser the application uses. Express 4's application.js sets this.set('query parser', 'extended'), which is qs. Express 5's sets this.set('query parser', 'simple'), which is Node's querystring. For form bodies, express.urlencoded() uses qs when extended is true. In body-parser 1.20.9, leaving extended unset logs a deprecation warning and then behaves as true (var extended = opts.extended !== false).

We sent the same inputs to the same handler under the four parser profiles. All but the last used username admin:

Inpute4e4plaine5e5ext
GET password=nope (baseline)401401401401
GET password[$ne]=x200 admin401401200 admin
GET password[%24ne]=x (dollar sign percent-encoded)200 admin401401200 admin
GET password[$regex]=.*200 admin401401200 admin
POST form password[$ne]=x200 admin401401200 admin
GET username=sso_dave, no password200 sso_dave200 sso_dave200 sso_dave200 sso_dave

The extended parsers built the operator, and percent-encoding the dollar sign as %24 made no difference, because decoding happens before parsing. We did not test encoded brackets. That is worth knowing if a WAF rule looks for a literal $ne.

The handler's log shows what the simple parsers did instead. They did not stringify the payload into "x", and they did not reject it. They produced a key literally named password[$ne], so body.password was undefined, and the filter that reached the driver had no usable password value. Against admin that returned 401, and the scanner in the opening scenario would report the endpoint clean. The last row of the table shows why that is not the end of it.

Null and missing fields: the bypass with no operator

The driver has to send something for password: undefined. bson 7.3.4 with its default ignoreUndefined: false serialises it as BSON null: BSON.serialize({p: undefined}) produced the bytes 080000000a700000, and 0x0a is the null type, which deserialises to {"p": null}. In a MongoDB filter, equality with null also matches a document where the field does not exist.

So sso_dave, the SSO-only account with no password field, logged in on all four parser profiles:

Now the driver option. With ignoreUndefined: true, bson leaves an undefined field out of the document altogether. BSON.serialize({p: undefined}, {ignoreUndefined: true}) deserialised to {}. A filter of { username: "admin", password: undefined } then reaches the server as { username: "admin" }, and on the two ignoreUndefined profiles:

This is the second finding in the opening scenario. The team was right that no operator reached the database, and wrong to conclude there was no bug. The fix that follows from "operator injection" is to block $ keys, and no $ key ever reached that handler: with express-mongo-sanitize in front of it, the same request still logged in as admin, as the section on defences below shows.

Login bypass as boolean evidence, and what hashing changes

A login that returns 200 for an operator payload and 401 for a wrong password is the clearest boolean evidence there is: two inputs, two different outcomes, and one of them is a session. It is the NoSQL equivalent of the true-versus-false pair in the SQL injection post.

It only works when the password is compared inside the query, which is the plaintext pattern. An application that stores a hash compares it in code: find the user by username, then check the hash. On the lab's hashed login:

The operator still reached the database, so the injection is still there. It just no longer decides the outcome on that route. In applications that hash passwords, the place where a matched document is the outcome is often somewhere else: a password-reset token, an email-verification code, an invitation or an API-key lookup. The lab's reset check does findOne({ resetToken: body.token }) and reports whether a token is valid. Only bob has one.

Whether a reset flow then lets someone set the password depends on what the next step checks, and we did not build that step. The finding is that the token check said valid for a token nobody had.

$regex as a differential channel

The reset check is an oracle: it returns 200 when a filter matches and 404 when it does not. With $regex the filter can ask a question about the secret's contents. {"token": {"$regex": "^a"}} is true only if a token starts with a. Repeating the question one character at a time recovers the token. Against e4, with the result checked against the token the seed script wrote:

The numbers are small because hex has sixteen symbols and the secrets are short. A wider alphabet or a longer secret costs more requests, roughly the logarithm of the alphabet per character for the binary search. None of it needs a 200 from a login. Any response that differs between match and no match will do: a status code, a length, an error message, or a different redirect.

$where and server-side JavaScript in MongoDB 8.0.20

$where takes a JavaScript expression and evaluates it for each document. It takes a string, so input concatenated into it is ordinary code injection. The lab's lookup builds { $where: "this.username == '" + name + "'" }. With scripting enabled, the default:

So in 8.0.20 $where still runs, and sleep() is still available inside it. The server did record a deprecation. Its log has a warning-level line, "$where is deprecated. For more information, see https://www.mongodb.com/docs/manual/reference/operator/query/where/". It appeared once in that process's log, although 16 $where queries reached it during the run. Deprecated is not removed, and the warning is in the server log, not in the response, so a client never sees it.

With --noscripting, every $where query failed with a 500 and no globalScriptEngine in $where parsing, code 6108304. That includes the harmless alice lookup, so turning scripting off breaks a route that depends on $where rather than making it safe to keep. Mongoose passed $where straight through too: User.find(req.body) with a body of {"$where": "true"} returned all 20 users.

Time-based evidence: unavailable, or dangerous

For SQL injection a time delay is a standard blind channel. For the operator payloads we sent, there was no delay primitive. An operator changes which documents match, not how long matching takes. We timed seven requests of each against e4:

Neither regex produced a delay that would stand out from network jitter on our short values. We did not test long field values or other patterns, so this is not a claim that regex timing never works, only that it did not here. The operator payloads were confirmed by their boolean effect, not by time.

In the lab, time worked only through server-side JavaScript, and there it is dangerous. sleep(100) in the lab lookup took a median of 2,015 ms over three requests, because the expression ran for each of 20 documents. The delay is the per-document sleep multiplied by the number of documents the query scanned, which a tester does not know in advance. By the same arithmetic, a 100 ms probe that scanned a million documents would sleep for 100,000 seconds, more than a day, if nothing stopped it. We did not test a large collection or any server-side time limit. A DAST tool that probes $where with a fixed sleep can turn a detection into a denial of service on a production database. With --noscripting, the same request failed in a median of 5.3 ms with the error above, so a time-based check would see no delay and report nothing, which is correct.

What stopped it, and what it let through

Each defence below was tested against the same inputs.

A type check. The type-checked login refuses with 400 if either field is not a string. {"$ne": null} got 400. "password": null for sso_dave got 400. An omitted password got 400 even on the ignoreUndefined profile. alice's real login got 200. It was the only defence in the lab that stopped all three paths: operators, null, and missing fields.

express-mongo-sanitize 2.2.0. Its source tests keys against /^\$|\./ and deletes the ones that match, from req.body, req.params, req.headers and req.query. On Express 4, "password": {"$ne": null} got 401: the handler's log shows the filter became password: {}, which matches nothing. A key containing a dot was stripped the same way. password[$ne]=x on the extended parser got 401. But:

Mongoose 9.12.0 with sanitizeFilter. Its source wraps any value that has $ keys in $eq, recurses into $and, $or and $nor, and throws on $where, $expr, $jsonSchema and $text keys. With it on:

Without sanitizeFilter, the Mongoose login took {"$ne": null} and logged in as admin, and "password": null for sso_dave got 200 as well. With Mongoose's default connection options, an omitted or null password for admin returned 401, with and without sanitizeFilter. We did not test Mongoose with ignoreUndefined set.

Mongoose strictQuery. The schema sets strictQuery: true, which removes filter paths the schema does not define. That is not an injection defence, and in one case it widened the result. User.find({"notAField": "x"}) returned all 20 users, with and without sanitizeFilter. The unknown path was removed, which left an empty filter, and an empty filter matches everything. {"role": {"$ne": "user"}} returned admin, because role is a schema path and its operator was kept.

False positives and false negatives a scanner hits

Every one of these was measured in the lab. Each is a way for a response difference to mean something other than what the finding says, or for no difference to hide a real bug.

Confirming a finding by hand

The procedure below is general practice. It needs authorisation to test the target and should use accounts you control. Do not send $where sleep payloads to a production database, for the reason given above.

  1. Establish the baselines. A real login or lookup with a test account, and a wrong one. Repeat the wrong one a few times and watch for a lockout or rate limit, so you know which differences are the application's own.
  2. Find out what the parser builds. Send the payload as a JSON body with application/json, as field[$ne]=x in the query string, and as the same in a form body. If you can see logs or a debugger, read the filter the handler builds. If you cannot, compare an unknown operator such as {"$foo": 1} with a plain wrong value: a database error that names the operator means an object reached the query.
  3. Get boolean evidence. A pair of payloads that should be true and false, for example {"$ne": null} and {"$eq": "definitely-not-the-value"} on the same field, sent from the same session state. Confirm the true one changes the outcome and the false one does not.
  4. Test null and missing fields separately. Send the field as null, then leave it out, against an account that has the field and, if you have one, an account that does not. This is the path that key stripping does not cover.
  5. If the outcome is a lookup, test the lookups that are not logins. Reset tokens, verification codes, invitations and API keys. Use $ne, $exists and null, and note which account the match returned.
  6. Measure a differential channel, briefly. One $regex prefix that should match your own test secret and one that should not. You are establishing that the channel exists. Count, do not extract someone else's data.
  7. Treat $where as code injection. If a lookup builds a JavaScript string, a boolean pair such as ' || '1'=='1 against a name that does not exist confirms it without timing. Use time only on a test instance, with a small sleep, and remember it multiplies by documents.
  8. Keep the evidence: each request and response, the account and its state, the Content-Type, and the filter if you could see it.

The fix

All of this is general practice, except where it says it was measured.

The static side

Some of this is visible in source and some is not. Static analysis can see a filter built from request data without a type check, a call to find() with req.body as its argument, a $where built by concatenation, an ignoreUndefined option, and which query parser an Express app sets. Those are real, checkable facts about the code.

It is harder to see the type confusion itself. { password: req.body.password } is an ordinary object literal, and whether it is dangerous depends on what the parser produced at runtime, which is configuration, framework version and Content-Type. A rule that flags every request value used in a filter will also flag the many where a schema validator upstream already guarantees a string, and it cannot know about that validator unless it models it. That is the sanitiser-against-the-wrong-sink-class problem the SAST false-positive post describes: a key-stripping sanitiser on the path looks like a sanitiser, and it does nothing for null. We did not run a static rule against the lab.

What source does not show at all:

A triage checklist for a DAST NoSQL injection finding

  1. What did the payload actually become? An operator from JSON, an operator from an extended parser, or a missing field from a simple one? If you can read the filter, read it.
  2. Is the evidence boolean or just a difference? A true-and-false pair that changes the outcome is evidence. A 500, a length change or a status change on its own is a lead. Check it against reflection, lockouts and type errors.
  3. Did the 500 come from the database? An unknown-operator error is the database. A TypeError, a validation error or a CastError is the application, and a CastError may be the defence.
  4. Does null or absence match? Test both, against an account with the field and one without.
  5. Is the driver option ignoreUndefined set? If so, a missing field may match anything.
  6. Is the secret compared in the query? If it is hashed and compared in code, look for the lookup that does decide the outcome: reset, verification, invitation, API key.
  7. Is there a differential channel? Count how many requests a $regex prefix test would need. Do not extract.
  8. Is server-side JavaScript involved? If $where is built from input, it is code injection, and time-based probes against it scale with the collection.
  9. Did the fix handle more than $ keys? A retest that only resends the operator payload will pass a fix that leaves null open, which is the trap the scan-passed post describes.
  10. For a clean result: did the scan send JSON with the right Content-Type, reach the routes that take a body, and test null? The crawler-coverage post covers what a scan never reached, and the Arjun post covers the parameters it never knew about.

The hypothetical findings, resolved

Back to the four findings.

Authentication bypass on the JSON login. True positive. The operator payload logged in as admin, and the key-stripping middleware stopped that payload. It was reopened because "password": null still logged in the SSO-only account through the same middleware. In the lab, the type-checked route refused operators, null and missing passwords. A real fix would be confirmed by sending all three.

Operator injection on the simple-parser service, closed as a false positive. The team was right that password[$ne]=x is not an operator on that parser. On the lab's version of that service, with ignoreUndefined: true, it became a missing password and logged in as admin, leaving the password out did the same, and both still worked behind express-mongo-sanitize. It was reopened. The finding to file is not "operator injection". It is "a missing field matches any value", and the fix is the type check, not key stripping. In the lab the type-checked route refused the omitted password with 400 on the ignoreUndefined profile.

Error-based NoSQL injection on the third login. False positive. The 500 was a TypeError from .trim() on a non-string, and the handler's log shows no query was built for those requests. It was closed as not injectable, with a note to return 400 for wrong types.

Time-based injection on the lookup. True positive, and code injection rather than operator injection: the lookup concatenated input into a $where expression. The ten seconds were twenty documents times 500 ms, so the probe itself was a load test against the collection. The fix in the scenario is to replace $where with an ordinary equality filter on a type-checked string, and to run the database with scripting disabled if nothing else needs it. We did not implement that replacement in the lab; we only confirmed that --noscripting made every $where query fail.

Where AppSecD fits

AppSecD's dynamic and API testing runs Nuclei, Dalfox, SQLMap, Commix, Katana, Arjun, FFuf and Interactsh for out-of-band detection, plus 150+ native checks and API discovery across 50+ web frameworks. That line, and the shorter versions of it elsewhere in data/products.ts, are the whole of what the file says about its dynamic testing, and none of them mentions NoSQL, MongoDB or operator injection, so this post does not claim AppSecD tests for any of it; the measurements, the confirmation procedure, the fixes and the checklist above are general practice that apply to any scanner's output, ours included.

The scenario in this post is hypothetical and does not describe any deployment, user or finding.

More about AppSecD · All posts