parameters, not string glue
type ' OR 1=1 -- into a login form and watch it become code. bound parameters and prepared statements.
- address
- everything.writes.parameters_and_injection
- part
- part 5, changing data
- chapter
- chapter 7 of 10
- reading time
- 10 min
SQL injection is user input that ends up being parsed as SQL. glue a value into a query string and a single quote in it closes your string literal: everything after it is code, written by whoever typed it.
a bound parameter is sent separately, after the query has been parsed, so it can only ever be a value. use parameters for every value. identifiers can't be parameters: quote them with format('%I') and check them against a list.
the picture
you know the login form that looks up a user by email? somewhere behind it is a line like "... WHERE email = '" + email + "'". it works for every email anyone has ever typed. then someone types a quote.
think of a form letter with a blank: "dear ____, your order has shipped." a mail merge fills the blank with a name. now imagine the letter is read aloud by someone who obeys any instructions in it, and a customer's name is "Bob. also, refund every order". string glue is that. a bound parameter is a letter where the blank is a sealed envelope: whatever's inside is read as a name, and only as a name.
SELECT id, name FROM customers WHERE email = '' OR 1=1 --' ORDER BY id;
SELECT id, name FROM customers WHERE email = $1 ORDER BY id;
the quote ends the string, and what follows is part of the WHERE clause now. -- comments out the app's own leftovers (struck through), so the query still parses.
' OR 1=1 -- is four tokens of SQL and one comment. the quote ends the email string (it's now the empty string), OR 1=1 is true for every row, and -- comments out the app's closing quote and its ORDER BY, so what's left still parses. the WHERE that was supposed to find one customer finds all of them.
the real thing, on shop
shop's customers table has 2,000 rows and one Ada. here's the app's query with her email glued in, and then with the try from the figure. (each is wrapped in a count, on lines of its own, so a -- inside ends at the line break and the page doesn't print 2,000 rows. the inner line is exactly what concatenation produces.)
SELECT count(*) AS rows FROM (
SELECT id, name FROM customers WHERE email = 'ada@example.com' ORDER BY id
) AS app_query;
SELECT count(*) AS rows FROM (
SELECT id, name FROM customers WHERE email = '' OR 1=1 --' ORDER BY id
) AS app_query;| rowsint8 |
|---|
| 1 |
| rowsint8 |
|---|
| 2000 |
1 row, then 2,000. every block here runs on a fresh copy of shop, so nothing you run sticks, injections included.
-- the app runs the glued query, takes the first row it gets
-- back, and logs you in as that customer. the email was:
-- ' OR 1=1 --the third try, '; DROP TABLE customers; --, uses a semicolon to end the first statement and start a second one. psql, and any client that sends a plain query string, runs both:
SELECT id, name FROM customers WHERE email = ''; DROP TABLE customers; --' ORDER BY id;| idint4 | nametext |
|---|
the SELECT ran (0 rows), then DROP TABLE customers ran too. it failed only because the orders table has a foreign key pointing at customers. that's luck, not security. the actual safety net here is permissions: an application's database role has no business being allowed to drop tables (roles and GRANT).
parameters
the fix is to never put the value into the SQL text at all. the query goes to the server with a numbered slot ($1), and the value goes separately. in SQL you can do this with PREPARE and EXECUTE:
PREPARE login(text) AS
SELECT id, name FROM customers WHERE email = $1 ORDER BY id;
EXECUTE login('ada@example.com');
EXECUTE login(''' OR 1=1 --');| idint4 | nametext |
|---|---|
| 42 | Ada Lovelace |
| idint4 | nametext |
|---|
1 row, then 0. the second EXECUTE looked for a customer whose email is, character for character, ' OR 1=1 --, and there isn't one. (the doubled quotes are only how you write a quote inside a literal in this one SQL demo. a driver never needs them.) the server keeps the parsed statement, slot and all:
SELECT name, statement, parameter_types FROM pg_prepared_statements;| nametext | statementtext | parameter_typesregtype[] |
|---|---|---|
| login | {text} |
your application never types PREPARE. drivers speak postgres's extended query protocol, which splits one query into separate messages:
hover a stage.
that last point closes the ; DROP TABLE door too. through the extended protocol, two statements in one query string are refused outright. recorded with node-postgres 8.23.1 against postgres 18.6, sending SELECT id FROM customers WHERE email = $1; DROP TABLE customers with one parameter:
ERROR: cannot insert multiple commands into a prepared statement (SQLSTATE 42601)here's the same lookup in three drivers. the shape is always the same: the SQL is a constant with placeholders, and the values travel next to it.
# psycopg 3 binds on the server: postgres receives $1, not the email
cur.execute(
"SELECT id, name FROM customers WHERE email = %s ORDER BY id",
(email,),
)try (PreparedStatement ps = conn.prepareStatement(
"SELECT id, name FROM customers WHERE email = ? ORDER BY id")) {
ps.setString(1, email);
try (ResultSet rs = ps.executeQuery()) { /* ... */ }
}const { rows } = await client.query(
"SELECT id, name FROM customers WHERE email = $1 ORDER BY id",
[email],
);the placeholder spelling differs (%s, ?, $1), and with each driver's default settings what reaches postgres is $1. the java book walks through JDBC's side of this, PreparedStatement and all, in JDBC. a prepared statement can also save planning on repeat runs; that's a separate story, told in prepared statements and generic plans.
why escaping by hand is the wrong fix
the tempting fix is to keep gluing and escape the quotes first: replace every ' with ''. it handles the try in the figure. it's still the wrong fix, three ways.
not every value sits in quotes. a number glued into WHERE id = + id has no string to break out of:
SELECT count(*) AS rows FROM (
SELECT id, name FROM customers WHERE id = 42 OR 1=1 ORDER BY id
) AS app_query;| rowsint8 |
|---|
| 2000 |
the "id" was 42 OR 1=1. no quote anywhere, nothing for an escaper to escape, 2,000 rows.
the rules depend on the database. mysql's habit is to escape a quote with a backslash, \'. in postgres, with standard_conforming_strings on (the default, and the setting here), a backslash in a plain string is just a backslash. so an escaper written for mysql turns x' OR 1=1 -- into x\' OR 1=1 --, and postgres reads the string as x\ and the rest as code:
SELECT count(*) AS rows FROM (
SELECT id, name FROM customers WHERE email = 'x\' OR 1=1 --' ORDER BY id
) AS app_query;| rowsint8 |
|---|
| 2000 |
escaped, and injected anyway.
it has to be right everywhere, forever. one call site that forgets, one new developer, one quick report script, and it's open. with parameters, the safe version is the only shape the call has.
lists are values too. instead of building IN (1, 7, 42) out of strings, bind one array, however many ids it holds:
PREPARE by_ids(int[]) AS
SELECT string_agg(name, ', ' ORDER BY id) AS names FROM customers WHERE id = ANY($1);
EXECUTE by_ids('{1,7,42}');| namestext |
|---|
| Maya Chen, Ming Li, Ada Lovelace |
identifiers can't be parameters
a parameter is a value. a table name, a column name, a sort direction is part of the statement's structure, and the parser needs it before any value arrives:
PREPARE count_rows(text) AS SELECT count(*) FROM $1;so when a name really has to come from outside (a report that lets you pick a column to sort by, a tool that works on any table), you build the SQL, and quote the name properly while you do. format('%I', name) quotes it as an identifier when it needs quoting, %L quotes a literal, and %s pastes it in raw:
| inputtext | %stext | %Itext | %Ltext |
|---|---|---|---|
| customers | customers | customers | 'customers' |
| Customers | Customers | "Customers" | 'Customers' |
| order items | order items | "order items" | 'order items' |
| select | select | "select" | 'select' |
| x"; DROP TABLE orders; -- | x"; DROP TABLE orders; -- | "x""; DROP TABLE orders; --" | 'x"; DROP TABLE orders; --' |
| O'Neil | O'Neil | "O'Neil" | 'O''Neil' |
format(). %I leaves a plain lowercase name alone and double-quotes everything else, doubling any " inside. %s pastes the text as is, which is string glue with a nicer name.in PL/pgSQL, dynamic SQL looks like this, with the name quoted and the value still bound:
EXECUTE format('SELECT count(*) FROM %I WHERE city = $1', tbl)
INTO n
USING city;quoting makes a name safe to parse. it doesn't make it safe to allow: %I will happily quote pg_authid or salaries. when names come from users, check them against a fixed list (the columns this report may sort by), and only then quote.
one level deepersecond-order injection
injection doesn't have to happen on the way in. a value can be stored perfectly safely, with a parameter, and become a problem later, when some other code glues it into a query. the school database has a student whose name is a classic (xkcd 327):
SELECT id, name FROM students WHERE name LIKE 'Robert%' ORDER BY id;| idint4 | nametext |
|---|---|
| 13 | Robert'); DROP TABLE students;-- |
stored as data, it's harmless: a string with some punctuation in it. the day a nightly script builds "... WHERE name = '" + row.name + "'" from it, it isn't. "it came from our own database" is not the same as "it's safe to glue". the rule doesn't change with the source: values are parameters, always.
keylines
- injection happens when input is parsed as SQL. a quote in a glued value is all it takes.
- a bound parameter arrives after parsing, so it can only ever be one value.
- PREPARE / EXECUTE is binding in SQL. drivers do it with $1, ? or %s, through the extended protocol.
- escaping by hand fails on numbers, on other databases' rules, and on the call site that forgot.
- identifiers can't be parameters: allow-list them, then quote them with format('%I').