logo

Database

Python Flask Use Of Insecure Randomness

Description

This detector identifies insecure use of randomness in Python Flask applications, specifically when cryptographically weak random number generators (e.g., Python's `random` module) are used in security-sensitive Flask contexts (e.g., generating tokens, secrets, or session values). Using non-cryptographic randomness in security-critical operations makes the generated values predictable and exploitable by attackers.

Weakness:

034 - Insecure generation of random numbers

Category: Probabilistic Techniques

Detection Strategy

    • The detector only activates when the analyzed file contains both Flask-related imports (e.g., `flask`) AND insecure random-related imports (e.g., `random`, `numpy.random`, etc.) simultaneously. If either import group is absent, no vulnerability is reported.

    • A vulnerability is reported on an **assignment statement** when the right-hand side uses a function or method from an insecure random library (e.g., `random.random()`, `random.randint()`) and the assigned value or its context is associated with a Flask security-sensitive operation (e.g., being used as a token, secret key, or session identifier).

    • A vulnerability is reported on a **function/method invocation** (outside of an assignment) when the call involves an insecure random function and is directly used in a Flask security-sensitive context, such as being passed as an argument to a Flask route handler, response builder, or security-related Flask API.

Vulnerable code example

import random
import flask
from flask import Flask, session, make_response, jsonify

app = Flask(__name__)

# VULNERABLE: secret key derived from non-cryptographic PRNG (Mersenne Twister)
app.secret_key = "".join(random.choices("abcdef", k=32))...

✅ Secure code example

import secrets
import os
import flask
from flask import Flask, session, make_response, jsonify

app = Flask(__name__)

# SAFE: os.urandom() uses the OS CSPRNG, not a predictable Mersenne Twister...