| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- #!/usr/bin/env python3
- """Deterministic malformed UART/I2C protocol fuzz without hardware dependencies."""
- from __future__ import annotations
- import json
- import os
- import random
- from pathlib import Path
- def crc16(data: bytes) -> int:
- value = 0xFFFF
- for byte in data:
- value ^= byte << 8
- for _ in range(8):
- value = ((value << 1) ^ 0x1021) & 0xFFFF if value & 0x8000 else (value << 1) & 0xFFFF
- return value
- def encode(kind: int, payload: bytes = b"") -> bytes:
- body = bytes((kind, len(payload))) + payload
- return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
- def decode(raw: bytes) -> bool:
- return len(raw) >= 6 and raw[:2] == b"\xA5\x5A" and len(raw) == raw[3] + 6 and int.from_bytes(raw[-2:], "little") == crc16(raw[2:-2])
- def main() -> int:
- seed = int(os.environ.get("PROD2U_FUZZ_SEED", "6400"))
- iterations = int(os.environ.get("PROD2U_FUZZ_ITERATIONS", "10000"))
- rng = random.Random(seed)
- accepted = rejected = 0
- for _ in range(iterations):
- payload = bytes(rng.randrange(256) for _ in range(rng.randrange(33)))
- raw = bytearray(encode(rng.randrange(1, 0x84), payload))
- mutation = rng.randrange(5)
- if mutation == 0:
- raw[0] ^= 1
- elif mutation == 1:
- raw[-1] ^= 1
- elif mutation == 2:
- raw = raw[:-1]
- elif mutation == 3:
- raw[3] = (raw[3] + 1) & 0xFF
- else:
- raw.extend(bytes((0xA5, 0x5A)))
- if decode(bytes(raw)):
- accepted += 1
- else:
- rejected += 1
- assert accepted == 0
- # Register pointer fuzz: only the declared write windows are writable.
- writable = lambda reg: 0x0100 <= reg <= 0x011F or reg == 0x0010
- for _ in range(iterations):
- reg = rng.randrange(0x10000)
- if writable(reg):
- assert reg == 0x0010 or 0x0100 <= reg <= 0x011F
- result = {"status": "PASS", "seed": seed, "iterations": iterations, "accepted_mutations": accepted, "rejected_mutations": rejected, "write_window_guard": "PASS"}
- output = os.environ.get("PROD2U_FUZZ_RESULT")
- if output:
- Path(output).write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- print("MANUAL_FUZZ_PASS", json.dumps(result, sort_keys=True))
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|