apex-twin 0.25.0: cap concurrent proxy children, fix concurrent audit

APEX_PROXY_MAX_CHILDREN (default 64, max 1024) bounds proxy children. SIGCHLD
now sets a flag and the parent reaps with waitpid(WNOHANG); at the cap the parent
answers 503 Service Unavailable with a 'proxy busy' reason and audits it instead
of forking. A failed fork still serves in the parent. --check and capabilities
report proxy_max_children.

The concurrency test exposed a real audit bug: append_line() wrote the JSON line
and the newline as two writes. With parallel children the writes interleaved and
audit_log() returned '{...}{...}' - invalid JSON at the caller. append_line()
now builds line+newline and writes once; audit_tail() reads with getline so a
command over 8 KiB is not split into half objects.

Tests: two slow requests fill a limit of 2, the third connection gets 503 with
'proxy busy', the refusal is audited, and a slot is usable after the children
exit. Red proof: removing the cap check turns the 503 and audit checks red.
One earlier run also showed the test racing a readiness child; the test now
retries admission and waits for both in-flight requests before probing.

309 checks, coverage 76.7%, release-check green including distcheck.
This commit is contained in:
lotherk committed 2026-11-21 08:54:51 +00:00
1 parent 1bb6f957e8
commit 0309e04011
11 files changed
+263 -28

No files matched your search

