mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-25 19:08:51 -06:00
refactor: move leaf modules into packages
core: hashing, artifacts, ziptools, deterministic_zip, romdir, sect233r1, crypto_verify, paths (REPO_ROOT). model: safeparse (needs yaml), dumpcatalog, largefiles, alternatives. resolve: nativemode, validation, launchers, slot, truth, gamedata, and exporter/baseline.py and exporter/candidates.py as resolve/reconcile.py and resolve/categories.py, which truth and gamedata read. Every importer follows. Modules one level deeper read the repository root from core.paths instead of __file__.
This commit is contained in:
1 parent
23d8a770f1
commit
c784aef883
167 files changed
+412
-434
No files matched your search
@@ -0,0 +1 @@
|
||||
"""Standard-library foundations: hashing, archives, parsing, artifacts, command-line plumbing."""
|
||||
@@ -0,0 +1,370 @@
|
||||
"""Writing generated files, and not writing them.
|
||||
|
||||
A generated artefact carries a timestamp but must not be rewritten
|
||||
when only the clock moved: the CI freshness guard is a git diff, and
|
||||
it is only meaningful if the comparison ignores the hour."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Iterator
|
||||
from typing import BinaryIO
|
||||
import contextlib
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
import re
|
||||
from core.paths import REPO_ROOT
|
||||
|
||||
|
||||
_TIMESTAMP_PATTERNS = [
|
||||
re.compile(r'"generated_at":\s*"[^"]*"'), # database.json
|
||||
re.compile(r'"imported_at":\s*"[^"]*"'), # provenance snapshots
|
||||
re.compile(r'"fetched":\s*"[^"]*"'), # games/catalogs/
|
||||
re.compile(r"\*Auto-generated on [^*]*\*"), # README.md
|
||||
re.compile(r"\*Generated on [^*]*\*"), # docs site pages
|
||||
# The decorated pages carry the same stamp again as a rendered element,
|
||||
# and missing it rewrote every page on every run for the clock alone.
|
||||
re.compile(r'<div class="rb-timestamp">[^<]*</div>'),
|
||||
re.compile(r'<time datetime="[^"]*">Data as of [^<]*</time>'),
|
||||
]
|
||||
|
||||
def json_text(value: object) -> str:
|
||||
"""Stable scalar representation for CSV and SQLite exports."""
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, (dict, list, tuple, bool)):
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True)
|
||||
return str(value)
|
||||
|
||||
|
||||
def write_if_changed(
|
||||
path: str, content: str, normalize: Callable[[str], str] | None = None
|
||||
) -> bool:
|
||||
"""Write content to path only if the non-timestamp content differs.
|
||||
|
||||
Compares new and existing content after stripping timestamp lines.
|
||||
Returns True if the file was written, False if skipped (unchanged).
|
||||
|
||||
A caller that writes a file in two passes (a body, then the same body
|
||||
wrapped in front matter) passes ``normalize`` to reduce both sides to the
|
||||
part it owns. Without it the second pass always sees a difference, the
|
||||
file is rewritten, and the fresh timestamp defeats the comparison.
|
||||
"""
|
||||
if os.path.exists(path):
|
||||
with open(path) as f:
|
||||
existing = f.read()
|
||||
before, after = (
|
||||
(normalize(existing), normalize(content))
|
||||
if normalize
|
||||
else (existing, content)
|
||||
)
|
||||
if _strip_timestamps(before) == _strip_timestamps(after):
|
||||
return False
|
||||
write_text_atomic(path, content)
|
||||
return True
|
||||
|
||||
|
||||
_UMASK_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def process_umask() -> int:
|
||||
"""The process umask, read without letting a second thread see it at 0.
|
||||
|
||||
Reading the umask sets it, so it is put back at once. Two threads doing
|
||||
that unguarded interleave as A sets 0 and reads 022, B sets 0 and reads 0,
|
||||
A restores 022, B restores 0: the process keeps umask 0 and every file it
|
||||
creates afterwards is world-writable.
|
||||
"""
|
||||
with _UMASK_LOCK:
|
||||
umask = os.umask(0)
|
||||
os.umask(umask)
|
||||
return umask
|
||||
|
||||
|
||||
def plain_file_mode() -> int:
|
||||
"""The mode open() gives a new file: 0o666 less the process umask."""
|
||||
return 0o666 & ~process_umask()
|
||||
|
||||
|
||||
def set_plain_mode(path: str | os.PathLike) -> None:
|
||||
"""Give a scratch file the mode a plain open() would have.
|
||||
|
||||
mkstemp creates its file 0600 so no other user reads it while it is
|
||||
written. Renamed into place, that mode stayed: database.json, the
|
||||
manifests, the packs and the recipe snapshots came out unreadable to
|
||||
every other account on the machine and to a web server serving them.
|
||||
"""
|
||||
os.chmod(path, plain_file_mode())
|
||||
|
||||
|
||||
def write_text_atomic(path: str, content: str) -> None:
|
||||
"""Write a whole file or nothing.
|
||||
|
||||
Truncate-then-write leaves a half-written artifact behind an interrupt:
|
||||
a partial database.json, manifest or README.md is committed-looking and
|
||||
silently wrong. The scratch file sits beside the target so the rename
|
||||
stays on one filesystem, which is what makes it atomic.
|
||||
"""
|
||||
directory = os.path.dirname(os.path.abspath(path))
|
||||
handle, scratch = tempfile.mkstemp(
|
||||
dir=directory, prefix=f".{os.path.basename(path)}.", suffix=".tmp"
|
||||
)
|
||||
try:
|
||||
with os.fdopen(handle, "w", encoding="utf-8") as f:
|
||||
f.write(content)
|
||||
set_plain_mode(scratch)
|
||||
os.replace(scratch, path)
|
||||
except BaseException:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(scratch)
|
||||
raise
|
||||
|
||||
|
||||
def write_bytes_atomic(path: str, content: bytes) -> None:
|
||||
"""Write a whole binary file or nothing, as write_text_atomic does."""
|
||||
directory = os.path.dirname(os.path.abspath(path))
|
||||
handle, scratch = tempfile.mkstemp(
|
||||
dir=directory, prefix=f".{os.path.basename(path)}.", suffix=".tmp"
|
||||
)
|
||||
try:
|
||||
with os.fdopen(handle, "wb") as f:
|
||||
f.write(content)
|
||||
set_plain_mode(scratch)
|
||||
os.replace(scratch, path)
|
||||
except BaseException:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(scratch)
|
||||
raise
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def file_lock(lock_path: str | os.PathLike, shared: bool = False) -> Iterator[None]:
|
||||
"""Hold a lock on lock_path, waiting for it if taken.
|
||||
|
||||
Several sessions refresh the same caches: without it, two swaps of one
|
||||
tree interleave, or two read-modify-writes of one index lose an entry.
|
||||
On platforms without flock the lock is a no-op.
|
||||
"""
|
||||
try:
|
||||
import fcntl
|
||||
except ImportError:
|
||||
yield
|
||||
return
|
||||
os.makedirs(os.path.dirname(os.path.abspath(lock_path)), exist_ok=True)
|
||||
with open(lock_path, "a") as handle:
|
||||
fcntl.flock(handle, fcntl.LOCK_SH if shared else fcntl.LOCK_EX)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
fcntl.flock(handle, fcntl.LOCK_UN)
|
||||
|
||||
|
||||
def copy_file_atomic(source: str, path: str) -> None:
|
||||
"""Copy a file into place whole or not at all, metadata included."""
|
||||
import shutil
|
||||
|
||||
directory = os.path.dirname(os.path.abspath(path))
|
||||
handle, scratch = tempfile.mkstemp(
|
||||
dir=directory, prefix=f".{os.path.basename(path)}.", suffix=".tmp"
|
||||
)
|
||||
os.close(handle)
|
||||
try:
|
||||
shutil.copy2(source, scratch)
|
||||
os.replace(scratch, path)
|
||||
except BaseException:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(scratch)
|
||||
raise
|
||||
|
||||
|
||||
def copy_stream_atomic(stream: BinaryIO, path: str) -> None:
|
||||
"""Stream a download into place whole or not at all.
|
||||
|
||||
A fixed scratch name let two runs interleave their bytes in one file of
|
||||
the right size, which the rename then promoted."""
|
||||
import shutil
|
||||
|
||||
directory = os.path.dirname(os.path.abspath(path))
|
||||
handle, scratch = tempfile.mkstemp(
|
||||
dir=directory, prefix=f".{os.path.basename(path)}.", suffix=".tmp"
|
||||
)
|
||||
try:
|
||||
with os.fdopen(handle, "wb") as f:
|
||||
shutil.copyfileobj(stream, f)
|
||||
set_plain_mode(scratch)
|
||||
os.replace(scratch, path)
|
||||
except BaseException:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(scratch)
|
||||
raise
|
||||
|
||||
|
||||
def _strip_timestamps(text: str) -> str:
|
||||
"""Remove known timestamp patterns for content comparison."""
|
||||
result = text
|
||||
for pattern in _TIMESTAMP_PATTERNS:
|
||||
result = pattern.sub("", result)
|
||||
return result
|
||||
|
||||
class ArtifactLockBusy(RuntimeError):
|
||||
"""Raised when another process already holds the artifact directory."""
|
||||
|
||||
|
||||
class ArtifactDirectoryMissing(FileNotFoundError):
|
||||
"""A reader named a directory that does not exist."""
|
||||
|
||||
# A run that holds artifact directories for its whole duration names them
|
||||
# here, os.pathsep apart, for the steps it spawns: they would otherwise be
|
||||
# refused by it. A pipeline holds the repository root and its --output-dir.
|
||||
HELD_LOCK_ENV = "RETROBIOS_HELD_ARTIFACT_DIR"
|
||||
# Where the repository root's lock is taken instead, set by tests/__init__.
|
||||
REPOSITORY_LOCK_ENV = "RETROBIOS_REPOSITORY_LOCK_DIR"
|
||||
|
||||
|
||||
def _held_directories() -> list[str]:
|
||||
return [d for d in os.environ.get(HELD_LOCK_ENV, "").split(os.pathsep) if d]
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def artifact_lock(directory: str, exclusive: bool = True) -> Iterator[None]:
|
||||
"""Serialize access to a shared artifact directory across processes.
|
||||
|
||||
Two pipeline runs building the same dist/ leave readers looking at
|
||||
half-written ZIPs, which surfaces as BadZipFile far from its cause.
|
||||
Writers take the lock exclusively, readers share it. On platforms
|
||||
without flock the lock is a no-op.
|
||||
"""
|
||||
# A reader creating the directory it was pointed at left a typo behind
|
||||
# as a directory holding a .lock, and the next run with the same typo
|
||||
# no longer said the path did not exist.
|
||||
if not exclusive and not os.path.isdir(directory):
|
||||
raise ArtifactDirectoryMissing(
|
||||
f"{directory}: no such directory, pass the --output-dir the packs "
|
||||
"were written to (default dist/)"
|
||||
)
|
||||
try:
|
||||
import fcntl
|
||||
except ImportError:
|
||||
yield
|
||||
return
|
||||
|
||||
os.makedirs(directory, exist_ok=True)
|
||||
if os.path.realpath(directory) in _held_directories():
|
||||
yield
|
||||
return
|
||||
lock_dir = directory
|
||||
# The test suite runs its modules side by side, each a process with its
|
||||
# own scratch folder (scripts/run_tests.py): the repository's hold is
|
||||
# taken there, so a module that runs the pipeline or a generator is not
|
||||
# refused because another module holds it. Nothing else sets it.
|
||||
moved = os.environ.get(REPOSITORY_LOCK_ENV)
|
||||
real = os.path.realpath(directory)
|
||||
if moved and os.path.isfile(os.path.join(real, "scripts", "core", "artifacts.py")):
|
||||
# Keyed by the root's path: a scratch checkout and the process it
|
||||
# spawns name the same root, and find the same lock.
|
||||
lock_dir = os.path.join(moved, real.strip(os.sep).replace(os.sep, "__"))
|
||||
os.makedirs(lock_dir, exist_ok=True)
|
||||
lock_path = os.path.join(lock_dir, ".lock")
|
||||
mode = fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH
|
||||
with open(lock_path, "w") as handle:
|
||||
try:
|
||||
fcntl.flock(handle, mode | fcntl.LOCK_NB)
|
||||
except OSError as exc:
|
||||
raise ArtifactLockBusy(
|
||||
f"{directory} is in use by another run "
|
||||
f"(lock: {lock_path}). Wait for it to finish."
|
||||
) from exc
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
fcntl.flock(handle, fcntl.LOCK_UN)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def hold_artifact_lock(directory: str) -> Iterator[None]:
|
||||
"""Hold a directory exclusively across several child steps.
|
||||
|
||||
A lock taken step by step frees the directory between them: another
|
||||
run can purge the packs one step built before the next step checks
|
||||
them. The children this process spawns inherit the hold.
|
||||
"""
|
||||
with artifact_lock(directory), publish_hold(directory):
|
||||
yield
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def publish_hold(directory: str) -> Iterator[None]:
|
||||
"""Name a directory this process holds to the steps it spawns."""
|
||||
previous = os.environ.get(HELD_LOCK_ENV)
|
||||
os.environ[HELD_LOCK_ENV] = os.pathsep.join(
|
||||
[*_held_directories(), os.path.realpath(directory)]
|
||||
)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if previous is None:
|
||||
os.environ.pop(HELD_LOCK_ENV, None)
|
||||
else:
|
||||
os.environ[HELD_LOCK_ENV] = previous
|
||||
|
||||
|
||||
# What a pipeline run writes at fixed paths, whatever its --output-dir.
|
||||
REPOSITORY_OUTPUTS = ("database.json", "install/", "README.md", "CONTRIBUTING.md", "website/")
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def hold_repository_outputs(root: str = ".") -> Iterator[None]:
|
||||
"""Hold the outputs a pipeline writes at fixed paths, for the whole run.
|
||||
|
||||
The output-directory lock let a run on tmp/packtest start beside a run
|
||||
on dist/: both rewrote database.json, and the second to reach the
|
||||
manifest step found install/ held after minutes of work, or, when the
|
||||
steps did not overlap, rewrote the committed manifests from its own
|
||||
state. The lock file is the repository root's .lock. A pipeline passes
|
||||
it to its steps with publish_hold.
|
||||
"""
|
||||
stack = contextlib.ExitStack()
|
||||
try:
|
||||
stack.enter_context(artifact_lock(root))
|
||||
except ArtifactLockBusy as exc:
|
||||
raise ArtifactLockBusy(
|
||||
f"another run is writing {', '.join(REPOSITORY_OUTPUTS)} "
|
||||
f"(lock: {os.path.join(root, '.lock')}). Wait for it to finish."
|
||||
) from exc
|
||||
with stack:
|
||||
yield
|
||||
|
||||
|
||||
_REPO_ROOT = str(REPO_ROOT)
|
||||
|
||||
|
||||
def repository_output_lock(path: str) -> contextlib.AbstractContextManager[None]:
|
||||
"""The repository hold, when *path* is one of its fixed outputs.
|
||||
|
||||
Only a pipeline took it: generate_db.py run beside a pipeline replaced
|
||||
database.json between its verify and its packs, and a manifest run on
|
||||
install/ made the pipeline's own manifest step fail after minutes of
|
||||
work. A path elsewhere (a scratch --output) takes nothing.
|
||||
"""
|
||||
target = os.path.realpath(path)
|
||||
for output in REPOSITORY_OUTPUTS:
|
||||
fixed = os.path.join(_REPO_ROOT, output.rstrip("/"))
|
||||
if target == fixed or target.startswith(fixed + os.sep):
|
||||
return hold_repository_outputs(_REPO_ROOT)
|
||||
return contextlib.nullcontext()
|
||||
|
||||
|
||||
def _build_timestamp(db: dict | None = None) -> str:
|
||||
"""Timestamp for generated artifacts.
|
||||
|
||||
Reads the database snapshot the artifact was built from, so rebuilding
|
||||
the same data twice yields the same value. Falls back to the clock only
|
||||
when no database is at hand.
|
||||
"""
|
||||
stamp = (db or {}).get("generated_at")
|
||||
if isinstance(stamp, str) and stamp:
|
||||
return stamp
|
||||
from datetime import datetime, timezone
|
||||
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
@@ -0,0 +1,536 @@
|
||||
"""3DS signature and crypto verification for emulator profile validation.
|
||||
|
||||
Reproduces the exact verification logic from Azahar/Citra source code:
|
||||
- SecureInfo_A: RSA-2048 PKCS1v15 SHA256
|
||||
- LocalFriendCodeSeed_B: RSA-2048 PKCS1v15 SHA256
|
||||
- movable.sed: magic check + RSA on embedded LFCS
|
||||
- otp.bin: AES-128-CBC decrypt + magic + SHA256 hash
|
||||
|
||||
RSA verification and AES decryption are pure Python (no dependencies).
|
||||
|
||||
Source refs:
|
||||
Azahar src/core/hw/unique_data.cpp
|
||||
Azahar src/core/hw/rsa/rsa.cpp
|
||||
Azahar src/core/file_sys/otp.cpp
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import struct
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
# Key file parsing (keys.txt / aes_keys.txt format)
|
||||
|
||||
|
||||
def parse_keys_file(path: str | Path) -> dict[str, dict[str, bytes]]:
|
||||
"""Parse a 3DS keys file with :AES, :RSA, :ECC sections.
|
||||
|
||||
Returns {section: {key_name: bytes_value}}.
|
||||
"""
|
||||
sections: dict[str, dict[str, bytes]] = {}
|
||||
current_section = ""
|
||||
for line in Path(path).read_text(errors="replace").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
if line.startswith(":"):
|
||||
current_section = line[1:].strip()
|
||||
if current_section not in sections:
|
||||
sections[current_section] = {}
|
||||
continue
|
||||
if "=" not in line:
|
||||
continue
|
||||
key, _, value = line.partition("=")
|
||||
key = key.strip()
|
||||
value = value.strip()
|
||||
try:
|
||||
sections.setdefault(current_section, {})[key] = bytes.fromhex(value)
|
||||
except ValueError:
|
||||
continue
|
||||
return sections
|
||||
|
||||
|
||||
def find_keys_file(bios_dir: str | Path) -> Path | None:
|
||||
"""Find the 3DS keys file in the bios directory."""
|
||||
candidates = [
|
||||
Path(bios_dir) / "Nintendo" / "3DS" / "aes_keys.txt",
|
||||
Path(bios_dir) / "Nintendo" / "3DS" / "keys.txt",
|
||||
]
|
||||
for p in candidates:
|
||||
if p.exists():
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
# Pure Python RSA-2048 PKCS1v15 SHA256 verification (zero dependencies)
|
||||
|
||||
|
||||
def _rsa_verify_pkcs1v15_sha256(
|
||||
message: bytes,
|
||||
signature: bytes,
|
||||
modulus: bytes,
|
||||
exponent: bytes,
|
||||
) -> bool:
|
||||
"""Verify RSA-2048 PKCS#1 v1.5 with SHA-256.
|
||||
|
||||
Pure Python: uses Python's native int for modular exponentiation.
|
||||
Reproduces CryptoPP::RSASS<PKCS1v15, SHA256>::Verifier.
|
||||
"""
|
||||
n = int.from_bytes(modulus, "big")
|
||||
e = int.from_bytes(exponent, "big")
|
||||
s = int.from_bytes(signature, "big")
|
||||
|
||||
if s >= n:
|
||||
return False
|
||||
|
||||
# RSA verification: m = s^e mod n
|
||||
m = pow(s, e, n)
|
||||
|
||||
# Convert to bytes, padded to modulus length
|
||||
mod_len = len(modulus)
|
||||
try:
|
||||
em = m.to_bytes(mod_len, "big")
|
||||
except OverflowError:
|
||||
return False
|
||||
|
||||
# PKCS#1 v1.5 signature encoding: 0x00 0x01 [0xFF padding] 0x00 [DigestInfo]
|
||||
# DigestInfo for SHA-256:
|
||||
# SEQUENCE { SEQUENCE { OID sha256, NULL }, OCTET STRING hash }
|
||||
digest_info_prefix = bytes(
|
||||
[
|
||||
0x30,
|
||||
0x31, # SEQUENCE (49 bytes)
|
||||
0x30,
|
||||
0x0D, # SEQUENCE (13 bytes)
|
||||
0x06,
|
||||
0x09, # OID (9 bytes)
|
||||
0x60,
|
||||
0x86,
|
||||
0x48,
|
||||
0x01,
|
||||
0x65,
|
||||
0x03,
|
||||
0x04,
|
||||
0x02,
|
||||
0x01, # sha256
|
||||
0x05,
|
||||
0x00, # NULL
|
||||
0x04,
|
||||
0x20, # OCTET STRING (32 bytes)
|
||||
]
|
||||
)
|
||||
|
||||
sha256_hash = hashlib.sha256(message).digest()
|
||||
expected_digest_info = digest_info_prefix + sha256_hash
|
||||
|
||||
# Expected encoding: 0x00 0x01 [0xFF * ps_len] 0x00 [digest_info]
|
||||
t_len = len(expected_digest_info)
|
||||
ps_len = mod_len - t_len - 3
|
||||
if ps_len < 8:
|
||||
return False
|
||||
|
||||
expected_em = b"\x00\x01" + (b"\xff" * ps_len) + b"\x00" + expected_digest_info
|
||||
return em == expected_em
|
||||
|
||||
|
||||
# AES-128-CBC decryption, standard library only. The build promises stdlib +
|
||||
# pyyaml, and a contributor without cryptography, pycryptodome or openssl on PATH
|
||||
# got a RuntimeError from verify.py on otp.bin. 256 bytes need no speed.
|
||||
|
||||
|
||||
def _xtime(value: int) -> int:
|
||||
value <<= 1
|
||||
return (value ^ 0x11B) & 0xFF if value & 0x100 else value
|
||||
|
||||
|
||||
def _gmul(a: int, b: int) -> int:
|
||||
product = 0
|
||||
while b:
|
||||
if b & 1:
|
||||
product ^= a
|
||||
a = _xtime(a)
|
||||
b >>= 1
|
||||
return product
|
||||
|
||||
|
||||
def _build_sbox() -> tuple[list[int], list[int]]:
|
||||
sbox = [0] * 256
|
||||
inverse = [0] * 256
|
||||
for value in range(256):
|
||||
# Multiplicative inverse in GF(2^8), then the affine transform.
|
||||
inv = 0 if value == 0 else next(
|
||||
c for c in range(1, 256) if _gmul(value, c) == 1
|
||||
)
|
||||
out = inv
|
||||
for shift in range(1, 5):
|
||||
out ^= ((inv << shift) | (inv >> (8 - shift))) & 0xFF
|
||||
out ^= 0x63
|
||||
sbox[value] = out
|
||||
inverse[out] = value
|
||||
return sbox, inverse
|
||||
|
||||
|
||||
_SBOX, _INV_SBOX = _build_sbox()
|
||||
|
||||
|
||||
def _expand_key(key: bytes) -> list[list[int]]:
|
||||
"""The eleven round keys of AES-128, each sixteen bytes."""
|
||||
words = [list(key[i : i + 4]) for i in range(0, 16, 4)]
|
||||
rcon = 1
|
||||
for i in range(4, 44):
|
||||
word = list(words[i - 1])
|
||||
if i % 4 == 0:
|
||||
word = [_SBOX[b] for b in word[1:] + word[:1]]
|
||||
word[0] ^= rcon
|
||||
rcon = _xtime(rcon)
|
||||
words.append([a ^ b for a, b in zip(words[i - 4], word)])
|
||||
return [sum(words[r * 4 : r * 4 + 4], []) for r in range(11)]
|
||||
|
||||
|
||||
def _decrypt_block(block: bytes, round_keys: list[list[int]]) -> bytes:
|
||||
state = [b ^ k for b, k in zip(block, round_keys[10])]
|
||||
for rnd in range(9, -1, -1):
|
||||
# Inverse ShiftRows on a column-major state, then inverse SubBytes.
|
||||
state = [state[(i + 4 * (i % 4) * 3) % 16] for i in range(16)]
|
||||
state = [_INV_SBOX[b] for b in state]
|
||||
state = [b ^ k for b, k in zip(state, round_keys[rnd])]
|
||||
if rnd:
|
||||
mixed = []
|
||||
for c in range(4):
|
||||
a0, a1, a2, a3 = state[c * 4 : c * 4 + 4]
|
||||
mixed += [
|
||||
_gmul(a0, 14) ^ _gmul(a1, 11) ^ _gmul(a2, 13) ^ _gmul(a3, 9),
|
||||
_gmul(a0, 9) ^ _gmul(a1, 14) ^ _gmul(a2, 11) ^ _gmul(a3, 13),
|
||||
_gmul(a0, 13) ^ _gmul(a1, 9) ^ _gmul(a2, 14) ^ _gmul(a3, 11),
|
||||
_gmul(a0, 11) ^ _gmul(a1, 13) ^ _gmul(a2, 9) ^ _gmul(a3, 14),
|
||||
]
|
||||
state = mixed
|
||||
return bytes(state)
|
||||
|
||||
|
||||
def _aes_128_cbc_decrypt(data: bytes, key: bytes, iv: bytes) -> bytes:
|
||||
"""Decrypt AES-128-CBC without padding."""
|
||||
if len(key) != 16 or len(iv) != 16 or len(data) % 16:
|
||||
raise ValueError("AES-128-CBC needs a 16-byte key and IV and whole blocks")
|
||||
round_keys = _expand_key(key)
|
||||
out = bytearray()
|
||||
previous = iv
|
||||
for offset in range(0, len(data), 16):
|
||||
block = data[offset : offset + 16]
|
||||
plain = _decrypt_block(block, round_keys)
|
||||
out += bytes(a ^ b for a, b in zip(plain, previous))
|
||||
previous = block
|
||||
return bytes(out)
|
||||
|
||||
|
||||
# File verification functions
|
||||
|
||||
|
||||
def verify_secure_info_a(
|
||||
filepath: str | Path,
|
||||
keys: dict[str, dict[str, bytes]],
|
||||
) -> tuple[bool, str]:
|
||||
"""Verify SecureInfo_A RSA-2048 PKCS1v15 SHA256 signature.
|
||||
|
||||
Source: Azahar src/core/hw/unique_data.cpp:43-92
|
||||
Struct: 0x100 signature + 0x11 body (region + unknown + serial) = 0x111
|
||||
|
||||
Returns (valid, reason_string).
|
||||
"""
|
||||
data = Path(filepath).read_bytes()
|
||||
|
||||
# Size check
|
||||
if len(data) != 0x111:
|
||||
return False, f"size mismatch: expected 273, got {len(data)}"
|
||||
|
||||
# Check validity (at least one non-zero byte in serial)
|
||||
serial = data[0x102:0x111]
|
||||
if serial == b"\x00" * 15:
|
||||
return False, "invalid: serial_number is all zeros"
|
||||
|
||||
rsa_keys = keys.get("RSA", {})
|
||||
modulus = rsa_keys.get("secureInfoMod")
|
||||
exponent = rsa_keys.get("secureInfoExp")
|
||||
if not modulus or not exponent:
|
||||
return False, "missing RSA keys (secureInfoMod/secureInfoExp) in keys file"
|
||||
|
||||
signature = data[0x000:0x100]
|
||||
body = data[0x100:0x111]
|
||||
|
||||
if _rsa_verify_pkcs1v15_sha256(body, signature, modulus, exponent):
|
||||
return True, "signature valid"
|
||||
|
||||
# Region change detection: try all other region values
|
||||
region_byte = data[0x100]
|
||||
for test_region in range(7):
|
||||
if test_region == region_byte:
|
||||
continue
|
||||
modified_body = bytes([test_region]) + body[1:]
|
||||
if _rsa_verify_pkcs1v15_sha256(modified_body, signature, modulus, exponent):
|
||||
return (
|
||||
False,
|
||||
f"signature invalid (region changed from {test_region} to {region_byte})",
|
||||
)
|
||||
|
||||
return False, "signature invalid"
|
||||
|
||||
|
||||
def verify_local_friend_code_seed_b(
|
||||
filepath: str | Path,
|
||||
keys: dict[str, dict[str, bytes]],
|
||||
) -> tuple[bool, str]:
|
||||
"""Verify LocalFriendCodeSeed_B RSA-2048 PKCS1v15 SHA256 signature.
|
||||
|
||||
Source: Azahar src/core/hw/unique_data.cpp:94-123
|
||||
Struct: 0x100 signature + 0x10 body (unknown + friend_code_seed) = 0x110
|
||||
|
||||
Returns (valid, reason_string).
|
||||
"""
|
||||
data = Path(filepath).read_bytes()
|
||||
|
||||
if len(data) != 0x110:
|
||||
return False, f"size mismatch: expected 272, got {len(data)}"
|
||||
|
||||
# Check validity (friend_code_seed != 0)
|
||||
friend_code_seed = struct.unpack_from("<Q", data, 0x108)[0]
|
||||
if friend_code_seed == 0:
|
||||
return False, "invalid: friend_code_seed is zero"
|
||||
|
||||
rsa_keys = keys.get("RSA", {})
|
||||
modulus = rsa_keys.get("lfcsMod")
|
||||
exponent = rsa_keys.get("lfcsExp")
|
||||
if not modulus or not exponent:
|
||||
return False, "missing RSA keys (lfcsMod/lfcsExp) in keys file"
|
||||
|
||||
signature = data[0x000:0x100]
|
||||
body = data[0x100:0x110]
|
||||
|
||||
if _rsa_verify_pkcs1v15_sha256(body, signature, modulus, exponent):
|
||||
return True, "signature valid"
|
||||
return False, "signature invalid"
|
||||
|
||||
|
||||
def verify_movable_sed(
|
||||
filepath: str | Path,
|
||||
keys: dict[str, dict[str, bytes]],
|
||||
) -> tuple[bool, str]:
|
||||
"""Verify movable.sed: magic check + RSA on embedded LFCS.
|
||||
|
||||
Source: Azahar src/core/hw/unique_data.cpp:170-200
|
||||
Struct: 0x08 header + 0x110 embedded LFCS + 0x08 keyY = 0x120
|
||||
Full variant: 0x120 + 0x20 extra = 0x140
|
||||
|
||||
Returns (valid, reason_string).
|
||||
"""
|
||||
data = Path(filepath).read_bytes()
|
||||
|
||||
if len(data) not in (0x120, 0x140):
|
||||
return False, f"size mismatch: expected 288 or 320, got {len(data)}"
|
||||
|
||||
# Magic check: "SEED" at offset 0
|
||||
magic = data[0:4]
|
||||
if magic != b"SEED":
|
||||
return False, f"invalid magic: expected 'SEED', got {magic!r}"
|
||||
|
||||
# Embedded LFCS at offset 0x08, size 0x110
|
||||
lfcs_data = data[0x08:0x118]
|
||||
|
||||
# Verify the embedded LFCS signature (same as LocalFriendCodeSeed_B)
|
||||
rsa_keys = keys.get("RSA", {})
|
||||
modulus = rsa_keys.get("lfcsMod")
|
||||
exponent = rsa_keys.get("lfcsExp")
|
||||
if not modulus or not exponent:
|
||||
return False, "missing RSA keys (lfcsMod/lfcsExp) in keys file"
|
||||
|
||||
signature = lfcs_data[0x000:0x100]
|
||||
body = lfcs_data[0x100:0x110]
|
||||
|
||||
if _rsa_verify_pkcs1v15_sha256(body, signature, modulus, exponent):
|
||||
return True, "magic valid, LFCS signature valid"
|
||||
return False, "magic valid, LFCS signature invalid"
|
||||
|
||||
|
||||
def verify_otp(
|
||||
filepath: str | Path,
|
||||
keys: dict[str, dict[str, bytes]],
|
||||
) -> tuple[bool, str]:
|
||||
"""Verify otp.bin: AES-128-CBC decrypt + magic + SHA-256 hash + ECC cert.
|
||||
|
||||
Source: Azahar src/core/file_sys/otp.cpp, src/core/hw/unique_data.cpp
|
||||
Struct: 0xE0 body + 0x20 SHA256 hash = 0x100
|
||||
|
||||
OTP body layout:
|
||||
0x000: u32 magic (0xDEADB00F)
|
||||
0x004: u32 device_id
|
||||
0x018: u8 otp_version
|
||||
0x019: u8 system_type (0=retail, non-zero=dev)
|
||||
0x020: u32 ctcert.expiry_date
|
||||
0x024: 0x20 ctcert.priv_key (ECC private key)
|
||||
0x044: 0x3C ctcert.signature (ECC signature r||s)
|
||||
|
||||
Certificate body (what is signed): issuer(0x40) + key_type(4) + name(0x40)
|
||||
+ expiration(4) + public_key_xy(0x3C), aligned to 0x100.
|
||||
|
||||
Returns (valid, reason_string).
|
||||
"""
|
||||
from core.sect233r1 import _N, _ec_mul, _Gx, _Gy, ecdsa_verify_sha256
|
||||
|
||||
data = bytearray(Path(filepath).read_bytes())
|
||||
|
||||
if len(data) != 0x100:
|
||||
return False, f"size mismatch: expected 256, got {len(data)}"
|
||||
|
||||
aes_keys = keys.get("AES", {})
|
||||
otp_key = aes_keys.get("otpKey")
|
||||
otp_iv = aes_keys.get("otpIV")
|
||||
|
||||
# Check magic before decryption (file might already be decrypted)
|
||||
magic = struct.unpack_from("<I", data, 0)[0]
|
||||
if magic != 0xDEADB00F:
|
||||
if not otp_key or not otp_iv:
|
||||
return (
|
||||
False,
|
||||
"encrypted OTP but missing AES keys (otpKey/otpIV) in keys file",
|
||||
)
|
||||
try:
|
||||
data = bytearray(_aes_128_cbc_decrypt(bytes(data), otp_key, otp_iv))
|
||||
except RuntimeError as e:
|
||||
return False, str(e)
|
||||
magic = struct.unpack_from("<I", data, 0)[0]
|
||||
if magic != 0xDEADB00F:
|
||||
return False, f"decryption failed: magic 0x{magic:08X} != 0xDEADB00F"
|
||||
|
||||
# SHA-256 hash verification
|
||||
body = bytes(data[0x00:0xE0])
|
||||
stored_hash = bytes(data[0xE0:0x100])
|
||||
computed_hash = hashlib.sha256(body).digest()
|
||||
|
||||
if computed_hash != stored_hash:
|
||||
return False, "SHA-256 hash mismatch (OTP corrupted)"
|
||||
|
||||
# ECC certificate verification (sect233r1)
|
||||
ecc_keys = keys.get("ECC", {})
|
||||
root_public_xy = ecc_keys.get("rootPublicXY")
|
||||
if not root_public_xy or len(root_public_xy) != 60:
|
||||
return (
|
||||
True,
|
||||
"decrypted, magic valid, SHA-256 valid (ECC skipped: no rootPublicXY)",
|
||||
)
|
||||
|
||||
# Extract CTCert fields from OTP body
|
||||
device_id = struct.unpack_from("<I", data, 0x04)[0]
|
||||
otp_version = data[0x18]
|
||||
system_type = data[0x19]
|
||||
|
||||
# Expiry date endianness depends on otp_version
|
||||
if otp_version < 5:
|
||||
expiry_date = struct.unpack_from(">I", data, 0x20)[0]
|
||||
else:
|
||||
expiry_date = struct.unpack_from("<I", data, 0x20)[0]
|
||||
|
||||
# ECC private key (0x20 bytes at offset 0x24)
|
||||
priv_key_raw = bytes(data[0x24:0x44])
|
||||
# ECC signature (0x3C bytes at offset 0x44)
|
||||
signature_rs = bytes(data[0x44:0x80])
|
||||
|
||||
# Fix up private key: privkey % subgroup_order (Nintendo's ECC lib quirk)
|
||||
priv_key_int = int.from_bytes(priv_key_raw, "big") % _N
|
||||
|
||||
# Derive public key from private key: Q = privkey * G
|
||||
pub_point = _ec_mul(priv_key_int, (_Gx, _Gy))
|
||||
if pub_point is None:
|
||||
return False, "ECC cert: derived public key is point at infinity"
|
||||
pub_key_xy = pub_point[0].to_bytes(30, "big") + pub_point[1].to_bytes(30, "big")
|
||||
|
||||
# Build certificate body (what was signed)
|
||||
# Issuer: "Nintendo CA - G3_NintendoCTR2prod" or "...dev"
|
||||
issuer = bytearray(0x40)
|
||||
if system_type == 0:
|
||||
issuer_str = b"Nintendo CA - G3_NintendoCTR2prod"
|
||||
else:
|
||||
issuer_str = b"Nintendo CA - G3_NintendoCTR2dev"
|
||||
issuer[: len(issuer_str)] = issuer_str
|
||||
|
||||
# Name: "CT{device_id:08X}-{system_type:02X}"
|
||||
name = bytearray(0x40)
|
||||
name_str = f"CT{device_id:08X}-{system_type:02X}".encode()
|
||||
name[: len(name_str)] = name_str
|
||||
|
||||
# Key type = 2 (ECC), big-endian u32
|
||||
key_type = struct.pack(">I", 2)
|
||||
|
||||
# Expiry date as big-endian u32
|
||||
expiry_be = struct.pack(">I", expiry_date)
|
||||
|
||||
# Serialize: issuer + key_type + name + expiry + public_key_xy
|
||||
cert_body = bytes(issuer) + key_type + bytes(name) + expiry_be + pub_key_xy
|
||||
# Align up to 0x40
|
||||
aligned_size = ((len(cert_body) + 0x3F) // 0x40) * 0x40
|
||||
cert_body_padded = cert_body.ljust(aligned_size, b"\x00")
|
||||
|
||||
# Verify ECDSA-SHA256 signature against root public key
|
||||
valid = ecdsa_verify_sha256(cert_body_padded, signature_rs, root_public_xy)
|
||||
|
||||
if valid:
|
||||
return True, "decrypted, magic valid, SHA-256 valid, ECC cert valid"
|
||||
return False, "decrypted, magic+SHA256 valid, but ECC cert signature invalid"
|
||||
|
||||
|
||||
# Unified verification interface for verify.py
|
||||
|
||||
# Map from (filename, validation_type) to verification function
|
||||
_CRYPTO_VERIFIERS: dict[str, Callable] = {
|
||||
"SecureInfo_A": verify_secure_info_a,
|
||||
"LocalFriendCodeSeed_B": verify_local_friend_code_seed_b,
|
||||
"movable.sed": verify_movable_sed,
|
||||
"otp.bin": verify_otp,
|
||||
}
|
||||
|
||||
|
||||
def _stat_key(path: str | Path) -> tuple | None:
|
||||
"""(path, inode, size, mtime_ns, ctime_ns): the file as compute_hashes
|
||||
keys it, None when it cannot be read."""
|
||||
try:
|
||||
stat = Path(path).stat()
|
||||
except OSError:
|
||||
return None
|
||||
return (str(Path(path).resolve()), stat.st_ino, stat.st_size,
|
||||
stat.st_mtime_ns, stat.st_ctime_ns)
|
||||
|
||||
|
||||
# (verifier, file key, keys file key) -> reason or None. verify --all ran the
|
||||
# curve and RSA checks of the same five files once per platform, 35 runs for
|
||||
# 5 answers: the answer depends on the file's bytes and the keys file alone.
|
||||
_crypto_cache: dict[tuple, str | None] = {}
|
||||
|
||||
|
||||
def check_crypto_validation(
|
||||
local_path: str,
|
||||
filename: str,
|
||||
bios_dir: str,
|
||||
) -> str | None:
|
||||
"""Check signature/crypto validation for 3DS files.
|
||||
|
||||
Returns None if verification passes or is not applicable.
|
||||
Returns a reason string on failure.
|
||||
"""
|
||||
verifier = _CRYPTO_VERIFIERS.get(filename)
|
||||
if not verifier:
|
||||
return None
|
||||
|
||||
keys_file = find_keys_file(bios_dir)
|
||||
if not keys_file:
|
||||
return "crypto check skipped: no keys file found"
|
||||
|
||||
file_key, keys_key = _stat_key(local_path), _stat_key(keys_file)
|
||||
key = (filename, file_key, keys_key) if file_key and keys_key else None
|
||||
if key in _crypto_cache:
|
||||
return _crypto_cache[key]
|
||||
keys = parse_keys_file(keys_file)
|
||||
valid, reason = verifier(local_path, keys)
|
||||
result = None if valid else reason
|
||||
if key is not None:
|
||||
_crypto_cache[key] = result
|
||||
return result
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Deterministic ZIP rebuilding for arcade BIOS and sample archives.
|
||||
|
||||
A ZIP's hash depends on entry order, timestamps, compression level, and
|
||||
permission bits as much as on content. Packs ship archives rebuilt with
|
||||
all of that fixed, so the same ROMs always produce the same pack hash
|
||||
regardless of how the source set was assembled.
|
||||
|
||||
Usage:
|
||||
from deterministic_zip import rebuild_zip_deterministic
|
||||
|
||||
sha1 = rebuild_zip_deterministic("neogeo.zip", "out/neogeo.zip")
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
# Fixed metadata for deterministic ZIPs
|
||||
_FIXED_DATE_TIME = (1980, 1, 1, 0, 0, 0) # minimum ZIP timestamp
|
||||
_FIXED_CREATE_SYSTEM = 0 # FAT/DOS (most compatible)
|
||||
_FIXED_EXTERNAL_ATTR = 0o100644 << 16 # -rw-r--r--
|
||||
_COMPRESS_LEVEL = 9 # deflate level 9 for determinism
|
||||
_COPY_CHUNK = 1024 * 1024
|
||||
|
||||
|
||||
def _sha1_file(path: str | Path) -> str:
|
||||
sha1 = hashlib.sha1()
|
||||
with open(path, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(65536), b""):
|
||||
sha1.update(chunk)
|
||||
return sha1.hexdigest()
|
||||
|
||||
|
||||
def rebuild_zip_deterministic(
|
||||
source_zip: str | Path,
|
||||
output_zip: str | Path,
|
||||
) -> str:
|
||||
"""Rebuild a ZIP with fixed metadata and entries sorted by name.
|
||||
|
||||
Copies one chunk at a time rather than loading the archive: arcade
|
||||
sample sets reach 279 MB, and holding a whole set plus its rebuilt
|
||||
copy in memory costs hundreds of megabytes per pack for no benefit.
|
||||
|
||||
Reading through ZipFile.open verifies each entry against the CRC
|
||||
recorded in the source archive, so a corrupt entry raises
|
||||
BadZipFile instead of being copied through.
|
||||
|
||||
Returns the SHA1 of the new ZIP.
|
||||
"""
|
||||
with zipfile.ZipFile(str(source_zip)) as src:
|
||||
entries = sorted(
|
||||
(i for i in src.infolist() if not i.is_dir()),
|
||||
key=lambda i: i.filename,
|
||||
)
|
||||
with zipfile.ZipFile(
|
||||
str(output_zip),
|
||||
"w",
|
||||
zipfile.ZIP_DEFLATED,
|
||||
compresslevel=_COMPRESS_LEVEL,
|
||||
) as dst:
|
||||
for info in entries:
|
||||
out_info = zipfile.ZipInfo(
|
||||
filename=info.filename, date_time=_FIXED_DATE_TIME
|
||||
)
|
||||
out_info.compress_type = zipfile.ZIP_DEFLATED
|
||||
out_info.create_system = _FIXED_CREATE_SYSTEM
|
||||
out_info.external_attr = _FIXED_EXTERNAL_ATTR
|
||||
with src.open(info) as fsrc, dst.open(out_info, "w") as fdst:
|
||||
shutil.copyfileobj(fsrc, fdst, _COPY_CHUNK)
|
||||
|
||||
return _sha1_file(output_zip)
|
||||
|
||||
|
||||
def verify_zip_determinism(zip_path: str | Path) -> tuple[bool, str, str]:
|
||||
"""Check whether a ZIP already matches its deterministic rebuild.
|
||||
|
||||
Returns (is_deterministic, original_sha1, rebuilt_sha1).
|
||||
"""
|
||||
original = _sha1_file(zip_path)
|
||||
fd, tmp_path = tempfile.mkstemp(suffix=".zip")
|
||||
os.close(fd)
|
||||
try:
|
||||
rebuilt = rebuild_zip_deterministic(zip_path, tmp_path)
|
||||
finally:
|
||||
Path(tmp_path).unlink(missing_ok=True)
|
||||
return original == rebuilt, original, rebuilt
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Content digests.
|
||||
|
||||
SHA-1 is the collection's primary key. The rest are what the various
|
||||
frontends check against."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import zipfile
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from typing import IO, BinaryIO
|
||||
from collections.abc import Iterable
|
||||
|
||||
|
||||
_ALL_ALGORITHMS = frozenset({"sha1", "md5", "sha256", "crc32", "adler32"})
|
||||
|
||||
# (path, inode, size, mtime_ns, ctime_ns) -> the digests read so far.
|
||||
# verify --all hashed GB_dmg.bin 13 times, once per platform and entry. The
|
||||
# bytes are still read from disk, once per file and change.
|
||||
_hash_cache: dict[tuple, dict[str, str]] = {}
|
||||
|
||||
|
||||
def compute_hashes(
|
||||
filepath: str | Path,
|
||||
algorithms: frozenset[str] | None = None,
|
||||
cache: bool = True,
|
||||
) -> dict[str, str]:
|
||||
"""Compute file hashes. Pass *algorithms* to limit which are computed.
|
||||
|
||||
cache=False reads the file again, for a second opinion on a digest.
|
||||
"""
|
||||
algos = frozenset(algorithms) if algorithms else _ALL_ALGORITHMS
|
||||
if not cache:
|
||||
return _compute_hashes(filepath, algos)
|
||||
try:
|
||||
stat = os.stat(filepath)
|
||||
key: tuple | None = (
|
||||
os.path.realpath(filepath), stat.st_ino, stat.st_size,
|
||||
stat.st_mtime_ns, stat.st_ctime_ns,
|
||||
)
|
||||
except OSError:
|
||||
key = None
|
||||
known = _hash_cache.get(key) if key else None
|
||||
if known is not None and algos <= known.keys():
|
||||
return {name: known[name] for name in algos}
|
||||
result = _compute_hashes(filepath, algos)
|
||||
if key is not None:
|
||||
_hash_cache.setdefault(key, {}).update(result)
|
||||
return result
|
||||
|
||||
|
||||
def _compute_hashes(filepath: str | Path, algos: frozenset[str]) -> dict[str, str]:
|
||||
"""Read the file once and compute the requested digests."""
|
||||
sha1 = hashlib.sha1() if "sha1" in algos else None
|
||||
md5 = hashlib.md5() if "md5" in algos else None
|
||||
sha256 = hashlib.sha256() if "sha256" in algos else None
|
||||
do_crc = "crc32" in algos
|
||||
do_adler = "adler32" in algos
|
||||
crc = 0
|
||||
adler = 1 # zlib.adler32 initial value
|
||||
with open(filepath, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(65536), b""):
|
||||
if sha1:
|
||||
sha1.update(chunk)
|
||||
if md5:
|
||||
md5.update(chunk)
|
||||
if sha256:
|
||||
sha256.update(chunk)
|
||||
if do_crc:
|
||||
crc = zlib.crc32(chunk, crc)
|
||||
if do_adler:
|
||||
adler = zlib.adler32(chunk, adler)
|
||||
result: dict[str, str] = {}
|
||||
if sha1:
|
||||
result["sha1"] = sha1.hexdigest()
|
||||
if md5:
|
||||
result["md5"] = md5.hexdigest()
|
||||
if sha256:
|
||||
result["sha256"] = sha256.hexdigest()
|
||||
if do_crc:
|
||||
result["crc32"] = format(crc & 0xFFFFFFFF, "08x")
|
||||
if do_adler:
|
||||
result["adler32"] = format(adler & 0xFFFFFFFF, "08x")
|
||||
return result
|
||||
|
||||
def md5sum(source: str | os.PathLike[str] | IO[bytes]) -> str:
|
||||
"""Compute MD5 of a file path or file-like object - matches Batocera's md5sum()."""
|
||||
h = hashlib.md5()
|
||||
if isinstance(source, (str, os.PathLike)):
|
||||
with open(source, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(65536), b""):
|
||||
h.update(chunk)
|
||||
else:
|
||||
for chunk in iter(lambda: source.read(65536), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
_md5_composite_cache: dict[str, str] = {}
|
||||
|
||||
def md5_composite(filepath: str | Path) -> str:
|
||||
"""Compute composite MD5 of a ZIP - matches Recalbox's Zip::Md5Composite().
|
||||
|
||||
Sorts filenames alphabetically, reads each file's contents in order,
|
||||
feeds everything into a single MD5 hasher. The result is independent
|
||||
of ZIP compression level or metadata. Results are cached per path.
|
||||
"""
|
||||
key = str(filepath)
|
||||
cached = _md5_composite_cache.get(key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
result = md5_composite_of(filepath)
|
||||
_md5_composite_cache[key] = result
|
||||
return result
|
||||
|
||||
|
||||
def md5_composite_of(source: str | Path | BinaryIO) -> str:
|
||||
"""md5_composite without the cache, for an archive held in memory.
|
||||
|
||||
A buffer has no stable name: keyed by its repr, a later buffer at the
|
||||
same address read back another archive's digest.
|
||||
"""
|
||||
with zipfile.ZipFile(source) as zf:
|
||||
names = sorted(n for n in zf.namelist() if not n.endswith("/"))
|
||||
h = hashlib.md5()
|
||||
for name in names:
|
||||
info = zf.getinfo(name)
|
||||
if info.file_size > 512 * 1024 * 1024:
|
||||
continue # skip oversized entries
|
||||
h.update(zf.read(name))
|
||||
return h.hexdigest()
|
||||
|
||||
def cut_md5_owner(cut: str, md5s: Iterable[str]) -> str | None:
|
||||
"""The one md5 a value cut short starts, None when none or several do.
|
||||
|
||||
The single rule for a cut md5, read by the scraper, the resolver and
|
||||
--from-md5. It names a dump, it never verifies one: Batocera compares
|
||||
the whole string (batocera-systems:1088), so every verdict compares
|
||||
exact digests.
|
||||
"""
|
||||
if not cut or len(cut) >= 32:
|
||||
return None
|
||||
found = {md5 for md5 in md5s if md5.startswith(cut)}
|
||||
return found.pop() if len(found) == 1 else None
|
||||
|
||||
|
||||
def parse_hash_list(raw: str | list | int | None) -> list[str]:
|
||||
"""Normalize any hash field into its accepted values, lowercase.
|
||||
|
||||
A field holds one value, a YAML list, or one comma-joined string
|
||||
(Recalbox md5, mesence's four sha256 for one entry), and a crc32 may carry
|
||||
a 0x prefix. Read one way here, the resolver, the gap report and
|
||||
profile_sync accept the same values.
|
||||
"""
|
||||
if raw is None or raw == "":
|
||||
return []
|
||||
items = raw if isinstance(raw, list) else str(raw).split(",")
|
||||
out: list[str] = []
|
||||
for item in items:
|
||||
value = str(item).strip().lower().removeprefix("0x")
|
||||
if value and value not in out:
|
||||
out.append(value)
|
||||
return out
|
||||
|
||||
|
||||
def parse_md5_list(raw: str | list | None) -> list[str]:
|
||||
"""Normalize an md5 field into a lowercase list.
|
||||
|
||||
Platform YAMLs carry Recalbox multi-hash as one comma-separated string,
|
||||
emulator profiles carry a YAML list. Both reach here.
|
||||
"""
|
||||
return parse_hash_list(raw)
|
||||
@@ -0,0 +1,8 @@
|
||||
"""The repository root, and pack-relative destinations normalized the same way by every reader."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
# The repository: scripts/core/ is two levels below it.
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
@@ -0,0 +1,171 @@
|
||||
"""The PS2 ROM directory test the PCSX2 family runs on every BIOS candidate.
|
||||
|
||||
A BIOS image starts with a table of 16-byte entries (a 10-byte name, a
|
||||
16-bit extended info size, a 32-bit file size) whose first entry is RESET.
|
||||
``LoadBiosVersion`` (pcsx2/ps2/BiosTools.cpp) reads the file 16 bytes at a
|
||||
time from its start until an entry named RESET, then walks the table from
|
||||
there, adding up the entry sizes rounded to 16 bytes to find where each
|
||||
file of the ROM lies, and reads the 14 bytes of ROMVER at its offset. The
|
||||
image is a BIOS when the walk met ROMVER.
|
||||
|
||||
The forks differ in how they compare the names and in what an unreadable
|
||||
read does, so a profile declares how its code reads the table (``romdir:``
|
||||
on the entry) and ``romdir_accepts`` runs that same walk. Stdlib only:
|
||||
install.py carries a copy of the walk.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from dataclasses import dataclass
|
||||
|
||||
ENTRY_SIZE = 16
|
||||
NAME_SIZE = 10
|
||||
# `for (i = 0; i < 512 * 1024; i++)` in every LoadBiosVersion.
|
||||
SEARCH_ENTRIES = 512 * 1024
|
||||
ROMVER_SIZE = 14
|
||||
EXTINFO_SIZE = 15
|
||||
|
||||
# What a read the code cannot complete does, by fork.
|
||||
REJECT = "rejects" # wxWidgets streams throw (pxStreams.cpp, EndOfStream)
|
||||
ENDS_WALK = "ends_walk" # the walk breaks, the result stands
|
||||
IGNORED = "ignored" # AetherSX2 zero-fills romver and counts it found
|
||||
|
||||
SPEC_KEYS = frozenset({
|
||||
"reset_compare", "missing_reset", "terminated_names", "extinfo", "unreadable_romver",
|
||||
"truncated_walk", "offset_width", "refused_serials", "zones", "refused_zones",
|
||||
})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Romdir:
|
||||
"""What a walk that met ROMVER read: its 14 bytes and the EXTINFO serial."""
|
||||
|
||||
romver: bytes
|
||||
serial: str
|
||||
|
||||
|
||||
def _name_is(name: bytes, wanted: bytes, compared: int) -> bool:
|
||||
"""strncmp(name, wanted, compared) == 0 over a 10-byte field."""
|
||||
a = name[:compared]
|
||||
b = (wanted + b"\x00")[:compared]
|
||||
for x, y in zip(a, b.ljust(len(a), b"\x00")):
|
||||
if x != y:
|
||||
return False
|
||||
if x == 0:
|
||||
return True
|
||||
return True
|
||||
|
||||
|
||||
def _after_reset(data: bytes, reset_compare: int, missing_reset: str) -> int | None:
|
||||
"""The offset past the RESET entry, or past the last entry searched when
|
||||
the walk goes on without one, None where the code gives up."""
|
||||
pos = 0
|
||||
for _ in range(SEARCH_ENTRIES):
|
||||
if pos + ENTRY_SIZE > len(data):
|
||||
return None
|
||||
name = data[pos:pos + NAME_SIZE]
|
||||
pos += ENTRY_SIZE
|
||||
if _name_is(name, b"RESET", reset_compare):
|
||||
break
|
||||
else:
|
||||
if missing_reset == REJECT:
|
||||
return None
|
||||
return pos
|
||||
|
||||
|
||||
def walk(data: bytes, spec: dict) -> Romdir | None:
|
||||
"""The ROM directory walk one fork's LoadBiosVersion runs, or None.
|
||||
|
||||
``reset_compare`` is the length strncmp compares RESET over: 5 in the
|
||||
wxWidgets and AetherSX2 code, which takes any name starting with RESET,
|
||||
sizeof(fileName) (10) after, which wants RESET and a NUL.
|
||||
``terminated_names`` stops the walk at a name with no NUL in its 10
|
||||
bytes (strnlen check of the later code). ``missing_reset`` says what
|
||||
512 Ki entries read without RESET do: ``rejects`` where the code throws
|
||||
(wxWidgets), ``ends_walk`` where the loop just ends and the walk starts
|
||||
at the last entry read. ``extinfo`` reads 15 bytes at
|
||||
the EXTINFO offset + 0x10 and ends the walk when they are not there.
|
||||
``unreadable_romver`` and ``truncated_walk`` say what a ROMVER read and
|
||||
a next-entry read past the end of the file do: ``rejects``,
|
||||
``ends_walk`` or, for ROMVER, ``ignored``. ``offset_width`` is the
|
||||
width of the offset sum: 32 where it is a uint (wxWidgets code), 64
|
||||
where it is an s64.
|
||||
"""
|
||||
size = len(data)
|
||||
reset_compare = int(spec.get("reset_compare", NAME_SIZE))
|
||||
terminated = bool(spec.get("terminated_names", True))
|
||||
extinfo = bool(spec.get("extinfo", True))
|
||||
unreadable = spec.get("unreadable_romver", ENDS_WALK)
|
||||
truncated = spec.get("truncated_walk", ENDS_WALK)
|
||||
missing_reset = spec.get("missing_reset", ENDS_WALK)
|
||||
offset_mask = (1 << int(spec.get("offset_width", 64))) - 1
|
||||
|
||||
found = _after_reset(data, reset_compare, missing_reset)
|
||||
if found is None:
|
||||
return None
|
||||
pos = found
|
||||
entry = data[pos - ENTRY_SIZE:pos]
|
||||
offset = 0
|
||||
romver: bytes | None = None
|
||||
serial = ""
|
||||
while True:
|
||||
name = entry[:NAME_SIZE]
|
||||
if name[0] == 0 or (terminated and b"\x00" not in name):
|
||||
break
|
||||
if extinfo and _name_is(name, b"EXTINFO", NAME_SIZE):
|
||||
start = offset + 0x10
|
||||
if start + EXTINFO_SIZE > size:
|
||||
break
|
||||
serial = data[start:start + EXTINFO_SIZE].split(b"\x00", 1)[0].decode("latin-1")
|
||||
if _name_is(name, b"ROMVER", NAME_SIZE):
|
||||
if offset + ROMVER_SIZE > size:
|
||||
if unreadable == REJECT:
|
||||
return None
|
||||
if unreadable == ENDS_WALK:
|
||||
break
|
||||
romver = bytes(ROMVER_SIZE)
|
||||
else:
|
||||
romver = data[offset:offset + ROMVER_SIZE]
|
||||
(file_size,) = struct.unpack_from("<I", entry, 12)
|
||||
offset += file_size if file_size % 0x10 == 0 else (file_size + 0x10) & 0xFFFFFFF0
|
||||
offset &= offset_mask
|
||||
if pos + ENTRY_SIZE > size:
|
||||
if truncated == REJECT:
|
||||
return None
|
||||
break
|
||||
entry = data[pos:pos + ENTRY_SIZE]
|
||||
pos += ENTRY_SIZE
|
||||
if romver is None:
|
||||
return None
|
||||
return Romdir(romver, serial)
|
||||
|
||||
|
||||
def zone_code(romver: bytes) -> str:
|
||||
"""The zone characters LoadBiosVersion switches on: ROMVER[4], and [5]
|
||||
where the code reads it to tell COH-H (T then Z) from T10K."""
|
||||
return romver[4:6].decode("latin-1")
|
||||
|
||||
|
||||
def romdir_accepts(data: bytes, spec: dict) -> bool:
|
||||
"""Whether a candidate passes the profile's ROM directory test.
|
||||
|
||||
Past the walk, ``refused_serials`` turns away an EXTINFO serial
|
||||
(ARMSX2's NOT_PS2_BIOS_STAMPS), and ``zones``/``refused_zones`` keep or
|
||||
drop an image by its ROMVER zone, as a scan that wants a COH-H board
|
||||
or passes one over does. A zone is written as the code tests it: ``J``
|
||||
is ROMVER[4], ``TZ`` ROMVER[4] and [5].
|
||||
"""
|
||||
found = walk(data, spec)
|
||||
if found is None:
|
||||
return False
|
||||
if found.serial in set(spec.get("refused_serials") or ()):
|
||||
return False
|
||||
code = zone_code(found.romver)
|
||||
|
||||
def matches(zones: list | None) -> bool:
|
||||
return any(code.startswith(str(z)) for z in zones or ())
|
||||
|
||||
if spec.get("zones") and not matches(spec["zones"]):
|
||||
return False
|
||||
return not matches(spec.get("refused_zones"))
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Pure Python ECDSA verification on sect233r1 (binary field curve).
|
||||
|
||||
Implements GF(2^233) field arithmetic, elliptic curve point operations,
|
||||
and ECDSA-SHA256 verification for Nintendo 3DS OTP certificate checking.
|
||||
|
||||
Zero external dependencies: uses only Python stdlib.
|
||||
|
||||
Curve: sect233r1 (NIST B-233, SEC 2 v2)
|
||||
Field: GF(2^233) with irreducible polynomial t^233 + t^74 + 1
|
||||
Equation: y^2 + xy = x^3 + x^2 + b
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
# sect233r1 curve parameters (SEC 2 v2)
|
||||
|
||||
_M = 233
|
||||
_F = (1 << 233) | (1 << 74) | 1 # irreducible polynomial
|
||||
|
||||
_A = 1
|
||||
_B = 0x0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD
|
||||
|
||||
_Gx = 0x00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B
|
||||
_Gy = 0x01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052
|
||||
|
||||
# Subgroup order
|
||||
_N = 0x01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7
|
||||
_N_BITLEN = _N.bit_length() # 233
|
||||
|
||||
# Cofactor
|
||||
_H = 2
|
||||
|
||||
|
||||
# GF(2^233) field arithmetic
|
||||
|
||||
|
||||
def _gf_reduce(a: int) -> int:
|
||||
"""Reduce polynomial a modulo t^233 + t^74 + 1."""
|
||||
while a.bit_length() > _M:
|
||||
shift = a.bit_length() - 1 - _M
|
||||
a ^= _F << shift
|
||||
return a
|
||||
|
||||
|
||||
def _gf_add(a: int, b: int) -> int:
|
||||
"""Add two elements in GF(2^233). Addition = XOR."""
|
||||
return a ^ b
|
||||
|
||||
|
||||
def _gf_mul(a: int, b: int) -> int:
|
||||
"""Multiply two elements in GF(2^233)."""
|
||||
a = _gf_reduce(a)
|
||||
result = 0
|
||||
while b:
|
||||
if b & 1:
|
||||
result ^= a
|
||||
a <<= 1
|
||||
b >>= 1
|
||||
return _gf_reduce(result)
|
||||
|
||||
|
||||
def _gf_sqr(a: int) -> int:
|
||||
"""Square an element in GF(2^233)."""
|
||||
return _gf_mul(a, a)
|
||||
|
||||
|
||||
def _gf_inv(a: int) -> int:
|
||||
"""Multiplicative inverse in GF(2^233) using extended Euclidean algorithm."""
|
||||
if a == 0:
|
||||
raise ZeroDivisionError("inverse of zero in GF(2^m)")
|
||||
# Extended GCD for polynomials in GF(2)[x]
|
||||
old_r, r = _F, a
|
||||
old_s, s = 0, 1
|
||||
while r != 0:
|
||||
# Polynomial division: old_r = q * r + remainder
|
||||
q = 0
|
||||
temp = old_r
|
||||
dr = r.bit_length() - 1
|
||||
while temp != 0 and temp.bit_length() - 1 >= dr:
|
||||
shift = temp.bit_length() - 1 - dr
|
||||
q ^= 1 << shift
|
||||
temp ^= r << shift
|
||||
remainder = temp
|
||||
# Multiply q * s in GF(2)[x] (no reduction: working in polynomial ring)
|
||||
qs = 0
|
||||
qt = q
|
||||
st = s
|
||||
while qt:
|
||||
if qt & 1:
|
||||
qs ^= st
|
||||
st <<= 1
|
||||
qt >>= 1
|
||||
old_r, r = r, remainder
|
||||
old_s, s = s, old_s ^ qs
|
||||
# old_r should be 1 (the GCD)
|
||||
if old_r != 1:
|
||||
raise ValueError("element not invertible")
|
||||
return _gf_reduce(old_s)
|
||||
|
||||
|
||||
# Elliptic curve point operations on sect233r1
|
||||
# y^2 + xy = x^3 + ax^2 + b (a=1)
|
||||
|
||||
# Point at infinity
|
||||
_INF = None
|
||||
|
||||
|
||||
def _ec_add(
|
||||
p: tuple[int, int] | None,
|
||||
q: tuple[int, int] | None,
|
||||
) -> tuple[int, int] | None:
|
||||
"""Add two points on the curve."""
|
||||
if p is _INF:
|
||||
return q
|
||||
if q is _INF:
|
||||
return p
|
||||
|
||||
x1, y1 = p
|
||||
x2, y2 = q
|
||||
|
||||
if x1 == x2:
|
||||
if y1 == _gf_add(y2, x2):
|
||||
# P + (-P) = O
|
||||
return _INF
|
||||
if y1 == y2:
|
||||
# P == Q, use doubling
|
||||
return _ec_double(p)
|
||||
return _INF
|
||||
|
||||
# lambda = (y1 + y2) / (x1 + x2)
|
||||
lam = _gf_mul(_gf_add(y1, y2), _gf_inv(_gf_add(x1, x2)))
|
||||
# x3 = lambda^2 + lambda + x1 + x2 + a
|
||||
x3 = _gf_add(_gf_add(_gf_add(_gf_sqr(lam), lam), _gf_add(x1, x2)), _A)
|
||||
# y3 = lambda * (x1 + x3) + x3 + y1
|
||||
y3 = _gf_add(_gf_add(_gf_mul(lam, _gf_add(x1, x3)), x3), y1)
|
||||
return (x3, y3)
|
||||
|
||||
|
||||
def _ec_double(p: tuple[int, int] | None) -> tuple[int, int] | None:
|
||||
"""Double a point on the curve."""
|
||||
if p is _INF:
|
||||
return _INF
|
||||
|
||||
x1, y1 = p
|
||||
if x1 == 0:
|
||||
return _INF
|
||||
|
||||
# lambda = x1 + y1/x1
|
||||
lam = _gf_add(x1, _gf_mul(y1, _gf_inv(x1)))
|
||||
# x3 = lambda^2 + lambda + a
|
||||
x3 = _gf_add(_gf_add(_gf_sqr(lam), lam), _A)
|
||||
# y3 = x1^2 + (lambda + 1) * x3
|
||||
y3 = _gf_add(_gf_sqr(x1), _gf_mul(_gf_add(lam, 1), x3))
|
||||
return (x3, y3)
|
||||
|
||||
|
||||
def _ec_mul(k: int, p: tuple[int, int] | None) -> tuple[int, int] | None:
|
||||
"""Scalar multiplication k*P using double-and-add."""
|
||||
if k == 0 or p is _INF:
|
||||
return _INF
|
||||
|
||||
result = _INF
|
||||
addend: tuple[int, int] | None = p
|
||||
while k:
|
||||
if k & 1:
|
||||
result = _ec_add(result, addend)
|
||||
addend = _ec_double(addend)
|
||||
k >>= 1
|
||||
return result
|
||||
|
||||
|
||||
# ECDSA-SHA256 verification
|
||||
|
||||
|
||||
def _modinv(a: int, m: int) -> int:
|
||||
"""Modular inverse of a modulo m (integers, not GF(2^m))."""
|
||||
if a < 0:
|
||||
a = a % m
|
||||
g, x, _ = _extended_gcd(a, m)
|
||||
if g != 1:
|
||||
raise ValueError("modular inverse does not exist")
|
||||
return x % m
|
||||
|
||||
|
||||
def _extended_gcd(a: int, b: int) -> tuple[int, int, int]:
|
||||
"""Extended Euclidean algorithm for integers."""
|
||||
if a == 0:
|
||||
return b, 0, 1
|
||||
g, x, y = _extended_gcd(b % a, a)
|
||||
return g, y - (b // a) * x, x
|
||||
|
||||
|
||||
def ecdsa_verify_sha256(
|
||||
message: bytes,
|
||||
signature_rs: bytes,
|
||||
public_key_xy: bytes,
|
||||
) -> bool:
|
||||
"""Verify ECDSA-SHA256 signature on sect233r1.
|
||||
|
||||
Args:
|
||||
message: The data that was signed.
|
||||
signature_rs: 60 bytes (r || s, each 30 bytes big-endian).
|
||||
public_key_xy: 60 bytes (x || y, each 30 bytes big-endian).
|
||||
|
||||
Returns:
|
||||
True if the signature is valid.
|
||||
"""
|
||||
if len(signature_rs) != 60:
|
||||
return False
|
||||
if len(public_key_xy) != 60:
|
||||
return False
|
||||
|
||||
r = int.from_bytes(signature_rs[:30], "big")
|
||||
s = int.from_bytes(signature_rs[30:], "big")
|
||||
|
||||
qx = int.from_bytes(public_key_xy[:30], "big")
|
||||
qy = int.from_bytes(public_key_xy[30:], "big")
|
||||
q_point = (qx, qy)
|
||||
|
||||
# Check r, s in [1, n-1]
|
||||
if not (1 <= r < _N and 1 <= s < _N):
|
||||
return False
|
||||
|
||||
h = hashlib.sha256(message).digest()
|
||||
e = int.from_bytes(h, "big")
|
||||
# Truncate to bit length of n
|
||||
if _N_BITLEN < 256:
|
||||
e >>= 256 - _N_BITLEN
|
||||
|
||||
# w = s^(-1) mod n
|
||||
w = _modinv(s, _N)
|
||||
|
||||
# u1 = e*w mod n, u2 = r*w mod n
|
||||
u1 = (e * w) % _N
|
||||
u2 = (r * w) % _N
|
||||
|
||||
# R = u1*G + u2*Q
|
||||
g_point = (_Gx, _Gy)
|
||||
r_point = _ec_add(_ec_mul(u1, g_point), _ec_mul(u2, q_point))
|
||||
|
||||
if r_point is _INF:
|
||||
return False
|
||||
|
||||
# v = R.x (as integer, already in GF(2^m) which is an integer)
|
||||
v = r_point[0] % _N
|
||||
|
||||
return v == r
|
||||
@@ -0,0 +1,381 @@
|
||||
"""Reading archives that may be hostile.
|
||||
|
||||
Every limit here bounds what a crafted archive can cost without
|
||||
capping a real romset: the largest pack is already several gigabytes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import functools
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
|
||||
from core.artifacts import process_umask, set_plain_mode
|
||||
from core.hashing import md5sum
|
||||
from core.paths import REPO_ROOT
|
||||
|
||||
|
||||
def check_inside_zip(container: str, file_name: str, expected_md5: str) -> str:
|
||||
"""Check a ROM inside a ZIP, as Batocera's checkInsideZip() does.
|
||||
|
||||
Returns "ok", "untested", "not_in_zip", or "error".
|
||||
"""
|
||||
try:
|
||||
info = os.stat(container)
|
||||
except OSError:
|
||||
return "error"
|
||||
found = _member_md5(
|
||||
container, info.st_size, info.st_mtime_ns, file_name.casefold(),
|
||||
expected_md5 != "",
|
||||
)
|
||||
if found in ("not_in_zip", "error"):
|
||||
return found
|
||||
if expected_md5 == "":
|
||||
return "ok"
|
||||
return "ok" if found == expected_md5 else "untested"
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=8192)
|
||||
def _member_md5(
|
||||
container: str, size: int, mtime_ns: int, folded: str, hashed: bool
|
||||
) -> str:
|
||||
"""The md5 of the member named `folded` (case-folded), or why there is none.
|
||||
|
||||
One archive member is asked about by every md5 a platform accepts for it
|
||||
and by every step that checks it: `verify --all` decompressed 355
|
||||
members 4 788 times. Keyed by the archive's size and mtime, so a
|
||||
rewritten archive is read again.
|
||||
"""
|
||||
try:
|
||||
with zipfile.ZipFile(container) as archive:
|
||||
for fname in archive.namelist():
|
||||
if fname.casefold() != folded:
|
||||
continue
|
||||
if archive.getinfo(fname).file_size > 512 * 1024 * 1024:
|
||||
return "error"
|
||||
if not hashed:
|
||||
return "present"
|
||||
with archive.open(fname) as entry:
|
||||
return md5sum(entry)
|
||||
return "not_in_zip"
|
||||
except (zipfile.BadZipFile, OSError, KeyError):
|
||||
return "error"
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=4096)
|
||||
def _member_crcs(path: str, mtime: float) -> frozenset[str]:
|
||||
try:
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
return frozenset(
|
||||
format(info.CRC, "08x") for info in archive.infolist() if not info.is_dir()
|
||||
)
|
||||
except (zipfile.BadZipFile, OSError):
|
||||
return frozenset()
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=4096)
|
||||
def _member_names(path: str, mtime: float) -> frozenset[str]:
|
||||
try:
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
return frozenset(
|
||||
info.filename.rsplit("/", 1)[-1].casefold()
|
||||
for info in archive.infolist() if not info.is_dir()
|
||||
)
|
||||
except (zipfile.BadZipFile, OSError):
|
||||
return frozenset()
|
||||
|
||||
|
||||
def zip_member_names(path: str) -> frozenset[str]:
|
||||
"""Casefolded base name of each member, read from the central directory."""
|
||||
try:
|
||||
mtime = os.path.getmtime(path)
|
||||
except OSError:
|
||||
return frozenset()
|
||||
return _member_names(path, mtime)
|
||||
|
||||
|
||||
def zip_member_crcs(path: str) -> frozenset[str]:
|
||||
"""CRC-32 of each member, read from the central directory."""
|
||||
try:
|
||||
mtime = os.path.getmtime(path)
|
||||
except OSError:
|
||||
return frozenset()
|
||||
return _member_crcs(path, mtime)
|
||||
|
||||
|
||||
_zip_contents_cache: tuple[tuple, dict] | None = None
|
||||
|
||||
# Member md5s per archive, keyed by the archive's sha1: content addressed, so
|
||||
# a cached answer is never stale. Every pipeline step that resolves a
|
||||
# zipped_file used to decompress the 54 845 members again, about 23 s each.
|
||||
MEMBER_CACHE = os.path.join(
|
||||
REPO_ROOT, ".cache", "zip_member_md5.json"
|
||||
)
|
||||
|
||||
|
||||
# No caller asks for a member above this bound, the index's default.
|
||||
MAX_HASHED_MEMBER = 512 * 1024 * 1024
|
||||
|
||||
|
||||
def _read_member_cache(path: str) -> dict[str, list[list]]:
|
||||
import json
|
||||
|
||||
try:
|
||||
with open(path, encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except (OSError, ValueError) as exc:
|
||||
print(f"warning: ignoring unreadable {path}: {exc}", file=sys.stderr)
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _write_member_cache(path: str, data: dict[str, list[list]]) -> None:
|
||||
import json
|
||||
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
fd, scratch = tempfile.mkstemp(dir=os.path.dirname(path), suffix=".tmp")
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
||||
json.dump(data, fh, separators=(",", ":"))
|
||||
set_plain_mode(scratch)
|
||||
os.replace(scratch, path)
|
||||
except OSError as exc:
|
||||
print(f"warning: could not write {path}: {exc}", file=sys.stderr)
|
||||
if os.path.exists(scratch):
|
||||
os.unlink(scratch)
|
||||
|
||||
|
||||
def _members_md5(path: str) -> list[list] | None:
|
||||
"""[md5, size] of each member, or None for an archive that cannot be read."""
|
||||
members: list[list] = []
|
||||
try:
|
||||
with zipfile.ZipFile(path, "r") as zf:
|
||||
for info in zf.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
if info.file_size > MAX_HASHED_MEMBER:
|
||||
members.append([None, info.file_size])
|
||||
continue
|
||||
h = hashlib.md5()
|
||||
with zf.open(info.filename) as inner:
|
||||
for chunk in iter(lambda: inner.read(65536), b""):
|
||||
h.update(chunk)
|
||||
members.append([h.hexdigest(), info.file_size])
|
||||
except (zipfile.BadZipFile, OSError) as exc:
|
||||
print(f"warning: unreadable archive {path}: {exc}", file=sys.stderr)
|
||||
return None
|
||||
return members
|
||||
|
||||
|
||||
def build_zip_contents_index(
|
||||
db: dict,
|
||||
max_entry_size: int = 512 * 1024 * 1024,
|
||||
cache_path: str | None = MEMBER_CACHE,
|
||||
) -> dict:
|
||||
"""Build {inner_rom_md5: zip_file_sha1} for ROMs inside ZIP files.
|
||||
|
||||
Cached in-process, and on disk per archive sha1 when cache_path is set.
|
||||
"""
|
||||
global _zip_contents_cache
|
||||
|
||||
zip_entries: list[tuple[str, str]] = []
|
||||
for sha1, entry in db.get("files", {}).items():
|
||||
path = entry["path"]
|
||||
if path.endswith(".zip") and os.path.exists(path):
|
||||
zip_entries.append((path, sha1))
|
||||
|
||||
# The bound and the sha1 each path carries are part of the answer: a
|
||||
# second call with a smaller bound got members the first one admitted,
|
||||
# and a regenerated database got the sha1 of the old one.
|
||||
fingerprint = (
|
||||
max_entry_size,
|
||||
frozenset((path, os.path.getmtime(path), sha1) for path, sha1 in zip_entries),
|
||||
)
|
||||
if _zip_contents_cache is not None and _zip_contents_cache[0] == fingerprint:
|
||||
return _zip_contents_cache[1]
|
||||
|
||||
cached = _read_member_cache(cache_path) if cache_path else {}
|
||||
added = False
|
||||
index: dict[str, str] = {}
|
||||
for path, sha1 in zip_entries:
|
||||
members = cached.get(sha1)
|
||||
if members is None:
|
||||
members = _members_md5(path)
|
||||
if members is None:
|
||||
continue
|
||||
cached[sha1] = members
|
||||
added = True
|
||||
for md5, size in members:
|
||||
if md5 is not None and size <= max_entry_size:
|
||||
index[md5] = sha1
|
||||
if added and cache_path:
|
||||
_write_member_cache(cache_path, cached)
|
||||
|
||||
_zip_contents_cache = (fingerprint, index)
|
||||
return index
|
||||
|
||||
|
||||
MAX_ZIP_MEMBERS = 100_000
|
||||
|
||||
MAX_ZIP_MEMBER_SIZE = 8 * 1024 * 1024 * 1024
|
||||
|
||||
# The largest generated pack is already ~5 GB uncompressed and the collection
|
||||
# only grows. This bounds a malicious archive without capping a real one.
|
||||
MAX_ZIP_TOTAL_SIZE = 64 * 1024 * 1024 * 1024
|
||||
|
||||
# DEFLATE cannot exceed roughly 1,032:1, so this rejects a declared ratio no
|
||||
# real DEFLATE member can reach. Methods with a higher ceiling (bzip2, LZMA)
|
||||
# are exempt and bounded by the per-member and per-archive size limits alone.
|
||||
MAX_ZIP_COMPRESSION_RATIO = 1_100
|
||||
_BOUNDED_RATIO_METHODS = (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _ZipLimits:
|
||||
"""The resource bounds safe_extract_zip enforces."""
|
||||
|
||||
members: int
|
||||
member_size: int
|
||||
total_size: int
|
||||
compression_ratio: int
|
||||
|
||||
|
||||
def _member_path(member: zipfile.ZipInfo, seen: set[str]) -> tuple[str, list[str], int]:
|
||||
"""(name, path components, mode) of a member whose path and type are safe."""
|
||||
# Archives written on Windows store a backslash separator. It is a
|
||||
# separator, not a filename character, so it is normalized before
|
||||
# the component checks rather than rejected.
|
||||
name = member.filename.replace("\\", "/")
|
||||
if not name or "\x00" in name:
|
||||
raise ValueError(f"Unsafe ZIP member name: {member.filename!r}")
|
||||
if name.startswith("/") or re.match(r"^[A-Za-z]:", name):
|
||||
raise ValueError(f"Absolute ZIP member path: {name}")
|
||||
parts = [part for part in name.split("/") if part]
|
||||
if any(part in (".", "..") for part in parts):
|
||||
raise ValueError(f"ZIP traversal detected: {name}")
|
||||
normalized = "/".join(parts)
|
||||
if normalized in seen:
|
||||
raise ValueError(f"Duplicate ZIP member path: {name}")
|
||||
seen.add(normalized)
|
||||
|
||||
mode = (member.external_attr >> 16) & 0xFFFF
|
||||
file_type = stat.S_IFMT(mode)
|
||||
if file_type not in (0, stat.S_IFREG, stat.S_IFDIR):
|
||||
raise ValueError(f"ZIP link or special file rejected: {name}")
|
||||
if member.flag_bits & 0x1:
|
||||
raise ValueError(f"Encrypted ZIP member rejected: {name}")
|
||||
return name, parts, mode
|
||||
|
||||
|
||||
def _check_member_size(
|
||||
member: zipfile.ZipInfo, name: str, declared_total: int, limits: _ZipLimits,
|
||||
) -> int:
|
||||
"""The declared total with this member, after its size limits are checked."""
|
||||
if member.file_size > limits.member_size:
|
||||
raise ValueError(
|
||||
f"ZIP member {name} is {member.file_size} bytes; "
|
||||
f"limit is {limits.member_size}"
|
||||
)
|
||||
declared_total += member.file_size
|
||||
if declared_total > limits.total_size:
|
||||
raise ValueError(
|
||||
f"ZIP expands to {declared_total} bytes, limit is {limits.total_size}"
|
||||
)
|
||||
if member.file_size and member.compress_type in _BOUNDED_RATIO_METHODS:
|
||||
if member.compress_size == 0:
|
||||
raise ValueError(f"Invalid compression size for ZIP member: {name}")
|
||||
if member.file_size / member.compress_size > limits.compression_ratio:
|
||||
raise ValueError(f"Suspicious compression ratio for ZIP member: {name}")
|
||||
return declared_total
|
||||
|
||||
|
||||
def _install_member(
|
||||
zf: zipfile.ZipFile,
|
||||
member: zipfile.ZipInfo,
|
||||
name: str,
|
||||
target: str,
|
||||
mode: int,
|
||||
umask: int,
|
||||
max_member_size: int,
|
||||
) -> None:
|
||||
"""Stream a member to a temporary sibling, check it, then move it in place."""
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
tmp_path = ""
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="wb", dir=os.path.dirname(target), delete=False
|
||||
) as tmp_file:
|
||||
tmp_path = tmp_file.name
|
||||
actual_size = 0
|
||||
with zf.open(member, "r") as source:
|
||||
while True:
|
||||
chunk = source.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
actual_size += len(chunk)
|
||||
if actual_size > member.file_size or actual_size > max_member_size:
|
||||
raise ValueError(
|
||||
f"ZIP member exceeded declared or configured size: {name}"
|
||||
)
|
||||
tmp_file.write(chunk)
|
||||
if actual_size != member.file_size:
|
||||
raise ValueError(
|
||||
f"ZIP member size mismatch for {name}: "
|
||||
f"{actual_size} != {member.file_size}"
|
||||
)
|
||||
# The member's own mode, else what a plain open() gives. The
|
||||
# temporary file is private and would keep 0600 otherwise.
|
||||
os.chmod(tmp_path, ((mode & 0o777) or 0o666) & ~umask)
|
||||
os.replace(tmp_path, target)
|
||||
tmp_path = ""
|
||||
finally:
|
||||
if tmp_path and os.path.exists(tmp_path):
|
||||
os.unlink(tmp_path)
|
||||
|
||||
|
||||
def safe_extract_zip(
|
||||
zip_path: str,
|
||||
dest_dir: str,
|
||||
*,
|
||||
max_members: int = MAX_ZIP_MEMBERS,
|
||||
max_member_size: int = MAX_ZIP_MEMBER_SIZE,
|
||||
max_total_size: int = MAX_ZIP_TOTAL_SIZE,
|
||||
max_compression_ratio: int = MAX_ZIP_COMPRESSION_RATIO,
|
||||
) -> None:
|
||||
"""Extract a ZIP with traversal, link and resource-limit protection.
|
||||
|
||||
Files are streamed to a temporary sibling and atomically installed only
|
||||
after their declared length and CRC have been checked by ``zipfile``.
|
||||
"""
|
||||
limits = _ZipLimits(max_members, max_member_size, max_total_size, max_compression_ratio)
|
||||
dest = os.path.realpath(dest_dir)
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
umask = process_umask()
|
||||
with zipfile.ZipFile(zip_path, "r") as zf:
|
||||
members = zf.infolist()
|
||||
if len(members) > limits.members:
|
||||
raise ValueError(
|
||||
f"ZIP has {len(members)} members, limit is {limits.members}"
|
||||
)
|
||||
|
||||
declared_total = 0
|
||||
seen: set[str] = set()
|
||||
for member in members:
|
||||
name, parts, mode = _member_path(member, seen)
|
||||
declared_total = _check_member_size(member, name, declared_total, limits)
|
||||
|
||||
target = os.path.realpath(os.path.join(dest, *parts))
|
||||
if not target.startswith(dest + os.sep) and target != dest:
|
||||
raise ValueError(f"ZIP traversal detected: {name}")
|
||||
if member.is_dir() or name.endswith("/"):
|
||||
os.makedirs(target, exist_ok=True)
|
||||
continue
|
||||
_install_member(zf, member, name, target, mode, umask, limits.member_size)
|
||||
Reference in new issue
Block a user