# fuzzer.py
import os
import sys
import random
import struct
import subprocess
import hashlib
import json
import signal
import time
from datetime import datetime
from pathlib import Path
from dataclasses import dataclass, asdict
from typing import List, Dict, Optional, Tuple
import tempfile
import psutil
@dataclass
class CrashInfo:
"""Container for crash information"""
seed: int
timestamp: str
input_file: str
crash_type: str # segfault, timeout, assertion, etc.
stderr_output: str
exit_code: int
input_size: int
input_hex: str
backtrace: Optional[str] = None
def to_dict(self):
return asdict(self)
class BinaryFuzzer:
"""Main fuzzing engine"""
def __init__(self,
target_binary: str,
output_dir: str = "fuzz_results",
timeout: int = 5,
memory_limit_mb: int = 512):
"""
Initialize fuzzer
Args:
target_binary: Path to binary to fuzz
output_dir: Directory for results
timeout: Timeout for each test (seconds)
memory_limit_mb: Memory limit per process
"""
self.target_binary = target_binary
self.output_dir = Path(output_dir)
self.timeout = timeout
self.memory_limit = memory_limit_mb
# Create output structure
self.output_dir.mkdir(exist_ok=True)
self.crashes_dir = self.output_dir / "crashes"
self.crashes_dir.mkdir(exist_ok=True)
self.corpus_dir = self.output_dir / "corpus"
self.corpus_dir.mkdir(exist_ok=True)
self.testcases_dir = self.output_dir / "testcases"
self.testcases_dir.mkdir(exist_ok=True)
self.crashes: List[CrashInfo] = []
self.interesting_inputs: List[bytes] = []
self.iteration = 0
self.start_time = time.time()
def generate_random_input(self, size: int) -> bytes:
"""Generate random binary input"""
return bytes(random.randint(0, 255) for _ in range(size))
def generate_valid_header(self) -> bytes:
"""Generate valid file header for better mutation"""
magic = 0xDEADBEEF
version = random.randint(1, 10)
offset = 0x100
size = random.randint(1, 10)
return struct.pack('<IIII', magic, version, offset, size)
def mutate_input(self, data: bytes, mutation_rate: float = 0.1) -> bytes:
"""Mutate existing input"""
data = bytearray(data)
mutations_count = max(1, int(len(data) * mutation_rate))
for _ in range(mutations_count):
mutation_type = random.choice([
'flip_bit',
'byte_flip',
'insert_bytes',
'delete_bytes',
'interesting_values'
])
if not data:
continue
pos = random.randint(0, len(data) - 1)
if mutation_type == 'flip_bit':
bit = random.randint(0, 7)
data[pos] ^= (1 << bit)
elif mutation_type == 'byte_flip':
data[pos] = random.randint(0, 255)
elif mutation_type == 'insert_bytes':
insert_pos = random.randint(0, len(data))
insert_data = bytes(random.randint(0, 255)
for _ in range(random.randint(1, 4)))
data = data[:insert_pos] + insert_data + data[insert_pos:]
elif mutation_type == 'delete_bytes':
delete_len = random.randint(1, min(4, len(data)))
del data[pos:pos + delete_len]
elif mutation_type == 'interesting_values':
# Insert known interesting values
interesting = [0, 255, 127, 128, 0x7FFFFFFF, 0xFFFFFFFF]
if len(data) >= 4:
val = random.choice(interesting)
struct.pack_into('<I', data, pos, val)
else:
data[pos] = random.choice(interesting)
return bytes(data)
def run_target(self, input_file: str) -> Tuple[bool, str, int]:
"""
Run target binary with input
Returns:
Tuple of (crashed, stderr_output, exit_code)
"""
try:
# Set resource limits
def set_resource_limits():
try:
soft, hard = resource.getrlimit(resource.RLIMIT_AS)
resource.setrlimit(
resource.RLIMIT_AS,
(self.memory_limit * 1024 * 1024, hard)
)
except:
pass
process = subprocess.Popen(
[self.target_binary, input_file],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
preexec_fn=set_resource_limits
)
try:
_, stderr = process.communicate(timeout=self.timeout)
stderr_str = stderr.decode('utf-8', errors='ignore')
crashed = process.returncode != 0
return crashed, stderr_str, process.returncode
except subprocess.TimeoutExpired:
process.kill()
return True, "TIMEOUT", -signal.SIGTERM
except Exception as e:
return True, str(e), -1
def save_crash(self, data: bytes, crash_info: CrashInfo) -> None:
"""Save crash details and input"""
seed_hash = hashlib.sha256(data).hexdigest()[:8]
crash_id = f"crash_{crash_info.seed}_{seed_hash}"
crash_file = self.crashes_dir / f"{crash_id}.bin"
crash_file.write_bytes(data)
json_file = self.crashes_dir / f"{crash_id}.json"
json_file.write_text(json.dumps(crash_info.to_dict(), indent=2))
crash_info.input_file = str(crash_file)
self.crashes.append(crash_info)
print(f"[CRASH] Seed: {crash_info.seed}, Type: {crash_info.crash_type}")
print(f" Input size: {crash_info.input_size} bytes")
print(f" Hex: {crash_info.input_hex[:64]}...")
def fuzz_iteration(self, seed: int, strategy: str = 'random') -> None:
"""Single fuzz iteration"""
# Generate input
if strategy == 'random':
if random.random() < 0.3 and self.interesting_inputs:
# Mutate interesting input
base_input = random.choice(self.interesting_inputs)
data = self.mutate_input(base_input)
else:
# Pure random
size = random.choice([
random.randint(1, 100), # small
random.randint(100, 1000), # medium
random.randint(1000, 10000), # large
random.randint(10000, 1000000) # very large
])
data = self.generate_random_input(size)
elif strategy == 'structured':
# Generate with valid header occasionally
if random.random() < 0.5:
data = self.generate_valid_header()
# Add random data after header
extra_size = random.randint(0, 1000)
data += self.generate_random_input(extra_size)
else:
data = self.generate_random_input(random.randint(1, 1000))
else:
data = self.generate_random_input(random.randint(1, 1000))
# Create temporary input file
with tempfile.NamedTemporaryFile(delete=False) as f:
input_file = f.name
f.write(data)
try:
crashed, stderr, exit_code = self.run_target(input_file)
if crashed:
crash_type = self._classify_crash(stderr, exit_code)
crash_info = CrashInfo(
seed=seed,
timestamp=datetime.now().isoformat(),
input_file=input_file,
crash_type=crash_type,
stderr_output=stderr[:1000], # Limit output
exit_code=exit_code,
input_size=len(data),
input_hex=data.hex()[:128]
)
self.save_crash(data, crash_info)
else:
# Save interesting inputs (arbitrary criteria)
if random.random() < 0.01: # Keep 1% of passing inputs
self.interesting_inputs.append(data)
if len(self.interesting_inputs) > 100:
self.interesting_inputs.pop(0)
finally:
# Cleanup
try:
os.unlink(input_file)
except:
pass
def _classify_crash(self, stderr: str, exit_code: int) -> str:
"""Classify type of crash"""
stderr_lower = stderr.lower()
if "TIMEOUT" in stderr:
return "timeout"
elif "segmentation fault" in stderr_lower or "sigsegv" in stderr_lower:
return "segfault"
elif "abort" in stderr_lower or "sigabrt" in stderr_lower:
return "abort"
elif "out of memory" in stderr_lower or "memory" in stderr_lower:
return "out_of_memory"
elif "assertion" in stderr_lower:
return "assertion"
else:
return f"crash_code_{exit_code}"
def run_fuzzing(self,
iterations: int = 10000,
strategy: str = 'random',
seed: Optional[int] = None) -> None:
"""
Main fuzzing loop
Args:
iterations: Number of iterations
strategy: 'random' or 'structured'
seed: Random seed for reproducibility
"""
if seed is not None:
random.seed(seed)
print(f"[*] Starting fuzzing campaign")
print(f" Target: {self.target_binary}")
print(f" Iterations: {iterations}")
print(f" Strategy: {strategy}")
print(f" Output: {self.output_dir}")
print()
try:
for i in range(iterations):
self.iteration = i
self.fuzz_iteration(i, strategy)
if (i + 1) % 100 == 0:
self._print_status(i + 1)
except KeyboardInterrupt:
print("\n[!] Fuzzing interrupted by user")
finally:
self._print_summary()
def _print_status(self, iterations: int) -> None:
"""Print fuzzing status"""
elapsed = time.time() - self.start_time
rate = iterations / elapsed if elapsed > 0 else 0
print(f"[*] Iteration {iterations} | "
f"Rate: {rate:.1f} test/s | "
f"Crashes: {len(self.crashes)}")
# Show crash types
crash_types = {}
for crash in self.crashes:
crash_types[crash.crash_type] = crash_types.get(crash.crash_type, 0) + 1
if crash_types:
types_str = ", ".join([f"{k}:{v}" for k, v in crash_types.items()])
print(f" Crash Types: {types_str}")
def _print_summary(self) -> None:
"""Print fuzzing summary"""
elapsed = time.time() - self.start_time
print("\n" + "="*60)
print("FUZZING SUMMARY")
print("="*60)
print(f"Total Iterations: {self.iteration + 1}")
print(f"Time Elapsed: {elapsed:.1f} seconds")
print(f"Test Rate: {(self.iteration + 1) / elapsed:.1f} test/s")
print(f"\nTotal Crashes Found: {len(self.crashes)}")
# Crashes by type
if self.crashes:
crash_types = {}
for crash in self.crashes:
crash_types[crash.crash_type] = crash_types.get(crash.crash_type, 0) + 1
print("\nCrashes by Type:")
for crash_type, count in sorted(crash_types.items(),
key=lambda x: x[1],
reverse=True):
print(f" {crash_type}: {count}")
print("\nUnique Crashes:")
for crash in self.crashes[:10]: # Show first 10
print(f" Seed {crash.seed}: {crash.crash_type} "
f"({crash.input_size} bytes)")
print(f"\nResults saved to: {self.output_dir}")
def generate_report(self, output_file: str = None) -> str:
"""Generate detailed report"""
if output_file is None:
output_file = self.output_dir / "fuzzing_report.html"
html_content = f"""
<html>
<head>
<title>Fuzzing Report</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 20px; }}
table {{ border-collapse: collapse; width: 100%; margin: 20px 0; }}
th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
th {{ background-color: #4CAF50; color: white; }}
tr:nth-child(even) {{ background-color: #f2f2f2; }}
.critical {{ color: red; font-weight: bold; }}
.warning {{ color: orange; }}
.info {{ color: blue; }}
pre {{ background-color: #f4f4f4; padding: 10px; overflow-x: auto; }}
</style>
</head>
<body>
<h1>Fuzzing Report</h1>
<p>Generated: {datetime.now()}</p>
<h2>Summary</h2>
<table>
<tr>
<th>Target</th>
<td>{self.target_binary}</td>
</tr>
<tr>
<th>Total Iterations</th>
<td>{self.iteration + 1}</td>
</tr>
<tr>
<th>Total Crashes</th>
<td class="critical">{len(self.crashes)}</td>
</tr>
<tr>
<th>Unique Crash Types</th>
<td>{len(set(c.crash_type for c in self.crashes))}</td>
</tr>
</table>
<h2>Crashes by Type</h2>
<table>
<tr>
<th>Crash Type</th>
<th>Count</th>
<th>Percentage</th>
</tr>
"""
crash_types = {}
for crash in self.crashes:
crash_types[crash.crash_type] = crash_types.get(crash.crash_type, 0) + 1
for crash_type, count in sorted(crash_types.items(),
key=lambda x: x[1],
reverse=True):
percentage = (count / len(self.crashes)) * 100
html_content += f"""
<tr>
<td class="warning">{crash_type}</td>
<td>{count}</td>
<td>{percentage:.1f}%</td>
</tr>
"""
html_content += """
</table>
<h2>Detailed Crashes</h2>
<table>
<tr>
<th>Seed</th>
<th>Type</th>
<th>Size</th>
<th>Time</th>
<th>Input Sample</th>
</tr>
"""
for crash in self.crashes[:100]: # First 100
html_content += f"""
<tr>
<td>{crash.seed}</td>
<td class="critical">{crash.crash_type}</td>
<td>{crash.input_size}</td>
<td>{crash.timestamp}</td>
<td><code>{crash.input_hex[:32]}...</code></td>
</tr>
"""
html_content += """
</table>
</body>
</html>
"""
output_file = Path(output_file)
output_file.write_text(html_content)
print(f"Report generated: {output_file}")
return str(output_file)
# Optional resource module import
try:
import resource
except ImportError:
resource = None
# coverage_fuzzer.py
import subprocess
import struct
from pathlib import Path
class CoverageFuzzer(BinaryFuzzer):
"""Fuzzer with coverage-guided feedback"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.coverage_data = {}
self.interesting_inputs_by_coverage = {}
def run_target_with_coverage(self, input_file: str) -> Tuple:
"""Run target and collect coverage data"""
try:
# Use LLVM coverage if available
env = os.environ.copy()
env['LLVM_PROFILE_FILE'] = f"/tmp/coverage_%p.profraw"
process = subprocess.Popen(
[self.target_binary, input_file],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env
)
try:
_, stderr = process.communicate(timeout=self.timeout)
crashed = process.returncode != 0
# Extract coverage data (simplified)
coverage_hash = hashlib.md5(
stderr.encode() if stderr else b"no_coverage"
).hexdigest()
return crashed, stderr.decode('utf-8', errors='ignore'), coverage_hash
except subprocess.TimeoutExpired:
process.kill()
return True, "TIMEOUT", "timeout_coverage"
except Exception as e:
return True, str(e), "error_coverage"
def fuzz_iteration_with_coverage(self, seed: int) -> None:
"""Fuzz iteration with coverage tracking"""
# Generate input (same as before)
if random.random() < 0.3 and self.interesting_inputs:
base_input = random.choice(self.interesting_inputs)
data = self.mutate_input(base_input)
else:
size = random.randint(1, 10000)
data = self.generate_random_input(size)
with tempfile.NamedTemporaryFile(delete=False) as f:
input_file = f.name
f.write(data)
try:
crashed, stderr, coverage_hash = self.run_target_with_coverage(input_file)
# Track coverage
if coverage_hash not in self.coverage_data:
self.coverage_data[coverage_hash] = {
'seed': seed,
'input': data,
'first_seen': datetime.now().isoformat()
}
self.interesting_inputs.append(data)
if crashed:
crash_type = self._classify_crash(stderr, -1)
crash_info = CrashInfo(
seed=seed,
timestamp=datetime.now().isoformat(),
input_file=input_file,
crash_type=crash_type,
stderr_output=stderr[:1000],
exit_code=-1,
input_size=len(data),
input_hex=data.hex()[:128]
)
self.save_crash(data, crash_info)
finally:
try:
os.unlink(input_file)
except:
pass
# crash_reproducer.py
import subprocess
import sys
from pathlib import Path
class CrashReproducer:
"""Reproduce and analyze crashes"""
def __init__(self, target_binary: str, crash_dir: str = "fuzz_results/crashes"):
self.target_binary = target_binary
self.crash_dir = Path(crash_dir)
def reproduce_crash(self, seed: int, verbose: bool = True) -> Dict:
"""Reproduce a specific crash"""
crash_file = self.crash_dir / f"crash_{seed}_*.bin"
# Find matching crash file
crash_files = list(self.crash_dir.glob(f"crash_{seed}_*.bin"))
if not crash_files:
print(f"No crash found for seed {seed}")
return {}
crash_file = crash_files[0]
json_file = crash_file.with_suffix('.json')
if not json_file.exists():
print(f"No metadata for {crash_file}")
return {}
crash_info = json.loads(json_file.read_text())
if verbose:
print(f"\n{'='*60}")
print(f"REPRODUCING CRASH: Seed {seed}")
print(f"{'='*60}")
print(f"Type: {crash_info['crash_type']}")
print(f"Size: {crash_info['input_size']} bytes")
print(f"Input: {crash_info['input_hex']}")
print(f"\nRunning with gdb...\n")
# Run with GDB for detailed info
self._run_with_gdb(str(crash_file))
return crash_info
def _run_with_gdb(self, input_file: str) -> None:
"""Run target in GDB"""
gdb_commands = f"""
file {self.target_binary}
run {input_file}
bt full
quit
"""
with tempfile.NamedTemporaryFile(mode='w', suffix='.gdb', delete=False) as f:
f.write(gdb_commands)
gdb_file = f.name
try:
subprocess.run(['gdb', '-x', gdb_file], check=False)
except FileNotFoundError:
print("GDB not found. Running normally...")
subprocess.run([self.target_binary, input_file])
finally:
os.unlink(gdb_file)
def minimize_crash(self, seed: int) -> bytes:
"""Minimize crash input to smallest failing case"""
crash_files = list(self.crash_dir.glob(f"crash_{seed}_*.bin"))
if not crash_files:
return b""
data = crash_files[0].read_bytes()
print(f"Minimizing crash from {len(data)} bytes...")
while len(data) > 1:
# Try to remove each byte
for i in range(len(data)):
test_data = data[:i] + data[i+1:]
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(test_data)
test_file = f.name
try:
result = subprocess.run(
[self.target_binary, test_file],
capture_output=True,
timeout=5
)
if result.returncode != 0:
# Still crashes, keep this version
data = test_data
print(f"Minimized to {len(data)} bytes")
break
except subprocess.TimeoutExpired:
# Timeout counts as crash
data = test_data
break
finally:
os.unlink(test_file)
else:
# No reduction found
break
print(f"Minimized to {len(data)} bytes")
return data