WHERE uses ? placeholders. Why is ORDER BY still SQL-injectable?
Question
An orders API binds WHERE tenant_id = ? properly, then interpolates ORDER BY {sort} {direction} because SQLite does not bind column names or ASC/DESC. A tester passes sort = "CASE WHEN (SELECT substr(pin,1,1) FROM admin_secrets)='9' THEN cents ELSE -cents END" and extracts an admin PIN from the row order.
- Why do
?placeholders fail for dynamic columns and sort direction? - Fix
list_orders(con, tenant_id, sort, direction)using strict allowlist dictionaries for bothsortanddirection. - Why is stripping spaces or quotes from
sortstill risky?
def list_orders(con, tenant_id, sort="created_at", direction="asc"): sql = (f"SELECT id, cents FROM orders WHERE tenant_id = ? " f"ORDER BY {sort} {direction}") return con.execute(sql, (tenant_id,)).fetchall()
Show hints (3)
- "VALUES VERSUS IDENTIFIERS"
Placeholders (
?) only represent SQL data values. A query planner compiles table names, column identifiers, and keywords likeASC/DESCbefore binding parameters. - "MAP FIXED TOKENS"
Map user keys like
"date"and"total"throughALLOWED_SORTandALLOWED_DIRdictionaries so only server-authored SQL tokens ever reach the query string. - "BLIND SORT ORACLE"
Even without spaces or quotes, SQLite accepts
/**/comments,char(), and unexposed column names likepassword_hashinsideORDER BY.
Show checked explanation
SQL placeholders (?) bind only data values, never column names, table names, or ASC/DESC keywords. Interpolating sort lets an attacker inject a CASE WHEN expression into ORDER BY to exfiltrate other tables via row order. Map user inputs through strict allowlist dictionaries (ALLOWED_SORT, ALLOWED_DIR) and reject unknown keys before running SQL.
import sqlite3 ALLOWED_SORT = {"date": "created_at", "total": "cents"} ALLOWED_DIR = {"asc": "ASC", "desc": "DESC"} def list_orders(con, tenant_id, sort="date", direction="asc"): col = ALLOWED_SORT.get(sort) order = ALLOWED_DIR.get(direction.lower()) if col is None or order is None: raise ValueError("invalid sort option") sql = (f"SELECT id, cents FROM orders WHERE tenant_id = ? " f"ORDER BY {col} {order}, id ASC") return con.execute(sql, (tenant_id,)).fetchall() con = sqlite3.connect(":memory:") con.execute("CREATE TABLE orders(id, tenant_id, created_at, cents)") con.executemany("INSERT INTO orders VALUES (?, ?, ?, ?)", [(1, 1, "2026-11-02", 100), (2, 1, "2026-11-01", 500)]) print("date:", list_orders(con, 1, "date", "asc")) print("total:", list_orders(con, 1, "total", "asc"))
date: [(2, 500), (1, 100)] total: [(1, 100), (2, 500)]
Author-checked on SQLite 3.49.1 and CPython 3.12.10 against synthetic in-memory orders and admin_secrets tables, reproducing full 4-digit boolean-blind PIN extraction and verifying the allowlist fix; official OWASP, SQLite, and Python sqlite3 links checked. Checked by an editor other than the author.
Walkthrough
Parameterized queries keep WHERE tenant_id = ? safe because SQLite parses the SQL structure first and binds tenant_id as a literal value afterward. That same rule means ? cannot select a column or keyword. Writing ORDER BY ? in SQLite sorts every row by the same constant text 'cents', turning sorting into a silent no-op, while ORDER BY cents ? is a syntax error.
Interpolating sort straight into ORDER BY hands the attacker a full SQL expression slot. On our two orders (1, 100) and (2, 500) with admin_secrets.pin = '9421', injecting CASE WHEN (SELECT substr(pin,1,1) FROM admin_secrets)='9' THEN cents ELSE -cents END leaks the PIN one character at a time:
sort input | starter result | fixed list_orders |
|---|---|---|
"date" (created_at) | [(2, 500), (1, 100)] | [(2, 500), (1, 100)] |
"total" (cents) | [(1, 100), (2, 500)] | [(1, 100), (2, 500)] |
CASE WHEN ...='9' ... (true) | [(1, 100), (2, 500)] (leaks '9') | Raises ValueError |
CASE WHEN ...='0' ... (false) | [(2, 500), (1, 100)] (false branch) | Raises ValueError |
Map public keys to server-owned SQL tokens. Notice the caller passes API labels ("date", "total", "asc", "desc"), never raw schema names. ALLOWED_SORT and ALLOWED_DIR translate those keys into fixed strings written in your source code. Unknown keys fail closed with ValueError (HTTP 400 or 422), and , id ASC keeps pagination ties deterministic.
Why sanitizing sort with regexes fails. Blocking spaces is bypassed with CASE/**/WHEN.... Blocking quotes is bypassed with char(57). Even allowing only [a-z_]+ lets a caller sort by hidden sensitive columns on the same table (such as internal_score or email) or trigger unindexed full-table sorts.
Common mistakes
- Replacing
ORDER BY {sort}withORDER BY ?. In SQLite,ORDER BY ?binds a constant string, so every row gets the same sort key and sorting silently breaks. - Stripping spaces, semicolons, or quotes from
sort. Attackers use/**/comments, numeric comparisons, orchar()insideCASE WHENwith zero spaces or quotes. - Allowing any
[a-z_]+string as a column name. Callers can still probe hidden columns on the table or sort on unindexed text blobs to cause DoS. - Allowlisting
sortwhile leavingdirectioninterpolated. Attackers can still inject expressions right after a valid column name viadirection.
Follow-up questions
- "How do you safely handle dynamic multi-column sorting like
sort=date:desc,total:asc?" Split the input into a bounded list, such as at most 3 sort keys, and validate every(key, dir)pair againstALLOWED_SORTandALLOWED_DIR. Reject unknown or duplicate keys, then join only the mapped server strings with", ". - "If you double-quote a user column name with
"..."orpsycopg.sql.Identifier, does that replace an allowlist?" Quoting stops syntax injection, yet it is still weaker than an allowlist. A caller could name hidden internal columns, unindexed columns that slow queries, or expose schema errors. Keep an explicit allowlist of API-exposed columns. - "How does this relate to parameterized
WHEREclauses andIN (...)lists?" Values inWHEREandINlists always use placeholders (?, one per element inIN (?, ?, ?)). Only structural SQL pieces that cannot be parameterized (identifiers,ASC/DESC, operators) use strict allowlist maps.
What a strong answer covers
Explains why ? binds values rather than identifiers and demonstrates boolean-blind CASE WHEN extraction via ORDER BY. Maps both column and direction through strict allowlists, and explains why regex filters and ORDER BY ? fail.
Open in interactive practice deck →