#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Read-only native probes of six constructed files. Never accepts image/device input.""" import datetime import hashlib import json import os from pathlib import Path import platform import subprocess import tempfile import observe COMMANDS = ( ("sfdisk-json", "/usr/sbin/sfdisk", "--json"), ("sfdisk-verify", "/usr/sbin/sfdisk", "--verify"), ("sgdisk-print", "/usr/sbin/sgdisk", "--print"), ("sgdisk-verify", "/usr/sbin/sgdisk", "--verify"), ) def sha(data): return hashlib.sha256(data).hexdigest() def fixtures(): images = {"baseline": observe.fixture()} for name, offset in ( ("header-byte", observe.PRIMARY * observe.BLOCK + 56), ("entry-byte", observe.PRIMARY_ARRAY * observe.BLOCK + 56), ("payload-byte", observe.PAYLOAD_LBA * observe.BLOCK), ): image = observe.fixture() image[offset] ^= 1 images[name] = image image = observe.fixture() image[observe.BACKUP_ARRAY * observe.BLOCK + 56] ^= 1 entries = image[observe.BACKUP_ARRAY * observe.BLOCK: observe.BACKUP_ARRAY * observe.BLOCK + observe.ARRAY_BYTES] image[observe.BACKUP * observe.BLOCK:(observe.BACKUP + 1) * observe.BLOCK] = observe.header( observe.BACKUP, observe.PRIMARY, observe.BACKUP_ARRAY, entries) images["inconsistent-backup"] = image image = observe.fixture() image[observe.PRIMARY * observe.BLOCK + observe.HEADER_SIZE] = 1 images["reserved-header-byte"] = image expected = {row["id"]: row["imageSha256"] for row in observe.observe()["cases"]} if {name: sha(image) for name, image in images.items()} != expected: raise ValueError("Native fixture hashes differ from original byte study") return images def call(args): result = subprocess.run(args, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=15, env={**os.environ, "LC_ALL": "C"}) return {"argv": list(args), "exitCode": result.returncode, "stdout": result.stdout, "stderr": result.stderr} def run(): programs = {} for _, binary, _ in COMMANDS: if binary in programs: continue path = Path(binary) programs[binary] = {"resolvedPath": str(path.resolve()), "sha256": sha(path.read_bytes()), "version": call([binary, "--version"])} rows = [] # Private files only: no mounts, loop devices, root privileges or writes by tools. with tempfile.TemporaryDirectory(prefix="hesela-gpt-") as directory: for name, image in fixtures().items(): path = Path(directory) / (name + ".img") path.write_bytes(image) path.chmod(0o400) for command_id, binary, flag in COMMANDS: before = sha(path.read_bytes()) result = call([binary, flag, str(path)]) after = sha(path.read_bytes()) if before != after: raise RuntimeError("Read-only command changed fixture: " + command_id) for field in ("stdout", "stderr"): result[field] = result[field].replace(str(path), "") result["argv"][-1] = "" rows.append({"fixture": name, "command": command_id, "beforeSha256": before, "afterSha256": after, **result}) return { "schemaVersion": 1, "evidenceType": "native-tools-on-constructed-regular-files", "generatedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), "platform": {"system": platform.system(), "release": platform.release(), "machine": platform.machine(), "python": platform.python_version()}, "packages": call(["dpkg-query", "-W", "-f=${Package} ${Version}\n", "fdisk", "gdisk", "libfdisk1"]), "logicalBlockBytes": observe.BLOCK, "imageBytes": observe.BLOCK * observe.BLOCKS, "programs": programs, "observations": rows, "limits": "Six deliberate byte cases, four commands each, one installed environment. " "Not a prevalence estimate, full GPT conformance test, filesystem test, " "firmware/boot test, kernel partition scan or repair experiment.", } if __name__ == "__main__": print(json.dumps(run(), indent=2))