{"title":"Insecure Randomness in Token Generation via `random` Module","language":"Python","severity":"Critical","cwe":"CWE-338","source_lines":[10],"flow_lines":[10],"sink_lines":[10],"vulnerable_code":"import random\nimport string\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\niot_device_sessions = {}\n\n@app.route('/api/iot/provision', methods=['POST'])\ndef provision_device():\n    device_id = request.json.get('device_id')\n    device_key = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(48))\n    iot_device_sessions[device_id] = {'key': device_key, 'status': 'active'}\n    return jsonify({'device_id': device_id, 'provisioning_key': device_key, 'expires': 86400})","explanation":"The code uses Python's `random` module to generate cryptographic keys for IoT device authentication. The `random` module uses a Mersenne Twister PRNG which is predictable and not cryptographically secure, allowing attackers to predict future keys if they observe sufficient output or know the seed state.","remediation":"The fix replaces the insecure `random` module with Python's `secrets` module, which is designed for generating cryptographically secure random values. The `secrets.token_urlsafe(48)` function generates a URL-safe token with 48 bytes of randomness (resulting in a 64-character base64-encoded string), providing sufficient entropy for long-term IoT device authentication keys.","secure_code":"import secrets\nimport string\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\niot_device_sessions = {}\n\n@app.route('/api/iot/provision', methods=['POST'])\ndef provision_device():\n    device_id = request.json.get('device_id')\n    device_key = secrets.token_urlsafe(48)\n    iot_device_sessions[device_id] = {'key': device_key, 'status': 'active'}\n    return jsonify({'device_id': device_id, 'provisioning_key': device_key, 'expires': 86400})"}