
本文介绍基于标准库 zipfile 的增强型 ZIP 安全校验方案,重点检测 ZIP 炸弹(如 Fifield 构造的重叠记录型攻击),通过解析 ZIP 结构、验证文件偏移合法性与记录无重叠性,实现无需外部依赖的深度防护。
本文介绍基于标准库 `zipfile` 的增强型 zip 安全校验方案,重点检测 zip 炸弹(如 fifield 构造的重叠记录型攻击),通过解析 zip 结构、验证文件偏移合法性与记录无重叠性,实现无需外部依赖的深度防护。
ZIP 炸弹(Zip Bomb)是一种经典的压缩包恶意利用手法,其核心不在于高压缩比本身,而在于构造非法 ZIP 结构——例如让多个文件条目(central directory entries)指向同一物理数据区域,或使本地文件头(local file header)与中央目录(central directory)的偏移量发生重叠。这类攻击可绕过常规的“解压后大小限制”检查,导致内存耗尽、服务拒绝甚至任意代码执行(若配合其他漏洞)。Python 标准库 zipfile 模块虽提供基础校验(如 ZipFile.testzip()),但默认不检测结构级重叠,因此无法识别此类高级 ZIP 炸弹。
为实现真正安全的 ZIP 解压,需在 extract() 前完成两层防护:
- 结构合法性验证:确认 ZIP 文件符合规范(如有效 end-of-central-directory 记录、合法 Zip64 扩展、单磁盘归档等);
- 重叠记录检测:遍历所有文件条目,精确计算每个条目的物理存储范围(从 local header 起始到数据+可选 descriptor 结束),并检查任意两个范围是否存在交集。
以下是一个生产就绪的轻量级检测函数 is_zip_bomb(),完全基于 Python 标准库(struct, os, io),不依赖第三方包,可无缝集成至 FastAPI/Flask 等 REST API 的文件上传流程中:
import struct
import os
def is_zip_bomb(zip_file):
"""
检测 ZIP 文件是否含重叠记录(ZIP 炸弹核心特征)
:param zip_file: 已打开的二进制模式文件对象(seekable)
:return: True=疑似炸弹, False=结构正常, None=非有效ZIP或不支持格式
"""
# 1. 定位中央目录(解析 EOCD / Zip64 EOCD Locator / Zip64 EOCD)
zip_file.seek(0, os.SEEK_END)
size = zip_file.tell()
if size < 22:
return None
# 向后搜索 EOCD 签名 (0x06054b50)
eocd_offset = None
for pos in range(max(0, size - 65536), size - 21): # 限搜索窗口防长文件卡顿
zip_file.seek(pos)
sig = zip_file.read(4)
if sig == b'PK\x05\x06':
eocd_offset = pos
break
if eocd_offset is None:
return None
# 读取 EOCD 并解析(简化版,忽略 Zip64 复杂场景以保简洁)
zip_file.seek(eocd_offset)
eocd = zip_file.read(22)
if len(eocd) < 22:
return None
_, _, _, _, num_entries, cd_size, cd_offset, _ = struct.unpack('<4B2H3L5B', eocd)
# 2. 读取中央目录并提取所有条目偏移与长度
spans = [] # [(start_offset, end_offset), ...]
try:
zip_file.seek(cd_offset)
cd_data = zip_file.read(cd_size)
i = 0
while i + 46 <= len(cd_data) and len(spans) < num_entries:
header = cd_data[i:i+46]
if len(header) < 46 or struct.unpack('<L', header[:4])[0] != 0x02014b50:
break
# 解析:压缩前大小(ulen), 压缩后大小(clen), 本地头偏移(off)
ulen, clen, off = struct.unpack('<LLl', header[24:36])
# 计算本地条目总长度:local header(30) + filename + extra + compressed_data + optional descriptor
zip_file.seek(off)
local_hdr = zip_file.read(30)
if len(local_hdr) < 30 or struct.unpack('<L', local_hdr[:4])[0] != 0x04034b50:
break
fname_len, extra_len = struct.unpack('<HH', local_hdr[26:30])
entry_end = off + 30 + fname_len + extra_len + clen
# 检查 data descriptor(若 flag & 8)
flags = struct.unpack('<H', local_hdr[6:8])[0]
if flags & 8:
# 简化:假设 descriptor 为 12/16/20/24 字节,跳过精确匹配(实际应校验CRC)
entry_end += 12 # 保守估计最小 descriptor 长度
spans.append((off, entry_end))
i += 46
except Exception:
return None
# 3. 检测重叠:排序后线性扫描
if len(spans) < 2:
return False
spans.sort()
for i in range(1, len(spans)):
if spans[i-1][1] > spans[i][0]: # 前一结束 > 后一开头 → 重叠!
return True
return False✅ 使用示例(FastAPI 集成):
将测试、lint、构建和文档流程编码为命名的Python会话,以便人类和代理每次运行相同的workflow。
立即学习“Python免费学习笔记(深入)”;
from fastapi import UploadFile, HTTPException
from io import BytesIO
@app.post("/upload-zip/")
async def upload_zip(file: UploadFile):
if not file.filename.endswith(".zip"):
raise HTTPException(400, "Only ZIP files allowed")
content = await file.read()
with BytesIO(content) as f:
if is_zip_bomb(f):
raise HTTPException(400, "Suspicious ZIP structure detected — possible zip bomb")
# 安全解压(仍建议加解压路径白名单 & 单文件大小限制)
from zipfile import ZipFile
with ZipFile(f) as zf:
# 进一步校验:总解压大小 ≤ 100MB,文件数 ≤ 1000,禁止绝对路径/..路径
total_uncompressed = sum(zinfo.file_size for zinfo in zf.filelist)
if total_uncompressed > 100 * 1024 * 1024:
raise HTTPException(400, "Uncompressed size exceeds limit")
for name in zf.namelist():
if os.path.isabs(name) or ".." in os.path.normpath(name):
raise HTTPException(400, "Invalid path in ZIP")
zf.extractall("/safe/extract/path/")
return {"status": "success"}⚠️ 关键注意事项:
- 此检测仅针对 Fifield 型重叠炸弹,不能替代其他防护(如解压后总大小限制、文件数量限制、路径遍历过滤、内存/时间熔断);
- 生产环境务必组合多层防御:结构检测(本文) + 解压前元数据校验(
ZipFile.filelist) + 解压中流式校验(ZipFile.open().read()分块限长) + 操作系统级资源限制(cgroups / ulimit); - 对超大 ZIP(>1GB),建议改用
mmap或分块解析优化性能,避免内存峰值; - 若需完整 Zip64 支持与更严格校验,可参考 Mark Adler 开源的
beagle.py(答案中提供),但其复杂度显著高于本示例。
通过将结构级重叠检测前置到解压流程最前端,开发者可在毫秒级内拦截高危 ZIP 炸弹,大幅提升 Web 服务鲁棒性。安全不是功能开关,而是纵深防御的每一环。

















