apex-twin 0.28.0: bound the MCP HTTP face and time out half requests

The HTTP face forked a child per connection without a limit and read the head
with a blocking read, so a local client could hold children forever.

- APEX_HTTP_MAX_CHILDREN (default 64, max 1024) with a SIGCHLD handler,
  waitpid(WNOHANG) reaping and a counter. At the cap the parent answers 503
  'http busy' and audits it; a failed fork serves in the parent.
- APEX_HTTP_HEAD_TIMEOUT_MS (default 20000, 0 disables) is a deadline for the
  whole head and body using poll with the remaining time; expiry answers 408
  Request Timeout.
- Rejections (503, 408) half-close and drain what the client already sent before
  closing: closing with unread bytes sends RST and can swallow the response.
  http_send now has reason phrases for 408 and 503.
- --check and capabilities report both values.

Tests: cap of 1 with a held partial request -> second gets 503 'http busy';
after closing, the slot is reused and a valid initialize gets 200. A 500 ms head
timeout closes a half-sent head with 408 in under 2.5 s. Red proof: disabling
both turns those two checks red.

327 checks, coverage 76.9%, release-check green including distcheck.
This commit is contained in:
lotherk committed 2026-11-21 09:27:32 +00:00
1 parent f44df202ba
commit d4192f95e1
9 files changed
+312 -22

No files matched your search

