SQL INJECTION
User input becomes database commands
The server (PostgreSQL or SQLite) runs: SELECT * FROM users WHERE name = '<name>' AND pass = '<pass>'. You type name = admin' -- and password = x. What happens?
The server builds a query by pasting the input between quotes: WHERE name = ‘ + name + ’. The database parses the whole string as SQL. A quote in the input ends the literal early, and whatever follows is parsed as code: a comment that deletes the password check, or an OR that matches every row.
The fix is to keep code and data apart. Send fixed SQL with ? placeholders and pass the values separately. The database parses the query first, then binds the values. A value cannot become syntax, whatever it contains.
# The input becomes part of the SQL text
sql = ("SELECT * FROM users WHERE name = '" + name +
"' AND pass = '" + password + "'")
row = db.execute(sql).fetchone()
# name = admin' --
# SELECT * FROM users WHERE name = 'admin' --' AND pass = 'x'
# └─ the rest is a comment
# (PostgreSQL, SQLite, SQL Server. MySQL needs whitespace after --,
# so there the attacker types "admin' -- " or "admin'#".)# The SQL text is fixed; inputs are bound after parsing
row = db.execute(
"SELECT id, pass_hash FROM users WHERE name = ?", (name,)
).fetchone()
# And do not store or compare plaintext passwords:
ok = row is not None and bcrypt.checkpw(password.encode(), row.pass_hash) Watch the parsed WHERE row. Under concatenation the attacker’s input changes the shape of the tree. Under bound parameters it stays (name = $1 AND pass = $2) for every input, the attacks return 0 rows, and o’brien logs in.
Three ordinary logins against the concatenating server. (o'brien gets a 500: the apostrophe already breaks the query.) Add one attacker login that gets in as a user whose password the attacker never typed.
GOAL: a login returns a user whose password was not typed
Make buildLogin(name, pass) return \{ sql, params \} with ? placeholders and the inputs in params. The grader runs it on the same SQL engine as the sim, with legitimate users (including o'brien) and injection payloads, and checks the SQL text never changes with the input. (Plaintext passwords stay to keep the query readable; see the code tab for the real comparison.)
Any query built with string formatting or +: login forms, search boxes, ORDER BY from a query string, raw SQL escape hatches in ORMs. The first sign is often a 500 for names with apostrophes. Drivers and ORMs bind parameters by default; identifiers (table, column, sort direction) cannot be bound and need an allowlist.
“What is SQL injection and how do you prevent it?” Show the payload and the query it produces. Say parameterized queries, and why: the statement is parsed before values are bound. Mention least-privilege database accounts and the identifier allowlist, and if a login query is involved, point out the plaintext password too.
USED IN
Chapters that build on this lesson.
- A security engineer's weekSecurity
- Secure code review and AppSecSecurity
- Security champions and paved roadsSecurity
- Security philosophies: defence in depth, least privilege, assume breach, risk not fearSecurity
- The map of security roles: AppSec, cloud, SecOps, GRC, red teamSecurity
- Threat modellingSecurity
- Why security engineering existsSecurity
- Security testing: fuzzing, scanners and abuse casesSoftware Testing and Quality