先看清单再解压:用 Python 标准库只读检查 ZIP 的路径、重名与体积线索
收到陌生 ZIP 文件时,我更愿意先问三个问题:它声称装了什么、这些名称在不同系统上会怎样解释、它声称需要多少展开空间。直接双击解压会把这些问题与实际写盘混在一起。本文用 Python 标准库做一个独立的“目录体检”步骤,先产生 JSON 清单,再由人决定是否继续处理。
边界先说清:检查器不解压、不打开成员内容、不创建目标目录,也不把“没有提示”称为“安全”。它不是杀毒软件,不验证全部 ZIP 结构,更不是防压缩炸弹的完整方案。适合学习、排查和人工预审,不应直接变成面向互联网的上传准入服务。

1. 为什么清单要按条目列,而不是按名字存字典
一个 ZIP 可以出现两个同名成员。如果把名称当成字典唯一键,后一个值可能覆盖前一个值,报告反而丢掉最该注意的信息。本文使用 infolist() 逐条保留记录,再用 Counter 统计相同名称;每条记录带有从零开始的 index,供复核定位。相关接口见 Python 官方 infolist 文档。
这里的“重复”只指 Python 解码后的 filename 完全相同。Readme.txt 与 README.TXT、a/b 与 a/./b、文件 a 与目录 a/,不一定被这条规则视为同名,却可能在实际文件系统或解压工具中发生冲突。不要把精确重名检测当作完整的目标路径冲突检测。
2. 跨平台路径检查只报告线索,不修复名称
在 Linux 上检查,也不能只用当前系统的路径规则。PurePosixPath 和 PureWindowsPath 都能做不访问文件系统的词法分析,后者可以识别盘符与 UNC 路径。本文同时看 POSIX 绝对路径、Windows 的 drive 和 root,而不是只依赖一个 is_absolute()。依据是 pathlib 的纯路径文档。
../report.txt 和 a/../report.txt 都标记 parent_component。这里只检查组成部分是否恰好等于两个点,不会把 report..txt 误报成上级目录。
C:report.txt 虽然是 Windows 的盘符相对路径,不是完整绝对路径,仍值得单独提醒。
以单个反斜杠开头的名称带有 Windows 根路径语义;UNC 名称也要提示。
反斜杠在 POSIX 下可以只是文件名字符。本例为了跨平台审阅,临时把它当作分隔符查找上级组件,同时发出可移植性提示,但绝不修改清单中的原名称。
这是保守提示规则,不是在预测某个解压器一定会越界。实际目标目录、现存符号链接、大小写规则和并发修改都没有参与判断。
3. 可直接保存运行的完整检查器
保存为 inspect_zip.py,仅依赖标准库。本次实际测试环境是 CPython 3.12.14、Linux;文档核验日期为 2026 年 10 月 20 日。没有把其他系统的词法测试写成在 Windows 上运行的结果。
默认阈值是本教程自己的保守示例,不是 Python 官方建议:输入文件最多 256 MiB,条目最多 10,000 个,单成员声明大小最多 128 MiB,声明总大小最多 512 MiB,声明展开倍率最多 100。MiB 按 1,048,576 字节计算。“超过”才触发阈值,等于阈值不触发。
"""Read ZIP metadata only. Findings are hints, not a safety verdict."""
import argparse
from collections import Counter
from dataclasses import dataclass
import json
import math
import os
from pathlib import PurePosixPath, PureWindowsPath
import stat
import sys
import zipfile
MIB = 1024 * 1024
@dataclass(frozen=True)
class Limits:
archive_bytes: int = 256 * MIB
entries: int = 10_000
member_bytes: int = 128 * MIB
total_bytes: int = 512 * MIB
ratio: float = 100.0
def path_hints(name):
hints = []
windows = PureWindowsPath(name)
if PurePosixPath(name).is_absolute():
hints.append('posix_absolute')
if windows.drive:
hints.append('windows_drive_or_unc')
if windows.root:
hints.append('windows_rooted')
# Backslash is a filename character on POSIX, but a separator on Windows.
if '..' in name.replace('\\', '/').split('/'):
hints.append('parent_component')
if '\\' in name:
hints.append('backslash_portability')
if not name or any(ord(c) < 32 or ord(c) == 127 for c in name):
hints.append('empty_or_control_character')
return hints
def inspect_zip(path, limits=Limits()):
values = (limits.archive_bytes, limits.entries,
limits.member_bytes, limits.total_bytes, limits.ratio)
if any(v <= 0 for v in values) or not math.isfinite(limits.ratio):
raise ValueError('Limits must be positive; ratio must be finite')
# Check the opened file, not a separate stat of the pathname.
with open(path, 'rb') as source:
physical_bytes = os.fstat(source.fileno()).st_size
if physical_bytes > limits.archive_bytes:
raise ValueError('Archive exceeds input-size limit')
with zipfile.ZipFile(source, 'r') as archive:
infos = archive.infolist()
# The central directory was already parsed before this check.
if len(infos) > limits.entries:
raise ValueError('Archive exceeds entry-count limit')
counts = Counter(info.filename for info in infos)
rows = []
total = 0
for index, info in enumerate(infos):
total += info.file_size
hints = path_hints(info.filename)
if counts[info.filename] > 1:
hints.append('duplicate_name')
if info.file_size > limits.member_bytes:
hints.append('declared_member_size_limit')
if info.compress_size == 0:
ratio = 0.0 if info.file_size == 0 else None
if info.file_size:
hints.append('nonempty_with_zero_compressed_size')
else:
ratio = info.file_size / info.compress_size
if ratio > limits.ratio:
hints.append('declared_ratio_limit')
encrypted = bool(info.flag_bits & 0x1)
unix_symlink = (
info.create_system == 3
and stat.S_ISLNK((info.external_attr >> 16) & 0xFFFF)
)
if encrypted:
hints.append('encrypted_flag')
if unix_symlink:
hints.append('unix_symlink_hint')
rows.append({
'index': index,
'name': info.filename,
'directory_name': info.is_dir(),
'declared_bytes': info.file_size,
'compressed_bytes': info.compress_size,
'declared_ratio': ratio,
'method_id': info.compress_type,
'flag_bits': info.flag_bits,
'create_system': info.create_system,
'external_attr': info.external_attr,
'hints': hints,
})
archive_hints = []
if total > limits.total_bytes:
archive_hints.append('declared_total_size_limit')
return {
'mode': 'metadata_only',
'physical_bytes': physical_bytes,
'entry_count': len(rows),
'declared_total_bytes': total,
'archive_hints': archive_hints,
'has_hints': bool(archive_hints or any(r['hints'] for r in rows)),
'entries': rows,
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('archive')
parser.add_argument('--max-ratio', type=float, default=100.0)
parser.add_argument('--max-total-mib', type=int, default=512)
args = parser.parse_args()
limits = Limits(ratio=args.max_ratio, total_bytes=args.max_total_mib * MIB)
try:
report = inspect_zip(args.archive, limits)
except (OSError, ValueError, EOFError, zipfile.BadZipFile,
NotImplementedError) as exc:
# JSON quoting also keeps terminal control characters escaped.
print(json.dumps({'error': str(exc)}, ensure_ascii=True), file=sys.stderr)
return 2
print(json.dumps(report, ensure_ascii=True, indent=2, allow_nan=False))
return 1 if report['has_hints'] else 0
if __name__ == '__main__':
raise SystemExit(main())在终端运行 python inspect_zip.py received.zip。需要保存报告时可用 python inspect_zip.py received.zip > report.json。请把报告写到另一个路径,不能重定向到被检查的 ZIP 本身。调整总大小与倍率可运行 python inspect_zip.py received.zip --max-total-mib 256 --max-ratio 80;其余阈值可在 Limits 默认值中调整。
退出码 0 表示“本规则未发现提示”,1 表示报告中存在提示,2 表示输入无法完成检查或超过输入/条目限制。0 不是放行授权。程序没有任何“继续解压”分支,自动化调用方也不应仅凭退出码 0 就执行后续内容。
4. 怎样读大小、加密与符号链接结果
声明展开倍率定义为 file_size 除以 compress_size,不是整个 ZIP 的压缩率。成员为空且压缩大小为零时记录 0;声明非空但压缩大小为零时用 JSON 的 null 表示不可计算,并额外提示。实现没有用 max(1, compress_size) 悄悄掩盖这种不一致。
这些数字来自 ZIP 元数据,不能当作实际解压结果。重复文本也可能拥有很高倍率,因此超过 100 倍不等于恶意;反过来,低倍率也不能证明没有风险。多个正常倍率成员仍可能积累出很大的总量,所以必须分别看单项与总量。本例对所有条目的声明大小求和,不因名称以斜杠结尾就忽略其大小。字段定义可查 ZipInfo 官方文档。
encrypted_flag 只检查通用标志的最低位,表示条目宣称加密,不验证密码、算法或内容,也不代表它能被当前解释器解密。该位可在 CPython 3.12.14 的 zipfile 实现中核对。攻击者可以伪造标志;某些不可解析的归档会直接检查失败,而不是得到加密清单。
unix_symlink_hint 采用常见 Unix 元数据约定:创建系统标记为 3,并且外部属性高 16 位中的类型符合 S_ISLNK。它仅提示“元数据像符号链接”,既没有读取链接目标,也不推断解压器会不会创建链接。未标记也不能排除其他特殊文件或扩展格式。类型判定依据见 stat.S_ISLNK 文档;高位模式的使用方式也可见 CPython 的 zipfile.Path 实现。本例不用版本行为有差异的 zipfile.Path.is_symlink()。
5. 不是只跑正常样本:10 个本地测试
将下面文件保存为 test_inspect_zip.py,与检查器放在同一目录,然后运行 python -m unittest -v test_inspect_zip.py。夹具均由测试在临时目录中生成,结束后清理,不需要下载来路不明的样本。
测试覆盖普通成员、空目录和空文件、中文名称、同名成员、八种跨平台路径、高压缩比、单项和总量阈值、Unix 链接属性、加密标志、零压缩大小、输入限制、损坏文件与三个退出码。只读测试会阻止调用 ZipFile.open、extract 和 extractall,并比较检查前后的归档字节。
from dataclasses import replace
from pathlib import Path
import stat
import struct
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
import warnings
import zipfile
from inspect_zip import Limits, inspect_zip, path_hints
class InspectionTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.path = Path(self.temp.name) / 'fixture.zip'
def create(self, entries, compression=zipfile.ZIP_STORED):
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
with zipfile.ZipFile(self.path, 'w', compression=compression) as z:
for name, data in entries:
z.writestr(name, data)
def test_normal_empty_and_unicode(self):
self.create([('docs/', b''), ('docs/说明.txt', b'ok'), ('empty', b'')])
report = inspect_zip(self.path)
self.assertEqual(report['entry_count'], 3)
self.assertEqual(report['declared_total_bytes'], 2)
self.assertFalse(report['has_hints'])
self.assertTrue(report['entries'][0]['directory_name'])
self.assertEqual(report['entries'][2]['declared_ratio'], 0.0)
def test_duplicates_preserve_both_entries(self):
self.create([('same.txt', b'a'), ('same.txt', b'bb')])
rows = inspect_zip(self.path)['entries']
self.assertEqual([r['declared_bytes'] for r in rows], [1, 2])
self.assertTrue(all('duplicate_name' in r['hints'] for r in rows))
def test_cross_platform_names_in_archive(self):
cases = {
'../x': 'parent_component',
'a/../x': 'parent_component',
r'a\..\x': 'parent_component',
'/tmp/x': 'posix_absolute',
r'C:\temp\x': 'windows_drive_or_unc',
r'C:relative.txt': 'windows_drive_or_unc',
r'\rooted.txt': 'windows_rooted',
r'\\server\share\x': 'windows_drive_or_unc',
}
self.create([(name, b'x') for name in cases])
rows = inspect_zip(self.path)['entries']
for row in rows:
self.assertIn(cases[row['name']], row['hints'])
self.assertEqual(path_hints('a/report..txt'), [])
def test_compression_ratio_and_declared_limits(self):
self.create([('repeated.txt', b'A' * 100_000)], zipfile.ZIP_DEFLATED)
limits = replace(Limits(), member_bytes=50_000, total_bytes=90_000)
report = inspect_zip(self.path, limits)
self.assertIn('declared_ratio_limit', report['entries'][0]['hints'])
self.assertIn('declared_member_size_limit', report['entries'][0]['hints'])
self.assertEqual(report['archive_hints'], ['declared_total_size_limit'])
def test_symlink_metadata_hint(self):
entry = zipfile.ZipInfo('link')
entry.create_system = 3
entry.external_attr = (stat.S_IFLNK | 0o777) << 16
self.create([(entry, b'../outside')])
self.assertIn('unix_symlink_hint', inspect_zip(self.path)['entries'][0]['hints'])
def patch_central(self, offset, value):
data = bytearray(self.path.read_bytes())
# Controlled fixture: one small entry; not a general ZIP parser.
start = data.index(b'PK\x01\x02')
struct.pack_into('<' + ('H' if offset == 8 else 'I'), data, start + offset, value)
self.path.write_bytes(data)
def test_encryption_flag_only_not_real_encryption(self):
self.create([('flag.txt', b'x')])
self.patch_central(8, 1)
self.assertIn('encrypted_flag', inspect_zip(self.path)['entries'][0]['hints'])
def test_declared_zero_compressed_nonempty(self):
self.create([('size.txt', b'x')])
self.patch_central(20, 0)
row = inspect_zip(self.path)['entries'][0]
self.assertIsNone(row['declared_ratio'])
self.assertIn('nonempty_with_zero_compressed_size', row['hints'])
def test_no_member_reads_or_extraction_and_archive_unchanged(self):
self.create([('../outside', b'x')])
before = self.path.read_bytes()
with patch.object(zipfile.ZipFile, 'open', side_effect=AssertionError('payload read')), \
patch.object(zipfile.ZipFile, 'extract', side_effect=AssertionError('extract')), \
patch.object(zipfile.ZipFile, 'extractall', side_effect=AssertionError('extractall')):
inspect_zip(self.path)
self.assertEqual(self.path.read_bytes(), before)
self.assertEqual(list(Path(self.temp.name).iterdir()), [self.path])
def test_resource_gates_and_invalid_input(self):
self.create([('a', b'a'), ('b', b'b')])
with self.assertRaises(ValueError):
inspect_zip(self.path, replace(Limits(), entries=1))
with self.assertRaises(ValueError):
inspect_zip(self.path, replace(Limits(), archive_bytes=1))
for ratio in (0, -1, float('nan'), float('inf')):
with self.assertRaises(ValueError):
inspect_zip(self.path, replace(Limits(), ratio=ratio))
self.path.write_bytes(b'not a zip')
with self.assertRaises(zipfile.BadZipFile):
inspect_zip(self.path)
def test_cli_exit_codes(self):
script = Path(__file__).with_name('inspect_zip.py')
def run():
return subprocess.run([sys.executable, str(script), str(self.path)],
capture_output=True, text=True).returncode
self.create([('ok.txt', b'ok')])
self.assertEqual(run(), 0)
self.create([('../x', b'x')])
self.assertEqual(run(), 1)
self.path.write_bytes(b'broken')
self.assertEqual(run(), 2)
if __name__ == '__main__':
unittest.main()本次实际运行结果:10 个测试全部通过。这里的测试数是测试方法数,其中若干方法包含多个样本和断言,不是声称验证了 ZIP 格式的所有情况。
两处刻意的测试边界:加密测试只是修改自建 ZIP 中央目录中的标志位,没有生成真实加密归档,更没有测试解密。零压缩大小测试也只修改受控样本的声明字段,用来证明检查器能报告异常声明;这两份样本都不能被宣传为有效的真实加密/压缩文件。patch_central 只是针对单成员小夹具的测试工具,不是通用 ZIP 编辑器。
6. 仍然不能省掉的安全边界
只读不代表资源消耗为零。ZipFile 在初始化时就会解析中央目录,条目数阈值是在这之后检查,不能作为解析阶段的严格内存上限。输入大小检查也不是 CPU、内存或运行时限的替代品。
它不检查成员内容和全部一致性。没有校验实际解压长度、CRC、局部文件头、重叠数据区域、嵌套归档或恶意文档。代码刻意不调用 testzip(),因为那个接口会读取成员内容,偏离“只看元数据”的目标。见 testzip 官方说明。
它不还原所有原始字节语义。检查的是 zipfile 解码并处理后提供的 filename,不是原始名称字节取证。没有完整检查 Unicode 归一化、保留设备名、尾随点/空格、Windows 数据流或所有名称碰撞。
报告输出有防显示混淆措施,但不是另一层内容扫描。JSON 使用 ensure_ascii=True,控制字符和非 ASCII 字符以转义形式输出;中文名称会显示为 Unicode 转义。它保留信息用于机器读取,但不会判断每一种视觉混淆。
可信输入与隔离仍重要。极端或高风险样本宜放在有 CPU、内存、磁盘和运行时限制的独立环境处理,并使用维护中的 Python。检查时文件仍可能被其他进程修改,打开同一文件句柄不等于锁定或快照。
我的建议是把这个脚本当作“拒绝仓促操作”的辅助工具:出现提示就回到来源、目标平台和业务需求逐项核实;无法完成检查时保持未知状态,而不是默认通过。清单让问题变得可见,但最终处理策略仍需要单独设计。

