{"title":"Insecure Session Token Generation via random.random()","language":"Python","severity":"High","cwe":"CWE-338","source_lines":[11],"flow_lines":[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_smart_device():\n    device_id = request.json.get('device_id')\n    device_type = request.json.get('type')\n    nonce = str(random.random() * 999999)\n    provision_token = hashlib.sha256(f\"{device_id}:{nonce}\".encode()).hexdigest()\n    iot_device_sessions[device_id] = {'token': provision_token, 'type': device_type}\n    return jsonify({'provision_token': provision_token, 'status': 'provisioned'})","explanation":"The code uses random.random() to generate a nonce for session tokens, which is cryptographically weak and predictable. Python's random module uses the Mersenne Twister algorithm, which is not suitable for security purposes as attackers can predict future values after observing a sequence of outputs, allowing them to forge valid provision tokens for IoT devices.","remediation":"The fix replaces the insecure `random.random()` call with `secrets.token_hex(32)`, which generates a cryptographically secure random nonce using the operating system's CSPRNG. This ensures that the nonce cannot be predicted by an attacker even if they observe previous token values, making it impossible to forge valid provision tokens for IoT devices.","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_smart_device():\n    device_id = request.json.get('device_id')\n    device_type = request.json.get('type')\n    nonce = secrets.token_hex(32)\n    provision_token = hashlib.sha256(f\"{device_id}:{nonce}\".encode()).hexdigest()\n    iot_device_sessions[device_id] = {'token': provision_token, 'type': device_type}\n    return jsonify({'provision_token': provision_token, 'status': 'provisioned'})"}