Skip to content

Commit 202ed25

Browse files
gh-83245: Raise BadZipFile instead of ValueError when reading a corrupt ZIP file (GH-32291)
Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent 6a6f823 commit 202ed25

File tree

3 files changed

+15
-0
lines changed

3 files changed

+15
-0
lines changed

Lib/test/test_zipfile.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1740,6 +1740,17 @@ def test_empty_file_raises_BadZipFile(self):
17401740
fp.write("short file")
17411741
self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
17421742

1743+
def test_negative_central_directory_offset_raises_BadZipFile(self):
1744+
# Zip file containing an empty EOCD record
1745+
buffer = bytearray(b'PK\x05\x06' + b'\0'*18)
1746+
1747+
# Set the size of the central directory bytes to become 1,
1748+
# causing the central directory offset to become negative
1749+
for dirsize in 1, 2**32-1:
1750+
buffer[12:16] = struct.pack('<L', dirsize)
1751+
f = io.BytesIO(buffer)
1752+
self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, f)
1753+
17431754
def test_closed_zip_raises_ValueError(self):
17441755
"""Verify that testzip() doesn't swallow inappropriate exceptions."""
17451756
data = io.BytesIO()

Lib/zipfile.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1381,6 +1381,8 @@ def _RealGetContents(self):
13811381
print("given, inferred, offset", offset_cd, inferred, concat)
13821382
# self.start_dir: Position of start of central directory
13831383
self.start_dir = offset_cd + concat
1384+
if self.start_dir < 0:
1385+
raise BadZipFile("Bad offset for central directory")
13841386
fp.seek(self.start_dir, 0)
13851387
data = fp.read(size_cd)
13861388
fp = io.BytesIO(data)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:class:`zipfile.ZipFile` now raises :exc:`zipfile.BadZipFile` instead of ``ValueError`` when reading a
2+
corrupt zip file in which the central directory offset is negative.

0 commit comments

Comments
 (0)