Which characters and sequences matter most when detecting SQL injection?
The string delimiter ' (and "), comment sequences --, # and /* */, the statement separator ;, and keywords such as OR, AND, UNION and SELECT, each also in their URL-encoded forms (for example %27 for ').
SQL injection works by making user input break out of its data context into SQL syntax. The characters that make this possible are the ones to watch:
| Sequence | Role in an attack |
|---|---|
' / " (%27 / %22) |
close the string the input was placed in |
--, #, /* … */ |
comment out the rest of the original query (the password check, say) |
; |
end the statement and start a new one (stacked queries) |
OR 1=1, 'a'='a' |
always-true condition to bypass a WHERE check |
UNION SELECT |
append a second query to read other tables |
= and spaces (%3D, %20, +) |
glue the payload together |
Because web input arrives URL-encoded, a detection rule must look for both the literal and the encoded form. And because SQL keywords are case-insensitive, it must ignore case.
The real fix is in the application: parameterised queries make these characters harmless data. The IDS rule is a second line that notices attempts.
Go deeper:
OWASP SQL Injection Prevention Cheat Sheet — the real fix: parameterised queries make these characters harmless.
Mookhey: Detection of SQL Injection and Cross-site Scripting Attacks (Black Hat USA 2004) — regexes for quotes, comments and
UNION, in literal and encoded forms.SQL injection (Wikipedia) — escape-character and stacked-query attacks, with real-world breaches.