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

  • Use tempfile.mkstemp() or tempfile.NamedTemporaryFile() to create the file securely.
  • Restrict temporary file access permissions.
  • Remove temporary files promptly after use.

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.

Explanation:

  • Before: Another process can create a file or link after mktemp() returns the name but before open() creates the file.
  • After: mkstemp() and NamedTemporaryFile() create the file securely rather than just reserving a name. tempfile.NamedTemporaryFile(delete=True) also handles removal when the context exits normally.

References