+18 -1
View File
@@ -8,7 +8,24 @@ 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.
## 0.24.0 — 2026-11-21 — this change
## 0.25.0 — 2026-11-21 — this change
- Bound concurrent proxy children with `APEX_PROXY_MAX_CHILDREN` (default 64,
max 1024). SIGCHLD now sets a flag and the parent reaps with
`waitpid(WNOHANG)`; at the cap the parent answers 503 `proxy busy` and audits
the refusal instead of forking.
- `--check` and `capabilities` report `proxy_max_children`.
- Found by the concurrent test: audit lines were written as two writes (line,
then newline). With parallel children they interleaved and `audit_log`
returned invalid JSON. `append_line()` now writes the line and newline in one
call, and `audit_tail()` reads with `getline` so a command longer than 8 KiB
stays one record.
- Tests: two slow in-flight requests fill a limit of 2, the third connection
gets 503, the audit records the reason, and a slot is usable again after the
children exit. Red proof: removing the cap check turns the 503 test and the
audit test red.
## 0.24.0 — 2026-11-21 — 1bb6f95
- The proxy forks one child per accepted connection: a `CONNECT` tunnel no
longer blocks the next request, and rewrite rules are inherited at fork while
+14 -11
View File
@@ -30,7 +30,7 @@ separate, explicitly armed switch.
```sh
make # apex-twin, ~239 kB static-ish binary, zero warnings under -Werror
make test # gate audit + 303 end-to-end checks, no mocks
make test # gate audit + 309 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 gate-audit # static audit: every target-taking tool calls the gate
@@ -180,8 +180,10 @@ It serves each accepted connection in a child process: a `CONNECT` tunnel does
not block the next request, and two captures can be written at once because the
traffic store reserves ids with `O_EXCL`. Each child inherits the scope and the
rewrite rules loaded at fork time; `SIGHUP` in the parent reloads the rules for
connections accepted afterwards. Slow origins are bounded by the per-stage
timeouts, not by a global queue.
connections accepted afterwards. At most `APEX_PROXY_MAX_CHILDREN` (default 64,
max 1024) children run at once; beyond that the parent answers
`503 Service Unavailable` with a `proxy busy` reason and audits it. Slow origins
are bounded by the per-stage timeouts.
Before forwarding, the proxy loads `$APEX_HOME/rewrite.json` (`APEX_REWRITE`
overrides the path) and applies the first matching rule:
@@ -290,7 +292,7 @@ plus a note per tool on what people get wrong with it.
apex-twin # MCP over stdin/stdout (one JSON-RPC line each way)
apex-twin --http 8797 # MCP over HTTP on 127.0.0.1:8797, POST /mcp
apex-twin --proxy 8798 # forward proxy on 127.0.0.1:8798 (curl -x)
apex-twin --check # scope, tool count, rewrite rules, webhook state, exit
apex-twin --check # scope, tools, rewrite rules, webhook, child limit, exit
```
HTTP and the proxy bind **loopback only**. A service that can scan and transmit
@@ -300,9 +302,9 @@ that: loopback ports, a 0700 state dir, `dialout` for the radio, and a capabilit
bounding set without `CAP_NET_RAW` (connect scans need none).
`--check` answers the operational questions without starting a server:
`rewrite_rules`, `webhook_configured` (a boolean; the URL is never printed) and
the loaded scope, alongside the version and tool count. `capabilities` returns
the same two fields to the model.
`rewrite_rules`, `webhook_configured` (a boolean; the URL is never printed),
`proxy_max_children` and the loaded scope, alongside the version and tool count.
`capabilities` returns the same fields to the model.
## The radio
@@ -334,6 +336,7 @@ APEX_SERIAL=/dev/ttyACM0 APEX_BAUD=115200
| `APEX_WEBHOOK` | unset | URL POSTed on a finding at or above the floor |
| `APEX_WEBHOOK_MIN_SEVERITY` | `critical` | floor for the webhook |
| `APEX_REWRITE` | `$APEX_HOME/rewrite.json` | proxy rewrite rules (SIGHUP reloads) |
| `APEX_PROXY_MAX_CHILDREN` | `64` | concurrent proxy connections before 503 |
## Files it writes
@@ -361,7 +364,7 @@ finding and the next report no longer mentions it.
make test
```
303 checks, real binary, real DNS, real files written; no mocks. The suite was
309 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
@@ -392,7 +395,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 303 checks pass with no ASan or UBSan report,
`-fsanitize=address,undefined`. All 309 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
@@ -451,7 +454,7 @@ 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.6%** —
The first measured pass was 55.9%; the gap tests brought it to **76.7%** —
`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
`tools_radio.c` from 31.7% to 76.2% without hardware: firmware `info`/`help`,
@@ -463,7 +466,7 @@ the copied scope reason is now bounded with a precision, not left to snprintf.
## Status
0.24.0. Built and run: 45 tools, 303 checks, 340 fuzz cases and 76.6% line
0.25.0. Built and run: 45 tools, 309 checks, 340 fuzz cases and 76.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
+4 -3
View File
@@ -73,9 +73,10 @@ only narrow what the proxy does (the scope gate still runs first).
- **TLS interception.** `CONNECT` is a blind tunnel; nothing inside TLS is
inspected, logged or rewritten. That is deliberate (no TLS stack is linked).
- **Denial of service from a local client.** The proxy forks a child per
connection; a local client can open many and consume processes and memory.
Per-stage timeouts bound each, but there is no authentication and no
connection limit.
connection and caps them at `APEX_PROXY_MAX_CHILDREN` (default 64, max 1024);
beyond that it answers 503 and audits. Per-stage timeouts bound each request,
but there is no authentication, so a local client can still consume the
allowed slots.
- **Compromised operator credentials.** A stolen shell or SSH key can run the
binary against the scope. The audit records what was asked, not who asked.
- **Webhook confidentiality.** Evidence titles and targets are POSTed to the
+4 -1
View File
@@ -134,7 +134,9 @@ recorded as metadata: the binary links no TLS stack, so it does not inspect TLS.
Each accepted connection gets its own child process, so a `CONNECT` tunnel does
not block the next request and parallel captures cannot overwrite each other
(traffic ids are reserved with `O_EXCL`). A SIGHUP in the parent reloads the
(traffic ids are reserved with `O_EXCL`). At most `APEX_PROXY_MAX_CHILDREN`
(default 64, max 1024) children run at once; beyond that the parent answers
`503 Service Unavailable` (`proxy busy`) and audits the refusal. A SIGHUP in the parent reloads the
rewrite rules for connections accepted after it; children keep the rules they
inherited at fork.
@@ -195,6 +197,7 @@ of that file — back up first.
| Findings per report | 1024 |
| Default tool timeout | 60 s (hard cap 900 s) |
| Radio scan | 3–300 s, always ends with `stopscan` |
| Concurrent proxy connections | `APEX_PROXY_MAX_CHILDREN`, default 64, 503 beyond |
## Troubleshooting
+3 -2
View File
@@ -357,10 +357,11 @@ int main(int argc, char **argv)
apex_scope_json(&b);
printf("{\"version\":\"%s\",\"tools\":%lu,\"home\":\"%s\","
"\"rewrite_rules\":%d,\"webhook_configured\":%s,"
"\"scope\":%s}\n", APEX_VERSION,
"\"proxy_max_children\":%d,\"scope\":%s}\n", APEX_VERSION,
(unsigned long)g_srv.ntools, g_cfg.home,
apex_rewrite_count(),
g_cfg.webhook[0] != '\0' ? "true" : "false", b.p);
g_cfg.webhook[0] != '\0' ? "true" : "false",
g_cfg.proxy_max_children, b.p);
mcp_buf_free(&b);
return 0;
}
+2 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "0.24.0"
#define APEX_VERSION "0.25.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
@@ -70,6 +70,7 @@ typedef struct {
char webhook[1024];
char webhook_min[16];
char rewrite_file[APEX_PATH_MAX];
int proxy_max_children;
char serial[128];
int baud;
int default_timeout_ms;
+6
View File
@@ -171,6 +171,12 @@ void apex_config_init(void)
env_int("APEX_DEFAULT_TIMEOUT_MS", &g_cfg.default_timeout_ms);
env_int("APEX_MAX_TIMEOUT_MS", &g_cfg.max_timeout_ms);
env_int("APEX_BAUD", &g_cfg.baud);
g_cfg.proxy_max_children = 64;
env_int("APEX_PROXY_MAX_CHILDREN", &g_cfg.proxy_max_children);
if (g_cfg.proxy_max_children <= 0)
g_cfg.proxy_max_children = 64;
if (g_cfg.proxy_max_children > 1024)
g_cfg.proxy_max_children = 1024;
if (dry != NULL && (*dry == '1' || *dry == 'y' || *dry == 't'))
g_cfg.dry_run = 1;
{
+44 -2
View File
@@ -28,6 +28,7 @@
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
#include "apex.h"
@@ -46,6 +47,24 @@
static volatile sig_atomic_t g_rules_dirty;
static volatile sig_atomic_t g_stop;
static volatile sig_atomic_t g_child_exit;
static int g_children;
static void on_child(int sig)
{
(void)sig;
g_child_exit = 1;
}
static void reap_children(void)
{
int status;
while (waitpid(-1, &status, WNOHANG) > 0) {
if (g_children > 0)
g_children--;
}
}
static void on_hup(int sig)
{
@@ -965,9 +984,14 @@ int apex_serve_proxy(int port)
socklen_t sl;
struct sigaction sa_hup;
struct sigaction sa_stop;
struct sigaction sa_child;
signal(SIGPIPE, SIG_IGN);
signal(SIGCHLD, SIG_IGN); /* one child per connection, no zombies */
memset(&sa_child, 0, sizeof(sa_child));
sa_child.sa_handler = on_child;
sigemptyset(&sa_child.sa_mask);
sa_child.sa_flags = 0; /* accept() returns EINTR on child exit */
sigaction(SIGCHLD, &sa_child, NULL);
memset(&sa_hup, 0, sizeof(sa_hup));
sa_hup.sa_handler = on_hup;
sigemptyset(&sa_hup.sa_mask);
@@ -1011,6 +1035,10 @@ int apex_serve_proxy(int port)
int fd;
pid_t pid;
if (g_child_exit) {
g_child_exit = 0;
reap_children();
}
if (g_stop)
break;
if (g_rules_dirty) {
@@ -1023,14 +1051,27 @@ int apex_serve_proxy(int port)
continue;
break;
}
reap_children();
if (g_rules_dirty) {
g_rules_dirty = 0;
reload_rules();
}
if (g_children >= g_cfg.proxy_max_children) {
char why[160];
snprintf(why, sizeof(why),
"proxy busy: %d connection(s) open, limit %d",
g_children, g_cfg.proxy_max_children);
apex_audit("proxy", "127.0.0.1", 0, 0, why, NULL);
reply_error(fd, 503, "Service Unavailable", why);
close(fd);
continue;
}
/*
* One child per connection: a CONNECT tunnel must not block the
* next request. The traffic store reserves ids with O_EXCL, so
* children can record at the same time.
* children can record at the same time. The child count is
* bounded; SIGCHLD reaps and frees a slot.
*/
pid = fork();
if (pid == 0) {
@@ -1040,6 +1081,7 @@ int apex_serve_proxy(int port)
exit(0);
}
if (pid > 0) {
g_children++;
close(fd);
continue;
}
+24 -4
View File
@@ -46,12 +46,25 @@ void apex_json_str(mcp_buf *b, const char *s)
static void append_line(const char *path, const char *line, size_t len)
{
int fd;
char *buf;
/*
* One write call: the proxy records from several children, and a line
* split into two writes (text plus newline) lets another process slip
* in between, producing an audit line that is not valid JSON.
*/
fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0600);
if (fd < 0)
return;
(void)write(fd, line, len);
(void)write(fd, "\n", 1);
buf = malloc(len + 1);
if (buf == NULL) {
close(fd);
return;
}
memcpy(buf, line, len);
buf[len] = '\n';
(void)write(fd, buf, len + 1);
free(buf);
close(fd);
}
@@ -789,7 +802,8 @@ int apex_finding_update(const char *id, const char *status, const char *severity
int apex_audit_tail(mcp_buf *b, int limit)
{
FILE *f;
char line[8192];
char *line = NULL;
size_t cap = 0;
char **ring = NULL;
int count = 0;
int start;
@@ -802,7 +816,12 @@ int apex_audit_tail(mcp_buf *b, int limit)
return -1;
f = fopen(g_cfg.audit_file, "rb");
if (f != NULL) {
while (fgets(line, sizeof(line), f) != NULL) {
/*
* getline, not a fixed buffer: a guard command or a proxied request
* line can be longer than 8 KiB, and splitting it would hand the
* model half a JSON object.
*/
while (getline(&line, &cap, f) >= 0) {
size_t len = strlen(line);
while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r'))
@@ -813,6 +832,7 @@ int apex_audit_tail(mcp_buf *b, int limit)
ring[count % limit] = apex_strdup(line);
count++;
}
free(line);
fclose(f);
}
start = count > limit ? count - limit : 0;
+4 -2
View File
@@ -933,9 +933,11 @@ static void t_capabilities(mcp_conn *c, const mcp_json *args, void *user)
mcp_buf_puts(&b, "},\"scope_loaded\":");
mcp_buf_puts(&b, g_scope.loaded ? "true" : "false");
(void)apex_rewrite_load();
mcp_buf_printf(&b, ",\"rewrite_rules\":%d,\"webhook_configured\":%s}",
mcp_buf_printf(&b, ",\"rewrite_rules\":%d,\"webhook_configured\":%s,"
"\"proxy_max_children\":%d}",
apex_rewrite_count(),
g_cfg.webhook[0] != '\0' ? "true" : "false");
g_cfg.webhook[0] != '\0' ? "true" : "false",
g_cfg.proxy_max_children);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
+140 -1
View File
@@ -1745,6 +1745,142 @@ check("both concurrent exchanges were captured",
len(set(c["id"] for c in conc_list)) == len(conc_list), methods)
shutil.rmtree(conc_home, ignore_errors=True)
print("\n== proxy connection cap ==")
cap_started = []
cap_lock = threading.Lock()
class _CapHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/slow":
with cap_lock:
cap_started.append(1)
time.sleep(3.0)
body = b"slow"
else:
body = b"ok"
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
cap_origin = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _CapHandler)
cap_origin_port = cap_origin.server_address[1]
threading.Thread(target=cap_origin.serve_forever, daemon=True).start()
cap_home = tempfile.mkdtemp(prefix="apex-cap-")
write_scope(cap_home, {"label": "cap", "expires": "2099-12-31T23:59:59Z",
"allow_private": True, "allow_ip": ["127.0.0.1"],
"allow_port": [str(cap_origin_port)]})
cap_port = free_port()
capenv = dict(env)
capenv["APEX_HOME"] = cap_home
capenv["APEX_PROXY_MAX_CHILDREN"] = "2"
cap_srv = subprocess.Popen([BIN, "--proxy", str(cap_port)], env=capenv,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True)
deadline = time.time() + 10
cup = False
while time.time() < deadline:
probe = socket.socket()
try:
probe.connect(("127.0.0.1", cap_port))
cup = True
probe.close()
break
except OSError:
probe.close()
time.sleep(0.1)
check("cap proxy came up", cup, cap_port)
def cap_get(path, timeout=5):
s = socket.create_connection(("127.0.0.1", cap_port), timeout=timeout)
s.sendall(("GET http://127.0.0.1:%d%s HTTP/1.1\r\n"
"Host: 127.0.0.1:%d\r\n"
"Connection: close\r\n\r\n" %
(cap_origin_port, path, cap_origin_port)).encode())
s.settimeout(timeout)
out = b""
try:
while True:
chunk = s.recv(65536)
if not chunk:
break
out += chunk
except ConnectionResetError:
pass
except socket.timeout:
out += b"<TIMEOUT>"
s.close()
return out
slow_results = []
def slow_get():
last = b""
for _ in range(20):
last = cap_get("/slow", 10)
if b" 200 " in last.split(b"\r\n")[0]:
slow_results.append(last)
return
time.sleep(0.1)
slow_results.append(last)
slow_threads = [threading.Thread(target=slow_get) for _ in range(2)]
try:
time.sleep(0.4) # let the readiness probe's child be reaped
for t in slow_threads:
t.start()
deadline = time.time() + 8
while time.time() < deadline:
with cap_lock:
started = len(cap_started)
if started >= 2 and len(slow_results) == 0:
break
time.sleep(0.02)
busy = cap_get("/", 3)
check("a third connection is refused at the cap",
busy.startswith(b"HTTP/1.1 503") and b"proxy busy" in busy,
busy[:120])
for t in slow_threads:
t.join(timeout=10)
check("both in-flight requests completed",
len(slow_results) == 2 and
all(b" 200 " in r.split(b"\r\n")[0] and b"slow" in r
for r in slow_results), slow_results)
freed = b""
deadline = time.time() + 5
while time.time() < deadline:
freed = cap_get("/", 3)
if b" 200 " in freed.split(b"\r\n")[0]:
break
time.sleep(0.1)
check("a slot is freed after the children exit",
b" 200 " in freed.split(b"\r\n")[0], freed[:120])
finally:
cap_srv.terminate()
try:
cap_srv.wait(timeout=5)
except subprocess.TimeoutExpired:
cap_srv.kill()
cap_origin.shutdown()
cap_origin.server_close()
res, _ = run([call(1, "audit_log", limit=200)], home=cap_home)
cap_audit = json.loads(text(res[0]))
check("the busy refusal is audited",
any(e["tool"] == "proxy" and e["decision"] == "deny" and
"proxy busy" in e["reason"] for e in cap_audit),
[e for e in cap_audit if e["tool"] == "proxy"][:3])
shutil.rmtree(cap_home, ignore_errors=True)
# ------------------------------------------------------------- serial guard
print("\n== serial guard ==")
fake = os.path.join(ROOT, "notamodem")
@@ -1778,6 +1914,8 @@ chk, _ = check_json()
check("--check counts the rewrite rules", chk["rewrite_rules"] == 2, chk)
check("--check reports webhook_configured=false",
chk["webhook_configured"] is False, chk)
check("--check reports the proxy child limit",
chk["proxy_max_children"] == 64, chk)
chk_hook, out_hook = check_json({"APEX_WEBHOOK": "http://127.0.0.1:9/hook"})
check("--check reports the webhook", chk_hook["webhook_configured"] is True,
chk_hook)
@@ -1787,7 +1925,8 @@ res, _ = run([call(1, "capabilities")], home=ops_home,
extra_env={"APEX_WEBHOOK": "http://127.0.0.1:9/hook"})
caps = json.loads(text(res[0]))
check("capabilities reports the operational state",
caps["rewrite_rules"] == 2 and caps["webhook_configured"] is True, caps)
caps["rewrite_rules"] == 2 and caps["webhook_configured"] is True and
caps["proxy_max_children"] == 64, caps)
check("capabilities does not leak the webhook URL",
"127.0.0.1:9" not in text(res[0]), text(res[0])[:200])
with open(os.path.join(ops_home, "rewrite.json"), "w") as f: