Index: Lib/zipfile.py =================================================================== --- Lib/zipfile.py (revision 84249) +++ Lib/zipfile.py (working copy) @@ -238,6 +238,9 @@ if start >= 0: # found the magic number; attempt to unpack and interpret recData = data[start:start+sizeEndCentDir] + if len(recData) != sizeEndCentDir: + # Zip file is corrupted. + return endrec = list(struct.unpack(structEndArchive, recData)) comment = data[start+sizeEndCentDir:] # check that comment length is correct Index: Lib/test/test_zipfile.py =================================================================== --- Lib/test/test_zipfile.py (revision 84249) +++ Lib/test/test_zipfile.py (working copy) @@ -745,6 +745,21 @@ fp.seek(0, 0) chk = zipfile.is_zipfile(fp) self.assertTrue(not chk) + + def test_damaged_zipfile(self): + """Check that zipfiles with missing bytes at the end raise BadZipfile.""" + # - Create a valid zip file + with zipfile.ZipFile(TESTFN, mode="w") as zipf: + zipf.writestr("foo.txt", b"O, for a Muse of Fire!") + + # - Now create copies of it missing the last N bytes and make sure + # a BadZipfile exception is raised when we try to open it + s = open(TESTFN, "rb").read() + for N in range(len(s) - 2): + f = open(TESTFN2, "wb") + f.write(s[:N]) + f.close() + self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN2) def test_is_zip_valid_file(self): """Check that is_zipfile() correctly identifies zip files."""