# Race Condition in File Creation via os.path.exists Check-Then-Use

Language: Python
Severity: High
CWE: CWE-367

## Source
6

## Flow
6-7

## Sink
7

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

def provision_iot_device_cert(device_id, cert_data):
    cert_path = f"/var/iot/certs/{device_id}.pem"
    if not os.path.exists(cert_path):
        with open(cert_path, 'w') as cert_file:
            cert_file.write(cert_data)
        os.chmod(cert_path, 0o600)
        return {"status": "provisioned", "path": cert_path}
    return {"status": "already_exists", "path": cert_path}
```

## Explanation

This code contains a classic Time-of-Check-Time-of-Use (TOCTOU) race condition. Between the os.path.exists() check on line 6 and the file creation on line 7, an attacker can create a malicious file or symbolic link at cert_path, potentially causing the application to overwrite sensitive files or write certificates to attacker-controlled locations.

## Remediation

The fix replaces the non-atomic os.path.exists() check followed by open() with a single atomic os.open() call using O_CREAT | O_EXCL flags. O_EXCL ensures the call fails if the file already exists (including symlinks), eliminating the TOCTOU race window. The permissions (0o600) are set atomically at creation time rather than applied after the fact with a separate chmod call.

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

def provision_iot_device_cert(device_id, cert_data):
    cert_path = f"/var/iot/certs/{device_id}.pem"
    try:
        fd = os.open(cert_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        try:
            with os.fdopen(fd, 'w') as cert_file:
                cert_file.write(cert_data)
        except:
            os.close(fd)
            raise
        return {"status": "provisioned", "path": cert_path}
    except FileExistsError:
        return {"status": "already_exists", "path": cert_path}
```
