{"title":"Insecure Temporary File Creation via tempfile.mktemp","language":"Python","severity":"Critical","cwe":"CWE-78","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    telemetry_file = tempfile.mktemp(suffix='.json', prefix=f'sensor_{device_id}_')\n    sensor_data = {\n        'device_id': device_id,\n        'metrics': {'temp': temperature, 'humidity': humidity, 'pressure': pressure},\n        'timestamp': os.popen('date +%s').read().strip()\n    }\n    with open(telemetry_file, 'w') as f:\n        json.dump(sensor_data, f)\n    os.system(f'curl -X POST https://iot-hub.cloud/ingest -d @{telemetry_file}')\n    return telemetry_file","explanation":"The function uses tempfile.mktemp() which creates a predictable temporary filename without actually creating the file, leading to a race condition vulnerability (TOCTOU). Additionally, the predictable filename is directly injected into an os.system() call without sanitization, enabling command injection if device_id contains shell metacharacters.","remediation":"The fix replaces tempfile.mktemp() with tempfile.mkstemp() which atomically creates the file and returns a file descriptor, eliminating the TOCTOU race condition. It also replaces os.system() with subprocess.run() using an argument list to prevent shell injection, validates device_id with a whitelist regex, and replaces os.popen('date +%s') with Python's time.time() to avoid unnecessary shell usage.","secure_code":"import tempfile\nimport json\nimport os\nimport time\nimport subprocess\nimport re\n\ndef store_iot_sensor_telemetry(device_id, temperature, humidity, pressure):\n    # Validate device_id to prevent injection\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    # Use mkstemp for secure temporary file creation (atomic, no race condition)\n    fd, telemetry_file = tempfile.mkstemp(suffix='.json', prefix=f'sensor_{device_id}_')\n    try:\n        sensor_data = {\n            'device_id': device_id,\n            'metrics': {'temp': temperature, 'humidity': humidity, 'pressure': pressure},\n            'timestamp': str(int(time.time()))\n        }\n        with os.fdopen(fd, 'w') as f:\n            json.dump(sensor_data, f)\n        \n        # Use subprocess with argument list to prevent command injection\n        subprocess.run(\n            ['curl', '-X', 'POST', 'https://iot-hub.cloud/ingest', '-d', f'@{telemetry_file}'],\n            check=True,\n            capture_output=True\n        )\n    except Exception:\n        raise\n    finally:\n        pass\n    \n    return telemetry_file"}