--- name: sh-kb-sqli description: "Knowledge base for finding SQL injection (and query-language injection). Use when hunting SQLi, or when a hunter/reviewer needs sources, sinks, detection queries, payloads, false-positive filters, detection signals, and remediation for injection into SQL/ORM raw queries. CWE-89, OWASP A03:2021-Injection." --- # SQL Injection - Hunter Knowledge Base SQLi happens when attacker-controlled input is placed into a SQL statement as **code** rather than **data** - typically string concatenation/interpolation into a query instead of a bound parameter. ## When to hunt this - Any code that builds SQL from variables: string concatenation, f-strings/template literals, `%`/`+`/`.format`. - ORM "raw" escape hatches even when the ORM normally parameterizes. - Dynamic query pieces attackers rarely expect to be bound: table/column names, `ORDER BY`, `LIMIT`, `IN (...)` lists, `LIKE` patterns, `GROUP BY`, `HAVING`, JSON path keys, search/filter DSLs that map user field names to columns. - Reachability first: prioritize sinks reachable from an entry point in `codebase-map.json`. ## Sources (untrusted input) Request params/body/query/headers/cookies, path segments, uploaded content (CSV/Excel import rows), GraphQL arguments, values from other services or queues, and anything from the entry-point inventory. Headers logged into an audit/analytics INSERT (`User-Agent`, `X-Forwarded-For`, `Referer`) count. Also "stored" sources: DB/file values that were themselves attacker-influenced (second-order SQLi), including usernames, profile fields and filenames re-read by cron jobs, exports, reports and admin screens. ## Sinks by ecosystem (grep targets) - **Python**: `cursor.execute(`, `cursor.executemany(`, `.execute(` on a DB conn; SQLAlchemy `text(`, `literal_column(`, `.from_statement(`, `session.execute(`, `engine.execute(`, `order_by(text(user))`; Django `.raw(`, `.extra(`, `RawSQL(`, `connection.cursor()`; FastAPI/Flask handlers using f-strings. Danger sign: a `%`, `+`, `f"..."`, or `.format(` inside the SQL string (`%` with a params list is safe). - **JS/TS**: `db.query(`, `connection.query(`, `pool.query(`, `client.query(`, `sequelize.query(` (without `replacements`/`bind`), `Sequelize.literal(`, `knex.raw(`/`whereRaw`/`orderByRaw`, `$queryRawUnsafe`/`$executeRawUnsafe`/`Prisma.raw(` (Prisma), TypeORM `.query(`, `.where(\`...${x}\`)`, `.orderBy(userInput)`. Template literals with `${...}` inside SQL. Express `qs` parsing makes `?a[b]=1` an object, so a value expected to be a string may arrive as an object or array. - **Java**: `Statement.execute*(`, `createStatement()` then `executeQuery(concat)`, `JdbcTemplate.query/update(concat)`, JPA/Hibernate `createQuery`/`createNativeQuery` with concat (HQL/JPQL injection too), Spring Data `Sort` or `JpaSort.unsafe` built from a request param, MyBatis `${}` (vs safe `#{}`), esp. in `ORDER BY`/`LIKE`/`IN`. - **PHP**: `mysqli_query(`, `$pdo->query(`, `->exec(` with concatenation; `mysql_query(`; Laravel `DB::raw(`, `whereRaw(`, `selectRaw(`, `orderByRaw(`, `havingRaw(`, `DB::select(` with concat, `orderBy($request->col)`. - **Go**: `db.Query(`/`db.Exec(`/`QueryRow(`/sqlx `Get`/`Select` where the query is built with `fmt.Sprintf`/`+`; GORM `db.Raw(`, `db.Exec(`, `Where("x = " + v)`, `.Order(userStr)`, `First(&o, "id = "+v)`. - **Ruby**: `where("... #{}")`, `find_by_sql(`, `exec_query(`, `.where(user_str)`, and string args to `order`, `reorder`, `group`, `joins`, `from`, `select`, `pluck`, `update_all`, `delete_all`, `find_by("...")`. - **.NET**: `SqlCommand(concat)`/`CommandText +=`, `ExecuteReader` with interpolated string; EF `FromSqlRaw(`/`ExecuteSqlRaw(` with an interpolated or concatenated string (`FromSqlInterpolated` binds); Dapper `Query(` with concat; Dynamic LINQ (`OrderBy(string)`, `Where(string)`) on user text. - **DB side**: stored procedures building SQL: `EXEC(@sql)`, `sp_executesql` with concat, `EXECUTE IMMEDIATE`, PL/pgSQL `EXECUTE format('%s', ...)` (`%I`/`%L` or `quote_ident`/`quote_literal` are safe). ## Detection recipe (see references/graft-guide.md) 1. `graft grep "execute\(|\.query\(|raw\(|Raw\(|whereRaw|orderByRaw|\.literal\(|createNativeQuery|FromSqlRaw|ExecuteSqlRaw|find_by_sql|queryRawUnsafe|\.Sprintf\(.*(SELECT|INSERT|UPDATE|DELETE)" --json` (or Grep, `-i`). 2. For each hit, inspect the query argument: is it a bound-parameter call (safe) or string building (suspect)? Grep the same lines for `%|\+|\$\{|f\"|\.format\(|#\{|Sprintf|concat`. 3. Also grep SQL keywords inside string literals that are concatenated across lines (`"SELECT ... " +`, `ORDER BY "`, `LIMIT "`), since the hit often is not on the call line. 4. `graft callers ` to reach an entry point; record the `data_flow[]` source->sink. 5. Confirm no whitelist/cast/parameterization intervenes. Read the helper that builds the fragment: a `build_where(filters)` or `sort_clause(col)` helper is where one fix covers or misses many callers. ## Payloads / PoC templates (curated) - Detection: `'` , `''` , `1' OR '1'='1` , `1) OR (1=1` , `admin'--` , `" OR ""="`. - Boolean-blind: `1 AND 1=1` vs `1 AND 1=2` (differing responses). - Time-blind: `1; WAITFOR DELAY '0:0:5'--` (MSSQL), `1 AND SLEEP(5)` (MySQL), `1; SELECT pg_sleep(5)--` (PG). - UNION: `1 UNION SELECT NULL,version(),NULL--` (adjust column count/types). - Error-based: `1 AND extractvalue(1,concat(0x7e,version()))` (MySQL). - Second-order: store `x'--` via one endpoint, trigger the vulnerable query via another. - Non-value positions: `ORDER BY (CASE WHEN 1=1 THEN id ELSE name END)` vs `1=2` (ordering differs = injectable). See `references/cheatsheet.md` for per-DB detail and `ORDER BY`/`LIKE`/`IN` injection variants. ## Variant hunting - Once one sink is found, grep for the **same helper** and every caller of it; fix gaps are per-helper. - Grep the same construction idiom repo-wide (same `f"SELECT`, same `Sprintf`, same `${}` position). - Walk sibling endpoints of the same resource (list/search/export/report/admin/CSV) - the list endpoint is often parameterized while `sort`, `filter`, `export` and `search` on the same resource are not. - Compare the same query in the REST, GraphQL, gRPC, and legacy/v1 handlers, and in background jobs. - Look for copy-pasted repository/DAO classes and for query builders accepting a user `field`/`op` pair. - For a second-order hit, list every reader of the tainted column (reports, emails, exports, cron). ## False-positive filters (do NOT flag) - Fully **parameterized** queries: `execute("... WHERE id = %s", [id])`, `?`/`:name` placeholders, Prisma `$queryRaw` tagged template (safe) vs `$queryRawUnsafe` or `$queryRaw(string)` (unsafe), MyBatis `#{}`. - The interpolated value is a **constant/enum/int-cast** the attacker cannot control, or is validated against an allowlist (e.g. sort column checked against a fixed set, direction compared to `asc`/`desc`). - ORM query builders (`.filter(User.id==id)`, `.where({id})`) that bind under the hood. Passing a user dict as `filter(**d)` or `where(obj)` is a field/operator-selection issue, not SQL injection, unless keys reach raw SQL. - Identifiers quoted via a proper quoting API (e.g. `psycopg2.sql.Identifier`, knex `??`). - Evidence for a real finding: the exact line where tainted text joins the SQL string, no cast/allowlist between source and sink, and the value type (string, not int) permits a quote or keyword. - Incomplete fixes that still count: quote escaping (`addslashes`, `replace("'", "''")`) on a numeric or identifier position, blocklists of `--`/`union`, a cast on one code path but not its sibling, a Ruby regex guard using `^...$` (line anchors) rather than `\A...\z`, validation done only client-side. ## CWE / OWASP / severity - CWE-89 (SQLi), CWE-943 (NoSQL/query injection). OWASP **A03:2021-Injection**. - Severity: usually **critical** if unauthenticated and dumps/modifies data; **high** if authenticated or limited. Blind-only with narrow impact may be high/medium. ## Chaining hints - SQLi -> read credential/secret tables -> auth bypass / account takeover. - SQLi write -> stored XSS or config poisoning. - SQLi -> read files (`LOAD_FILE`, `COPY ... FROM PROGRAM`) -> RCE on some DBs; -> SSRF via DB features. - Feeds chains with `secrets`, `auth`, `access-control`. ## Detection signals (for defenders) - **Web/WAF/proxy logs** (URL, query string, POST body, status, response bytes, latency): bursts of 500s or DB-error text on one parameter; one client trying many quote/keyword variants on the same field; response size or latency that swings with a single parameter (boolean/time-blind probing); very long or keyword-heavy values in fields that are normally short ids. - **Database audit/query logs** (pgaudit, MySQL audit or general log, MSSQL audit/Extended Events; need app account, statement text, error code, duration): syntax-error counts per app account; the app account reading `information_schema`, `pg_catalog`, `sqlite_master` or `sys.*` when it never does; statements that change shape (new `UNION`, extra subselects, stacked statements); sleep/delay functions in statement text. - **Behavior-based ideas**: (1) baseline the set of normalized statement templates each app account runs, alert on a never-seen template or on catalog-table access by that account; (2) alert when a single source's request-latency standard deviation on one endpoint jumps while the parameter value varies (time-based extraction), independent of any payload string. - **EDR/host**: database server process (`mysqld`, `postgres`, `sqlservr`) spawning a shell or interpreter; new files written by the DB service into web roots (`INTO OUTFILE`, `COPY ... TO`). - **Egress/DNS**: DB host making DNS or HTTP requests to unfamiliar domains (out-of-band exfil). - ATT&CK: T1190 Exploit Public-Facing Application; T1059 Command and Scripting Interpreter (DB-spawned shell); T1565 Data Manipulation (injected writes). ## Mitigation (put a specific one on each finding) Use parameterized queries / prepared statements for values; for identifiers use an allowlist or the driver's identifier-quoting API; least-privilege DB accounts (no file, exec, or catalog-wide rights); ORM safe APIs; turn off multi-statement execution where the driver offers it. Never concatenate input into SQL, and do not rely on escaping or blocklists.