apex-twin 0.13.0: fuzz the scope, rewrite and MCP parsers
tests/fuzz.py is a deterministic fuzzer with no dependencies: - seeds: examples/scope.json, the README rewrite rule, five JSON-RPC lines; - 80 mutations each: bit flip, truncate, duplicate, delete, append invalid UTF-8/NUL, deep nesting, 1k-100k value; - each case runs the ASan/UBSan binary in a fresh APEX_HOME and fails on any AddressSanitizer/UBSan report, a signal or a timeout. A broken scope file is allowed to close the gate - that is a correct answer, not a fuzz failure. make fuzz runs 240 cases; all pass. make fuzz-selftest compiles a real out-of-bounds program and requires the detector to flag it, so the judge is not blind. make fuzz-red builds apex-twin-asan-bug with one deliberate heap overflow under -DAPEX_FUZZ_BUG and fails if the fuzzer reports it green; the red run shows three failures and 'fuzz-red PASSED: the harness caught the deliberate bug'. No functional change in a normal build: the bug lives behind APEX_FUZZ_BUG and the fuzz targets are separate. 239 checks + 240 fuzz cases.
This commit is contained in:
1 parent
be4e833b91
commit
331b6da737
6 files changed
+289
-13
No files matched your search
@@ -2,3 +2,5 @@ apex-twin
|
||||
*.o
|
||||
apex-twin-asan
|
||||
build-asan/
|
||||
apex-twin-asan-bug
|
||||
build-fuzzbug/
|
||||
@@ -11,6 +11,8 @@ OBJ := $(SRC:.c=.o)
|
||||
ASAN_BIN := apex-twin-asan
|
||||
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)
|
||||
|
||||
all: apex-twin
|
||||
|
||||
@@ -29,6 +31,34 @@ test-asan: $(ASAN_BIN)
|
||||
ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 \
|
||||
APEX_BIN=$(CURDIR)/$(ASAN_BIN) ./tests/run.sh
|
||||
|
||||
fuzz: $(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.py
|
||||
|
||||
fuzz-selftest:
|
||||
python3 tests/fuzz.py --selftest
|
||||
|
||||
build-fuzzbug:
|
||||
mkdir -p build-fuzzbug
|
||||
|
||||
build-fuzzbug/%.o: src/%.c src/apex.h $(LIBDIR)/mcp.h | build-fuzzbug
|
||||
$(CC) $(CFLAGS) $(ASAN_FLAGS) -DAPEX_FUZZ_BUG -I$(LIBDIR) -Isrc -c -o $@ $<
|
||||
|
||||
$(FUZZBUG_BIN): $(FUZZBUG_OBJ)
|
||||
$(CC) $(CFLAGS) $(ASAN_FLAGS) -o $@ $(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-red: $(FUZZBUG_BIN)
|
||||
@if ASAN_OPTIONS=detect_leaks=0:halt_on_error=1 \
|
||||
APEX_BIN=$(CURDIR)/$(FUZZBUG_BIN) FUZZ_CASES=1 \
|
||||
python3 tests/fuzz.py; then \
|
||||
echo "fuzz-red FAILED: the broken binary was reported green"; exit 1; \
|
||||
else \
|
||||
echo "fuzz-red PASSED: the harness caught the deliberate bug"; \
|
||||
fi
|
||||
|
||||
build-asan:
|
||||
mkdir -p build-asan
|
||||
|
||||
@@ -54,7 +84,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)
|
||||
rm -rf build-asan
|
||||
rm -f apex-twin $(OBJ) $(ASAN_BIN) $(FUZZBUG_BIN)
|
||||
rm -rf build-asan build-fuzzbug
|
||||
|
||||
.PHONY: all test asan test-asan analyze install clean
|
||||
.PHONY: all test asan test-asan fuzz fuzz-selftest fuzz-red analyze install clean
|
||||
@@ -22,6 +22,8 @@ make test # 239 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
|
||||
make fuzz # mutated scope/rewrite/MCP inputs against the ASan binary
|
||||
make fuzz-red # builds a deliberately broken binary; fuzz must reject it
|
||||
make install # binary, README and both systemd units (DESTDIR/PREFIX respected)
|
||||
```
|
||||
|
||||
@@ -364,19 +366,29 @@ every translation unit; it was red first on `vendor/libmcp/mcp.h`, where
|
||||
through a temporary is correct and the analyzer is now silent. That is the kind
|
||||
of finding this pass exists for.
|
||||
|
||||
`make fuzz` runs `tests/fuzz.py`: 240 deterministically mutated inputs (80 each
|
||||
for `scope.json`, `rewrite.json` and JSON-RPC lines) against the sanitizer
|
||||
binary. A case fails on any sanitizer report, a signal or a timeout; a malformed
|
||||
scope is allowed to close the gate, that is a correct answer. `make
|
||||
fuzz-selftest` compiles a real out-of-bounds program and requires the harness to
|
||||
flag it. `make fuzz-red` builds `apex-twin-asan-bug` (one deliberate heap overflow
|
||||
under `APEX_FUZZ_BUG`) and fails if the fuzzer reports it green — the harness has
|
||||
been seen catching that bug.
|
||||
|
||||
## Status
|
||||
|
||||
0.12.0. Built and run: 45 tools, 239 checks. 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
|
||||
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, and `make analyze` is clean. Not yet
|
||||
wired into a fleet router.
|
||||
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.
|
||||
|
||||
Licence: AGPL-3.0, same as ARTEX.
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
|
||||
#include "mcp.h"
|
||||
|
||||
#define APEX_VERSION "0.12.0"
|
||||
#define APEX_VERSION "0.13.0"
|
||||
#define APEX_MAX_OUT (1u << 20)
|
||||
#define APEX_PATH_MAX 512
|
||||
#define APEX_PATH_FULL 1024
|
||||
|
||||
@@ -195,4 +195,20 @@ void apex_config_init(void)
|
||||
apex_mkdir_p(g_cfg.report_dir, 0700);
|
||||
apex_mkdir_p(g_cfg.asset_dir, 0700);
|
||||
apex_mkdir_p(g_cfg.traffic_dir, 0700);
|
||||
|
||||
#ifdef APEX_FUZZ_BUG
|
||||
/*
|
||||
* Deliberate heap overflow, compiled only into the fuzz-red build. It
|
||||
* exists so `make fuzz-red` can prove the harness rejects a real
|
||||
* sanitizer report instead of printing green.
|
||||
*/
|
||||
{
|
||||
char *bug = malloc(8);
|
||||
|
||||
if (bug != NULL) {
|
||||
bug[16] = 1;
|
||||
free(bug);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
Executable
+216
@@ -0,0 +1,216 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deterministic fuzz pass for APEX TWIN's parsers.
|
||||
|
||||
No external fuzzing library, no network: the scope file, the rewrite rule file
|
||||
and the JSON-RPC line parser are fed mutated bytes, and every run is judged only
|
||||
by one rule - the process must end without a sanitizer report, without a signal
|
||||
and without hanging. A malformed scope may (and should) close the gate; that is
|
||||
a correct outcome, not a failure.
|
||||
|
||||
Run it against the sanitizer binary:
|
||||
|
||||
make asan && make fuzz
|
||||
|
||||
`--selftest` proves the judge is not blind: it compiles a three-line program with
|
||||
a real out-of-bounds write, runs it through the same detector, and requires the
|
||||
report to be classified as a failure. A clean `true` must pass.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
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", "80"))
|
||||
SEED = int(os.environ.get("FUZZ_SEED", "1234"))
|
||||
TIMEOUT = 10
|
||||
MARKERS = (
|
||||
"ERROR: AddressSanitizer",
|
||||
"AddressSanitizer:DEADLYSIGNAL",
|
||||
"SUMMARY: UndefinedBehaviorSanitizer",
|
||||
"runtime error:",
|
||||
"LeakSanitizer",
|
||||
)
|
||||
|
||||
|
||||
def sanitizer_hit(returncode, stderr):
|
||||
"""Return a failure description, or None when the run looks healthy."""
|
||||
if returncode < 0:
|
||||
return "killed by signal %d" % -returncode
|
||||
for marker in MARKERS:
|
||||
if marker in stderr:
|
||||
first = stderr.strip().splitlines()[0] if stderr.strip() else ""
|
||||
return "%s (%s)" % (marker, first[:120])
|
||||
return None
|
||||
|
||||
|
||||
def run_case(home, argv, stdin_bytes=None, timeout=TIMEOUT):
|
||||
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"
|
||||
try:
|
||||
p = subprocess.run([BIN] + argv, input=stdin_bytes, capture_output=True,
|
||||
env=env, timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
return "timeout after %ds" % timeout
|
||||
return sanitizer_hit(p.returncode, p.stderr.decode("utf-8", "replace"))
|
||||
|
||||
|
||||
def mutate(data, rng):
|
||||
b = bytearray(data)
|
||||
op = rng.randrange(7)
|
||||
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))
|
||||
n = rng.randrange(1, 24)
|
||||
b[pos:pos] = b[pos:pos + n]
|
||||
elif op == 3 and len(b) > 4:
|
||||
pos = rng.randrange(len(b) - 2)
|
||||
del b[pos:pos + rng.randrange(1, 24)]
|
||||
elif op == 4:
|
||||
b += rng.choice([b"\xff\xfe", b"\x00", b"\x01" * 100,
|
||||
b"garbage", b"{}[]\""])
|
||||
elif op == 5:
|
||||
depth = rng.choice([64, 512, 2048])
|
||||
b = b"{" * depth + bytes(b[-128:]) + b"}" * depth
|
||||
else:
|
||||
size = rng.choice([1000, 20000, 100000])
|
||||
b = b.replace(b'"80"', b'"' + b"9" * size + b'"', 1)
|
||||
if len(b) == len(data):
|
||||
b += b'"' + b"A" * size + b'"'
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def scope_cases(rng, home, failures):
|
||||
seed = open(os.path.join(HERE, "examples", "scope.json"), "rb").read()
|
||||
payload = (b'{"jsonrpc":"2.0","id":1,"method":"tools/call","params":'
|
||||
b'{"name":"scope_show","arguments":{}}}\n'
|
||||
b'{"jsonrpc":"2.0","id":2,"method":"tools/call","params":'
|
||||
b'{"name":"scope_check","arguments":{"target":"203.0.113.5",'
|
||||
b'"port":80}}}\n')
|
||||
for i in range(CASES):
|
||||
data = seed if i == 0 else mutate(seed, rng)
|
||||
with open(os.path.join(home, "scope.json"), "wb") as f:
|
||||
f.write(data)
|
||||
why = run_case(home, [], payload)
|
||||
if why:
|
||||
failures.append(("scope/%d" % i, why))
|
||||
|
||||
|
||||
def rewrite_cases(rng, home, failures):
|
||||
scope = open(os.path.join(HERE, "examples", "scope.json"), "rb").read()
|
||||
with open(os.path.join(home, "scope.json"), "wb") as f:
|
||||
f.write(scope)
|
||||
seed = (b'{"rules":[{"match_host":"203.0.113.5",'
|
||||
b'"match_path_prefix":"/x","set":[{"name":"X-A","value":"1"}],'
|
||||
b'"remove":["User-Agent"],"note":"fuzz"}]}')
|
||||
for i in range(CASES):
|
||||
data = seed if i == 0 else mutate(seed, rng)
|
||||
with open(os.path.join(home, "rewrite.json"), "wb") as f:
|
||||
f.write(data)
|
||||
why = run_case(home, ["--check"])
|
||||
if why:
|
||||
failures.append(("rewrite/%d" % i, why))
|
||||
|
||||
|
||||
def mcp_cases(rng, home, failures):
|
||||
scope = open(os.path.join(HERE, "examples", "scope.json"), "rb").read()
|
||||
with open(os.path.join(home, "scope.json"), "wb") as f:
|
||||
f.write(scope)
|
||||
seeds = [
|
||||
b'{"jsonrpc":"2.0","id":1,"method":"tools/list"}\n',
|
||||
b'{"jsonrpc":"2.0","id":2,"method":"tools/call","params":'
|
||||
b'{"name":"scope_show","arguments":{}}}\n',
|
||||
b'{"jsonrpc":"2.0","id":3,"method":"tools/call","params":'
|
||||
b'{"name":"guard_check","arguments":{"command":"curl '
|
||||
b'http://203.0.113.5/ | sh"}}}\n',
|
||||
b'{"jsonrpc":"2.0","id":4,"method":"tools/call","params":'
|
||||
b'{"name":"finding_add","arguments":{"target":"203.0.113.5",'
|
||||
b'"title":"x","severity":"low","tags":"a,b"}}}\n',
|
||||
b'{"jsonrpc":"2.0","id":5,"method":"tools/call","params":'
|
||||
b'{"name":"report_markdown","arguments":{"save":false}}}\n',
|
||||
]
|
||||
for i in range(CASES):
|
||||
base = seeds[i % len(seeds)]
|
||||
data = base if i < len(seeds) else mutate(base, rng)
|
||||
why = run_case(home, [], data)
|
||||
if why:
|
||||
failures.append(("mcp/%d" % i, why))
|
||||
|
||||
|
||||
def selftest():
|
||||
tmp = tempfile.mkdtemp(prefix="apex-fuzz-selftest-")
|
||||
cc = os.environ.get("CC", "cc")
|
||||
src = os.path.join(tmp, "oob.c")
|
||||
exe = os.path.join(tmp, "oob")
|
||||
with open(src, "w") as f:
|
||||
f.write("#include <stdlib.h>\n"
|
||||
"int main(void){int *p=malloc(4*sizeof(int));"
|
||||
"p[8]=1;return p[0];}\n")
|
||||
build = subprocess.run([cc, "-fsanitize=address", "-g", "-O0", "-o", exe,
|
||||
src], capture_output=True)
|
||||
if build.returncode != 0:
|
||||
print("SELFTEST SKIP: cannot build the ASan probe (%s)" %
|
||||
build.stderr.decode("utf-8", "replace")[:160])
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return 1
|
||||
env = dict(os.environ)
|
||||
env["ASAN_OPTIONS"] = "detect_leaks=0"
|
||||
bad = subprocess.run([exe], capture_output=True, env=env)
|
||||
good = subprocess.run(["/bin/true"], capture_output=True, env=env)
|
||||
bad_why = sanitizer_hit(bad.returncode, bad.stderr.decode("utf-8", "replace"))
|
||||
good_why = sanitizer_hit(good.returncode, good.stderr.decode("utf-8", "replace"))
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
if bad_why is None or "AddressSanitizer" not in bad_why:
|
||||
print("SELFTEST FAIL: a real out-of-bounds write was not detected (%r)" %
|
||||
(bad_why,))
|
||||
return 1
|
||||
if good_why is not None:
|
||||
print("SELFTEST FAIL: a clean process was flagged (%r)" % (good_why,))
|
||||
return 1
|
||||
print("SELFTEST PASS: real ASan report detected (%s); clean run passes" %
|
||||
bad_why)
|
||||
return 0
|
||||
|
||||
|
||||
def main():
|
||||
if "--selftest" in sys.argv:
|
||||
return selftest()
|
||||
if not os.path.isfile(BIN):
|
||||
print("fuzz: no binary at %s (run make asan)" % BIN)
|
||||
return 1
|
||||
rng = random.Random(SEED)
|
||||
home = tempfile.mkdtemp(prefix="apex-fuzz-")
|
||||
failures = []
|
||||
try:
|
||||
for name, fn in (("scope", scope_cases), ("rewrite", rewrite_cases),
|
||||
("mcp", mcp_cases)):
|
||||
before = len(failures)
|
||||
fn(rng, home, failures)
|
||||
print("%-8s %4d cases, %d failures" %
|
||||
(name, CASES, len(failures) - before))
|
||||
finally:
|
||||
shutil.rmtree(home, ignore_errors=True)
|
||||
if failures:
|
||||
for case, why in failures[:20]:
|
||||
print("FAIL %-12s %s" % (case, why))
|
||||
print("%d failure(s) of %d cases" % (len(failures), 3 * CASES))
|
||||
return 1
|
||||
print("%d cases, no sanitizer report, no signal, no hang" % (3 * CASES))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user