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 | |
|---|---|
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 | |
|---|---|
Default Configuration
See also
New in version 0.1.9