← Back to Backend, page 3

backend-0048 · Medium mid

How does SQL injection work, why do parameterized queries prevent it, and what do you do about parts of a query that cannot be parameters, such as column names?

SQL injection happens when user input is concatenated into the SQL text, so the input can change the structure of the query (OR '1'='1', or a second statement). With parameterized queries the SQL text and the values travel separately, so the database always treats the values as data. Values must always be parameters. Identifiers (column or table names), sort directions and similar parts cannot be parameters, so choose them from an allowlist in code, or quote them with a library function. Least-privilege database users limit the damage.

Full answer

The attack

  • Code: "SELECT * FROM users WHERE name = '" + name + "'". Input ' OR '1'='1 turns the condition into always true. Input x'; DROP TABLE users; -- ends the first statement and runs another one.

The defence

  1. Parameterized (prepared) queries: db.query('SELECT * FROM users WHERE name = $1', [name]). The driver sends the parameters separately from the SQL, and PostgreSQL never parses them as SQL. This also works for LIKE patterns (pass the pattern as the value), IN lists (= ANY($1)) and numbers.
  2. Allowlist for structure: ORDER BY column and direction, table names and operators come from a fixed map in code. If you must use an identifier from input, escape it with the driver's identifier function (pg: escapeIdentifier) after checking it against known names.
  3. Validate input type and length, as defence in depth (not the main defence).
  4. Least privilege: the application's database user should not own tables or run DDL, and should use only the permissions it needs.
  5. ORMs and query builders help, but raw fragments (sequelize.literal, knex.raw) can reintroduce the problem.
  6. Do not hide errors in logs, but never return database errors to users. Test with automated scanners and code review.

Second-order injection: data that was stored safely and later concatenated into a query. Parameterise there too.

javascript
const { Client } = require('pg');

(async () => {
  const db = new Client(); await db.connect();
  await db.query(`DROP TABLE IF EXISTS bk48_users; DROP TABLE IF EXISTS bk48_victim;
    CREATE TABLE bk48_users (id serial PRIMARY KEY, name text, secret text);
    INSERT INTO bk48_users (name, secret) VALUES ('asha', 'a-secret'), ('ravi', 'r-secret');
    CREATE TABLE bk48_victim (id int)`);
  const exists = async () => (await db.query("SELECT to_regclass('bk48_victim') IS NOT NULL AS e")).rows[0].e;

  const vulnerable = (name) => db.query(`SELECT name FROM bk48_users WHERE name = '${name}'`);          // string concatenation: do not do this
  const safe = (name) => db.query('SELECT name FROM bk48_users WHERE name = $1', [name]);

  const attack1 = "x' OR '1'='1";
  console.log('input                 :', attack1);
  console.log('concatenated returns  :', (await vulnerable(attack1)).rows.map((r) => r.name).join(', '), '(every user)');
  console.log('parameterized returns :', (await safe(attack1)).rows.length, 'rows');

  const attack2 = "x'; DROP TABLE bk48_victim; --";
  await vulnerable(attack2);
  console.log('victim table after the concatenated query:', (await exists()) ? 'still exists' : 'DROPPED');
  await db.query('CREATE TABLE IF NOT EXISTS bk48_victim (id int)');
  await safe(attack2);
  console.log('victim table after the parameterized one :', (await exists()) ? 'still exists' : 'DROPPED');

  // Identifiers cannot be parameters. Use an allowlist.
  const sortable = { name: 'name', id: 'id' };
  const listUsers = async (sortKey, direction) => {
    const column = sortable[sortKey];
    if (!column) throw new Error('invalid sort column');
    const dir = direction === 'desc' ? 'DESC' : 'ASC';
    return db.query(`SELECT name FROM bk48_users ORDER BY ${column} ${dir}`);
  };
  console.log('allowlisted sort      :', (await listUsers('name', 'desc')).rows.map((r) => r.name).join(', '));
  console.log('malicious sort column :', await listUsers('name; DROP TABLE x', 'asc').catch((e) => e.message));
  console.log('quoted identifier     :', db.escapeIdentifier('name"; DROP TABLE x; --'));

  await db.query('DROP TABLE bk48_users; DROP TABLE IF EXISTS bk48_victim');
  await db.end();
})();

Runs against the local PostgreSQL and attacks its own demo tables only. The concatenated query is shown to explain the bug, and it must never be used in real code. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): input : x' OR '1'='1 concatenated returns : asha, ravi (every user) parameterized returns : 0 rows victim table after the concatenated query: DROPPED victim table after the parameterized one : still exists allowlisted sort : ravi, asha malicious sort column : invalid sort column quoted identifier : "name""; DROP TABLE x; --"

Key points

  • Injection changes the structure of a query through concatenated input.
  • Parameterized queries send values separately from the SQL text.
  • Identifiers and keywords need an allowlist or proper quoting.
  • Use least-privilege database accounts.
  • Raw fragments in ORMs are still dangerous.

Common mistakes

  • Escaping quotes by hand.
  • Parameterising values but concatenating the ORDER BY from input.
  • Using raw query fragments in ORM code.
  • A database user with owner or superuser rights.
  • Showing database error messages to users.

Follow-ups

  • How do prepared statements differ from parameterized queries?
  • How do you pass an array to IN safely?
  • What is second-order SQL injection?

Tips

  • Show the vulnerable and the safe version.
  • Mention identifiers and allowlists.
  • Add least privilege.