{"title":"Insecure Temporary File Creation via Predictable Filename Race Condition","language":"Python","severity":"High","cwe":"CWE-377","source_lines":[4],"flow_lines":[4,8],"sink_lines":[8],"vulnerable_code":"import os\nimport time\ndef export_iot_sensor_telemetry(device_id, metrics_data):\n    temp_filename = f\"/tmp/iot_telemetry_{device_id}_{int(time.time())}.json\"\n    if os.path.exists(temp_filename):\n        os.remove(temp_filename)\n    time.sleep(0.5)\n    with open(temp_filename, 'w') as telemetry_file:\n        telemetry_file.write(metrics_data)\n    process_and_upload_to_cloud(temp_filename)\n    os.remove(temp_filename)\n    return temp_filename","explanation":"The code creates a predictable temporary filename using device_id and timestamp, then checks for existence and sleeps before creating the file. An attacker can exploit the race condition window between the existence check and file creation to pre-create a malicious file or symlink at the predictable path, leading to arbitrary file write or symlink attack vulnerabilities.","remediation":"The fix uses tempfile.mkstemp() which atomically creates a temporary file with a unique, unpredictable name and returns a file descriptor, eliminating the race condition between checking existence and creating the file. The file descriptor is immediately used via os.fdopen() to write data, and cleanup is handled in a finally block to ensure the temporary file is always removed.","secure_code":"import os\nimport tempfile\nimport json\n\ndef export_iot_sensor_telemetry(device_id, metrics_data):\n    fd, temp_filename = tempfile.mkstemp(suffix='.json', prefix=f'iot_telemetry_{device_id}_', dir=None)\n    try:\n        with os.fdopen(fd, 'w') as telemetry_file:\n            telemetry_file.write(metrics_data)\n        process_and_upload_to_cloud(temp_filename)\n    finally:\n        if os.path.exists(temp_filename):\n            os.remove(temp_filename)\n    return temp_filename"}