{"title":"Insecure Session Token Generation via random.choice()","language":"Python","severity":"High","cwe":"CWE-338","source_lines":[10],"flow_lines":[10],"sink_lines":[10],"vulnerable_code":"import random\nimport string\nfrom flask import Flask, session, request, jsonify\n\napp = Flask(__name__)\napp.secret_key = 'iot_device_mgmt_key'\n\n@app.route('/api/device/provision', methods=['POST'])\ndef provision_iot_device():\n    device_id = request.json.get('device_id')\n    device_token = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(24))\n    session['device_auth_token'] = device_token\n    session['device_id'] = device_id\n    return jsonify({'status': 'provisioned', 'auth_token': device_token, 'device': device_id})","explanation":"The code uses Python's random.choice() which relies on the Mersenne Twister algorithm, a cryptographically insecure pseudo-random number generator. This makes the generated device authentication tokens predictable if an attacker can observe a sequence of tokens or knows the initial seed state, allowing them to forge valid tokens for unauthorized device access.","remediation":"The fix replaces the insecure random.choice() with Python's secrets module, which uses a cryptographically secure random number generator (CSPRNG). Additionally, secrets.token_urlsafe(32) generates a 32-byte (256-bit) URL-safe token that is unpredictable and resistant to brute-force attacks. The hardcoded Flask secret_key was also replaced with a securely generated random key.","secure_code":"import secrets\nimport string\nfrom flask import Flask, session, request, jsonify\n\napp = Flask(__name__)\napp.secret_key = secrets.token_hex(32)\n\n@app.route('/api/device/provision', methods=['POST'])\ndef provision_iot_device():\n    device_id = request.json.get('device_id')\n    device_token = secrets.token_urlsafe(32)\n    session['device_auth_token'] = device_token\n    session['device_id'] = device_id\n    return jsonify({'status': 'provisioned', 'auth_token': device_token, 'device': device_id})"}