NoSQL injection is an attack that exploits applications using NoSQL databases — such as MongoDB, CouchDB, or Redis — by injecting malicious operators or expressions into database queries constructed from unsanitized user input. While the syntax differs from SQL injection, the fundamental issue is the same: trusting user input in query construction.
How It Works
NoSQL databases use various query formats instead of SQL. MongoDB, the most common target, uses JSON-like query documents with special operators. When an application passes user input directly into a MongoDB query without validation, an attacker can inject query operators to alter the query's logic.
A classic example targets authentication. An application might construct a login query like db.users.find({username: INPUT, password: INPUT}). If the application accepts JSON in the input fields, an attacker can submit {"$ne": ""} as the password value. The query becomes db.users.find({username: "admin", password: {"$ne": ""}}), which matches any document where the password is not empty — effectively bypassing authentication.
The $gt, $lt, $ne, $regex, and $where operators are commonly exploited. The $where operator is particularly dangerous because it accepts JavaScript expressions, potentially enabling server-side code execution. An attacker might use $regex to extract data character by character through boolean-based blind injection, similar to blind SQL injection techniques.
In applications that use HTTP query parameters, type manipulation is another vector. Some frameworks automatically parse array-like or object-like parameter syntax, converting username[$ne]=x into a nested object that becomes a query operator when passed to the database driver.
Prevention
Validate and sanitize all user input before incorporating it into database queries. Reject unexpected types — if a field should be a string, ensure it is a string and not an object. Use parameterized queries or the database driver's built-in methods that separate query structure from data. Disable or restrict dangerous operators like $where in application queries. Apply least-privilege principles to database accounts so that injected queries cannot access or modify data beyond the application's intended scope.
Why It Matters
The misconception that NoSQL databases are immune to injection attacks leaves many applications unprotected. As NoSQL adoption grows, so does the attack surface for NoSQL injection, making it a critical vulnerability class for modern web application assessments.
Need your application tested? Get in touch.