# Insecure Temporary File Creation via tempfile.mktemp()

Language: Python
Severity: High
CWE: CWE-377

## Source
13

## Flow
13-14

## Sink
14

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

def store_iot_sensor_telemetry(device_id, temperature, humidity, pressure):
    telemetry_data = {
        'device_id': device_id,
        'temperature': temperature,
        'humidity': humidity,
        'pressure': pressure,
        'timestamp': os.popen('date +%s').read().strip()
    }
    temp_file = tempfile.mktemp(suffix='.json', prefix=f'iot_device_{device_id}_')
    with open(temp_file, 'w') as f:
        json.dump(telemetry_data, f)
    upload_to_cloud_storage(temp_file)
    os.remove(temp_file)
    return temp_file

def upload_to_cloud_storage(filepath):
    pass
```

## Explanation

The function uses tempfile.mktemp() which creates a predictable filename but doesn't create the file atomically, leading to a race condition vulnerability. An attacker can predict the filename and create a symlink to a sensitive file between mktemp() and open(), causing the application to overwrite arbitrary files with sensor data.

## Remediation

Replaced tempfile.mktemp() with tempfile.mkstemp() which atomically creates the file and returns a file descriptor, eliminating the race condition between filename generation and file creation. Also replaced the insecure os.popen('date +%s') call with time.time() for generating timestamps, and wrapped the upload/cleanup in a try/finally block for proper resource management.

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

def store_iot_sensor_telemetry(device_id, temperature, humidity, pressure):
    telemetry_data = {
        'device_id': device_id,
        'temperature': temperature,
        'humidity': humidity,
        'pressure': pressure,
        'timestamp': str(int(time.time()))
    }
    fd, temp_file = tempfile.mkstemp(suffix='.json', prefix=f'iot_device_{device_id}_')
    try:
        with os.fdopen(fd, 'w') as f:
            json.dump(telemetry_data, f)
        upload_to_cloud_storage(temp_file)
    finally:
        if os.path.exists(temp_file):
            os.remove(temp_file)
    return temp_file

def upload_to_cloud_storage(filepath):
    pass
```
