#!/usr/bin/env python3 """Offline ext4 image controls. Only private regular files, never mounts/devices.""" import argparse import hashlib import json import os from pathlib import Path import re import shutil import subprocess import tempfile from datetime import datetime, timezone SIZES = (1, 4096, 4097, 65536, 65537) CLUSTERS = (4096, 16384, 65536) TOOLS = {name: shutil.which(name) or "/usr/sbin/" + name for name in ("mke2fs", "debugfs", "dumpe2fs", "e2fsck")} ENV = {**os.environ, "LC_ALL": "C"} def run(argv): p = subprocess.run(argv, text=True, capture_output=True, env=ENV, timeout=45) return {"argv": argv, "returncode": p.returncode, "stdout": p.stdout, "stderr": p.stderr} def require(ok, message): if not ok: raise ValueError(message) def stat_fields(text): size = re.search(r"\bSize:\s*(\d+)", text) blocks = re.search(r"\bBlockcount:\s*(\d+)", text) require(size is not None and blocks is not None, "Incomplete debugfs inode stat") return int(size.group(1)), int(blocks.group(1)) def validate(report): rows = report["rows"] require(all(type(r[k]) is int for r in rows for k in ("cluster_bytes", "logical_bytes", "allocated_bytes", "blockcount_512")), "Observation units must be integers") expected = {(c, s) for c in CLUSTERS for s in SIZES} require(len(rows) == len(expected), "Wrong observation count") require({(r["cluster_bytes"], r["logical_bytes"]) for r in rows} == expected, "Missing, duplicate or unexpected observation") for r in rows: expected_bytes = ((r["logical_bytes"] + r["cluster_bytes"] - 1) // r["cluster_bytes"]) * r["cluster_bytes"] require(r["allocated_bytes"] == expected_bytes, "Allocation mismatch") require(r["blockcount_512"] * 512 == r["allocated_bytes"], "Unit mismatch") require(r["content_matches"] is True, "Readback content mismatch") require(len(report["checks"]) == len(CLUSTERS), "Missing image check") require({r["cluster_bytes"] for r in report["checks"]} == set(CLUSTERS), "Wrong image check identities") require(all(r["returncode"] == 0 for r in report["checks"]), "e2fsck failure") require({r["case"] for r in report["rejections"]} == {"cluster_without_bigalloc", "bigalloc_without_extents"}, "Missing rejected configuration") require(len(report["rejections"]) == 2, "Duplicate rejection") require(all(r["returncode"] != 0 for r in report["rejections"]), "Invalid configuration accepted") def capture(): rows, commands, checks, rejections = [], [], [], [] versions = {name: run([exe, "-V"]) for name, exe in TOOLS.items()} with tempfile.TemporaryDirectory(prefix="hesela-bigalloc-") as name: root = Path(name) source = root / "input" source.mkdir() for size in SIZES: (source / ("f" + str(size))).write_bytes(b"X" * size) for cluster in CLUSTERS: target = root / ("fs-" + str(cluster) + ".img") with target.open("xb") as image: image.truncate(64 * 1024 * 1024) features = "none,extent,filetype,64bit,metadata_csum,huge_file" args = [TOOLS["mke2fs"], "-t", "ext4", "-q", "-b", "4096", "-I", "256", "-N", "128", "-m", "0", "-E", "lazy_itable_init=0,nodiscard"] if cluster != 4096: features += ",bigalloc" args += ["-C", str(cluster)] args += ["-O", features, "-d", str(source), str(target)] created = run(args) commands.append(created) require(created["returncode"] == 0, "mke2fs failed: " + created["stderr"]) header = run([TOOLS["dumpe2fs"], "-h", str(target)]) commands.append(header) require(header["returncode"] == 0, "dumpe2fs failed") block = re.search(r"Block size:\s+(\d+)", header["stdout"]) cluster_match = re.search(r"Cluster size:\s+(\d+)", header["stdout"]) require(block is not None and int(block.group(1)) == 4096, "Wrong block size") actual_cluster = int(cluster_match.group(1)) if cluster_match else 4096 require(actual_cluster == cluster, "Wrong cluster size") feature_line = re.search(r"Filesystem features:\s+([^\n]+)", header["stdout"]) require(feature_line is not None, "Missing feature list") actual_features = feature_line.group(1).split() require(("bigalloc" in actual_features) == (cluster != 4096), "Wrong bigalloc state") require("inline_data" not in actual_features and "has_journal" not in actual_features, "Unexpected inline or journal feature") for size in SIZES: name = "/f" + str(size) observed = run([TOOLS["debugfs"], "-R", "stat " + name, str(target)]) commands.append(observed) require(observed["returncode"] == 0, "debugfs failed") logical, sectors = stat_fields(observed["stdout"]) require(logical == size, "Wrong inode size") dumped = root / ("dump-" + str(cluster) + "-" + str(size)) readback = run([TOOLS["debugfs"], "-R", "dump " + name + " " + str(dumped), str(target)]) commands.append(readback) require(readback["returncode"] == 0 and dumped.is_file(), "Missing dump") matches = dumped.read_bytes() == b"X" * size rows.append({"cluster_bytes": cluster, "logical_bytes": logical, "blockcount_512": sectors, "allocated_bytes": sectors * 512, "content_matches": matches}) checked = run([TOOLS["e2fsck"], "-f", "-n", str(target)]) commands.append(checked) checks.append({"cluster_bytes": cluster, "returncode": checked["returncode"]}) for case, options in ( ("cluster_without_bigalloc", ["-O", "none,extent", "-C", "65536"]), ("bigalloc_without_extents", ["-O", "none,bigalloc,^extent", "-C", "65536"]), ): target = root / (case + ".img") with target.open("xb") as image: image.truncate(64 * 1024 * 1024) result = run([TOOLS["mke2fs"], "-q", "-t", "ext4", "-b", "4096", *options, str(target)]) commands.append(result) rejections.append({"case": case, "returncode": result["returncode"], "diagnostic": result["stderr"]}) report = {"schema_version": 1, "kind": "offline-userspace-image-control", "generated_at": datetime.now(timezone.utc).isoformat(), "script_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "versions": versions, "rows": rows, "checks": checks, "rejections": rejections, "commands": commands} validate(report) return report if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--verify", type=Path) args = parser.parse_args() if args.verify: data = json.loads(args.verify.read_text()) validate(data) require(data["script_sha256"] == hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "Capture script hash differs") print("Verified 15 allocation observations, 3 image checks and 2 rejected configurations") else: print(json.dumps(capture(), indent=2))