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

import tempfile


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

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.

import tempfile


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

See also

New in version 0.1.9