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

Language: Python
Severity: High
CWE: CWE-377

## Source
3

## Flow
3-4-5

## Sink
5

## Vulnerable Code
```python
import tempfile, os
def cache_sensor_payload(device_id, raw_data):
    tmp_path = tempfile.mktemp(suffix='.bin', prefix=f'iot_{device_id}_')
    if not os.path.exists(tmp_path):
        with open(tmp_path, 'wb') as fh:
            fh.write(raw_data)
    parsed = parse_binary_frame(tmp_path)
    os.remove(tmp_path)
    return parsed
```

## Explanation

tempfile.mktemp() returns a filename without atomically creating the file, introducing a Time-Of-Check-Time-Of-Use (TOCTOU) race condition. The os.path.exists() check on line 4 further widens the window between name generation and file creation, allowing an attacker to place a symlink or malicious file at tmp_path before open() is called on line 5, enabling arbitrary file writes or data injection.

## Remediation

Replaced `tempfile.mktemp()` with `tempfile.mkstemp()`, which atomically creates the file and returns an open file descriptor, eliminating the TOCTOU race condition. The file descriptor is wrapped with `os.fdopen()` for writing, and cleanup is placed in a `finally` block to ensure the temporary file is always removed. The redundant `os.path.exists()` check was also removed since `mkstemp()` guarantees the file is created exclusively.

## Secure Code
```python
import tempfile, os
def cache_sensor_payload(device_id, raw_data):
    fd, tmp_path = tempfile.mkstemp(suffix='.bin', prefix=f'iot_{device_id}_')
    try:
        with os.fdopen(fd, 'wb') as fh:
            fh.write(raw_data)
        parsed = parse_binary_frame(tmp_path)
    finally:
        os.remove(tmp_path)
    return parsed
```
