All writing
5 min read

String-built SQL: injection in generated backends

Ask an AI assistant for a search box and you often get a query glued together from strings, with the user's text dropped straight into the SQL. I built that in my own lab, used one quote, OR 1=1 and UNION SELECT to read every workspace's contacts and the users table, then fixed it with parameterized queries, demonstrated on Kali Linux.

Asghar Ali · Chief Technology Officer, Kakushin.io LTD

Talk · Asghar Ali

This is the fifth in a series where I build a realistic app, break it, and fix it, all in my own lab with nothing pointed at anyone else's systems. Day one was a file upload, day two was one number in the address bar, day three was keys in a JavaScript bundle, and day four was the Binance hack rebuilt with fake money. Today is one of the oldest bugs on the web, and it still turns up in brand-new code: SQL injection.

The feature

The lab app is Metrika, a demo analytics product where several companies ("workspaces") share one database. I'm signed in as Acme. The Audience page lists Acme's contacts, with a search box on top. I search for "Sara" and get one row, from my own workspace. Nothing strange.

Here is the code behind it. It's the shape you get very often when you ask an assistant to "add a search box":

// vulnerable: the query is one string, and the search text is glued into it
$q = $_GET['q'] ?? '';
$sql = "SELECT name, email, company, country FROM contacts "
     . "WHERE workspace = '$ME' AND name LIKE '%" . $q . "%' ORDER BY name";
$result = $db->query($sql);

The same mistake looks like this in other stacks:

// Node: a template literal is still string-building
const [rows] = await db.query(`SELECT * FROM contacts WHERE name LIKE '%${q}%'`);
# Python: so is an f-string
cur.execute(f"SELECT * FROM contacts WHERE name LIKE '%{q}%'")

In every case the database receives a single piece of text. It has no way to know where the developer's SQL ends and the user's input begins. If the input contains a quote, the user isn't searching any more. They're writing SQL.

Breaking it

All of this runs against my own lab app on my own machine, with fake data.

One quote. I searched for a single '. The page broke and printed the database's own error, quoting the SQL around my input. That tells an attacker two things: the input reaches the query, and the quote is theirs to close.

OR 1=1. Next I searched for:

' OR 1=1 -- -

The quote closes the string, OR 1=1 adds a condition that is true for every row, and -- starts a comment, so the rest of the developer's query is ignored. The page showed 13 contacts instead of 6: Acme's, plus Northwind Traders, Lumen Labs and Orbit Dev. Every workspace in the product.

UNION. An attacker doesn't have to stay in the contacts table. UNION joins the results of a second query onto the first. The page shows four columns, so I asked the users table for four:

x' UNION SELECT email, password_hash, role, workspace FROM users -- -

The contacts table came back as every login in the product: emails, password hashes, roles, and the platform's superadmin. From a search box, with no password and no access I'd ever been given.

Catching it

Your access logs tell the story if you look. I searched the lab's log for an encoded quote (%27) and the word union:

grep -iE "%27|union" access.log

Three requests, in order: a lone quote, then OR 1=1, then UNION SELECT ... FROM users. Real people search for names; they don't type SQL. A burst of database syntax errors in your error log is the same alarm from the other side. Neither replaces the fix, but both tell you someone is probing.

The four fixes

I patched the lab and ran the same three inputs again. The quote gave no error, just "no contacts match". OR 1=1 and the UNION both returned zero contacts, because the database looked for a person literally called that and found nobody.

// fixed: the query is fixed, and the input is only ever data
$sort = in_array($_GET['sort'] ?? '', ['name', 'company', 'country'], true) ? $_GET['sort'] : 'name';
$stmt = $db->prepare("SELECT name, email, company, country FROM contacts
                      WHERE workspace = ? AND name LIKE ? ORDER BY $sort LIMIT 50");
try {
  $stmt->execute([$ME, '%' . $q . '%']);
  $rows = $stmt->fetchAll(PDO::FETCH_NUM);
} catch (PDOException $e) {
  error_log('audience search failed: ' . $e->getMessage());   // details stay on the server
  $error = 'Search is unavailable right now.';
}
  1. Parameterized queries everywhere. Write the query once, with placeholders where the values go, and send the values separately. In Node that's db.execute('... WHERE name LIKE ?', ['%' + q + '%']); in Python it's cur.execute("... WHERE name LIKE %s", ('%' + q + '%',)). ORMs are safe by default, but their raw-query escape hatches (Prisma's $queryRawUnsafe, raw whereRaw strings and the like) bring the problem straight back.
  2. Allowlists for what you can't parameterize. Column names and sort directions can't be placeholders. Pick them from a fixed list (name, company, country) and nothing else.
  3. No database errors on the page. Log the details on the server and show the user a plain message. A raw SQL error is a map for whoever is probing.
  4. Least privilege for the database account. The patched search connects as an account that can only SELECT from the contacts table, with credentials kept out of the code. Even if a bug slipped in somewhere else, asking that account for the users table gets SELECT command denied.

The OWASP SQL Injection Prevention Cheat Sheet covers the same ground in more depth.

A five-minute check for your own code

If an assistant wrote your backend, search the code for queries built with +, ., template literals or f-strings, and for raw-query helpers in your ORM. Each hit should either use placeholders or take its value from a fixed list. Ask your assistant to rewrite any that don't, then test the search boxes and filters with a single quote and make sure nothing breaks.


SQL injection is decades old and fully solved on paper, which is why it hurts when it ships. I build these labs, break them, and fix them in the open every weekday. If you've shipped something AI-built and want it checked properly, that is exactly the work I do. For what a full review covers, see what a security review of an AI-built app covers.

Next — Day 6: 1,200 AI agents hacked Hugging Face: how it happened, step by step.