在提取前检查tar档案

4 投票
1 回答
1607 浏览
提问于 2025-04-17 06:13

在Python的文档中,有建议说在提取tar压缩包之前,最好先检查一下内容。那么,使用tarfile这个Python模块,确保压缩包安全的最佳方法是什么呢?我是不是应该遍历所有的文件名,检查它们是否包含绝对路径呢?

像下面这样的做法够不够呢?

import sys
import tarfile
with tarfile.open('sample.tar', 'r') as tarf:
    for n in tarf.names():
        if n[0] == '/' or n[0:2] == '..':
            print 'sample.tar contains unsafe filenames'
            sys.exit(1)
    tarf.extractall()

编辑

这个脚本在2.7版本之前是不能用的。可以参考with和tarfile

我现在是遍历压缩包里的所有成员:

target_dir = "/target/"
with closing(tarfile.open('sample.tar', mode='r:gz')) as tarf:
    for m in tarf:
        pathn = os.path.abspath(os.path.join(target_dir, m.name))
        if not pathn.startswith(target_dir):
            print 'The tar file contains unsafe filenames. Aborting.'
            sys.exit(1)
        tarf.extract(m, path=tdir)

1 个回答

4

差不多,不过还是有可能出现像 foo/../../ 这样的路径。

更好的做法是使用 os.path.joinos.path.abspath,这两个函数可以正确处理路径开头的 / 和路径中的 ..,无论它们出现在什么地方:

target_dir = "/target/" # trailing slash is important
with tarfile.open(…) as tarf:
    for n in tarf.names:
        if not os.path.abspath(os.path.join(target_dir, n)).startswith(target_dir):
            print "unsafe filenames!"
            sys.exit(1)
    tarf.extractall(path=target_dir)

撰写回答