Content · Programming · Python

Python Detect Archive Bombs and Excessive File Counts

Inspect archive entry count and total expanded size before extraction.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Inspect archive entry count and total expanded size before extraction.

How It Works


Decompression bombs exploit the gap between small compressed bytes and enormous expanded output. Count members, sum declared sizes and reject archives outside a documented budget. Declared sizes may be false, so enforce limits again while writing decompressed bytes.

Include limits for path length, recursion, elapsed time and disk space in a production extractor.

Step-by-Step Example


import io
import zipfile

memory = io.BytesIO()
with zipfile.ZipFile(memory, "w", compression=zipfile.ZIP_DEFLATED) as archive:
    archive.writestr("log.txt", "X" * 3000)
with zipfile.ZipFile(io.BytesIO(memory.getvalue())) as archive:
    members = archive.infolist()
    expanded_bytes = sum(member.file_size for member in members)
    print(len(members), expanded_bytes)
    print(expanded_bytes <= 10_000)

Understanding the Example


  • The expression 'io.BytesIO()' supplies the value stored as 'memory'. 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:

1 3000
True

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


Reduce the maximum allowed bytes to 1000 and verify the archive is rejected.

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


  • Checking the number of entries but not their cumulative or per-file expanded sizes.
  • Treating declared metadata limits as a complete defence against malformed compressed streams.

Key Takeaways


  • Inspect archive entry count and total expanded size before extraction.
  • Decompression bombs exploit the gap between small compressed bytes and enormous expanded output.
  • Include limits for path length, recursion, elapsed time and disk space in a production extractor.
Share this resourceSend this page to someone who may find it useful.