Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

docs(case-study): complete PHP guide — dangerous PATTERNS (==, array-inj, SQL truncation)

Xerj Squad A6d0fc7dfa638
diff --git a/docs/case-studies/wordpress-security-audit/README.md b/docs/case-studies/wordpress-security-audit/README.md
index ab8fb2135..045e4eba3 100644
--- a/docs/case-studies/wordpress-security-audit/README.md
+++ b/docs/case-studies/wordpress-security-audit/README.md
@@ -103,6 +103,10 @@ read; scale and durability come from XERJ.
→ reverse callers → authz), with `sink-census/trace_sink.py`.
- [`sink-census/PHP-DANGEROUS-FUNCTIONS.md`](sink-census/PHP-DANGEROUS-FUNCTIONS.md) —
the **full map of 275 dangerous PHP functions** (28 categories, taint-arg noted).
+- [`sink-census/PHP-SECURITY-GUIDE.md`](sink-census/PHP-SECURITY-GUIDE.md) — the
+ **complete guide**: 275 functions **+** the non-function patterns (type-juggle
+ `==`, array injection `?login[]=`, SQL truncation, magic-hash, null-byte,
+ second-order, TOCTOU, timing, …) with attack + detection + safe recipe.
- **Copyable Claude Code skill**: [`skill/SKILL.md`](skill/SKILL.md)
— install it and run this whole workflow on your own codebase.
- [`FINDINGS.md`](FINDINGS.md) — the SSRF vulnerability, with verification and
diff --git a/docs/case-studies/wordpress-security-audit/sink-census/PHP-SECURITY-GUIDE.md b/docs/case-studies/wordpress-security-audit/sink-census/PHP-SECURITY-GUIDE.md
new file mode 100644
index 000000000..99dded3a7
--- /dev/null
+++ b/docs/case-studies/wordpress-security-audit/sink-census/PHP-SECURITY-GUIDE.md
@@ -0,0 +1,172 @@
+# The complete PHP security guide (for the xerj-security-audit skill)
+
+A whitebox PHP audit has **two axes**, and both must be covered to claim
+completeness:
+
+1. **Dangerous functions (sinks)** — 275 built-ins/constructs, one call = one
+ candidate. Enumerable and *provable* by AST census. See
+ [`PHP-DANGEROUS-FUNCTIONS.md`](PHP-DANGEROUS-FUNCTIONS.md) /
+ `php_dangerous_functions.json`.
+2. **Dangerous patterns** — vulnerabilities that are **not a function call**:
+ language semantics (`==` juggling), input *shape* (`?login[]=`), and semantic
+ attacks (SQL truncation). These the sink census misses entirely. Catalogued in
+ `php_dangerous_patterns.json`; the AST-detectable ones are censused by
+ `pattern_census.py` into the `wppatterns` index.
+
+> **Rule of thumb:** a sink tells you *where danger can happen*; a pattern tells
+> you *how safe-looking code is actually exploitable*. You need both.
+
+Measured on WordPress core: **11,191 sink sites** (proven 0-gap) + **2,077
+pattern hits** across 10 AST-detectable patterns, + the manual/semantic classes
+below that require reasoning.
+
+---
+
+## Part 1 — Dangerous functions (the sink axis)
+
+Full table in [`PHP-DANGEROUS-FUNCTIONS.md`](PHP-DANGEROUS-FUNCTIONS.md). 275
+functions across 28 categories, each with vuln class, safe/unsafe recipe, and the
+taint-relevant argument: command/code exec, dynamic callables (`array_map`,
+`preg_replace_callback`), `unserialize`, include loaders, file read/write/delete/
+perms, directory, SSRF, SQL drivers, LDAP, XXE, variable-injection, ReDoS/ereg,
+mail, header/redirect, weak crypto/random, info-disclosure, runtime-config,
+process-control, reflection-invoke, type-juggle functions, output/XSS. Coverage is
+*proven*: every call site is enumerated and reconciled against grep to 0 gaps.
+
+---
+
+## Part 2 — Dangerous patterns (the class the sink axis misses)
+
+### A. Type juggling & loose comparison
+- **Loose `==` / `!=`** (`loose-eq`) — `'0e123' == '0e456'` (both are `0` as
+ floats → **magic hash** auth bypass); `'0'==false`, `null==0`, `'1abc'==1`,
+ `0=='abc'` (pre-PHP8). **Detect:** AST `binary_expression` with `==`/`!=`/`<>`;
+ flag when a side is a `hash()`/`md5()`/token/password. **Safe:** `===`,
+ `hash_equals()`, `password_verify()`. *(WP core: 1,373 loose-`==`.)*
+- **`switch()` uses loose `==`** (`switch-loose`) — `switch($_GET['role'])`
+ matches `case 0` for `'0abc'`/`true`. **Safe:** `match(true)` / cast+validate.
+- **`strcmp`/`strcasecmp`/`strncmp` with an array arg returns `NULL`**
+ (`strcmp-array`) — `?pw[]=x` makes `$_GET['pw']` an array; `strcmp(array,$x)`
+ → `NULL`; `if(strcmp(...)==0)` → `NULL==0` → **TRUE → bypass**. **Safe:**
+ `is_string()` guard; `hash_equals`; `===0`.
+- **`in_array`/`array_search` without `strict=true`** (`in-array-loose`) —
+ `in_array('1abc',[1,2,3])` is TRUE; allow-list bypass. **Safe:** pass `true`.
+ *(WP core: 124.)*
+- **Non-constant-time secret compare** (`timing-compare`) — `$mac == $expected`
+ leaks timing *and* juggles. **Safe:** `hash_equals`. *(WP core: 56.)*
+
+### B. Input shape (the `?param[]=` family)
+- **Array injection** (`array-injection`) — sending `login[]=a` makes
+ `$_POST['login']` an **array**. It breaks every string-typed sink:
+ `preg_match` returns `false`, `strcmp`/`md5`/`hash` return `NULL`+warning, SQL
+ interpolates the literal `Array`, and `is_string()`-less validators are
+ bypassed. The single most under-tested PHP input bug. **Detect:** request params
+ reaching string functions/SQL/regex with no `is_string()`/`is_scalar()`/`(string)`
+ guard. **Safe:** validate/cast every request param to the expected type; reject
+ arrays where scalars are expected.
+- **Mass assignment / register_globals emulation** (`mass-assignment`) —
+ `extract($_REQUEST)`, `foreach($_POST as $k=>$v){$$k=$v;}`,
+ `$obj->fill($_POST)` overwrite variables/columns (`is_admin`). **Safe:** explicit
+ field allow-list.
+- **Variable variables** (`var-variable`) — `$$key` with request-controlled
+ `$key` → arbitrary variable overwrite. **Safe:** allow-listed array lookup.
+
+### C. SQL semantics (beyond the driver call)
+- **SQL truncation** (`sql-truncation`) — register `admin` + 55 spaces + `x`;
+ MySQL in non-STRICT mode silently truncates to the `VARCHAR(N)` column length →
+ stored as `admin` → **duplicate/overwrite the admin account**. **Detect:**
+ needs the column length — manual/schema. **Safe:** validate max length;
+ `STRICT_ALL_TABLES`.
+- **Multibyte charset SQLi** (`charset-sqli`) — GBK/Big5 + `addslashes` →
+ `0xbf27` becomes a valid char + a free quote, escaping the escaper. **Safe:**
+ parameterized queries; `set_charset('utf8mb4')`.
+- **ORDER BY / LIMIT / identifier injection** (`order-by-inj`) — placeholders
+ can't bind identifiers; `ORDER BY $_GET['sort']` = injection. **Safe:**
+ allow-list columns. *(WP core: 22 candidate lines.)*
+- **Second-order injection** (`second-order`) — safe on input, unescaped when
+ later read from the DB and concatenated. **Safe:** escape at every sink; treat
+ DB reads as untrusted.
+
+### D. Type confusion & validation bypass
+- **`is_numeric`/`intval`/`filter_var` bypass** (`is-numeric-bypass`) —
+ `is_numeric('0x1A'|'1e3'|' 12')` can be TRUE; `(int)'123abc'==123`;
+ `FILTER_VALIDATE_URL` accepts `javascript:`. **Safe:** `ctype_digit`; explicit
+ FILTER flags; cast+re-render+compare.
+- **`empty()`/`isset()` logic pitfalls** (`loose-empty-isset`) — `empty('0')` is
+ TRUE → a legitimate `'0'` treated as missing in an auth branch. **Safe:**
+ `=== ''`, `array_key_exists`.
+
+### E. Regex footguns
+- **Anchor / multiline / dot bypass** (`regex-anchor-bypass`) — `/^ok$/`: `$`
+ matches before a trailing `\n`; `.` doesn't match `\n`, so a newline payload
+ bypasses. **Safe:** `\A...\z`, `/D`, reject newlines.
+- **PCRE backtrack returns `false`, not `0`** (`pcre-backtrack`) — on catastrophic
+ backtracking `preg_match` returns `false`; `if(preg_match($bad,$x))` treats it as
+ no-match → validator bypass + ReDoS. **Safe:** check `===1`; bound input length.
+- **`preg_replace /e`** — eval'd replacement (see the sink catalog).
+
+### F. Files, paths, races
+- **Null-byte truncation** (`null-byte`) — `secret.php%00.jpg` truncates in file
+ ops (pre-5.3.4); `%00` splits validators. **Safe:** reject `\0`; PHP ≥ 5.3.4.
+- **Path traversal encodings** (`path-traversal`) — `../`, `..%2f`, `%2e%2e`,
+ `....//`, absolute override. **Safe:** `realpath()` under a verified base;
+ `basename`+allow-list.
+- **phar:// deserialization** (`phar-deser`) — `phar://x.jpg` triggers
+ `unserialize` of Phar metadata via **any** file op → POP chain. **Safe:** deny
+ wrappers; `Phar::interceptFileFuncs`.
+- **TOCTOU race** (`toctou`) — `is_writable($f)` then `fopen($f)`; attacker swaps
+ via symlink. **Safe:** operate on fds; atomic ops.
+- **Upload → exec** (`upload-exec`) — `shell.php`/`.phtml`/double-ext/MIME-spoof/
+ `.htaccess` in a served dir. **Safe:** random name; ext+content allow-list;
+ non-exec storage.
+
+### G. Auth, session, trust boundaries
+- **CSRF absence** (`csrf-absence`) — state change reachable with no verified
+ nonce/token. **Detect:** absence property (the authz graph). **Safe:** per-user
+ per-action nonce.
+- **Session fixation** (`session-fixation`) — no `session_regenerate_id(true)`
+ after login. **Safe:** regenerate on every privilege change.
+- **Missing cookie flags** (`cookie-flags`) — `setcookie` without HttpOnly/Secure/
+ SameSite. **Safe:** set all three. *(WP core: 44 candidate calls.)*
+- **Host/X-Forwarded trust** (`host-header`) — `$_SERVER['HTTP_HOST']` /
+ `X-Forwarded-*` used in URLs, reset links, or access decisions → poisoning.
+ **Safe:** fixed site URL; trust only vetted proxies. *(WP core: 25.)*
+- **Open redirect** (`open-redirect`) — `Location: $_GET['next']` to `//evil`,
+ `\evil`, `javascript:`. **Safe:** allow-list host; `wp_safe_redirect`.
+
+### H. Output / XSS context
+- **Wrong-context escaping** (`xss-context`) — `htmlspecialchars` without
+ `ENT_QUOTES` in an attribute; `esc_html` on a JS/URL/CSS value; JSON in
+ `<script>` without `JSON_HEX_TAG`. **Safe:** context-correct escaper.
+
+### I. Footguns
+- **`@` error suppression** (`error-suppression`) — `@unserialize`/`@$_GET` hides
+ security-relevant failures. **Safe:** handle errors. *(WP core: 419.)*
+- **User enumeration** (`user-enum`) — distinct message/timing for valid vs
+ invalid users. **Safe:** uniform responses.
+
+---
+
+## Part 3 — Coverage: what's provable vs what needs reasoning
+
+| detection kind | classes | how the skill covers it |
+|---|---|---|
+| **AST (provable census)** | all 275 sinks; loose-`==`, `in_array`, `strcmp`-array, `@`, var-vars, cookie-flags, `switch`-on-request | `sink_census.py` (0-gap proof) + `pattern_census.py` → `wpsinks`/`wppatterns` |
+| **regex/query** | ORDER-BY injection, Host-header trust, open-redirect | pattern census + XERJ queries over facts |
+| **manual / semantic** | SQL truncation, charset SQLi, second-order, phar, TOCTOU, upload-exec, is_numeric bypass, regex-anchor, session-fixation, xss-context, user-enum | agent reasoning on the flagged code + schema/runtime; verify by reading then executing |
+
+**The honest coverage statement:** *sink calls are enumerated with a proven
+zero-gap census; the AST-detectable patterns are censused into `wppatterns`; the
+semantic/manual pattern classes are catalogued with detection guidance and swept
+by agent reasoning — no dangerous class is un-catalogued.* That last clause is
+what "we know ALL the functions and patterns" means, honestly.
+
+## Reuse
+```bash
+python3 sink_census.py <src> # 275 functions -> wpsinks (0-gap proof)
+python3 pattern_census.py <src> # AST-detectable patterns -> wppatterns
+python3 enrich_pipeline.py # AI verdicts on the high-risk of both
+python3 trace_sink.py <file> <line>
+```
+Extend `php_dangerous_functions.json` and `php_dangerous_patterns.json` for your
+framework/language — the model is data, not code.
diff --git a/docs/case-studies/wordpress-security-audit/sink-census/pattern_census.py b/docs/case-studies/wordpress-security-audit/sink-census/pattern_census.py
new file mode 100644
index 000000000..fbc8b4278
--- /dev/null
+++ b/docs/case-studies/wordpress-security-audit/sink-census/pattern_census.py
@@ -0,0 +1,94 @@
+#!/usr/bin/env python3
+"""Census the AST-detectable dangerous PATTERNS (the non-function vuln classes:
+loose ==, non-strict in_array, strcmp/array injection, @ suppression, variable
+variables, unsafe setcookie, switch-on-request, Host-header trust, ORDER BY
+injection). Complements sink_census.py so coverage spans patterns, not just
+sinks. Indexes hits into XERJ `wppatterns`."""
+import glob, json, os, re, sys, urllib.request
+from tree_sitter import Language, Parser
+import tree_sitter_php as tsphp
+
+WP = sys.argv[1]; X = "http://127.0.0.1:9200"
+parser = Parser(Language(tsphp.language_php()))
+def txt(n): return n.text.decode("utf8", "replace")
+
+SECRET_RE = re.compile(r"(pass|pwd|hash|hmac|mac|sig|sign|token|nonce|secret|key|digest|auth)", re.I)
+REQ_RE = re.compile(r"\$_(GET|POST|REQUEST|COOKIE)\b")
+hits = []
+def add(pid, cls, f, line, snippet):
+ hits.append({"pattern": pid, "class": cls, "file": f, "line": line, "snippet": snippet[:160].replace("\n", " ")})
+
+def scan(path, rel):
+ src = open(path, "rb").read()
+ root = parser.parse(src).root_node
+ def w(n):
+ t = n.type
+ if t == "binary_expression":
+ op = n.child_by_field_name("operator")
+ ops = txt(op) if op is not None else ""
+ if ops in ("==", "!=", "<>"):
+ s = txt(n)
+ if SECRET_RE.search(s):
+ add("timing-compare", "crypto-logic", rel, n.start_point[0]+1, s)
+ else:
+ add("loose-eq", "type-juggling", rel, n.start_point[0]+1, s)
+ elif t == "function_call_expression":
+ fn = n.child_by_field_name("function"); name = txt(fn) if fn is not None else ""
+ base = name.split("\\")[-1]
+ args = n.child_by_field_name("arguments")
+ argn = [a for a in args.children if a.type == "argument"] if args else []
+ if base in ("in_array", "array_search"):
+ strict = len(argn) >= 3 and txt(argn[-1]).strip().lower() in ("true", "1")
+ if not strict:
+ add("in-array-loose", "type-juggling", rel, n.start_point[0]+1, txt(n))
+ elif base in ("strcmp", "strcasecmp", "strncmp", "strncasecmp"):
+ if any(REQ_RE.search(txt(a)) for a in argn):
+ add("strcmp-array", "type-juggling", rel, n.start_point[0]+1, txt(n))
+ elif base in ("extract", "import_request_variables") or (base == "parse_str" and len(argn) < 2):
+ add("mass-assignment", "input-shape", rel, n.start_point[0]+1, txt(n))
+ elif base in ("setcookie", "setrawcookie"):
+ s = txt(n).lower()
+ if "httponly" not in s or "secure" not in s or "samesite" not in s:
+ add("cookie-flags", "auth-session", rel, n.start_point[0]+1, txt(n)[:120])
+ elif t == "error_suppression_expression":
+ add("error-suppression", "footgun", rel, n.start_point[0]+1, txt(n)[:120])
+ elif t == "dynamic_variable_name" or (t == "variable_name" and n.child_count and n.children[0].type == "variable_name"):
+ add("var-variable", "input-shape", rel, n.start_point[0]+1, txt(n))
+ elif t == "switch_statement":
+ cond = n.child_by_field_name("condition")
+ if cond is not None and REQ_RE.search(txt(cond)):
+ add("switch-loose", "type-juggling", rel, n.start_point[0]+1, txt(cond))
+ for c in n.children: w(c)
+ w(root)
+ # regex-only patterns over raw source
+ for m in re.finditer(r"\$_SERVER\[\s*['\"]HTTP_(HOST|X_FORWARDED_[A-Z]+)['\"]", src.decode("utf8", "replace")):
+ pass # counted below by grep for speed
+ for i, ln in enumerate(src.decode("utf8", "replace").splitlines(), 1):
+ if re.search(r"ORDER\s+BY[^'\"]*\$", ln, re.I) or re.search(r"\bLIMIT\b[^'\"]*\$_", ln, re.I):
+ add("order-by-inj", "sql-semantic", rel, i, ln.strip())
+ if re.search(r"\$_SERVER\[\s*['\"]HTTP_(HOST|X_FORWARDED_)", ln):
+ add("host-header", "trust-boundary", rel, i, ln.strip())
+
+for p in glob.glob(f"{WP}/**/*.php", recursive=True):
+ scan(p, os.path.relpath(p, WP))
+
+from collections import Counter
+c = Counter(h["pattern"] for h in hits)
+print(f"pattern census: {len(hits)} hits across {len(c)} detectable patterns")
+for pid, n in c.most_common():
+ print(f" {pid:20} {n}")
+
+def post(path, body, ct="application/json"):
+ r = urllib.request.Request(f"{X}/{path}", data=body.encode(), headers={"Content-Type": ct}, method="POST")
+ return json.loads(urllib.request.urlopen(r).read())
+try: urllib.request.urlopen(urllib.request.Request(f"{X}/wppatterns", method="DELETE")).read()
+except Exception: pass
+urllib.request.urlopen(urllib.request.Request(f"{X}/wppatterns", method="PUT",
+ headers={"Content-Type": "application/json"},
+ data=json.dumps({"mappings": {"properties": {"pattern": {"type": "keyword"}, "class": {"type": "keyword"},
+ "file": {"type": "keyword"}, "line": {"type": "integer"}, "snippet": {"type": "text"}}}}).encode())).read()
+lines = []
+for h in hits:
+ lines.append(json.dumps({"index": {}})); lines.append(json.dumps(h))
+resp = post("wppatterns/_bulk", "\n".join(lines) + "\n", "application/x-ndjson")
+print(f"indexed {len(hits)} pattern hits into XERJ `wppatterns` (errors={resp.get('errors')})")
diff --git a/docs/case-studies/wordpress-security-audit/sink-census/php_dangerous_patterns.json b/docs/case-studies/wordpress-security-audit/sink-census/php_dangerous_patterns.json
new file mode 100644
index 000000000..7608538ad
--- /dev/null
+++ b/docs/case-studies/wordpress-security-audit/sink-census/php_dangerous_patterns.json
@@ -0,0 +1,129 @@
+{
+ "meta": {
+ "title": "PHP dangerous PATTERNS (non-function vulnerability classes)",
+ "purpose": "Language-level, input-shape, and semantic vulnerabilities that are NOT a single dangerous function call — the half a sink catalog misses. Each pattern says HOW to detect it (ast=node pattern, regex, query=XERJ, manual=reasoning) so the audit can claim coverage of patterns too.",
+ "detect_kinds": {"ast":"tree-sitter node pattern", "regex":"exact source regex", "query":"XERJ index query over facts", "manual":"needs agent reasoning / schema / runtime"}
+ },
+ "patterns": [
+ {"id":"loose-eq","class":"type-juggling","title":"Loose == / != comparison",
+ "attack":"'0e123'==<'0e456' (magic hash), '0'==false, null==0, '1abc'==1, 'abc'==0 (pre-PHP8). Auth bypass when comparing secrets/hashes/tokens with == instead of ===.",
+ "detect":"ast: binary_expression operator in {==,!=,<>}. Flag when either side is a hash()/md5()/sha1() call, a token/password/hmac variable, or a request value.",
+ "safe":"=== / !== ; hash_equals() for secrets; password_verify() for passwords."},
+ {"id":"switch-loose","class":"type-juggling","title":"switch() uses loose comparison",
+ "attack":"switch($_GET['role']){case 0: admin...} — '0abc' or true loosely matches case 0.",
+ "detect":"ast: switch_statement whose condition is a request value or unhashed string.",
+ "safe":"match(true){...} (strict) or cast+validate the switch value first."},
+ {"id":"magic-hash","class":"type-juggling","title":"Magic-hash comparison (0e...)",
+ "attack":"md5('240610708')=='0e462097431906509019562988736854'; two 0e-prefixed hashes are equal under ==. Password/token bypass.",
+ "detect":"ast+manual: == between two hash outputs, or hash compared to a user value with ==.",
+ "safe":"hash_equals(); never == on hashes."},
+ {"id":"strcmp-array","class":"type-juggling","title":"strcmp/strcasecmp/strncmp with array arg returns NULL",
+ "attack":"?pw[]=x makes $_GET['pw'] an array; strcmp(array,$secret) returns NULL (+warning); if(strcmp(...)==0) => NULL==0 => TRUE => bypass.",
+ "detect":"ast+query: strcmp-family call where an argument traces to a request value with no is_string()/is_scalar() guard.",
+ "safe":"validate is_string() first; use hash_equals; check ===0 not ==0."},
+ {"id":"in-array-loose","class":"type-juggling","title":"in_array/array_search without strict=true",
+ "attack":"in_array('1abc',[1,2,3]) is TRUE loosely; in_array(0,['a','b']) TRUE pre-PHP8. Allow-list bypass.",
+ "detect":"ast: in_array/array_search call with <3 args (strict omitted) or 3rd arg falsey.",
+ "safe":"in_array($x,$arr,true)."},
+ {"id":"array-injection","class":"input-shape","title":"Array injection via param[]=",
+ "attack":"?login[]=a or login[]=a in POST makes $_POST['login'] an ARRAY. Breaks string-typed sinks: preg_match(returns false), strcmp/hash(NULL), sql (Array->'Array'), and bypasses is_string()-less checks. Also DoS/logic.",
+ "detect":"query+manual: request params used by string functions/SQL/regex without a preceding is_string()/is_scalar()/(string) cast or (array) normalisation.",
+ "safe":"cast/validate every request param to the expected type; reject arrays where scalars expected."},
+ {"id":"sql-truncation","class":"sql-semantic","title":"SQL column truncation (silent, non-STRICT mode)",
+ "attack":"Register user 'admin<55 spaces>x'; MySQL (non-strict) truncates to column length -> stored as 'admin' -> duplicate/overwrite admin account.",
+ "detect":"manual+schema: INSERT/UPDATE of a user-controlled string into a VARCHAR(N) unique column without an explicit length check; requires column lengths.",
+ "safe":"validate max length before insert; STRICT_ALL_TABLES; unique+trim checks."},
+ {"id":"charset-sqli","class":"sql-semantic","title":"Multibyte charset SQLi (addslashes/GBK bypass)",
+ "attack":"In GBK/Big5, 0xbf27 + addslashes -> 0xbf5c27 which is a valid multibyte char + a free quote -> breaks out. Defeats addslashes/manual escaping.",
+ "detect":"manual: manual escaping (addslashes/mysql_real_escape_string) with a connection charset set to a multibyte set instead of set_charset('utf8mb4').",
+ "safe":"parameterized queries; mysqli::set_charset('utf8mb4')."},
+ {"id":"order-by-inj","class":"sql-semantic","title":"ORDER BY / LIMIT / identifier injection",
+ "attack":"ORDER BY $_GET['sort'] — identifiers can't be bound with placeholders; direct concat = injection.",
+ "detect":"regex+query: ORDER BY/GROUP BY/LIMIT/table/column built from a request value (prepare can't bind these).",
+ "safe":"allow-list of column names; map input->fixed identifier."},
+ {"id":"second-order","class":"injection-flow","title":"Second-order injection (stored then used raw)",
+ "attack":"Value stored safely, later read from DB and concatenated into SQL/HTML/cmd without re-escaping. Taint 'launders' through storage.",
+ "detect":"manual: a value read from DB/option/meta reaching a sink; the taint graph must treat storage reads as tainted for stored-then-used flows.",
+ "safe":"escape at every sink, not just at input; treat DB reads as untrusted."},
+ {"id":"mass-assignment","class":"input-shape","title":"Mass assignment / register_globals emulation",
+ "attack":"extract($_REQUEST) or foreach($_POST as $k=>$v){$$k=$v;} or $obj->fill($_POST) overwrites vars/columns (e.g. is_admin).",
+ "detect":"ast: extract() / parse_str(1-arg) / variable_variable assignment ($$k) fed by a request array; object hydration from a raw request array.",
+ "safe":"explicit allow-list of fields; never bulk-assign request data."},
+ {"id":"var-variable","class":"input-shape","title":"Variable variables $$x",
+ "attack":"$$key where key is request-controlled -> arbitrary variable overwrite / info leak.",
+ "detect":"ast: variable_name whose name is itself a variable (dynamic_variable_name) fed by request.",
+ "safe":"array lookups with an allow-list, not $$."},
+ {"id":"null-byte","class":"input-shape","title":"Null-byte / poison-byte truncation",
+ "attack":"?file=secret.php%00.jpg truncates at NUL in include/file ops (pre-5.3.4); also %00 in strings splitting validators.",
+ "detect":"manual+regex: file/path/validator using a request value without an explicit NUL/`\\0` rejection; older PHP targets.",
+ "safe":"reject \\0; PHP>=5.3.4; realpath+allow-list."},
+ {"id":"path-traversal","class":"input-shape","title":"Path traversal encodings",
+ "attack":"../, ..%2f, %2e%2e%2f, ....//, absolute-path override, unicode dot. Escapes an intended base dir.",
+ "detect":"query+manual: file op / include with a request-derived path lacking realpath()-under-base or basename()+allow-list.",
+ "safe":"realpath() then verify str_starts_with(base); basename+allow-list."},
+ {"id":"phar-deser","class":"deserialization","title":"phar:// deserialization",
+ "attack":"phar://attacker.jpg triggers unserialize of the Phar metadata via ANY file op (file_exists/getimagesize/fopen) on an attacker-controlled path -> POP chain.",
+ "detect":"query+manual: any file op whose path can start with a user-controlled wrapper/scheme; combined with a gadget class present.",
+ "safe":"validate/deny wrappers; Phar::interceptFileFuncs; check scheme."},
+ {"id":"toctou","class":"race","title":"TOCTOU file race (check-then-use)",
+ "attack":"is_writable($f)/file_exists($f) then fopen/unlink($f) — attacker swaps the path (symlink) between check and use.",
+ "detect":"ast+manual: a file predicate on a path followed by an operation on the same path in a privileged context.",
+ "safe":"operate on fds (O_NOFOLLOW), atomic ops, avoid predictable temp paths."},
+ {"id":"timing-compare","class":"crypto-logic","title":"Non-constant-time secret comparison",
+ "attack":"if($mac == $expected) leaks byte-by-byte timing -> MAC/token forgery; also juggling.",
+ "detect":"ast: == / != / strcmp on a variable named mac/sig/hmac/token/hash/nonce.",
+ "safe":"hash_equals($known,$user)."},
+ {"id":"is-numeric-bypass","class":"type-confusion","title":"is_numeric / intval / filter_var bypass",
+ "attack":"is_numeric('0x1A'|'1e3'|' 12'|'+9') can be TRUE; (int)'123abc'=123; filter_var URL/EMAIL accepts javascript:, unusual hosts; is_numeric hex opens ID confusion.",
+ "detect":"ast+manual: is_numeric/ctype_digit/intval/(int)/filter_var used as the ONLY validation on a security-relevant value.",
+ "safe":"ctype_digit for digit-strings; FILTER + explicit flags; compare after cast+re-render."},
+ {"id":"loose-empty-isset","class":"logic","title":"empty()/isset() logic pitfalls",
+ "attack":"empty('0') and empty(0) are TRUE -> a legit '0' input treated as missing; isset() true for null-coalesced; == in guards.",
+ "detect":"manual: empty()/! on a value where '0'/0/'' are valid, in an auth/authorization/branch decision.",
+ "safe":"=== '' / array_key_exists / isset with explicit checks."},
+ {"id":"regex-anchor-bypass","class":"regex","title":"Regex anchor / multiline / dot bypass",
+ "attack":"preg_match('/^allowed$/',$x) — $ matches before a trailing \\n; with /m, ^/$ per line; . doesn't match \\n so payload on a second line bypasses. Also \\A\\z vs ^$.",
+ "detect":"regex+manual: a validation preg_match using ^...$ (not \\A...\\z) on a request value; check for /m and missing /s or /D.",
+ "safe":"\\A...\\z anchors; /D; reject newlines."},
+ {"id":"pcre-backtrack","class":"regex","title":"PCRE returns false on backtrack-limit (not 0)",
+ "attack":"On catastrophic backtracking preg_match returns FALSE, not 0; if(preg_match($bad,$x)) treats false as no-match, but code checking ==1 or !==false differs -> validator bypass + ReDoS.",
+ "detect":"ast+manual: preg_match result used in a boolean/auth branch without ===1 / preg_last_error() check; user-influenced pattern or subject length.",
+ "safe":"check ===1; bound input length; pcre.backtrack_limit."},
+ {"id":"session-fixation","class":"auth-session","title":"Session fixation (no regenerate on auth)",
+ "attack":"Attacker sets victim's session id pre-login; app doesn't session_regenerate_id(true) after auth -> session hijack.",
+ "detect":"query+manual: a login/privilege-elevation path with no session_regenerate_id(true) after establishing identity.",
+ "safe":"session_regenerate_id(true) on every privilege change."},
+ {"id":"cookie-flags","class":"auth-session","title":"Missing cookie security flags",
+ "attack":"setcookie without HttpOnly/Secure/SameSite -> XSS theft / CSRF / MITM.",
+ "detect":"ast: setcookie/setrawcookie/session_set_cookie_params with options lacking httponly|secure|samesite.",
+ "safe":"set HttpOnly+Secure+SameSite=Lax/Strict."},
+ {"id":"csrf-absence","class":"auth-logic","title":"State change without CSRF/nonce",
+ "attack":"A state-changing handler reachable without a verified nonce/token -> CSRF.",
+ "detect":"query: entry point performing a state change with NO nonce/token verification on the path (absence property — see the authz graph).",
+ "safe":"verify a per-user, per-action nonce/CSRF token on every state change."},
+ {"id":"xss-context","class":"xss","title":"Wrong-context / incomplete output escaping",
+ "attack":"htmlspecialchars without ENT_QUOTES inside an attribute; esc_html on a value placed in JS/URL/CSS context; double-encoding; json in <script> without JSON_HEX_TAG.",
+ "detect":"manual: an escaper whose context (HTML text/attr/JS/URL/CSS) does not match the output position.",
+ "safe":"context-correct escaper (attr vs html vs js vs url); ENT_QUOTES; JSON_HEX_* in <script>."},
+ {"id":"open-redirect","class":"redirect","title":"Open redirect",
+ "attack":"header('Location: '.$_GET['next']) or redirect($url) to //evil.com, \\evil, javascript:.",
+ "detect":"ast+query: header('Location'..)/redirect with a request-derived target lacking an allow-list/same-host check.",
+ "safe":"allow-list hosts; wp_safe_redirect; strip scheme/host."},
+ {"id":"host-header","class":"trust-boundary","title":"Host / X-Forwarded trust",
+ "attack":"Using $_SERVER['HTTP_HOST'] / X-Forwarded-For / X-Forwarded-Host for links, password-reset URLs, or IP allow-lists -> poisoning/spoof.",
+ "detect":"regex: $_SERVER['HTTP_HOST'|'HTTP_X_FORWARDED_*'] used in a URL, email, or access decision.",
+ "safe":"fixed site URL config; trust only vetted proxies."},
+ {"id":"error-suppression","class":"footgun","title":"@ error suppression hiding failures",
+ "attack":"@unserialize / @file_get_contents / @$_GET hides errors that mask a security-relevant failure or type issue.",
+ "detect":"ast: error_suppression_expression (@) on a security-relevant call.",
+ "safe":"handle errors explicitly."},
+ {"id":"upload-exec","class":"file-upload","title":"Unrestricted file upload -> exec",
+ "attack":"Attacker uploads shell.php / .phtml / double-ext shell.php.jpg / MIME-spoofed / .htaccess; served from an executable dir.",
+ "detect":"manual+query: move_uploaded_file/write into a web-served dir with extension/MIME derived from the upload and no allow-list / non-exec storage.",
+ "safe":"random name; extension+content allow-list; store outside web root / non-exec."},
+ {"id":"user-enum","class":"info-leak","title":"User enumeration (distinct response/timing)",
+ "attack":"Login/reset returns different message or timing for valid vs invalid users -> account enumeration.",
+ "detect":"manual: auth/reset flows with user-existence-dependent branches in message or timing.",
+ "safe":"uniform responses and timing."}
+ ]
+}
diff --git a/docs/case-studies/wordpress-security-audit/skill/SKILL.md b/docs/case-studies/wordpress-security-audit/skill/SKILL.md
index 28a7367d5..bd57af56f 100644
--- a/docs/case-studies/wordpress-security-audit/skill/SKILL.md
+++ b/docs/case-studies/wordpress-security-audit/skill/SKILL.md
@@ -32,6 +32,17 @@ For another framework/language, extend this map — it is data, not code.
### 2. Census every call site (AST)
`python3 sink_census.py <src>` parses every file with tree-sitter and records
+
+### 2b. Census the dangerous PATTERNS (the class a sink list misses)
+`python3 pattern_census.py <src>` AST-detects the non-function vulns — loose `==`
+/ magic-hash, non-strict `in_array`, `strcmp`-with-array (`?login[]=`), `@`
+suppression, variable-variables, unsafe `setcookie`, `switch`-on-request,
+Host-header trust, ORDER-BY injection — into `wppatterns`. Semantic classes a
+census can't decide (SQL truncation, charset SQLi, second-order, phar, TOCTOU,
+upload-exec, is_numeric bypass, regex-anchor, session-fixation, wrong-context
+XSS) are catalogued in `php_dangerous_patterns.json` with detection guidance and
+swept by reasoning. FULL REFERENCE: `PHP-SECURITY-GUIDE.md` — every function AND
+pattern mapped to attack + detection + safe recipe.
**every** call site of a catalogued function (calls, methods, constructs like
`echo`/`include`/backtick, `new ReflectionFunction`). tree-sitter captures real
calls regardless of formatting/namespacing — grep cannot.