Skip to main content

Insecure Temporary File in the tempfile Module

PY021
insecure_temporary_file
CWE-377
⚠️ Warning

The tempfile.mktemp function in Python is a legacy method for creating temporary files with a unique name. It is important to note that this function is susceptible to race conditions, which can occur when multiple processes or threads attempt to create temporary files concurrently. These race conditions may lead to unintended behavior, data corruption, or security vulnerabilities in your code.

Example


warning
import tempfile


filename = tempfile.mktemp(suffix='', prefix='tmp', dir=None)
with open(filename) as f:
f.write(b"Hello World!\n")

Remediation


Fix Iconfix

To ensure the reliability and security of your temporary file management, consider using NamedTemporaryFile. The tempfile.NamedTemporaryFile class automatically handles the generation of unique filenames, proper file closure, and cleanup when the file is no longer needed.

import tempfile


with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(b"Hello World!\n")

False Positives


In the case of a false positive the rule can be suppressed. Simply add a trailing or preceding comment line with either the rule ID (PY021) or rule category name (insecure_temporary_file).

Fix Iconfix
import tempfile


# suppress: PY021
filename = tempfile.mktemp(suffix='', prefix='tmp', dir=None)
with open(filename) as f:
f.write(b"Hello World!\n")

See also