{"title":"Insecure Temporary File Creation via tempfile.mktemp()","language":"Python","severity":"High","cwe":"CWE-377","source_lines":[13],"flow_lines":[13,14],"sink_lines":[14],"vulnerable_code":"import tempfile\nimport os\nimport json\n\ndef store_iot_sensor_telemetry(device_id, temperature, humidity, pressure):\n    telemetry_data = {\n        'device_id': device_id,\n        'temperature': temperature,\n        'humidity': humidity,\n        'pressure': pressure,\n        'timestamp': os.popen('date +%s').read().strip()\n    }\n    temp_file = tempfile.mktemp(suffix='.json', prefix=f'iot_device_{device_id}_')\n    with open(temp_file, 'w') as f:\n        json.dump(telemetry_data, f)\n    upload_to_cloud_storage(temp_file)\n    os.remove(temp_file)\n    return temp_file\n\ndef upload_to_cloud_storage(filepath):\n    pass","explanation":"The function uses tempfile.mktemp() which creates a predictable filename but doesn't create the file atomically, leading to a race condition vulnerability. An attacker can predict the filename and create a symlink to a sensitive file between mktemp() and open(), causing the application to overwrite arbitrary files with sensor data.","remediation":"Replaced tempfile.mktemp() with tempfile.mkstemp() which atomically creates the file and returns a file descriptor, eliminating the race condition between filename generation and file creation. Also replaced the insecure os.popen('date +%s') call with time.time() for generating timestamps, and wrapped the upload/cleanup in a try/finally block for proper resource management.","secure_code":"import tempfile\nimport os\nimport json\nimport time\n\ndef store_iot_sensor_telemetry(device_id, temperature, humidity, pressure):\n    telemetry_data = {\n        'device_id': device_id,\n        'temperature': temperature,\n        'humidity': humidity,\n        'pressure': pressure,\n        'timestamp': str(int(time.time()))\n    }\n    fd, temp_file = tempfile.mkstemp(suffix='.json', prefix=f'iot_device_{device_id}_')\n    try:\n        with os.fdopen(fd, 'w') as f:\n            json.dump(telemetry_data, f)\n        upload_to_cloud_storage(temp_file)\n    finally:\n        if os.path.exists(temp_file):\n            os.remove(temp_file)\n    return temp_file\n\ndef upload_to_cloud_storage(filepath):\n    pass"}