Parameterized Queries & SQL Injection
See how pasting user input into SQL lets it become code, and how parameterized queries keep data and commands apart.
When data becomes code
SQL injection happens when a program builds a query by gluing user input into the SQL text. Characters in the input, such as a quote or a semicolon, are then read as part of the SQL, so the user can change what the query does.
A parameterized query keeps the two apart. The program sends the query text with placeholders ($1, $2), and sends the values separately. The database never reads a value as SQL.
One quote can ruin a database
Any search box, login form or URL that reaches a query is a way in. Injection can leak other users' data, change or delete rows, or drop whole tables. It is one of the oldest and most common web security problems, and the fix is simple and cheap.
Same input, two ways
// Dangerous: the input becomes part of the SQL text
db.query("SELECT id, name, email FROM users WHERE name = '" + input + "'");
// Safe: the text and the value travel apart
db.query("SELECT id, name, email FROM users WHERE name = $1", [input]);Type ' OR '1'='1 in the glued version and the query becomes ... WHERE name = '' OR '1'='1'. The test '1'='1' is always true, so every user comes back. Type '; DROP TABLE users; -- and the first statement ends early, a second statement drops the table, and -- comments out the leftover quote.
PostgreSQL's simple query protocol runs several statements in one string, as one transaction. In the parameterized version the same input is just a name nobody has, so the query returns no rows and nothing changes. The extended query protocol also takes only one statement per query text, so a second statement cannot be smuggled in.
Try the attacks, then the fix
Run each input with Glue into the text, and then with Send as a parameter. Watch the highlighted characters, which came from the user, and the list of tables.
Tables in the database now: users, notes
Pick an input and a way of building the query, then press Run query. Try the same input both ways.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- SQL injection is user input that becomes part of the SQL text. A quote and a semicolon can start a new statement.
- A parameterized query sends the text and the values apart, so a value is never read as SQL.
- Parameters are values only. For table names, column names and sort order, use an allow-list.
- Do not escape by hand. Also use a database account with only the rights it needs.
Done with this concept?
Mark it complete to track your progress. No login needed.