Treat archive extraction as a potentially destructive filesystem operation.
How It Works
An archive may contain unexpected paths, huge decompressed data or links that redirect writes. For unfamiliar ZIP and TAR files, inspect entry names and resource sizes and extract into a fresh restricted directory. TAR data filters help but do not guarantee safety against all attacks.
Checking names ahead of time cannot eliminate symlink races when an attacker can alter the destination during extraction.
Step-by-Step Example
import io
import zipfile
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as archive:
archive.writestr("docs/readme.txt", "example")
with zipfile.ZipFile(io.BytesIO(buffer.getvalue())) as archive:
entries = archive.infolist()
print([(item.filename, item.file_size) for item in entries])
Understanding the Example
- The expression 'io.BytesIO()' supplies the value stored as 'buffer'. This value is then used or checked by the later statements.
- The with block manages the opened resource and closes it when the block finishes, including when an exception occurs.
A successful run of this example prints the following output:
[('docs/readme.txt', 7)]
Where This Fits in a Real Program
A practical archive workflow has separate decisions for selection, compression, extraction and verification. When files come from other people, inspect paths, member counts and uncompressed sizes before writing anything; a successful decompression does not establish that its contents are trustworthy.
Practice: Try It Yourself
Design a checklist that rejects absolute names, traversal components, excessive counts and oversize entries.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Extracting unknown archives directly into the same directory as important application files.
- Checking compressed file size but ignoring total uncompressed bytes and the number of entries.
Key Takeaways
- Treat archive extraction as a potentially destructive filesystem operation.
- An archive may contain unexpected paths, huge decompressed data or links that redirect writes.
- Checking names ahead of time cannot eliminate symlink races when an attacker can alter the destination during extraction.