Lesson 260 of 296
SQL injection and command injection
What you will learn
- What injection is
- SQL injection: how it works, demonstrated
- Parameterised queries and why they work
- Dynamic identifiers, ORMs and stored procedures
- OS command injection and how to avoid it
- Other injection types
On this page
What is injection?
Injection happens when untrusted input is mixed into something that gets interpreted as code or commands: a SQL query, a shell command, an HTML page, an LDAP query, a template. The attacker crafts input that escapes from the "data" part and becomes instructions.
SQL injection, demonstrated
A login lookup built by joining strings:
type Db = { query(sql: string, params?: unknown[]): Promise<{ rows: Record<string, unknown>[] }> };
export async function findUserVulnerable(db: Db, email: string) {
return db.query(`SELECT id, email FROM users WHERE email = '${email}'`);
}
export async function findUserSafe(db: Db, email: string) {
return db.query("SELECT id, email FROM users WHERE email = $1", [email]);
}Normal input aisha@example.com builds a normal query. But the input ' OR '1'='1 builds:
SELECT id, email FROM users WHERE email = '' OR '1'='1'The quote closes the string early, and OR '1'='1' is always true, so the query returns every user. Tested against a real PostgreSQL engine with three users: the vulnerable function returned all 3 users for this input. With the input x' UNION SELECT id, password_hash FROM users --, the attacker could also read password hashes through the same query (-- starts a comment, removing the rest of the original query).
The safe function returned 0 rows for both attacks: the database searched for a user whose email is literally the text ' OR '1'='1, which does not exist.
Why parameters work
With a parameterised query (also called a prepared statement), the SQL text and the values travel to the database separately. The database parses and plans the query first, with a placeholder, and only then plugs in the value as pure data. No value can change the structure of the query, whatever characters it contains. This is the fix, not "escaping quotes" by hand, which is easy to get wrong (different databases, character sets, numeric contexts).
Real consequences of SQL injection: stolen databases, logins bypassed, data changed or deleted, and in some setups commands run on the server. It has caused some of the largest data breaches in history.
Things parameters cannot do: identifiers
Parameters work for values, not for table or column names or SQL keywords. For a user-chosen sort column (Lesson 197), use an allow-list:
const SORTABLE = { created: "created_at", total: "total_pence", name: "customer_name" } as const;
export function orderByClause(sortKey: string, direction: string): string {
const column = SORTABLE[sortKey as keyof typeof SORTABLE] ?? "created_at";
const dir = direction === "asc" ? "ASC" : "DESC";
return `ORDER BY ${column} ${dir}, id ${dir}`;
}Whatever the user sends, only known column names and ASC/DESC can reach the SQL.
ORMs and query builders
Prisma, Drizzle, TypeORM and Knex parameterise automatically, but raw-query escape hatches can reintroduce injection:
| Safe | Dangerous |
|---|---|
prisma.$queryRaw\... WHERE email = ${email}\`` (tagged template: parameterised) | prisma.$queryRawUnsafe("... WHERE email = '" + email + "'") |
knex("users").where({ email }) | knex.raw("... '" + email + "'") |
Never concatenate user input into SQL anywhere, including LIKE patterns, ORDER BY, LIMIT or JSON paths.
Extra layers (defence in depth): the application's database user has least privilege (no DROP, no superuser, Lesson 265); errors do not show SQL to users (Lesson 263); a WAF can block obvious attack strings, but it is not a fix.
OS command injection
Running shell commands with user input has the same problem:
import { exec, execFile } from "node:child_process";
import { promisify } from "node:util";
const execAsync = promisify(exec);
const execFileAsync = promisify(execFile);
export async function countLinesVulnerable(fileName: string): Promise<string> {
const { stdout } = await execAsync(`wc -l uploads/${fileName}`);
return stdout.trim();
}
export async function countLinesSafe(fileName: string): Promise<string> {
if (!/^[\w.-]+$/.test(fileName) || fileName.includes("..")) throw new Error("Invalid file name");
const { stdout } = await execFileAsync("wc", ["-l", `uploads/${fileName}`]);
return stdout.trim();
}execruns the string through a shell (/bin/sh), where;,&&,|,$(...)and backticks start new commands. The inputa.txt; touch /tmp/pwnedrunstouchtoo. In testing, the vulnerable function created the file; the attacker's command ran.execFileruns the program directly, passing arguments as a list. There is no shell, so;is just a character in a file name. The safe version also validates the name and blocks..(path traversal). In testing, it rejected the malicious name and no file was created.- Better still: avoid shell commands entirely when Node can do the job (
fs.readFileand count the lines). Never run commands built from input withshell: true.
Other injection types
| Type | Where | Defence |
|---|---|---|
| XSS | HTML and JavaScript in browsers (Lesson 261) | Output encoding, CSP |
| NoSQL injection | MongoDB queries receiving objects like {"$ne": null} instead of a string | Validate types with schemas; reject objects where strings are expected |
| Path traversal | File paths: ../../etc/passwd | Allow-list names, resolve the path and check it stays inside the base folder |
| Template injection | Server-side template engines evaluating user input | Never compile templates from user input |
| Header / log injection | Newlines in input written to headers or logs | Strip or encode control characters; structured logging |
| Prompt injection | Instructions hidden in content given to an AI model (Lesson 279) | Treat model input as untrusted; limit tool permissions |
How to say it in an interview
"Injection is untrusted input being interpreted as code. In SQL injection, input like quote OR 1 equals 1 closes the string and changes the query's logic, which can return every user or, with UNION, leak other tables. The fix is parameterised queries, where SQL and values are sent separately so values can never change the query's structure; for dynamic identifiers like sort columns I use allow-lists, and I avoid unsafe raw-query functions in ORMs. For command injection I never pass input to a shell: I use execFile with an argument array, validate inputs, or avoid shell commands entirely. I add least-privilege database users and safe error messages as extra layers."
Key words
| Word | Meaning |
|---|---|
| Injection | Untrusted input interpreted as code or commands |
| SQL injection | Input that changes a SQL query's structure |
| Parameterised query | SQL with placeholders; values sent separately |
| Allow-list | Only explicitly permitted values are accepted |
| Command injection | Input that runs extra shell commands |
| execFile vs exec | Run a program directly vs through a shell |
| Path traversal | Using ../ to reach files outside an allowed folder |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.