"""NTFS-3G fixup lifecycle controls on bounded synthetic buffers. SPDX-License-Identifier: CC0-1.0 """ import argparse import ctypes import errno import json from pathlib import Path import platform import struct import subprocess import study OPERATIONS = { "read": "ntfs_mst_post_read_fixup", "protect": "ntfs_mst_pre_write_fixup", "restore": "ntfs_mst_post_write_fixup", } PLANS = { "read-once": ("read",), "read-twice": ("read", "read"), "writer-paired": ("protect", "restore", "protect", "read"), "writer-double-protect": ("protect", "protect", "read"), "bad-marker-checked": ("read",), "bad-marker-unchecked": ("restore",), "valid-unchecked": ("restore",), "writer-restore-twice": ("protect", "restore", "restore"), } def plain(size): data = bytearray(study.record(size)) for index, end in enumerate(range(512, size + 1, 512), 1): data[end - 2:end] = (0x8100 + 0x23 * index).to_bytes(2, "little") return bytes(data) def protected(size): data = bytearray(plain(size)) for index, end in enumerate(range(512, size + 1, 512), 1): data[48 + 2 * index:50 + 2 * index] = data[end - 2:end] data[end - 2:end] = (42).to_bytes(2, "little") return bytes(data) def fixtures(): for size in (512, 1024, 4096): for kind, plan in PLANS.items(): data = bytearray(plain(size) if kind.startswith("writer-") else protected(size)) if kind.startswith("bad-marker"): data[-2] ^= 1 yield {"id": f"{size}-{kind}", "kind": kind, "size": size, "input": bytes(data), "plan": plan, "reference": plain(size)} def valid_layout(data): if not isinstance(data, bytes) or len(data) not in (512, 1024, 4096): raise ValueError("complete bounded buffer required") offset, count = struct.unpack_from(" 510: raise ValueError("unchecked restore requires a validated array layout") def expected_step(data, operation): valid_layout(data) offset = int.from_bytes(data[4:6], "little") marker = data[offset:offset + 2] ends = list(range(512, len(data) + 1, 512)) result = bytearray(data) if operation == "read": if any(data[end - 2:end] != marker for end in ends): return -1, errno.EIO, b"BAAD" + data[4:] elif operation == "protect": number = (int.from_bytes(marker, "little") % 65534) + 1 marker = number.to_bytes(2, "little") result[offset:offset + 2] = marker for index, end in enumerate(ends, 1): result[offset + 2 * index:offset + 2 * index + 2] = data[end - 2:end] result[end - 2:end] = marker return 0, 0, bytes(result) elif operation != "restore": raise ValueError("unsupported operation") for index, end in enumerate(ends, 1): result[end - 2:end] = data[offset + 2 * index:offset + 2 * index + 2] return (None if operation == "restore" else 0), 0, bytes(result) class NativeLifecycle(study.Native): def __init__(self): super().__init__() function = self.lib.ntfs_mst_post_write_fixup function.argtypes = [ctypes.c_void_p] function.restype = None def step(self, data, operation): valid_layout(data) if operation not in OPERATIONS: raise ValueError("unsupported operation") if operation != "restore": return self.call(data, OPERATIONS[operation]) buffer = ctypes.create_string_buffer(data, len(data)) ctypes.set_errno(0) self.lib.ntfs_mst_post_write_fixup(buffer) return None, ctypes.get_errno(), bytes(buffer.raw) def capture(): native = NativeLifecycle() rows = [] for fixture in fixtures(): current = fixture["input"] steps = [] for operation in fixture["plan"]: expected = expected_step(current, operation) result, error, output = native.step(current, operation) if (result, error, output) != expected: raise ValueError(f"oracle mismatch: {fixture['id']} / {operation}") steps.append({"operation": operation, "returnCode": result, "errno": error, "inputSha256": study.digest(current), "outputSha256": study.digest(output)}) current = output if result not in (0, None): break rows.append({ "id": fixture["id"], "kind": fixture["kind"], "size": fixture["size"], "inputHex": fixture["input"].hex(), "outputHex": current.hex(), "steps": steps, "payloadMatchesReference": current[100:] == fixture["reference"][100:], "trailerWords": [study.word(current, end - 2) for end in range(512, len(current) + 1, 512)], }) package = subprocess.run( ["dpkg-query", "-W", "-f=${Package} ${Version}", "libntfs-3g89t64"], check=True, capture_output=True, text=True).stdout return { "schemaVersion": 1, "evidenceType": "native-library synthetic lifecycle controls", "environment": {"python": platform.python_version(), "platform": platform.platform(), "library": str(native.path), "librarySha256": study.digest(native.path.read_bytes()), "package": package}, "rows": rows, } def verify(report): if not isinstance(report, dict): raise ValueError("object report required") fresh = capture() # Serialized comparison also rejects boolean/integer and float/integer substitution. if json.dumps(report, sort_keys=True, allow_nan=False) != json.dumps(fresh, sort_keys=True): raise ValueError("lifecycle report differs from native replay") return True def summary(report): verify(report) outcomes = [] for kind in PLANS: rows = [row for row in report["rows"] if row["kind"] == kind] outcomes.append({ "kind": kind, "cases": len(rows), "finalCheckedSuccesses": sum(row["steps"][-1]["returnCode"] == 0 for row in rows), "finalUncheckedCalls": sum(row["steps"][-1]["returnCode"] is None for row in rows), "finalErrors": sum(row["steps"][-1]["returnCode"] == -1 for row in rows), "payloadMatchesReference": sum(row["payloadMatchesReference"] for row in rows), }) return {"schemaVersion": 1, "nativeLifecycleCases": len(report["rows"]), "nativeCalls": sum(len(row["steps"]) for row in report["rows"]), "outcomes": outcomes, "comparisonScope": "bytes 100 through end; excludes header and update-sequence array", "librarySha256": report["environment"]["librarySha256"], "limitations": ["One NTFS-3G library on one host, not Windows or a mounted filesystem.", "Deliberate API misuse controls are not evidence of production caller defects.", "A void restore call has no success status; errno zero is not verification.", "Counts describe fixture coverage, not failure probabilities."]} if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("command", choices=("capture", "verify", "summary")) parser.add_argument("path", type=Path) args = parser.parse_args() if args.command == "capture": args.path.write_text(json.dumps(capture(), indent=2) + "\n") else: report = study.load_report(args.path.read_text()) if args.command == "verify": verify(report) print("Lifecycle replay: exact") else: print(json.dumps(summary(report), indent=2))