# Insecure Randomness via random.randint for Session Token Generation

Language: Python
Severity: High
CWE: CWE-338

## Source
11

## Flow
11-12

## Sink
11

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

app = Flask(__name__)
iot_device_sessions = {}

@app.route('/iot/provision', methods=['POST'])
def provision_device():
    device_id = request.json.get('device_id')
    device_key = random.randint(100000000000, 999999999999)
    session_token = hashlib.sha256(f"{device_id}:{device_key}".encode()).hexdigest()
    iot_device_sessions[device_id] = {'token': session_token, 'key': device_key}
    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
```python
import secrets
import hashlib
from flask import Flask, request, jsonify

app = Flask(__name__)
iot_device_sessions = {}

@app.route('/iot/provision', methods=['POST'])
def provision_device():
    device_id = request.json.get('device_id')
    device_key = secrets.token_hex(16)
    session_token = hashlib.sha256(f"{device_id}:{device_key}".encode()).hexdigest()
    iot_device_sessions[device_id] = {'token': session_token, 'key': device_key}
    return jsonify({'device_id': device_id, 'session_token': session_token, 'expires': 3600})
```
