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:

  1. Authentication bypass — tautologies or comment truncation on a login query (four ways), or a UNION that returns an attacker-chosen row the login then trusts as the admin record (B-52 on XBEN-029).
  2. 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).
  3. Data tampering / privilege escalation — overwriting an admin password hash via a writable sink (ILIAS, Craft search).
  4. 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 SELECT appends 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, Oracle dbms_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/order identifiers (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 (Vtiger ExportData.php, LimeSurvey statistics).
  • Identifiers the ORM won’t parameterize: table/column names, SET search_path schema names (django-tenants), formula fields (NocoDB, emlog). See ORM Injection.
  • Auth and password-reset flows: Metabase /api/session/reset_password, LiteLLM Authorization header, “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/member ssn field; the same ssn param on password reset was a second paid finding) ($60k Georgia DHS).
  • Batch and dispatch layers: WordPress 7.0 /wp-json/batch/v1 index desync made a string author_exclude skip absint() and land in NOT 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 EXTENSION script substitution, Perl SQL::Abstract — libraries, not just apps.

How to test

Methodology (manual-first; scanners miss context-dependent sinks — manual method):

  1. Map every sink that could reach SQL: not just obvious search boxes but sort keys, array/object parameters, JSON bodies, headers, and import files.
  2. Provoke a differential. A single quote, then its balanced pair; arithmetic on numeric params (1 vs 2-1); boolean pairs (' AND 1=1 vs ' AND 1=2). A change in behavior between true/false is the signal, even when no error shows.
  3. 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) vs SLEEP(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).
  4. 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.
  5. 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, MSSQL xp_cmdshell, Oracle CREATE 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 _groupby incomplete 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 UNION pushes extraction to boolean inference rather than stopping it (SQLi at NASA).
  • Type guards that check emptiness, not type — WP_Query tested ! empty($q['author__not_in']) but not is_array, so a string skipped the per-element absint() (Essity WP batch route confusion).
  • Read-only guardrails — comment-parsing divergence and ATTACH/COMMIT escapes in DB MCP servers (SQL Injection in MCP Servers).

Real-world cases

  • Metabase CVE-2026-72898 (CVSS 10.0) — unauth SQLi via undeclared user-id key in /api/session/reset_password; Clojure merge + 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 Authorization header; 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 SOURCE to run SYSTEM-level commands from inside Oracle, evading EDR (CSO).
  • PostgreSQL CVE-2025-1094 — quoting-API/psql injection 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 $matches but the index still advances, so nested batches run sub-request N with handler N+1 and a categories query string reaches a posts NOT IN clause (Essity WP batch route confusion).
  • Georgia DHS (HackerOne, $25k + $20k) — unauth time-based blind SQLi on IBM DB2 via the ssn field 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 label parameter; WAF blocked UNION (SQLi at NASA).
  • Bugcrowd private program (P1) — time-based SQLi in asset_id on 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.php put 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_tokens into 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 sort values pasted into a native query’s ORDER BY on GET /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

Sub-pages

Sources