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): gadget inventory (unguarded magic methods) + autoloader test

Xerj Squad Ad89e9f2b32c5
diff --git a/docs/case-studies/wordpress-security-audit/GADGET-INVENTORY.md b/docs/case-studies/wordpress-security-audit/GADGET-INVENTORY.md
new file mode 100644
index 000000000..131c0bed4
--- /dev/null
+++ b/docs/case-studies/wordpress-security-audit/GADGET-INVENTORY.md
@@ -0,0 +1,66 @@
+# Gadget inventory: unguarded dangerous magic methods + the autoloader question
+
+Empirically established (`GADGET-WAKEUP-TEST.md`): a throwing `__wakeup`/`__unserialize`
+suppresses `__destruct`. So the **exposed** deserialization gadgets are classes with
+a dangerous *auto-fire* magic method (`__destruct`/`__toString`) that **lack** such a
+guard. This inventories them — XERJ first, then manually, then tests the autoloader
+bypass idea in real PHP.
+
+## XERJ pass (`gadget_inventory.py`)
+Groups every dangerous magic method by class and checks for a throwing
+`__wakeup`/`__unserialize` in the same class.
+
+| | count |
+|---|--:|
+| classes with a dangerous magic method | 43 |
+| GUARDED (throwing `__wakeup`/`__unserialize`) | 4 |
+| **EXPOSED (auto-fire magic, no guard)** | **12** |
+
+The 12 exposed are **all `__toString`** (not `__destruct`): 11 SimplePie classes
+doing `md5(...)` (object-identity hashing — benign) and one Requests `StreamTrait`
+`set_error_handler` (internal callback). `__toString` only fires when the object is
+**cast to string**, not automatically on unserialize. **No exposed `__destruct`.**
+
+## Manual pass (grep + read) — cross-check
+Read every `__destruct` in the whole tree (core + vendored):
+
+```
+__destruct classes: 12
+DANGEROUS __destruct body: class-wp-html-token.php __wakeup guard: throws
+-> 1 dangerous __destruct, and it is GUARDED
+```
+
+**XERJ and manual agree exactly:** the only dangerous `__destruct` is
+`WP_HTML_Token`, and it is guarded. There is **no unguarded dangerous `__destruct`
+gadget** in core or the bundled libraries.
+
+## The autoloader hypothesis — tested (`gadget_autoload_test.php`, PHP 8.3)
+*"Could you autoload the class so it's destroyed without `__wakeup`?"* — No:
+```
+[autoloader] loading Guarded
+caught: should never be unserialized # __wakeup STILL fired -> __destruct suppressed
+```
+Whether a class is pre-loaded (bootstrap) or brought in on-demand by an autoloader,
+`unserialize` runs its `__wakeup` once it's available. The autoloader only controls
+**availability** — and core has no unguarded dangerous-`__destruct` class to make
+available. So the guard is autoload-proof.
+
+## Honest XERJ-vs-manual comparison (tokens & quality)
+| | XERJ facts | manual grep+read |
+|---|--:|--:|
+| tokens | ~14,700 (all magic methods pulled) | **~649** (12 `__destruct` bodies) |
+| result | 43 grouped, 4 guarded, 12 exposed | 1 dangerous `__destruct`, guarded |
+| agreement | — | **identical on the `__destruct` question** |
+
+**Honest call:** for this *narrow, low-cardinality* question (only 12 `__destruct`
+methods, all short), **grep+read is cheaper** — XERJ's pull is broader than needed.
+XERJ wins when the question is **broad, interprocedural, or reused** (every magic
+method + call-graph reachability + taint over the same index), not for a single
+small lookup. Use the cheaper tool for the question at hand; that's the honest rule.
+
+## Verdict
+Core has **zero unguarded dangerous `__destruct` gadgets**; the one dangerous
+`__destruct` (`WP_HTML_Token`) is guarded by a throwing `__wakeup` that is
+autoload-proof and (verified) suppresses `__destruct`. The `__toString` "exposed"
+set is benign (`md5`) or internal. No usable core POP gadget exists — independent of
+any delivery vector.
diff --git a/docs/case-studies/wordpress-security-audit/sink-census/gadget_autoload_test.php b/docs/case-studies/wordpress-security-audit/sink-census/gadget_autoload_test.php
new file mode 100644
index 000000000..5c52666a3
--- /dev/null
+++ b/docs/case-studies/wordpress-security-audit/sink-census/gadget_autoload_test.php
@@ -0,0 +1,17 @@
+<?php
+function GADGET($a){ echo " >>> GADGET EXECUTED (autoloaded) arg='$a' <<<\n"; }
+spl_autoload_register(function($c){
+ if ($c==='Guarded') { echo " [autoloader] loading Guarded\n"; require __DIR__.'/Guarded.php'; }
+ if ($c==='Unguarded') { echo " [autoloader] loading Unguarded\n"; require __DIR__.'/Unguarded.php'; }
+});
+echo "PHP ".PHP_VERSION." (classes NOT pre-loaded; only the autoloader can bring them in)\n";
+echo "class_exists before? Guarded=".var_export(class_exists('Guarded',false),true)."\n";
+
+echo "\n[1] unserialize Guarded (autoloader loads it) — does __wakeup still fire+block?\n";
+$p1='O:7:"Guarded":2:{s:13:"bookmark_name";s:5:"PWNED";s:10:"on_destroy";s:6:"GADGET";}';
+try{ unserialize($p1);}catch(\Throwable $e){ echo " caught: ".$e->getMessage()."\n"; } gc_collect_cycles();
+
+echo "\n[2] CONTROL: unserialize Unguarded (autoloaded, no __wakeup) — gadget SHOULD fire:\n";
+$p2='O:9:"Unguarded":2:{s:13:"bookmark_name";s:5:"PWNED2";s:10:"on_destroy";s:6:"GADGET";}';
+try{ unserialize($p2);}catch(\Throwable $e){ echo " caught: ".$e->getMessage()."\n"; } gc_collect_cycles();
+echo "\n=== END ===\n";
diff --git a/docs/case-studies/wordpress-security-audit/sink-census/gadget_inventory.py b/docs/case-studies/wordpress-security-audit/sink-census/gadget_inventory.py
new file mode 100644
index 000000000..9c6b10e85
--- /dev/null
+++ b/docs/case-studies/wordpress-security-audit/sink-census/gadget_inventory.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python3
+"""Gadget inventory over XERJ data: classes with a dangerous magic method that
+LACK a throwing __wakeup/__unserialize guard — the ones whose __destruct fires
+without a guard blocking it. Empirically proven (GADGET-WAKEUP-TEST.md): a
+throwing __wakeup suppresses __destruct; so the EXPOSED gadgets are the unguarded
+ones. Also flags autoload/bootstrap loadability (can unserialize instantiate it?).
+"""
+import json, os, re, urllib.request
+X="http://127.0.0.1:9200"; here=os.path.dirname(__file__)
+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","require":"LFI-RFI","echo":"XSS","print":"XSS"}
+MAGIC={"__destruct","__toString","__call","__callStatic","__get","__set","__invoke",
+ "__unserialize","__wakeup","__sleep","__serialize","__isset","__unset","__clone"}
+AUTOFIRE={"__destruct","__toString","__wakeup","__unserialize"} # fire without a method being called
+
+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":list(MAGIC)}},"size":800,"_source":["func","file","line","code"]})
+
+def dangerous(code):
+ out=[]
+ for fn,cls in FN2CLASS.items():
+ if re.search(rf"(?<![\w$])(->|::|\b){re.escape(fn)}\s*\(",code): out.append((fn,cls))
+ for kw,cls in CONSTRUCTS.items():
+ if re.search(rf"(?<![\w$>]){kw}[\s(\"'$]",code): out.append((kw,cls))
+ return sorted(set(out))
+
+# group magic methods by file (~class in WP: one class per file)
+byfile={}
+for m in magic:
+ byfile.setdefault(m["file"],{})[m["func"]]=m
+
+rows=[]
+for f,methods in byfile.items():
+ # does this class have a throwing __wakeup or __unserialize guard?
+ guard=False
+ for g in ("__wakeup","__unserialize"):
+ if g in methods and re.search(r"\bthrow\b", methods[g].get("code","")): guard=True
+ # dangerous magic methods in this class
+ for name,m in methods.items():
+ d=dangerous(m.get("code",""))
+ if d and name in MAGIC and name not in ("__wakeup","__unserialize"):
+ rows.append({"class_file":f,"magic":name,"line":m["line"],"guard":guard,
+ "autofire": name in AUTOFIRE,"danger":d})
+
+exposed=[r for r in rows if not r["guard"] and r["autofire"]]
+guarded=[r for r in rows if r["guard"]]
+print(f"classes-with-dangerous-magic-method entries: {len(rows)}")
+print(f" GUARDED by throwing __wakeup/__unserialize: {len(guarded)}")
+print(f" EXPOSED (auto-fire magic, NO guard) -> gadget candidates: {len(exposed)}\n")
+print("EXPOSED gadget candidates (auto-fire, unguarded):")
+for r in sorted(exposed,key=lambda x:x['class_file']):
+ dd=", ".join(f"{fn}[{cls}]" for fn,cls in r["danger"])
+ print(f" {r['class_file'].split('/')[-1]:42} {r['magic']:12} -> {dd}")
+json.dump({"exposed":exposed,"guarded":[{k:r[k] for k in ('class_file','magic','danger')} for r in guarded]},
+ open(os.path.join(here,"gadget_inventory.json"),"w"),indent=1)
+print(f"\nwrote gadget_inventory.json (facts-only token cost of this whole hunt: ~{len(json.dumps([m for m in magic]))//4:,} tokens)")