← All tracks
InjectionSQL Injection10 labsFoundation → Intermediate → Advanced6h practice

SQL Injection: When Input Becomes Grammar

Input is not data until the parser says it is.

“The login form asked for a password. The database answered a different question.”

CWE-89OWASP Top 10 A03:2021OWASP ASVS 5.3.4
The mental model
A query is a sentence with grammar. User input is supposed to be a noun inside that sentence. Injection happens when the input changes the grammar instead of filling the blank.

String concatenation places raw input inside a query. A quote closes the intended string, OR changes the predicate, and a comment removes the rest. The database then executes the attacker's sentence with the application's privileges.

The query looks like a sentence, so we read it like language. The database reads it like grammar. That difference is the bug.

Threat model

What is actually at stake?

Before touching a payload, map the assets, the actors and the boundary that is supposed to protect them. A finding only becomes a vulnerability when you can connect the failed boundary to a real asset.

Assets

  • Customer and payment records
  • Authentication decisions
  • Administrative reports and exports
  • Database metadata and credentials

Actors

  • External attacker with a search or login form
  • Authenticated user with a report filter
  • Malicious insider
  • Automated scanner

Trust boundaries

  • Client string to SQL parser
  • Query text to parameter values
  • Application role to database role
  • Read query to write or administrative function

Abuse cases

  • Use a tautology to bypass login
  • Union-select data from another table
  • Use boolean or time inference when output is hidden
  • Inject through a sort or column name that cannot be parameterized
  • Store a payload for a later second-order query
PrerequisitesSQL SELECT, WHERE and JOIN basicsHow prepared statements separate code from dataReading a query string and request body
Request anatomy

Follow the decision, not the payload

Every family has a moment where trusted data becomes an authorization, parsing or state decision. Learn to point at that moment in the request path.

  1. 01

    Collect

    The application receives a search term, login, filter, sort key or API parameter.

  2. 02

    Concatenate

    The value is placed into SQL text instead of being bound as a parameter.

  3. 03

    Parse

    The database parser treats attacker-controlled text as SQL syntax and may change the query structure.

  4. 04

    Execute

    The modified query runs with the application's database privileges.

  5. 05

    Return

    Rows, errors, timing or side effects reveal the result. Even a blind query can be extracted one bit at a time.

Case study

Heartland Payment Systems, 2008

Heartland Payment Systems, 2008, public reporting
Context

Attackers used SQL injection to enter a payment processor's network and install malware on systems that handled card transactions.

Discovery

The intrusion began with a web-facing SQL injection flaw. The attackers moved laterally and captured payment data as it was processed.

Impact

Public reporting described one of the largest card breaches of its era, with tens of millions of records and major industry consequences.

Root cause

Unsafe query construction exposed the database, and network segmentation and monitoring were insufficient to stop lateral movement.

Fix

Parameterized queries everywhere, least-privilege database roles, egress and segmentation controls, and detection for anomalous query volume and database access.

Read it as a chain: discovery → failed decision → impact → fix. Then ask which link would have broken earliest.

Attacker lens

A repeatable testing sequence

  1. Send a single quote and observe errors, status changes or timing.
  2. Test boolean tautologies and comments in login, search, filters and sort parameters.
  3. Use errors, UNION or time delays to learn the query shape and database.
  4. Keep the goal small: bypass a predicate, read one row, or prove the injection.

Where smart people get fooled

  • A WAF blocks known payloads, not the vulnerability.
  • An ORM can still be used with raw fragments.
  • Escaping quotes is not the same as parameterization.
Detection engineering

What would the logs show?

A control is stronger when someone can see it fail. These signals are starting points for a detection rule, not a complete SIEM use case.

  • Query strings or bodies containing SQL keywords, comments or tautologies
  • A sudden increase in database errors from one client
  • UNION-shaped result counts or unexpected columns
  • Repeated requests with small time delays
  • One application account reading tables it never normally touches
Starter query
index=web sourcetype=app_logs | eval sqli=if(match(uri,"(?i)(union|select|sleep|benchmark|information_schema|or%201=1|'--)"),1,0) | where sqli=1 | stats count values(uri) by clientip, status | where count > 2
The defender's move

