{"title":"Unsafe Temporary File Creation via tempfile.mktemp","language":"Python","severity":"High","cwe":"CWE-377","source_lines":[5],"flow_lines":[5,7],"sink_lines":[7],"vulnerable_code":"import tempfile\nimport json\n\ndef store_iot_sensor_telemetry(device_id, temperature, humidity, pressure):\n    telemetry_file = tempfile.mktemp(suffix='.json', prefix=f'sensor_{device_id}_')\n    sensor_data = {'device': device_id, 'temp': temperature, 'humidity': humidity, 'pressure': pressure, 'timestamp': time.time()}\n    with open(telemetry_file, 'w') as f:\n        json.dump(sensor_data, f)\n    upload_to_cloud_storage(telemetry_file)\n    return telemetry_file","explanation":"The code uses tempfile.mktemp() which creates a predictable filename without atomically creating the file, allowing a race condition (TOCTOU vulnerability). An attacker can predict the filename and create a malicious file or symlink between mktemp() and the open() call, leading to unauthorized file access or data manipulation.","remediation":"The fix replaces tempfile.mktemp() with tempfile.mkstemp(), which atomically creates and opens the temporary file, eliminating the TOCTOU race condition. The file descriptor returned by mkstemp() is wrapped with os.fdopen() to get a file object for writing, ensuring no window exists between filename generation and file creation where an attacker could intervene.","secure_code":"import tempfile\nimport json\nimport time\nimport os\n\ndef store_iot_sensor_telemetry(device_id, temperature, humidity, pressure):\n    sensor_data = {'device': device_id, 'temp': temperature, 'humidity': humidity, 'pressure': pressure, 'timestamp': time.time()}\n    fd, telemetry_file = tempfile.mkstemp(suffix='.json', prefix=f'sensor_{device_id}_')\n    try:\n        with os.fdopen(fd, 'w') as f:\n            json.dump(sensor_data, f)\n        upload_to_cloud_storage(telemetry_file)\n    except Exception:\n        os.unlink(telemetry_file)\n        raise\n    return telemetry_file"}