apex-twin 0.15.0: fuzz the MCP HTTP front
tests/fuzz_http.py drives the sanitizer build in --http mode with raw requests: - valid initialize, wrong path, GET, garbage request line, missing head; - Content-Length: negative, 999999999, 100000 (with body), duplicated, absent; - chunked body, invalid UTF-8 body, 8.5 MiB body (refused from the header), - a head split across two writes (exercises the partial-read loop), - 40 mutated raw requests on top. The HTTP face forks a child per connection, so liveness is not the judge: the child inherits stderr and any ASan/UBSan report fails the run. A case also fails if the connection does not close within 3 s. 200/202/400/404/405/413 are all legitimate; a sanity counter requires at least one valid 200 so a server that rejects everything cannot pass. make fuzz-http: 40 cases, 18 valid 200 answers, no sanitizer report, no hang. make fuzz-http-red builds with APEX_FUZZ_BUG_HTTP (heap overflow after a complete head) and requires rejection: 2 failures including the exact apex-twin.c UBSan line, 'caught the deliberate bug'. Normal builds never see the macro. 239 checks + 240 file-fuzz + 60 proxy-fuzz + 40 HTTP-fuzz cases.
This commit is contained in:
1 parent
a74aa0feaa
commit
ed4e326ed2
6 files changed
+315
-17
No files matched your search
@@ -6,3 +6,5 @@ apex-twin-asan-bug
|
||||
build-fuzzbug/
|
||||
apex-twin-asan-bug-proxy
|
||||
build-fuzzbug-proxy/
|
||||
apex-twin-asan-bug-http
|
||||
build-fuzzbug-http/
|
||||
@@ -15,6 +15,8 @@ FUZZBUG_BIN := apex-twin-asan-bug
|
||||
FUZZBUG_OBJ := $(SRC:src/%.c=build-fuzzbug/%.o)
|
||||
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)
|
||||
|
||||
all: apex-twin
|
||||
|
||||
@@ -66,6 +68,29 @@ 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)
|
||||
|
||||
fuzz-http: $(ASAN_BIN)
|
||||
ASAN_OPTIONS=detect_leaks=0:halt_on_error=1 \
|
||||
UBSAN_OPTIONS=halt_on_error=1 \
|
||||
APEX_BIN=$(CURDIR)/$(ASAN_BIN) python3 tests/fuzz_http.py
|
||||
|
||||
build-fuzzbug-http:
|
||||
mkdir -p build-fuzzbug-http
|
||||
|
||||
build-fuzzbug-http/%.o: src/%.c src/apex.h $(LIBDIR)/mcp.h | build-fuzzbug-http
|
||||
$(CC) $(CFLAGS) $(ASAN_FLAGS) -DAPEX_FUZZ_BUG_HTTP -I$(LIBDIR) -Isrc -c -o $@ $<
|
||||
|
||||
$(FUZZBUG_HTTP_BIN): $(FUZZBUG_HTTP_OBJ)
|
||||
$(CC) $(CFLAGS) $(ASAN_FLAGS) -o $@ $(FUZZBUG_HTTP_OBJ)
|
||||
|
||||
fuzz-http-red: $(FUZZBUG_HTTP_BIN)
|
||||
@if ASAN_OPTIONS=detect_leaks=0:halt_on_error=1 \
|
||||
APEX_BIN=$(CURDIR)/$(FUZZBUG_HTTP_BIN) FUZZ_CASES=1 \
|
||||
python3 tests/fuzz_http.py; then \
|
||||
echo "fuzz-http-red FAILED: the broken HTTP face was reported green"; exit 1; \
|
||||
else \
|
||||
echo "fuzz-http-red PASSED: the harness caught the deliberate bug"; \
|
||||
fi
|
||||
|
||||
fuzz-proxy-red: $(FUZZBUG_PROXY_BIN)
|
||||
@if ASAN_OPTIONS=detect_leaks=0:halt_on_error=1 \
|
||||
APEX_BIN=$(CURDIR)/$(FUZZBUG_PROXY_BIN) FUZZ_CASES=1 \
|
||||
@@ -109,7 +134,8 @@ install: apex-twin
|
||||
install -m 0644 systemd/apex-twin-proxy.service $(DESTDIR)$(UNITDIR)/apex-twin-proxy.service
|
||||
|
||||
clean:
|
||||
rm -f apex-twin $(OBJ) $(ASAN_BIN) $(FUZZBUG_BIN) $(FUZZBUG_PROXY_BIN)
|
||||
rm -rf build-asan build-fuzzbug build-fuzzbug-proxy
|
||||
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
|
||||
|
||||
.PHONY: all test asan test-asan fuzz fuzz-selftest fuzz-red fuzz-proxy fuzz-proxy-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 analyze install clean
|
||||
@@ -25,6 +25,7 @@ make analyze # gcc -fanalyzer over every translation unit
|
||||
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
|
||||
make fuzz-http # mutated raw HTTP against the ASan MCP HTTP face
|
||||
make install # binary, README and both systemd units (DESTDIR/PREFIX respected)
|
||||
```
|
||||
|
||||
@@ -387,20 +388,31 @@ everything cannot pass. `make fuzz-proxy-red` builds the same proxy with a
|
||||
deliberate parser overflow (`APEX_FUZZ_BUG_PROXY`) and requires the fuzzer to
|
||||
reject it; it does (3/3 failure lines, "caught the deliberate bug").
|
||||
|
||||
`make fuzz-http` (`tests/fuzz_http.py`) points the same idea at the MCP HTTP
|
||||
face: broken request lines, negative/huge/duplicate Content-Length, chunked
|
||||
bodies, 100 kB and 8.5 MB bodies, invalid UTF-8, a head split across two writes,
|
||||
wrong paths and methods, plus mutated raw requests. The HTTP face forks a child
|
||||
per connection, so process liveness is not the judge — the child inherits stderr
|
||||
and any ASan/UBSan report fails the run. A case also fails on a hang; 200/202/
|
||||
400/404/405/413 are all legitimate answers. 40 cases, 18 valid 200s.
|
||||
`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.
|
||||
|
||||
## Status
|
||||
|
||||
0.14.0. Built and run: 45 tools, 239 checks, 240 file-parser fuzz cases and 60
|
||||
proxy-parser 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 both fuzzers have been shown to reject a binary with
|
||||
a deliberate bug. Not yet wired into a fleet router.
|
||||
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.
|
||||
|
||||
Licence: AGPL-3.0, same as ARTEX.
|
||||
@@ -189,6 +189,23 @@ static void serve_one(int fd, const char *session)
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef APEX_FUZZ_BUG_HTTP
|
||||
/*
|
||||
* Deliberate heap overflow for `make fuzz-http-red`, compiled only into
|
||||
* that build. It fires only for a complete request head, so the readiness
|
||||
* probe (connect and close) does not trip it; the listener survives
|
||||
* because the HTTP face forks a child per connection.
|
||||
*/
|
||||
if (done) {
|
||||
char *bug = malloc(4);
|
||||
|
||||
if (bug != NULL) {
|
||||
bug[8] = 1;
|
||||
free(bug);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if (!done) {
|
||||
http_send(fd, 400, "text/plain", "incomplete request\n", 20, NULL);
|
||||
free(body);
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
|
||||
#include "mcp.h"
|
||||
|
||||
#define APEX_VERSION "0.14.0"
|
||||
#define APEX_VERSION "0.15.0"
|
||||
#define APEX_MAX_OUT (1u << 20)
|
||||
#define APEX_PATH_MAX 512
|
||||
#define APEX_PATH_FULL 1024
|
||||
|
||||
Executable
+241
@@ -0,0 +1,241 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fuzz the MCP HTTP front (`apex-twin --http`).
|
||||
|
||||
The HTTP face forks a child per connection, so "the process is still alive" is
|
||||
not enough: a child crash would leave the listener running and the client with a
|
||||
closed socket. The judge here is stderr - the child inherits the pipe, so any
|
||||
AddressSanitizer/UBSan report reaches the parent's stderr and fails the run.
|
||||
|
||||
make asan && make fuzz-http
|
||||
make fuzz-http-red # deliberate child crash must be caught
|
||||
"""
|
||||
import errno
|
||||
import os
|
||||
import random
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
DEFAULT_BIN = os.path.join(HERE, "apex-twin-asan")
|
||||
if not os.path.isfile(DEFAULT_BIN):
|
||||
DEFAULT_BIN = os.path.join(HERE, "apex-twin")
|
||||
BIN = os.environ.get("APEX_BIN") or DEFAULT_BIN
|
||||
CASES = int(os.environ.get("FUZZ_CASES", "40"))
|
||||
SEED = int(os.environ.get("FUZZ_SEED", "1234"))
|
||||
MARKERS = (
|
||||
"ERROR: AddressSanitizer",
|
||||
"AddressSanitizer:DEADLYSIGNAL",
|
||||
"SUMMARY: UndefinedBehaviorSanitizer",
|
||||
"runtime error:",
|
||||
)
|
||||
|
||||
|
||||
def free_port():
|
||||
s = socket.socket()
|
||||
s.bind(("127.0.0.1", 0))
|
||||
port = s.getsockname()[1]
|
||||
s.close()
|
||||
return port
|
||||
|
||||
|
||||
def marker_line(err):
|
||||
for line in err.splitlines():
|
||||
for marker in MARKERS:
|
||||
if marker in line:
|
||||
return line.strip()[:160]
|
||||
return None
|
||||
|
||||
|
||||
def wait_listening(port, proc, deadline=10.0):
|
||||
end = time.time() + deadline
|
||||
while time.time() < end:
|
||||
if proc.poll() is not None:
|
||||
return False
|
||||
s = socket.socket()
|
||||
try:
|
||||
s.settimeout(0.2)
|
||||
s.connect(("127.0.0.1", port))
|
||||
s.close()
|
||||
return True
|
||||
except OSError:
|
||||
s.close()
|
||||
time.sleep(0.05)
|
||||
return False
|
||||
|
||||
|
||||
def probe(port, chunks, timeout=3.0):
|
||||
"""chunks is a list of byte strings, sent with a short gap between them."""
|
||||
try:
|
||||
s = socket.create_connection(("127.0.0.1", port), timeout=timeout)
|
||||
except OSError as e:
|
||||
return "cannot connect: %s" % e, b""
|
||||
s.settimeout(timeout)
|
||||
try:
|
||||
for chunk in chunks:
|
||||
s.sendall(chunk)
|
||||
if len(chunks) > 1:
|
||||
time.sleep(0.05)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
s.shutdown(socket.SHUT_WR)
|
||||
except OSError:
|
||||
pass
|
||||
resp = b""
|
||||
reason = None
|
||||
try:
|
||||
while len(resp) < (1 << 20):
|
||||
chunk = s.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
resp += chunk
|
||||
except socket.timeout:
|
||||
reason = "connection did not close within %.1fs" % timeout
|
||||
except OSError as e:
|
||||
if e.errno not in (errno.ECONNRESET, errno.EPIPE):
|
||||
reason = "socket error: %s" % e
|
||||
finally:
|
||||
s.close()
|
||||
return reason, resp
|
||||
|
||||
|
||||
def post(headers, body, path="/mcp"):
|
||||
head = ("POST %s HTTP/1.1\r\nHost: fuzz\r\n" % path) + headers + \
|
||||
"Connection: close\r\n\r\n"
|
||||
return head.encode() + body
|
||||
|
||||
|
||||
def mutate(chunks, rng):
|
||||
data = b"".join(chunks)
|
||||
b = bytearray(data)
|
||||
op = rng.randrange(8)
|
||||
if op == 0 and b:
|
||||
pos = rng.randrange(len(b))
|
||||
b[pos] ^= 1 << rng.randrange(8)
|
||||
elif op == 1:
|
||||
b = b[:rng.randrange(len(b) + 1)]
|
||||
elif op == 2 and b:
|
||||
pos = rng.randrange(len(b))
|
||||
b[pos:pos] = b[pos:pos + rng.randrange(1, 60)]
|
||||
elif op == 3 and len(b) > 8:
|
||||
pos = rng.randrange(len(b) - 4)
|
||||
del b[pos:pos + rng.randrange(1, 60)]
|
||||
elif op == 4:
|
||||
b += rng.choice([b"\xff\xfe", b"\x00", b"\r\nX-Dup: 1",
|
||||
b"\r\n\r\n", b"Z" * 5000])
|
||||
elif op == 5:
|
||||
# duplicate an existing header line
|
||||
lines = bytes(b).split(b"\r\n")
|
||||
if len(lines) > 1:
|
||||
i = rng.randrange(1, len(lines))
|
||||
lines.insert(i, lines[i])
|
||||
b = bytearray(b"\r\n".join(lines))
|
||||
elif op == 6:
|
||||
# deep JSON body, if there is a body separator
|
||||
marker = b"\r\n\r\n"
|
||||
if marker in b:
|
||||
head, _, _ = bytes(b).partition(marker)
|
||||
depth = rng.choice([256, 4096])
|
||||
b = bytearray(head + marker + b"{" * depth + b"\r\n")
|
||||
else:
|
||||
b = bytearray(b) + bytes(rng.randrange(1, 2000))
|
||||
return [bytes(b)]
|
||||
|
||||
|
||||
def main():
|
||||
if not os.path.isfile(BIN):
|
||||
print("fuzz-http: no binary at %s (run make asan)" % BIN)
|
||||
return 1
|
||||
rng = random.Random(SEED)
|
||||
home = tempfile.mkdtemp(prefix="apex-fuzz-http-")
|
||||
with open(os.path.join(home, "scope.json"), "w") as f:
|
||||
f.write('{"label":"fuzz","expires":"2099-12-31T23:59:59Z",'
|
||||
'"allow_ip":["203.0.113.0/24"],"allow_port":["80"]}')
|
||||
port = free_port()
|
||||
env = dict(os.environ)
|
||||
env["APEX_HOME"] = home
|
||||
env["ASAN_OPTIONS"] = "detect_leaks=0:halt_on_error=1"
|
||||
env["UBSAN_OPTIONS"] = "halt_on_error=1:print_stacktrace=1"
|
||||
proc = subprocess.Popen([BIN, "--http", str(port)], env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
text=True)
|
||||
failures = []
|
||||
ok200 = 0
|
||||
try:
|
||||
if not wait_listening(port, proc):
|
||||
out, err = proc.communicate(timeout=5)
|
||||
print("fuzz-http: server did not start\n%s" % err[:800])
|
||||
return 1
|
||||
init = (b'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}')
|
||||
seeds = [
|
||||
[post("Content-Type: application/json\r\nContent-Length: %d\r\n" %
|
||||
len(init), init)],
|
||||
[post("Content-Length: 2\r\n", b"{}", path="/")],
|
||||
[post("Content-Length: 2\r\n", b"{}", path="/nope")],
|
||||
[b"POST /mcp HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked"
|
||||
b"\r\n\r\n2\r\n{}\r\n0\r\n\r\n"],
|
||||
[post("Content-Length: 8\r\nContent-Length: 4\r\n", b"{}")],
|
||||
[post("Content-Length: -5\r\n", b"")],
|
||||
[post("Content-Length: 999999999\r\n", b"")],
|
||||
[post("Content-Length: 100000\r\n", b"{" * 100000)],
|
||||
[post("Content-Length: 20\r\n", b"\xff" * 20)],
|
||||
# 8.5 MiB is over MAX_BODY and must be refused on the header alone
|
||||
[post("Content-Length: 8912896\r\n", b"")],
|
||||
# a head split across two writes exercises the partial-read loop
|
||||
[b"POST /mcp HTTP/1.1\r\nHost: x\r\n",
|
||||
b"Content-Length: 2\r\n\r\n{}"],
|
||||
[b"GARBAGE\r\n\r\n"],
|
||||
[b"POST /mcp HTTP/1.1\r\nHost: x\r\n\r\n"],
|
||||
[b"GET /mcp HTTP/1.1\r\nHost: x\r\n\r\n"],
|
||||
[post("Content-Length: 2\r\n", b"{}", path="/mcp?x=y")],
|
||||
]
|
||||
suite = seeds + [[]]
|
||||
for i in range(CASES + len(seeds)):
|
||||
chunks = suite[i] if i < len(suite) else mutate(
|
||||
seeds[i % len(seeds)], rng)
|
||||
reason, resp = probe(port, chunks)
|
||||
if resp.startswith(b"HTTP/1.") and b" 200 " in resp.split(b"\r\n")[0]:
|
||||
ok200 += 1
|
||||
if reason is None and proc.poll() is not None:
|
||||
out, err = proc.communicate(timeout=5)
|
||||
line = marker_line(err)
|
||||
reason = "server died (%s)" % (line or "no marker")
|
||||
if reason is not None:
|
||||
failures.append(("case/%d" % i, reason))
|
||||
if proc.poll() is not None:
|
||||
break
|
||||
if proc.poll() is None:
|
||||
proc.terminate()
|
||||
out, err = proc.communicate(timeout=10)
|
||||
line = marker_line(err)
|
||||
if line is not None:
|
||||
failures.append(("stderr", line))
|
||||
if ok200 == 0:
|
||||
failures.append(("sanity", "no valid request got a 200"))
|
||||
finally:
|
||||
if proc.poll() is None:
|
||||
proc.kill()
|
||||
try:
|
||||
os.unlink(os.path.join(home, "scope.json"))
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
os.rmdir(home)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
if failures:
|
||||
for case, why in failures[:20]:
|
||||
print("FAIL %-10s %s" % (case, why))
|
||||
print("%d failure(s) of %d case(s)" % (len(failures), CASES))
|
||||
return 1
|
||||
print("%d cases, %d valid 200 answers, no sanitizer report, no hang"
|
||||
% (CASES, ok200))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user