{"title":"Race Condition in Temporary File Creation via Insecure mktemp()","language":"Python","severity":"High","cwe":"CWE-377","source_lines":[9],"flow_lines":[9,11],"sink_lines":[11],"vulnerable_code":"import tempfile\nimport os\ndef export_sensor_telemetry(device_id, payload):\n    tmp_path = tempfile.mktemp(suffix='.json', prefix=f'iot_{device_id}_')\n    with open(tmp_path, 'w') as f:\n        f.write(payload)\n    os.chmod(tmp_path, 0o644)\n    result = os.popen(f'gzip -c {tmp_path}').read()\n    os.remove(tmp_path)\n    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":"import tempfile\nimport os\nimport gzip\n\ndef export_sensor_telemetry(device_id, payload):\n    with tempfile.NamedTemporaryFile(\n        mode='w',\n        suffix='.json',\n        prefix=f'iot_{device_id}_',\n        delete=False\n    ) as f:\n        tmp_path = f.name\n        f.write(payload)\n\n    try:\n        with open(tmp_path, 'rb') as f_in:\n            result = gzip.compress(f_in.read())\n    finally:\n        os.remove(tmp_path)\n\n    return result"}