logo

Database

Python Use Of Insecure Randomness

Description

This detector identifies use of cryptographically insecure random number generators in security-sensitive contexts. Using weak randomness sources like Python's random module for cryptographic operations can lead to predictable values that attackers can exploit to compromise security mechanisms.

Weakness:

034 - Insecure generation of random numbers

Category: Probabilistic Techniques

Detection Strategy

    Code imports cryptographic libraries (cryptography, pycrypto, etc.)

    Code imports insecure random functions from Python's random module

    A cryptographic function receives input that traces back to an insecure random number generator

    The insecure random value is passed to security-sensitive parameters without proper sanitization

Vulnerable code example

import random
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from Crypto.Cipher import AES
import os

def vulnerable_salt():
    # VULNERABLE: random.randbytes() uses non-cryptographic PRNG
    salt = random.randbytes(16)...

✅ Secure code example

import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from Crypto.Cipher import AES

def secure_salt():
    # SAFE: os.urandom() provides cryptographically secure randomness
    salt = os.urandom(16)
    return salt...