apex-twin 0.17.0: forward chunked request bodies through the proxy

Transfer-Encoding: chunked is no longer 501. The proxy reads the chunk framing
(hex size with extensions, data, CRLF, trailers), validates it, and relays it
unchanged so the origin still receives chunked encoding:

- payload cap 1 MiB, checked from the chunk size before reading the data, so a
  declared gigabyte costs one line; over the cap -> 413.
- malformed size or framing -> 400. Both answers happen before the origin socket
  is opened, so a broken body never becomes half a request to someone else.
- the raw capture keeps the chunk framing (Transfer-Encoding header, size lines,
  data, trailers), so traffic_read shows what was actually sent.
- Content-Length is dropped when chunked is present (TE wins); the old 501 branch
  and its comment are gone.

Tests use a local origin that decodes chunked: 5+6 bytes become 'hello world',
a body split across two writes works, 0x200000 answers 413, 'ZZ' answers 400,
and the traffic record contains the framing. Red proof: forcing
r->chunked = 0 turned seven checks red.

276 checks, coverage 74.1% (make coverage re-run).
This commit is contained in:
lotherk committed 2026-11-21 07:50:55 +00:00
1 parent a04b072e8f
commit a00bcdb90c
5 files changed
+349 -40

No files matched your search

+21 -12
View File
@@ -18,7 +18,7 @@ separate, explicitly armed switch.
```sh
make # apex-twin, ~239 kB static-ish binary, zero warnings under -Werror
make test # 267 end-to-end checks, no mocks
make test # 276 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
@@ -182,6 +182,14 @@ line to `audit.log`. The applied rule is named in the traffic record and audited
rules stay active. The scope gate still runs first: a rule can only narrow what
the proxy does, never widen the engagement.
Request bodies with `Content-Length` are forwarded as before. `Transfer-Encoding:
chunked` is read chunk by chunk — hex size, CRLF framing, extensions and
trailers — validated against a 1 MiB payload cap and relayed unchanged, so the
origin still receives chunked encoding. Over the cap answers `413`, a malformed
size or framing answers `400`, and both are decided before the origin socket is
opened. The raw capture keeps the chunk framing, so `traffic_read` shows what was
actually sent.
## Checks that end in a finding
Three web checks exist because the header audit alone leaves money on the table:
@@ -330,7 +338,7 @@ finding and the next report no longer mentions it.
make test
```
267 checks, real binary, real DNS, real files written; no mocks. The suite was
276 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
@@ -361,7 +369,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 267 checks pass with no ASan or UBSan report,
`-fsanitize=address,undefined`. All 276 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
@@ -401,7 +409,7 @@ 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%** —
The first measured pass was 55.9%; the gap tests brought it to **74.1%** —
`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
@@ -410,18 +418,19 @@ the copied scope reason is now bounded with a precision, not left to snprintf.
## Status
0.16.0. Built and run: 45 tools, 267 checks, 340 fuzz cases and 73.4% line
0.17.0. Built and run: 45 tools, 276 checks, 340 fuzz cases and 74.1% 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.
the same gate in front of curl and a browser, forwards chunked and
Content-Length bodies, and takes rewrite rules that can set or remove a header
or block a path; `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.
+1 -1
View File
@@ -22,7 +22,7 @@ module, deliberately left out, or still open.
| Asset inventory (`server/assets*.go`) | `src/store.c` assets + `asset_*` | One file per target, merged by target, gated on add |
| Traffic archive (`traffic/`) | `src/store.c` traffic + `http_capture`/`traffic_*` | Request/response pair on disk; a capture is a proof |
| Notifications (`notify/`) | `src/notify.c`, `notify_test` | Webhook via curl, severity floor, fire-and-forget, audited; not gated (operator infrastructure) |
| Intercepting proxy (`intercept/`, `traffic/proxy.go`) | `src/proxy.c`, `--proxy` | Loopback forward proxy, gate before connect, HTTP captured, CONNECT tunnelled blind; no TLS interception |
| Intercepting proxy (`intercept/`, `traffic/proxy.go`) | `src/proxy.c`, `--proxy` | Loopback forward proxy, gate before connect, HTTP captured (Content-Length and chunked bodies), CONNECT tunnelled blind; no TLS interception |
| Request rewriting (`traffic/rewrite`, `intercept`) | `src/rewrite.c`, `rewrite.json` | Ordered host/path rules: set/remove headers or block, first match, SIGHUP reload, rule named in traffic and audit; scope still first |
| Report export (`report/findings.go`) | `tools_report.c` `report_markdown` | Markdown and CSV, severity-sorted, severity and lifecycle tables, optional asset table |
| Budgets / timeouts (`agent/budget.go`) | `APEX_DEFAULT_TIMEOUT_MS`, `APEX_MAX_TIMEOUT_MS` | Per-tool timeout, process-group kill |
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "0.16.0"
#define APEX_VERSION "0.17.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+190 -26
View File
@@ -439,7 +439,7 @@ static int parse_request(const char *head, proxy_req *r)
if (header_value(head, "transfer-encoding", te, sizeof(te)) &&
ci_prefix(te, "chunked"))
return -4;
r->chunked = 1;
}
return 0;
}
@@ -480,6 +480,9 @@ static void build_forward(const char *head, int head_end, const proxy_req *r,
continue;
if (ci_prefix(line, "host:"))
had_host = 1;
/* Transfer-Encoding wins over Content-Length; do not forward both */
if (r->chunked && ci_prefix(line, "content-length:"))
continue;
mcp_buf_puts(out, line);
mcp_buf_puts(out, "\r\n");
}
@@ -613,6 +616,140 @@ static void handle_connect(int cfd, const proxy_req *r, const char *line)
}
}
/* ---------------------------------------------------------- chunked body */
typedef struct {
int fd;
const unsigned char *pre;
size_t pre_len;
size_t pre_off;
} chunk_reader;
static int cr_read(chunk_reader *cr, void *dst, size_t n)
{
unsigned char *d = dst;
size_t got = 0;
while (got < n && cr->pre_off < cr->pre_len)
d[got++] = cr->pre[cr->pre_off++];
if (got < n)
return read_into(cr->fd, (char *)d + got, n - got, PROXY_READ_MS);
return 0;
}
/* One line including its terminator, so the raw chunked body stays raw. */
static int cr_line(chunk_reader *cr, char *buf, size_t cap, size_t *len)
{
size_t used = 0;
for (;;) {
unsigned char c;
if (cr_read(cr, &c, 1) != 0)
return -1;
if (used + 1 >= cap)
return -1;
buf[used++] = (char)c;
if (c == '\n')
break;
}
*len = used;
return 0;
}
/*
* Read a chunked body the way the client framed it and copy every byte of that
* framing into out. Payload is capped by PROXY_BODY_MAX; the cap is checked
* from the chunk size before the data is read, so a declared 1 GiB chunk costs
* one line, not a gigabyte. Returns -1 on malformed framing, sets *too_large
* when a limit was hit.
*/
static int read_chunked_body(chunk_reader *cr, mcp_buf *out, int *too_large)
{
size_t payload = 0;
for (;;) {
char line[512];
char copy[512];
size_t len = 0;
size_t size = 0;
size_t i;
int digits = 0;
if (cr_line(cr, line, sizeof(line), &len) != 0)
return -1;
if (out->len + len > PROXY_BODY_MAX + 65536) {
*too_large = 1;
return 0;
}
mcp_buf_add(out, line, len);
memcpy(copy, line, len);
copy[len] = '\0';
for (i = 0; i < len && isxdigit((unsigned char)copy[i]); i++) {
int d = isdigit((unsigned char)copy[i])
? copy[i] - '0'
: tolower((unsigned char)copy[i]) - 'a' + 10;
size = size * 16 + (size_t)d;
digits++;
if (size > PROXY_BODY_MAX)
break;
}
if (digits == 0)
return -1;
if (size > PROXY_BODY_MAX) {
*too_large = 1;
return 0;
}
if (size == 0) {
/* trailers, terminated by an empty line */
for (;;) {
if (cr_line(cr, line, sizeof(line), &len) != 0)
return -1;
if (out->len + len > PROXY_BODY_MAX + 65536) {
*too_large = 1;
return 0;
}
mcp_buf_add(out, line, len);
if ((len == 2 && line[0] == '\r' && line[1] == '\n') ||
(len == 1 && line[0] == '\n'))
return 0;
}
}
if (payload + size > PROXY_BODY_MAX) {
*too_large = 1;
return 0;
}
payload += size;
{
size_t left = size;
while (left > 0) {
char tmp[8192];
size_t n = left < sizeof(tmp) ? left : sizeof(tmp);
if (cr_read(cr, tmp, n) != 0)
return -1;
if (out->len + n > PROXY_BODY_MAX + 65536) {
*too_large = 1;
return 0;
}
mcp_buf_add(out, tmp, n);
left -= n;
}
}
{
char crlf[2];
if (cr_read(cr, crlf, 2) != 0)
return -1;
if (crlf[0] != '\r' || crlf[1] != '\n')
return -1;
mcp_buf_add(out, crlf, 2);
}
}
}
static void handle_forward(int cfd, const char *head, int head_end,
size_t total, const proxy_req *r, const char *line)
{
@@ -620,11 +757,14 @@ static void handle_forward(int cfd, const char *head, int head_end,
int ofd;
int rule;
mcp_buf req;
mcp_buf body;
size_t prefix;
size_t remaining;
char *resp;
size_t rlen = 0;
char note[320];
int bad = 0;
int too_large = 0;
if (!proxy_gate(r->host, r->port, line, reason, sizeof(reason))) {
reply_error(cfd, 403, "Forbidden", reason);
@@ -640,8 +780,54 @@ static void handle_forward(int cfd, const char *head, int head_end,
reply_error(cfd, 403, "Forbidden", why);
return;
}
/*
* Read and validate the whole request body before the origin is opened:
* a malformed chunked body should be a 400 to the client, not a half
* request sent to someone else.
*/
mcp_buf_init(&body);
prefix = total > (size_t)head_end ? total - (size_t)head_end : 0;
if (r->chunked) {
chunk_reader cr = { cfd, (const unsigned char *)head + head_end,
prefix, 0 };
if (read_chunked_body(&cr, &body, &too_large) != 0)
bad = 1;
} else {
if (prefix > (size_t)r->content_length)
prefix = (size_t)r->content_length;
if (prefix > 0)
mcp_buf_add(&body, head + head_end, prefix);
remaining = (size_t)r->content_length - prefix;
while (remaining > 0) {
char tmp[8192];
size_t n = remaining < sizeof(tmp) ? remaining : sizeof(tmp);
if (read_into(cfd, tmp, n, PROXY_READ_MS) != 0) {
bad = 1;
break;
}
mcp_buf_add(&body, tmp, n);
remaining -= n;
}
}
if (too_large) {
mcp_buf_free(&body);
reply_error(cfd, 413, "Payload Too Large",
"request body over the proxy limit");
return;
}
if (bad) {
mcp_buf_free(&body);
reply_error(cfd, 400, "Bad Request",
"incomplete or malformed request body");
return;
}
ofd = tcp_connect_host(r->host, r->port, PROXY_ORIGIN_MS);
if (ofd < 0) {
mcp_buf_free(&body);
reply_error(cfd, 502, "Bad Gateway",
"cannot connect to the requested host");
return;
@@ -649,25 +835,9 @@ static void handle_forward(int cfd, const char *head, int head_end,
mcp_buf_init(&req);
build_forward(head, head_end, r, &req, rule);
prefix = total > (size_t)head_end ? total - (size_t)head_end : 0;
if (prefix > (size_t)r->content_length)
prefix = (size_t)r->content_length;
if (prefix > 0)
mcp_buf_add(&req, head + head_end, prefix);
remaining = (size_t)r->content_length - prefix;
while (remaining > 0) {
char tmp[8192];
size_t chunk = remaining < sizeof(tmp) ? remaining : sizeof(tmp);
if (read_into(cfd, tmp, chunk, PROXY_READ_MS) != 0) {
mcp_buf_free(&req);
close(ofd);
reply_error(cfd, 400, "Bad Request", "incomplete request body");
return;
}
mcp_buf_add(&req, tmp, chunk);
remaining -= chunk;
}
if (body.len > 0)
mcp_buf_add(&req, body.p, body.len);
mcp_buf_free(&body);
if (send_all(ofd, req.p, req.len) != 0)
fprintf(stderr, "apex-twin: proxy write to origin failed\n");
@@ -760,12 +930,6 @@ static void handle_client(int cfd)
free(head);
return;
}
if (pr == -4) {
reply_error(cfd, 501, "Not Implemented",
"chunked request bodies are not supported");
free(head);
return;
}
if (pr != 0) {
reply_error(cfd, 400, "Bad Request", "cannot parse the request line");
free(head);
+136
View File
@@ -1240,6 +1240,142 @@ check("rewrite allow and block are audited",
[e for e in rwa if e["tool"] == "rewrite"][:3])
shutil.rmtree(rw_home, ignore_errors=True)
print("\n== proxy chunked bodies ==")
def _read_chunked(rf):
out = b""
while True:
line = rf.readline()
if not line:
return out
size = int(line.split(b";")[0].strip() or b"0", 16)
if size == 0:
while True:
trailer = rf.readline()
if trailer in (b"\r\n", b"\n", b""):
return out
out += rf.read(size)
rf.read(2)
chunk_seen = []
class _ChunkHandler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
te = self.headers.get("Transfer-Encoding", "")
if "chunked" in te.lower():
body = _read_chunked(self.rfile)
else:
body = self.rfile.read(int(self.headers.get("Content-Length", "0")))
chunk_seen.append((te, body))
resp = str(len(body)).encode()
self.send_response(200)
self.send_header("Content-Length", str(len(resp)))
self.end_headers()
self.wfile.write(resp)
def log_message(self, *args):
pass
chunk_origin = http.server.HTTPServer(("127.0.0.1", 0), _ChunkHandler)
cport = chunk_origin.server_address[1]
threading.Thread(target=chunk_origin.serve_forever, daemon=True).start()
chunk_home = tempfile.mkdtemp(prefix="apex-chunk-")
write_scope(chunk_home, {"label": "chunk", "expires": "2099-12-31T23:59:59Z",
"allow_private": True, "allow_ip": ["127.0.0.1"],
"allow_port": [str(cport)]})
chunk_port = free_port()
cenv = dict(env)
cenv["APEX_HOME"] = chunk_home
csrv = subprocess.Popen([BIN, "--proxy", str(chunk_port)], env=cenv,
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", chunk_port))
cup = True
probe.close()
break
except OSError:
probe.close()
time.sleep(0.1)
check("chunked proxy came up", cup, chunk_port)
def chunk_request(data, chunks=None):
s = socket.create_connection(("127.0.0.1", chunk_port), timeout=10)
try:
if chunks:
for part in chunks:
s.sendall(part)
time.sleep(0.05)
else:
s.sendall(data)
s.shutdown(socket.SHUT_WR)
except OSError:
pass
s.settimeout(10)
out = b""
try:
while True:
got = s.recv(65536)
if not got:
break
out += got
except socket.timeout:
pass
s.close()
return out
chead = ("POST http://127.0.0.1:%d/up HTTP/1.1\r\n"
"Host: 127.0.0.1:%d\r\n"
"Transfer-Encoding: chunked\r\n"
"Connection: close\r\n\r\n" % (cport, cport)).encode()
cbody = b"5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n"
try:
got = chunk_request(chead + cbody)
check("proxy forwards a chunked body", b" 200 " in
got.split(b"\r\n")[0], got[:80])
check("the origin decoded the chunks",
chunk_seen and chunk_seen[-1][1] == b"hello world", chunk_seen[-1:])
check("the origin saw Transfer-Encoding: chunked",
chunk_seen and "chunked" in chunk_seen[-1][0].lower(), chunk_seen[-1:])
split = chunk_request(b"", chunks=[chead + b"5\r\nhel",
b"lo\r\n6\r\n world\r\n0\r\n\r\n"])
check("a chunked body split across writes works", b" 200 " in
split.split(b"\r\n")[0] and chunk_seen[-1][1] == b"hello world",
(split[:60], chunk_seen[-1:]))
over = chunk_request(chead + b"200000\r\n")
check("a chunk over the cap answers 413",
over.startswith(b"HTTP/1.1 413"), over[:80])
bad = chunk_request(chead + b"ZZ\r\n")
check("a malformed chunk size answers 400",
bad.startswith(b"HTTP/1.1 400"), bad[:80])
finally:
csrv.terminate()
try:
csrv.wait(timeout=5)
except subprocess.TimeoutExpired:
csrv.kill()
chunk_origin.shutdown()
chunk_origin.server_close()
res, _ = run([call(1, "traffic_list")], home=chunk_home)
listed = json.loads(text(res[0]))
check("both chunked exchanges were captured", len(listed) == 2, listed)
with open(listed[0]["raw"], "rb") as f:
craw = f.read()
check("the raw capture keeps the chunked framing",
b"Transfer-Encoding: chunked" in craw and b"5\r\nhello\r\n" in craw,
craw[:160])
shutil.rmtree(chunk_home, ignore_errors=True)
# ------------------------------------------------------------- serial guard
print("\n== serial guard ==")
fake = os.path.join(ROOT, "notamodem")