lessons/injection.md

Lesson 5 of 18

Injection: data must never become code

Injection happens when untrusted input is interpreted as part of a command.

Remember: Use parameters for values, allowlists for identifiers, argument arrays for processes, and allowlists for hosts.

Injection happens when untrusted input is interpreted as part of a command: SQL, a shell, an HTML page, an outgoing URL. The root cause is string building. The interpreter cannot tell your data from your instructions, so you have to keep them apart.

cur.execute(f"SELECT * FROM transactions WHERE account_id = {account_id}")
Vulnerable: string interpolation. account_id = “0 OR 1=1” changes the meaning of the query.
cur.execute("SELECT * FROM transactions WHERE account_id = %s", (account_id,))
Fixed: a parameter is always data. The driver sends the statement and the value separately.

Identifiers cannot be parameters

You cannot parameterise a column name or the direction of ORDER BY. Map the user's choice to a fixed value from an allowlist, for example ORDER_COLUMNS = {"date": "t.created_at"}.

Commands

Never pass input to a shell. Use an argument array (ProcessBuilder, subprocess with a list, execFile). Validate the value too: a host starting with “-” is read as an option.

SSRF

A server that fetches user-supplied URLs can reach networks the attacker cannot, including internal services and the cloud metadata address 169.254.169.254. Allowlist the hosts, require https, disable automatic redirects, and check the resolved IP address.

Whenever a string is built from input, stop and ask which interpreter receives it: SQL, a shell, HTML, or a URL. Each one has its own special characters.

Questions to ask yourself

  1. Which interpreter receives this string?
  2. Is the input a value, an identifier, a host, or a path?
  3. What can the interpreter do with a quote, a semicolon, or a leading dash?

Practise this