Files
apex-twin/tests/gate_audit.py
T
lotherk ebb046c7b1 apex-twin 1.38.0: Consul, Vault and ZooKeeper audits, mTLS probe
Blue:
- consul_config_audit: consul.hcl and consul.d/*.hcl (root prefix): ACL
  default policy allow, bind_addr on every interface, incoming/outgoing
  verification off, missing gossip encryption, enabled UI and world-writable
  files.
- vault_config_audit: vault.hcl: tls_disable 1/true, UI enabled, disable_mlock
  and a Shamir seal without auto-unseal.
- zookeeper_audit: zoo.cfg: an open 4lw whitelist (stat/mntr/envi),
  clientPortAddress on every interface and a missing authProvider.

Red:
- tls_client_auth_probe: one openssl s_client -msg handshake; a
  CertificateRequest means the server requires a client certificate. Reports
  protocol and cipher and presents no certificate.

Tests with vulnerable and hardened Consul/Vault/ZooKeeper trees plus a
client-cert-required TLS server and a plain one. 905 checks, ASan suite green,
analyze clean, release-check green including distcheck 1.38.0.

Note: two unrelated nmap timeout checks failed once under system load and
passed on the immediate rerun (905/905), so they are recorded as environmental.
2026-11-22 07:18:12 +00:00

192 lines
6.7 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 = 191
GATE = ("gated(", "gated_cmd(", "gated_run(", "apex_scope_check(")
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))))
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)
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())