Injection (SQL, NoSQL, Command)
Injection happens when user input is treated as code instead of data.
Packages
| Package | Use |
|---|---|
pg / mysql2 | DB drivers with parameterized queries |
prisma / sequelize / knex | ORMs / query builders (parameterize for you) |
express-mongo-sanitize | Removes $ and . operators from input (NoSQL injection) |
execa / child_process.execFile | Run commands without a shell |
SQL injection
// ❌ input: id = "1 OR 1=1" → returns every row
db.query(`SELECT * FROM users WHERE id = ${req.params.id}`);
// ✅ parameterized: input is always data
db.query('SELECT * FROM users WHERE id = $1', [req.params.id]);
// ⚠️ ORMs have raw escape hatches. Avoid string building there too
prisma.$queryRawUnsafe(`... ${input}`); // ❌
prisma.$queryRaw`SELECT * FROM users WHERE id = ${input}`; // ✅ tagged template = parameterizedNoSQL injection (MongoDB)
// ❌ body: { "email": "a@b.com", "password": { "$ne": null } } → logs in without a password
User.findOne({ email: req.body.email, password: req.body.password });
// ✅ validate types first (see 03) and/or sanitize
const mongoSanitize = require('express-mongo-sanitize');
app.use(mongoSanitize());
const email = String(req.body.email);Command injection
const { exec, execFile } = require('child_process');
// ❌ filename = "a.png; rm -rf /"
exec(`convert ${filename} out.jpg`);
// ✅ no shell, args passed as an array
execFile('convert', [filename, 'out.jpg']);Other injection types
- LDAP, XPath, template injection (SSTI): never put user input into templates as code
- Log injection: strip
\nfrom user input before logging eval,new Function,vm: never with user input
Checklist
- 100% parameterized queries; grep the codebase for template strings inside
query( - Validate types so objects can't reach Mongo queries
- No
execwith user input; useexecFilewith an array - No
eval - The DB user has least privilege (see
17-infrastructure)