{"title":"Insecure Randomness via random.random() for API Key Generation","language":"Python","severity":"Critical","cwe":"CWE-338","source_lines":[9],"flow_lines":[9,10,11],"sink_lines":[11],"vulnerable_code":"import random\nimport string\nfrom flask import Flask, jsonify\n\napp = Flask(__name__)\n\n@app.route('/provision/iot-device', methods=['POST'])\ndef provision_iot_device():\n    device_secret = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(48))\n    device_id = f\"IOT-{random.randint(100000, 999999)}\"\n    mqtt_token = hex(int(random.random() * (10**16)))[2:]\n    return jsonify({\"device_id\": device_id, \"secret_key\": device_secret, \"mqtt_auth_token\": mqtt_token})","explanation":"The code uses Python's random module (random.choice(), random.randint(), random.random()) to generate cryptographic secrets for IoT device authentication. The random module uses a Mersenne Twister PRNG which is not cryptographically secure and predictable, allowing attackers to predict future device credentials after observing a sequence of generated values.","remediation":"The fix replaces all uses of the insecure `random` module with Python's `secrets` module, which is designed for generating cryptographically secure random values. `secrets.choice()` replaces `random.choice()` for the device secret, `secrets.randbelow()` replaces `random.randint()` for the device ID, and `secrets.token_hex()` replaces the `random.random()` hack for the MQTT token.","secure_code":"import secrets\nimport string\nfrom flask import Flask, jsonify\n\napp = Flask(__name__)\n\n@app.route('/provision/iot-device', methods=['POST'])\ndef provision_iot_device():\n    device_secret = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(48))\n    device_id = f\"IOT-{secrets.randbelow(900000) + 100000}\"\n    mqtt_token = secrets.token_hex(16)\n    return jsonify({\"device_id\": device_id, \"secret_key\": device_secret, \"mqtt_auth_token\": mqtt_token})"}