gpt4 book ai didi

python - 在 extractall 之前检查 tar 存档

转载 作者:太空狗 更新时间:2023-10-30 03:06:31 26 4
gpt4 key购买 nike

在 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 and 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)

最佳答案

几乎,尽管仍然有可能有像 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)

关于python - 在 extractall 之前检查 tar 存档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8112742/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com