mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-24 02:27:52 -06:00
fix: check zip member paths with core.ziptools
The data directory refresh dropped any name containing .. in silence, wrote a backslash as a filename character and let a drive letter or a backslash traversal through. The pack integrity check flagged Read..me as a traversal. Both now use safe_member_parts, and an unsafe member fails the refresh of its key instead of thinning the tree.
This commit is contained in:
1 parent
79e5eae036
commit
8bc497cf15
5 files changed
+62
-25
No files matched your search
+16
-10
@@ -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(
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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)), ())
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
Reference in new issue
Block a user