manual_6400_fuzz.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/env python3
  2. """Deterministic malformed UART/I2C protocol fuzz without hardware dependencies."""
  3. from __future__ import annotations
  4. import json
  5. import os
  6. import random
  7. from pathlib import Path
  8. def crc16(data: bytes) -> int:
  9. value = 0xFFFF
  10. for byte in data:
  11. value ^= byte << 8
  12. for _ in range(8):
  13. value = ((value << 1) ^ 0x1021) & 0xFFFF if value & 0x8000 else (value << 1) & 0xFFFF
  14. return value
  15. def encode(kind: int, payload: bytes = b"") -> bytes:
  16. body = bytes((kind, len(payload))) + payload
  17. return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
  18. def decode(raw: bytes) -> bool:
  19. 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])
  20. def main() -> int:
  21. seed = int(os.environ.get("PROD2U_FUZZ_SEED", "6400"))
  22. iterations = int(os.environ.get("PROD2U_FUZZ_ITERATIONS", "10000"))
  23. rng = random.Random(seed)
  24. accepted = rejected = 0
  25. for _ in range(iterations):
  26. payload = bytes(rng.randrange(256) for _ in range(rng.randrange(33)))
  27. raw = bytearray(encode(rng.randrange(1, 0x84), payload))
  28. mutation = rng.randrange(5)
  29. if mutation == 0:
  30. raw[0] ^= 1
  31. elif mutation == 1:
  32. raw[-1] ^= 1
  33. elif mutation == 2:
  34. raw = raw[:-1]
  35. elif mutation == 3:
  36. raw[3] = (raw[3] + 1) & 0xFF
  37. else:
  38. raw.extend(bytes((0xA5, 0x5A)))
  39. if decode(bytes(raw)):
  40. accepted += 1
  41. else:
  42. rejected += 1
  43. assert accepted == 0
  44. # Register pointer fuzz: only the declared write windows are writable.
  45. writable = lambda reg: 0x0100 <= reg <= 0x011F or reg == 0x0010
  46. for _ in range(iterations):
  47. reg = rng.randrange(0x10000)
  48. if writable(reg):
  49. assert reg == 0x0010 or 0x0100 <= reg <= 0x011F
  50. result = {"status": "PASS", "seed": seed, "iterations": iterations, "accepted_mutations": accepted, "rejected_mutations": rejected, "write_window_guard": "PASS"}
  51. output = os.environ.get("PROD2U_FUZZ_RESULT")
  52. if output:
  53. Path(output).write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  54. print("MANUAL_FUZZ_PASS", json.dumps(result, sort_keys=True))
  55. return 0
  56. if __name__ == "__main__":
  57. raise SystemExit(main())