{"title":"Insecure Temporary File Creation via tempfile.mktemp()","language":"Python","severity":"High","cwe":"CWE-377","source_lines":[6],"flow_lines":[6,7,9],"sink_lines":[7],"vulnerable_code":"import tempfile\nimport json\nimport os\n\ndef export_iot_device_telemetry(device_id, sensor_data):\n    temp_path = tempfile.mktemp(suffix='.json', prefix=f'iot_telemetry_{device_id}_')\n    with open(temp_path, 'w') as f:\n        json.dump({'device': device_id, 'metrics': sensor_data, 'timestamp': sensor_data.get('ts')}, f)\n    upload_to_cloud_storage(temp_path)\n    os.remove(temp_path)\n    return temp_path\n\ndef upload_to_cloud_storage(file_path):\n    pass","explanation":"The code uses tempfile.mktemp() which creates a predictable filename but doesn't actually create the file, leaving a race condition window between line 6 (getting the path) and line 7 (opening the file). An attacker can predict the filename and create a symlink or file at that path before line 7 executes, potentially redirecting sensitive IoT telemetry data to an attacker-controlled location or reading the data before it's uploaded.","remediation":"Replaced tempfile.mktemp() with tempfile.mkstemp(), which atomically creates and opens the temporary file with exclusive access (O_EXCL), eliminating the race condition between filename generation and file creation. The file descriptor is wrapped with os.fdopen() for convenient writing, and cleanup is handled in a finally block to ensure the temp file is removed even if an error occurs during upload.","secure_code":"import tempfile\nimport json\nimport os\n\ndef export_iot_device_telemetry(device_id, sensor_data):\n    fd, temp_path = tempfile.mkstemp(suffix='.json', prefix=f'iot_telemetry_{device_id}_')\n    try:\n        with os.fdopen(fd, 'w') as f:\n            json.dump({'device': device_id, 'metrics': sensor_data, 'timestamp': sensor_data.get('ts')}, f)\n        upload_to_cloud_storage(temp_path)\n    finally:\n        if os.path.exists(temp_path):\n            os.remove(temp_path)\n    return temp_path\n\ndef upload_to_cloud_storage(file_path):\n    pass"}