#!/usr/bin/env python3 """Bounded TAR boundary observations. No external archives or extraction paths.""" import argparse import base64 from datetime import datetime, timezone import gzip import hashlib import io import json import os from pathlib import Path import platform import shutil import subprocess import tarfile BLOCK = 512 ZERO = bytes(BLOCK) PAYLOADS = {"alpha.bin": b"A" * 17, "beta.bin": b"B" * 513, "gamma.bin": b"C" * 31} def digest(data): return hashlib.sha256(data).hexdigest() def require(condition, message): if not condition: raise RuntimeError(message) def member(name, data): info = tarfile.TarInfo(name) info.size = len(data) info.mode = 0o600 info.mtime = 0 return info.tobuf(format=tarfile.USTAR_FORMAT) + data + bytes(-len(data) % BLOCK) def fixtures(): a, b, c = (member(name, data) for name, data in PAYLOADS.items()) joined = a + b + c + ZERO * 2 separated = a + ZERO * 2 + b + c + ZERO * 2 bad = bytearray(joined) bad[len(a)] ^= 1 # Change only beta's header name byte; retain its checksum. zero_expected = dict(PAYLOADS, **{"alpha.bin": ZERO}) raw = [ ("combined", joined, PAYLOADS, 1), ("concatenated-tar", separated, PAYLOADS, 1), ("concatenated-gzip", separated, PAYLOADS, 2), ("single-zero-gap", a + ZERO + b + c + ZERO * 2, PAYLOADS, 1), ("missing-terminator", a + b + c, PAYLOADS, 1), ("invalid-middle-header", bytes(bad), PAYLOADS, 1), ("missing-middle-member", a + c + ZERO * 2, PAYLOADS, 1), ("zero-payload-control", member("alpha.bin", ZERO) + b + c + ZERO * 2, zero_expected, 1), ] result = [] for name, data, expected, count in raw: compressed = (gzip.compress(a + ZERO * 2, mtime=0) + gzip.compress(b + c + ZERO * 2, mtime=0) if count == 2 else gzip.compress(data, mtime=0)) require(gzip.decompress(compressed) == data, "Fixture gzip mismatch") result.append({"id": name, "raw": data, "gzip": compressed, "expected": expected, "gzip_members": count}) return result def run(command, data=None): proc = subprocess.run(command, input=data, capture_output=True, timeout=15, env={"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "LC_ALL": "C"}) return {"command": command, "exit": proc.returncode, "stdout_base64": base64.b64encode(proc.stdout).decode("ascii"), "stdout_bytes": len(proc.stdout), "stdout_sha256": digest(proc.stdout), "stderr": proc.stderr.decode("utf-8", errors="replace")}, proc.stdout def python_read(raw, expected, ignore): payloads = {} entries = [] error = None try: with tarfile.open(fileobj=io.BytesIO(raw), mode="r:", ignore_zeros=ignore) as archive: for entry in archive: require(entry.name in PAYLOADS and entry.isfile(), "Unexpected fixture member") stream = archive.extractfile(entry) require(stream is not None, "Missing regular-file stream") with stream: data = stream.read() entries.append({"name": entry.name, "header_offset": entry.offset, "bytes": len(data), "sha256": digest(data)}) require(entry.name not in payloads, "Unexpected duplicate fixture") payloads[entry.name] = data except (tarfile.TarError, EOFError, OSError) as exc: error = {"type": type(exc).__name__, "message": str(exc)} return {"reader": "python-ignore" if ignore else "python-default", "scope": "entry_payloads", "api_ok": error is None, "error": error, "entries": entries, "names": list(payloads), "matches_expected": payloads == expected} def observe(): tar = shutil.which("tar") gunzip = shutil.which("gzip") require(tar is not None and gunzip is not None, "GNU tar and gzip are required") tar_version, tv = run([tar, "--version"]) gzip_version, gv = run([gunzip, "--version"]) require(tar_version["exit"] == 0 and b"GNU tar" in tv, "GNU tar is required") require(gzip_version["exit"] == 0, "gzip version lookup failed") rows = [] for fixture in fixtures(): raw, compressed, expected = fixture["raw"], fixture["gzip"], fixture["expected"] gztest, _ = run([gunzip, "-t"], compressed) gzread, decoded = run([gunzip, "-dc"], compressed) require(gztest["exit"] == 0 and gzread["exit"] == 0 and decoded == raw, "Outer gzip control failed") readers = [] for ignore in (False, True): for operation in ("list", "stdout"): args = [tar, "--list" if operation == "list" else "--extract"] if operation == "stdout": args.append("--to-stdout") if ignore: args.append("--ignore-zeros") args.extend(["--file", "-"]) item, output = run(args, decoded) names = output.decode("ascii").splitlines() if operation == "list" else None item.update(reader="gnu-" + operation + ("-ignore" if ignore else "-default"), scope="inventory" if operation == "list" else "payload_stream", api_ok=item["exit"] == 0, names=names, matches_expected=(names == list(expected) if operation == "list" else output == b"".join(expected.values()))) readers.append(item) readers.append(python_read(decoded, expected, ignore)) rows.append({"id": fixture["id"], "gzip_members": fixture["gzip_members"], "tar_bytes": len(raw), "tar_sha256": digest(raw), "gzip_bytes": len(compressed), "gzip_sha256": digest(compressed), "gzip_test": gztest, "gzip_decode": gzread, "decoded_equals_constructed_tar": decoded == raw, "expected": [{"name": name, "bytes": len(data), "sha256": digest(data)} for name, data in expected.items()], "readers": readers}) return {"schema_version": 1, "generated_at": datetime.now(timezone.utc).isoformat(), "kind": "controlled software observation with synthetic payloads", "environment": {"python": platform.python_version(), "kernel": platform.release(), "machine": platform.machine(), "tar": tv.decode().splitlines()[0], "gzip": gv.decode().splitlines()[0], "tar_sha256": digest(Path(tar).read_bytes()), "gzip_sha256": digest(Path(gunzip).read_bytes()), "tarfile_sha256": digest(Path(tarfile.__file__).read_bytes())}, "harness_sha256": digest(Path(__file__).read_bytes()), "limits": ["No hostile archives, metadata restore, network or crash test.", "GNU stdout extraction does not preserve member boundaries; listing is separate.", "Eight fixtures and 48 reader operations are not failure-rate samples.", "Input corruption is applied before gzip compression; gzip correctly covers those bytes.", "Default reads on decoded TAR isolate the container from compression read-ahead."], "cases": rows} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() # Refuse to overwrite an earlier receipt before starting the experiment. with args.output.open("x", encoding="utf-8") as output: json.dump(observe(), output, indent=2) output.write("\n") if __name__ == "__main__": main()