Python 在提取之前检查tar存档

Python 在提取之前检查tar存档,python,tar,Python,Tar,在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] == '..':

在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之前的版本不兼容。cf

我现在对成员进行迭代:

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)

几乎可以,尽管仍然可以有类似于
foo/./../
的路径

最好使用
os.path.join
os.path.abspath
,这两个选项一起可以正确处理路径中的任何位置的前导
/
s:

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)

谢谢你的小把戏。我现在更喜欢在成员上迭代并使用tarf.extract(member,path=target_dir),因为归档文件似乎完全由tarf.getnames()读取,这很有效。你也可以使用<代码> TARF。查找(0)<代码>然后<代码> Excel()/代码>。此外,如果这个答案是有用的,请考虑投票和接受它。啊,对,我忘了它是15或25个代表来投票,而不是10。另外,欢迎使用StackOverflow:)