apex-twin 0.14.0: fuzz the proxy's request parser
tests/fuzz_proxy.py starts the sanitizer proxy against a local origin and sends mutated raw request heads in a fresh connection each time: - seeds: absolute-URI GET, CONNECT, origin-form GET; - 60 mutations: bit flip, truncate, duplicate/delete, invalid UTF-8/NUL, CRLF injection, 1k/40k/100k request lines, garbage request line; - the client half-closes after sending, so a truncated head is EOF, not a 20 s read timeout. A case fails on a dead proxy, a sanitizer report, or a connection that never closes. 400/403/501/502 and an ECONNRESET after the proxy rejected unread bytes are successes. Valid requests must still get a 200 (the run counts them), so a proxy that rejects everything cannot pass. make fuzz-proxy: 60 cases, 23 valid 200 answers, no sanitizer report, no hang. make fuzz-proxy-red builds the same proxy with a deliberate heap overflow in the request path (APEX_FUZZ_BUG_PROXY) and requires the fuzzer to reject it: 3 failure lines, including the proxy.c UBSan report, 'harness caught the deliberate bug'. Normal builds never see the macro. 239 checks + 240 file fuzz cases + 60 proxy fuzz cases.
This commit is contained in:
1 parent
331b6da737
commit
a74aa0feaa
6 files changed
+308
-17
No files matched your search
@@ -4,3 +4,5 @@ apex-twin-asan
|
||||
build-asan/
|
||||
apex-twin-asan-bug
|
||||
build-fuzzbug/
|
||||
apex-twin-asan-bug-proxy
|
||||
build-fuzzbug-proxy/
|
||||
@@ -13,6 +13,8 @@ ASAN_OBJ := $(SRC:src/%.c=build-asan/%.o)
|
||||
ASAN_FLAGS := -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer
|
||||
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)
|
||||
|
||||
all: apex-twin
|
||||
|
||||
@@ -50,6 +52,29 @@ $(FUZZBUG_BIN): $(FUZZBUG_OBJ)
|
||||
|
||||
# The red proof: build with a deliberate heap overflow and require the fuzzer to
|
||||
# reject it. A green run here would mean the harness is blind.
|
||||
fuzz-proxy: $(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_proxy.py
|
||||
|
||||
build-fuzzbug-proxy:
|
||||
mkdir -p build-fuzzbug-proxy
|
||||
|
||||
build-fuzzbug-proxy/%.o: src/%.c src/apex.h $(LIBDIR)/mcp.h | build-fuzzbug-proxy
|
||||
$(CC) $(CFLAGS) $(ASAN_FLAGS) -DAPEX_FUZZ_BUG_PROXY -I$(LIBDIR) -Isrc -c -o $@ $<
|
||||
|
||||
$(FUZZBUG_PROXY_BIN): $(FUZZBUG_PROXY_OBJ)
|
||||
$(CC) $(CFLAGS) $(ASAN_FLAGS) -o $@ $(FUZZBUG_PROXY_OBJ)
|
||||
|
||||
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 \
|
||||
python3 tests/fuzz_proxy.py; then \
|
||||
echo "fuzz-proxy-red FAILED: the broken proxy was reported green"; exit 1; \
|
||||
else \
|
||||
echo "fuzz-proxy-red PASSED: the harness caught the deliberate bug"; \
|
||||
fi
|
||||
|
||||
fuzz-red: $(FUZZBUG_BIN)
|
||||
@if ASAN_OPTIONS=detect_leaks=0:halt_on_error=1 \
|
||||
APEX_BIN=$(CURDIR)/$(FUZZBUG_BIN) FUZZ_CASES=1 \
|
||||
@@ -84,7 +109,7 @@ 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)
|
||||
rm -rf build-asan build-fuzzbug
|
||||
rm -f apex-twin $(OBJ) $(ASAN_BIN) $(FUZZBUG_BIN) $(FUZZBUG_PROXY_BIN)
|
||||
rm -rf build-asan build-fuzzbug build-fuzzbug-proxy
|
||||
|
||||
.PHONY: all test asan test-asan fuzz fuzz-selftest fuzz-red analyze install clean
|
||||
.PHONY: all test asan test-asan fuzz fuzz-selftest fuzz-red fuzz-proxy fuzz-proxy-red analyze install clean
|
||||
@@ -24,6 +24,7 @@ make test-asan # the whole suite against the sanitizer binary
|
||||
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 install # binary, README and both systemd units (DESTDIR/PREFIX respected)
|
||||
```
|
||||
|
||||
@@ -375,20 +376,31 @@ flag it. `make fuzz-red` builds `apex-twin-asan-bug` (one deliberate heap overfl
|
||||
under `APEX_FUZZ_BUG`) and fails if the fuzzer reports it green — the harness has
|
||||
been seen catching that bug.
|
||||
|
||||
`make fuzz-proxy` is the socket-side counterpart (`tests/fuzz_proxy.py`): it
|
||||
starts the sanitizer proxy against a local origin and sends 60 mutated raw
|
||||
requests — absolute URIs with broken authorities, CONNECT variants, 100 kB
|
||||
request lines, CRLF injection, invalid UTF-8, truncated heads. A case fails if
|
||||
the proxy dies, prints a sanitizer report or leaves the connection hanging; a
|
||||
400/403/501/502 or a reset after the proxy rejected unread bytes is success. The
|
||||
run reports how many valid requests still got a 200, so a proxy that rejects
|
||||
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").
|
||||
|
||||
## Status
|
||||
|
||||
0.13.0. Built and run: 45 tools, 239 checks and 240 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 `make fuzz`
|
||||
feeds 240 mutated parser inputs to the sanitizer build with `make fuzz-red`
|
||||
proving the harness catches a real report. Not yet wired into a fleet router.
|
||||
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.
|
||||
|
||||
Licence: AGPL-3.0, same as ARTEX.
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
|
||||
#include "mcp.h"
|
||||
|
||||
#define APEX_VERSION "0.13.0"
|
||||
#define APEX_VERSION "0.14.0"
|
||||
#define APEX_MAX_OUT (1u << 20)
|
||||
#define APEX_PATH_MAX 512
|
||||
#define APEX_PATH_FULL 1024
|
||||
|
||||
+15
@@ -724,6 +724,21 @@ static void handle_client(int cfd)
|
||||
free(head);
|
||||
return;
|
||||
}
|
||||
#ifdef APEX_FUZZ_BUG_PROXY
|
||||
/*
|
||||
* Deliberate heap overflow for `make fuzz-proxy-red`, compiled only into
|
||||
* that build. It fires only after a complete request head was parsed, so
|
||||
* the readiness probe (connect and close) does not trip it.
|
||||
*/
|
||||
{
|
||||
char *bug = malloc(4);
|
||||
|
||||
if (bug != NULL) {
|
||||
bug[8] = 1;
|
||||
free(bug);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
pr = parse_request(head, &r);
|
||||
if (pr == -2) {
|
||||
reply_error(cfd, 501, "Not Implemented",
|
||||
|
||||
Executable
+237
@@ -0,0 +1,237 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fuzz the proxy's request parser with raw bytes.
|
||||
|
||||
The proxy is a network-facing parser: it reads a request head off a socket,
|
||||
splits an absolute URI or CONNECT authority, and decides before it connects.
|
||||
`tests/fuzz.py` covers the file parsers; this one covers the socket path.
|
||||
|
||||
Method: start the sanitizer build in `--proxy` mode against a local origin, then
|
||||
send mutated request heads over loopback in a fresh connection each time. A case
|
||||
fails if the proxy dies, prints a sanitizer report, or does not close the
|
||||
connection. A 400/403/501/502 answer is success: the parser rejected the input
|
||||
and the gate held.
|
||||
|
||||
make asan && make fuzz-proxy
|
||||
make fuzz-proxy-red # deliberate parser bug must be caught
|
||||
"""
|
||||
import errno
|
||||
import http.server
|
||||
import os
|
||||
import random
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
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", "60"))
|
||||
SEED = int(os.environ.get("FUZZ_SEED", "1234"))
|
||||
MARKERS = (
|
||||
"ERROR: AddressSanitizer",
|
||||
"AddressSanitizer:DEADLYSIGNAL",
|
||||
"SUMMARY: UndefinedBehaviorSanitizer",
|
||||
"runtime error:",
|
||||
)
|
||||
|
||||
|
||||
class Origin(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
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
|
||||
|
||||
|
||||
def free_port():
|
||||
s = socket.socket()
|
||||
s.bind(("127.0.0.1", 0))
|
||||
port = s.getsockname()[1]
|
||||
s.close()
|
||||
return port
|
||||
|
||||
|
||||
def mutate(data, rng):
|
||||
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, 40)]
|
||||
elif op == 3 and len(b) > 8:
|
||||
pos = rng.randrange(len(b) - 4)
|
||||
del b[pos:pos + rng.randrange(1, 40)]
|
||||
elif op == 4:
|
||||
b += rng.choice([b"\xff\xfe", b"\x00", b"\r\nX-Evil: 1",
|
||||
b" ", b"\r\n\r\n"])
|
||||
elif op == 5:
|
||||
# a very long request line or header value
|
||||
b = b.replace(b"/", b"/" + b"A" * rng.choice([1000, 40000, 100000]), 1)
|
||||
elif op == 6:
|
||||
# CRLF injection inside the authority/header area
|
||||
b = b.replace(b" HTTP/1.1", b"\r\nInjected: 1 HTTP/1.1", 1)
|
||||
else:
|
||||
b = b"GET " + b"x" * rng.choice([100, 5000, 70000]) + b" HTTP/1.1\r\n\r\n"
|
||||
return bytes(b)
|
||||
|
||||
|
||||
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, data, timeout=3.0):
|
||||
"""Return (failure_reason, response_bytes)."""
|
||||
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:
|
||||
s.sendall(data)
|
||||
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:
|
||||
# A close with unread data is a reset on the wire; the proxy rejected
|
||||
# the input and closed, which is a correct answer, not a failure.
|
||||
if e.errno not in (errno.ECONNRESET, errno.EPIPE):
|
||||
reason = "socket error: %s" % e
|
||||
finally:
|
||||
s.close()
|
||||
return reason, resp
|
||||
|
||||
|
||||
def main():
|
||||
if not os.path.isfile(BIN):
|
||||
print("fuzz-proxy: no binary at %s (run make asan)" % BIN)
|
||||
return 1
|
||||
rng = random.Random(SEED)
|
||||
origin = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Origin)
|
||||
oport = origin.server_address[1]
|
||||
threading.Thread(target=origin.serve_forever, daemon=True).start()
|
||||
|
||||
home = tempfile.mkdtemp(prefix="apex-fuzz-proxy-")
|
||||
with open(os.path.join(home, "scope.json"), "w") as f:
|
||||
f.write('{"label":"fuzz","expires":"2099-12-31T23:59:59Z",'
|
||||
'"allow_private":true,"allow_ip":["127.0.0.1"],'
|
||||
'"allow_port":["%d"]}' % oport)
|
||||
pport = 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, "--proxy", str(pport)], env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
text=True)
|
||||
failures = []
|
||||
ok200 = 0
|
||||
try:
|
||||
if not wait_listening(pport, proc):
|
||||
out, err = proc.communicate(timeout=5)
|
||||
print("fuzz-proxy: proxy did not start\n%s" % err[:800])
|
||||
return 1
|
||||
base = ("GET http://127.0.0.1:%d/ HTTP/1.1\r\n"
|
||||
"Host: 127.0.0.1:%d\r\n"
|
||||
"User-Agent: fuzz\r\n"
|
||||
"Connection: close\r\n\r\n" % (oport, oport)).encode()
|
||||
connect = ("CONNECT 127.0.0.1:%d HTTP/1.1\r\n"
|
||||
"Host: 127.0.0.1:%d\r\n\r\n" % (oport, oport)).encode()
|
||||
origin_form = ("GET / HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n"
|
||||
"Connection: close\r\n\r\n" % oport).encode()
|
||||
seeds = [base, connect, origin_form]
|
||||
for i in range(CASES):
|
||||
seed = seeds[i % len(seeds)]
|
||||
data = seed if i < len(seeds) else mutate(seed, rng)
|
||||
reason, resp = probe(pport, data)
|
||||
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)
|
||||
hit = next((m for m in MARKERS if m in err), "no marker")
|
||||
reason = "proxy died (returncode %s, %s)" % (proc.returncode, hit)
|
||||
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=5)
|
||||
hit = next((m for m in MARKERS if m in err), None)
|
||||
if hit is not None:
|
||||
failures.append(("stderr", marker_line(err) or hit))
|
||||
if ok200 == 0:
|
||||
failures.append(("sanity", "the proxy never returned 200 to a valid request"))
|
||||
finally:
|
||||
if proc.poll() is None:
|
||||
proc.kill()
|
||||
origin.shutdown()
|
||||
origin.server_close()
|
||||
for name in ("scope.json",):
|
||||
try:
|
||||
os.unlink(os.path.join(home, name))
|
||||
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