cpld_c_drive_audit.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. """Read-only inventory and archive comparison for CPLD-related C-drive paths."""
  2. from __future__ import annotations
  3. import argparse
  4. import ctypes
  5. import hashlib
  6. import json
  7. import os
  8. import re
  9. import stat
  10. import subprocess
  11. import sys
  12. import zipfile
  13. from dataclasses import dataclass, field
  14. from datetime import datetime, timezone
  15. from functools import lru_cache
  16. from pathlib import Path, PurePosixPath
  17. from typing import Any, Iterable, Iterator, Mapping, Sequence
  18. SCHEMA = "cpld-c-drive-audit-v1"
  19. CONFIG_SCHEMA = "cpld-c-drive-audit-config-v1"
  20. DEFAULT_CONFIG = Path(__file__).resolve().parents[1] / "config" / "cpld_c_drive_audit.json"
  21. MAX_MEMBER_BYTES = 8 * 1024 * 1024 * 1024
  22. REPARSE_ATTRIBUTE = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
  23. DEFAULT_CANDIDATE_PATTERNS = (
  24. "cpld",
  25. "p4",
  26. "prod2u",
  27. "temperature",
  28. "normal",
  29. "handoff",
  30. "analysis",
  31. "board",
  32. "ct7428",
  33. "fpga",
  34. )
  35. DEFAULT_PROTECTED_PATTERNS = (
  36. "release",
  37. "source",
  38. "firmware",
  39. "final-gate",
  40. "rc1",
  41. "sha256sums",
  42. "license",
  43. r"\.lic$",
  44. "private",
  45. "original",
  46. r"hardware[-_ ]evidence",
  47. )
  48. @dataclass(frozen=True)
  49. class AuditConfig:
  50. candidate_patterns: tuple[str, ...] = DEFAULT_CANDIDATE_PATTERNS
  51. excluded_patterns: tuple[str, ...] = ()
  52. protected_patterns: tuple[str, ...] = DEFAULT_PROTECTED_PATTERNS
  53. max_files: int = 100_000
  54. root_scopes: Mapping[str, str] = field(default_factory=dict)
  55. @classmethod
  56. def from_mapping(cls, payload: Mapping[str, Any]) -> "AuditConfig":
  57. if payload.get("schema") not in (None, CONFIG_SCHEMA):
  58. raise ValueError(f"unsupported audit config schema: {payload.get('schema')!r}")
  59. roots = payload.get("scan_roots", [])
  60. scopes = {
  61. str(Path(item["path"]).resolve()): str(item.get("scope", "configured_root"))
  62. for item in roots
  63. if isinstance(item, Mapping) and item.get("path")
  64. }
  65. return cls(
  66. candidate_patterns=tuple(str(item) for item in payload.get("candidate_patterns", DEFAULT_CANDIDATE_PATTERNS)),
  67. excluded_patterns=tuple(str(item) for item in payload.get("excluded_patterns", ())),
  68. protected_patterns=tuple(str(item) for item in payload.get("protected_patterns", DEFAULT_PROTECTED_PATTERNS)),
  69. max_files=max(1, int(payload.get("max_files", 100_000))),
  70. root_scopes=scopes,
  71. )
  72. def _now() -> str:
  73. return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
  74. def _matches(value: str, patterns: Sequence[str]) -> bool:
  75. for pattern in patterns:
  76. try:
  77. if re.search(pattern, value, flags=re.IGNORECASE):
  78. return True
  79. except re.error:
  80. if pattern.casefold() in value.casefold():
  81. return True
  82. return False
  83. def _is_reparse(path: Path, file_stat: os.stat_result | None = None) -> bool:
  84. if path.is_symlink():
  85. return True
  86. try:
  87. value = file_stat if file_stat is not None else path.stat(follow_symlinks=False)
  88. return bool(getattr(value, "st_file_attributes", 0) & REPARSE_ATTRIBUTE)
  89. except OSError:
  90. return False
  91. def _safe_resolve(path: Path) -> Path:
  92. try:
  93. return path.resolve(strict=False)
  94. except OSError:
  95. return Path(os.path.abspath(os.fspath(path)))
  96. def _absolute_path(path: Path) -> Path:
  97. raw = os.fspath(path)
  98. if not os.path.isabs(raw):
  99. raw = os.path.abspath(raw)
  100. if os.name != "nt":
  101. return Path(raw)
  102. buffer = ctypes.create_unicode_buffer(32768)
  103. length = ctypes.windll.kernel32.GetFullPathNameW(raw, len(buffer), buffer, None)
  104. if not length:
  105. return Path(raw)
  106. full = buffer.value[:length]
  107. long_buffer = ctypes.create_unicode_buffer(32768)
  108. long_length = ctypes.windll.kernel32.GetLongPathNameW(full, long_buffer, len(long_buffer))
  109. return Path(long_buffer.value[:long_length] if long_length else full)
  110. def _sha256(path: Path) -> str:
  111. digest = hashlib.sha256()
  112. with path.open("rb") as handle:
  113. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  114. digest.update(chunk)
  115. return digest.hexdigest()
  116. def _git_anchor(path: Path) -> Path | None:
  117. current = path if path.is_dir() else path.parent
  118. for candidate in (current, *current.parents):
  119. try:
  120. if (candidate / ".git").exists() or (candidate / ".git").is_file():
  121. return candidate
  122. except OSError:
  123. continue
  124. return None
  125. @lru_cache(maxsize=256)
  126. def _git_context_for_anchor(anchor_value: str) -> tuple[str | None, bool, list[str]]:
  127. anchor = Path(anchor_value)
  128. if not anchor.exists():
  129. return None, False, []
  130. try:
  131. top = subprocess.run(
  132. ["git", "-C", str(anchor), "rev-parse", "--show-toplevel"],
  133. check=True,
  134. capture_output=True,
  135. text=True,
  136. timeout=10,
  137. ).stdout.strip()
  138. common_raw = subprocess.run(
  139. ["git", "-C", str(anchor), "rev-parse", "--git-common-dir"],
  140. check=True,
  141. capture_output=True,
  142. text=True,
  143. timeout=10,
  144. ).stdout.strip()
  145. common = _safe_resolve(Path(common_raw) if os.path.isabs(common_raw) else Path(top) / common_raw)
  146. status = subprocess.run(
  147. ["git", "-C", str(anchor), "status", "--porcelain", "--untracked-files=all"],
  148. check=True,
  149. capture_output=True,
  150. text=True,
  151. timeout=20,
  152. ).stdout
  153. except (OSError, subprocess.SubprocessError):
  154. return None, False, ["git_probe_failed"]
  155. return str(common), bool(status.strip()), [f"git_worktree:{top}", f"git_common_dir:{common}"]
  156. def _git_context(path: Path) -> tuple[str | None, bool, list[str]]:
  157. anchor = _git_anchor(path)
  158. return _git_context_for_anchor(str(anchor)) if anchor is not None else (None, False, [])
  159. def _base_record(path: Path | None, *, size: int | None, sha256: str | None, classification: str,
  160. recommended_action: str, reason: str, reparse_point: bool = False,
  161. comparison_target: str | None = None, comparison_result: str = "not_compared",
  162. ownership_evidence: Iterable[str] = ()) -> dict[str, Any]:
  163. resolved_path = _safe_resolve(path) if path is not None else None
  164. absolute = str(_absolute_path(path)) if path is not None else None
  165. resolved = str(resolved_path) if resolved_path is not None else None
  166. git_common_dir, dirty, git_evidence = _git_context(path) if path is not None else (None, False, [])
  167. evidence = list(dict.fromkeys([*ownership_evidence, *git_evidence]))
  168. return {
  169. "absolute_path": absolute,
  170. "resolved_path": resolved,
  171. "size": size,
  172. "git_common_dir": git_common_dir,
  173. "worktree_dirty": dirty,
  174. "reparse_point": reparse_point,
  175. "ownership_evidence": evidence,
  176. "sha256": sha256,
  177. "comparison_target": comparison_target,
  178. "comparison_result": comparison_result,
  179. "classification": classification,
  180. "recommended_action": recommended_action,
  181. "reason": reason,
  182. }
  183. def _iter_files(root: Path, config: AuditConfig) -> Iterator[tuple[Path, os.stat_result, bool]]:
  184. pending = [root]
  185. while pending:
  186. current = pending.pop()
  187. try:
  188. entries = list(os.scandir(current))
  189. except OSError:
  190. continue
  191. for entry in sorted(entries, key=lambda item: item.name.casefold()):
  192. path = Path(entry.path)
  193. try:
  194. file_stat = entry.stat(follow_symlinks=False)
  195. except OSError:
  196. continue
  197. if _matches(str(path), config.excluded_patterns):
  198. continue
  199. reparse = _is_reparse(path, file_stat)
  200. if entry.is_dir(follow_symlinks=False):
  201. if reparse:
  202. yield path, file_stat, True
  203. else:
  204. pending.append(path)
  205. continue
  206. yield path, file_stat, reparse
  207. def _record_file(
  208. path: Path,
  209. file_stat: os.stat_result,
  210. reparse: bool,
  211. config: AuditConfig,
  212. *,
  213. force_include: bool = False,
  214. ) -> dict[str, Any] | None:
  215. text = str(path)
  216. if not force_include and not _matches(text, config.candidate_patterns):
  217. return None
  218. evidence = ["configured_root_scope" if force_include else "candidate_name_match"]
  219. protected = _matches(text, config.protected_patterns)
  220. if reparse:
  221. return _base_record(
  222. path,
  223. size=int(file_stat.st_size),
  224. sha256=None,
  225. classification="reparse_point",
  226. recommended_action="retain_and_review",
  227. reason="reparse point was not followed or hashed",
  228. reparse_point=True,
  229. ownership_evidence=evidence,
  230. )
  231. try:
  232. digest = _sha256(path)
  233. except OSError as exc:
  234. return _base_record(
  235. path,
  236. size=int(file_stat.st_size),
  237. sha256=None,
  238. classification="unreadable_cpld_related_file",
  239. recommended_action="retain_and_review",
  240. reason=f"sha256 failed: {exc}",
  241. ownership_evidence=evidence,
  242. )
  243. if protected:
  244. classification = "protected_asset"
  245. action = "retain"
  246. reason = "release/source/original/license/private or hardware evidence path"
  247. elif path.suffix.casefold() in {".zip", ".7z", ".rar"}:
  248. classification = "archive_candidate"
  249. action = "review_with_compare_archives"
  250. reason = "archive requires independent member/hash comparison before any disposal"
  251. else:
  252. classification = "cpld_related_file"
  253. action = "review"
  254. reason = "under a configured CPLD scope" if force_include else "matched configured CPLD/P4 name or path pattern"
  255. return _base_record(
  256. path,
  257. size=int(file_stat.st_size),
  258. sha256=digest,
  259. classification=classification,
  260. recommended_action=action,
  261. reason=reason,
  262. ownership_evidence=evidence,
  263. )
  264. def scan_paths(paths: Sequence[Path], *, config: AuditConfig) -> dict[str, Any]:
  265. records: list[dict[str, Any]] = []
  266. visited = 0
  267. root_names = [str(_safe_resolve(Path(path))) for path in paths]
  268. for root_value in paths:
  269. root = Path(root_value)
  270. if not root.exists():
  271. continue
  272. root_scope = config.root_scopes.get(str(_safe_resolve(root)))
  273. force_include = root_scope in {"cpld_workspace", "named_cpld_path"}
  274. for path, file_stat, reparse in _iter_files(root, config):
  275. visited += 1
  276. if visited > config.max_files:
  277. records.append(_base_record(
  278. root,
  279. size=None,
  280. sha256=None,
  281. classification="scan_limit",
  282. recommended_action="retain_and_review",
  283. reason=f"scan stopped after max_files={config.max_files}",
  284. ownership_evidence=("scan_limit",),
  285. ))
  286. break
  287. record = _record_file(path, file_stat, reparse, config, force_include=force_include)
  288. if record is not None:
  289. records.append(record)
  290. records.sort(key=lambda item: str(item["absolute_path"]).casefold())
  291. return {
  292. "schema": SCHEMA,
  293. "command": "scan",
  294. "generated_at": _now(),
  295. "roots": root_names,
  296. "records": records,
  297. }
  298. def _normalize_member(name: str) -> str | None:
  299. normalized = name.replace("\\", "/")
  300. path = PurePosixPath(normalized)
  301. if not normalized or normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized):
  302. return None
  303. if any(part in {"", ".", ".."} for part in path.parts):
  304. return None
  305. return "/".join(path.parts)
  306. def _directory_files(root: Path) -> dict[str, Path]:
  307. files: dict[str, Path] = {}
  308. for path in root.rglob("*"):
  309. if not path.is_file() or _is_reparse(path):
  310. continue
  311. relative = "/".join(path.relative_to(root).parts).casefold()
  312. files[relative] = path
  313. return files
  314. def _archive_member_hash(handle: zipfile.ZipFile, info: zipfile.ZipInfo) -> tuple[int, str]:
  315. if info.file_size > MAX_MEMBER_BYTES:
  316. raise ValueError("archive member exceeds audit size budget")
  317. digest = hashlib.sha256()
  318. size = 0
  319. with handle.open(info, "r") as stream:
  320. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  321. size += len(chunk)
  322. digest.update(chunk)
  323. return size, digest.hexdigest()
  324. def compare_archive(archive: Path, directory: Path, *, config: AuditConfig | None = None) -> dict[str, Any]:
  325. config = config or AuditConfig()
  326. archive = Path(archive)
  327. directory = Path(directory)
  328. archive_record = _base_record(
  329. archive,
  330. size=archive.stat().st_size if archive.is_file() else None,
  331. sha256=_sha256(archive) if archive.is_file() else None,
  332. classification="protected_archive" if _matches(str(archive), config.protected_patterns) else "archive_candidate",
  333. recommended_action="retain",
  334. reason="archive under independent comparison",
  335. ownership_evidence=("archive_input",),
  336. )
  337. directory_record = _base_record(
  338. directory,
  339. size=None,
  340. sha256=None,
  341. classification="comparison_directory",
  342. recommended_action="retain",
  343. reason="directory used as independent archive comparison target",
  344. ownership_evidence=("comparison_input",),
  345. )
  346. members: list[dict[str, Any]] = []
  347. unsafe = False
  348. target_files = _directory_files(directory) if directory.is_dir() else {}
  349. seen: set[str] = set()
  350. try:
  351. with zipfile.ZipFile(archive) as handle:
  352. for info in handle.infolist():
  353. normalized = _normalize_member(info.filename)
  354. if normalized is None or normalized.casefold() in seen:
  355. unsafe = True
  356. members.append({
  357. **_base_record(
  358. None,
  359. size=info.file_size,
  360. sha256=None,
  361. classification="unsafe_archive_member",
  362. recommended_action="retain",
  363. reason="absolute, traversal, empty, or duplicate archive member path",
  364. ownership_evidence=("zip_member_path_rejected",),
  365. comparison_result="unsafe_member",
  366. ),
  367. "member_path": info.filename,
  368. "target_size": None,
  369. })
  370. continue
  371. seen.add(normalized.casefold())
  372. if info.is_dir() or info.filename.endswith(("/", "\\")):
  373. members.append({
  374. **_base_record(
  375. directory / normalized,
  376. size=0,
  377. sha256=None,
  378. classification="archive_directory_member",
  379. recommended_action="review",
  380. reason="directory entry does not require file hash coverage",
  381. comparison_result="directory_entry",
  382. ownership_evidence=("zip_directory_member",),
  383. ),
  384. "member_path": info.filename,
  385. "target_size": None,
  386. })
  387. continue
  388. try:
  389. member_size, member_hash = _archive_member_hash(handle, info)
  390. except (OSError, ValueError, zipfile.BadZipFile) as exc:
  391. unsafe = True
  392. members.append({
  393. **_base_record(
  394. None,
  395. size=info.file_size,
  396. sha256=None,
  397. classification="unsafe_archive_member",
  398. recommended_action="retain",
  399. reason=f"archive member could not be independently hashed: {exc}",
  400. ownership_evidence=("zip_member_hash_failed",),
  401. comparison_result="unsafe_member",
  402. ),
  403. "member_path": info.filename,
  404. "target_size": None,
  405. })
  406. continue
  407. target = target_files.get(normalized.casefold())
  408. if target is None:
  409. result = "missing"
  410. target_size = None
  411. target_path = None
  412. else:
  413. target_size = target.stat().st_size
  414. target_path = target
  415. if target_size != member_size:
  416. result = "size_mismatch"
  417. elif _sha256(target) != member_hash:
  418. result = "sha256_mismatch"
  419. else:
  420. result = "covered_match"
  421. if result != "covered_match":
  422. unsafe = False if result in {"missing", "size_mismatch", "sha256_mismatch"} else unsafe
  423. members.append({
  424. **_base_record(
  425. target_path,
  426. size=member_size,
  427. sha256=member_hash,
  428. classification="archive_member",
  429. recommended_action="review",
  430. reason="member compared by normalized path, size, and SHA-256",
  431. comparison_target=str(target_path.resolve()) if target_path is not None else None,
  432. comparison_result=result,
  433. ownership_evidence=("zip_member_hash",),
  434. ),
  435. "member_path": info.filename,
  436. "target_size": int(target_size) if target_size is not None else None,
  437. })
  438. except (OSError, zipfile.BadZipFile) as exc:
  439. unsafe = True
  440. members.append({
  441. **_base_record(
  442. archive,
  443. size=archive_record["size"],
  444. sha256=archive_record["sha256"],
  445. classification="unreadable_archive",
  446. recommended_action="retain",
  447. reason=f"archive could not be read: {exc}",
  448. comparison_result="unsafe_member",
  449. ownership_evidence=("zip_open_failed",),
  450. ),
  451. "member_path": "",
  452. "target_size": None,
  453. })
  454. all_match = bool(members) and all(item["comparison_result"] in {"covered_match", "directory_entry"} for item in members)
  455. protected = _matches(str(archive), config.protected_patterns)
  456. if unsafe:
  457. status = "unsafe"
  458. action = "retain"
  459. elif all_match and protected:
  460. status = "full_coverage"
  461. action = "retain_protected_archive"
  462. elif all_match:
  463. status = "full_coverage"
  464. action = "delete_archive_after_verification"
  465. else:
  466. status = "mismatch"
  467. action = "retain"
  468. archive_record["comparison_target"] = str(directory.resolve())
  469. archive_record["comparison_result"] = status
  470. archive_record["recommended_action"] = action
  471. return {
  472. "schema": SCHEMA,
  473. "command": "compare-archives",
  474. "generated_at": _now(),
  475. "archive": archive_record,
  476. "directory": directory_record,
  477. "comparison": {"status": status, "recommended_action": action, "members": members},
  478. }
  479. def load_config(path: Path) -> tuple[AuditConfig, list[Path]]:
  480. payload = json.loads(Path(path).read_text(encoding="utf-8"))
  481. config = AuditConfig.from_mapping(payload)
  482. roots = [Path(str(item["path"])) for item in payload.get("scan_roots", []) if isinstance(item, Mapping) and item.get("path")]
  483. return config, roots
  484. def build_parser() -> argparse.ArgumentParser:
  485. parser = argparse.ArgumentParser(description="Read-only CPLD C-drive audit")
  486. subparsers = parser.add_subparsers(dest="command", required=True)
  487. scan = subparsers.add_parser("scan", help="scan configured roots and emit JSON inventory")
  488. scan.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
  489. scan.add_argument("--root", action="append", type=Path, help="override configured scan roots; repeatable")
  490. scan.add_argument("--output", type=Path, help="write JSON report to this path")
  491. compare = subparsers.add_parser("compare-archives", help="compare ZIP members with an extracted directory")
  492. compare.add_argument("--archive", type=Path, required=True)
  493. compare.add_argument("--directory", type=Path, required=True)
  494. compare.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
  495. compare.add_argument("--output", type=Path, help="write JSON report to this path")
  496. return parser
  497. def _emit(payload: Mapping[str, Any], output: Path | None) -> None:
  498. encoded = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
  499. if output is None:
  500. sys.stdout.write(encoded)
  501. else:
  502. output.parent.mkdir(parents=True, exist_ok=True)
  503. output.write_text(encoded, encoding="utf-8", newline="\n")
  504. def main(argv: Sequence[str] | None = None) -> int:
  505. args = build_parser().parse_args(argv)
  506. try:
  507. config, configured_roots = load_config(args.config)
  508. if args.command == "scan":
  509. roots = args.root if args.root else configured_roots
  510. _emit(scan_paths(roots, config=config), args.output)
  511. else:
  512. _emit(compare_archive(args.archive, args.directory, config=config), args.output)
  513. except (OSError, ValueError, json.JSONDecodeError) as exc:
  514. print(f"cpld-c-drive-audit: fail: {exc}", file=sys.stderr)
  515. return 2
  516. return 0
  517. if __name__ == "__main__":
  518. raise SystemExit(main())