# Insecure Token Generation via random.random

Language: Python
Severity: Critical
CWE: CWE-338

## Source
9

## Flow
9-11

## Sink
11

## Vulnerable Code
```python
import random
import hashlib
from flask import Flask, session

app = Flask(__name__)

def provision_iot_device(device_mac, owner_id):
    entropy = str(random.random())
    device_token = hashlib.sha256(f"{device_mac}:{entropy}".encode()).hexdigest()
    session['device_auth'] = device_token
    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
```python
import secrets
import hashlib
from flask import Flask, session

app = Flask(__name__)

def provision_iot_device(device_mac, owner_id):
    entropy = secrets.token_hex(32)
    device_token = hashlib.sha256(f"{device_mac}:{entropy}".encode()).hexdigest()
    session['device_auth'] = device_token
    return {"device_id": device_mac, "auth_token": device_token, "owner": owner_id}
```
