{"title":"Insecure Randomness via random.choice() for Security Token Generation","language":"Python","severity":"High","cwe":"CWE-330","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    auth_token = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(32))\n    iot_device_sessions[device_id] = {'token': auth_token, 'provisioned': True}\n    return jsonify({'device_id': device_id, 'auth_token': auth_token, 'status': 'provisioned'})","explanation":"The code uses random.choice() from Python's random module to generate authentication tokens for IoT devices. The random module uses a Mersenne Twister PRNG which is cryptographically weak and predictable, making the generated tokens susceptible to brute-force and prediction attacks by attackers who can observe previous tokens.","remediation":"The fix replaces the insecure random.choice() with secrets.token_urlsafe(32), which uses a cryptographically secure random number generator (CSPRNG) to produce unpredictable tokens. The secrets module is specifically designed for generating security-sensitive tokens and is resistant to prediction attacks, unlike the Mersenne Twister PRNG used by the random module.","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    auth_token = secrets.token_urlsafe(32)\n    iot_device_sessions[device_id] = {'token': auth_token, 'provisioned': True}\n    return jsonify({'device_id': device_id, 'auth_token': auth_token, 'status': 'provisioned'})"}