"""Observe checker coverage on disposable regular files only; never mount images.""" import argparse import hashlib import json import os from pathlib import Path import platform import re import shutil import subprocess import tempfile from datetime import datetime, timezone def require(condition, message): if not condition: raise ValueError(message) def digest(path): with Path(path).open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest() def observe(): tools = {name: shutil.which(name) or "/usr/sbin/" + name for name in ("mke2fs", "debugfs", "e2fsck", "dumpe2fs")} for path in tools.values(): require(Path(path).is_file(), "Missing executable: " + path) commands = [] with tempfile.TemporaryDirectory(prefix=".e2fsck-coverage-", dir=Path.cwd()) as temporary: root = Path(temporary) env = dict(os.environ, LC_ALL="C", TZ="UTC") config = root / "e2fsck.conf" config.write_text("[options]\nallow_cancellation = false\n") mkconfig = root / "mke2fs.conf" mkconfig.write_text("[defaults]\nbase_features = sparse_super,large_file,filetype,ext_attr,resize_inode,dir_index,extent,64bit,flex_bg,metadata_csum\nblocksize = 4096\ninode_size = 256\ninode_ratio = 16384\n") mkconfig.write_text(mkconfig.read_text() + "[fs_types]\next4 = {\nfeatures = extent\n}\n") env.update(E2FSCK_CONFIG=str(config), MKE2FS_CONFIG=str(mkconfig)) def run(name, *args, allowed=(0,)): argv = [tools[name], *map(str, args)] result = subprocess.run(argv, capture_output=True, text=True, env=env, timeout=30) row = {"argv": [arg.replace(str(root), "$TMP") for arg in argv], "status": result.returncode, "stdout": result.stdout.replace(str(root), "$TMP"), "stderr": result.stderr.replace(str(root), "$TMP")} commands.append(row) require(result.returncode in allowed, repr(row)) return row versions = {name: run(name, "-V") for name in tools} source = root / "payload.bin" source.write_bytes(bytes(range(256)) * 32) clean = root / "clean.img" with clean.open("xb") as stream: stream.truncate(64 * 1024 * 1024) run("mke2fs", "-q", "-t", "ext4", "-b", "4096", "-I", "256", "-O", "^has_journal", "-E", "lazy_itable_init=0", clean) run("debugfs", "-w", "-R", "write " + str(source) + " /payload", clean) run("e2fsck", "-f", "-y", clean, allowed=(0, 1)) filesystem = run("dumpe2fs", "-h", clean)["stdout"] require("metadata_csum" in filesystem, "Checksum feature missing") features = next(line for line in filesystem.splitlines() if line.startswith("Filesystem features:")) require("has_journal" not in features, "Fixture must have no journal") mapping = run("debugfs", "-R", "blocks /payload", clean)["stdout"].split() require(len(mapping) == 2 and all(token.isdigit() for token in mapping), "Expected two payload blocks") block = int(mapping[0]) payload_image = root / "payload-change.img" shutil.copyfile(clean, payload_image) with payload_image.open("r+b") as stream: stream.seek(block * 4096 + 123) before = stream.read(1) require(before == source.read_bytes()[123:124], "Wrong payload offset") stream.seek(block * 4096 + 123) stream.write(bytes([before[0] ^ 1])) counter_image = root / "counter-change.img" shutil.copyfile(clean, counter_image) with counter_image.open("rb") as stream: stream.seek(1024 + 12) original_count = int.from_bytes(stream.read(4), "little") require(original_count > 1, "Invalid initial free block count") run("debugfs", "-w", "-R", "set_super_value free_blocks_count " + str(original_count - 1), counter_image) link_image = root / "link-change.img" shutil.copyfile(clean, link_image) run("debugfs", "-w", "-R", "set_inode_field /payload links_count 2", link_image) rows = [] def check(case, image, options): require(image.parent == root and image.is_file() and not image.is_symlink(), "Unsafe image path") before_hash = digest(image) command = run("e2fsck", *options, image, allowed=tuple(range(256))) after_hash = digest(image) dump = root / (case + ".bin") run("debugfs", "-R", "dump /payload " + str(dump), image) require(dump.is_file() and dump.stat().st_size == source.stat().st_size, "Incomplete payload dump") text = command["stdout"] + command["stderr"] rows.append({"case": case, "options": options, "status": command["status"], "passes": [int(n) for n in re.findall(r"^Pass ([1-5]):", text, re.M)], "imageBeforeSha256": before_hash, "imageAfterSha256": after_hash, "imageUnchanged": before_hash == after_hash, "payloadSha256": digest(dump), "payloadMatches": digest(dump) == digest(source), "transcript": command}) check("clean-normal", clean, ["-n"]) check("clean-forced", clean, ["-f", "-n"]) check("payload-normal", payload_image, ["-n"]) check("payload-forced", payload_image, ["-f", "-n"]) check("counter-normal", counter_image, ["-n"]) check("counter-forced", counter_image, ["-f", "-n"]) check("counter-repair", counter_image, ["-f", "-y"]) check("counter-recheck", counter_image, ["-f", "-n"]) check("link-forced", link_image, ["-f", "-n"]) check("link-repair", link_image, ["-f", "-y"]) check("link-recheck", link_image, ["-f", "-n"]) return {"schemaVersion": 1, "kind": "native-controlled-observation", "generatedAt": datetime.now(timezone.utc).isoformat(), "platform": platform.platform(), "python": platform.python_version(), "scriptSha256": digest(__file__), "tools": {name: {"path": path, "sha256": digest(path), "version": versions[name]} for name, path in tools.items()}, "fixture": {"bytes": 64 * 1024 * 1024, "blockBytes": 4096, "payloadBytes": 8192, "payloadReferenceSha256": digest(source), "mutation": {"payloadByte": 123, "xor": 1, "physicalBlock": block, "freeBlocksBefore": original_count, "freeBlocksAfter": original_count - 1}, "mke2fsConfig": mkconfig.read_text(), "e2fsckConfig": config.read_text(), "filesystem": filesystem}, "cases": rows, "commands": commands} if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("output", help="New observation JSON; existing files are never overwritten.") args = parser.parse_args() output = Path(args.output) require(not output.exists(), "Refusing to overwrite an observation") result = observe() with output.open("x") as stream: json.dump(result, stream, indent=2) stream.write("\n") print(json.dumps({"output": str(output), "cases": len(result["cases"])}))