{"title":"Insecure Randomness via random.randint for Session Token Generation","language":"Python","severity":"High","cwe":"CWE-338","source_lines":[11],"flow_lines":[11,12],"sink_lines":[11],"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    device_key = random.randint(100000000000, 999999999999)\n    session_token = hashlib.sha256(f\"{device_id}:{device_key}\".encode()).hexdigest()\n    iot_device_sessions[device_id] = {'token': session_token, 'key': device_key}\n    return jsonify({'device_id': device_id, 'session_token': session_token, 'expires': 3600})","explanation":"The code uses random.randint() instead of secrets module to generate cryptographic keys for IoT device authentication. The random module uses Mersenne Twister which is predictable and not cryptographically secure, allowing attackers to predict future device keys and forge session tokens.","remediation":"The fix replaces the insecure `random.randint()` call with `secrets.token_hex(16)`, which generates a cryptographically secure random 32-character hexadecimal string (128 bits of entropy). The `secrets` module uses the operating system's cryptographically secure random number generator, making the generated keys unpredictable and resistant to sequence prediction attacks.","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    device_key = secrets.token_hex(16)\n    session_token = hashlib.sha256(f\"{device_id}:{device_key}\".encode()).hexdigest()\n    iot_device_sessions[device_id] = {'token': session_token, 'key': device_key}\n    return jsonify({'device_id': device_id, 'session_token': session_token, 'expires': 3600})"}