"""Disposable ext4 UUID observations. No device or image path is accepted.""" import argparse import hashlib import json import os from pathlib import Path import shutil import struct import subprocess import tempfile import uuid from datetime import datetime, timezone OLD = "11111111-2222-4333-8444-555555555555" NEW = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee" PAYLOAD = b"Hesela ext4 UUID fixture: identity is not a content digest.\n" * 7 FEATURES = "none,extent,64bit,flex_bg,filetype,sparse_super,large_file,huge_file,dir_nlink,extra_isize,metadata_csum" BLOCK = 4096 SIZE = 16 * 1024 * 1024 def digest(data): return hashlib.sha256(data).hexdigest() def tool(name): candidate = shutil.which(name) or "/usr/sbin/" + name if not Path(candidate).is_file(): raise RuntimeError("Required e2fsprogs binary unavailable: " + name) return candidate def run(name, args, folder): proc = subprocess.run([tool(name), *map(str, args)], capture_output=True, env={**os.environ, "LC_ALL": "C"}, timeout=60) return {"tool": name, "args": [str(a).replace(str(folder), "") for a in args], "exit_code": proc.returncode, "stdout": proc.stdout.decode("utf-8", errors="strict").replace(str(folder), ""), "stderr": proc.stderr.decode("utf-8", errors="strict").replace(str(folder), "")} def require(ok, message): if not ok: raise ValueError(message) def fields(data): sb = data[1024:2048] require(len(data) == SIZE and struct.unpack_from("/files", "/fixture.img"], "Formatting protocol differs") require(row["change"]["tool"] == "tune2fs" and row["change"]["args"] == [ "-U", NEW, "/fixture.img"], "UUID-change protocol differs") for view in (a, b): features = view["features"] require("metadata_csum" in features and "has_journal" not in features, "Fixture feature scope changed") require(("metadata_csum_seed" in features) == seed and ("stable_inodes" in features) == stable, "Feature flags differ") require(view["payload_sha256"] == report["payload_sha256"] and view["read_only_unchanged"], "Payload or inspection integrity failed") require([c["tool"] for c in view["commands"]] == ["dumpe2fs", "e2fsck", "debugfs"], "Missing inspection command") require(all(c["exit_code"] == 0 for c in view["commands"]), "Inspection failed") require(view["commands"][2]["stdout"].encode() == PAYLOAD, "Captured payload differs") require([c["args"] for c in view["commands"]] == [ ["-h", "/fixture.img"], ["-f", "-n", "/fixture.img"], ["-R", "cat /payload.txt", "/fixture.img"]], "Inspection protocol differs") header = dict(line.split(":", 1) for line in view["commands"][0]["stdout"].splitlines() if ":" in line) require(int(header["Block size"].strip()) == BLOCK, "Header block size differs") require(header["Filesystem UUID"].strip() == view["fields"]["uuid"], "UUID differs from captured header") require(header["Filesystem features"].split() == features, "Features differ from header") if seed: require(int(header["Checksum seed"].strip(), 16) == view["fields"]["seed"], "Seed differs from captured header") diff = row["difference"] edits = diff["byte_edits"] require(all(type(e["offset"]) is int and 0 <= e["offset"] < SIZE and type(e["before"]) is int and type(e["after"]) is int and 0 <= e["before"] <= 255 and 0 <= e["after"] <= 255 and e["before"] != e["after"] for e in edits), "Invalid byte edit") offsets = [e["offset"] for e in edits] require(offsets == sorted(set(offsets)), "Duplicate or unsorted byte edit") require(diff["changed_bytes"] == len(edits) and diff["changed_blocks"] == sorted({i // BLOCK for i in offsets}) and diff["outside_primary_superblock_changed"] == any(i < 1024 or i >= 2048 for i in offsets), "Inconsistent difference ledger") require(a["fields"]["uuid"] == OLD, "Wrong initial UUID") require(row["format"]["exit_code"] == 0, "Format failed") if stable: require(row["change"]["exit_code"] != 0 and "stable_inodes" in row["change"]["stderr"], "Expected stable_inodes refusal") require(b["fields"]["uuid"] == OLD and a["image_sha256"] == b["image_sha256"], "Rejected change altered image") require(row["difference"]["changed_bytes"] == 0 and row["difference"]["changed_blocks"] == [] and not row["difference"]["outside_primary_superblock_changed"], "Refusal changed bytes") else: require(row["change"]["exit_code"] == 0 and b["fields"]["uuid"] == NEW, "UUID change did not succeed") require(a["image_sha256"] != b["image_sha256"] and row["difference"]["changed_bytes"] > 0, "Successful change has no image difference") require(row["difference"]["outside_primary_superblock_changed"] == (not seed), "Observed rewrite boundary changed") if seed: require(a["fields"]["seed"] == b["fields"]["seed"], "Stored seed changed") return report def observe(): return validate({"schema_version": 1, "observed_at": datetime.now(timezone.utc).isoformat(), "method": "Unmounted disposable regular files; no journal, device, mount or crash experiment.", "image_bytes": SIZE, "block_bytes": BLOCK, "payload_sha256": digest(PAYLOAD), "mke2fs_version": run("mke2fs", ["-V"], Path("/nonexistent-fixture")), "cases": [observe_case(seed, stable) for stable in (False, True) for seed in (False, True)]}) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--output", type=Path) group.add_argument("--check", type=Path) args = parser.parse_args() if args.check: validate(json.loads(args.check.read_text())) print("Four captured native cases validated") else: result = observe() with args.output.open("x") as output: json.dump(result, output, indent=2) output.write("\n") print("Four native cases captured")