Skip to content

Lesson 6 of 14 · 22m

Parameterized Queries, Not Escaping

Injection is a code/data boundary bug — bind parameters move the boundary into the wire protocol, and whitelists cover what parameters can't.

SQL injection is not an exotic attack class; it was the vector behind the 2015 TalkTalk breach — about 157,000 customer records, a £400,000 ICO fine — and it still tops the OWASP lists because the underlying mistake is one line long: building a SQL string by concatenating user input into it.

Here is what actually happens. Your code produces one string:

sql = "SELECT * FROM users WHERE name = '" + name + "'"

and the database receives only that string. The parser cannot see which bytes came from the programmer and which came from the request. With name = ' OR '1'='1, the tautology is not text inside a string literal — it is grammar. The quotes, the OR, the comparison all parse. ' UNION SELECT password_hash FROM credentials -- parses too, and now your search endpoint returns the credential table. sqlmap automates this: point it at a concatenated endpoint and it fingerprints the database, then exfiltrates schema and data with time-based blind queries that produce no error output at all.

The wrong fix is the one everyone reaches for first: escaping, or worse, stripping keywords. Escaping fails because the problem is not characters, it's the boundary between code and data — and because the escaping itself is attackable. The classic demonstration is the GBK multibyte attack: on a connection mis-configured with a multibyte charset, an input byte like 0xbf27 ends with the byte for '. Escape the quote by prefixing \ and the two bytes together now decode as a single valid GBK character — the backslash is eaten — followed by a real, unescaped quote. addslashes just manufactured your exploit. Keyword-stripping fails faster: OR inside a legitimate string, nested OORR that reassembles after one strip pass, comments-as-whitespace SEL/**/ECT. You are playing whack-a-mole against a grammar you don't control.

Parameterized queries kill the entire class by moving the boundary into the wire protocol. The driver sends the statement template and the values separately — Postgres's extended protocol literally parses the string SELECT * FROM users WHERE name = $1, then binds the value bytes to $1 at execute time. The value is never syntax; it's data attached to an already-parsed tree. There is nothing for ' OR '1'='1 to become — it's just a weird name that matches no rows.

cur.execute("SELECT * FROM users WHERE name = %s", (name,))   # psycopg: %s placeholder, NEVER Python % formatting
db.query("SELECT * FROM users WHERE name = $1", [name])        # node-postgres

Every driver has the same shape: ? on MySQL and most libraries, $1/$2 on Postgres-native drivers. In psql you can even demo it with \bind.

Parameterization covers values only — never identifiers. Table names, column names, ASC/DESC, and LIMIT in some drivers can't be bind parameters, because the parser needs the query's structure before it sees data. That makes ORDER BY ${col}-style sorting endpoints a live hole even in codebases that parameterize everything else. The correct pattern is a whitelist: map the client's token to a hard-coded column ({'name': 'name', 'created': 'created_at'}[input], 400 on miss), and never interpolate the raw input. In PL/pgSQL and server-side dynamic SQL, format('%I', colname) quotes identifiers safely — %I for identifiers, %L for literals, and %s never for values.

ORMs don't exempt you. The injection isn't in SQL, it's in string concatenation, and every ORM ships escape hatches — .raw(), .execute(), where("name = '" + x + "'"), extra() — that reintroduce it. Audit by grepping for concatenated queries and raw-SQL calls, not by trusting the framework badge. Watch for second-order injection too: a value stored "safely" through a parameterized insert, then concatenated into a query on the way back out. The payload doesn't care that it took the scenic route into your database.

One more reason to parameterize everything, even with zero attackers: correctness. A user named O'Brien breaks naive quoting on a Tuesday. Parameterized writes store O'Brien fine because apostrophes are data.

The rule is one line: the query's shape is a constant in source code; user input travels as values. There is no escaping layer that is as correct as not needing it.

Pitfalls

  • LIMIT/OFFSET are parameterizable in Postgres (LIMIT $1); column names and sort direction are not — whitelist, don't interpolate.
  • Prepared statements are not magic either: PREPARE q AS 'SELECT ... ' || user_input concatenates before parsing and injects normally. The safety is in the boundary, not the API name.
  • A WAF that "blocks SQL keywords" is a rate limit, not a fix — it fails on the GBK-style byte tricks above and false-positives on legitimate prose. Parameterize; the WAF is optional decoration.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.