File size: 2,304 Bytes
5909a7f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | #!/usr/bin/env python3
"""Unseal one or more FrontierChallenge English task statements."""
from __future__ import annotations
import argparse
import gzip
import hashlib
import hmac
import io
import struct
import tarfile
from pathlib import Path
MAGIC = b"FCREF1\n"
PASSWORD = "apodex.ai"
def decrypt(blob: bytes, password: str) -> bytes:
if not blob.startswith(MAGIC):
raise ValueError("not a FrontierChallenge sealed archive")
offset = len(MAGIC)
salt = blob[offset:offset + 16]
tag = blob[offset + 16:offset + 48]
ciphertext = blob[offset + 48:]
material = hashlib.pbkdf2_hmac(
"sha256", password.encode("utf-8"), salt, 200_000, dklen=64
)
enc_key, mac_key = material[:32], material[32:]
expected = hmac.new(mac_key, ciphertext, hashlib.sha256).digest()
if not hmac.compare_digest(tag, expected):
raise ValueError("wrong password or corrupt archive")
blocks = (len(ciphertext) + 31) // 32
stream = b"".join(
hmac.digest(enc_key, struct.pack(">Q", counter), "sha256")
for counter in range(blocks)
)[:len(ciphertext)]
return bytes(left ^ right for left, right in zip(ciphertext, stream))
def unseal(task: Path, password: str, force: bool) -> None:
target = task / "instruction.md"
if target.exists() and not force:
raise FileExistsError(f"{target} already exists; use --force to replace it")
plaintext = decrypt((task / "statement.fcref").read_bytes(), password)
with gzip.GzipFile(fileobj=io.BytesIO(plaintext), mode="rb") as gz:
with tarfile.open(fileobj=gz, mode="r:") as tar:
member = tar.getmember("instruction.md")
handle = tar.extractfile(member)
if handle is None:
raise ValueError(f"instruction.md missing from {task / 'statement.fcref'}")
target.write_bytes(handle.read())
print(target)
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("tasks", nargs="+", type=Path)
parser.add_argument("--password", default=PASSWORD)
parser.add_argument("--force", action="store_true")
args = parser.parse_args()
for task in args.tasks:
unseal(task, args.password, args.force)
return 0
if __name__ == "__main__":
raise SystemExit(main())
|