SQL Injection
Injecting attacker-controlled text into a SQL statement so that data is reinterpreted as query structure, letting an attacker read, modify or destroy database contents, bypass authentication, and often pivot to the host.
What it is
SQLi is the archetypal injection flaw (CWE-89): untrusted input is concatenated or interpolated into a query string, so the parser cannot tell the developer’s intended query apart from attacker syntax. The trust boundary that breaks is data vs. code at the query layer — the application treats a value as data, the database treats part of it as SQL. Any sink that builds SQL from strings is exposed: WHERE, ORDER BY, INSERT/UPDATE values, LIMIT/OFFSET, column and table identifiers, GROUP BY, and JSON path expressions. Two decades after it was cataloged it remains endemic, driven by legacy code, ORMs misused as string builders, and now AI-generated “vibe-coded” apps that reintroduce the classic mistake (persistent threat, vibe-coding risk, one apostrophe).
Why it matters
Impact ladder, roughly ascending:
- Authentication bypass — tautologies or comment truncation on a login query (four ways), or a
UNIONthat returns an attacker-chosen row the login then trusts as the admin record (B-52 on XBEN-029). - Data exfiltration — full read of every table; password hashes and PII are the usual target (Ghost CMS CVE-2026-26980 hijacked 700 sites incl. DuckDuckGo/Harvard; Metabase CVE-2026-72898 exfiltrated Trezor/ShipMonk PII of 14k customers).
- Data tampering / privilege escalation — overwriting an admin password hash via a writable sink (ILIAS, Craft
search). - Remote code execution and host compromise — DB-native features turn SQLi into OS access; see SQL Injection to RCE.
Severity drivers: authentication required or not (unauth = critical, e.g. CVSS 10.0 Metabase, Philips Hue Bridge Pro RCE as root), whether the sink is read-only or writable (stacked queries), DB engine capabilities, and the DB role the app connects as (superuser = near-certain RCE). Historic breaches — Heartland, Sony, TalkTalk, MOVEit (2023) — were all SQLi-rooted (survey).
How it works
Injection is classified by how results come back to the attacker:
- In-band / union-based — the query result is reflected in the response, so
UNION SELECTappends attacker rows. See Union-Based SQL Injection. - Error-based — the engine leaks data inside error text (
extractvalue()/updatexml()on MySQL,CAST/type errors on PostgreSQL and MSSQL). A sub-variant of in-band, covered under Union-Based SQL Injection and the cheat sheets (PortSwigger cheat sheet). - Blind (inferential) — no data in the response; the attacker infers it bit by bit via boolean oracles or time delays (
SLEEP(),pg_sleep(),WAITFOR DELAY, Oracledbms_pipe.receive_message). See Blind SQL Injection. - Out-of-band (OOB) — the DB is coerced into a DNS/HTTP callback carrying stolen data, used when the channel is both blind and non-timing (DNS egress). Relies on Out-of-Band Detection.
- Second-order — payload is stored benignly, then executed when later read into a query. See Second-Order SQL Injection.
Adjacent families that share the root cause but differ in engine: NoSQL Injection (operator injection on MongoDB and, surprisingly, on relational ORMs) and ORM Injection (query-builder misfeatures that re-open raw SQL).
Where to find it
- Values from “trusted” peers: OAuth/OIDC-returned profile fields (Virtualizor email) and replication/sync payloads (Trilium) are attacker-chosen even though they arrive from another system. See Second-Order SQL Injection.
- Parameters that reach non-value clauses:
sort/orderBy/orderidentifiers (Daptin, free-fs, Worklenz, Omnispace, EUSurvey), pagination tokens (Kubeflow Pipelines),GROUP BY(pREST), search filters (AppFlowy, YesWiki Bazar, Keep CEL-to-SQL), report/export builders (VtigerExportData.php, LimeSurvey statistics). - Identifiers the ORM won’t parameterize: table/column names,
SET search_pathschema names (django-tenants), formula fields (NocoDB, emlog). See ORM Injection. - Auth and password-reset flows: Metabase
/api/session/reset_password, LiteLLMAuthorizationheader, “SQLi in password reset” bug-bounty pattern (one email). - Pre-registration lookups: identity checks that run before an account exists (Georgia DCSS
POST /api/public/memberssnfield; the samessnparam on password reset was a second paid finding) ($60k Georgia DHS). - Batch and dispatch layers: WordPress 7.0
/wp-json/batch/v1index desync made a stringauthor_excludeskipabsint()and land inNOT IN (...)(Essity WP batch route confusion). - Origin hosts behind SSO: a subdomain fronted by SSO exposed an unauthenticated PHP AJAX endpoint on its origin IP (found via DNS history) with a time-injectable
asset_id(blind SQLi in a private program). - Headers: HTTP header SQLi is real (SqliSniper targets headers; LiteLLM injected via
Authorization). - GraphQL resolvers and API gateways: GraphQL is just a layer over the backend query (WPGraphQL CVE-2026-40762 unauth SQLi; GraphQL time-based SQLi). Link: GraphQL Authorization Flaws.
- AI/agent plumbing: database MCP servers and LLM gateways — a fast-growing surface. See SQL Injection in MCP Servers.
- The DB tooling itself: PostgreSQL
psql/quoting APIs (CVE-2025-1094),pg_dump,CREATE EXTENSIONscript substitution, PerlSQL::Abstract— libraries, not just apps.
How to test
Methodology (manual-first; scanners miss context-dependent sinks — manual method):
- Map every sink that could reach SQL: not just obvious search boxes but sort keys, array/object parameters, JSON bodies, headers, and import files.
- Provoke a differential. A single quote, then its balanced pair; arithmetic on numeric params (
1vs2-1); boolean pairs (' AND 1=1vs' AND 1=2). A change in behavior between true/false is the signal, even when no error shows. - Confirm with a benign oracle before extracting: a timing payload tuned to the engine, or a conditional error. Prefer delay differentials that hold the SQL structure constant (e.g.
SLEEP(0)vsSLEEP(0.01), where per-row evaluation multiplies the delay) over a single long sleep (Essity WP batch route confusion). Distinguishable failure messages (unknown user vs wrong password) are themselves a boolean oracle (B-52 on XBEN-029). - Fingerprint the DBMS (verbose stack traces can leak the exact query and engine, e.g. Tomcat traces showing an Oracle
SQLSyntaxErrorException— SQLi at NASA; version functions, comment syntax, string concat differ per engine — cheat sheet) to pick the right extraction syntax. - Escalate deliberately, choosing the channel the sink allows (union → error → boolean → time → OOB), then enumerate schema.
Checklist:
- Every user-influenced value AND identifier (sort/column/table) tested, in query string, body, JSON, and headers.
- Numeric and string contexts both probed (quote vs. no quote).
- Boolean true/false differential established before blind extraction.
- DBMS fingerprinted; engine-specific comment and concat syntax used.
- Stacked-query support checked (enables writes/DDL and some RCE paths).
- Second-order: inputs that are stored then re-displayed/re-queried retested after the second action.
- OOB channel tried when blind and timing is unreliable (Out-of-Band Detection).
- ORM/NoSQL operator injection tested on JSON and
param[$op]array syntax.
Exploitation and escalation
Paths to impact, each detailed on its page:
- Read everything — Union-Based SQL Injection (direct), Blind SQL Injection (inferential), error-based leaks.
- Bypass auth / escalate — tautologies, overwriting admin credentials through a writable sink or stacked query (OpenEMR Syndromic Surveillance resets any user’s password; ILIAS overwrites root hash).
- Reach the OS — SQL Injection to RCE: PostgreSQL superuser
COPY ... PROGRAM/large objects, MSSQLxp_cmdshell, OracleCREATE JAVA SOURCE(khunt toolkit), file read/write primitives, and chains into deserialization (LangGraph checkpointer CVE-2026-28277). - Pivot across tenants / cloud — stealing API keys and provider credentials (LiteLLM, Kong AI Gateway LLM usage counters, Looker Studio “LeakyLooker”).
Bypassing defenses
Common failures that re-open a “fixed” or “protected” app — see WAF Bypass for SQL Injection and ORM Injection:
- Parameterization skipped for identifiers — prepared statements bind values, not column/table names, so
ORDER BY, schema names and formula fields stay injectable. - Encoding/charset escaping bugs — multibyte lead-byte absorption defeats byte-wise escaping (Trilogy MySQL adapter GHSA-744p-w4gc-m3gh, CVE-2025-1094 invalid UTF-8 in
psql). - Incomplete fixes — patching one call site, not the sink: Craft
findOne()second path (GHSA-cphx-cx67-jcqj) after the September fix; pREST_groupbyincomplete fix. - WAF signature evasion — case/whitespace/comment mutation, versioned comments (
/*!...*/), JSON-based SQLi that WAFs don’t parse (JSON-based), and ML/adversarial evasion (AutoSpear). - Keyword blocklists — case-sensitive matching misses mixed-case keywords, and comment bans are sidestepped by balancing the app’s own trailing quote (TryHackMe Light); a WAF blocking
UNIONpushes extraction to boolean inference rather than stopping it (SQLi at NASA). - Type guards that check emptiness, not type —
WP_Querytested! empty($q['author__not_in'])but notis_array, so a string skipped the per-elementabsint()(Essity WP batch route confusion). - Read-only guardrails — comment-parsing divergence and
ATTACH/COMMITescapes in DB MCP servers (SQL Injection in MCP Servers).
Real-world cases
- Metabase CVE-2026-72898 (CVSS 10.0) — unauth SQLi via undeclared
user-idkey in/api/session/reset_password; Clojuremerge+ JSON keywordization + HoneySQL:raw; exploited in the wild, Trezor/ShipMonk breach (Wiz teardown, Bishop Fox). - LiteLLM CVE-2026-42208 (CVSS 9.3) — pre-auth SQLi in proxy key verification via
Authorizationheader; exploited within 36 hours, added to CISA KEV; stole OpenAI/Anthropic/AWS creds (THN). - Oracle “khunt” / oraexec — SQLi into a Java app, then
CREATE JAVA SOURCEto run SYSTEM-level commands from inside Oracle, evading EDR (CSO). - PostgreSQL CVE-2025-1094 — quoting-API/
psqlinjection via invalid UTF-8; a prerequisite for BeyondTrust CVE-2024-12356 RCE (Rapid7). - Ghost CMS CVE-2026-26980 — unauth SQLi, 700+ sites hijacked for ClickFix malware (SecurityWeek).
- GeoServer / FortiWeb / ServiceNow / SAP — unauth SQLi in enterprise and infra products, several exploited as zero-days (GeoServer
jsonArrayContains; FortiWeb GUI; ServiceNow CVE-2026-74820 CVSS 10.0; SAP BPC CVSS 9.9). - WordPress 7.0 REST batch (Essity, HackerOne, critical) — unauth blind SQLi: a failed
parse_url()sub-request isn’t pushed to$matchesbut the index still advances, so nested batches run sub-request N with handler N+1 and a categories query string reaches a postsNOT INclause (Essity WP batch route confusion). - Georgia DHS (HackerOne, $25k + $20k) — unauth time-based blind SQLi on IBM DB2 via the
ssnfield of a member lookup, then the same root cause on the password-reset endpoint ($60k Georgia DHS). - NASA (VDP, LoR) — Oracle boolean blind SQLi in a WADL-discovered
labelparameter; WAF blockedUNION(SQLi at NASA). - Bugcrowd private program (P1) — time-based SQLi in
asset_idon an origin IP behind SSO, 22 databases enumerated with sqlmap (blind SQLi in a private program). - Softaculous Virtualizor CVE-2026-135174 (critical, <3.2.9) — unauth auth bypass:
enduser/auth_callback.phpput the OAuth-returned email into SQL, so an IdP account whose email carries SQL syntax completes social login as the admin (advisory). - Trilium CVE-2026-135686 (critical, ≤0.107.0) — a malicious sync partner supplies entity names and column keys that
updateNormalEntity()interpolates, copying sessions/etapi_tokensinto synced rows and writing arbitrary rows (advisory). - WHMCS CVE-2026-82981 — unauth SQLi exposing client PII, support tickets, admin records and password hashes (advisory).
- EUSurvey ≤1.6 — Form Manager role, unrecognized
sortvalues pasted into a native query’sORDER BYonGET /dashboard/surveys; time-based inference reads anything the DB account can (advisory). - Ghost Render CTF — sqlmap on a saved login request dumps admin creds, which unlock a Jinja2 SSTI (walkthrough). See Server-Side Template Injection.
- Looker Studio “LeakyLooker” — zero-click cross-tenant SQLi against BigQuery/Spanner connectors (THN).
- Cisco Secure Email Gateway CVE-2026-76461: unauthenticated SQLi in the ECS Message-ID handling led to RCE and was exploited as a zero-day. (source)
Prevention
- Parameterized queries / prepared statements everywhere — the only reliable fix; treat input strictly as data. Pair with real password-hash verification and uniform login-failure responses so a returned row alone can’t authenticate and failures don’t form an oracle (B-52) (parameterization, defense methods).
- Identifiers can’t be bound — allow-list them. Map sort/column/table/schema names to a fixed set; never interpolate. This is where most 2026 CVEs live (ORM Injection).
- Use the ORM safely. Prefer typed query APIs; avoid
FromSqlRaw/raw escapes and operator-accepting filters on untrusted input (EF Core, Node.js). - Validate type, not just presence. Array-expected parameters must be checked with
is_array(or typed binding) before per-element casts (Essity). - Don’t leak stack traces. Production 500s that print the query and DBMS hand the attacker steps 2–4 (NASA).
- Least privilege DB role. No superuser for app connections; this alone blocks most SQLi→RCE paths. Disable stacked queries where the driver allows.
- Fix the sink, not the call site. Craft and pREST show that patching one path leaves the sink open.
- Defense in depth, not substitution. WAFs and RASP (e.g. in-app firewalls) are a backstop, not a control — all are bypassable (WAF Bypass for SQL Injection, SQLi isn't dead).
Tools
- sqlmap — the standard automated detection/exploitation engine (in-band, blind, OOB, DBMS takeover).
- Burp Suite / Scanner, ghauri, jSQL, BBQSQL, SqliSniper (header-focused), BSQLinjector (blind), NoSQLMap (NoSQL) — surveyed in the SQLi tool roundups (detection tools, payload/tool collection).
- References: PortSwigger cheat sheet, NetSPI SQL Injection Wiki, OWASP.
Sub-pages
- Blind SQL Injection — boolean, time-based and OOB inference when the response carries no data.
- Union-Based SQL Injection — in-band and error-based extraction via
UNION SELECTand error leakage. - Second-Order SQL Injection — stored-then-executed injection across requests.
- NoSQL Injection — operator injection on MongoDB and relational ORMs.
- ORM Injection — raw-SQL misfeatures and identifier gaps in ORMs and query builders.
- SQL Injection to RCE — DB-native escalation to OS command execution and host compromise.
- WAF Bypass for SQL Injection — evading signature, encoding and JSON-parsing gaps.
- SQL Injection in MCP Servers — read-only bypass and SQLi in AI database connectors and gateways.
- sqlmap — the automated SQLi detection and exploitation tool.
Sources
- EUSurvey blind SQL injection · original
- WHMCS unauthenticated SQL injection · original
- Trilium SQL injection in updateNormalEntity() (critical) · original
- Softaculous Virtualizor SQL injection (critical) · original
- Ghost Render CTF: SQL Injection, Jinja2 SSTI and Reverse Shell · original
- SQL injection isn't dead · original
- Demystifying SQL Injection · original
- 9 SQLi Detection Tools · original
- A login bypassed by SQL injection: B-52 on XBEN-029 · original
- Critical SQL Injection in Metabase via Password Reset (CVE-2026-72898) · original
- SQLi at NASA: how I got my Letter of Recognition · original
- SQL Injection 2025 Advanced Exploitation & Defense Guide · original
- secret-table-2: AlpacaHack web writeup (SQLi) · original
- TryHackMe Light: SQLite injection past a keyword filter · original
- Attackers hid malware inside Oracle Database after SQL injection · original
- SAP Security Patch Day April 2026 (CVSS 9.9 SQLi) · original
- GeoServer zero-day unauth SQLi · original
- Unauthenticated SQL Injection in FortiWeb GUI · original
- SQLi Payloads - Classic, Blind, Error-Based, Time-Based, WAF Bypass · original
- Essity: Unauthenticated SQL Injection via REST Batch Route Confusion ████████ · original
- SQL injection remains a persistent cyber threat after two decades · original
- SQL Injection in Password Reset: Full Database, One Email · original
- The Devil Went Down to Georgia: How I Made $60k Hacking the DHS · original
- Bypassing a Login Form with SQL Injection: Four Ways · original
- How I discovered a blind SQL injection in a private program · original
- How I Find SQL Injection Vulnerabilities (manual method) · original
- Second-Order SQL Injection with Stored Procedures and DNS-Based Egress · original
- SQL Injection 101: Common Defense Methods · original
- ML WAF vs AutoSpear evasion · original
- SQL Injection (OWASP) · original
- WAF Bypass Using JSON-Based SQL Injection · original
- SQL injection cheat sheet (PortSwigger) · original
- SQL Injection Tutorial & Examples (PortSwigger) · original
- Identifying SQL Injections in a GraphQL API · original
- CVE-2025-1094: PostgreSQL psql SQL Injection (Rapid7) · original
- picoCTF 2026 SQL Map1 writeup · original
- Ghost CMS Vulnerability Exploited to Hack Over 700 Websites · original
- 7 Types of SQL Injection Attacks & How to Prevent Them · original
- Getting started with query parameterization · original
- Preventing SQL injection attacks in Node.js · original
- Preventing SQL injection in C# with Entity Framework · original
- SQL Injection Wiki (NetSPI) · original
- Vibe-Coding's Hidden Danger: SQL Injection Risks Go Live · original
- LiteLLM CVE-2026-42208 Exploited within 36 Hours · original
- Metabase Zero-Day Exploited in Wild · original
- LeakyLooker: Cross-Tenant SQL in Looker Studio · original
- Three CVSS 10.0 ServiceNow Flaws · original
- SQL Injection in 2026: It Took One Apostrophe · original
- Inside the Metabase SQLi: Exploited in the Wild · original
- Metasploit Wrap Up: Breaking Zimbra's Identity Boundaries · original