Track 08 · Lesson 12 of 20Attacks and defenses

Track 08 · Attacks and defenses

SQL and command injection

Lesson 12 of 20· 8 min

If a server builds a database query or a shell command by gluing user input into a string, the input can change the command itself. This is a server-side bug, but every web developer should recognise it on sight.

SQL injection

Glue strings, then switch to parameters

The query the server runs

SELECT * FROM users WHERE username = 'ana' AND password = 'correct-horse'

Simplified for clarity: real apps never store or compare plain-text passwords. They store a slow hash such as bcrypt or Argon2.

Parameters keep data as data#

A parameterized query sends the SQL and the values separately: WHERE username = $1, with the username alongside. The database never parses the value as SQL, so quotes and dashes are just characters. ORMs and query builders do this for you, until someone reaches for the raw-query escape hatch with a template string.

Notice that the safe version also works for real names like O’Brien. Injection bugs are security holes and ordinary bugs at the same time.

The same bug in a shell#

Passing a string to a shell has the same problem with different punctuation: ;, &&, | and $( ) are syntax to the shell, even inside a file name.

Command injection

A thumbnail service and five file names

import { execSync } from "node:child_process"

// The whole line goes to /bin/sh, which reads ; && | $( ) as syntax
execSync(`convert ${file.name} -resize 200x200 thumb.png`)
  1. $ convert holiday.jpg -resize 200x200 thumb.png
    Thumbnail written.
A normal file. Try one of the other names.

Run programs with an argument array (execFile, spawn without shell: true) so there’s no shell to interpret anything. In CI, the same applies to pull-request titles and branch names, which the next track covers.

In a code review

CriticalBackend

SQL or command injection

Fix: Use parameterised queries and argument arrays everywhere; validate input types; run the database user with least privilege.

0 of 3 checked

Check yourself

Which is safe?