{"title":"Insecure Token Generation via random.random","language":"Python","severity":"Critical","cwe":"CWE-338","source_lines":[9],"flow_lines":[9,11],"sink_lines":[11],"vulnerable_code":"import random\nimport hashlib\nfrom flask import Flask, session\n\napp = Flask(__name__)\n\ndef provision_iot_device(device_mac, owner_id):\n    entropy = str(random.random())\n    device_token = hashlib.sha256(f\"{device_mac}:{entropy}\".encode()).hexdigest()\n    session['device_auth'] = device_token\n    return {\"device_id\": device_mac, \"auth_token\": device_token, \"owner\": owner_id}","explanation":"The code uses random.random() to generate authentication tokens for IoT devices, which relies on Python's pseudorandom number generator that is predictable and not cryptographically secure. An attacker can predict the sequence of random values and forge device authentication tokens, allowing unauthorized access to IoT devices and cloud backend.","remediation":"The fix replaces the insecure `random.random()` with `secrets.token_hex(32)`, which uses a cryptographically secure random number generator (CSPRNG). This produces 32 bytes (64 hex characters) of unpredictable entropy, making it computationally infeasible for an attacker to predict or brute-force the generated device authentication tokens.","secure_code":"import secrets\nimport hashlib\nfrom flask import Flask, session\n\napp = Flask(__name__)\n\ndef provision_iot_device(device_mac, owner_id):\n    entropy = secrets.token_hex(32)\n    device_token = hashlib.sha256(f\"{device_mac}:{entropy}\".encode()).hexdigest()\n    session['device_auth'] = device_token\n    return {\"device_id\": device_mac, \"auth_token\": device_token, \"owner\": owner_id}"}