Injection
Why a concatenated query returns every row, why parameters work where escaping does not, and the identifiers placeholders cannot cover.
Injection is what happens when data becomes code. A value arrives as text, gets pasted into something a machine interprets, and a character inside it changes what that machine was told to do.
It has been at or near the top of the OWASP list since the list existed, not because the fix is hard — the fix is one line — but because the broken version works perfectly until someone types an apostrophe.
The same bug, three inputs
Here is the query everybody writes first, and the parameterised version beside it, against the same three-row table.
An ordinary name. Both correct:
### ordinary input: ana
### concatenated -> ana=100
### parameterised -> ana=100This is why the bug survives review. It works.
A name containing a quote. The concatenated version breaks open:
### input containing a quote: ana' or '1'='1
### concatenated -> ana=100 bo=5000 cy=250
### parameterised -> (no rows)Every row in the table, including another customer's balance. The quote closed the string the query author opened, and everything after it was read as SQL rather than as a name.
And an ordinary surname:
### an ordinary name with an apostrophe: O'Reilly
### concatenated -> SQLException: Syntax error in SQL statement
"select owner, balance from account where owner = 'O'Reilly[*]'"
### parameterised -> (no rows)This is the case worth dwelling on, because it reframes the whole subject. The same defect that lets an attacker read every row also breaks for a customer named O'Reilly. Injection is not a separate security concern bolted onto working code — it is a correctness bug about mixing data with syntax, which happens to also be exploitable.
Why parameters work, and escaping does not
The instinct after seeing the above is to escape the input: double the quotes, strip the apostrophes, reject odd characters. It is the wrong shape of fix, and the reason is structural.
Escaping means: build one string containing both instruction and data, then try to make the data harmless. You are still handing the database a single sentence and hoping it parses the way you intended. Every escaping bug in history is a case where some encoding, some character set, some nested context made the escaping insufficient.
A parameterised query does something different in kind. The SQL goes to the database with placeholders, is parsed into a plan, and only then are the values supplied — as values, in a separate channel, to a statement whose structure is already decided. There is no parsing step left for the input to influence. That is why the malicious string above returned (no rows): the database looked, in perfect good faith, for a customer literally named ana' or '1'='1.
It is also why parameterisation fixes O'Reilly for free. You never asked the question that apostrophes make ambiguous.
// the defect
"select owner, balance from account where owner = '" + owner + "'"
// the fix
PreparedStatement ps = c.prepareStatement(
"select owner, balance from account where owner = ?");
ps.setString(1, owner);The part parameters cannot reach
Placeholders stand in for values. They cannot stand in for a table name, a column name, or a sort direction — those are structure, and structure has to be decided before parsing.
So this is still a hole:
"select * from account order by " + sortField + " " + direction // not fixable with ?The answer is an allow-list, not sanitisation:
private static final Set<String> SORTABLE = new HashSet<>(asList("owner", "balance", "created_at"));
if (!SORTABLE.contains(sortField)) throw new BadRequestException("unknown sort field");Map the user's input onto a value you wrote, and never build identifiers from what arrived. The pagination lesson made the same point for a different reason — this is the security half of it.
Where else the same shape appears
Once you see injection as data reaching a parser, the family becomes obvious, and several of these are the ones people forget:
- JPQL and HQL. An ORM is not immunity.
"from Account where owner = '" + owner + "'"is injectable;setParameteris the fix. Everything in the JPA course about@Queryassumes named parameters for this reason. - Command injection.
Runtime.exec("ping " + host). Use the array form, which does not go through a shell, and allow-list the input. - LDAP, XPath, NoSQL filters. Same shape, different parser, and the driver's parameter mechanism is again the fix.
- Log injection. A newline in user input writes a fake log line. Everything the operator later reads is now partly attacker-written, which matters when somebody greps that file during an incident.
- XML external entities (XXE). An uploaded XML document referencing a local file, parsed by a configured-by-default parser, reads that file. Disable external entities on every XML parser you construct.
- Deserialisation. Handing untrusted bytes to a mechanism that constructs arbitrary objects is the most severe member of the family. Do not deserialise untrusted input into arbitrary types; use a schema-validated format, which is what the JSON lesson's advice about validating at the boundary is really protecting.
Finding it before someone else does
- Grep for string concatenation next to
select,insert,update,deleteandwhere. Crude, fast, and it finds most of them. - Turn the warning on. Static analysis — SpotBugs with the security plugin, or your platform's scanner — detects tainted values reaching a query. Wire it into CI, where it runs on code nobody is reviewing carefully at five o'clock.
- Test with the apostrophe. A single
'in every free-text field, as a habit, during ordinary manual testing. It is not a penetration test; it is the fastest way to discover that a field is concatenated, and it doubles as a real-data test for every customer named O'Brien.
Under the hood: what "parsed before values arrive" means on the wire, and a second parser — the shell
"The statement is parsed before the values arrive" is not a metaphor; it describes real messages on the connection between your JVM and the database. A PreparedStatement does not send one string. It sends (at minimum) a Parse step — the SQL text, with ? placeholders, which the database compiles into an execution plan before it has seen a single value — and then, separately, a Bind step that supplies the actual parameter values against that already-compiled plan, followed by Execute. (PostgreSQL's extended query protocol names these steps exactly this; other databases' wire protocols differ in detail but keep the same two-phase shape, which is what JDBC's PreparedStatement API is built on top of.) By the time your malicious-looking string reaches the database at all, the structure of the query — which columns, which table, where owner = ? — has already been fixed and cannot be un-fixed by anything arriving in the Bind message. A value is data the plan reads, never text the plan is built from. That is the literal, mechanical reason a quote character inside a bound parameter cannot close a string literal the way it can in a concatenated string: there is no string literal in the compiled plan for it to close, only a slot waiting for a value.
Injection is not unique to SQL — it is any case of "data reaching a parser," and a shell is a parser too. Runtime.exec("ping " + host) and new ProcessBuilder("sh", "-c", "ping " + host) are exploitable the same way a concatenated SQL string is, but the mechanism is different: a shell interprets metacharacters in the command text it is given — ; to chain a second command, | to pipe, ` or $() to substitute the output of another command — so a host value of example.com; rm -rf / is not "a weird hostname," it is two commands to the shell, exactly the way ana' or '1'='1 was not "a weird name" to a concatenated SQL string. The fix has the same shape as parameterisation, for the same reason: new ProcessBuilder("ping", host) — the array/varargs form, one argument per array element — never invokes a shell at all. Each array element becomes exactly one argument to the target program, with no parsing step that metacharacters could influence, the same way a bound SQL parameter never re-enters the parser that built the query's structure.
Try it yourself
Trace a bind parameter that never re-enters parsing
This stands in for the two-phase shape above: a "compiled" lookup — which field to compare, decided once — and a value supplied afterward that is only ever compared, never re-parsed as part of that decision.
List<Map<String, String>> rows = List.of(
Map.of("owner", "ana", "balance", "100"),
Map.of("owner", "bo", "balance", "5000"));
// "compiled" once, like Parse: which field the comparison reads never changes after this line
String boundColumn = "owner";
for (String candidate : List.of("ana", "ana' or '1'='1")) {
// "Bind": candidate is a value compared with equals(), never text re-joined into a query
boolean match = rows.stream().anyMatch(r -> r.get(boundColumn).equals(candidate));
System.out.println("owner: " + candidate + " -> match: " + match);
}The second candidate contains the same ' or '1'='1 shape that broke the concatenated query earlier in this lesson. Why does it fail to match here, when the same characters returned every row against the concatenated version?
The candidate is data to `.equals()`, never syntax to a parser
rows.get(boundColumn).equals(candidate) treats candidate purely as a literal string to compare, character for character, against a stored value — there is no step anywhere in this loop that re-interprets those characters as instructions, the way a concatenated SQL string hands the same characters to a parser that does interpret quotes and or as syntax. A bind parameter in a real PreparedStatement is compared (by the database) against the compiled plan's slot in exactly this spirit: as a value the plan reads, not text the plan is built from. The ana' or '1'='1 string is, to this loop and to a real parameterised query alike, just a name nobody has — one long, unusual literal, and nothing more.
Misconceptions
- "A stored procedure is immune to injection because the database controls it." Only if the procedure's own SQL is built from fixed text and parameters. A procedure that builds a string internally and runs it with dynamic SQL (
EXECUTE IMMEDIATE, or the equivalent in your database) is exactly as injectable as application code doing the same thing — the boundary that matters is whether the final SQL text is assembled by concatenation anywhere in the chain, not which layer happens to hold the code. - "Strict input validation (letters and numbers only) is basically as safe as parameterisation." Validation constrains shape, and it helps, but it is not a substitute: it is easy to get subtly wrong (a name like O'Reilly, a legitimate
-in a phone number, a Unicode character that normalises differently later), and it is orthogonal to the actual mechanism — even input that passes strict validation is still exploitable if it is then concatenated into a query, because validation says nothing about how the value is later used. Parameterisation removes the hazard structurally, at the point the value is used, regardless of what the value contains.
Sources
- OWASP Top 10 — A03:2021 Injection.
- OWASP SQL Injection Prevention Cheat Sheet.
- OWASP Command Injection page (Community Pages / Cheat Sheet Series).
- PostgreSQL documentation — the extended query protocol (Parse/Bind/Execute).