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): per-method magic-method scan — corrects gadget hunt (1 real, defused)

Xerj Squad A1a31b39a3e1e
diff --git a/docs/case-studies/wordpress-security-audit/GADGET-CHAINS.md b/docs/case-studies/wordpress-security-audit/GADGET-CHAINS.md
index 4a29a646f..47ff156c0 100644
--- a/docs/case-studies/wordpress-security-audit/GADGET-CHAINS.md
+++ b/docs/case-studies/wordpress-security-audit/GADGET-CHAINS.md
@@ -66,3 +66,38 @@ python3 gadget_hunt.py # magic methods -> dangerous call, over the XERJ grap
```
Generalize by extending `MAGIC`/`DANGER`; point `wpaudit` at a plugin/vendored lib
to find the gadgets that core doesn't have.
+
+
+## Correction (per-method scan supersedes the first pass)
+
+The result above used `byname` (first definition per name) — a **name-collision
+bug**: only 1 of 12 `__destruct` methods was analyzed, so it under-reported.
+`magic_unsafe.py` scans **each** magic method's own body against the full 287-fn
+catalog and is the authority. Corrected finding:
+
+- **44 magic methods contain a dangerous call inside.** The one that matters is
+ **`WP_HTML_Token::__destruct` → `call_user_func($this->on_destroy, $this->bookmark_name)`**
+ (both properties settable) — a **real POP-gadget shape** (unserialize a token
+ with `on_destroy='system'`, `bookmark_name='id'` → RCE on destruct).
+- **It is defused:** the class adds `__wakeup(){ throw new LogicException('… should
+ never be unserialized'); }` (WP 6.4.2) — `unserialize` can't build the object, so
+ the `__destruct` is unreachable via object injection. This is WP's deliberate
+ hardening of a real gadget, not the absence of one.
+- Everything else is benign/not-a-gadget: IRI/Iri `__set`/`__unset` `call_user_func`
+ is internal `[$this,'set_'.$name]` dispatch (bounded, and `__set` isn't
+ unserialize-triggered); `imagick`/`PHPMailer` `__destruct` do cleanup
+ (`->clear()`, `smtpClose()`), no sink; `get_headers`/`debug_backtrace` are
+ method-name collisions.
+
+**All dangerous calls found INSIDE magic methods, by class:**
+
+| class | calls (count) | assessment |
+|---|---|---|
+| RCE-code-callable | `call_user_func` ×5, `set_error_handler` ×1, `array_filter` ×1 | 1 real gadget shape (HTML_Token, **defused**); rest internal dispatch |
+| auth-bypass-type-juggle | `in_array` ×25 | non-strict `in_array` in `__get/__isset/__set/__unset` — property-name allow-list checks, low severity |
+| weak-crypto | `md5` ×11 | SimplePie `__toString` object-identity hashing — benign (not passwords) |
+| info-disclosure | `debug_backtrace` ×1 | SimplePie `__call` debug — FP |
+| SSRF | `get_headers` ×1 | method-name collision — FP |
+
+**Net:** core has **one** genuine deserialization gadget shape and it is
+explicitly guarded; no usable POP chain via core magic methods.
diff --git a/docs/case-studies/wordpress-security-audit/sink-census/magic_unsafe.py b/docs/case-studies/wordpress-security-audit/sink-census/magic_unsafe.py
new file mode 100644
index 000000000..6405a4e80
--- /dev/null
+++ b/docs/case-studies/wordpress-security-audit/sink-census/magic_unsafe.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python3
+"""For every magic method, list the dangerous calls INSIDE its body — scanned
+against the full 287-function dangerous catalog (+ constructs). This is the
+precise 'magic methods with unsafe calls inside' answer, each call tagged with
+its vuln class. Uses the wpaudit `code` field via XERJ."""
+import json, os, re, urllib.request
+X="http://127.0.0.1:9200"; here=os.path.dirname(__file__)
+MAGIC=["__wakeup","__destruct","__toString","__call","__callStatic","__get","__set",
+ "__invoke","__unserialize","__sleep","__serialize","__set_state","__clone","__isset","__unset"]
+AUTO={"__wakeup","__unserialize","__destruct","__toString"}
+# fn -> vuln class, from the full catalog
+cat=json.load(open(os.path.join(here,"php_dangerous_functions.json")))["categories"]
+FN2CLASS={f["fn"]: c.get("class",cn) for cn,c in cat.items() for f in c["fns"]}
+CONSTRUCTS={"eval":"RCE-code","include":"LFI-RFI","include_once":"LFI-RFI","require":"LFI-RFI",
+ "require_once":"LFI-RFI","echo":"XSS","print":"XSS","exit":"XSS-or-info","die":"XSS-or-info"}
+
+def q(body):
+ r=urllib.request.Request(f"{X}/wpaudit/_search",data=json.dumps(body).encode(),headers={"Content-Type":"application/json"})
+ return [h["_source"] for h in json.loads(urllib.request.urlopen(r).read())["hits"]["hits"]]
+
+magic=q({"query":{"terms":{"func":MAGIC}},"size":500,"_source":["func","file","line","code"]})
+
+def dangerous_in(code):
+ found=[]
+ for fn,cls in FN2CLASS.items():
+ # call or ->method( / ::method(
+ if re.search(rf"(?<![\w$])(->|::|\b){re.escape(fn)}\s*\(",code):
+ found.append((fn,cls))
+ for kw,cls in CONSTRUCTS.items():
+ if re.search(rf"(?<![\w$>]){kw}\b",code):
+ # avoid matching in strings crudely: require a following space/paren/quote/$
+ if re.search(rf"(?<![\w$>]){kw}[\s(\"'$]",code): found.append((kw,cls))
+ # de-dup, drop the magic-method's own name noise
+ return sorted(set(found))
+
+rows=[]
+for m in magic:
+ d=dangerous_in(m.get("code",""))
+ if d: rows.append((m,d))
+rows.sort(key=lambda r:(r[0]["func"] not in AUTO, r[0]["func"]))
+
+print(f"magic methods scanned: {len(magic)} with >=1 dangerous call inside: {len(rows)}\n")
+print("MAGIC METHODS WITH UNSAFE CALLS INSIDE (■ = auto-triggered on unserialize/free/print):")
+for m,d in rows:
+ mark="■" if m["func"] in AUTO else " "
+ calls=", ".join(f"{fn}[{cls}]" for fn,cls in d)
+ print(f" {mark} {m['func']:14} {m['file'].split('/')[-1]}:{m['line']}")
+ print(f" {calls}")
+
+# aggregate: the full list of dangerous calls found inside magic methods, by class
+from collections import Counter, defaultdict
+bycls=defaultdict(Counter)
+for _,d in rows:
+ for fn,cls in d: bycls[cls][fn]+=1
+print("\n=== ALL dangerous calls found inside magic methods, grouped by class ===")
+for cls in sorted(bycls, key=lambda c:-sum(bycls[c].values())):
+ print(f" {cls}: {dict(bycls[cls])}")
+json.dump([{"magic":m["func"],"file":m["file"],"line":m["line"],"auto":m["func"] in AUTO,
+ "dangerous":[{"fn":fn,"class":cls} for fn,cls in d]} for m,d in rows],
+ open(os.path.join(here,"magic_unsafe.json"),"w"),indent=1)
+print("\nwrote magic_unsafe.json")