From 357153eaa360ad2b5714c1ff35a1d2dd9727cc80 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:45:02 +0100 Subject: [PATCH] fix: bound data directory zip extraction The refresh fetched, filtered and extracted in one function and copied ZIP members with no size, ratio or duplicate path check. Extraction now lives in packs/datadirextract.py as local functions, the ZIP side on safe_extract_zip, which gains a member select hook and returns the file count. Tests read the member rules on local archives. --- .github/workflows/deploy-site.yml | 1 + scripts/core/ziptools.py | 32 +++++++-- scripts/packs/datadirextract.py | 81 +++++++++++++++++++++ scripts/packs/datadirs.py | 114 ++++++------------------------ tests/sources.py | 6 +- tests/test_refresh_data_dirs.py | 106 ++++++++++++++++++++++----- 6 files changed, 222 insertions(+), 118 deletions(-) create mode 100644 scripts/packs/datadirextract.py diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml index fdc2c2531..1f5fb163f 100644 --- a/.github/workflows/deploy-site.yml +++ b/.github/workflows/deploy-site.yml @@ -76,6 +76,7 @@ on: - "scripts/packs/archive.py" - "scripts/packs/coverage.py" - "scripts/packs/crossref.py" + - "scripts/packs/datadirextract.py" - "scripts/packs/datadirs.py" - "scripts/packs/extras.py" - "scripts/packs/gaps.py" diff --git a/scripts/core/ziptools.py b/scripts/core/ziptools.py index ef1636cba..d323d0634 100644 --- a/scripts/core/ziptools.py +++ b/scripts/core/ziptools.py @@ -5,6 +5,7 @@ capping a real romset: the largest pack is already several gigabytes.""" from __future__ import annotations +from collections.abc import Callable from dataclasses import dataclass import functools @@ -304,9 +305,23 @@ def safe_member_parts(member: zipfile.ZipInfo) -> list[str]: 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.""" +MemberSelect = Callable[[zipfile.ZipInfo, list[str]], "list[str] | None"] +"""Maps a member's safe path components to the components it is written +under, or to None to leave the member out.""" + + +def _member_path( + member: zipfile.ZipInfo, seen: set[str], select: MemberSelect | None = None, +) -> tuple[str, list[str], int] | None: + """(name, path components, mode) of a member whose path and type are + safe, None when select leaves it out. Two members written to one path + refuse the archive.""" parts = safe_member_parts(member) + if select is not None: + chosen = select(member, parts) + if chosen is None: + return None + parts = chosen name = member.filename.replace("\\", "/") normalized = "/".join(parts) if normalized in seen: @@ -389,11 +404,14 @@ def safe_extract_zip( 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: + select: MemberSelect | None = None, +) -> int: """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``. + select renames or leaves out members, and the limits apply to what it + keeps. Returns the number of files written. """ limits = _ZipLimits(max_members, max_member_size, max_total_size, max_compression_ratio) dest = os.path.realpath(dest_dir) @@ -407,9 +425,13 @@ def safe_extract_zip( ) declared_total = 0 + written = 0 seen: set[str] = set() for member in members: - name, parts, mode = _member_path(member, seen) + path = _member_path(member, seen, select) + if path is None: + continue + name, parts, mode = path declared_total = _check_member_size(member, name, declared_total, limits) target = os.path.realpath(os.path.join(dest, *parts)) @@ -419,3 +441,5 @@ def safe_extract_zip( os.makedirs(target, exist_ok=True) continue _install_member(zf, member, name, target, mode, umask, limits.member_size) + written += 1 + return written diff --git a/scripts/packs/datadirextract.py b/scripts/packs/datadirextract.py new file mode 100644 index 000000000..110971726 --- /dev/null +++ b/scripts/packs/datadirextract.py @@ -0,0 +1,81 @@ +"""Extraction of a downloaded data directory archive into a local tree.""" + +from __future__ import annotations + +import os +import shutil +import tarfile +import zipfile +from pathlib import Path + +from core.ziptools import safe_extract_zip + + +def _is_safe_tar_member(member: tarfile.TarInfo, dest: Path) -> bool: + """Reject path traversal, absolute paths, and symlinks in tar members.""" + if member.issym() or member.islnk(): + return False + if member.name.startswith("/") or ".." in member.name.split("/"): + return False + resolved = (dest / member.name).resolve() + dest_str = str(dest.resolve()) + os.sep + return str(resolved).startswith(dest_str) or str(resolved) == str(dest.resolve()) + + +def extract_tar_subtree( + archive_path: Path, extract_dir: Path, source_path: str, exclude: list[str], +) -> tuple[int, list[str]]: + """Write the files under source_path of a gzipped tarball to extract_dir, + paths relative to source_path, top directories in exclude left out. + + Returns the number of files written and the unsafe members skipped. + """ + prefix = source_path.rstrip("/") + "/" + file_count = 0 + skipped: list[str] = [] + with tarfile.open(archive_path, "r:gz") as tf: + for member in tf.getmembers(): + if not member.name.startswith(prefix) and member.name != source_path: + continue + rel = member.name[len(prefix) :] + if not rel or rel.split("/")[0] in exclude: + continue + if not _is_safe_tar_member(member, extract_dir): + skipped.append(member.name) + continue + if member.isdir(): + (extract_dir / rel).mkdir(parents=True, exist_ok=True) + elif member.isfile(): + dest_file = extract_dir / rel + dest_file.parent.mkdir(parents=True, exist_ok=True) + src = tf.extractfile(member) + if src is None: + continue + with src, open(dest_file, "wb") as dst: + shutil.copyfileobj(src, dst) + file_count += 1 + return file_count, skipped + + +def extract_zip_tree( + archive_path: Path, extract_dir: Path, exclude: list[str], strip_components: int = 0, +) -> int: + """Write the files of a ZIP to extract_dir under core.ziptools' limits. + + strip_components removes N leading path components from each entry + (like tar --strip-components), then top directories in exclude are left + out. Returns the number of files written. + """ + + def select(info: zipfile.ZipInfo, parts: list[str]) -> list[str] | None: + if info.is_dir(): + return None + if strip_components > 0: + if len(parts) <= strip_components: + return None + parts = parts[strip_components:] + if (parts[0] if parts else "") in exclude: + return None + return parts + + return safe_extract_zip(str(archive_path), str(extract_dir), select=select) diff --git a/scripts/packs/datadirs.py b/scripts/packs/datadirs.py index 892586440..0ff78411b 100644 --- a/scripts/packs/datadirs.py +++ b/scripts/packs/datadirs.py @@ -7,7 +7,6 @@ import http.client import json import logging import os -import shutil import tarfile import tempfile import time @@ -19,8 +18,8 @@ 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 +from packs.datadirextract import extract_tar_subtree, extract_zip_tree log = logging.getLogger(__name__) @@ -199,17 +198,6 @@ class NothingExtractedError(Exception): """ -def _is_safe_tar_member(member: tarfile.TarInfo, dest: Path) -> bool: - """Reject path traversal, absolute paths, and symlinks in tar members.""" - if member.issym() or member.islnk(): - return False - if member.name.startswith("/") or ".." in member.name.split("/"): - return False - resolved = (dest / member.name).resolve() - dest_str = str(dest.resolve()) + os.sep - return str(resolved).startswith(dest_str) or str(resolved) == str(dest.resolve()) - - def _download_and_extract( source_url: str, source_path: str, @@ -222,62 +210,20 @@ def _download_and_extract( Returns the number of files extracted. measured receives the size of the archive downloaded. """ - exclude = exclude or [] cache_dir = Path(local_cache) with _staging_dir(cache_dir) as tmpdir: tarball_path = Path(tmpdir) / "archive.tar.gz" - log.info("downloading %s", source_url) - - upstream.download( - source_url, tarball_path, timeout=DOWNLOAD_TIMEOUT, user_agent=USER_AGENT - ) - if measured is not None: - measured(tarball_path.stat().st_size) + _fetch(source_url, tarball_path, measured) log.info("extracting %s -> %s", source_path, local_cache) - - prefix = source_path.rstrip("/") + "/" - file_count = 0 - - with tarfile.open(tarball_path, "r:gz") as tf: - extract_dir = Path(tmpdir) / "extract" - extract_dir.mkdir() - - for member in tf.getmembers(): - if not member.name.startswith(prefix) and member.name != source_path: - continue - - rel = member.name[len(prefix) :] - if not rel: - continue - - # skip excluded subdirectories - top_component = rel.split("/")[0] - if top_component in exclude: - continue - - if not _is_safe_tar_member(member, extract_dir): - log.warning("skipping unsafe tar member: %s", member.name) - continue - - # rewrite member name to relative path - member_copy = tarfile.TarInfo(name=rel) - member_copy.size = member.size - member_copy.mode = member.mode - member_copy.type = member.type - - if member.isdir(): - (extract_dir / rel).mkdir(parents=True, exist_ok=True) - elif member.isfile(): - dest_file = extract_dir / rel - dest_file.parent.mkdir(parents=True, exist_ok=True) - src = tf.extractfile(member) - if src is None: - continue - with src, open(dest_file, "wb") as dst: - shutil.copyfileobj(src, dst) - file_count += 1 + extract_dir = Path(tmpdir) / "extract" + extract_dir.mkdir() + file_count, skipped = extract_tar_subtree( + tarball_path, extract_dir, source_path, exclude or [] + ) + for name in skipped: + log.warning("skipping unsafe tar member: %s", name) if not file_count: raise NothingExtractedError(f"no file under {source_path} in the archive") @@ -299,43 +245,15 @@ def _download_and_extract_zip( (like tar --strip-components). Useful when a ZIP has a single root directory that should be flattened. """ - exclude = exclude or [] cache_dir = Path(local_cache) with _staging_dir(cache_dir) as tmpdir: zip_path = Path(tmpdir) / "archive.zip" - log.info("downloading %s", source_url) - - upstream.download( - source_url, zip_path, timeout=DOWNLOAD_TIMEOUT, user_agent=USER_AGENT - ) - if measured is not None: - measured(zip_path.stat().st_size) + _fetch(source_url, zip_path, measured) extract_dir = Path(tmpdir) / "extract" extract_dir.mkdir() - file_count = 0 - - with zipfile.ZipFile(zip_path) as zf: - for info in zf.infolist(): - if info.is_dir(): - continue - parts = safe_member_parts(info) - # strip leading path components - if strip_components > 0: - if len(parts) <= strip_components: - continue - parts = parts[strip_components:] - name = "/".join(parts) - # skip excludes (check against stripped path) - top = parts[0] if parts else "" - if top in exclude: - continue - dest = extract_dir / name - dest.parent.mkdir(parents=True, exist_ok=True) - with zf.open(info) as src, open(dest, "wb") as dst: - shutil.copyfileobj(src, dst) - file_count += 1 + file_count = extract_zip_tree(zip_path, extract_dir, exclude or [], strip_components) if not file_count: raise NothingExtractedError("the archive holds no file to extract") @@ -347,6 +265,16 @@ def _download_and_extract_zip( return file_count +def _fetch(source_url: str, archive_path: Path, measured: Callable[[int], None] | None) -> None: + """Download source_url to archive_path, its size handed to measured.""" + log.info("downloading %s", source_url) + upstream.download( + source_url, archive_path, timeout=DOWNLOAD_TIMEOUT, user_agent=USER_AGENT + ) + if measured is not None: + measured(archive_path.stat().st_size) + + def _measure_archive(source_url: str) -> int | None: """The size of the archive at source_url, read by streaming it: a tarball GitHub builds on request is sent without a Content-Length.""" diff --git a/tests/sources.py b/tests/sources.py index 322c8cd0c..a7dcd579f 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -41,7 +41,7 @@ COMMANDS = { "resolve/review.py", "resolve/reviewfiles.py", "resolve/reviewreport.py", "core/gitclone.py", ), - "refresh_data_dirs.py": ("packs/datadirs.py",), + "refresh_data_dirs.py": ("packs/datadirs.py", "packs/datadirextract.py"), "split_pack.py": ("packs/parts.py", "release/sums.py"), "retired_files.py": ("model/retired.py", "collection/retiredhistory.py"), "region_audit.py": ("resolve/regionaudit.py",), @@ -64,7 +64,9 @@ COMMANDS = { "generate_installer_doc.py": ("installer_build/installerdoc.py",), "commit_rules.py": ("devtools/commitrules.py",), "pr_checks.py": ("devtools/prchecks.py",), - "check_buildbot_system.py": ("scraper/buildbot_system.py", "packs/datadirs.py"), + "check_buildbot_system.py": ( + "scraper/buildbot_system.py", "packs/datadirs.py", "packs/datadirextract.py", + ), "generate_site.py": ( "sitegen/config.py", "sitegen/emulatorsindex.py", "sitegen/places.py", "sitegen/home.py", "sitegen/versions.py", "sitegen/guidepage.py", "sitegen/install.py", "sitegen/getpages.py", diff --git a/tests/test_refresh_data_dirs.py b/tests/test_refresh_data_dirs.py index d75b7b5d2..273acf8dc 100644 --- a/tests/test_refresh_data_dirs.py +++ b/tests/test_refresh_data_dirs.py @@ -13,6 +13,8 @@ import tests import io import json +import shutil +import tarfile import tempfile import threading import unittest @@ -23,6 +25,7 @@ from unittest import mock from packs import datadirs from model.registry import load_data_dir_registry, load_versions from packs.archive import Placed +from packs.datadirextract import extract_tar_subtree, extract_zip_tree from packs.datatrees import data_directory_members REPO_ROOT = Path(__file__).resolve().parents[1] @@ -61,7 +64,7 @@ class RefreshConcurrency(unittest.TestCase): with mock.patch.object( datadirs.urllib.request, "urlopen", lambda *a, **k: _Response(payload) ), mock.patch.object( - datadirs.shutil, "move", side_effect=AssertionError("copy across filesystems") + shutil, "move", side_effect=AssertionError("copy across filesystems") ): count = datadirs._download_and_extract_zip("https://x/pak.zip", str(self.cache)) self.assertEqual(count, 1) @@ -69,24 +72,11 @@ 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)) + def test_a_refused_archive_leaves_no_cache(self): + archive = self.root / "pak.zip" + archive.write_bytes(_zip_bytes({"a.bin": b"a", "..\\escape.bin": b"x"})) + with self.assertRaises(ValueError): + datadirs._download_and_extract_zip(archive.as_uri(), str(self.cache)) self.assertFalse(self.cache.exists()) def test_refresh_holds_the_directory_lock(self): @@ -478,6 +468,84 @@ class TheRemoteCommitComesFromTheForgeClient(unittest.TestCase): self.assertEqual(sha, "c" * 40) write.assert_not_called() +class ArchiveExtraction(unittest.TestCase): + """The member rules, read on a local archive with no download.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.out = self.root / "extract" + self.out.mkdir() + + def _zip(self, files: dict[str, bytes], method: int = zipfile.ZIP_STORED) -> Path: + path = self.root / "archive.zip" + with zipfile.ZipFile(path, "w", method) as zf: + for name, data in files.items(): + zf.writestr(name, data) + return path + + 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.""" + archive = self._zip({"Docs/Read..me.txt": b"r", "sub\\a.bin": b"a"}) + self.assertEqual(extract_zip_tree(archive, self.out, []), 2) + self.assertEqual((self.out / "Docs" / "Read..me.txt").read_bytes(), b"r") + self.assertEqual((self.out / "sub" / "a.bin").read_bytes(), b"a") + + def test_a_traversing_member_refuses_the_archive(self): + archive = self._zip({"a.bin": b"a", "..\\escape.bin": b"x"}) + with self.assertRaises(ValueError): + extract_zip_tree(archive, self.out, []) + + def test_two_members_on_one_path_refuse_the_archive(self): + """`a/x` and `a\\x` are one file once the separator is read: the + second overwrote the first in silence.""" + archive = self._zip({"a/x": b"1", "a\\x": b"2"}) + with self.assertRaisesRegex(ValueError, "Duplicate"): + extract_zip_tree(archive, self.out, []) + + def test_stripping_onto_one_path_refuses_the_archive(self): + archive = self._zip({"r1/a.bin": b"1", "r2/a.bin": b"2"}) + with self.assertRaisesRegex(ValueError, "Duplicate"): + extract_zip_tree(archive, self.out, [], strip_components=1) + + def test_a_member_larger_than_declared_refuses_the_archive(self): + """A header that announces 10 bytes for a member that expands to + more was copied to the end with no bound, and left a partial file.""" + archive = self._zip({"bomb.bin": b"x" * 100}) + data = bytearray(archive.read_bytes()) + local = data.index(b"PK\x03\x04") + central = data.index(b"PK\x01\x02") + data[local + 22:local + 26] = (10).to_bytes(4, "little") + data[central + 24:central + 28] = (10).to_bytes(4, "little") + archive.write_bytes(bytes(data)) + with self.assertRaises((ValueError, zipfile.BadZipFile)): + extract_zip_tree(archive, self.out, []) + self.assertEqual(list(self.out.iterdir()), []) + + def test_strip_and_exclude(self): + archive = self._zip({ + "root/a.bin": b"a", "root/skip/b.bin": b"b", "root/": b"", "top.bin": b"t", + }) + self.assertEqual(extract_zip_tree(archive, self.out, ["skip"], strip_components=1), 1) + self.assertEqual(sorted(p.name for p in self.out.rglob("*")), ["a.bin"]) + + def test_tar_subtree_relative_to_its_path(self): + archive = self.root / "archive.tar.gz" + payload = self.root / "f" + payload.write_bytes(b"x") + with tarfile.open(archive, "w:gz") as tf: + for name in ("repo/Data/Sys/a.bin", "repo/Data/Sys/skip/b.bin", "repo/Other/c.bin"): + tf.add(payload, arcname=name) + link = tarfile.TarInfo("repo/Data/Sys/link") + link.type = tarfile.SYMTYPE + link.linkname = "/etc/passwd" + tf.addfile(link) + count, skipped = extract_tar_subtree(archive, self.out, "repo/Data/Sys", ["skip"]) + self.assertEqual((count, skipped), (1, ["repo/Data/Sys/link"])) + self.assertEqual((self.out / "a.bin").read_bytes(), b"x") + if __name__ == "__main__": unittest.main()