Track 08 · Lesson 12 of 20Attacks and defenses
- 01What HTTPS protects
- 02The same-origin policy
- 03CORS
- 04Security headers
- 05Cookies done right
- 06Cross-site scripting (XSS)
- 07Content Security Policy
- 08Cross-site request forgery (CSRF)
- 09Clickjacking
- 10Unsafe URLs and open redirects
- 11Prompt injection
- 12SQL and command injection
- 13Prototype pollution, CRLF and SVG
- 14Server-side request forgery (SSRF)
- 15Remote code execution and denial of service
- 16Spoofed headers
- 17Rate limiting
- 18Cache poisoning
- 19The OWASP Top 10
- 20The attack lab
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`)$ convert holiday.jpg -resize 200x200 thumb.pngThumbnail written.
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
CriticalBackendSQL 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