apex-twin 0.16.0: coverage pass, gap tests, graceful shutdowns

make coverage builds apex-twin-cov with -O0 --coverage, runs the suite and
prints per-file line coverage via tests/coverage.py (gcov only).

First measured pass: 55.9%. Gap tests brought it to 73.4%:
- method_techniques/playbook/tool (tools_kb.c 0 -> 100%),
- http_head, http_paths against a routed local origin, sqli_probe, xss_probe,
  curl, http_capture of a binary body and traffic_read base64 (tools_web.c
  50.4 -> 71.6%),
- banner against a raw socket, scope_reload, dns, dry-run gated_cmd
  (tools_recon.c 51.8 -> 68.0%),
- traffic_list target filter and unknown-id read (tools_traffic.c 63.6 -> 81.8%),
- marauder_cmd/scan without a device (tools_radio.c 15.2 -> 31.7%; the rest
  needs hardware, documented as a host limit).

The -O0 build also proved a real truncation warning in guard.c that -O2 did not
report: the copied scope reason is now bounded with %.240s. The proxy and the
HTTP face now handle SIGTERM/SIGINT by returning from the accept loop instead of
dying, so the last stderr line and coverage data are not lost (proxy.c 0 -> 70.9%,
rewrite.c 53.2 -> 79.9%, apex-twin.c 20.7 -> 77.2%); the HTTP child uses exit()
so gcov flushes.

Also corrected the technique count in the README: the table has 11 entries, not
12. 267 checks.
This commit is contained in:
lotherk committed 2026-11-21 07:45:03 +00:00
1 parent ed4e326ed2
commit a04b072e8f
9 files changed
+359 -26

No files matched your search

