A client's zip file can overwrite files on your machine
Checking each entry before extraction is only the first layer of defense: you also need resource limits and a patched version of Python.
In brief
- File names inside an archive can contain '..', absolute paths or symlinks that write outside the directory you chose.
- A 10 MB zip file can expand to 281 TB, so count real bytes as you extract.
- Always extract into a new temporary directory, check every entry, set limits and use a patched Python.
In a paper presented at the WOOT ’19 workshop, David Fifield built a 10 MB zip file that expands to 281 TB, a compression ratio of more than 28 million to one. No file is nested inside another: the entries in the zip overlap, and the zip format allows it.
That figure matters to FDEs because receiving client data is part of the job every week. Logs exported from legacy systems, document sets for a RAG pipeline, database dumps: they usually arrive as .zip or .tar.gz.
Most of them are harmless. But the extraction code runs on a laptop holding SSH keys, on a shared project server, and sometimes inside the client’s own environment.
If an archive overwrites a config file or fills the disk, you are the one who explains it to the client. The good news is that the defense is compact, and it can go into every ingest script this week.
How can an archive be dangerous?
The first attack has its own name. Snyk published Zip Slip on June 5, 2018, describing it as a critical, widespread archive extraction vulnerability that lets attackers write arbitrary files. The trick is simple: an entry name in the archive contains a directory traversal path such as ../../, and the extraction library simply joins that name onto the target directory.
The Python documentation for tarfile lists the variants: absolute paths, .. components, or symlinks that affect entries extracted after them. The symlink variant is the hardest to spot. The first entry creates a link pointing outside; the second writes a file “into” that link.
The second attack is the zip bomb from the opening. The third is one few people think about: overwriting existing files. The zipfile documentation states plainly that extracting the same archive twice overwrites files without asking. In a directory holding last week’s processed output, that means lost data.
How much do the defaults differ between tools?
This is where many good engineers still trip, because each tool protects a different part.
| Tool | Default | Watch out for |
|---|---|---|
unzip (command line) |
Strips ../ from file names |
-: disables this; -o overwrites without asking, which the man page itself calls dangerous; -n never overwrites |
Python zipfile.extract/extractall |
Strips .., leading / and drive letters |
Still overwrites existing files; the zipfile.Path class does not sanitize names |
Python tarfile |
data filter from 3.14 |
3.13 and earlier behave like fully_trusted; you must pass filter='data' yourself |
java.util.zip |
Does not check ../ |
Verify each entry’s path yourself |
Even filter='data' is not a complete shield. The Python documentation says outright that, even with this filter, tarfile is not suited to extracting untrusted files without prior inspection, and that the built-in filters do not prevent denial-of-service attacks.
In June 2025 Python disclosed several CVEs in tarfile, among them CVE-2025-4517, rated critical, which allows files to be written outside the extraction directory even when filter="data" is used.
The zip side has a similar story. A Python security advisory says zipfile in CPython 3.12.2, 3.11.8, 3.10.13, 3.9.18, 3.8.18 and earlier is affected by CVE-2024-0450, which leaves it open to zip bombs built from overlapping entries.
The fix makes zipfile reject archives with overlapping entries. The lesson: the Python version on the machine running the pipeline is part of your security layer.
An extraction function good enough for client projects
Android’s developer guidance boils the principle down to two sentences: before extracting each entry, verify that the target path is inside the destination directory, and make sure the destination directory is empty before you start.
The Python documentation adds three points: extract into a new temporary directory so existing links cannot be exploited and cleanup is easy on failure; limit the number of files and the total size; and apply disk, memory and CPU limits at the operating-system level.
Put together, the function for zip looks like this:
import shutil, tarfile, tempfile, zipfile
from pathlib import Path
MAX_FILES = 10_000
MAX_BYTES = 2 * 1024**3 # 2 GB, adjust to the client's real data
def safe_unzip(archive: str) -> Path:
dest = Path(tempfile.mkdtemp(prefix="customer-")).resolve() # new, empty directory
try:
total = 0
with zipfile.ZipFile(archive) as zf:
members = zf.infolist()
if len(members) > MAX_FILES:
raise ValueError("too many files")
for m in members:
target = (dest / m.filename).resolve()
if not target.is_relative_to(dest):
raise ValueError(f"path escapes target directory: {m.filename}")
if m.is_dir():
target.mkdir(parents=True, exist_ok=True)
continue
target.parent.mkdir(parents=True, exist_ok=True)
# "xb": fail if the file already exists, never overwrite
with zf.open(m) as src, open(target, "xb") as out:
while chunk := src.read(1 << 20):
total += len(chunk) # count real bytes, do not trust the header
if total > MAX_BYTES:
raise ValueError("size limit exceeded")
out.write(chunk)
return dest
except Exception:
shutil.rmtree(dest, ignore_errors=True)
raise
Every line has a reason. mkdtemp gives a brand-new directory, so there is no old link to exploit and no old file to overwrite. Calling resolve() and then is_relative_to catches both ../ and absolute paths, because in Python dest / "/etc/passwd" returns /etc/passwd itself. The "xb" open mode is a second net against overwriting.
Counting bytes is the most important defense against zip bombs. The size declared in a zip header is written by whoever created the file; the number of bytes you actually read does not lie. At a ratio of 28 million to one, reading in 1 MB chunks and stopping at 2 GB means losing a few seconds instead of the whole disk.
For tar, keep the same approach: walk each entry, check its path, and count real bytes instead of trusting the header.
def safe_untar(archive: str) -> Path:
dest = Path(tempfile.mkdtemp(prefix="customer-")).resolve() # new, empty directory
try:
total = 0
with tarfile.open(archive) as tf:
for i, m in enumerate(tf): # iterate lazily, do not list everything first
if i >= MAX_FILES:
raise ValueError("too many files")
target = (dest / m.name).resolve()
if not target.is_relative_to(dest):
raise ValueError(f"path escapes target directory: {m.name}")
if m.isdir():
target.mkdir(parents=True, exist_ok=True)
continue
if not m.isfile(): # symlinks, hardlinks, devices: reject them all
raise ValueError(f"entry type not allowed: {m.name}")
target.parent.mkdir(parents=True, exist_ok=True)
with tf.extractfile(m) as src, open(target, "xb") as out:
while chunk := src.read(1 << 20):
total += len(chunk) # count real bytes, do not trust the header
if total > MAX_BYTES:
raise ValueError("size limit exceeded")
out.write(chunk)
return dest
except Exception:
shutil.rmtree(dest, ignore_errors=True)
raise
This function is stricter than the data filter: it creates no links at all, so the symlink attack on later entries has nothing to hold on to. For client data destined for ingestion, you rarely need to keep links; if you do, that is the moment to inspect each archive carefully rather than loosen the code.
If you still have to call extractall somewhere, pass filter="data" explicitly even on 3.14, so the code behaves correctly on every machine, including a client’s machine running an older version. Then run the whole function in a container or process with disk and memory limits, as the Python documentation advises.
The mistakes seen most often in the field
One is typing unzip -o as a shortcut when a re-run script complains that files already exist. Another is reading an archive through zipfile.Path for convenience and then joining names into paths without checking, even though this class does not sanitize names.
Two more are harder to spot. The first is believing that filter='data' is enough, when CVE-2025-4517 shows it also needs patching. The second is copying extraction code wholesale from an old Java or Android project, where java.util.zip does not check ../ at all.
Turning this skill into an advantage
On a CV, a concrete line carries more weight than an adjective, for example: built an ingest step with path checks, size limits and resource isolation for client-supplied files.
In a design interview, when you sketch a pipeline that receives client data, stop at the extraction step unprompted and say where you unpack it, what you check and what limits you set. That shows you treat even the file names inside an archive as untrusted input.
The next time a client sends an archive, your first question should be “where do I extract it?”, before “what’s inside?”.
Was this article useful?
Thanks for the feedback!
8 sources
- snyk/zip-slip-vulnerability (GitHub)
- tarfile — Read and write tar archive files (Python docs)
- zipfile — Work with ZIP archives (Python docs)
- Zip Path Traversal (Android Developers)
- unzip(1) — Debian Manpages (bookworm)
- A better zip bomb (USENIX WOOT '19) · 2019-08
- Multiple CVEs (1 CRITICAL, 3 HIGH, 1 MODERATE) affecting the tarfile module · 2025-06-03
- [CVE-2024-0450] Quoted zip-bomb protection for zipfile · 2024-03-19