Files
apex-twin/tests/gate_audit.py
T
lotherk 41eac32f53 apex-twin 1.91.0: promtail and otel collector audits, Loki and Tempo probes
Two blue config audits and two red API probes for the observability stack.

promtail_audit (blue): positions.filename missing or under /tmp, a client
without tenant_id, a plain http push URL and a world-writable config.
otel_collector_audit (blue): an exporters block without tls, a debug
exporter, zpages/pprof and a world-writable config.
loki_probe (red): /loki/api/v1/labels without credentials; the label list
is saved as evidence.
tempo_probe (red): /api/search/tags without credentials; the tag list is
saved as evidence.

Verified: 1477/1477 checks (make test and test-asan), gate-audit 397 tools
from 14 tables, analyze 0 warnings, 240 fuzz cases, distcheck from the
tarball, coverage 85.0%. Red proof: disabling the tmp-positions check in
promtail_audit turns the fixture check red (1476/1), restored afterwards.
2026-11-23 15:33:59 +00:00

211 lines
7.6 KiB
Python
Executable File

#!/usr/bin/env python3
"""Static audit: every tool that names a target must go through the gate.
Parses each TOOLS_*[] table in src/tools_*.c, extracts the handler bodies with
brace matching (comments and string literals stripped), and checks two rules:
A. a tool whose input schema has a "target" key must call gated(),
gated_cmd() or apex_scope_check() in its handler, unless it is a record
filter that only reads local state (explicit allowlist below);
B. a handler that opens a socket or spawns a process (http_once,
tcp_connect_host, tcp_probe, apex_run) must call one of the same functions.
The tool count must match EXPECTED_TOOLS, so adding a tool forces a look here.
make gate-audit
python3 tests/gate_audit.py -v
"""
import glob
import os
import re
import sys
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
EXPECTED_TOOLS = 397
GATE = ("gated(", "gated_cmd(", "gated_run(", "apex_scope_check(")
# Handlers may hand argv to a shared runner instead of calling the gate
# themselves. That runner has to call the gate; both halves are checked
# below, so "ext_run(" is not a free pass.
INDIRECT = {"ext_run(": "ext_run"}
NET = ("http_once(", "tcp_connect_host(", "tcp_probe(", "apex_run(")
# Tools whose "target" argument filters local records; they never touch it.
RECORD_FILTERS = {"asset_list", "finding_list", "report_markdown",
"traffic_list", "detect_rules", "mitre_map"}
# Tools that spawn a local program for hardware, not a network target. They take
# no target and cannot reach one through the argv they build.
LOCAL_EXEC = {"esp_info", "esp_read_flash", "esp_flash", "package_integrity",
"firewall_audit"}
TABLE_RE = re.compile(r"const mcp_tool (TOOLS_[A-Z_]+)\[\] = \{(.*?)\n\};",
re.S)
ENTRY_RE = re.compile(r'\{\s*"([a-z0-9_]+)",(.*?)\n\t ([a-z_][a-z0-9_]*) \},',
re.S)
TARGET_KEY = re.compile(r'\\"target\\":')
def extract_body(text, brace):
"""Return (raw body, code-only body) for the brace block at `brace`."""
code = []
depth = 0
i = brace
state = "code"
while i < len(text):
ch = text[i]
nxt = text[i + 1] if i + 1 < len(text) else ""
if state == "code":
if ch == "/" and nxt == "*":
state = "block"
code.append(" ")
i += 2
continue
if ch == "/" and nxt == "/":
state = "line"
code.append(" ")
i += 2
continue
if ch == '"':
state = "string"
code.append(" ")
i += 1
continue
if ch == "'":
state = "char"
code.append(" ")
i += 1
continue
code.append(ch)
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return text[brace:i + 1], "".join(code)
elif state == "block":
if ch == "*" and nxt == "/":
state = "code"
code.append(" ")
i += 2
continue
code.append("\n" if ch == "\n" else " ")
elif state == "line":
if ch == "\n":
state = "code"
code.append("\n")
else:
code.append(" ")
elif state == "string":
if ch == "\\":
code.append(" ")
i += 2
continue
if ch == '"':
state = "code"
code.append(" ")
elif state == "char":
if ch == "\\":
code.append(" ")
i += 2
continue
if ch == "'":
state = "code"
code.append(" ")
i += 1
return None, None
def handler_code(sources, name):
for path, text in sources:
m = re.search(r"static void\s+" + re.escape(name) +
r"\s*\(\s*mcp_conn\s*\*c\s*,[^)]*\)", text)
if m is None:
continue
brace = text.find("{", m.end())
if brace < 0:
continue
_, code = extract_body(text, brace)
if code is not None:
return code, path
return None, None
def main():
verbose = "-v" in sys.argv
sources = [(p, open(p).read())
for p in sorted(glob.glob(os.path.join(HERE, "src", "tools_*.c")))]
tools = []
for path, text in sources:
for tm in TABLE_RE.finditer(text):
table = tm.group(1)
body = tm.group(2)
entries = list(ENTRY_RE.finditer(body))
if not entries:
print("gate-audit: %s has no entries" % table)
return 1
for em in entries:
tools.append({"name": em.group(1), "table": table,
"text": em.group(2),
"handler": em.group(3), "file": path})
print("gate-audit: parsed %d tools from %d tables" %
(len(tools), len(set(t["table"] for t in tools))))
# An indirect gate is only worth anything if the helper calls the real gate.
all_code = "\n".join(code for _, code in sources)
for token, fname in INDIRECT.items():
m = re.search(r"static [a-z_ ]*\b%s\s*\([^)]*\)\s*\{" % fname,
all_code)
if m is None:
print("gate-audit: indirect gate %s not found" % fname)
return 1
_, hcode = extract_body(all_code, m.end() - 1)
if not any(g in hcode for g in GATE):
print("gate-audit: indirect gate %s never calls the scope gate" %
fname)
return 1
violations = []
seen = set()
for tool in tools:
name = tool["name"]
if name in seen:
violations.append("%s: duplicate tool name" % name)
seen.add(name)
code, hpath = handler_code(sources, tool["handler"])
if code is None:
violations.append("%s: handler %s not found" %
(name, tool["handler"]))
continue
gated = any(g in code for g in GATE) or \
any(g in code for g in INDIRECT)
wants_target = TARGET_KEY.search(tool["text"]) is not None
uses_net = any(n in code for n in NET)
ok = True
if wants_target and not gated and name not in RECORD_FILTERS:
violations.append("%s: schema has target but %s has no gate call" %
(name, tool["handler"]))
ok = False
if uses_net and not gated and name not in LOCAL_EXEC:
violations.append("%s: %s uses a socket/process but has no gate call" %
(name, tool["handler"]))
ok = False
if verbose:
print(" %-4s %-22s %s" % ("ok" if ok else "FAIL", name,
os.path.basename(hpath)))
if len(tools) != EXPECTED_TOOLS:
violations.append("tool count is %d, expected %d (update EXPECTED_TOOLS "
"and review the new tool)" % (len(tools),
EXPECTED_TOOLS))
if violations:
for v in violations:
print("FAIL " + v)
print("gate-audit: %d violation(s) over %d tools" %
(len(violations), len(tools)))
return 1
print("gate-audit: OK (%d tools, %d record-filter exception(s))" %
(len(tools), len(RECORD_FILTERS)))
return 0
if __name__ == "__main__":
sys.exit(main())