Files
lotherk 59b71ab3a1 apex-twin 1.100.0: auth_test over six protocols, SIGPIPE fix
Authentication testing in src/tools_auth.c (new file, 16th table): auth_test
speaks http Basic, ftp, smtp AUTH LOGIN, imap, pop3 and mysql
(mysql_native_password) against one in-scope service. The operator supplies
the wordlists (inline or file) and every limit - delay_ms, max_attempts,
stop_on_hit, lockout_limit, timeout_ms; the program adds none of its own.
auth_plan counts a run without connecting, auth_protocols lists the
protocols, auth_hits returns the credential findings with evidence paths.
A hit is the protocol's own accept answer; each accepted pair becomes a
critical finding with the pair and the answer in evidence, while the audit
log keeps the account and service and never the password.

Two real bugs found by the tests they came with:

- An HTTP answer below 400 counted as a hit, so a 404 or a 500 would have
  been reported as valid credentials. Only 2xx/3xx prove authentication
  now; two checks pin it and fail against the old logic.
- SIGPIPE killed the whole server when a target hung up mid-write: one
  dead target, one dead MCP server. Ignored once at startup, so the write
  returns EPIPE and the tool reports a failed connection. Five checks, one
  per protocol.

SHA1 for the MySQL scramble is written out in the file and checked against
the published vectors for "", "abc", "password" and a 1000-byte multi-block
input. The MySQL seed is read by counting handshake fields; a fixed offset
picked up the capability flags and made every login fail against a healthy
server, which the suite proves by neutralising the offset.

427 tools, 1637 end-to-end checks, 84.7% line coverage.
release-check exit 0, distcheck 1.100.0 passes 1637/1637 from the tarball.
2026-11-24 06:45:02 +00:00

214 lines
7.8 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 = 427
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_runx", "ext_runx(": "ext_runx",
"exploit_call(": "exploit_call"}
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", "auth_hits"}
# Tools that spawn a local program and take no target at all, so there is
# nothing for the gate to check. Each one still writes its audit line before it
# runs. msfvenom_build renders a payload on this host; the others talk to a
# board on a serial port.
LOCAL_EXEC = {"esp_info", "esp_read_flash", "esp_flash", "package_integrity",
"firewall_audit", "msfvenom_build"}
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())