0

我在我的项目上运行了 bandit 并遇到了以下安全问题,我不明白为什么这是一个问题以及这些问题的解决方案是什么。

   --------------------------------------------------
>> Issue: [B108:hardcoded_tmp_directory] Probable insecure usage of temp file/directory.
   Severity: Medium   Confidence: Medium
   Location: abc/xyz/xxx.py:176
   More Info: https://bandit.readthedocs.io/en/latest/plugins/b108_hardcoded_tmp_directory.html
175         def get_pickle_file_path(self):
176             return os.path.join("/tmp/aaa", "folder_" + self.name)
177 
--------------------------------------------------
>> Issue: [B102:exec_used] Use of exec detected.
   Severity: Medium   Confidence: High
   Location: abc/models.py:1405
   More Info: https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html
1404            loc = {'result': []}
1405            exec(self.code, globals(), loc)
1406            return loc['result']

在寻找B108问题的解决方案后。我发现这个where/tmptempfile.gettempdir()函数替换了,但是两者的值是一样的。tempfile.gettempdir()解决方案是什么/tmp

4

1 回答 1

0

刚刚也遇到了这个 Bandit 问题。您现在共享的第一个链接链接到解释问题和解决方法的资源。

主要问题似乎是创建可预测的临时文件会使您面临“检查时间,使用时间攻击(TOCTOU)”。从资源:

可以预测文件名并写入包含临时文件的目录的恶意用户可以通过在程序创建文件本身之前使用临时文件的名称创建符号链接来有效地劫持临时文件。这允许恶意用户提供恶意数据或导致程序采取行动来影响攻击者选择的文件。

tempfile.gettempdir()并将 umask 设置为 0077 以确保只有创建者可以编辑和阅读似乎是最好的解决方案。

也来自该资源:

import os
import tempfile

tmpdir = tempfile.mkdtemp()
predictable_filename = 'myfile'

# Ensure the file is read/write by the creator only
saved_umask = os.umask(0077)

path = os.path.join(tmpdir, predictable_filename)
print path
try:
    with open(path, "w") as tmp:
        tmp.write("secrets!")
except IOError as e:
    print 'IOError'
else:
    os.remove(path)
finally:
    os.umask(saved_umask)
    os.rmdir(tmpdir)
于 2020-12-17T02:36:46.073 回答