Insecure temporary file creation

Insecure temporary file creation

Description

tempfile.mktemp() returns an available name without creating the file. Another process can claim that path before the application opens it. This race can expose data or cause the application to overwrite an unintended file.

Potential impact

  • Data exposure: An attacker may access sensitive temporary data.
  • Data tampering: The temporary file’s contents may be changed.
  • Privilege escalation: Manipulating the path may affect resources accessible to the application’s account.

Remediation

  • Create the temporary file in one operation with tempfile.mkstemp() or tempfile.NamedTemporaryFile(). tempfile.mktemp() only chooses a name. Keep access restricted to the owner.
  • With mkstemp(), the caller must close and remove the file. For automatic cleanup, use NamedTemporaryFile(delete=True) in a with block.

Examples

Before

python
# Unsafe temporary file creation
import tempfile

filename = tempfile.mktemp()  # Noncompliant
tmp_file = open(filename, "w+")

After

Using tempfile.mkstemp

python
# Safe temporary file creation with mkstemp
import tempfile
import os

fd, filename = tempfile.mkstemp()
try:
    with os.fdopen(fd, "w+") as tmp_file:
        tmp_file.write("Sensitive information")
finally:
    # Remove the file after use.
    os.remove(filename)

Using tempfile.NamedTemporaryFile

python
# Safe temporary file creation with NamedTemporaryFile
import tempfile

with tempfile.NamedTemporaryFile(delete=True) as tmp_file:
    tmp_file.write(b"Sensitive information")
    tmp_file.flush()
    print(f"Temporary file created at {tmp_file.name}")
    # Use the temporary file.
    tmp_file.seek(0)
    data = tmp_file.read()
# With delete=True, the temporary file is removed automatically.

The first example closes the file through the os.fdopen context manager and removes the path in finally. The second closes and removes the file when the with block exits.

References