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): POP-gadget (deserialization) chain hunt — core has 0 live gadgets

Xerj Squad Ad1db8ceb7bab
diff --git a/docs/case-studies/wordpress-security-audit/FINDINGS.md b/docs/case-studies/wordpress-security-audit/FINDINGS.md
index b78c982e6..3b60970ec 100644
--- a/docs/case-studies/wordpress-security-audit/FINDINGS.md
+++ b/docs/case-studies/wordpress-security-audit/FINDINGS.md
@@ -123,6 +123,13 @@ type first but the content is still parsed. **Fix (deploy):** patched ImageMagic
explicitly guarded — `if ($parent->ID !== $revision->post_parent) return 404`.
- **`map_meta_cap`** fails closed on missing object / missing arg.
+### Deserialization POP-gadget chains — none in core
+131 magic methods; **0** auto-triggered ones (`__wakeup`/`__unserialize`/
+`__destruct`/`__toString`) reach a dangerous sink. The 2 that reach any dangerous
+call are `__callStatic` (deprecation shim → WP hook dispatcher) — false positives,
+and not unserialize-triggered. So even arbitrary object injection has **no core
+gadget chain** to escalate. See `GADGET-CHAINS.md`.
+
### SQL de-escape (double `prepare`) — safe
`WP_List_Table::months_dropdown` re-feeds a `prepare()`'d value (from
`$_GET['post_status']`) into another `prepare()`. Safe **only** because
diff --git a/docs/case-studies/wordpress-security-audit/GADGET-CHAINS.md b/docs/case-studies/wordpress-security-audit/GADGET-CHAINS.md
new file mode 100644
index 000000000..4a29a646f
--- /dev/null
+++ b/docs/case-studies/wordpress-security-audit/GADGET-CHAINS.md
@@ -0,0 +1,68 @@
+# POP-gadget (deserialization) chain hunt
+
+A dangerous `unserialize` is only exploitable if a **gadget chain** exists: a
+class whose **magic method** — auto-invoked by unserialize (`__wakeup`,
+`__unserialize`), by object destruction (`__destruct`), or by later use
+(`__toString`, `__call`) — reaches a sink. This hunt enumerates every magic method
+and traces it, interprocedurally, to any dangerous call.
+
+## Method (XERJ data first)
+
+`gadget_hunt.py` scrolls the `wpaudit` call graph, selects the 15 magic-method
+names, and DFS-walks each (unambiguous call edges) to a **payoff**: a reached
+function whose `sinks` are non-empty or whose `calls` include a high-impact
+function (`exec`/`eval`/`unserialize`/`file_put_contents`/`unlink`/
+`call_user_func`/`extractTo`/…). Flags the *auto-triggered* magic methods
+separately — those are the live deserialization gadgets.
+
+## Result on WordPress core
+
+| | |
+|---|--:|
+| magic methods in core | 131 |
+| **auto-triggered (`__wakeup`/`__unserialize`/`__destruct`/`__toString`) reaching a sink** | **0** |
+| any magic method reaching a dangerous call | 2 |
+
+The 2 are `__callStatic` (`pluggable-deprecated.php`, `AbstractEnum.php`), and both
+are **false positives** on reading:
+```php
+public static function __callStatic($name, $arguments) {
+ _deprecated_function(__CLASS__.'::'.$name, '3.5.0', '…'); // just a deprecation notice
+}
+```
+The `call_user_func_array` at the end of the traced path
+(`__callStatic → _deprecated_function → wp_trigger_error → do_action → _wp_call_all_hook → call_user_func_array`)
+is WordPress's **generic hook dispatcher** firing registered callbacks — not
+attacker-controlled from the magic method. And `__callStatic` is invoked by an
+undefined *static* call, **not** by `unserialize`.
+
+**Impact — a clean positive:** WordPress **core has no deserialization POP-gadget
+chain.** Even given arbitrary object injection, no core magic method escalates it
+to RCE/file-write/SSRF. The `__wakeup` methods that exist (e.g. SimplePie's
+`FilteredIterator`) are inert or *defensive* (they throw to block deserialization).
+Live gadget risk in the WP ecosystem comes from **vendored libraries and plugins**,
+not core magic methods — point the same hunt at those.
+
+## XERJ vs grep+context (measured)
+
+The question — *"which magic methods reach a dangerous sink?"* — is inherently
+**interprocedural**, so grep alone can't answer it; you must read the bodies and
+hand-trace callees across files.
+
+| approach | what it costs | tokens |
+|---|---|--:|
+| grep + read | read all **83 files** that define a magic method **and trace callees across files** | **~562,000** (> a context window → chunk → lose cross-file traces) |
+| **XERJ** | query the 15 magic-method names + traverse the pre-built call graph → the answer | **~144** (2 candidates) |
+
+**≈3,900× to the answer.** Quality is *higher*, not just cheaper: XERJ followed
+6-hop cross-file chains reliably; a human/grep pass over 562k tokens would chunk
+the code and is exactly where an interprocedural gadget chain slips through. The
+call graph is built once and reused for every such query (gadgets, taint,
+reachability).
+
+## Reproduce
+```bash
+python3 gadget_hunt.py # magic methods -> dangerous call, over the XERJ graph
+```
+Generalize by extending `MAGIC`/`DANGER`; point `wpaudit` at a plugin/vendored lib
+to find the gadgets that core doesn't have.
diff --git a/docs/case-studies/wordpress-security-audit/README.md b/docs/case-studies/wordpress-security-audit/README.md
index 7a40b2710..d5cfd2f87 100644
--- a/docs/case-studies/wordpress-security-audit/README.md
+++ b/docs/case-studies/wordpress-security-audit/README.md
@@ -101,6 +101,9 @@ read; scale and durability come from XERJ.
- [`VERIFY-AND-TRACE.md`](VERIFY-AND-TRACE.md) — **verify the data is live in
XERJ and trace any sink end-to-end via the API** (sink → enclosing fn → sources
→ reverse callers → authz), with `sink-census/trace_sink.py`.
+- [`GADGET-CHAINS.md`](GADGET-CHAINS.md) — **POP-gadget (deserialization) hunt**:
+ every magic method traced to a sink; core has **0 auto-triggered gadgets**
+ (`sink-census/gadget_hunt.py`); ~3,900× cheaper than grep+read.
- [`sink-census/TAINT-ANALYSIS.md`](sink-census/TAINT-ANALYSIS.md) — **interprocedural
taint over the XERJ call graph** (source → sink, no sanitizer on path): 70
candidate flows on WP core, ranked, with honest real-vs-FP verification
diff --git a/docs/case-studies/wordpress-security-audit/sink-census/gadget_hunt.py b/docs/case-studies/wordpress-security-audit/sink-census/gadget_hunt.py
new file mode 100644
index 000000000..fe3f709aa
--- /dev/null
+++ b/docs/case-studies/wordpress-security-audit/sink-census/gadget_hunt.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python3
+"""POP-gadget hunt over XERJ data: find magic methods (__wakeup/__destruct/
+__toString/__call/...) that reach a dangerous call — the deserialization
+gadget-chain surface. A class is a usable gadget only if a magic method (which
+unserialize/free/print auto-invokes) leads to a sink.
+
+Interprocedural DFS over the wpaudit call graph (unambiguous edges), payoff =
+a reached function whose wpaudit `sinks` is non-empty OR whose `calls` include a
+high-impact dangerous function.
+"""
+import json, sys, urllib.request
+X="http://127.0.0.1:9200"
+MAGIC={"__wakeup","__destruct","__toString","__call","__callStatic","__get","__set",
+ "__invoke","__unserialize","__sleep","__serialize","__set_state","__clone","__isset","__unset"}
+# auto-triggered on unserialize/free/print/use (the ones that make a gadget "live")
+AUTO={"__wakeup","__unserialize","__destruct","__toString"}
+DANGER={"exec","shell_exec","system","passthru","popen","proc_open","pcntl_exec","eval","assert",
+ "create_function","call_user_func","call_user_func_array","unserialize","file_put_contents",
+ "fwrite","fputs","unlink","rename","copy","move_uploaded_file","extractTo","readImage",
+ "mysqli_query","mysql_query","fopen","file_get_contents","include","require"}
+
+def scroll():
+ docs=[]; r=urllib.request.Request(f"{X}/wpaudit/_search?scroll=2m",
+ data=json.dumps({"size":2000,"query":{"match_all":{}},"_source":["func","file","line","sinks","calls"]}).encode(),
+ headers={"Content-Type":"application/json"})
+ res=json.loads(urllib.request.urlopen(r).read()); sid=res["_scroll_id"]; hits=res["hits"]["hits"]
+ while hits:
+ docs+=[h["_source"] for h in hits]
+ r=urllib.request.Request(f"{X}/_search/scroll",data=json.dumps({"scroll":"2m","scroll_id":sid}).encode(),headers={"Content-Type":"application/json"})
+ res=json.loads(urllib.request.urlopen(r).read()); sid=res["_scroll_id"]; hits=res["hits"]["hits"]
+ return docs
+
+docs=scroll()
+byname={}; name_count={}
+for d in docs:
+ name_count[d["func"]]=name_count.get(d["func"],0)+1
+ byname.setdefault(d["func"],d)
+
+def reaches_danger(start, depth=6):
+ """DFS from a magic method; return (danger_fn, path) if a dangerous call is reached."""
+ stack=[(start["func"],[start["func"]])]; seen=set()
+ while stack:
+ fn,path=stack.pop()
+ if fn in seen or len(path)>depth: continue
+ seen.add(fn); d=byname.get(fn)
+ if not d: continue
+ if fn!=start["func"] and d["sinks"]:
+ return ("sink:"+"/".join(d["sinks"]), path)
+ for c in d.get("calls",[]):
+ if c in DANGER: return (c, path+[c])
+ if c in byname and name_count.get(c,0)==1: stack.append((c,path+[c]))
+ return None
+
+magic=[d for d in docs if d["func"] in MAGIC]
+gadgets=[]
+for m in magic:
+ r=reaches_danger(m)
+ if r:
+ danger,path=r
+ gadgets.append({"magic":m["func"],"file":m["file"],"line":m["line"],
+ "auto": m["func"] in AUTO,"danger":danger,"path":path})
+gadgets.sort(key=lambda g:(not g["auto"], g["magic"]))
+print(f"magic methods: {len(magic)} reaching a dangerous call: {len(gadgets)}")
+print(f" of which AUTO-triggered (__wakeup/__unserialize/__destruct/__toString -> the live gadgets): {sum(1 for g in gadgets if g['auto'])}")
+print("\nGADGET CANDIDATES (magic -> ... -> danger):")
+for g in gadgets:
+ tag="LIVE" if g["auto"] else "call-only"
+ print(f" [{tag}] {g['magic']:14} {g['file'].split('/')[-1]}:{g['line']}")
+ print(f" -> {' -> '.join(g['path'])} ==> {g['danger']}")
+# token measure: facts pulled (func/calls/sinks for the whole graph loaded once)
+import io
+facts_bytes=sum(len(json.dumps({k:d[k] for k in ('func','calls','sinks')})) for d in docs)
+print(f"\nXERJ-facts token cost (whole call graph, loaded once): ~{facts_bytes//4:,} tokens")
+print(f" (but the ANSWER — {len(gadgets)} candidates — is ~{len(json.dumps(gadgets))//4} tokens)")
+json.dump(gadgets, open("gadgets.json","w"))
diff --git a/docs/case-studies/wordpress-security-audit/skill/SKILL.md b/docs/case-studies/wordpress-security-audit/skill/SKILL.md
index 0ba9d7feb..c2e7c6e5d 100644
--- a/docs/case-studies/wordpress-security-audit/skill/SKILL.md
+++ b/docs/case-studies/wordpress-security-audit/skill/SKILL.md
@@ -95,6 +95,12 @@ high-recall REACHABILITY triage, not precise per-argument data-flow — the SQL
flows include WP_Query (safe) and intval-guarded sinks, so read each candidate.
See `TAINT-ANALYSIS.md`.
+### 6c. POP-gadget hunt (`gadget_hunt.py`)
+Trace every magic method (__wakeup/__destruct/__toString/__call/...) through the
+call graph to a dangerous call — the deserialization gadget surface. Flag the
+AUTO-triggered ones (unserialize/free/print) as the live gadgets. WP core: 0.
+See `GADGET-CHAINS.md`.
+
## Honesty rules (these make the result trustworthy)
1. Precision from the graph/facts; full-text only to navigate. FTS over raw code
is noisy for security.