Skip to content

Commit 1f876f1

Browse files
1cbycinsisong
andcommitted
gh-162129: Validate ZIP member comment length
Co-authored-by: insisong <emmanuelisaacnsisong@gmail.com>
1 parent 4497fe9 commit 1f876f1

3 files changed

Lines changed: 30 additions & 0 deletions

File tree

‎Lib/test/test_zipfile/test_core.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4498,6 +4498,28 @@ def test_comments(self):
44984498
with zipfile.ZipFile(TESTFN,mode="r") as zipf:
44994499
self.assertEqual(zipf.comment, b"shorter comment")
45004500

4501+
def test_member_comment_too_long(self):
4502+
stream = io.BytesIO()
4503+
with zipfile.ZipFile(stream, mode="w") as zipf:
4504+
zinfo = zipfile.ZipInfo("accepted.txt")
4505+
zinfo.comment = b"x" * zipfile.ZIP_MAX_COMMENT
4506+
zipf.writestr(zinfo, b"content")
4507+
4508+
zinfo = zipfile.ZipInfo("rejected.txt")
4509+
zinfo.comment = b"x" * (zipfile.ZIP_MAX_COMMENT + 1)
4510+
with self.assertRaisesRegex(
4511+
ValueError,
4512+
r"ZipInfo\.comment exceeds the maximum length of 65535 bytes",
4513+
):
4514+
zipf.writestr(zinfo, b"content")
4515+
4516+
with zipfile.ZipFile(stream) as zipf:
4517+
self.assertEqual(zipf.namelist(), ["accepted.txt"])
4518+
self.assertEqual(
4519+
zipf.getinfo("accepted.txt").comment,
4520+
b"x" * zipfile.ZIP_MAX_COMMENT,
4521+
)
4522+
45014523
def test_unicode_comment(self):
45024524
with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
45034525
zipf.writestr("foo.txt", "O, for a Muse of Fire!")

‎Lib/zipfile/__init__.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2528,6 +2528,11 @@ def _extract_member(self, member, targetpath, pwd):
25282528

25292529
def _writecheck(self, zinfo):
25302530
"""Check for errors before writing a file to the archive."""
2531+
if len(zinfo.comment) > ZIP_MAX_COMMENT:
2532+
raise ValueError(
2533+
f"ZipInfo.comment exceeds the maximum length of "
2534+
f"{ZIP_MAX_COMMENT} bytes"
2535+
)
25312536
if zinfo.filename in self.NameToInfo:
25322537
warnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3)
25332538
if self.mode not in ('w', 'x', 'a'):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Raise :exc:`ValueError` before writing a ZIP member whose
2+
:attr:`~zipfile.ZipInfo.comment` is too long for the ZIP format. This avoids
3+
an opaque :exc:`struct.error` while closing the archive.

0 commit comments

Comments
 (0)