NoSQL Injection
Overview
NoSQL databases like MongoDB are vulnerable to injection attacks that exploit the query language structure. Unlike SQL injection, NoSQL injection often exploits JSON/object operators:
$whereclause with JavaScript execution- Operator injection:
{ "username": { "$gt": "" } }bypasses authentication $regexinjection for data enumeration
Detection Strategy
- MongoDB
$whereoperator with user input (arbitrary JS execution) - Direct use of request body as a query object without validation
findOne()/find()with unvalidated user objects
Remediation
- Never use
$wherewith user input - Sanitize input using
mongo-sanitizeor similar - Use schema validation (Mongoose)
- Explicitly define expected query fields
Vulnerable (Node.js):
const user = await User.findOne({ username: req.body.username, password: req.body.password });
// Attacker sends: {"username": {"$gt": ""}, "password": {"$gt": ""}}
Safe (Node.js):
const mongoSanitize = require('express-mongo-sanitize');
app.use(mongoSanitize());
// OR manually: ensure fields are strings
const user = await User.findOne({ username: String(req.body.username) });