{"title":"Insecure Temporary File Creation via tempfile.mktemp()","language":"Python","severity":"High","cwe":"CWE-377","source_lines":[5],"flow_lines":[5,13],"sink_lines":[13],"vulnerable_code":"import tempfile\nimport json\nimport os\n\ndef store_iot_sensor_telemetry(device_id, temperature, humidity, pressure):\n    temp_path = tempfile.mktemp(suffix='.json', prefix=f'iot_{device_id}_')\n    telemetry_data = {\n        'device': device_id,\n        'temp': temperature,\n        'humidity': humidity,\n        'pressure': pressure\n    }\n    with open(temp_path, 'w') as f:\n        json.dump(telemetry_data, f)\n    os.system(f'curl -X POST https://cloud.iot-platform.com/ingest -d @{temp_path}')\n    return temp_path","explanation":"The code uses tempfile.mktemp() which creates a predictable temporary filename without actually creating the file, allowing race condition attacks where an attacker can create a malicious file at that path before the legitimate code does. Additionally, the temp_path is used directly in os.system() with shell expansion, creating a command injection vulnerability if device_id contains shell metacharacters.","remediation":"The fix replaces tempfile.mktemp() with tempfile.mkstemp() which atomically creates the file with restrictive permissions (0600), eliminating the race condition vulnerability. It also replaces os.system() with subprocess.run() using an argument list to prevent shell injection, and adds input validation on device_id to ensure only safe characters are used in file paths and commands.","secure_code":"import tempfile\nimport json\nimport os\nimport subprocess\nimport re\n\ndef store_iot_sensor_telemetry(device_id, temperature, humidity, pressure):\n    # Validate device_id to prevent injection attacks\n    if not re.match(r'^[a-zA-Z0-9_-]+$', str(device_id)):\n        raise ValueError(\"Invalid device_id: only alphanumeric characters, hyphens, and underscores are allowed\")\n    \n    telemetry_data = {\n        'device': device_id,\n        'temp': temperature,\n        'humidity': humidity,\n        'pressure': pressure\n    }\n    \n    # Use mkstemp() which atomically creates the file with secure permissions\n    fd, temp_path = tempfile.mkstemp(suffix='.json', prefix=f'iot_{device_id}_')\n    try:\n        with os.fdopen(fd, 'w') as f:\n            json.dump(telemetry_data, f)\n        \n        # Use subprocess with argument list to avoid shell injection\n        subprocess.run(\n            ['curl', '-X', 'POST', 'https://cloud.iot-platform.com/ingest', '-d', f'@{temp_path}'],\n            check=True,\n            capture_output=True\n        )\n    finally:\n        # Clean up the temporary file\n        if os.path.exists(temp_path):\n            os.unlink(temp_path)\n    \n    return temp_path"}