Implement fuzz testing that generates random malformed binary inputs to test a file parser. Monitor for segmentation faults and log the specific input seed that caused each crash.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'm planning a Python-based fuzz tester that generates deterministic random malformed binary inputs to feed an external parser process, detecting segmentation faults by analyzing the subprocess exit code and logging the crash-inducing seed and input file for reproducibility. The approach uses seeded random generation, temporary input files, subprocess invocation with timeout, and signal-based crash detection, with provisions for cross-platform segmentation fault handling and detailed logging.
A simple way to do this in practice is to let a supervisory process generate inputs, run the parser as a separate process, and inspect its exit status. On UNIX‐like systems a segmentation fault causes the process to be terminated by SIGSEGV (signal 11), which shows up as a negative return code in subprocess.run.
The script below uses a reproducible random number generator: each test case is generated from a 64‑bit seed, and that seed is logged if the parser crashes. Crashing inputs are left on disk so you can replay them later with the logged seed or file path.
python
import os
import random
import signal
import subprocess
import tempfile
import logging
from typing import Optional
# Path to the parser executable you want to fuzz
PARSER_BIN = "/path/to/your/parser"
# Configure logging
logging.basicConfig(
filename="crashes.log",
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
def make_malformed_input(seed: int, max_len: int = 4096) -> bytes:
"""Generate a deterministic pseudo‑random byte string from a seed."""
rng = random.Random(seed)
length = rng.randint(1, max_len)
return bytes(rng.getrandbits(8) for _ in range(length))
def run_parser_on_input(blob: bytes, timeout: float = 1.0) -> Optional[int]:
"""Write blob to a temp file, run the parser on it, and return the exit code."""
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(blob)
tmp_path = f.name
try:
result = subprocess.run(
[PARSER_BIN, tmp_path],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=timeout,
)
return result.returncode
finally:
# Clean up the temp file unless you want to keep all inputs
if os.path.exists(tmp_path):
os.unlink(tmp_path)
def fuzz(num_cases: int = 100000) -> None:
for i in range(num_cases):
seed = random.getrandbits(64)
test_input = make_malformed_input(seed)
try:
rc = run_parser_on_input(test_input)
except subprocess.TimeoutExpired:
logging.warning(f"iteration {i}: parser hung (seed={seed})")
continue
# On POSIX, a negative return code indicates termination by signal
if rc == -signal.SIGSEGV:
# Write crashing input to disk for later analysis
crash_file = f"crash_seed_{seed:x}.bin"
with open(crash_file, "wb") as f:
f.write(test_input)
logging.error(
f"iteration {i}: SEGFAULT (seed={seed}, saved={crash_file})"
)
elif rc is not None and rc < 0:
logging.warning(f"iteration {i}: terminated by signal {-rc} (seed={seed})")
if __name__ == "__main__":
fuzz()
A few notes:
Replace PARSER_BIN with the actual path to your parser executable.
The seed is drawn randomly for each iteration and drives the input generator; because it’s logged on crash you can reproduce the crashing input by re‑using the same seed.
If you’re running on Windows, segmentation faults don’t show up as -signal.SIGSEGV; you may need to check for specific exit codes like 0xC0000005 instead.
The timeout guards against hangs; hung cases are logged as warnings.
Run this script alongside your parser. Any segmentation faults will be recorded in crashes.log with the seed and the file name containing the offending input.