]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-83245: Raise BadZipFile instead of ValueError when reading a corrupt ZIP file...
authorSam Ezeh <sam.z.ezeh@gmail.com>
Mon, 23 May 2022 17:59:21 +0000 (18:59 +0100)
committerGitHub <noreply@github.com>
Mon, 23 May 2022 17:59:21 +0000 (20:59 +0300)
Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
Lib/test/test_zipfile.py
Lib/zipfile.py
Misc/NEWS.d/next/Library/2022-04-03-19-40-09.bpo-39064.76PbIz.rst [new file with mode: 0644]

index 848bf4f76d4536d08e197591ec417c133429f3cc..f4c11d88c8a09fa2b9e9e823c825b7a2f1436d7a 100644 (file)
@@ -1740,6 +1740,17 @@ class OtherTests(unittest.TestCase):
             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()
index 9f4437526c91f0a3e9b1aceb9e5722288f00643a..fc6ca65e5ed1e9e95745fb5fd7e2c4bd3683f516 100644 (file)
@@ -1381,6 +1381,8 @@ class ZipFile:
             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)
diff --git a/Misc/NEWS.d/next/Library/2022-04-03-19-40-09.bpo-39064.76PbIz.rst b/Misc/NEWS.d/next/Library/2022-04-03-19-40-09.bpo-39064.76PbIz.rst
new file mode 100644 (file)
index 0000000..34d3152
--- /dev/null
@@ -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.