mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-22 17:47:48 -06:00
feat: find a file stored inside others by crc32
A ROM an emulator embeds sits at an undocumented offset of its executable, installer or archive. find_embedded tries every offset with a rolling crc32 (a 29 MB executable in about 3 seconds), reads ZIP members and walks folders. A hit stays a candidate until --sha1 confirms it, and --extract writes only a confirmed one, to tmp/acquire/.
This commit is contained in:
1 parent
fa0f6bc798
commit
fb33ee58e1
2 files changed
+203
No files matched your search
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Find a file stored inside other files, by its crc32 and size.
|
||||
|
||||
Usage:
|
||||
python scripts/find_embedded.py --crc32 c23d280e --size 2048 WinUAE.exe
|
||||
python scripts/find_embedded.py --crc32 c23d280e --size 2048 --sha1 b5c4b8c3... dumps/
|
||||
python scripts/find_embedded.py --crc32 ... --size ... --extract emulator.zip
|
||||
|
||||
A ROM an emulator embeds sits somewhere in its executable, an installer or
|
||||
an archive, at an offset nobody documents: DCMOTO carried the MO6 images
|
||||
under UPX, and a sliding search was the only way to see them. Every offset
|
||||
of every file is tried with a rolling crc32, so a 30 MB executable takes
|
||||
seconds rather than one crc per offset. ZIP members are read too, a folder
|
||||
is walked. A hit is only a candidate until --sha1 confirms it: crc32 alone
|
||||
can be met by chance in a large file. --extract writes a confirmed hit to
|
||||
tmp/acquire/<sha1>, never into bios/.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import sys
|
||||
import zipfile
|
||||
import zlib
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
ACQUIRE_DIR = Path("tmp") / "acquire"
|
||||
_POLY = 0xEDB88320
|
||||
_TABLE = []
|
||||
for _byte in range(256):
|
||||
_value = _byte
|
||||
for _ in range(8):
|
||||
_value = (_value >> 1) ^ _POLY if _value & 1 else _value >> 1
|
||||
_TABLE.append(_value)
|
||||
|
||||
|
||||
def _raw(data: bytes) -> int:
|
||||
"""The crc32 register over data, from 0 and without the final xor: a
|
||||
linear function, which is what lets the window roll."""
|
||||
register = 0
|
||||
for byte in data:
|
||||
register = (register >> 8) ^ _TABLE[(register ^ byte) & 0xFF]
|
||||
return register
|
||||
|
||||
|
||||
def offsets(data: bytes, crc32: int, size: int) -> list[int]:
|
||||
"""Every offset where data[offset:offset + size] has this zlib crc32."""
|
||||
if size <= 0 or len(data) < size:
|
||||
return []
|
||||
# zlib's crc32 of a window is the linear register xor a constant that
|
||||
# depends on the length alone: the crc32 of as many zero bytes.
|
||||
target = crc32 ^ zlib.crc32(bytes(size))
|
||||
leaving = [_raw(bytes([byte]) + bytes(size)) for byte in range(256)]
|
||||
table = _TABLE
|
||||
register = _raw(data[:size])
|
||||
found = [0] if register == target else []
|
||||
for start in range(len(data) - size):
|
||||
register = ((register >> 8) ^ table[(register ^ data[start + size]) & 0xFF]
|
||||
^ leaving[data[start]])
|
||||
if register == target:
|
||||
found.append(start + 1)
|
||||
return found
|
||||
|
||||
|
||||
def sources(paths: list[Path]) -> Iterator[tuple[str, bytes]]:
|
||||
"""(label, bytes) of each file under paths, and of each ZIP member."""
|
||||
for path in paths:
|
||||
files = sorted(p for p in path.rglob("*") if p.is_file()) if path.is_dir() else [path]
|
||||
for file in files:
|
||||
try:
|
||||
data = file.read_bytes()
|
||||
except OSError as exc:
|
||||
print(f" {file}: not read ({exc.strerror or exc})", file=sys.stderr)
|
||||
continue
|
||||
yield str(file), data
|
||||
if zipfile.is_zipfile(file):
|
||||
try:
|
||||
with zipfile.ZipFile(file) as archive:
|
||||
for info in archive.infolist():
|
||||
if not info.is_dir():
|
||||
yield f"{file}!{info.filename}", archive.read(info)
|
||||
except (zipfile.BadZipFile, OSError, RuntimeError, NotImplementedError) as exc:
|
||||
print(f" {file}: members not read ({exc})", file=sys.stderr)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__.split("\n\n", 1)[0])
|
||||
parser.add_argument("paths", nargs="+", type=Path, help="files, folders or ZIPs to search")
|
||||
parser.add_argument("--crc32", required=True, help="crc32 of the wanted file, in hex")
|
||||
parser.add_argument("--size", required=True, type=int, help="size of the wanted file, in bytes")
|
||||
parser.add_argument("--sha1", help="sha1 that confirms a hit")
|
||||
parser.add_argument("--extract", action="store_true",
|
||||
help="write each confirmed hit to tmp/acquire/<sha1> (needs --sha1)")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
crc32 = int(args.crc32, 16)
|
||||
except ValueError:
|
||||
parser.error(f"--crc32 takes a hex value, not {args.crc32!r}")
|
||||
if args.extract and not args.sha1:
|
||||
parser.error("--extract writes only a hit --sha1 confirms: give --sha1")
|
||||
wanted_sha1 = args.sha1.lower() if args.sha1 else None
|
||||
confirmed = candidates = 0
|
||||
for label, data in sources(args.paths):
|
||||
for offset in offsets(data, crc32, args.size):
|
||||
window = data[offset:offset + args.size]
|
||||
sha1 = hashlib.sha1(window).hexdigest()
|
||||
if wanted_sha1 and sha1 != wanted_sha1:
|
||||
print(f" {label} at {offset}: crc32 matches, sha1 {sha1} does not")
|
||||
candidates += 1
|
||||
continue
|
||||
confirmed += 1 if wanted_sha1 else 0
|
||||
candidates += 0 if wanted_sha1 else 1
|
||||
print(f" {label} at {offset}: sha1 {sha1}"
|
||||
+ (" (confirmed)" if wanted_sha1 else " (crc32 only, give --sha1)"))
|
||||
if args.extract:
|
||||
ACQUIRE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
out = ACQUIRE_DIR / sha1
|
||||
out.write_bytes(window)
|
||||
print(f" written to {out}")
|
||||
if not confirmed and not candidates:
|
||||
print("Not found.")
|
||||
return 0 if confirmed or (candidates and not wanted_sha1) else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,75 @@
|
||||
"""find_embedded.py finds a file stored inside others by a rolling crc32:
|
||||
the offset of every window that holds it, in a file or a ZIP member."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache
|
||||
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(REPO_ROOT / "scripts"))
|
||||
|
||||
import find_embedded # noqa: E402
|
||||
|
||||
ROM = bytes(random.Random(8039).randrange(256) for _ in range(2048))
|
||||
CRC = zlib.crc32(ROM)
|
||||
SHA1 = hashlib.sha1(ROM).hexdigest()
|
||||
|
||||
|
||||
class RollingWindow(unittest.TestCase):
|
||||
def test_every_offset_matches_a_direct_crc(self):
|
||||
noise = random.Random(1).randbytes(5000)
|
||||
data = noise[:777] + ROM + noise[777:3000] + ROM + noise[3000:]
|
||||
self.assertEqual(find_embedded.offsets(data, CRC, len(ROM)), [777, 777 + 2048 + 2223])
|
||||
|
||||
def test_the_file_itself_and_a_short_file(self):
|
||||
self.assertEqual(find_embedded.offsets(ROM, CRC, len(ROM)), [0])
|
||||
self.assertEqual(find_embedded.offsets(ROM[:100], CRC, len(ROM)), [])
|
||||
|
||||
|
||||
class Command(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.root = Path(tempfile.mkdtemp())
|
||||
self.cwd = os.getcwd()
|
||||
os.chdir(self.root)
|
||||
self.addCleanup(os.chdir, self.cwd)
|
||||
(self.root / "emu.exe").write_bytes(b"MZ" * 300 + ROM + b"\0" * 64)
|
||||
with zipfile.ZipFile(self.root / "pack.zip", "w") as archive:
|
||||
archive.writestr("data/blob.bin", b"x" * 10 + ROM)
|
||||
|
||||
def run_cli(self, *argv: str) -> tuple[int, str]:
|
||||
with mock.patch.object(sys, "argv", ["find_embedded.py", *argv]), \
|
||||
contextlib.redirect_stdout(io.StringIO()) as out:
|
||||
code = find_embedded.main()
|
||||
return code, out.getvalue()
|
||||
|
||||
def test_a_confirmed_hit_in_a_file_and_in_a_zip_member_is_extracted(self):
|
||||
code, out = self.run_cli(str(self.root), "--crc32", f"{CRC:08x}", "--size", "2048",
|
||||
"--sha1", SHA1, "--extract")
|
||||
self.assertEqual(code, 0, out)
|
||||
self.assertIn("emu.exe at 600: sha1", out)
|
||||
self.assertIn("pack.zip!data/blob.bin at 10", out)
|
||||
self.assertEqual((self.root / "tmp" / "acquire" / SHA1).read_bytes(), ROM)
|
||||
|
||||
def test_nothing_found_and_extract_without_sha1_are_refused(self):
|
||||
code, out = self.run_cli(str(self.root / "emu.exe"), "--crc32", "deadbeef",
|
||||
"--size", "2048")
|
||||
self.assertEqual((code, out.strip()), (1, "Not found."))
|
||||
with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
|
||||
self.run_cli(str(self.root), "--crc32", f"{CRC:08x}", "--size", "2048", "--extract")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user