Topic 1 of 6 · 4 min read
Injection in AI-written queries and commands
Goal: Find an injection flaw in AI-generated code and rewrite the vulnerable line with a parameterized or properly escaped form.
Injection happens when user input is glued into a query or command as text, so the input can change what the code does. AI assistants still write this pattern whenever it is the shortest path to working code.
Check yourself · 1 of 3
An AI assistant builds a query with an f-string that includes a request parameter. What is the correct fix?
Why it matters
Injection stays on the CWE Top 25 list of dangerous weaknesses year after year. Models learned from decades of tutorials, and many tutorials build SQL with string formatting. A prompt like "add a search endpoint" often returns exactly that, and the demo works. The bug only shows when someone types a quote character.
How to find it
Look at every line where a value from outside (request body, query string, header, file name, model output) reaches an interpreter. Four interpreters cover most cases:
- SQL. Any query built with f-strings, template literals or
+. - Shell.
os.system,child_process.exec, backticks, orshell=True. - Templates and HTML. Raw output into a page, or user text passed to a template engine as the template itself.
- Paths. A file name joined onto a folder, where
../walks out of it.
The fix is the same idea each time: keep code and data separate. Use parameterized queries, pass shell arguments as a list with no shell, escape on output, and resolve paths then check they stay inside the base folder.
Before and after
# Before: the name is part of the SQL text
cur.execute(f"SELECT id, email FROM users WHERE name = '{name}'")
# name = "x' OR '1'='1" returns every user
# After: the driver sends the value separately
cur.execute("SELECT id, email FROM users WHERE name = %s", (name,))
The shell version has the same shape. Replace exec("convert " + file + " out.png") with execFile("convert", [file, "out.png"]), so the file name can never become a second command.
What goes wrong
- Escaping by hand. The agent adds a
replace("'", "''")call. It misses encodings and other dialects. Parameters are the fix, not cleanup. - Parameterizing the value but not the identifier. Column names and
ORDER BYcannot be parameters. Allow-list them against a fixed set. - ORM raw escape hatches.
raw()and$queryRawUnsafeaccept strings and bypass the ORM's protection. - Trusting the model's own claim. "I sanitized the input" in an agent summary needs a look at the actual line.
When reviewing, search the diff for string building near execute, query, exec, system and open. See the OWASP SQL Injection Prevention Cheat Sheet for the full set of defenses.
Examples
The search endpoint that works in the demo
app.get("/search", async (req, res) => {
const rows = await db.query(
`SELECT * FROM products WHERE title LIKE '%${req.query.q}%'`
);
res.json(rows);
});
The agent returned working search. A request with q=' UNION SELECT email, password_hash FROM users -- returns user data. The fix is db.query("SELECT * FROM products WHERE title LIKE ?", ["%" + q + "%"]).
The path that walks out of the upload folder
path = os.path.join("uploads", request.args["name"])
return send_file(path)
A request for name=../../etc/passwd leaves the folder. Resolve the full path and check that it still starts with the uploads directory, or serve files by an id you generated.
Key points
- Injection means user input becomes part of the code that runs, so keep code and data separate.
- Parameterized queries and argument lists replace string building for SQL and shell commands.
- Identifiers such as column names cannot be parameters; check them against an allow-list.
- Manual escaping and blacklists are weaker than parameters and are a sign of a flawed fix.
- Search a diff for f-strings, template literals and concatenation next to query, exec and system calls.
Common mistakes
- Approving a query because it "uses the ORM" without checking for raw or unsafe query methods.
- Accepting hand-written escaping or a character blacklist as the fix instead of parameters.
- Parameterizing the WHERE value but leaving a user-chosen sort column concatenated into the query.
- Testing only with friendly input, so a quote or a ../ never appears in the tests.
Check yourself · 2 of 3
Which call is safest for running an external tool on a user-supplied file name in Node.js?
Check yourself · 3 of 3
A search endpoint lets the client pass a sort column name. Parameters cannot hold identifiers. What should the code do?
Practice items, not counted towards your mastery.
Start here
- CWE Top 25 Most Dangerous Software Weaknesses (MITRE) (opens in a new tab)DocsFree
The ranked list of weakness classes, including injection and broken access control, that generated code should be checked against.
- Do Users Write More Insecure Code with AI Assistants? (opens in a new tab)PaperFree
A user study showing assistant users wrote less secure code while feeling more sure of it.
- OWASP Top Ten (opens in a new tab)StandardFree
The standard awareness list of web application risks, from access control to misconfiguration.
More for this topic
- SQL Injection Prevention Cheat Sheet (OWASP) (opens in a new tab)ArticleFree
The ranked defenses: prepared statements first, then allow-lists and escaping as last resort.