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.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
docs(case-study): interprocedural taint analysis over XERJ data (taint_analysis.py)
Xerj Squad A9fd8f61a9f50
diff --git a/docs/case-studies/wordpress-security-audit/README.md b/docs/case-studies/wordpress-security-audit/README.mdindex 045e4eba3..7a40b2710 100644--- a/docs/case-studies/wordpress-security-audit/README.md+++ b/docs/case-studies/wordpress-security-audit/README.md@@ -101,6 +101,10 @@ read; scale and durability come from XERJ.- [`VERIFY-AND-TRACE.md`](VERIFY-AND-TRACE.md) — **verify the data is live inXERJ and trace any sink end-to-end via the API** (sink → enclosing fn → sources→ reverse callers → authz), with `sink-census/trace_sink.py`.+- [`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+ (`sink-census/taint_analysis.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) — thediff --git a/docs/case-studies/wordpress-security-audit/sink-census/TAINT-ANALYSIS.md b/docs/case-studies/wordpress-security-audit/sink-census/TAINT-ANALYSIS.mdnew file mode 100644index 000000000..249937f07--- /dev/null+++ b/docs/case-studies/wordpress-security-audit/sink-census/TAINT-ANALYSIS.md@@ -0,0 +1,73 @@+# Interprocedural taint analysis on XERJ data++Once the AST scan is exported (the 6 `wp*` indices), taint analysis is a query ++graph walk over facts already in XERJ — **no local files**. `taint_analysis.py`+finds **source → sink flows**: a function that reads a request source+(`$_GET/$_POST/$_REQUEST/$_COOKIE/$_SERVER/$_FILES`) that reaches a dangerous sink+(`sql/cmd/code/deser/lfi/xss`) with **no sanitizer on the call path**.++## How it works (all from `wpaudit`)++- `wpaudit` already stores, per function: the `sources` it reads, the `sinks` it+ hits, a `sanit` flag, and its `calls` (edges). Taint is then:+ - **intra-procedural** — `sources` + `sinks` + `sanit=false` in one function;+ - **inter-procedural** — forward-DFS the call graph (unambiguous-name edges+ only) from a source function to a sink function, carrying a sanitizer-seen+ flag; stop at the first unsanitized sink.+- Flows are ranked by sink severity (cmd/code/deser > sql > lfi > xss) and joined+ to `wpsinks` for the exact dangerous call.++```bash+python3 taint_analysis.py # -> ranked flows + taint_flows.json+```++## Result on WordPress core++```+10,000 functions in the graph, 362 read a source, 956 hit a sink+TAINT FLOWS (source -> sink, no sanitizer on path): 70+ by terminal sink class: {deser: 1, sql: 11, lfi: 30, xss: 34}+```++70 candidate flows from ~12k functions — a reviewable set, each with the full+`source -> f1 -> f2 -> ... -> sink` path.++## Honest verification of the top flows (real vs false-positive)++Reading the terminals (the discipline the whole method uses):++| flow | terminal sink | verdict |+|---|---|---|+| `save_widget` **[deser]** ($_POST) | `unserialize($serialized_instance)` | **real candidate** — request input reaches a deserialization sink; guarded by the REST `show_instance_in_rest` opt-in + hash (confirm the guard). |+| `… -> get_posts` **[sql]** | `new WP_Query()->query($args)` | **false positive** — `WP_Query::query()`, not `$wpdb->query()`; parameterized internally (receiver-type blindness). |+| `wp_ajax_trash_post -> … -> _prime_term_caches` **[sql]** | `$wpdb->get_results("… IN (%s)", intval($ids))` | **false positive** — ids are `intval`'d; and the path is *reachability*, the tainted `$_POST` value never flows to `$ids`. |+| `wp_ajax_query_attachments` **[sql]** | `WP_Query` (key allow-list) | **false positive** — auth-gated + allow-listed (read earlier). |++## What this taint pass is — and is not (state it plainly)++- It is **reachability taint** over the function-call graph: "a source function can+ transitively reach a sink function with no name-based sanitizer on the path." It+ is a fast, high-recall **triage** that turns 12k functions into ~70 candidates.+- It is **not precise data-flow.** It does not prove the specific tainted *value*+ reaches the sink argument — many SQL flows terminate in `WP_Query` (safe) or an+ `intval`-guarded `$wpdb` call, or the tainted variable simply isn't the one used+ at the sink. Those are the same false-positive drivers documented in+ `../IMPROVEMENTS.md`:+ - **receiver-typed sinks** — distinguish `$wpdb->query` from `WP_Query->query`;+ - **argument-level data-flow** — confirm the source value flows into the sink+ argument, not just that the functions are call-connected;+ - **sanitizer precision** — `intval`/`absint`/allow-list on the sink argument.+- With those refinements the 70 collapse toward the true positives (here: the+ `save_widget` deserialization candidate, then confirm its guard).++## The honest taint statement++> Every function that reads a request source is walked to every dangerous sink it+> can reach with no sanitizer on the path (70 candidate flows on WP core, ranked+> by severity, each with its full path). This is high-recall reachability triage+> over the XERJ call graph — precise per-argument data-flow and receiver-typed+> sinks are the next refinement; until then each flow is a candidate to read, not+> a confirmed bug.++This is the same contract as the rest of the workflow: the graph narrows, you+read, you verify by executing.diff --git a/docs/case-studies/wordpress-security-audit/sink-census/taint_analysis.py b/docs/case-studies/wordpress-security-audit/sink-census/taint_analysis.pynew file mode 100644index 000000000..eb220318b--- /dev/null+++ b/docs/case-studies/wordpress-security-audit/sink-census/taint_analysis.py@@ -0,0 +1,88 @@+#!/usr/bin/env python3+"""Interprocedural taint analysis over XERJ data (no local files).++Uses the per-function facts already in `wpaudit` (sources it reads, sink classes+it hits, sanitizer-on-path flag, call edges) to find SOURCE -> SINK flows:++ a function that reads a request source ($_GET/$_POST/...) reaches a dangerous+ sink (sql/cmd/code/deser/lfi/xss) with NO sanitizer anywhere on the call path.++Intra-procedural: source + sink + no-sanitizer in the same function.+Inter-procedural: forward DFS over unambiguous call edges to a sink function.+Ranks flows by sink severity and joins `wpsinks` for the exact dangerous call.+"""+import json, urllib.request+X = "http://127.0.0.1:9200"+SEV = {"cmd": 5, "code": 5, "deser": 5, "sql": 4, "lfi": 3, "xss": 2}++def scroll(idx, src):+ docs = []+ r = urllib.request.Request(f"{X}/{idx}/_search?scroll=2m",+ data=json.dumps({"size": 2000, "query": {"match_all": {}}, "_source": src}).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++print("loading wpaudit call graph from XERJ ...")+docs = scroll("wpaudit", ["func", "file", "line", "sources", "sinks", "sanit", "calls"])+byname = {}+name_count = {}+for d in docs:+ name_count[d["func"]] = name_count.get(d["func"], 0) + 1+ byname.setdefault(d["func"], d) # first def; edges resolved only if unambiguous+print(f" {len(docs)} functions, {sum(1 for d in docs if d['sources'])} read a source, "+ f"{sum(1 for d in docs if d['sinks'])} hit a sink")++def taint_dfs(start, depth=8):+ """From a source function, forward-DFS unambiguous call edges to a sink,+ tracking whether a sanitizer was seen on the path. Returns (path, sink_classes)."""+ stack = [(start["func"], [start["func"]], start["sanit"])]+ seen = set()+ while stack:+ fn, path, san = stack.pop()+ if fn in seen or len(path) > depth: continue+ seen.add(fn)+ d = byname.get(fn)+ if not d: continue+ if d["sinks"] and not san:+ return path, d["sinks"], d+ for c in d.get("calls", []):+ if c in byname and name_count.get(c, 0) == 1: # unambiguous edge only+ stack.append((c, path + [c], san or byname[c]["sanit"]))+ return None++flows = []+for d in docs:+ if not d["sources"]: continue+ # intra-procedural: source + sink + no sanitizer in the same function+ if d["sinks"] and not d["sanit"]:+ flows.append({"kind": "intra", "path": [d["func"]], "sink_fn": d,+ "sinks": d["sinks"], "src": d["sources"]})+ continue+ if d["sanit"]: continue+ r = taint_dfs(d)+ if r:+ path, sinks, sink_d = r+ flows.append({"kind": "inter", "path": path, "sink_fn": sink_d,+ "sinks": sinks, "src": d["sources"]})++def score(f): return max((SEV.get(s, 1) for s in f["sinks"]), default=0)+flows.sort(key=lambda f: (-score(f), -len(f["path"])))+print(f"\nTAINT FLOWS (source -> sink, no sanitizer on path): {len(flows)}")+from collections import Counter+byc = Counter(s for f in flows for s in f["sinks"])+print(" by terminal sink class:", dict(byc))+print("\n top high-severity flows (read these):")+for f in flows[:20]:+ sd = f["sink_fn"]+ print(f" [{'/'.join(sorted(f['sinks'], key=lambda s:-SEV.get(s,0)))}] "+ f"{f['src']} {' -> '.join(f['path'])}")+ print(f" sink in {sd['file']}:{sd['line']}")+json.dump(flows[:200], open("taint_flows.json", "w"), default=str)+print(f"\nwrote top-200 flows to taint_flows.json")diff --git a/docs/case-studies/wordpress-security-audit/skill/SKILL.md b/docs/case-studies/wordpress-security-audit/skill/SKILL.mdindex bd57af56f..0ba9d7feb 100644--- a/docs/case-studies/wordpress-security-audit/skill/SKILL.md+++ b/docs/case-studies/wordpress-security-audit/skill/SKILL.md@@ -87,6 +87,14 @@ incomplete allow/deny list, e.g. SSRF missing `169.254`), and sanitizer*composition* order (`wp_compose_index.py`). Verify each candidate by reading,then by executing the flow. Trace reachability to real input.+### 6b. Interprocedural taint (`taint_analysis.py`)+Once the AST is exported, run source->sink taint over the XERJ call graph: every+function that reads a request source, walked to every dangerous sink it can reach+with no sanitizer on the path (ranked by severity, full path per flow). This is+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`.+## Honesty rules (these make the result trustworthy)1. Precision from the graph/facts; full-text only to navigate. FTS over raw codeis noisy for security.