Parameterization, ORMs and why escaping does not save you
SQL injection is prevented by parameterized queries, not escaping: the command text and the values go to the database separately. Escaping and keyword blocklists depend on dialect and context and can be bypassed, for example in a numeric parameter. Column names and ORDER BY are not parameterized but matched against an allowlist. Raw ORM methods and second-order data remain a risk.
Pentest · Injections
A developer escapes apostrophes and considers SQL injection closed. What did he miss?
After a vulnerability report a developer added a function that replaces ' with \' and asks to close the defect. The tester switches from a search by string to a search by number ?id=1 OR 1=1, and the injection works again: there are no quotes in a numeric context, so there is nothing to escape. The lesson explains why reliable protection is not cleaning input but separating the command from the data.
Mechanism. In a parameterized (prepared) query the SQL text with placeholders ($1, ?, :name) is sent to the database separately from the values. The database parses and plans the command without the data and then substitutes the values as values. Even if a value contains ' OR 1=1 --, it is only a string to compare, not a fragment of the command. So there is no need to know which characters are dangerous in this dialect, encoding and context: the question "what to escape" disappears.
// before: a string is a command
db.query("SELECT * FROM users WHERE id = " + id);
// after: a command and a value are separate
db.query("SELECT * FROM users WHERE id = $1", [id]);
A numeric parameter: where escaping is powerless
"… WHERE id = " + escapeQuotes(id)
The input 1 OR 1=1 contains no quotes. Escaping changes nothing and the condition becomes always true.
"… WHERE id = $1", [id]
The value 1 OR 1=1 does not become a number: PostgreSQL rejects it as not a number, and the request ends with an error, not a leak.
Why "cleaning input" does not work.
| Approach | Reliable? | Why |
|---|---|---|
| Escaping quotes | no | numbers, encodings |
| Word blacklist | no | case, comments |
| Parameters | yes | data apart |
A word blacklist (SELECT, UNION) is bypassed with case (SeLeCt), comments inside a word or encoding. Escaping depends on the dialect and character set: a mistake in one place leaves a hole. Besides, they work only where someone remembered them, while parameters become the default way.
What cannot be a parameter. A parameter substitutes a value, not a table or column name. So user-chosen sorting (ORDER BY) is not parameterized. The right way is to map the permitted options to a fixed set:
const SORT = { price: "price", name: "name" };
const col = SORT[req.query.sort] ?? "name";
const dir = req.query.dir === "desc" ? "DESC" : "ASC";
db.query("SELECT * FROM products ORDER BY " + col + " " + dir);
Only a string from our own dictionary reaches SQL, not the input. The same goes for column names in filters and dynamic reports.
ORMs and "raw" queries. An ORM parameterizes ordinary calls by default (findMany({ where })). The flaw appears in "raw" methods: in Prisma $queryRawUnsafe with an assembled string is vulnerable, while $queryRaw with a template literal is parameterized. Similar traps exist in Sequelize (query with concatenation), Django (raw, extra) and Hibernate (HQL strings). In code review look for SQL assembled with + or interpolation.
Second order. A value may have entered the database safely (a parameterized INSERT), but later other code takes it from the database and inserts it into SQL as a string, for example in an administrator report. The database does not "clean" what is stored: it is dangerous where it is used as code. Parameterization is needed in every query, whatever the source of the value.
Extra layers. An application account with only the needed rights (no DROP, no file system access, a separate account for reading), hidden database error messages (only a generic error and an identifier for the logs in the response), a WAF as a temporary shield. This reduces the consequences but does not replace the fix: a WAF is bypassed, and account rights do not stop reading data the account can access.
A real case. In August 2009 the US Department of Justice published charges against Albert Gonzalez: according to the indictment, SQL injections were the start of intrusions into the networks of several large companies, among them Heartland Payment Systems and Hannaford, involving about 130 million payment card numbers. The technique was already old and the reliable defence known. That injections still occur about fifteen years later (MOVEit, 2023) shows that the problem is not ignorance of the technique but discipline: one line assembled by concatenation undoes everything else.
Common mistakes.
- Parameterizing values while taking the sort column name from input as is;
- Treating an ORM as a guarantee: a raw method with concatenation stays vulnerable;
- Trusting "already stored" data and assembling SQL from it as a string (second order).
Check yourself
The query ORDER BY $1 with the parameter price does not sort by price. Why and how to do it right?
Answer
A parameter passes a value (the string "price"), not a column name, so the database sorts by a constant. The right way is a dictionary of permitted columns and substituting only the matching string from it.
Does the rule "the database never receives the words SELECT and UNION from a user" protect against SQL injection?
Answer
No. Bypasses are easy (case, comments inside a word, encoding), and changing a condition needs no such keywords: OR 1=1 or a delay does not contain them. Reliable protection does not depend on the words in the input.