diff --git a/scripts/core/ziptools.py b/scripts/core/ziptools.py index 1b5dae489..db1d8a589 100644 --- a/scripts/core/ziptools.py +++ b/scripts/core/ziptools.py @@ -257,8 +257,9 @@ class _ZipLimits: 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.""" +def safe_member_parts(member: zipfile.ZipInfo) -> list[str]: + """Path components of a member whose path and type are safe to write + under a directory, ValueError otherwise.""" # 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. @@ -270,18 +271,23 @@ def _member_path(member: zipfile.ZipInfo, seen: set[str]) -> tuple[str, list[str 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) + file_type = stat.S_IFMT(member.external_attr >> 16) 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 + return parts + + +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.""" + parts = safe_member_parts(member) + name = member.filename.replace("\\", "/") + normalized = "/".join(parts) + if normalized in seen: + raise ValueError(f"Duplicate ZIP member path: {name}") + seen.add(normalized) + return name, parts, (member.external_attr >> 16) & 0xFFFF def _check_member_size( diff --git a/scripts/packs/datadirs.py b/scripts/packs/datadirs.py index d65711cb8..6fabab996 100644 --- a/scripts/packs/datadirs.py +++ b/scripts/packs/datadirs.py @@ -18,6 +18,7 @@ from pathlib import Path from core import upstream from core.artifacts import file_lock as _file_lock, write_text_atomic from core.upstream import remote_etag as _get_remote_etag +from core.ziptools import safe_member_parts from model.registry import VERSIONS_FILE, load_versions @@ -321,16 +322,13 @@ def _download_and_extract_zip( for info in zf.infolist(): if info.is_dir(): continue - name = info.filename - if ".." in name or name.startswith("/"): - continue + parts = safe_member_parts(info) # strip leading path components - parts = name.split("/") if strip_components > 0: if len(parts) <= strip_components: continue parts = parts[strip_components:] - name = "/".join(parts) + name = "/".join(parts) # skip excludes (check against stripped path) top = parts[0] if parts else "" if top in exclude: @@ -512,13 +510,14 @@ def _refresh_entry( source_url, source_path, local_cache, exclude, measured=archive_sizes.append ) - # An archive that reads but holds nothing under the path is the same on - # every try: only a failed or unreadable download is tried again. + # An archive that reads but holds nothing under the path, or a member + # core.ziptools refuses (ValueError), is the same on every try: only a + # failed or unreadable download is tried again. for attempt, wait in enumerate((*DOWNLOAD_RETRY_WAITS, None), start=1): try: file_count = fetch() break - except NothingExtractedError as exc: + except (NothingExtractedError, ValueError) as exc: log.warning("[%s] download failed: %s", key, exc) return None except _TRANSIENT as exc: diff --git a/scripts/packs/integrity.py b/scripts/packs/integrity.py index 1b67ad89f..52de843e1 100644 --- a/scripts/packs/integrity.py +++ b/scripts/packs/integrity.py @@ -13,6 +13,7 @@ from typing import TYPE_CHECKING, TypedDict from core.artifacts import build_timestamp from packs.paths import MEDIA_MARKER, has_path_conflict from core.ziptools import build_zip_contents_index +from core.ziptools import safe_member_parts from resolve.nativemode import digest_algorithm, platform_mode from resolve.validation import ( baseline_verdict, digest_verdict, inner_rom_check, inner_rom_data_check, @@ -510,13 +511,12 @@ def _structural_errors(zf: zipfile.ZipFile, zip_set: set) -> list[str]: dupes = sum(1 for c in Counter(zf.namelist()).values() if c > 1) if dupes: errors.append(f"{dupes} duplicate entries") - for n in zip_set: - if "//" in n: - errors.append(f"double slash: {n}") - if n.startswith("/"): - errors.append(f"absolute path: {n}") - if ".." in n: - errors.append(f"path traversal: {n}") + errors.extend(f"double slash: {n}" for n in zip_set if "//" in n) + for info in zf.infolist(): + try: + safe_member_parts(info) + except ValueError as exc: + errors.append(str(exc)) # Zero-byte check (exclude Dolphin GraphicMods markers) errors.extend( diff --git a/tests/test_pack_counts.py b/tests/test_pack_counts.py index 43554be71..c738b0228 100644 --- a/tests/test_pack_counts.py +++ b/tests/test_pack_counts.py @@ -355,6 +355,18 @@ class APackForAndroidHidesItsMedia(PackCountFixture): errors = packverify._structural_errors(archive, set(archive.namelist())) self.assertEqual(errors, ["zero-byte: empty.bin"]) + def test_the_integrity_check_reads_paths_like_core_ziptools(self): + """"Read..me" was reported as a traversal, a backslash one was not.""" + from packs import integrity as packverify + + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as archive: + archive.writestr("Docs/Read..me.txt", b"r") + archive.writestr("..\\escape.bin", b"x") + with zipfile.ZipFile(buffer) as archive: + errors = packverify._structural_errors(archive, set(archive.namelist())) + self.assertEqual(errors, ["ZIP traversal detected: ../escape.bin"]) + def test_a_platform_without_android_gets_none(self): self.assertEqual(datatrees.pack_markers("demo", None, str(self.platforms)), ()) diff --git a/tests/test_refresh_data_dirs.py b/tests/test_refresh_data_dirs.py index 610bb68b0..337ae23e2 100644 --- a/tests/test_refresh_data_dirs.py +++ b/tests/test_refresh_data_dirs.py @@ -69,6 +69,26 @@ class RefreshConcurrency(unittest.TestCase): leftovers = [p.name for p in self.cache.parent.iterdir() if p.name != "pak"] self.assertEqual(leftovers, []) + def test_members_follow_the_core_ziptools_rule(self): + """A name with ".." inside a segment was dropped in silence, and a + backslash member became a file named with the backslash.""" + payload = _zip_bytes({"Docs/Read..me.txt": b"r", "sub\\a.bin": b"a"}) + with mock.patch.object( + datadirs.urllib.request, "urlopen", lambda *a, **k: _Response(payload) + ): + count = datadirs._download_and_extract_zip("https://x/pak.zip", str(self.cache)) + self.assertEqual(count, 2) + self.assertEqual((self.cache / "Docs" / "Read..me.txt").read_bytes(), b"r") + self.assertEqual((self.cache / "sub" / "a.bin").read_bytes(), b"a") + + def test_a_traversing_member_refuses_the_archive(self): + payload = _zip_bytes({"a.bin": b"a", "..\\escape.bin": b"x"}) + with mock.patch.object( + datadirs.urllib.request, "urlopen", lambda *a, **k: _Response(payload) + ), self.assertRaises(ValueError): + datadirs._download_and_extract_zip("https://x/pak.zip", str(self.cache)) + self.assertFalse(self.cache.exists()) + def test_refresh_holds_the_directory_lock(self): import fcntl