Fix the decision, then prove it stays fixed

  • Use parameterized queries or a query builder that binds values.
  • Allowlist identifiers such as sort columns; never concatenate them.
  • Run the database with least privilege and return generic errors.
Vulnerable patterntypescript
const sql = `SELECT * FROM users WHERE email = '${email}'`;
const row = await db.query(sql);
Safer patterntypescript
const row = await db.query(
  "SELECT id, email FROM users WHERE email = $1",
  [email]
);

Bind every value. For identifiers such as sort columns, map the client choice to a fixed allowlist instead of interpolating the raw string.

Regression tests a reviewer would ask for

Login tautology

GivenA login form accepts email and password

WhenThe email contains ' OR 1=1 --

ThenAuthentication fails and the query is unchanged

Search union

GivenA search endpoint accepts q

WhenThe value contains a UNION SELECT

ThenThe value is treated as literal text and no extra columns appear

Sort identifier

GivenA report accepts a sort parameter

WhenThe parameter is an unknown column or contains a subquery

ThenThe server maps only allowlisted columns and rejects the rest

Second order

GivenA username is stored and later used in an admin report

WhenThe username contains SQL syntax

ThenThe report query binds it as data and does not execute it

False positives

What this finding is not

Strong testers kill their own findings before someone else does. These are the shortcuts that turn a real bug into a weak report — or a false alarm into a wasted escalation.

  • A single quote causes a generic 500: it may be a parser error, but confirm with boolean and time-based tests before calling it injectable.
  • A WAF blocks a payload: encoding, alternate syntax and different parameters may still reach the query; never treat the WAF as the fix.
  • The ORM is used: raw fragments, order clauses and dynamic identifiers can still be concatenated.
  • The response is identical for true and false conditions: use time delays or out-of-band interaction to confirm blind injection.
Working vocabulary

Terms you should be able to use precisely

Parameterized query
A query where values are bound separately from SQL text, so input cannot change the syntax.
Tautology
A condition that is always true, such as OR 1=1, used to bypass a predicate.
UNION injection
Appending a second SELECT to return data from another table or database.
Blind SQL injection
Injection where the result is inferred from boolean responses, timing or out-of-band signals.
Second-order injection
A payload stored by one query and executed later by another unsafe query.
Least privilege
Giving the application database account only the permissions it actually needs.
Interview drill

Answer these without reciting a payload

Why do prepared statements stop SQL injection?

The database parses the query structure before values are bound. A value can never become syntax, even if it contains quotes or keywords.

How do you safely handle a user-selected sort column?

Map the client value to a fixed allowlist of column names and directions. Identifiers cannot be bound like values, so never concatenate the raw input.

What should you do when a WAF blocks your test payload?

Treat it as a signal, not a conclusion. Try alternative encodings and injection points, and verify at the database or application layer whether input reaches a query unsafely.

Knowledge check

Can you separate the mechanism from the payload?

Four questions, graded on the server. Answers and explanations are released only after you submit, and signed-in learners keep a best score.

4 questions
01Which fix addresses the root cause of SQL injection?
02A sort parameter cannot be bound. What is the correct approach?
03Which technique confirms blind SQL injection when output is suppressed?
04What makes second-order injection easy to miss?
الخلاصة الموسّعة
لماذا هذا مهم؟

حقن SQL ليس قصة علامة اقتباس واحدة؛ هو أن يتحول نص المستخدم إلى جزء من قواعد اللغة التي يفهمها محرك قاعدة البيانات.

الحل الجذري هو استعلامات مُعدة وقيم مربوطة، وليس تنظيف النص أو جدار حماية فقط. أما أسماء الأعمدة والجداول فتُختار من قائمة بيضاء ثابتة. وأضف طبقة دفاع ثانية: صلاحيات قاعدة بيانات محدودة، مراقبة أخطاء غير طبيعية، واختبار الحقن من الدرجة الثانية حيث يُخزن النص ثم يُنفذ لاحقًا.

Where exactly does user text stop being a value and become syntax?