用 Python zipfile 安全解压用户上传 ZIP 的路径校验与限额实践
【摘要】 用户上传 ZIP 直接解压可能造成路径穿越与符号链接逃逸。本文用 zipfile 逐成员解析目标路径,以 commonpath 校验位于解压根目录内,拒绝绝对路径、../ 和符号链接,并对声明大小与实际写入量双重限额,给出最小函数与恶意 ZIP 测试方法。
用 Python zipfile 安全解压用户上传的 ZIP
问题场景
用户上传 ZIP 后直接调用 ZipFile.extractall(),成员名中的 ../、绝对路径或符号链接可能把文件写到目标目录之外;超大解压体积还可能耗尽磁盘。zipfile 负责解析容器格式,不负责目标路径安全,需要调用方逐成员校验。
校验规则
- 解压前创建全新的空目录,不覆盖已有文件。
- 把成员名中的反斜杠统一为
/,拒绝绝对路径、盘符路径和任何..段。 - 用
realpath解析目标路径,再用commonpath确认它位于解压根目录内。 - 拒绝外部属性标记为符号链接、设备文件等特殊类型的条目。
- 同时限制成员数量、声明解压总大小和实际写入字节数,避免只信任头部声明。
- 先校验、后写文件;目录条目也要走同一套路径检查。
最小实现
import os
import stat
import zipfile
class UnsafeArchiveError(ValueError):
pass
def safe_extract(zip_path, dest_dir, max_total_size=100 * 1024 * 1024, max_members=1000):
root = os.path.realpath(dest_dir)
os.makedirs(root, exist_ok=True)
declared_total = 0
written_total = 0
with zipfile.ZipFile(zip_path) as zf:
infos = zf.infolist()
if len(infos) > max_members:
raise UnsafeArchiveError('成员数量超过限制')
for info in infos:
name = info.filename
if not name or chr(0) in name:
raise UnsafeArchiveError('非法文件名')
normalized = name.replace(chr(92), '/')
if normalized.startswith('/') or os.path.isabs(normalized):
raise UnsafeArchiveError('绝对路径: %r' % name)
if len(normalized) >= 2 and normalized[1] == ':' and normalized[0].isalpha():
raise UnsafeArchiveError('盘符路径: %r' % name)
parts = [p for p in normalized.split('/') if p not in ('', '.')]
if any(p == '..' for p in parts):
raise UnsafeArchiveError('包含 ..: %r' % name)
mode = info.external_attr >> 16
if stat.S_ISLNK(mode):
raise UnsafeArchiveError('符号链接: %r' % name)
if mode and not (stat.S_ISREG(mode) or stat.S_ISDIR(mode)):
raise UnsafeArchiveError('特殊文件: %r' % name)
if stat.S_ISDIR(mode) and not info.is_dir():
raise UnsafeArchiveError('目录条目格式异常: %r' % name)
target = os.path.realpath(os.path.join(root, *parts))
if os.path.commonpath([root, target]) != root:
raise UnsafeArchiveError('越出根目录: %r' % name)
if info.is_dir():
if parts:
os.makedirs(target, exist_ok=True)
continue
if not parts:
raise UnsafeArchiveError('空文件名')
declared_total += info.file_size
if declared_total > max_total_size:
raise UnsafeArchiveError('声明解压大小超限')
os.makedirs(os.path.dirname(target), exist_ok=True)
with zf.open(info) as src, open(target, 'xb') as dst:
while True:
chunk = src.read(64 * 1024)
if not chunk:
break
written_total += len(chunk)
if written_total > max_total_size:
raise UnsafeArchiveError('实际写入大小超限')
dst.write(chunk)
return written_total
open(target, 'xb') 使用独占创建,重复条目或已存在文件会失败,调用方可将其视为拒绝。commonpath 在路径位于不同盘符或绝对/相对混合时会抛 ValueError,生产代码应捕获并拒绝。
运行方法
将上面代码保存为 safe_zip.py,同目录新建 test_safe_zip.py:
import os
import stat
import tempfile
import zipfile
from safe_zip import UnsafeArchiveError, safe_extract
def build(path, entries):
with zipfile.ZipFile(path, 'w') as zf:
for entry_name, data in entries:
zf.writestr(entry_name, data)
def build_symlink(path):
with zipfile.ZipFile(path, 'w') as zf:
info = zipfile.ZipInfo('link')
info.external_attr = (stat.S_IFLNK | 0o777) << 16
zf.writestr(info, '../../etc/passwd')
cases = {
'dotdot.zip': [('../escape.txt', 'x')],
'abs.zip': [('/tmp/escape.txt', 'x')],
'win.zip': [('C:/escape.txt', 'x')],
'backslash.zip': [('..' + chr(92) + 'escape.txt', 'x')],
}
with tempfile.TemporaryDirectory() as td:
for filename, entries in cases.items():
archive = os.path.join(td, filename)
build(archive, entries)
out = os.path.join(td, filename + '.out')
try:
safe_extract(archive, out)
except UnsafeArchiveError as exc:
print(filename, '已拒绝:', exc)
else:
raise AssertionError(filename + ' 未被拒绝')
archive = os.path.join(td, 'symlink.zip')
build_symlink(archive)
try:
safe_extract(archive, os.path.join(td, 'symlink.out'))
except UnsafeArchiveError as exc:
print('symlink.zip 已拒绝:', exc)
else:
raise AssertionError('symlink.zip 未被拒绝')
good = os.path.join(td, 'good.zip')
build(good, [('a/b.txt', 'hello')])
out = os.path.join(td, 'good.out')
size = safe_extract(good, out)
assert size == 5
with open(os.path.join(out, 'a', 'b.txt'), encoding='utf-8') as fp:
assert fp.read() == 'hello'
print('正常 ZIP 解压成功')
运行:
python test_safe_zip.py
脚本会在临时目录生成恶意样本并验证被拒绝,不会写入固定系统路径。
边界与限制
- 这段代码防的是路径穿越和符号链接逃逸,不是完整沙箱。解压目录应使用独立临时目录,并以低权限进程运行。
realpath与写文件之间存在 TOCTOU 窗口;若同一目录会被并发不可信写入,需要更严格的隔离或文件描述符级操作。- 不处理 Windows 保留设备名(如
CON、NUL)、大小写不敏感冲突、Unicode 规范化冲突和超长路径,需按部署平台补充策略。 - 只限制解压体积,不限制压缩包本身大小;可再结合压缩比、磁盘配额和上传大小限制。压缩比阈值过严会误伤正常的小文件。
- 实际写入超限时,前面已写出的文件可能已落盘,应在临时目录中解压,失败后整体删除。
- 损坏、加密 ZIP 会由
zipfile抛出BadZipFile等异常,调用方需捕获并返回统一错误。 - 解压成功不代表内容安全,后续仍需按业务做类型检查、病毒扫描或隔离预览。
【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)