SQL injection: how it happens, how testers confirm it, and the fix that holds

How concatenated queries let input change SQL, the error, boolean, time, and out-of-band behaviors testers look for in an authorized test, what scanners like sqlmap report, and parameterization plus least privilege as the fix.

Lesson 5 of 69 · 16 min read · practice only with authorization

Diagram

From a field to a query the database parses

Follow the path. One example at a time.

Step 1 of 4

Input

A search box sends a value.

Illustration: Input
GET /products?category=Gifts
What changes the outcome
Input

Becomes part of the statement

Role

Often the schema owner

Error

Database message returned to the user

The example on the open step is one illustration, or the fix you can paste into an application you own.

What this page is made of

3 pieces. Each one says what fails, who is affected, what you would notice, and what you change.

  1. Where to look in review

    What fails
    Any query built with +, format strings, f-strings, or template literals around request data.
    Who is affected
    Everyone whose rows that database login can read or change.
    What you would notice
    grep hits for execute(f" or "WHERE id = " + in the codebase.
    What you change
    Replace with placeholders and add a lint rule that rejects string-built SQL.
  2. What a test observes

    What fails
    In an authorized test, a stray quote causing a database error, true and false conditions returning different pages, or a deliberate delay are the classic signals.
    Who is affected
    The application owner, who needs proof without data being dumped.
    What you would notice
    A 500 response naming the database engine after a quote is added.
    What you change
    Report the parameter and the behavior. Do not extract tables to prove the point.
  3. Damage control

    What fails
    Even with a bug, the database role limits what leaks.
    Who is affected
    Tenants and users stored in tables the feature never needed.
    What you would notice
    An application connecting as root, sa, or the schema owner.
    What you change
    Give each service a role with only the grants it needs.

The behaviors testers classify

Error-based injection shows database errors in the response. Boolean-based injection changes the page depending on whether an injected condition is true. Time-based injection makes the database wait, which shows up as a slower response. Out-of-band injection makes the database contact another system. Second-order injection stores a value that a later query concatenates, which the second-order SQL injection page covers.

Scanners such as sqlmap automate those checks. In an engagement, run them only where the scope allows automated injection testing, against a test database, with rate limits, and stop at confirmation. Their output names the parameter, the technique, and the database engine, which is what the report needs.

[INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
[INFO] GET parameter 'category' appears to be 'AND boolean-based blind' injectable
[INFO] the back-end DBMS is PostgreSQL
parameter: category (GET)  type: boolean-based blind
-> confirmed; stop here and write the finding

A code-review walkthrough

Search the codebase for query execution calls, then read each call site and trace its arguments back to the request. ORMs are not automatically safe: raw query helpers, string interpolation in filters, and dynamic ORDER BY columns are common holes. Column and table names cannot be parameters, so map them through an allow-list.

$ rg -n "execute\(f\"|\.raw\(|query\(\`.*\$\{" src/
src/reports/export.py:88:    cur.execute(f"SELECT * FROM orders ORDER BY {sort}")
# fix: sort = {"date": "created_at", "total": "total"}.get(sort, "created_at")

What defenders see

Database error rates per endpoint, WAF alerts on SQL keywords, and slow-query logs with unusual sleep calls all point at testing or attacks. A WAF buys time; the fix is in the query.

Check yourself

Recognition and the fix. Nothing here is a procedure.

1 / 3

A report sorts by a column name taken from the URL. Parameters cannot bind identifiers. What is the fix?

Go deeper

Specific techniques, exercises, and glossary cards for this topic.

  1. 01Second-order SQL injectionText that was stored safely can still change a later query if that job concatenates the stored value into SQL. Includes the diagram and a defensive fix.
  2. 02Query builders that still concatenateAn ORM or a query builder is safe only when the SQL text stays under your control. Includes the diagram and a defensive fix.
  3. 03Injection through API fields: JSON bodies reaching SQL, NoSQL, and shellsWhy JSON APIs are still injection targets: operator injection in MongoDB-style queries, typed fields that are never type-checked, and filter parameters passed to query builders. Includes the diagram and a defensive fix.

Exercises

  1. 01Evidence deskRead a query review and a server-side fetch that were already collected. Name the failure and the fix.
  2. 02Parameterized vs concatenated queriesBuild the same product search three ways and watch the token view: concatenation lets input change the query, bound parameters and allowlists keep it a value.
  3. 03Terminal mission: A search box that returned the users tableThe shop’s search API logged a run of quotes, ORDER BY probes, and UNION SELECTs. Identify the parameter, the table that was dumped, and the size of the response that leaked it.

Glossary

  1. 01SQL injectionUntrusted input changes a database query, exposing or altering records the caller should not reach.
  2. 02Injection through API fieldsA field the client sends is glued into a query, a filter, or a command.