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.
238 lines
7.8 KiB
Python
Executable File
238 lines
7.8 KiB
Python
Executable File
#!/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())
|