+3
View File
@@ -8,3 +8,6 @@ apex-twin-asan-bug-proxy
build-fuzzbug-proxy/
apex-twin-asan-bug-http
build-fuzzbug-http/
apex-twin-cov
build-cov/
*.gcov
+21 -3
View File
@@ -17,6 +17,9 @@ FUZZBUG_PROXY_BIN := apex-twin-asan-bug-proxy
FUZZBUG_PROXY_OBJ := $(SRC:src/%.c=build-fuzzbug-proxy/%.o)
FUZZBUG_HTTP_BIN := apex-twin-asan-bug-http
FUZZBUG_HTTP_OBJ := $(SRC:src/%.c=build-fuzzbug-http/%.o)
COV_BIN := apex-twin-cov
COV_OBJ := $(SRC:src/%.c=build-cov/%.o)
COV_FLAGS := -g -O0 --coverage
all: apex-twin
@@ -68,6 +71,19 @@ build-fuzzbug-proxy/%.o: src/%.c src/apex.h $(LIBDIR)/mcp.h | build-fuzzbug-prox
$(FUZZBUG_PROXY_BIN): $(FUZZBUG_PROXY_OBJ)
$(CC) $(CFLAGS) $(ASAN_FLAGS) -o $@ $(FUZZBUG_PROXY_OBJ)
coverage: $(COV_BIN)
APEX_BIN=$(CURDIR)/$(COV_BIN) ./tests/run.sh
python3 tests/coverage.py
build-cov:
mkdir -p build-cov
build-cov/%.o: src/%.c src/apex.h $(LIBDIR)/mcp.h | build-cov
$(CC) $(CFLAGS) $(COV_FLAGS) -I$(LIBDIR) -Isrc -c -o $@ $<
$(COV_BIN): $(COV_OBJ)
$(CC) $(CFLAGS) $(COV_FLAGS) -o $@ $(COV_OBJ)
fuzz-http: $(ASAN_BIN)
ASAN_OPTIONS=detect_leaks=0:halt_on_error=1 \
UBSAN_OPTIONS=halt_on_error=1 \
@@ -135,7 +151,9 @@ install: apex-twin
clean:
rm -f apex-twin $(OBJ) $(ASAN_BIN) $(FUZZBUG_BIN) $(FUZZBUG_PROXY_BIN) \
$(FUZZBUG_HTTP_BIN)
rm -rf build-asan build-fuzzbug build-fuzzbug-proxy build-fuzzbug-http
$(FUZZBUG_HTTP_BIN) $(COV_BIN)
rm -rf build-asan build-fuzzbug build-fuzzbug-proxy build-fuzzbug-http \
build-cov
rm -f *.gcov
.PHONY: all test asan test-asan fuzz fuzz-selftest fuzz-red fuzz-proxy fuzz-proxy-red fuzz-http fuzz-http-red analyze install clean
.PHONY: all test asan test-asan fuzz fuzz-selftest fuzz-red fuzz-proxy fuzz-proxy-red fuzz-http fuzz-http-red coverage analyze install clean
+27 -18
View File
@@ -18,10 +18,11 @@ separate, explicitly armed switch.
```sh
make # apex-twin, ~239 kB static-ish binary, zero warnings under -Werror
make test # 239 end-to-end checks, no mocks
make test # 267 end-to-end checks, no mocks
make asan # apex-twin-asan with ASan + UBSan
make test-asan # the whole suite against the sanitizer binary
make analyze # gcc -fanalyzer over every translation unit
make coverage # -O0 --coverage build, suite, per-file gcov report
make fuzz # mutated scope/rewrite/MCP inputs against the ASan binary
make fuzz-red # builds a deliberately broken binary; fuzz must reject it
make fuzz-proxy # mutated raw requests against the ASan proxy
@@ -250,7 +251,7 @@ whether curl accepted it)
Method is not decoration. `method_playbook` returns the ordered steps for a
technique, the check that turns a lead into a finding, and the mistake that wastes
an engagement — 12 techniques across recon, enum, web, creds, AD, wifi and report,
an engagement — 11 techniques across recon, enum, web, creds, AD, wifi and report,
plus a note per tool on what people get wrong with it.
## Transport
@@ -329,7 +330,7 @@ finding and the next report no longer mentions it.
make test
```
239 checks, real binary, real DNS, real files written; no mocks. The suite was
267 checks, real binary, real DNS, real files written; no mocks. The suite was
seen red on purpose: with the "no scope" branch disabled by `if (0 && ...)`,
three checks fail, because they assert the *reason* and not merely that an error
came back — a gate that falls through to the next deny branch looks identical
@@ -360,7 +361,7 @@ this host is an SSH forward to another machine, and a foreign server answered
`{"serverInfo":{"name":"koder"}}` while the suite was green.
The suite is also run against `apex-twin-asan` (`make test-asan`), built with
`-fsanitize=address,undefined`. All 239 checks pass with no ASan or UBSan report,
`-fsanitize=address,undefined`. All 267 checks pass with no ASan or UBSan report,
and a separate batch of error paths, network captures and report generation was
run with leak detection on: no leaks. `make analyze` runs `gcc -fanalyzer` over
every translation unit; it was red first on `vendor/libmcp/mcp.h`, where
@@ -398,21 +399,29 @@ and any ASan/UBSan report fails the run. A case also fails on a hang; 200/202/
`make fuzz-http-red` (`APEX_FUZZ_BUG_HTTP`, a heap overflow after a complete
head) is rejected 2/2 with the exact `apex-twin.c` UBSan line.
`make coverage` builds `apex-twin-cov` with `-O0 --coverage`, runs the suite and
prints per-file line coverage (`tests/coverage.py`, gcov only, no extra tools).
The first measured pass was 55.9%; the gap tests brought it to **73.4%** —
`tools_kb.c` 100%, `tools_traffic.c` 81.8%, `tools_web.c` 71.6%,
`tools_recon.c` 68.0%. `tools_radio.c` stays lowest (31.7%) because the radio
paths need the hardware; that is a limit of the host, not a missing test. The
`-O0` build also proved a truncation warning in `guard.c` that `-O2` had not:
the copied scope reason is now bounded with a precision, not left to snprintf.
## Status
0.15.0. Built and run: 45 tools, 239 checks, 240 file-parser fuzz cases, 60
proxy-parser fuzz cases and 40 HTTP-face fuzz cases. The loop closes: a probe
captures the exchange as a pair, a finding points at it, `finding_update` gives
it a state, an asset records the host it came from,
`cors_check`/`cookie_audit`/`http_options` turn a web answer into a graded lead,
`report_markdown` turns findings and inventory into one Markdown or CSV file,
and `evidence_read`/`traffic_read` get the proof back. `--proxy` puts the same
gate in front of curl and a browser, with optional rewrite rules that can set or
remove a header or block a path, and `APEX_WEBHOOK` wakes someone when the
severity floor is crossed. `make install` ships the binary, this README and both
units; `--check` reports the operational state without starting a server. The
whole suite also runs under ASan/UBSan, `make analyze` is clean, and all three
fuzzers have been shown to reject a binary with a deliberate bug. Not yet wired
into a fleet router.
0.16.0. Built and run: 45 tools, 267 checks, 340 fuzz cases and 73.4% line
coverage. The loop closes: a probe captures the exchange as a pair, a finding
points at it, `finding_update` gives it a state, an asset records the host it
came from, `cors_check`/`cookie_audit`/`http_options` turn a web answer into a
graded lead, `report_markdown` turns findings and inventory into one Markdown or
CSV file, and `evidence_read`/`traffic_read` get the proof back. `--proxy` puts
the same gate in front of curl and a browser, with optional rewrite rules that
can set or remove a header or block a path, and `APEX_WEBHOOK` wakes someone when
the severity floor is crossed. `make install` ships the binary, this README and
both units; `--check` reports the operational state without starting a server.
The whole suite also runs under ASan/UBSan, `make analyze` is clean, all three
fuzzers reject a deliberately broken build, and `make coverage` keeps the gaps
visible. Not yet wired into a fleet router.
Licence: AGPL-3.0, same as ARTEX.
+28 -2
View File
@@ -33,6 +33,13 @@
static mcp_server g_srv;
static mcp_tool g_tools[64];
static volatile sig_atomic_t g_http_stop;
static void on_http_stop(int sig)
{
(void)sig;
g_http_stop = 1;
}
static void build_tools(void)
{
@@ -257,6 +264,16 @@ static int serve_http(int port)
snprintf(session, sizeof(session), "%08x-%08x", (unsigned)time(NULL),
(unsigned)getpid());
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = on_http_stop;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0; /* accept() returns EINTR on SIGTERM */
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
}
ls = socket(AF_INET, SOCK_STREAM, 0);
if (ls < 0) {
perror("socket");
@@ -283,22 +300,31 @@ static int serve_http(int port)
fprintf(stderr, "apex-twin: http mcp on 127.0.0.1:%d (session %s)\n", port,
session);
for (;;) {
int fd = accept(ls, NULL, NULL);
int fd;
pid_t pid;
if (g_http_stop)
break;
fd = accept(ls, NULL, NULL);
if (fd < 0)
continue;
if (g_http_stop) {
close(fd);
break;
}
pid = fork();
if (pid == 0) {
close(ls);
serve_one(fd, session);
_exit(0);
exit(0);
}
if (pid > 0)
close(fd);
else
serve_one(fd, session);
}
close(ls);
return 0;
}
int main(int argc, char **argv)
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "0.15.0"
#define APEX_VERSION "0.16.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+3 -2
View File
@@ -986,8 +986,9 @@ int apex_guard_check(const char *command, int default_port, guard_verdict *v)
if (strstr(t->reason, t->host) != NULL)
str_copy(v->reason, sizeof(v->reason), t->reason);
else
snprintf(v->reason, sizeof(v->reason), "%s:%d: %s",
t->host, t->port, t->reason);
snprintf(v->reason, sizeof(v->reason),
"%s:%d: %.240s", t->host, t->port,
t->reason);
}
}
if (denied) {
+18
View File
@@ -45,6 +45,7 @@
#define PROXY_TUNNEL_CAP (64L << 20)
static volatile sig_atomic_t g_rules_dirty;
static volatile sig_atomic_t g_stop;
static void on_hup(int sig)
{
@@ -52,6 +53,12 @@ static void on_hup(int sig)
g_rules_dirty = 1;
}
static void on_stop(int sig)
{
(void)sig;
g_stop = 1;
}
static void reload_rules(void)
{
if (apex_rewrite_load() == 0)
@@ -793,6 +800,7 @@ int apex_serve_proxy(int port)
struct sockaddr_in sa;
socklen_t sl;
struct sigaction sa_hup;
struct sigaction sa_stop;
signal(SIGPIPE, SIG_IGN);
memset(&sa_hup, 0, sizeof(sa_hup));
@@ -800,6 +808,14 @@ int apex_serve_proxy(int port)
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0; /* accept() must return EINTR on SIGHUP */
sigaction(SIGHUP, &sa_hup, NULL);
/* SIGTERM/SIGINT end the listener cleanly so coverage data and the last
* stderr line are not lost to a signal death */
memset(&sa_stop, 0, sizeof(sa_stop));
sa_stop.sa_handler = on_stop;
sigemptyset(&sa_stop.sa_mask);
sa_stop.sa_flags = 0;
sigaction(SIGTERM, &sa_stop, NULL);
sigaction(SIGINT, &sa_stop, NULL);
reload_rules();
ls = socket(AF_INET, SOCK_STREAM, 0);
@@ -829,6 +845,8 @@ int apex_serve_proxy(int port)
for (;;) {
int fd;
if (g_stop)
break;
if (g_rules_dirty) {
g_rules_dirty = 0;
reload_rules();
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Per-file line coverage from gcov, no external tools beyond gcc's gcov.
`make coverage` builds apex-twin-cov with -O0 --coverage, runs the whole suite
against it, then this script runs gcov per translation unit and prints the files
worst-covered first. It never fails a build on a percentage; the number is a
map for where the next test should go, not a gate.
"""
import glob
import os
import re
import subprocess
import sys
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BUILD = os.path.join(HERE, "build-cov")
SOURCES = sorted(glob.glob(os.path.join(HERE, "src", "*.c")))
LINE_RE = re.compile(r"Lines executed:([\d.]+)% of (\d+)")
def gcov_one(path):
base = os.path.basename(path)
out = subprocess.run(["gcov", "-b", "-c", "-o", BUILD, path],
capture_output=True, text=True, cwd=HERE)
text = out.stdout
for block in re.split(r"^File '", text, flags=re.M)[1:]:
name = block.split("'", 1)[0]
if os.path.basename(name) != base:
continue
m = LINE_RE.search(block)
if m is not None:
pct = float(m.group(1))
total = int(m.group(2))
return pct, total, int(round(pct * total / 100.0))
return None
def main():
if not os.path.isdir(BUILD):
print("coverage: no %s (run make coverage)" % BUILD)
return 1
rows = []
for src in SOURCES:
got = gcov_one(src)
if got is not None:
rows.append((os.path.basename(src),) + got)
for junk in glob.glob(os.path.join(HERE, "*.gcov")):
os.unlink(junk)
if not rows:
print("coverage: gcov produced no data")
return 1
total_lines = sum(r[2] for r in rows)
total_hit = sum(r[3] for r in rows)
rows.sort(key=lambda r: (r[1], r[2]))
print("%-22s %8s %8s %8s" % ("file", "lines", "hit", "cover"))
print("-" * 50)
for name, pct, lines, hit in rows:
print("%-22s %8d %8d %7.1f%%" % (name, lines, hit, pct))
print("-" * 50)
print("%-22s %8d %8d %7.1f%%" %
("total", total_lines, total_hit,
100.0 * total_hit / total_lines if total_lines else 0.0))
return 0
if __name__ == "__main__":
sys.exit(main())
+191
View File
@@ -6,6 +6,7 @@ that is in scope, and assertions on the files the server actually wrote. The
point of the suite is the gate: everything else is a tool, the gate is the
product.
"""
import base64
import http.server
import json
import os
@@ -17,6 +18,7 @@ import sys
import tempfile
import threading
import time
import urllib.parse
import urllib.request
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -764,6 +766,195 @@ quiet = json.loads(text(res[0]))
check("without a webhook the test says so", quiet["configured"] is False,
quiet)
print("\n== method and radio knowledge ==")
res, _ = run([
call(1, "method_techniques"),
call(2, "method_techniques", phase="web"),
call(3, "method_techniques", id="port-scan"),
call(4, "method_techniques", id="nope"),
call(5, "method_playbook", phase="web"),
call(6, "method_tool", name="nmap"),
call(7, "method_tool", name="nope"),
call(8, "method_tool"),
call(9, "marauder_commands"),
])
by_id = {r.get("id"): r for r in res}
tech = json.loads(text(by_id[1]))
check("method_techniques lists all eleven", len(tech) == 11, len(tech))
web = json.loads(text(by_id[2]))
check("method_techniques filters by phase",
len(web) > 0 and all(t["phase"] == "web" for t in web), web)
detail = json.loads(text(by_id[3]))
check("a technique carries steps and a pitfall",
"steps" in detail and "confirm" in detail and "pitfall" in detail, detail)
check("an unknown technique is refused", err(by_id[4]), text(by_id[4]))
plan = json.loads(text(by_id[5]))
check("method_playbook returns an ordered list",
plan["count"] > 0 and len(plan["order"]) == plan["count"], plan)
note = json.loads(text(by_id[6]))
check("method_tool explains a tool and its mistake",
note["name"] == "nmap" and "mistake" in note and note["mistake"] != "",
note)
check("an unknown tool note is refused", err(by_id[7]), text(by_id[7]))
index = json.loads(text(by_id[8]))
check("method_tool without a name lists the table", len(index) > 5, len(index))
radio = json.loads(text(by_id[9]))
check("marauder_commands lists commands without a device",
len(radio["commands"]) > 10 and radio["serial_tx"] is False, radio)
check("the radio list includes info", any(c["command"] == "info"
for c in radio["commands"]), radio)
print("\n== tool branches (local routes) ==")
class _RouteHandler(http.server.BaseHTTPRequestHandler):
def _body(self):
parts = urllib.parse.urlsplit(self.path)
q = urllib.parse.parse_qs(parts.query).get("q", [""])[0]
if parts.path == "/binary":
return 200, b"\x00\xff\x01BIN"
if parts.path == "/echo":
return 200, ("ref:" + q).encode()
if parts.path == "/sqli":
if "'" in q:
return 500, b"x" * 80
return 200, b"x"
if parts.path == "/admin":
return 200, b"admin"
return 404, b"nope"
def do_GET(self):
code, body = self._body()
self.send_response(code)
self.send_header("Content-Length", str(len(body)))
self.send_header("X-Test", "route")
self.end_headers()
self.wfile.write(body)
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-Length", "0")
self.send_header("X-Test", "route")
self.end_headers()
def log_message(self, *args):
pass
route = http.server.HTTPServer(("127.0.0.1", 0), _RouteHandler)
rport = route.server_address[1]
threading.Thread(target=route.serve_forever, daemon=True).start()
route_home = tempfile.mkdtemp(prefix="apex-route-")
write_scope(route_home, {"label": "route", "expires": "2099-12-31T23:59:59Z",
"allow_private": True, "allow_ip": ["127.0.0.1"],
"allow_port": [str(rport)]})
try:
res, _ = run([
call(1, "http_head", target="127.0.0.1", port=rport, path="/admin",
tls=False),
call(2, "http_paths", target="127.0.0.1", port=rport, base="/",
limit=5, tls=False),
call(3, "sqli_probe", target="127.0.0.1", port=rport, path="/sqli",
param="q", tls=False),
call(4, "xss_probe", target="127.0.0.1", port=rport, path="/echo",
param="q", tls=False),
call(5, "http_capture", target="127.0.0.1", port=rport,
path="/binary", tls=False, note="binary"),
call(6, "traffic_read", id="t0001"),
call(7, "curl", target="127.0.0.1", port=rport, url="/admin"),
call(8, "scope_reload"),
call(9, "traffic_list", target="127.0.0.1"),
call(10, "traffic_read", id="t9999"),
], home=route_home)
by_id = {r.get("id"): r for r in res}
check("http_head returns the response head", "200" in text(by_id[1]),
text(by_id[1])[:200])
check("http_head shows the headers", "X-Test" in text(by_id[1]),
text(by_id[1])[:240])
paths = json.loads(text(by_id[2]))
check("http_paths finds the admin path", paths["hits_count"] >= 1 and
any(h["path"] == "/admin" for h in paths["hits"]), paths)
sqli = json.loads(text(by_id[3]))
check("sqli_probe sends the payload set", len(sqli["probes"]) == 5, sqli)
check("sqli_probe reports differing answers",
any(p["differs"] for p in sqli["probes"]), sqli)
xss = json.loads(text(by_id[4]))
check("xss_probe sees the reflection", xss["reflected"] is True, xss)
cap = json.loads(text(by_id[5]))
check("http_capture stores a binary response", cap["status"] == 200, cap)
raw = json.loads(text(by_id[6]))
check("traffic_read returns binary as base64",
raw["encoding"] == "base64", raw)
check("the binary bytes survive the round trip",
base64.b64decode(raw["data"]).split(
b"=== RESPONSE (raw) ===\n", 1)[1].endswith(b"\x00\xff\x01BIN"),
raw["data"][:80])
curled = text(by_id[7])
check("curl runs against the gated path", "exit=0" in curled and
"200" in curled, curled[:200])
reloaded = json.loads(text(by_id[8]))
check("scope_reload reloads the same file", reloaded["loaded"] is True,
reloaded)
filtered = json.loads(text(by_id[9]))
check("traffic_list filters by target", len(filtered) == 1 and
filtered[0]["path"] == "/binary", filtered)
check("traffic_read refuses an unknown id", err(by_id[10]),
text(by_id[10]))
finally:
route.shutdown()
route.server_close()
shutil.rmtree(route_home, ignore_errors=True)
print("\n== banner against a raw socket ==")
banner_srv = socket.socket()
banner_srv.bind(("127.0.0.1", 0))
banner_srv.listen(4)
bport = banner_srv.getsockname()[1]
def banner_serve():
try:
conn, _ = banner_srv.accept()
conn.sendall(b"SSH-2.0-fuzz\r\n")
conn.close()
except OSError:
pass
threading.Thread(target=banner_serve, daemon=True).start()
banner_home = tempfile.mkdtemp(prefix="apex-banner-")
write_scope(banner_home, {"label": "banner", "expires": "2099-12-31T23:59:59Z",
"allow_private": True, "allow_ip": ["127.0.0.1"],
"allow_port": [str(bport)]})
res, _ = run([call(1, "banner", target="127.0.0.1", port=bport, wait_ms=800)],
home=banner_home)
check("banner reads the service greeting", "SSH-2.0-fuzz" in text(res[0]),
text(res[0])[:160])
banner_srv.close()
shutil.rmtree(banner_home, ignore_errors=True)
print("\n== radio without a device ==")
fake = os.path.join(ROOT, "notamodem")
with open(fake, "w") as f:
f.write("")
res, _ = run([
call(1, "marauder_cmd", command="list"),
call(2, "marauder_scan", commands="scanall"),
], extra_env={"APEX_SERIAL": fake})
check("marauder_cmd fails loudly without a radio", err(res[0]), text(res[0]))
check("marauder_scan fails loudly without a radio", err(res[1]), text(res[1]))
print("\n== dry run and dns ==")
res, _ = run([
call(1, "nmap", target="192.0.2.5", profile="quick"),
call(2, "dns", target="example.com", type="A"),
], extra_env={"APEX_DRY_RUN": "1"})
check("dry_run prints the command instead of running nmap",
not err(res[0]) and "DRY RUN" in text(res[0]), text(res[0])[:160])
res2, _ = run([call(1, "dns", target="example.com", type="A")])
check("dns runs dig through the gate", not err(res2[0]) and
"exit=" in text(res2[0]), text(res2[0])[:160])
# --------------------------------------------------------------- transport
print("\n== http transport ==")