NoSQL Injection
An injection attack against NoSQL databases (MongoDB, CouchDB) using query operators like $ne, $gt, or $regex to bypass authentication and extract data.
NoSQL Injection is a vulnerability that allows attackers to interfere with queries to NoSQL databases like MongoDB, CouchDB, or Redis. Unlike SQL injection, NoSQL injection often exploits JSON/BSON query operators or JavaScript evaluation to bypass authentication and extract data.
How It Works
NoSQL databases use different query languages and structures than SQL. When user input is incorporated into queries without proper validation, attackers can inject operators or code that changes the query's behavior.
Prevention
- Validate input types: Ensure strings are strings, not objects/arrays
- Use parameterized queries: MongoDB driver's parameterized methods
- Sanitize operators: Strip or reject
$prefixed keys from input - Disable JavaScript: Disable
$whereandmapReduceif not needed - Use schema validation: Mongoose schemas with strict types
Prevention Example
// Sanitize input to prevent operator injection
function sanitize(obj) {
if (typeof obj !== 'object' || obj === null) return obj;
const clean = {};
for (const key of Object.keys(obj)) {
if (key.startsWith('$')) continue; // Remove operators
clean[key] = sanitize(obj[key]);
}
return clean;
}
// Or enforce string type
const username = String(req.body.username);
const password = String(req.body.password);