Overview
Injection flaws in Node.js (Express) apps allow attackers to tamper with queries, commands, or code paths by supplying untrusted input. Real-world impact includes authentication bypass, data leakage, data corruption, and potential remote code execution when combined with unsafe system calls.
In Express apps, injection often arises when building SQL strings by concatenating req.query or req.body values, or when using NoSQL queries or shell commands that incorporate user input.
The consequences include data breaches, downtime, financial loss, and reputational damage; attackers may move laterally across systems.
Remediation focuses on parameterized queries, input validation, safe command handling, and restricting database privileges; adopt a secure development lifecycle to catch these patterns.
Code Fix Example
Node.js (Express) API Security Remediation
const express = require('express');
const mysql = require('mysql2/promise');
const app = express();
const pool = mysql.createPool({ host: 'localhost', user: 'root', password: '', database: 'test' });
// Vulnerable pattern
app.get('/user', async (req, res) => {
const username = req.query.username;
const sql = "SELECT * FROM users WHERE username = '" + username + "'";
try {
const [rows] = await pool.execute(sql);
res.json(rows);
} catch (e) {
res.status(500).send('Error');
}
});
// Fixed pattern
app.get('/user-secure', async (req, res) => {
const username = req.query.username;
const sql = "SELECT * FROM users WHERE username = ?";
try {
const [rows] = await pool.execute(sql, [username]);
res.json(rows);
} catch (e) {
res.status(500).send('Error');
}
});
app.listen(3000, () => console.log('Server running'));