{"title":"Insecure Temporary File Creation via tempfile.mktemp()","language":"Python","severity":"High","cwe":"CWE-377","source_lines":[1],"flow_lines":[1,6,1,13],"sink_lines":[6,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'iot_{device_id}_')\n    sensor_data = {\n        'device': 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://cloud.iot-platform.com/ingest -d @{telemetry_file}')\n    return telemetry_file","explanation":"The code uses tempfile.mktemp() which creates a predictable filename without actually creating the file, leading to a race condition where an attacker can create a symlink or file at that path before the legitimate code uses it. Additionally, the untrusted device_id parameter flows into both the filename and the os.system() command, enabling command injection attacks.","remediation":"The fix replaces tempfile.mktemp() with tempfile.mkstemp() which atomically creates and opens the file, eliminating the race condition. The device_id is sanitized with a whitelist regex to prevent path traversal and injection. Additionally, os.system() and os.popen() are replaced with subprocess.run() with an argument list and time.time() respectively, preventing command injection vulnerabilities.","secure_code":"import tempfile\nimport json\nimport os\nimport re\nimport time\nimport subprocess\n\ndef store_iot_sensor_telemetry(device_id, temperature, humidity, pressure):\n    # Sanitize device_id to prevent injection attacks\n    sanitized_device_id = re.sub(r'[^a-zA-Z0-9_-]', '', str(device_id))\n    if not sanitized_device_id:\n        raise ValueError(\"Invalid device_id\")\n\n    # Use mkstemp for secure temporary file creation (atomically creates the file)\n    fd, telemetry_file = tempfile.mkstemp(suffix='.json', prefix=f'iot_{sanitized_device_id}_')\n    try:\n        sensor_data = {\n            'device': sanitized_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://cloud.iot-platform.com/ingest', '-d', f'@{telemetry_file}'],\n            check=True,\n            capture_output=True,\n            timeout=30\n        )\n    except Exception:\n        os.unlink(telemetry_file)\n        raise\n    return telemetry_file"}