{"title":"Insecure Session Token Generation via random.Random() Predictability","language":"Python","severity":"Critical","cwe":"CWE-338","source_lines":[10],"flow_lines":[10,11,12],"sink_lines":[12],"vulnerable_code":"import random\nimport hashlib\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\niot_device_sessions = {}\n\n@app.route('/iot/provision', methods=['POST'])\ndef provision_device():\n    device_id = request.json.get('device_id')\n    seed_val = int(device_id.split('-')[1])\n    rng = random.Random(seed_val)\n    session_key = hashlib.sha256(str(rng.getrandbits(128)).encode()).hexdigest()\n    iot_device_sessions[device_id] = session_key\n    return jsonify({'device_id': device_id, 'session_key': session_key, 'status': 'provisioned'})","explanation":"The application uses user-controlled device_id input to derive a seed for random.Random(), making the random number generation predictable. An attacker who knows or can predict the device_id pattern can reproduce the exact same session key, allowing unauthorized access to IoT devices.","remediation":"The fix replaces the predictable random.Random() seeded with user-controlled input with secrets.token_hex(32), which uses the operating system's cryptographically secure random number generator (CSPRNG) to produce a 256-bit session key. This ensures the session key has full entropy and cannot be predicted or reproduced by an attacker regardless of knowledge of the device_id.","secure_code":"import secrets\nimport hashlib\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\niot_device_sessions = {}\n\n@app.route('/iot/provision', methods=['POST'])\ndef provision_device():\n    device_id = request.json.get('device_id')\n    if not device_id or not isinstance(device_id, str):\n        return jsonify({'error': 'Invalid device_id'}), 400\n    session_key = secrets.token_hex(32)\n    iot_device_sessions[device_id] = session_key\n    return jsonify({'device_id': device_id, 'session_key': session_key, 'status': 'provisioned'})"}