{"title":"Race Condition in File Creation via os.path.exists Check-Then-Use","language":"Python","severity":"High","cwe":"CWE-367","source_lines":[6],"flow_lines":[6,7],"sink_lines":[7],"vulnerable_code":"import os\nimport json\n\ndef provision_iot_device_cert(device_id, cert_data):\n    cert_path = f\"/var/iot/certs/{device_id}.pem\"\n    if not os.path.exists(cert_path):\n        with open(cert_path, 'w') as cert_file:\n            cert_file.write(cert_data)\n        os.chmod(cert_path, 0o600)\n        return {\"status\": \"provisioned\", \"path\": cert_path}\n    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":"import os\nimport json\n\ndef provision_iot_device_cert(device_id, cert_data):\n    cert_path = f\"/var/iot/certs/{device_id}.pem\"\n    try:\n        fd = os.open(cert_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)\n        try:\n            with os.fdopen(fd, 'w') as cert_file:\n                cert_file.write(cert_data)\n        except:\n            os.close(fd)\n            raise\n        return {\"status\": \"provisioned\", \"path\": cert_path}\n    except FileExistsError:\n        return {\"status\": \"already_exists\", \"path\": cert_path}"}