NoSQL injection

On this page 7

NoSQL injection is a class of attack in which untrusted input changes the structure or meaning of a query sent to a non-relational database, such as a document store, key-value store or wide-column database, so that the database executes logic the developer never intended. In database security, it is the NoSQL counterpart of SQL injection, but it usually abuses query operators, JSON objects or server-side JavaScript rather than string concatenation of SQL keywords.

The attack matters because many NoSQL drivers accept structured query objects directly from parsed request bodies. When an application passes user input into such an object without type checks, an attacker can replace a simple value with an operator expression and bypass authentication, extract records or exhaust server resources.

How NoSQL injection alters a query

NoSQL injection succeeds when the application treats attacker-controlled data as query syntax. In a document database, a login check may build a filter such as {username: input.user, password: input.pass}. If the web framework parses a request body into nested objects, the attacker can send {"$ne": null} as the password, and the filter becomes true for every account.

The root cause is the same as in SQL injection: data and instructions share one channel. The difference is the grammar. NoSQL query languages express conditions as objects, so the injected payload is often a JSON fragment with an operator key rather than a quote character followed by SQL text.

The following table lists the main injection vectors and the database features they abuse.

VectorAbused featureTypical payload pattern
Operator injectionComparison operators in query objects$ne, $gt or $regex in place of a value
JavaScript injectionServer-side evaluation such as $whereExpression that always returns true or loops
String concatenationQueries assembled as textQuote characters that close a string early
Aggregation injectionUser-supplied pipeline stagesExtra $lookup or $match stages
Key name injectionAttacker-chosen field namesKeys that start with $ or contain dots
Common NoSQL injection vectors

Attack outcomes and severity

The impact of NoSQL injection ranges from a single account takeover to full data disclosure, depending on what the query controls and which privileges the database connection holds. Blind techniques also exist: an attacker can use $regex conditions to extract a secret one character at a time by observing whether a response changes.

OutcomeExample situationSeverity
Authentication bypassPassword filter replaced by a not-equal operatorCritical
Data exfiltrationSearch filter widened to return every documentHigh to critical
Blind data extractionRegex probes reveal a token character by characterHigh
Denial of serviceCatastrophic regex or an endless $where loopMedium to high
Data modificationUpdate filter matches far more documents than intendedHigh
Outcomes of successful NoSQL injection

Severity grows sharply when the application connects with an over-privileged database role. A connection that may read every collection and run administrative commands turns a narrow logic flaw into a database-wide compromise.

NoSQL injection compared with SQL injection

NoSQL injection and SQL injection share a cause but differ in syntax, tooling and defenses. A common misconception is that NoSQL systems are immune because they lack SQL; in practice the risk moves to operators and object parsing.

AspectSQL injectionNoSQL injection
Payload formSQL fragments and quotesOperator objects, JSON or JavaScript
Entry pointConcatenated query stringsParsed request bodies and query parameters
Primary defenseParameterized queryStrict typing plus safe query builders
Detection toolingMature scanners and signaturesFewer, product-specific scanners
Language diversityOne broadly shared standardMany vendor-specific query languages
Differences between SQL and NoSQL injection

Because each NoSQL product has its own query grammar, a defense that works for one document database may not cover a key-value or graph store. Security reviews therefore need to be specific to the driver and query API that the application actually uses.

Preventing NoSQL injection

The decisive defense is to ensure that user input can only ever be a value, never an operator or a field name. Layered controls then limit the damage if one check fails.

ControlWhat it doesLimitation
Schema validation of inputRejects objects where a string is expectedMust cover every endpoint
Operator sanitizationStrips keys starting with $ or containing dotsCan break legitimate nested data
Typed query buildersBind values separately from query structureRaw query features may bypass it
Disabling server-side JavaScriptRemoves $where and similar evaluationSome legacy queries need rewriting
Least-privilege rolesLimits collections and commands per connectionDoes not stop logic bypass inside scope
Defensive controls and their purpose
  • Cast inputs explicitly, for example converting a password field with String() before it enters a filter.
  • Validate request bodies against a strict schema that forbids unexpected nested objects.
  • Never build queries by concatenating strings, even in NoSQL query languages that accept text.
  • Set timeouts and regex limits so that expensive expressions cannot exhaust the server.
  • Log rejected payloads and feed them into database activity monitoring for early detection.

Testing and detection mistakes

Many teams test only for classic SQL payloads and conclude that a NoSQL application is safe. Effective testing sends operator objects, array values and regex probes to every parameter, including JSON bodies, headers and cookies that the framework may parse into objects.

Another frequent mistake is relying on a web application firewall alone. Signature rules catch obvious strings such as $where, but encoded or nested payloads often pass, so input typing in application code remains the primary control and the firewall serves as an additional layer.

In plain words

A database query is like a form the application fills in before asking the database for something. NoSQL injection happens when an attacker manages to write instructions into a blank meant for plain data. Instead of typing a password, the attacker writes something that means “any password is fine”, and the database obeys.

The fix is simple in principle. The application must check every blank for the expected kind of data. A password blank should hold a short piece of text. A visitor must never be able to add new instructions to the form.

A real-world example

A small online shop runs a Node.js API backed by a document database. The login endpoint reads a JSON body and passes the username and password fields straight into a find query. During a penetration test, a consultant sends a password value of {"$ne": "x"} together with the username of an administrator and logs in without knowing the password.

The consultant then shows that the product search endpoint accepts a $regex filter, which allows extraction of reset tokens character by character within roughly 2,000 requests. The database connection also uses a role with read access to every collection, so customer addresses are exposed as well.

The development team adds schema validation that requires plain strings, sanitizes keys that start with a dollar sign, disables server-side JavaScript and moves the API to a role limited to three collections. A retest a week later finds no exploitable injection points, and failed attempts now appear in the monitoring dashboard.