logo

Database

Php Insecure Random Functions

Description

Detects insecure usage of PHP hash functions where weak random data is used as input. Using predictable or weak random data to generate hashes can make the resulting hash values guessable, potentially compromising security mechanisms that rely on these hashes like token generation or password storage.

Weakness:

034 - Insecure generation of random numbers

Category: Probabilistic Techniques

Detection Strategy

    Identifies calls to PHP's hash() function in the code

    Checks if the second argument (data parameter) of the hash function contains or is derived from weak random data sources

    Reports a vulnerability when hash() is called with random data as input, since this could produce predictable hash outputs

Vulnerable code example

<?php
// Using insecure random number generators for cryptographic hashing
$weak_random = mt_rand(1, 1000); // mt_rand() is not cryptographically secure
$bad_hash = hash('sha512', $weak_random, true); // Vulnerable: hash derived from weak random source

$unsafe_random = uniqid(mt_rand(1, mt_getrandmax())); // Another insecure random generation
$another_bad_hash = hash('sha256', $unsafe_random, true); // Vulnerable: using uniqid+mt_rand for crypto

✅ Secure code example

<?php
// Using cryptographically secure random number generation
$secure_random = random_bytes(16); // Use random_bytes() for secure random values
$safe_hash = hash('sha512', $secure_random, true); // Safe: hash derived from cryptographically secure source

$secure_random2 = random_int(1, 1000); // Use random_int() for secure random integers
$safe_hash2 = hash('sha256', $secure_random2, true); // Safe: using cryptographically secure random source