>>> 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
Bug description
zipimport.zipimporter()is documented to raisezipimport.ZipImportErrorfor an invalid archive, but it leaks a raw
UnicodeDecodeErrorwhen a centraldirectory entry sets the UTF-8 file name flag (
0x800) yet stores bytes thatare not valid UTF-8.
In
_read_directory()(Lib/zipimport.py) the UTF-8 branch doesname = name.decode()with no error handling, whereas the sibling non-UTF-8branch already guards
UnicodeDecodeErrorand falls back to latin-1/cp437.Every other corruption path in the function raises
ZipImportError.Expected:
zipimport.ZipImportError.CPython versions tested on
3.13, 3.14, 3.15
Operating systems tested on
Linux, macOS
Linked PRs