Description
If you concatenate request values into the SQL passed to MySQL2’s execute, those values can change the statement before it is prepared.
Potential impact
Changed conditions can expose other users’ records or bypass access checks. Write or schema privileges can allow changes, deletion or service disruption.
Remediation
Keep the SQL fixed and pass an array of values for its ? placeholders. Use value-binding methods in an ORM as well. Validate the format, length and permitted values, and check the caller’s right to read the requested record.
Examples
conn is an existing MySQL2 Promise connection or pool. Supply connection setup and error handling separately.
Before
javascript
const mysql = require('mysql2');
async function getUserById(req, res) {
let userId = req.query.userId;
let sql = "SELECT * FROM users WHERE id = " + userId; // Input is inserted directly into SQL
const [rows, fields] = await conn.execute(sql);
res.json(rows);
}
After
javascript
const mysql = require('mysql2');
async function getUserById(req, res) {
let userId = req.query.userId;
// Bind the value as a parameter
const [rows, fields] = await conn.execute(
"SELECT * FROM users WHERE id = ?", [userId]
);
res.json(rows);
}
conn.execute binds userId to the prepared statement’s ? placeholder.