# Race Condition in Temporary File Creation via Insecure mktemp()

Language: Python
Severity: High
CWE: CWE-377

## Source
9

## Flow
9-11

## Sink
11

## Vulnerable Code
```python
import tempfile
import os
def export_sensor_telemetry(device_id, payload):
    tmp_path = tempfile.mktemp(suffix='.json', prefix=f'iot_{device_id}_')
    with open(tmp_path, 'w') as f:
        f.write(payload)
    os.chmod(tmp_path, 0o644)
    result = os.popen(f'gzip -c {tmp_path}').read()
    os.remove(tmp_path)
    return result
```

## Explanation

tempfile.mktemp() returns a filename without creating the file, introducing a TOCTOU (Time-Of-Check-Time-Of-Use) race condition window between path generation (line 4) and file creation (line 5). An attacker can exploit this window by creating a symlink at tmp_path pointing to a sensitive file like /etc/passwd, causing the subsequent open(tmp_path, 'w') to overwrite the target of the symlink with attacker-influenced or system-sensitive payload data.

## Remediation

The fix replaces the insecure tempfile.mktemp() with tempfile.NamedTemporaryFile(), which atomically creates and opens the file with secure permissions (mode 0o600 by default), eliminating the TOCTOU race window. The os.chmod(0o644) call is removed since the file no longer needs loosened permissions, and os.popen('gzip ...') is replaced with Python's built-in gzip.compress() to eliminate the shell command injection vector that existed due to unsanitized device_id interpolation into the shell command.

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

def export_sensor_telemetry(device_id, payload):
    with tempfile.NamedTemporaryFile(
        mode='w',
        suffix='.json',
        prefix=f'iot_{device_id}_',
        delete=False
    ) as f:
        tmp_path = f.name
        f.write(payload)

    try:
        with open(tmp_path, 'rb') as f_in:
            result = gzip.compress(f_in.read())
    finally:
        os.remove(tmp_path)

    return result
```
