Skip to content

zipfile: ZipInfo.comment exceeding 65535 bytes causes struct.error in ZipFile.close() without proper validation #162129

Description

@klnmurthi12345

Bug report

Bug description:

When adding an entry to a ZipFile using a ZipInfo object whose comment exceeds 65,535 bytes (the maximum size representable by the 16-bit unsigned short H in the ZIP central directory header), writestr() accepts the entry without validation.

Later, when ZipFile.close() is called (or upon exiting a with ZipFile(...) block), _write_end_record() attempts to pack len(zinfo.comment) into structCentralDir using H, raising an unhandled struct.error:

struct.error: 'H' format requires 0 <= number <= 65535

Because this failure occurs during close(), the central directory and end-of-central-directory record are never written, leaving the ZIP archive unfinalized.

In contrast, archive-level comments (ZipFile.comment) are guarded against ZIP_MAX_COMMENT (65,535 bytes) with a warning and truncation.

Steps/Code to Reproduce:

import zipfile, io

buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
    zinfo = zipfile.ZipInfo("test.txt")
    zinfo.comment = b"x" * 70000
    zf.writestr(zinfo, b"content")

Actual outcome:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "zipfile/__init__.py", line 1475, in __exit__
    self.close()
  File "zipfile/__init__.py", line 2060, in close
    self._write_end_record()
  File "zipfile/__init__.py", line 2107, in _write_end_record
    centdir = struct.pack(structCentralDir,
                          stringCentralDir, create_version,
                          ...
                          len(filename), len(extra_data),
                          len(zinfo.comment),
                          ...)
struct.error: 'H' format requires 0 <= number <= 65535

Expected outcome:

ZipFile.writestr() (or ZipInfo) should validate len(zinfo.comment) <= 65535 and raise a descriptive ValueError(f"ZipInfo.comment exceeds maximum allowable length of {ZIP_MAX_COMMENT} bytes") (or truncate with a warning similar to archive comments) to prevent corrupting the close sequence.

CPython versions tested on:

Python 3.12, 3.13, main

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    stdlibStandard Library Python modules in the Lib/ directory
    on Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions