# Unsafe Temporary File Creation via tempfile.mktemp

Language: Python
Severity: High
CWE: CWE-377

## Source
5

## Flow
5-7

## Sink
7

## Vulnerable Code
```python
import tempfile
import json

def store_iot_sensor_telemetry(device_id, temperature, humidity, pressure):
    telemetry_file = tempfile.mktemp(suffix='.json', prefix=f'sensor_{device_id}_')
    sensor_data = {'device': device_id, 'temp': temperature, 'humidity': humidity, 'pressure': pressure, 'timestamp': time.time()}
    with open(telemetry_file, 'w') as f:
        json.dump(sensor_data, f)
    upload_to_cloud_storage(telemetry_file)
    return telemetry_file
```

## Explanation

The code uses tempfile.mktemp() which creates a predictable filename without atomically creating the file, allowing a race condition (TOCTOU vulnerability). An attacker can predict the filename and create a malicious file or symlink between mktemp() and the open() call, leading to unauthorized file access or data manipulation.

## Remediation

The fix replaces tempfile.mktemp() with tempfile.mkstemp(), which atomically creates and opens the temporary file, eliminating the TOCTOU race condition. The file descriptor returned by mkstemp() is wrapped with os.fdopen() to get a file object for writing, ensuring no window exists between filename generation and file creation where an attacker could intervene.

## Secure Code
```python
import tempfile
import json
import time
import os

def store_iot_sensor_telemetry(device_id, temperature, humidity, pressure):
    sensor_data = {'device': device_id, 'temp': temperature, 'humidity': humidity, 'pressure': pressure, 'timestamp': time.time()}
    fd, telemetry_file = tempfile.mkstemp(suffix='.json', prefix=f'sensor_{device_id}_')
    try:
        with os.fdopen(fd, 'w') as f:
            json.dump(sensor_data, f)
        upload_to_cloud_storage(telemetry_file)
    except Exception:
        os.unlink(telemetry_file)
        raise
    return telemetry_file
```
