# Symlink Race Condition in Insecure Temporary File Creation

Language: Python
Severity: High
CWE: CWE-367

## Source
9

## Flow
9-10-11-12

## Sink
12

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

def export_iot_device_telemetry(device_id, metrics_data):
    temp_dir = tempfile.gettempdir()
    export_filename = f"device_{device_id}_telemetry.json"
    export_path = os.path.join(temp_dir, export_filename)
    if os.path.exists(export_path):
        os.remove(export_path)
    time.sleep(0.1)
    with open(export_path, 'w') as telemetry_file:
        telemetry_file.write(metrics_data)
    os.chmod(export_path, 0o644)
    return export_path
```

## Explanation

The code creates a predictable temporary file path using untrusted device_id input in a shared directory. Between checking if the file exists (line 9), deleting it (line 10), sleeping (line 11), and recreating it (line 12), an attacker can create a symlink at that path pointing to a sensitive file, causing the application to overwrite arbitrary files on the system.

## Remediation

The fix uses tempfile.mkstemp() which atomically creates a unique temporary file with restrictive permissions (0600), eliminating the race condition window entirely. It also sanitizes the device_id input to prevent path traversal attacks and removes the predictable filename pattern and sleep delay that widened the exploitation window.

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

def export_iot_device_telemetry(device_id, metrics_data):
    sanitized_device_id = re.sub(r'[^a-zA-Z0-9_\-]', '', str(device_id))
    if not sanitized_device_id:
        raise ValueError("Invalid device_id")
    
    prefix = f"device_{sanitized_device_id}_telemetry_"
    
    fd, export_path = tempfile.mkstemp(prefix=prefix, suffix='.json')
    try:
        with os.fdopen(fd, 'w') as telemetry_file:
            telemetry_file.write(metrics_data)
    except Exception:
        os.unlink(export_path)
        raise
    
    return export_path
```
