Skip to content

tempfile — mktemp race condition

Insecure Temporary File in the tempfile Module

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

tempfile_mktemp_args_with_open_args.py
1
2
3
4
5
6
7
8
import tempfile


filename = tempfile.mktemp("", "tmp", dir=None)
with open(
    filename, "w+", buffering=-1, encoding=None, errors=None, newline=None
) as f:
    f.write(b"Hello World!\n")
Example Output
> precli tests/unit/rules/python/stdlib/tempfile/examples/tempfile_mktemp_args_with_open_args.py
⚠️  Warning on line 4 in tests/unit/rules/python/stdlib/tempfile/examples/tempfile_mktemp_args_with_open_args.py
PY021: Insecure Temporary File
The function 'tempfile.mktemp' can allow insecure ways of creating temporary files and directories that can lead to race conditions.

Remediation

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.

tempfile_mktemp_args_with_open_args.py
1
2
3
4
5
6
7
8
import tempfile


filename = tempfile.NamedTemporaryFile(delete=False)
with open(
    filename, "w+", buffering=-1, encoding=None, errors=None, newline=None
) as f:
    f.write(b"Hello World!\n")

Default Configuration

enabled = true
level = "warning"

See also

New in version 0.1.9