Fix NoSQL Injection in Sails
Sails.js and its underlying Waterline ORM are vulnerable to NoSQL injection if you're lazy with input handling. When you pipe raw request objects directly into model methods, attackers can inject MongoDB operators like $gt, $ne, or $regex to bypass authentication or exfiltrate the entire database. This is a classic 'Object Injection' vector where the ORM interprets the payload as logic rather than data.
The Vulnerable Pattern
async login(req, res) {
// CRITICAL VULNERABILITY: Passing the entire body to findOne
// Attacker sends: { "email": "[email protected]", "password": { "$ne": "" } }
const user = await User.findOne(req.body);
if (user) {
return res.ok('Authenticated');
}
return res.forbidden();
}
The Secure Implementation
The vulnerability exists because Waterline allows query criteria to be passed as objects. If an attacker provides an object instead of a string, they can use MongoDB query operators to manipulate the logic. To fix this: First, never pass req.body or req.query directly into a Waterline method. Second, strictly cast or validate that your inputs are scalars (strings/numbers) using 'typeof' checks or a validation library like Joi. Third, always construct an explicit criteria object so that user input is treated as a value, not a key-value pair of operators.
async login(req, res) { const { email, password } = req.body;// 1. Validate types to ensure they aren’t objects if (typeof email !== ‘string’ || typeof password !== ‘string’) { return res.badRequest(‘Invalid input types’); }
// 2. Use an explicit criteria object const user = await User.findOne({ email: email, password: password });
if (user) { return res.ok(‘Authenticated’); } return res.forbidden(); }
Your Sails API
might be exposed to NoSQL Injection
74% of Sails apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.