logo

Database

Python Use Of Mktemp

Description

Detects the use of the insecure tempfile.mktemp() function in Python code, which creates temporary files in an unsafe manner. This function is deprecated and vulnerable to race conditions because it doesn't guarantee exclusive access to the created file, potentially allowing attackers to perform symlink attacks or access sensitive data.

Weakness:

160 - Excessive privileges - Temporary Files

Category: Access Subversion

Detection Strategy

    Check for function calls to tempfile.mktemp in Python code

    Identify expressions that specifically match 'tempfile.mktemp' by examining object and member references

    Report a vulnerability when tempfile.mktemp is found since it should be replaced with the secure tempfile.mkstemp() or tempfile.NamedTemporaryFile()

Vulnerable code example

import tempfile

def write_temp_data():
    temp_path = tempfile.mktemp()  # Vulnerable: Race condition between filename generation and file creation
    with open(temp_path, 'w') as f:
        f.write('sensitive data')

✅ Secure code example

import tempfile

def write_temp_data():
    # Safe: Creates and opens temp file atomically, avoiding race conditions
    with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
        temp_file.write('sensitive data')