SQL Injection (SQLi): How Untrusted Input Becomes a Database Query
Attack mechanics, the main SQLi variants, how testers confirm exploitability, and the controls that actually remove the bug class.
What Is SQL Injection (SQLi)
The root cause is always the same: the database cannot tell the difference between the query the developer wrote and the data the user supplied, because both arrive as one string. Anything that keeps code and data in separate channels, such as parameterized queries, removes the bug. Anything that tries to clean the string first, such as blocklists or escaping functions, reduces it at best.
How SQL Injection Works
Consider a login lookup written with string concatenation:
query = "SELECT id FROM users WHERE email = '" + email + "' AND pwd_hash = '" + hash + "'"If the attacker submits [email protected]'-- as the email, the resulting statement becomes:
SELECT id FROM users WHERE email = '[email protected]'--' AND pwd_hash = '...'The -- sequence starts a comment in most SQL dialects, so the password check is discarded and the query returns the admin row. The same mechanism works in any clause: WHERE, ORDER BY, LIMIT, INSERT values, table or column names, and stored procedure arguments.
Injection is not limited to form fields. Any value that reaches a query is a candidate: URL path segments, query strings, JSON and XML bodies, HTTP headers such as User-Agent or X-Forwarded-For when they are logged to a database, cookies, and values that were stored earlier and later reused in a query (second-order injection).
Types of SQL Injection
In-band (classic) SQLi
The attacker sends the payload and reads the result in the same HTTP response. Error-based injection forces the database to return verbose error messages that leak data or schema details. UNION-based injection appends a UNION SELECT so that attacker-chosen columns are returned alongside the legitimate result set, which requires matching the original column count and compatible data types.
Blind (inferential) SQLi
No data or errors are reflected, so the attacker infers results one bit at a time. Boolean-based blind injection compares responses for a true condition (AND 1=1) and a false one (AND 1=2). Time-based blind injection uses database delay functions, for example SLEEP() in MySQL, pg_sleep() in PostgreSQL or WAITFOR DELAY in SQL Server, and measures the response time.
Out-of-band SQLi
The database is made to send data over a separate channel, typically a DNS lookup or HTTP request to an attacker-controlled host. It depends on database features and outbound network access, so it is less common, but it works when responses are neither reflected nor timing-stable.
Second-order SQLi
The payload is stored safely on first use (for example in a profile field) and executed later when another code path reads it back and concatenates it into a new query. Scanners that only inspect the immediate response routinely miss this variant.
What an Attacker Can Do With SQLi
- Data exfiltration: dump tables the application account can read, including credentials, tokens and personal data.
- Authentication bypass: alter the login predicate as shown above.
- Data tampering: modify prices, roles or balances when the injectable statement or stacked queries allow writes.
- Escalation to the host: on some platforms and configurations, database features can read files or execute operating system commands, for example
xp_cmdshellin SQL Server when it is enabled, turning SQLi into remote code execution.
Impact is bounded by the privileges of the database account the application uses. An application that connects as a database owner turns every injectable parameter into full database compromise.
SQL injection is not a legacy problem. In May 2023 the Cl0p group mass-exploited CVE-2023-34362, a SQL injection in Progress MOVEit Transfer, to steal data from hundreds of organizations; CISA and the FBI documented the campaign in joint advisory AA23-158A.
How Penetration Testers Confirm SQLi
A scanner alert such as "possible SQL injection" is a hypothesis. Confirmation needs evidence that the query structure changed under attacker control:
- Probe: inject syntax-breaking characters (
',",)) and observe errors, status code changes or response length differences. - Differential test: send logically true and false conditions and confirm consistent, repeatable differences. A single difference can be caching or noise.
- Fingerprint the database: use dialect-specific functions or delay primitives to identify the engine, which determines viable payloads.
- Demonstrate controlled impact: extract a harmless value such as the database version or current user, rather than bulk data, to prove exploitability without damaging production.
- Record reproducible steps: the exact request, parameter, payload and response that a developer can replay after the fix.
Testing must also cover authenticated areas, API endpoints and second-order paths. A large share of injectable queries sit behind login, in search and reporting features, and in API parameters that never appear in an HTML form. See authenticated testing and API penetration testing.
Prevention: Controls That Remove the Bug Class
| Control | What it does | Limitation |
|---|---|---|
| Parameterized queries / prepared statements | Sends the query structure and the values separately, so input can never change the statement | Cannot parameterize identifiers such as table or column names; those need allowlisting |
| Safe ORM usage | Generates parameterized SQL by default | Raw query and string-interpolation APIs inside ORMs reintroduce the bug |
| Stored procedures | Safe when they use parameters internally | Dynamic SQL built inside the procedure is still injectable |
| Allowlist input validation | Restricts values such as sort direction or column name to known-good options | A complement, not a substitute for parameterization |
| Least-privilege database accounts | Limits what a successful injection can reach | Reduces impact, does not prevent injection |
| WAF rules | Blocks common payload signatures | Bypassable with encoding and syntax variations; treat as temporary mitigation |
The OWASP SQL Injection Prevention Cheat Sheet lists prepared statements as the primary defense, with stored procedures and allowlist validation as secondary options, and recommends against relying on escaping user input.
Standards Mapping
| Framework | Reference |
|---|---|
| CWE | CWE-89: Improper Neutralization of Special Elements used in an SQL Command |
| OWASP Top 10 (2025) | A05:2025 Injection |
| MITRE ATT&CK | T1190 Exploit Public-Facing Application (initial access via injectable internet-facing apps) |
| PCI DSS v4.0.1 | Requirement 6.2.4 lists injection attacks, including SQL injection, among the attack types software engineering practices must prevent |
How FireCompass Tests for SQL Injection
FireCompass AI agents test injection points across web applications and APIs, including authenticated flows, and report a finding only after confirming exploitability with a controlled payload. Each finding includes the request, the payload and the evidence needed to reproduce it, so engineering can verify the fix with a retest rather than re-running a full engagement. See the web application penetration testing page for scope details.
Sources and Standards
- MITRE CWE-89: Improper Neutralization of Special Elements used in an SQL Command
- OWASP Top 10:2025, A05 Injection
- OWASP SQL Injection Prevention Cheat Sheet
- CISA and FBI Advisory AA23-158A: CL0P exploitation of MOVEit (CVE-2023-34362)
- MITRE ATT&CK T1190: Exploit Public-Facing Application
Frequently Asked Questions
Is SQL injection still common?
Yes. Injection remains a category in the OWASP Top 10:2025 (A05), and SQL injection flaws continue to be assigned CVEs and exploited in the wild, as the 2023 MOVEit Transfer campaign (CVE-2023-34362) showed.
Does a WAF stop SQL injection?
A WAF blocks many known payload patterns but can be bypassed with encoding, comments, case changes and alternate syntax. It is a compensating control while the code is fixed with parameterized queries.
What is the difference between blind and in-band SQL injection?
In-band SQLi returns data or errors directly in the response. Blind SQLi returns nothing visible, so the attacker infers data from true or false response differences or from time delays.
Do ORMs prevent SQL injection?
ORMs generate parameterized queries by default, but most expose raw-query or string-interpolation methods. Injection reappears whenever developers pass untrusted input into those methods.
Which CWE covers SQL injection?
CWE-89, Improper Neutralization of Special Elements used in an SQL Command. It is a child of the broader injection weakness CWE-74.
How do you prove SQL injection without damaging production data?
Use read-only, low-impact proofs such as extracting the database version or current user, boolean differentials or time delays, and avoid stacked write queries or bulk extraction.
Further Reading
- FireCompass web application penetration testing
- How FireCompass AI Agent Discovered a Critical SQL Injection in an Authentication and Password-Reset Flow
- Detecting NoSQL Injection
Related Terms
Find Out Which of Your Parameters Are Injectable
Run a free AI pentest against your web app and API surface and get confirmed SQL injection findings with the exact request and payload, not a scanner guess.
Free AI Pen TestNo credit card. Findings include reproducible steps and exploit code.
