IC Improve Code Recipes

Recipe 10.4 · Python

Zip and Unzip Without Surprises

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Zip files arrive from partners and users, and go out as bundles of reports. Creating them is easy. Extracting them is where the risk is. An entry named ../../web.config writes outside the target folder; this is the "Zip Slip" bug. A small archive that expands to tens of gigabytes, a zip bomb, fills the disk. And old code loads entire entries into memory to copy them.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Path.Combine with an entry name of ..\..\app.config points outside target, and nothing limits how much is written.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Extract every zip entry by joining its name onto the target folder (p215_r10_4_unchecked_zip_extract_before.py)
"""Extract every zip entry by joining its name onto the target folder

Source: ImproveCode, Chapter 10, Recipe 10.4 "Zip and Unzip Without Surprises"
Section: The way it's often written
Book page: 215  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
ZipFile.OpenRead -> zipfile.ZipFile; ExtractToFile(overwrite) -> manual copy.
Vulnerable to zip-slip ("../") and zip bombs.
"""

import os
import shutil
import zipfile


def extract(zip_path: str, target: str) -> None:
    with zipfile.ZipFile(zip_path) as archive:
        for entry in archive.infolist():
            dest = os.path.join(target, entry.filename)
            with archive.open(entry) as src, open(dest, "wb") as out:
                shutil.copyfileobj(src, out)

The improved recipe

Creation streams each file into its entry. Extraction resolves every entry through SafePath.Combine from Recipe 10.1, enforces limits on entry count, total size and compression ratio, and counts the bytes actually written rather than trusting the sizes in the archive's headers.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Create zips and extract them safely with entry, size and ratio limits (p215_r10_4_safe_zip_create_and_extract.py)
"""Create zips and extract them safely with entry, size and ratio limits

Source: ImproveCode, Chapter 10, Recipe 10.4 "Zip and Unzip Without Surprises"
Section: The improved recipe
Book page: 215-217  -- original C# listing
Converted from C# to Python.
System.IO.Compression -> zipfile; InvalidDataException -> ValueError subclass;
SafePath.Combine comes from p205. Async CopyToAsync -> synchronous copy inside
an async function (zipfile is blocking).
"""

from __future__ import annotations

import os
import shutil
import zipfile
from collections.abc import Iterable
from dataclasses import dataclass
from typing import BinaryIO

from p205_r10_1_safe_path_combine_and_filename import combine


class InvalidDataError(ValueError):
    """Equivalent of System.IO.InvalidDataException."""


@dataclass(frozen=True)
class ZipLimits:
    max_entries: int = 10_000
    max_total_bytes: int = 1 * 1024 * 1024 * 1024
    max_compression_ratio: int = 100


async def create_async(
    destination: BinaryIO,
    files: Iterable[tuple[str, str]],
) -> None:
    if destination is None or files is None:
        raise ValueError("destination and files are required")
    # The caller owns `destination` (leaveOpen: true).
    with zipfile.ZipFile(destination, "w",
                         compression=zipfile.ZIP_DEFLATED,
                         compresslevel=9) as archive:
        for entry_name, file_path in files:
            with open(file_path, "rb") as src, \
                    archive.open(entry_name.replace("\\", "/"), "w") as out:
                shutil.copyfileobj(src, out)


def extract_safely(
    zip_path: str, destination_folder: str, limits: ZipLimits | None = None
) -> list[str]:
    limits = limits or ZipLimits()
    with zipfile.ZipFile(zip_path) as archive:
        entries = archive.infolist()
        if len(entries) > limits.max_entries:
            raise InvalidDataError("Too many entries in archive.")

        os.makedirs(destination_folder, exist_ok=True)
        written: list[str] = []
        remaining = limits.max_total_bytes

        for entry in entries:
            target = combine(destination_folder, entry.filename)
            if entry.filename.endswith("/"):
                os.makedirs(target, exist_ok=True)
                continue
            if (entry.compress_size > 0 and entry.file_size
                    // entry.compress_size > limits.max_compression_ratio):
                raise InvalidDataError(
                    f"Suspicious compression ratio: {entry.filename}")

            os.makedirs(os.path.dirname(target), exist_ok=True)
            with archive.open(entry) as src, open(target, "xb") as out:
                remaining -= _copy_with_limit(src, out, remaining)
            written.append(target)
        return written


def _copy_with_limit(input: BinaryIO, output: BinaryIO, limit: int) -> int:
    total = 0
    while chunk := input.read(81920):
        total += len(chunk)
        if total > limit:
            raise InvalidDataError("Archive expands beyond the allowed size.")
        output.write(chunk)
    return total

How it works

CreateAsync writes to any stream: a file, a MemoryStream for an e-mail attachment, or an HTTP response body. Each entry is opened, the source file is copied into it, and the entry is closed before the next one starts, so memory use stays flat however many files you add. Entry names use forward slashes, which is what the zip format specifies; backslashes produce archives that look broken on macOS and Linux.

ExtractSafely checks three things before writing. Every entry path goes through SafePath.Combine, which throws for .., absolute paths and invalid names, so Zip Slip is impossible. The entry count is capped, because a million empty entries is a denial-of-service attack of its own. And entries whose declared compression ratio exceeds 100 to 1 are refused; ordinary documents compress 2 to 10 times, text logs perhaps 20.

Declared sizes come from the archive and can lie, so CopyWithLimit counts the bytes really written and stops when the total for the whole archive passes the limit. FileMode.CreateNew refuses to overwrite files, which also catches archives that contain the same name twice.

Variations and pitfalls

  • ZipFile.ExtractToDirectory in modern .NET rejects entries that would land outside the destination, but it has no size limits. It is fine for archives you created yourself. Use the limited version for anything from outside.
  • Partial extraction. If extraction throws halfway, some files exist. Extract into a fresh temp folder (Recipe 10.7) and move it into place only after success.