+14 -1
View File
@@ -8,7 +8,20 @@ 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.27.0 — 2026-11-21 — this change
## 0.28.0 — 2026-11-21 — this change
- The MCP HTTP face is bounded like the proxy: `APEX_HTTP_MAX_CHILDREN` (default
64, max 1024) with SIGCHLD reaping and a 503 `http busy` + audit at the cap.
- `APEX_HTTP_HEAD_TIMEOUT_MS` (default 20000) bounds the whole request head and
body with a poll deadline; a half-sent request is answered 408 and closed.
Rejections half-close and drain before close so the response is not lost to
RST. `--check` and `capabilities` report both values.
- Tests: with a cap of 1 a held partial request makes the second answer 503, and
the slot is reused after close; with a 500 ms head timeout a half-sent head is
closed with 408 in under 2.5 s. Red proof: disabling both turns the two checks
red.
## 0.27.0 — 2026-11-21 — f44df20
- `audit.log` rotates to `audit.log.1` when it reaches `APEX_AUDIT_MAX_BYTES`
(default 10 MiB, `0` disables). The size is checked again under
+14 -7
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 + 323 end-to-end checks, no mocks
make test # gate audit + 327 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
@@ -302,14 +302,19 @@ apex-twin --check # scope, tools, rewrite rules, webhook, child limit, e
```
HTTP and the proxy bind **loopback only**. A service that can scan and transmit
must not appear on a LAN by accident; reach it through a tunnel.
must not appear on a LAN by accident; reach it through a tunnel. The HTTP face
bounds itself: at most `APEX_HTTP_MAX_CHILDREN` (default 64) connections are
served at once (503 `http busy` beyond), and a request head must arrive within
`APEX_HTTP_HEAD_TIMEOUT_MS` (default 20000) or the connection is answered with
408 and closed.
`systemd/apex-twin.service` and `systemd/apex-twin-proxy.service` run exactly
that: loopback ports, a 0700 state dir, `dialout` for the radio, and a capability
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),
`proxy_max_children`, `audit_max_bytes` and the loaded scope, alongside the version and tool count.
`proxy_max_children`, `audit_max_bytes`, `http_max_children`,
`http_head_timeout_ms` and the loaded scope, alongside the version and tool count.
`capabilities` returns the same fields to the model.
## The radio
@@ -344,6 +349,8 @@ APEX_SERIAL=/dev/ttyACM0 APEX_BAUD=115200
| `APEX_REWRITE` | `$APEX_HOME/rewrite.json` | proxy rewrite rules (SIGHUP reloads) |
| `APEX_PROXY_MAX_CHILDREN` | `64` | concurrent proxy connections before 503 |
| `APEX_AUDIT_MAX_BYTES` | `10485760` | rotate `audit.log` to `.1`; `0` disables |
| `APEX_HTTP_MAX_CHILDREN` | `64` | concurrent MCP HTTP connections before 503 |
| `APEX_HTTP_HEAD_TIMEOUT_MS` | `20000` | request head/body deadline; `0` disables |
## Files it writes
@@ -372,7 +379,7 @@ finding and the next report no longer mentions it.
make test
```
323 checks, real binary, real DNS, real files written; no mocks. The suite was
327 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
@@ -403,7 +410,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 323 checks pass with no ASan or UBSan report,
`-fsanitize=address,undefined`. All 327 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
@@ -462,7 +469,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 **77.1%** —
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
`tools_radio.c` from 31.7% to 76.2% without hardware: firmware `info`/`help`,
@@ -474,7 +481,7 @@ the copied scope reason is now bounded with a precision, not left to snprintf.
## Status
0.27.0. Built and run: 45 tools, 323 checks, 340 fuzz cases and 77.1% line
0.28.0. Built and run: 45 tools, 327 checks, 340 fuzz cases and 76.9% 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
+6 -3
View File
@@ -72,9 +72,12 @@ only narrow what the proxy does (the scope gate still runs first).
stored as bytes. The program does not execute target content.
- **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 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,
- **Denial of service from a local client.** The proxy and the HTTP face fork a
child per connection and cap them (`APEX_PROXY_MAX_CHILDREN` and
`APEX_HTTP_MAX_CHILDREN`, default 64 each, max 1024); beyond that they answer
503 and audit. The HTTP face also enforces a head/body deadline
(`APEX_HTTP_HEAD_TIMEOUT_MS`, default 20 s) so half a request cannot hold a
child forever. 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
+5 -1
View File
@@ -14,7 +14,9 @@ check when something refuses.
| Diagnostics | `apex-twin --check` | none, prints JSON and exits |
Both listeners bind loopback only on purpose. Reach them through an SSH tunnel
or a VPN; never put them on a LAN interface.
or a VPN; never put them on a LAN interface. The HTTP face serves at most
`APEX_HTTP_MAX_CHILDREN` connections at once (503 beyond) and closes a request
whose head or body does not arrive within `APEX_HTTP_HEAD_TIMEOUT_MS`.
## Install
@@ -201,6 +203,8 @@ of that file — back up first.
| Radio scan | 3–300 s, always ends with `stopscan` |
| Concurrent proxy connections | `APEX_PROXY_MAX_CHILDREN`, default 64, 503 beyond |
| Audit file size | `APEX_AUDIT_MAX_BYTES`, default 10 MiB, rotates to `.1` |
| Concurrent HTTP connections | `APEX_HTTP_MAX_CHILDREN`, default 64, 503 beyond |
| HTTP request deadline | `APEX_HTTP_HEAD_TIMEOUT_MS`, default 20000 |
## Troubleshooting
+145 -6
View File
@@ -16,11 +16,14 @@
*/
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <unistd.h>
@@ -34,6 +37,8 @@
static mcp_server g_srv;
static mcp_tool g_tools[64];
static volatile sig_atomic_t g_http_stop;
static volatile sig_atomic_t g_http_child_exit;
static int g_http_children;
static void on_http_stop(int sig)
{
@@ -41,6 +46,57 @@ static void on_http_stop(int sig)
g_http_stop = 1;
}
static void on_http_child(int sig)
{
(void)sig;
g_http_child_exit = 1;
}
static void reap_http_children(void)
{
int status;
while (waitpid(-1, &status, WNOHANG) > 0) {
if (g_http_children > 0)
g_http_children--;
}
}
static long mono_ms(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000L + tv.tv_usec / 1000;
}
/*
* Send the answer, half-close, and drain what the client already sent before
* closing. Closing with unread bytes makes the kernel send RST, which can
* discard the response the client has not read yet - a busy 503 must arrive.
*/
static void http_finish(int fd)
{
long start = mono_ms();
(void)shutdown(fd, SHUT_WR);
while (mono_ms() - start < 200) {
struct pollfd pfd;
char tmp[4096];
int pr;
pfd.fd = fd;
pfd.events = POLLIN;
pfd.revents = 0;
pr = poll(&pfd, 1, 50);
if (pr <= 0)
break;
if (read(fd, tmp, sizeof(tmp)) <= 0)
break;
}
close(fd);
}
static void build_tools(void)
{
size_t n = 0;
@@ -112,8 +168,12 @@ static void http_send(int fd, int code, const char *ctype, const char *body,
reason = "Not Found";
else if (code == 405)
reason = "Method Not Allowed";
else if (code == 408)
reason = "Request Timeout";
else if (code == 413)
reason = "Payload Too Large";
else if (code == 503)
reason = "Service Unavailable";
mcp_buf_init(&out);
mcp_buf_printf(&out, "HTTP/1.1 %d %s\r\n", code, reason);
@@ -143,12 +203,43 @@ static void serve_one(int fd, const char *session)
long clen = 0;
char *body = NULL;
char *reply;
long deadline;
mcp_buf_init(&head);
deadline = g_cfg.http_head_timeout_ms > 0
? mono_ms() + g_cfg.http_head_timeout_ms : 0;
while (!done) {
ssize_t r = read(fd, buf, sizeof(buf));
ssize_t r;
char *sep;
if (deadline > 0) {
long wait = deadline - mono_ms();
struct pollfd pfd;
int pr;
if (wait <= 0) {
http_send(fd, 408, "text/plain", "request timeout\n", 16, NULL);
mcp_buf_free(&head);
http_finish(fd);
return;
}
pfd.fd = fd;
pfd.events = POLLIN;
pfd.revents = 0;
pr = poll(&pfd, 1, (int)wait);
if (pr == 0) {
http_send(fd, 408, "text/plain", "request timeout\n", 16, NULL);
mcp_buf_free(&head);
http_finish(fd);
return;
}
if (pr < 0) {
if (errno == EINTR)
continue;
break;
}
}
r = read(fd, buf, sizeof(buf));
if (r <= 0)
break;
mcp_buf_add(&head, buf, (size_t)r);
@@ -185,8 +276,40 @@ static void serve_one(int fd, const char *session)
have = (size_t)clen;
memcpy(body, head.p + hlen, have);
while (have < (size_t)clen) {
ssize_t r2 = read(fd, body + have, (size_t)clen - have);
ssize_t r2;
if (deadline > 0) {
long wait = deadline - mono_ms();
struct pollfd pfd;
int pr;
if (wait <= 0) {
http_send(fd, 408, "text/plain",
"request timeout\n", 16, NULL);
free(body);
mcp_buf_free(&head);
http_finish(fd);
return;
}
pfd.fd = fd;
pfd.events = POLLIN;
pfd.revents = 0;
pr = poll(&pfd, 1, (int)wait);
if (pr == 0) {
http_send(fd, 408, "text/plain",
"request timeout\n", 16, NULL);
free(body);
mcp_buf_free(&head);
http_finish(fd);
return;
}
if (pr < 0) {
if (errno == EINTR)
continue;
break;
}
}
r2 = read(fd, body + have, (size_t)clen - have);
if (r2 <= 0)
break;
have += (size_t)r2;
@@ -273,6 +396,8 @@ static int serve_http(int port)
sa.sa_flags = 0; /* accept() returns EINTR on SIGTERM */
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
sa.sa_handler = on_http_child;
sigaction(SIGCHLD, &sa, NULL);
}
ls = socket(AF_INET, SOCK_STREAM, 0);
if (ls < 0) {
@@ -296,31 +421,43 @@ static int serve_http(int port)
close(ls);
return 1;
}
signal(SIGCHLD, SIG_IGN);
fprintf(stderr, "apex-twin: http mcp on 127.0.0.1:%d (session %s)\n", port,
session);
for (;;) {
int fd;
pid_t pid;
if (g_http_child_exit) {
g_http_child_exit = 0;
reap_http_children();
}
if (g_http_stop)
break;
fd = accept(ls, NULL, NULL);
if (fd < 0)
continue;
reap_http_children();
if (g_http_stop) {
close(fd);
break;
}
if (g_http_children >= g_cfg.http_max_children) {
http_send(fd, 503, "text/plain", "http busy\n", 10, NULL);
apex_audit("http", "127.0.0.1", 0, 0,
"http busy: connection limit reached", NULL);
http_finish(fd);
continue;
}
pid = fork();
if (pid == 0) {
close(ls);
serve_one(fd, session);
exit(0);
}
if (pid > 0)
if (pid > 0) {
g_http_children++;
close(fd);
else
} else
serve_one(fd, session);
}
close(ls);
@@ -358,11 +495,13 @@ int main(int argc, char **argv)
printf("{\"version\":\"%s\",\"tools\":%lu,\"home\":\"%s\","
"\"rewrite_rules\":%d,\"webhook_configured\":%s,"
"\"proxy_max_children\":%d,\"audit_max_bytes\":%d,"
"\"http_max_children\":%d,\"http_head_timeout_ms\":%d,"
"\"scope\":%s}\n", APEX_VERSION,
(unsigned long)g_srv.ntools, g_cfg.home,
apex_rewrite_count(),
g_cfg.webhook[0] != '\0' ? "true" : "false",
g_cfg.proxy_max_children, g_cfg.audit_max_bytes, b.p);
g_cfg.proxy_max_children, g_cfg.audit_max_bytes,
g_cfg.http_max_children, g_cfg.http_head_timeout_ms, b.p);
mcp_buf_free(&b);
return 0;
}
+3 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "0.27.0"
#define APEX_VERSION "0.28.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
@@ -76,6 +76,8 @@ typedef struct {
int default_timeout_ms;
int max_timeout_ms;
int audit_max_bytes;
int http_max_children;
int http_head_timeout_ms;
size_t max_output;
int dry_run;
} apex_cfg;
+12
View File
@@ -166,6 +166,8 @@ void apex_config_init(void)
g_cfg.default_timeout_ms = 60000;
g_cfg.max_timeout_ms = 900000;
g_cfg.audit_max_bytes = 10 * 1024 * 1024;
g_cfg.http_max_children = 64;
g_cfg.http_head_timeout_ms = 20000;
g_cfg.max_output = APEX_MAX_OUT;
g_cfg.dry_run = 0;
@@ -174,6 +176,16 @@ void apex_config_init(void)
env_int("APEX_AUDIT_MAX_BYTES", &g_cfg.audit_max_bytes);
if (g_cfg.audit_max_bytes < 0)
g_cfg.audit_max_bytes = 0;
env_int("APEX_HTTP_MAX_CHILDREN", &g_cfg.http_max_children);
if (g_cfg.http_max_children <= 0)
g_cfg.http_max_children = 64;
if (g_cfg.http_max_children > 1024)
g_cfg.http_max_children = 1024;
env_int("APEX_HTTP_HEAD_TIMEOUT_MS", &g_cfg.http_head_timeout_ms);
if (g_cfg.http_head_timeout_ms < 0)
g_cfg.http_head_timeout_ms = 0;
if (g_cfg.http_head_timeout_ms > 3600000)
g_cfg.http_head_timeout_ms = 3600000;
env_int("APEX_BAUD", &g_cfg.baud);
g_cfg.proxy_max_children = 64;
env_int("APEX_PROXY_MAX_CHILDREN", &g_cfg.proxy_max_children);
+4 -2
View File
@@ -954,10 +954,12 @@ static void t_capabilities(mcp_conn *c, const mcp_json *args, void *user)
mcp_buf_puts(&b, g_scope.loaded ? "true" : "false");
(void)apex_rewrite_load();
mcp_buf_printf(&b, ",\"rewrite_rules\":%d,\"webhook_configured\":%s,"
"\"proxy_max_children\":%d,\"audit_max_bytes\":%d}",
"\"proxy_max_children\":%d,\"audit_max_bytes\":%d,"
"\"http_max_children\":%d,\"http_head_timeout_ms\":%d}",
apex_rewrite_count(),
g_cfg.webhook[0] != '\0' ? "true" : "false",
g_cfg.proxy_max_children, g_cfg.audit_max_bytes);
g_cfg.proxy_max_children, g_cfg.audit_max_bytes,
g_cfg.http_max_children, g_cfg.http_head_timeout_ms);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
+109 -1
View File
@@ -1311,6 +1311,109 @@ finally:
except subprocess.TimeoutExpired:
srv.kill()
print("\n== http limits ==")
def start_http(extra):
port = free_port()
e = dict(env)
e.update(extra)
proc = subprocess.Popen([BIN, "--http", str(port)], env=e,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True)
deadline = time.time() + 10
while time.time() < deadline:
probe = socket.socket()
try:
probe.connect(("127.0.0.1", port))
probe.close()
return proc, port
except OSError:
probe.close()
time.sleep(0.05)
return proc, port
def http_raw(port, raw, timeout=3):
s = socket.create_connection(("127.0.0.1", port), timeout=timeout)
s.sendall(raw)
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
init = b'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}'
post = ("POST /mcp HTTP/1.1\r\nHost: x\r\nContent-Length: %d\r\n"
"Connection: close\r\n\r\n" % len(init)).encode() + init
cap_proc, cap_port = start_http({"APEX_HTTP_MAX_CHILDREN": "1",
"APEX_HTTP_HEAD_TIMEOUT_MS": "5000"})
try:
time.sleep(0.4)
held = socket.create_connection(("127.0.0.1", cap_port), timeout=5)
held.sendall(b"POST /mcp HTTP/1.1\r\nHost: x\r\n")
time.sleep(0.2)
busy = http_raw(cap_port, post)
check("a second HTTP request is refused at the cap",
busy.startswith(b"HTTP/1.1 503") and b"http busy" in busy,
busy[:120])
held.close()
freed = b""
deadline = time.time() + 5
while time.time() < deadline:
freed = http_raw(cap_port, post)
if b" 200 " in freed.split(b"\r\n")[0]:
break
time.sleep(0.1)
check("the HTTP slot is freed after the child exits",
b" 200 " in freed.split(b"\r\n")[0], freed[:120])
finally:
cap_proc.terminate()
try:
cap_proc.wait(timeout=5)
except subprocess.TimeoutExpired:
cap_proc.kill()
time_proc, time_port = start_http({"APEX_HTTP_MAX_CHILDREN": "4",
"APEX_HTTP_HEAD_TIMEOUT_MS": "500"})
try:
slow = socket.create_connection(("127.0.0.1", time_port), timeout=5)
slow.sendall(b"POST /mcp HTTP/1.1\r\nHost: x\r\n")
started = time.time()
slow.settimeout(3)
got = b""
try:
while True:
chunk = slow.recv(4096)
if not chunk:
break
got += chunk
except ConnectionResetError:
pass
except socket.timeout:
got += b"<TIMEOUT>"
elapsed = time.time() - started
slow.close()
check("a half-sent head is closed at the head timeout",
got.startswith(b"HTTP/1.1 408") and elapsed < 2.5,
(got[:60], elapsed))
finally:
time_proc.terminate()
try:
time_proc.wait(timeout=5)
except subprocess.TimeoutExpired:
time_proc.kill()
print("\n== proxy ==")
pport = free_port()
psrv = subprocess.Popen([BIN, "--proxy", str(pport)], env=env,
@@ -1993,6 +2096,9 @@ check("--check reports the proxy child limit",
chk["proxy_max_children"] == 64, chk)
check("--check reports the audit rotation size",
chk["audit_max_bytes"] == 10485760, chk)
check("--check reports the HTTP limits",
chk["http_max_children"] == 64 and
chk["http_head_timeout_ms"] == 20000, 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)
@@ -2004,7 +2110,9 @@ caps = json.loads(text(res[0]))
check("capabilities reports the operational state",
caps["rewrite_rules"] == 2 and caps["webhook_configured"] is True and
caps["proxy_max_children"] == 64 and
caps["audit_max_bytes"] == 10485760, caps)
caps["audit_max_bytes"] == 10485760 and
caps["http_max_children"] == 64 and
caps["http_head_timeout_ms"] == 20000, 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: