python / python/cpython

zipfile raises UnicodeDecodeError instead of BadZipFile for a member name flagged UTF-8 but not valid UTF-8

未关闭
#153,426 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Bug report

Bug description:

When a ZIP entry has general purpose bit 11 set (the name and comment are UTF-8), zipfile decodes the member name with .decode('utf-8') without guarding the decode. A member name that is flagged as UTF-8 but holds bytes that are not valid UTF-8 makes the operation raise UnicodeDecodeError instead of zipfile.BadZipFile.

A corrupt archive should surface as BadZipFile, the module's own error type, so that callers that already handle BadZipFile do not also have to catch UnicodeDecodeError. The sibling extra-field decoder _decodeExtra already wraps its own failures in BadZipFile.

Reproduction:

import io, struct, zipfile

name = b'\xff\xfe'          # flagged UTF-8 but not valid UTF-8
flag = 0x800               # general purpose bit 11
lfh = struct.pack(zipfile.structFileHeader, zipfile.stringFileHeader,
                  20, 0, flag, 0, 0, 0, 0, 0, 0, len(name), 0) + name
cd = struct.pack(zipfile.structCentralDir, zipfile.stringCentralDir,
                 20, 0, 20, 0, flag, 0, 0, 0, 0, 0, 0, len(name), 0, 0, 0, 0, 0, 0) + name
eocd = struct.pack(zipfile.structEndArchive, zipfile.stringEndArchive,
                   0, 0, 1, 1, len(cd), len(lfh), 0)
zipfile.ZipFile(io.BytesIO(lfh + cd + eocd))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

The local file header path has the same gap: if the central directory name is valid UTF-8 but the local header name is not, ZipFile.open() / .read() raises UnicodeDecodeError.

Fix: wrap the two UTF-8 filename decodes (_RealGetContents for the central directory and open() for the local file header) so a UnicodeDecodeError is re-raised as BadZipFile, mirroring _decodeExtra.

CPython versions tested on:

3.13, 3.14

Operating systems tested on:

macOS

Linked PRs
  • gh-153428

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 zipfile.py 中的 _RealGetContents 和 open() 开始,issue 在这里指出了两处 UTF-8 文件名解码。运行提供的内存中归档复现,并添加或更新针对性测试,以确保格式错误的 UTF-8 名称始终引发 BadZipFile,而不是 UnicodeDecodeError。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
backend
Issue 类型
缺陷
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
描述清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。