1

I ran bandit on my project and got the following issue for security, I don't understand why this is an issue and what are the solutions for the issues.

   --------------------------------------------------
>> 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']

After searching for the solution of B108 issue. I found this where /tmp is replaced by tempfile.gettempdir() function, but the value of the both is same. Is tempfile.gettempdir() the solution for /tmp?

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
Ravindra Gupta
  • 1,256
  • 12
  • 42

1 Answers1

3

Just came across this Bandit issue as well. The first link you shared now links to a resource explaining the issue and methods of resolving it.

The main issue appears to be that creating predictable temp files leaves you open to a "time of check, time of use attack (TOCTOU)". From the resource:

Malicious users that can predict the file name and write to directory containing the temporary file can effectively hijack the temporary file by creating a symlink with the name of the temporary file before the program creates the file itself. This allows a malicious user to supply malicious data or cause actions by the program to affect attacker chosen files.

tempfile.gettempdir() and setting umask to 0077 to ensure only the creator can edit and read seem to be the best solution.

From that resource as well:

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)
Mrenoe
  • 93
  • 6