Files
apex-twin/tests/gate_audit.py
T
lotherk 539b552c3d apex-twin 1.6.0: TLS, Redis, SNMP and DNS zone-transfer checks
Red, deep service checks (tools_proto.c):
- tls_audit: four openssl s_client probes (TLS 1.0/1.1/1.2/1.3) plus a
  -showcerts run, then openssl x509 for subject, issuer, validity and DNS SANs.
  Flags TLS 1.0/1.1 and RC4/3DES/NULL/EXPORT/MD5 ciphers. A failed handshake
  also prints a session block, so success is keyed on 'New, ..., Cipher is ...'
  and (NONE) counts as failure.
- redis_probe: PING on one connection; when it answers without AUTH, INFO and
  DBSIZE follow. Reports open access (audited), version, role, connected
  clients, OS and database size. No password guessing.
- snmp_probe: hand-built SNMPv1/v2c GET sysDescr.0 over UDP, two attempts per
  community (default public/private, max 4), raw answer saved as evidence. No
  net-snmp dependency.
- dns_zone_transfer: dig AXFR against one in-scope server for one in-scope
  zone; record counts per type, up to 200 raw records, full output as evidence,
  and explicit refused/unreachable reasons.

Shared gated_run(): gate, audit and run with the output returned to the caller,
so multi-command tools keep the gate invariant.

Tests: TLS server with a generated certificate, open and AUTH-required Redis
servers, a UDP SNMP agent answering only 'public', an AXFR server with
SOA/NS/A records plus a refusing variant, and the out-of-scope paths. 522
checks, ASan suite green, analyze clean (an analyzer uninitialised-field report
was removed by initialising the token array), release-check green including
distcheck 1.6.0.
2026-11-21 12:23:56 +00:00

191 lines
6.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 = 73
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"}
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())