#!/usr/bin/env python3 """Native duplicate-credential checks on private regular files, never devices. No mapping or payload decryption. Public credentials and PBKDF2/1000 are NOT production security settings. Requires the companion probe.py. """ import argparse import datetime import hashlib import json from pathlib import Path import platform import shutil import subprocess import tempfile from probe import CREDENTIALS, Experiment, digest, require STATES = { "initial": {"0": "old", "1": None}, "duplicate": {"0": "old", "1": "old"}, "changed-slot-0": {"0": "new", "1": "old"}, "removed-slot-1": {"0": "new", "1": None}, } SCOPES = ("any", "0", "1") def validate(result): require(result["schemaVersion"] == 1, "schema") repetitions = result["repetitions"] require(type(repetitions) is int and 1 <= repetitions <= 10, "repetitions") rows = result["observations"] require(len(rows) == 2 * repetitions * len(STATES) * 3 * 3, "row count") seen = set() for row in rows: fmt, rep, state, scope, credential = ( row[k] for k in ("format", "repetition", "state", "scope", "credential") ) identity = (fmt, rep, state, scope, credential) require(identity not in seen, "duplicate") seen.add(identity) require(fmt in ("luks1", "luks2"), "format") require(type(rep) is int and 1 <= rep <= repetitions, "repetition") require(state in STATES and scope in SCOPES and credential in CREDENTIALS, "identity") slots = STATES[state] accepted = credential in slots.values() if scope == "any" else credential == slots[scope] require(row["accepted"] is accepted, "acceptance") require(type(row["returncode"]) is int, "returncode") require(row["returncode"] == 0 if accepted else row["returncode"] in (1, 2), "native result") key = row["recoveredKeySha256"] if accepted: require(isinstance(key, str) and len(key) == 64 and all(c in "0123456789abcdef" for c in key), "key hash") else: require(key is None, "rejected key") for fmt in ("luks1", "luks2"): for rep in range(1, repetitions + 1): subset = [r for r in rows if r["format"] == fmt and r["repetition"] == rep] hashes = {r["recoveredKeySha256"] for r in subset if r["accepted"]} require(len(hashes) == 1, "volume key changed") return True def run(executable, repetitions): require(type(repetitions) is int and 1 <= repetitions <= 10, "repetitions") executable = str(Path(executable).resolve()) version = subprocess.check_output([executable, "--version"], text=True).strip() rows = [] with tempfile.TemporaryDirectory(prefix="hesela-luks-slots-") as temporary: root = Path(temporary) for name in CREDENTIALS: (root / f"{name}.key").write_bytes(f"PUBLIC TEST FIXTURE {name}".encode()) experiment = Experiment(executable, root) for fmt in ("luks1", "luks2"): for rep in range(1, repetitions + 1): image = root / f"{fmt}-{rep}.img" experiment.format(image, fmt) for state in STATES: if state == "duplicate": experiment.run("luksAddKey", "--batch-mode", "--key-slot", "1", "--pbkdf", "pbkdf2", "--pbkdf-force-iterations", "1000", "--key-file", root / "old.key", image, root / "old.key") elif state == "changed-slot-0": experiment.run("luksChangeKey", "--batch-mode", "--key-slot", "0", "--pbkdf", "pbkdf2", "--pbkdf-force-iterations", "1000", "--key-file", root / "old.key", image, root / "new.key") elif state == "removed-slot-1": experiment.run("luksKillSlot", "--batch-mode", image, "1") for scope in SCOPES: for credential in CREDENTIALS: options = [] if scope == "any" else ["--key-slot", scope] response = experiment.run( "open", "--type", fmt, "--test-passphrase", *options, "--key-file", root / f"{credential}.key", image, expected=None ) accepted = response.returncode == 0 rows.append({ "format": fmt, "repetition": rep, "state": state, "scope": scope, "credential": credential, "returncode": response.returncode, "accepted": accepted, "recoveredKeySha256": experiment.key_hash(image, credential) if accepted else None, }) return { "schemaVersion": 1, "generatedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), "measurement": "Native credential checks with explicit slot controls on disposable files", "environment": {"cryptsetup": version, "binarySha256": digest(executable), "python": platform.python_version(), "kernel": platform.release()}, "repetitions": repetitions, "parameters": {"formats": ["luks1", "luks2"], "states": list(STATES), "scopes": list(SCOPES), "credentials": list(CREDENTIALS), "cipher": "aes-xts-plain64", "keyBits": 256, "sectorBytes": 512, "pbkdf": "pbkdf2", "pbkdfIterations": 1000, "security": "Public synthetic credentials; NOT production settings"}, "limitations": [ "No device mapping, payload decryption, reencryption or media sanitization.", "Key recovery uses the accepted credential without a slot restriction.", "Explicit-slot acceptance is observed separately by native test-passphrase.", "Selected transitions are not a random sample or a failure-rate estimate.", ], "observations": rows, "commands": experiment.commands, } def summarize(result, raw): validate(result) rows = [] for state in STATES: selected = [r for r in result["observations"] if r["state"] == state] row = {"state": state} for credential in CREDENTIALS: row[credential] = sorted({r["scope"] for r in selected if r["credential"] == credential and r["accepted"] and r["scope"] != "any"}) rows.append(row) return {"schemaVersion": 1, "sourceSha256": hashlib.sha256(raw).hexdigest(), "passphraseObservations": len(result["observations"]), "repetitionsPerFormat": result["repetitions"], "rows": rows, "limitations": result["limitations"]} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--cryptsetup", default=shutil.which("cryptsetup") or "/usr/sbin/cryptsetup") parser.add_argument("--repetitions", type=int, default=2) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--summary", type=Path, required=True) args = parser.parse_args() result = run(args.cryptsetup, args.repetitions) raw = (json.dumps(result, indent=2) + "\n").encode() with args.output.open("xb") as stream: stream.write(raw) summary = summarize(result, raw) with args.summary.open("x") as stream: json.dump(summary, stream, indent=2) stream.write("\n") print(f"Validated {len(result['observations'])} explicit-slot and global checks.") if __name__ == "__main__": main()