Creating a new temporary file using the mktemp function in the tempfile does not ensure exclusive access to the file, as it simply returns a filename that is guaranteed to be unique at the point when mktemp returns. Opening a file with this name must then happen separately, and there is no guarantee that these operations will happen atomically. Because of this, it may be possible for an attacker to interfere with the file before it is opened.

Note that mktemp has been deprecated since Python 2.3.

Replace the use of mktemp with some of the more secure functions in the tempfile module, such as TemporaryFile. If the file is intended to be accessed from other processes, consider using the NamedTemporaryFile function.

The following piece of code opens a temporary file and writes a set of results to it. Because the filename is created using mktemp, another process may have accessed this file before it is opened using open.

By changing the code to use NamedTemporaryFile instead, the file is opened immediately.

  • Python Standard Library: tempfile.mktemp.