Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

gh-163190: Do not decompress a zipfile member past its file_size in read() - #163191

Open
hyeonsang010716 wants to merge 1 commit into
python:mainfrom
hyeonsang010716:gh-163190-zipfile-read-past-file-size
Open

hyeonsang010716 wants to merge 1 commit into
python:mainfrom
hyeonsang010716:gh-163190-zipfile-read-past-file-size

Conversation

@hyeonsang010716

Copy link
Copy Markdown

ZipExtFile.read() without a size calls _read1(self.MAX_N), and _read1() passed that on to the decompressor as max_length before cutting the result to self._left. A member whose central directory entry states a smaller file_size than its data expands to was decompressed whole, up to 2 GiB per call, to return those few bytes. The script in the issue reads 100 bytes from a 510 KB archive and peaks at 697 MiB.

_read1() now asks the decompressor for no more than the member still has to give, max(min(n, self._left), self.MIN_READ_SIZE), for deflate and for bzip2, LZMA and Zstandard alike. What read() and read1() return is the same, and the CRC is checked over the same bytes. With the change the script peaks at 1 MiB.

The test states a file_size of 100 for a 4 MiB member and checks, for each compression method, that read() and read1(-1) return those 100 bytes and that no decompress() call returned more than MIN_READ_SIZE. It fails without the change for the four compressed methods.

Reading a 200 MiB member whole takes the same time before and after (deflate 25 ms, bzip2 330 ms, LZMA 133 ms here). test_zipfile, test_zipimport, test_zipapp, test_shutil and test_importlib pass.

@efanntyo

efanntyo commented Dec 5, 2026

Copy link
Copy Markdown

One additional regression case could combine a partial first read with CRC failure. The current test corrects the CRC to the truncated prefix, which is useful for isolating the allocation bound; keeping a wrong-CRC variant would also protect the existing failure behavior.

I used a bounded 64 KiB deflate member, set the declared size to 5,000, then called read(100) followed by read(). On Python 3.12.16/Linux, the installed control returned decompressor chunks of [4096, 61440]; substituting the exact _read1 method from 0b5168a produced [4096, 4096]. With the prefix CRC, both returned 100 + 4,900 bytes then EOF. With CRC set to zero, both raised BadZipFile on the second read. This checks the remaining-size cap after an earlier read, rather than only the initial read(-1) path.

This was an isolated method-substitution probe for deflate on the installed interpreter, not a full PR build, other-codec test or memory benchmark. AI-assisted analysis; the bounded probe and both CRC controls were executed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants