diff --git a/tests/test_ped_catalogues.py b/tests/test_ped_catalogues.py index 638cd8bbd..710d039ec 100644 --- a/tests/test_ped_catalogues.py +++ b/tests/test_ped_catalogues.py @@ -7,6 +7,7 @@ no real asset names, and no retail hashes are used. """ from __future__ import annotations +import io import json import os import struct @@ -14,6 +15,7 @@ import subprocess import sys import tempfile import unittest +from unittest import mock import zlib ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -800,5 +802,235 @@ class PedCataloguesTests(unittest.TestCase): self.assertEqual(rep["presets"], 5) +class PedCataloguesHardeningTests(unittest.TestCase): + """Regression tests for filter handling, BOM/UTF-8 safety, traversal guards, depth cap, bounds, and atomic JSON.""" + + @staticmethod + def _cli(*args: str) -> subprocess.CompletedProcess: + return subprocess.run( + [sys.executable, "-I", os.path.join(TOOLS, "ped_catalogues.py"), *args], + capture_output=True, + text=True, + timeout=60, + ) + + def test_empty_names_file_and_blank_name_keep_filtering_active(self): + blocks, _ = build_rich_catalogue_blocks() + raw = build_synthetic_0drp(blocks) + with tempfile.TemporaryDirectory() as tmp: + cat_file = os.path.join(tmp, "sample.0drp") + with open(cat_file, "wb") as fh: + fh.write(raw) + + empty_names = os.path.join(tmp, "empty_names.txt") + with open(empty_names, "w", encoding="utf-8", newline="\n") as fh: + fh.write("# comment only\n \n\n") + + r1 = self._cli("resolve", cat_file, "--names-file", empty_names, "--json") + self.assertEqual(r1.returncode, 0, r1.stderr) + self.assertEqual(json.loads(r1.stdout)["matches"], 0) + + r2 = self._cli("resolve", cat_file, "--name", " ", "--json") + self.assertEqual(r2.returncode, 0, r2.stderr) + self.assertEqual(json.loads(r2.stdout)["matches"], 0) + + def test_utf8_bom_and_invalid_utf8_in_names_file_and_carved_index(self): + blocks, _ = build_rich_catalogue_blocks() + raw = build_synthetic_0drp(blocks) + split = len(raw) // 2 + with tempfile.TemporaryDirectory() as tmp: + cat_file = os.path.join(tmp, "sample.0drp") + with open(cat_file, "wb") as fh: + fh.write(raw) + + # UTF-8 BOM on line 1 of --names-file must still match the first name + bom_names = os.path.join(tmp, "bom_names.txt") + with open(bom_names, "wb") as fh: + fh.write(b"\xef\xbb\xbfsynth_body_full_03\n") + r_bom = self._cli("resolve", cat_file, "--names-file", bom_names, "--json") + self.assertEqual(r_bom.returncode, 0, r_bom.stderr) + doc_bom = json.loads(r_bom.stdout) + self.assertEqual(doc_bom["matches"], 1) + self.assertEqual(doc_bom["bindings"][0]["matched_name"], "synth_body_full_03") + + # Invalid UTF-8 in --names-file exits cleanly with code 2 (no traceback) + bad_names = os.path.join(tmp, "bad_names.txt") + with open(bad_names, "wb") as fh: + fh.write(b"\xff\xfeinvalid") + r_bad = self._cli("resolve", cat_file, "--names-file", bad_names) + self.assertEqual(r_bad.returncode, 2) + self.assertNotIn("Traceback", r_bad.stderr) + self.assertIn("ERROR:", r_bad.stderr) + + # Carved index.json with UTF-8 BOM joins continuation streams cleanly + bom_dir = os.path.join(tmp, "bom_carve") + os.makedirs(bom_dir) + with open(os.path.join(bom_dir, "000000000100.bin"), "wb") as fh: + fh.write(raw[:split]) + with open(os.path.join(bom_dir, "000000000300.bin"), "wb") as fh: + fh.write(raw[split:]) + idx_payload = json.dumps({ + "files": [ + {"offset": 0x100, "stored": 0x1F5, "file": "000000000100.bin"}, + {"offset": 0x300, "stored": 0x200, "file": "000000000300.bin"}, + ] + }).encode("utf-8") + with open(os.path.join(bom_dir, "index.json"), "wb") as fh: + fh.write(b"\xef\xbb\xbf" + idx_payload) + self.assertEqual(len(list(pc.iter_catalogues_in_dir(bom_dir))), 1) + + # Invalid UTF-8 index.json falls back to directory walk without crashing + bad_idx_dir = os.path.join(tmp, "bad_idx") + os.makedirs(bad_idx_dir) + with open(os.path.join(bad_idx_dir, "index.json"), "wb") as fh: + fh.write(b"\xff\xfe{not utf8}") + with open(os.path.join(bad_idx_dir, "good.0drp"), "wb") as fh: + fh.write(raw) + self.assertEqual(len(list(pc.iter_catalogues_in_dir(bad_idx_dir))), 1) + + def test_carved_index_blocks_path_traversal(self): + blocks, _ = build_rich_catalogue_blocks() + raw = build_synthetic_0drp(blocks) + split = len(raw) // 2 + with tempfile.TemporaryDirectory() as tmp: + outside = os.path.join(tmp, "outside.0drp") + with open(outside, "wb") as fh: + fh.write(raw) + outside_part1 = os.path.join(tmp, "outside_part1.bin") + with open(outside_part1, "wb") as fh: + fh.write(raw[split:]) + + carve_dir = os.path.join(tmp, "carved") + os.makedirs(carve_dir) + with open(os.path.join(carve_dir, "part0.bin"), "wb") as fh: + fh.write(raw[:split]) + with open(os.path.join(carve_dir, "index.json"), "w", encoding="utf-8", newline="\n") as fh: + json.dump( + { + "files": [ + {"offset": 0x100, "stored": 0x100, "file": "../outside.0drp"}, + {"offset": 0x400, "stored": 0x1F5, "file": "part0.bin"}, + {"offset": 0x600, "stored": 0x200, "file": "../outside_part1.bin"}, + ] + }, + fh, + ) + self.assertEqual(list(pc.iter_catalogues_in_dir(carve_dir)), []) + + def test_exact_max_parent_depth_chain_does_not_warn_and_max_depth_validation(self): + # Clean chain of exactly MAX_PARENT_DEPTH hops (last ancestor has parent_id=0): no cap warning. + exact_presets = bytearray() + for idx in range(pc.MAX_PARENT_DEPTH + 1): + pid = 0x1000 + idx + parent_id = (0x1000 + idx + 1) if idx < pc.MAX_PARENT_DEPTH else 0 + exact_presets.extend(_pack_preset(preset_id=pid, parent_id=parent_id)) + exact_blocks = [ + (pc.CATALOG_ROOT_HASH, _pack_root(bucket0_count=pc.MAX_PARENT_DEPTH + 1, bucket0_ptr=_encode_ptr(2, 0))), + (pc.PRESET_STRUCT_HASH, bytes(exact_presets)), + ] + cat_exact = pc.parse_catalogue_strict(build_synthetic_0drp(exact_blocks), source="exact_depth.0drp") + self.assertEqual(cat_exact.stats["max_parent_depth"], pc.MAX_PARENT_DEPTH) + self.assertEqual(cat_exact.warnings, ()) + + # Chain of MAX_PARENT_DEPTH + 1 hops DOES trigger the cap warning. + over_presets = bytearray() + for idx in range(pc.MAX_PARENT_DEPTH + 2): + pid = 0x2000 + idx + parent_id = (0x2000 + idx + 1) if idx < pc.MAX_PARENT_DEPTH + 1 else 0 + over_presets.extend(_pack_preset(preset_id=pid, parent_id=parent_id)) + over_blocks = [ + (pc.CATALOG_ROOT_HASH, _pack_root(bucket0_count=pc.MAX_PARENT_DEPTH + 2, bucket0_ptr=_encode_ptr(2, 0))), + (pc.PRESET_STRUCT_HASH, bytes(over_presets)), + ] + cat_over = pc.parse_catalogue_strict(build_synthetic_0drp(over_blocks), source="over_depth.0drp") + self.assertTrue(any("reached cap" in w for w in cat_over.warnings)) + + # Invalid max_depth rejected cleanly + root_preset = cat_exact.presets[0] + for bad_depth in (-1, True): + with self.assertRaises(ValueError): + pc.resolve_ancestor_tags(cat_exact, root_preset, max_depth=bad_depth) + with self.assertRaises(ValueError): + pc.resolve_effective_tags(cat_exact, root_preset, max_depth=bad_depth) + with self.assertRaises(ValueError): + pc.resolve_preset_bindings(cat_exact, max_depth=bad_depth) + + def test_scan_bounds_and_inspect_max_inflate(self): + blocks, _ = build_rich_catalogue_blocks() + raw = build_synthetic_0drp(blocks) + rpf_bytes = build_synthetic_rpf([raw]) + with tempfile.TemporaryDirectory() as tmp: + cat_file = os.path.join(tmp, "sample.0drp") + zcat_file = os.path.join(tmp, "sample.0drp.z") + rpf_path = os.path.join(tmp, "sample.rpf") + with open(cat_file, "wb") as fh: + fh.write(raw) + with open(zcat_file, "wb") as fh: + fh.write(zlib.compress(raw, 6)) + with open(rpf_path, "wb") as fh: + fh.write(rpf_bytes) + + for kwargs in ( + {"limit": 0}, + {"limit": -4}, + {"limit": True}, + {"start": -1}, + {"start": True}, + {"max_inflate": 0}, + {"max_inflate": True}, + ): + with self.subTest(rpf_kwargs=kwargs): + with self.assertRaises(ValueError): + list(pc.iter_catalogues_in_rpf(rpf_path, **kwargs)) + + with self.assertRaises(ValueError): + list(pc.iter_catalogues_in_file(cat_file, max_inflate=0)) + with self.assertRaises(ValueError): + list(pc.iter_catalogues_in_dir(tmp, max_inflate=-1)) + + # inspect enforces --max-inflate on both raw and zlib-compressed inputs + r_raw = self._cli("inspect", cat_file, "--max-inflate", "64") + self.assertEqual(r_raw.returncode, 2) + self.assertIn("--max-inflate", r_raw.stderr) + + r_z = self._cli("inspect", zcat_file, "--max-inflate", str(len(raw) - 1)) + self.assertEqual(r_z.returncode, 2) + self.assertIn("--max-inflate", r_z.stderr) + + def test_atomic_write_json_rejects_nan_and_cli_handles_write_oserror(self): + blocks, _ = build_rich_catalogue_blocks() + raw = build_synthetic_0drp(blocks) + with tempfile.TemporaryDirectory() as tmp: + out_path = os.path.join(tmp, "out.json") + sentinel = '{"keep": true}\n' + with open(out_path, "w", encoding="utf-8", newline="\n") as fh: + fh.write(sentinel) + + with self.assertRaises(ValueError): + pc._write_json(out_path, {"bad": float("nan")}) + with open(out_path, encoding="utf-8") as fh: + self.assertEqual(fh.read(), sentinel) + self.assertEqual(os.listdir(tmp), ["out.json"]) + + cat_file = os.path.join(tmp, "sample.0drp") + with open(cat_file, "wb") as fh: + fh.write(raw) + + for argv in ( + ["census", cat_file, "--out", out_path], + ["inspect", cat_file, "--out", out_path], + ["resolve", cat_file, "--out", out_path], + ): + with self.subTest(argv=argv): + err_buf = io.StringIO() + with mock.patch.object(pc, "_write_json", side_effect=OSError("disk full")), mock.patch.object( + sys, "stderr", err_buf + ): + rc = pc.main(argv) + self.assertEqual(rc, 2) + self.assertIn("ERROR:", err_buf.getvalue()) + self.assertIn("disk full", err_buf.getvalue()) + + if __name__ == "__main__": unittest.main() diff --git a/tools/ped_catalogues.py b/tools/ped_catalogues.py index 0b65be43c..2adf21743 100644 --- a/tools/ped_catalogues.py +++ b/tools/ped_catalogues.py @@ -53,13 +53,16 @@ import os import re import struct import sys +import tempfile import zlib from typing import Iterable, Iterator # -I keeps the script directory off sys.path, so add it explicitly before importing sibling modules. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import file_mode # noqa: E402 import odrp_7a # noqa: E402 import psin_data # noqa: E402 +import replace_retry # noqa: E402 from report_paths import same_report_path, path_key # noqa: E402 import world_names # noqa: E402 @@ -641,10 +644,10 @@ def parse_catalogue_blocks( break seen.add(cur) depth += 1 - if depth >= MAX_PARENT_DEPTH: + cur = parent.parent_id + if cur and depth >= MAX_PARENT_DEPTH: warnings.append(f"parent_id chain depth reached cap ({MAX_PARENT_DEPTH}) at preset 0x{rec.preset_id:08x}") break - cur = parent.parent_id if depth > max_parent_depth: max_parent_depth = depth @@ -729,6 +732,12 @@ def parse_catalogue( # ---------------------------------------------------------------- inheritance & resolution +def _require_int_bound(value: object, name: str, *, minimum: int) -> int: + if type(value) is not int or value < minimum: + raise ValueError(f"{name} must be an integer >= {minimum}, got {value!r}") + return value + + def resolve_ancestor_tags( catalogue: CatalogueContainer, preset: PresetRecord, @@ -740,6 +749,7 @@ def resolve_ancestor_tags( Returns `(matched_tags_subset, parent_chain_traversed, hit_cycle)`. """ + _require_int_bound(max_depth, "max_depth", minimum=0) if not preset.parent_id: return {}, (), False visited = {preset.preset_id} @@ -767,6 +777,7 @@ def resolve_effective_tags( max_depth: int = MAX_PARENT_DEPTH, ) -> tuple[dict[int, tuple[int, ...]], tuple[int, ...], bool]: """Merge tags along the `parent_id` chain (child keys override ancestor keys) with cycle guard.""" + _require_int_bound(max_depth, "max_depth", minimum=0) visited = {preset.preset_id} ancestors: list[PresetRecord] = [preset] chain: list[int] = [] @@ -818,6 +829,7 @@ def resolve_preset_bindings( 4. Direct state drawable `h0` (`murmur64`). 5. Direct `cull_drawable` target (`murmur64`, when `h0 == 0` or matched by a `cull_drawable` query). """ + _require_int_bound(max_depth, "max_depth", minimum=0) j32_names: dict[int, list[str]] = collections.defaultdict(list) m64_names: dict[int, list[str]] = collections.defaultdict(list) want_32: set[int] = set(filter_hashes_32 or ()) @@ -1060,6 +1072,7 @@ def _try_parse_candidate( def iter_catalogues_in_file(path: str, *, max_inflate: int = MAX_INFLATE) -> Iterator[CatalogueContainer]: """Yield a `0x8dcb4cf5` catalogue if `path` contains one (raw `0DRP`/`PSIN` or single zlib stream).""" + _require_int_bound(max_inflate, "max_inflate", minimum=1) if os.path.getsize(path) > max_inflate: return with open(path, "rb") as fh: @@ -1084,12 +1097,13 @@ def _row_file_name(row: dict) -> str: def iter_catalogues_in_dir(path: str, *, max_inflate: int = MAX_INFLATE) -> Iterator[CatalogueContainer]: """Yield all `0x8dcb4cf5` catalogues in a carved directory (joining contiguous streams when `index.json` exists).""" + _require_int_bound(max_inflate, "max_inflate", minimum=1) manifest = os.path.join(path, "index.json") if os.path.isfile(manifest): try: - with open(manifest, encoding="utf-8") as fh: + with open(manifest, encoding="utf-8-sig") as fh: doc = json.load(fh) - except (OSError, json.JSONDecodeError): + except (OSError, UnicodeDecodeError, json.JSONDecodeError): doc = None if isinstance(doc, dict) and isinstance(doc.get("files"), list): rows = sorted( @@ -1101,7 +1115,7 @@ def iter_catalogues_in_dir(path: str, *, max_inflate: int = MAX_INFLATE) -> Iter row = rows[i] fname = _row_file_name(row) fpath = os.path.join(path, fname) - if not os.path.isfile(fpath) or os.path.getsize(fpath) > max_inflate: + if not _is_under_dir(fpath, path) or not os.path.isfile(fpath) or os.path.getsize(fpath) > max_inflate: i += 1 continue with open(fpath, "rb") as fh: @@ -1126,7 +1140,7 @@ def iter_catalogues_in_dir(path: str, *, max_inflate: int = MAX_INFLATE) -> Iter break nname = _row_file_name(rows[j + 1]) npath = os.path.join(path, nname) - if not os.path.isfile(npath): + if not _is_under_dir(npath, path) or not os.path.isfile(npath): break with open(npath, "rb") as fh: chunk = fh.read() @@ -1164,6 +1178,11 @@ def iter_catalogues_in_rpf( Uses a 96-byte zlib header peek to skip non-`PSIN`/non-`0DRP` streams without inflating them, and joins contiguous continuation streams automatically when a catalogue spans multiple zlib blocks. """ + _require_int_bound(max_inflate, "max_inflate", minimum=1) + if start is not None: + _require_int_bound(start, "start", minimum=0) + if limit is not None: + _require_int_bound(limit, "limit", minimum=1) file_size = os.path.getsize(path) if file_size == 0: raise ValueError("empty file") @@ -1380,9 +1399,31 @@ def _check_out_path(out_path: str, inputs: list[str]) -> str | None: def _write_json(path: str, payload: object) -> None: - with open(path, "w", encoding="utf-8", newline="\n") as fh: - json.dump(payload, fh, indent=1) - fh.write("\n") + text = json.dumps(payload, indent=1, allow_nan=False) + "\n" + abs_path = os.path.abspath(path) + parent = os.path.dirname(abs_path) or "." + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=parent, + prefix=f".{os.path.basename(abs_path)}.", + suffix=".tmp", + delete=False, + ) as fh: + tmp_path = fh.name + fh.write(text) + os.chmod(tmp_path, file_mode.published_mode(abs_path)) + replace_retry.replace(tmp_path, abs_path) + tmp_path = None + finally: + if tmp_path is not None: + try: + os.unlink(tmp_path) + except OSError: + pass def _cmd_census(args: argparse.Namespace) -> int: @@ -1403,7 +1444,11 @@ def _cmd_census(args: argparse.Namespace) -> int: print(f"ERROR: {args.source}: {exc}", file=sys.stderr) return 2 if args.out: - _write_json(args.out, report) + try: + _write_json(args.out, report) + except (OSError, ValueError) as exc: + print(f"ERROR: {args.out}: {exc}", file=sys.stderr) + return 2 if args.json: json.dump(report, sys.stdout, indent=1) sys.stdout.write("\n") @@ -1445,12 +1490,17 @@ def _cmd_inspect(args: argparse.Namespace) -> int: print(f"ERROR: {args.file}: no such file", file=sys.stderr) return 2 try: + max_inf = getattr(args, "max_inflate", MAX_INFLATE) + _require_int_bound(max_inf, "max_inflate", minimum=1) + if os.path.getsize(args.file) > max_inf: + raise ValueError(f"file size exceeds --max-inflate cap ({max_inf:,} bytes)") with open(args.file, "rb") as fh: data = fh.read() if len(data) >= 2 and data[0] == 0x78 and data[1] in (0x01, 0x5E, 0x9C, 0xDA): - inflated = _inflate_at(data, 0, len(data), MAX_INFLATE) - if inflated is not None: - data = inflated[0] + inflated = _inflate_at(data, 0, len(data), max_inf) + if inflated is None: + raise ValueError(f"zlib inflate failed or exceeded --max-inflate ({max_inf:,} bytes)") + data = inflated[0] cat = parse_catalogue_strict(data, source=args.file) except (OSError, ValueError) as exc: print(f"ERROR: {args.file}: {exc}", file=sys.stderr) @@ -1460,7 +1510,11 @@ def _cmd_inspect(args: argparse.Namespace) -> int: if args.limit > 0: payload["presets"] = [p.to_dict() for p in cat.presets[:args.limit]] if args.out: - _write_json(args.out, payload) + try: + _write_json(args.out, payload) + except (OSError, ValueError) as exc: + print(f"ERROR: {args.out}: {exc}", file=sys.stderr) + return 2 if args.json: json.dump(payload, sys.stdout, indent=1) sys.stdout.write("\n") @@ -1503,14 +1557,15 @@ def _cmd_resolve(args: argparse.Namespace) -> int: names: list[str] = list(args.name or ()) if args.names_file: try: - with open(args.names_file, encoding="utf-8") as fh: + with open(args.names_file, encoding="utf-8-sig") as fh: for line in fh: s = line.strip() if s and not s.startswith("#"): names.append(s) - except OSError as exc: + except (OSError, UnicodeDecodeError) as exc: print(f"ERROR: {args.names_file}: {exc}", file=sys.stderr) return 2 + has_name_filter = bool(args.name) or args.names_file is not None h32: set[int] = set() h64: set[int] = set() @@ -1533,7 +1588,7 @@ def _cmd_resolve(args: argparse.Namespace) -> int: bindings.extend( resolve_preset_bindings( cat, - drawable_names=names if names else None, + drawable_names=names if has_name_filter else None, filter_hashes_32=h32 or None, filter_hashes_64=h64 or None, require_textures=args.require_textures, @@ -1551,7 +1606,11 @@ def _cmd_resolve(args: argparse.Namespace) -> int: "bindings": [b.to_dict() for b in bindings], } if args.out: - _write_json(args.out, payload) + try: + _write_json(args.out, payload) + except (OSError, ValueError) as exc: + print(f"ERROR: {args.out}: {exc}", file=sys.stderr) + return 2 if args.json: json.dump(payload, sys.stdout, indent=1) sys.stdout.write("\n") @@ -1590,6 +1649,7 @@ def build_parser() -> argparse.ArgumentParser: p_ins.add_argument("--json", action="store_true", help="print inspection result as JSON") p_ins.add_argument("--out", help="write JSON result to FILE") p_ins.add_argument("--limit", type=_nonneg_int, default=10, help="number of presets to include (default 10, 0 for summary)") + p_ins.add_argument("--max-inflate", type=_pos_int, default=MAX_INFLATE, help="inflate/file size cap in bytes (default 64 MiB)") p_ins.set_defaults(func=_cmd_inspect) p_res = sub.add_parser("resolve", help="resolve preset inheritance, textures, and cull_drawable swaps")