prod2u_validate.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. #!/usr/bin/env python3
  2. """Raw-first validator for Prod2U PROGRAM_SRAM binary921 evidence."""
  3. from __future__ import annotations
  4. import hashlib
  5. import json
  6. import sys
  7. from datetime import datetime, timezone
  8. from pathlib import Path
  9. from typing import Any, Mapping
  10. TOOLS = Path(__file__).resolve().parent
  11. if str(TOOLS) not in sys.path:
  12. sys.path.insert(0, str(TOOLS))
  13. from binary921 import MAGIC, CommandId, FrameType, decode_frame, decode_payload, frame_to_dict # noqa: E402
  14. from prod2u_collector import COMMAND_SEQUENCE # noqa: E402
  15. from prod2u_receipts import validate_evidence_manifest # noqa: E402
  16. PROFILE = "prod2u-bmc-replay-binary921"
  17. PROFILE_ID = 3
  18. def sha256_bytes(data: bytes) -> str:
  19. return hashlib.sha256(data).hexdigest()
  20. def _mapping(value: Any) -> Mapping[str, Any]:
  21. return value if isinstance(value, Mapping) else {}
  22. def _receipt_int(value: Any) -> int | None:
  23. if isinstance(value, bool) or not isinstance(value, int):
  24. return None
  25. return value
  26. def _parse_utc(value: Any) -> datetime | None:
  27. if not isinstance(value, str) or not value:
  28. return None
  29. normalized = value[:-1] + "+00:00" if value.endswith("Z") else value
  30. try:
  31. parsed = datetime.fromisoformat(normalized)
  32. except ValueError:
  33. return None
  34. if parsed.tzinfo is None:
  35. parsed = parsed.replace(tzinfo=timezone.utc)
  36. return parsed.astimezone(timezone.utc)
  37. def strict_decode_stream(data: bytes) -> dict[str, Any]:
  38. failures: list[str] = []
  39. frames: list[dict[str, Any]] = []
  40. offset = 0
  41. if not data:
  42. failures.append("raw_empty")
  43. while offset < len(data):
  44. if data[offset : offset + 2] != MAGIC:
  45. failures.append(f"unexpected_bytes_at_offset:{offset}")
  46. break
  47. if len(data) - offset < 16:
  48. failures.append(f"incomplete_frame_header_at_offset:{offset}")
  49. break
  50. payload_len = data[offset + 13]
  51. end = offset + 14 + payload_len + 2
  52. if end > len(data):
  53. failures.append(f"incomplete_frame_at_offset:{offset}")
  54. break
  55. candidate = data[offset:end]
  56. try:
  57. frame = decode_frame(candidate)
  58. except Exception as exc:
  59. failures.append(f"corrupt_frame_at_offset:{offset}:{exc}")
  60. break
  61. row = frame_to_dict(frame)
  62. row["offset"] = offset
  63. row["end_offset"] = end
  64. frames.append(row)
  65. offset = end
  66. if offset != len(data) and not failures:
  67. failures.append(f"unconsumed_bytes_at_offset:{offset}")
  68. return {
  69. "status": "pass" if frames and not failures and offset == len(data) else "fail",
  70. "byte_count": len(data),
  71. "frame_count": len(frames),
  72. "consumed_bytes": offset,
  73. "failures": failures,
  74. "frames": frames,
  75. }
  76. def _validate_commands(frames: list[dict[str, Any]]) -> dict[str, Any]:
  77. failures: list[str] = []
  78. commands = [frame for frame in frames if frame.get("frame_type") == int(FrameType.HOST_CMD)]
  79. if len(commands) != len(COMMAND_SEQUENCE):
  80. failures.append(f"host_command_count_not_12:{len(commands)}")
  81. for index, expected in enumerate(COMMAND_SEQUENCE, start=1):
  82. if index > len(commands):
  83. break
  84. _, command, channel, percent = expected
  85. frame = commands[index - 1]
  86. decoded = _mapping(frame.get("decoded"))
  87. if frame.get("profile_id") != PROFILE_ID:
  88. failures.append(f"host_command_profile_mismatch:{index}")
  89. if frame.get("seq") != index:
  90. failures.append(f"host_command_seq_mismatch:{index}:{frame.get('seq')}")
  91. if decoded.get("cmd_id") != int(command):
  92. failures.append(f"host_command_id_mismatch:{index}")
  93. if channel is not None and decoded.get("channel") != channel:
  94. failures.append(f"host_command_channel_mismatch:{index}")
  95. if command == CommandId.SET_PID_REQUESTED:
  96. if decoded.get("enabled") is not bool(percent):
  97. failures.append(f"host_command_enabled_mismatch:{index}")
  98. elif percent is not None and decoded.get("percent") != percent:
  99. failures.append(f"host_command_percent_mismatch:{index}")
  100. return {"status": "pass" if not failures else "fail", "count": len(commands), "failures": failures}
  101. def _validate_acks(frames: list[dict[str, Any]]) -> dict[str, Any]:
  102. failures: list[str] = []
  103. acks = [frame for frame in frames if frame.get("frame_type") == int(FrameType.HOST_ACK)]
  104. matched = 0
  105. if len(acks) != len(COMMAND_SEQUENCE):
  106. failures.append(f"host_ack_count_not_12:{len(acks)}")
  107. for index, expected in enumerate(COMMAND_SEQUENCE, start=1):
  108. if index > len(acks):
  109. break
  110. _, command, _, _ = expected
  111. frame = acks[index - 1]
  112. decoded = _mapping(frame.get("decoded"))
  113. accepted = (
  114. frame.get("profile_id") == PROFILE_ID
  115. and frame.get("seq") == index
  116. and decoded.get("cmd_id") == int(command)
  117. and decoded.get("ok") is True
  118. and decoded.get("status_code") == 0
  119. )
  120. if accepted:
  121. matched += 1
  122. else:
  123. failures.append(f"host_ack_mismatch:{index}")
  124. return {
  125. "status": "pass" if not failures and matched == len(COMMAND_SEQUENCE) else "fail",
  126. "count": len(acks),
  127. "matched_count": matched,
  128. "failures": failures,
  129. }
  130. def _load_bmc_receipt(path: Path) -> dict[str, Any]:
  131. if not path.is_file():
  132. return {"status": "not_run", "bmc_source": "not_run", "payload_sha256": None}
  133. try:
  134. payload = json.loads(path.read_text(encoding="utf-8-sig"))
  135. except (OSError, json.JSONDecodeError) as exc:
  136. return {
  137. "status": "blocked_invalid_bmc_replay_receipt",
  138. "bmc_source": "not_run",
  139. "payload_sha256": None,
  140. "error": str(exc),
  141. "failures": ["bmc_receipt_unreadable"],
  142. }
  143. if not isinstance(payload, dict):
  144. return {
  145. "status": "blocked_invalid_bmc_replay_receipt",
  146. "bmc_source": "not_run",
  147. "payload_sha256": None,
  148. "failures": ["bmc_receipt_not_object"],
  149. }
  150. failures: list[str] = []
  151. reply_sha = str(payload.get("reply_sha256") or payload.get("payload_reply_sha256") or "").lower()
  152. values: bytes | None = None
  153. payload_hex = payload.get("payload_hex")
  154. if not isinstance(payload_hex, list) or len(payload_hex) != 48:
  155. failures.append("bmc_receipt_payload_hex_not_48")
  156. else:
  157. try:
  158. values = bytes(int(str(value), 16) for value in payload_hex)
  159. except (TypeError, ValueError, OverflowError):
  160. failures.append("bmc_receipt_payload_hex_invalid")
  161. else:
  162. canonical_reply = " ".join(f"{value:02x}" for value in values) + "\r\n"
  163. if sha256_bytes(canonical_reply.encode("ascii")) != reply_sha:
  164. failures.append("bmc_receipt_reply_sha256_mismatch")
  165. if payload.get("schema") != "prod2u-bmc-replay-session-v1":
  166. failures.append("bmc_receipt_schema_mismatch")
  167. if payload.get("status") != "pass":
  168. failures.append("bmc_receipt_status_not_pass")
  169. if payload.get("bmc_source") != "pc_replay_from_real_bmc_capture":
  170. failures.append("bmc_receipt_source_mismatch")
  171. matched_poll_count = _receipt_int(payload.get("matched_poll_count"))
  172. reply_count = _receipt_int(payload.get("reply_count"))
  173. if matched_poll_count is None or matched_poll_count <= 0 or reply_count is None or reply_count <= 0:
  174. failures.append("bmc_receipt_no_poll_response")
  175. byte_count = _receipt_int(payload.get("byte_count"))
  176. if byte_count != 48:
  177. failures.append("bmc_receipt_byte_count_not_48")
  178. valid_count = _receipt_int(payload.get("valid_count"))
  179. missing_count = _receipt_int(payload.get("missing_count"))
  180. if (
  181. valid_count is None
  182. or missing_count is None
  183. or valid_count < 0
  184. or missing_count < 0
  185. or valid_count + missing_count != 24
  186. ):
  187. failures.append("bmc_receipt_sensor_count_not_24")
  188. passed = not failures
  189. return {
  190. "status": "pass" if passed else "blocked_bmc_replay_not_run",
  191. "schema": payload.get("schema"),
  192. "bmc_source": payload.get("bmc_source", "not_run"),
  193. "payload_sha256": reply_sha or None,
  194. "byte_count": byte_count,
  195. "valid_count": valid_count,
  196. "missing_count": missing_count,
  197. "matched_poll_count": matched_poll_count,
  198. "reply_count": reply_count,
  199. "started_at": payload.get("started_at"),
  200. "last_reply_at": payload.get("last_reply_at"),
  201. "payload_hex": payload_hex if values is not None else None,
  202. "payload_first": None if values is None else values[0],
  203. "payload_last": None if values is None else values[-1],
  204. "payload_checksum": None if values is None else sum(values) & 0xFFFF,
  205. "failures": failures,
  206. }
  207. def validate_evidence_directory(
  208. *,
  209. collector_dir: Path,
  210. collector: Mapping[str, Any],
  211. program: Mapping[str, Any],
  212. source_manifest: Mapping[str, Any],
  213. programmer_receipt_path: str,
  214. programmer_receipt_sha256: str,
  215. bmc_replay_receipt_path: Path,
  216. ) -> dict[str, Any]:
  217. collector_dir = Path(collector_dir)
  218. combined_path = collector_dir / "combined-rx.raw"
  219. command_path = collector_dir / "host-command-wire.bin"
  220. combined = combined_path.read_bytes() if combined_path.is_file() else b""
  221. command_wire = command_path.read_bytes() if command_path.is_file() else b""
  222. combined_validation = strict_decode_stream(combined)
  223. command_validation = strict_decode_stream(command_wire)
  224. combined_frames = list(combined_validation["frames"])
  225. command_frames = list(command_validation["frames"])
  226. failures: list[str] = []
  227. failures.extend(f"combined:{failure}" for failure in combined_validation["failures"])
  228. failures.extend(f"host_wire:{failure}" for failure in command_validation["failures"])
  229. ready_frames = [frame for frame in combined_frames if frame.get("frame_type") == int(FrameType.READY)]
  230. expected_build_id = str(source_manifest.get("build_id", "")).upper()
  231. def ready_matches_identity(frame: Mapping[str, Any]) -> bool:
  232. decoded = _mapping(frame.get("decoded"))
  233. return (
  234. frame.get("profile_id") == PROFILE_ID
  235. and frame.get("seq") == 1
  236. and decoded.get("profile_id_payload") == PROFILE_ID
  237. and decoded.get("build_id") == expected_build_id
  238. and decoded.get("por_reason") == 1
  239. and isinstance(decoded.get("announcement_seq"), int)
  240. and 0 <= int(decoded["announcement_seq"]) <= 2
  241. )
  242. matching_ready_frames = [frame for frame in ready_frames if ready_matches_identity(frame)]
  243. if matching_ready_frames and int(matching_ready_frames[0].get("offset", -1)) != 0:
  244. failures.append("formal_epoch_does_not_start_at_matching_ready")
  245. ready = matching_ready_frames[-1] if matching_ready_frames else ready_frames[-1] if ready_frames else {}
  246. ready_decoded = _mapping(ready.get("decoded"))
  247. formal_frames = [
  248. frame
  249. for frame in combined_frames
  250. if ready and int(frame.get("offset", -1)) >= int(ready.get("end_offset", 0))
  251. ]
  252. command_result = _validate_commands(command_frames)
  253. ack_result = _validate_acks(formal_frames)
  254. failures.extend(command_result["failures"])
  255. failures.extend(ack_result["failures"])
  256. if not ready:
  257. failures.append("startup_ready_missing")
  258. elif not ready_matches_identity(ready):
  259. failures.append("startup_ready_identity_mismatch")
  260. bmc_replay = _load_bmc_receipt(Path(bmc_replay_receipt_path))
  261. bmc_replay_pass = bmc_replay["status"] == "pass"
  262. bmc_frames = [frame for frame in formal_frames if frame.get("frame_type") == int(FrameType.BMC_PAYLOAD)]
  263. sensor_frames = [frame for frame in formal_frames if frame.get("frame_type") == int(FrameType.SENSOR_CACHE)]
  264. snapshot_frames = [frame for frame in formal_frames if frame.get("frame_type") == int(FrameType.MODULE_SNAPSHOT)]
  265. if bmc_replay_pass and not bmc_frames:
  266. failures.append("bmc_payload_frame_missing")
  267. sensor = _mapping(sensor_frames[-1].get("decoded")) if sensor_frames else {}
  268. valid_count = sensor.get("valid_count")
  269. missing_count = sensor.get("missing_count")
  270. sensor_cache_valid = (
  271. isinstance(valid_count, int)
  272. and isinstance(missing_count, int)
  273. and valid_count + missing_count == 24
  274. )
  275. if bmc_replay_pass and not sensor_cache_valid:
  276. failures.append("sensor_cache_not_24_dimms")
  277. snapshot = _mapping(snapshot_frames[-1].get("decoded")) if snapshot_frames else {}
  278. if not snapshot_frames:
  279. failures.append("module_snapshot_missing")
  280. pid_status = "pass" if snapshot.get("pid_requested") is False else "fail"
  281. if pid_status != "pass":
  282. failures.append("pid_not_inactive")
  283. timeout_status = "pass" if (
  284. snapshot.get("timeout_active") is True
  285. and snapshot.get("ptc01_percent") == 0
  286. and snapshot.get("ptc24_percent") == 0
  287. and snapshot.get("fan01_percent") == 30
  288. and snapshot.get("fan04_percent") == 30
  289. ) else "fail"
  290. if timeout_status != "pass":
  291. failures.append("timeout_fallback_invalid")
  292. actual_hashes = {
  293. "combined-rx.raw": sha256_bytes(combined),
  294. "host-command-wire.bin": sha256_bytes(command_wire),
  295. }
  296. expected_hashes = _mapping(collector.get("artifact_hashes"))
  297. artifact_mismatches = [
  298. name for name, actual in actual_hashes.items() if expected_hashes.get(name) != actual
  299. ]
  300. failures.extend(f"collector_artifact_hash_mismatch:{name}" for name in artifact_mismatches)
  301. if not bmc_replay_pass:
  302. failures.extend(f"bmc_replay:{failure}" for failure in bmc_replay.get("failures", []))
  303. elif bmc_frames:
  304. observed_bmc = _mapping(bmc_frames[-1].get("decoded"))
  305. expected_bmc_fields = {
  306. "payload_len_reported": 48,
  307. "payload_count": 48,
  308. "first_byte": bmc_replay.get("payload_first"),
  309. "last_byte": bmc_replay.get("payload_last"),
  310. "checksum": bmc_replay.get("payload_checksum"),
  311. }
  312. for field, expected in expected_bmc_fields.items():
  313. if observed_bmc.get(field) != expected:
  314. failures.append(f"bmc_payload_provenance_mismatch:{field}")
  315. if valid_count != bmc_replay.get("valid_count") or missing_count != bmc_replay.get("missing_count"):
  316. failures.append("bmc_sensor_cache_provenance_mismatch")
  317. program_started_at = _parse_utc(_mapping(program.get("execution")).get("started_at"))
  318. bmc_last_reply_at = _parse_utc(bmc_replay.get("last_reply_at"))
  319. if program_started_at is None or bmc_last_reply_at is None:
  320. failures.append("bmc_session_time_evidence_missing")
  321. elif bmc_last_reply_at < program_started_at:
  322. failures.append("bmc_session_predates_program_invocation")
  323. evidence: dict[str, Any] = {
  324. "schema": "prod2u-evidence-manifest-v1",
  325. "status": "pass",
  326. "protocol": "binary921",
  327. "profile": PROFILE,
  328. "profile_id": PROFILE_ID,
  329. "build_identity": {
  330. "build_id": str(source_manifest.get("build_id", "")).upper(),
  331. "source_manifest_sha256": str(source_manifest.get("source_manifest_sha256", "")).lower(),
  332. },
  333. "programmer_receipt": {
  334. "path": programmer_receipt_path,
  335. "sha256": programmer_receipt_sha256,
  336. "status": program.get("status"),
  337. },
  338. "startup_ready": {
  339. "frame_type": ready.get("frame_type"),
  340. "seq": ready.get("seq"),
  341. "profile_id": ready.get("profile_id"),
  342. "build_id": ready_decoded.get("build_id"),
  343. "post_program_epoch": program.get("status") == "pass" and bool(ready),
  344. "timestamp_tick": ready.get("timestamp_tick"),
  345. "por_reason": ready_decoded.get("por_reason"),
  346. "announcement_seq": ready_decoded.get("announcement_seq"),
  347. "matching_ready_count": len(matching_ready_frames),
  348. "selection_policy": "last_matching_ready" if matching_ready_frames else None,
  349. "epoch_start_offset": _mapping(collector.get("startup_ready")).get("epoch_start_offset"),
  350. },
  351. "host_command_count": command_result["count"],
  352. "host_ack_count": ack_result["count"],
  353. "host_ack_matched_count": ack_result["matched_count"],
  354. "bmc_replay": bmc_replay,
  355. "artifact_hashes": actual_hashes,
  356. "real_fan_ptc_hardware_status": "not_run",
  357. "safety": {
  358. "flash_attempted": False,
  359. "programs_nonvolatile": False,
  360. "driver_install_attempted": False,
  361. "power_cycle_attempted": False,
  362. "toggles_dtr_rts": False,
  363. },
  364. "raw_validation": {
  365. "combined": {key: value for key, value in combined_validation.items() if key != "frames"},
  366. "host_command_wire": {key: value for key, value in command_validation.items() if key != "frames"},
  367. "host_commands": command_result,
  368. "host_acks": ack_result,
  369. "sensor_cache": {
  370. "status": "pass" if sensor_cache_valid else ("fail" if bmc_replay_pass else "not_run"),
  371. "valid_count": valid_count,
  372. "missing_count": missing_count,
  373. },
  374. "pid_inactive": {"status": pid_status},
  375. "timeout_fallback": {"status": timeout_status},
  376. "artifact_hash_mismatches": artifact_mismatches,
  377. },
  378. }
  379. contract = validate_evidence_manifest(evidence, program)
  380. blockers = list(dict.fromkeys(list(contract["failures"]) + failures))
  381. if failures:
  382. status = "fail"
  383. else:
  384. status = contract["status"]
  385. evidence["status"] = status
  386. evidence["blockers"] = blockers
  387. return evidence