# Insecure Temporary File Creation via Predictable Filename Race Condition

Language: Python
Severity: High
CWE: CWE-377

## Source
4

## Flow
4-8

## Sink
8

## Vulnerable Code
```python
import os
import time
def export_iot_sensor_telemetry(device_id, metrics_data):
    temp_filename = f"/tmp/iot_telemetry_{device_id}_{int(time.time())}.json"
    if os.path.exists(temp_filename):
        os.remove(temp_filename)
    time.sleep(0.5)
    with open(temp_filename, 'w') as telemetry_file:
        telemetry_file.write(metrics_data)
    process_and_upload_to_cloud(temp_filename)
    os.remove(temp_filename)
    return temp_filename
```

## Explanation

The code creates a predictable temporary filename using device_id and timestamp, then checks for existence and sleeps before creating the file. An attacker can exploit the race condition window between the existence check and file creation to pre-create a malicious file or symlink at the predictable path, leading to arbitrary file write or symlink attack vulnerabilities.

## Remediation

The fix uses tempfile.mkstemp() which atomically creates a temporary file with a unique, unpredictable name and returns a file descriptor, eliminating the race condition between checking existence and creating the file. The file descriptor is immediately used via os.fdopen() to write data, and cleanup is handled in a finally block to ensure the temporary file is always removed.

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

def export_iot_sensor_telemetry(device_id, metrics_data):
    fd, temp_filename = tempfile.mkstemp(suffix='.json', prefix=f'iot_telemetry_{device_id}_', dir=None)
    try:
        with os.fdopen(fd, 'w') as telemetry_file:
            telemetry_file.write(metrics_data)
        process_and_upload_to_cloud(temp_filename)
    finally:
        if os.path.exists(temp_filename):
            os.remove(temp_filename)
    return temp_filename
```
