Skip to content

zipimport.zipimporter raises UnicodeDecodeError instead of ZipImportError for an invalid UTF-8 file name #153679

Description

@tonghuaroot

Bug description

zipimport.zipimporter() is documented to raise zipimport.ZipImportError
for an invalid archive, but it leaks a raw UnicodeDecodeError when a central
directory entry sets the UTF-8 file name flag (0x800) yet stores bytes that
are not valid UTF-8.

In _read_directory() (Lib/zipimport.py) the UTF-8 branch does
name = name.decode() with no error handling, whereas the sibling non-UTF-8
branch already guards UnicodeDecodeError and falls back to latin-1/cp437.
Every other corruption path in the function raises ZipImportError.

>>> import struct, zipimport
>>> name = b'\xff\xfe\xff'
>>> cdh = b'PK\x01\x02' + struct.pack('<HHHHHHIIIHHHHHII', 20,20,0x800,0,0,0,0,50,100,len(name),0,0,0,0,0,0) + name
>>> eocd = b'PK\x05\x06' + struct.pack('<HHHHIIH', 0,0,1,1,len(cdh),0,0)
>>> _ = open('bad.zip','wb').write(cdh + eocd)
>>> zipimport.zipimporter('bad.zip')
Traceback (most recent call last):
  ...
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

Expected: zipimport.ZipImportError.

CPython versions tested on

3.13, 3.14, 3.15

Operating systems tested on

Linux, macOS

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions