Skip to content
Merged
11 changes: 11 additions & 0 deletions Lib/test/test_zipfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -1727,6 +1727,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 @@ -1366,6 +1366,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.