Skip to content

[3.10] gh-83245: Raise BadZipFile instead of ValueError when reading a corrupt ZIP file (GH-32291) #93140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Lib/test/test_zipfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -1736,6 +1736,17 @@ def test_empty_file_raises_BadZipFile(self):
fp.write("short file")
self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)

def test_negative_central_directory_offset_raises_BadZipFile(self):
# Zip file containing an empty EOCD record
buffer = bytearray(b'PK\x05\x06' + b'\0'*18)

# Set the size of the central directory bytes to become 1,
# causing the central directory offset to become negative
for dirsize in 1, 2**32-1:
buffer[12:16] = struct.pack('<L', dirsize)
f = io.BytesIO(buffer)
self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, f)

def test_closed_zip_raises_ValueError(self):
"""Verify that testzip() doesn't swallow inappropriate exceptions."""
data = io.BytesIO()
Expand Down
2 changes: 2 additions & 0 deletions Lib/zipfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -1349,6 +1349,8 @@ def _RealGetContents(self):
print("given, inferred, offset", offset_cd, inferred, concat)
# self.start_dir: Position of start of central directory
self.start_dir = offset_cd + concat
if self.start_dir < 0:
raise BadZipFile("Bad offset for central directory")
fp.seek(self.start_dir, 0)
data = fp.read(size_cd)
fp = io.BytesIO(data)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
:class:`zipfile.ZipFile` now raises :exc:`zipfile.BadZipFile` instead of ``ValueError`` when reading a
corrupt zip file in which the central directory offset is negative.