← Back to Baseline

MB-R023Cryptographically secure RNG

C03 Secure Coding Practices High

Security tokens, nonces, and session identifiers must use CSPRNG functions (random_bytes, random_int). Insecure RNG (rand, mt_rand) can be predicted by attackers, enabling replay or token guessing. Cryptographically secure generators are mandatory for sensitive operations.

Why it Matters

Security tokens, session IDs, and nonces must be unpredictable. If weak random functions like rand() or mt_rand() are used, attackers may guess the values and hijack sessions or bypass protections.

Cryptographically secure random number generators (CSPRNG) like random_bytes() or random_int() produce values that cannot be predicted. Using them ensures that tokens for authentication, password reset, and API access remain safe against brute force or guessing attacks.

Verification Steps

Manual

# Search custom code for weak RNG functions
grep -R "rand(" app/code
grep -R "mt_rand(" app/code

# Check if secure functions like random_bytes() or random_int() are used instead

Remediation / Fix Guidance

  1. Replace rand() and mt_rand() with random_int() for integers.
  2. Use random_bytes() when generating tokens or binary data.
  3. Base64-encode or hex-encode random bytes if a string output is needed.
  4. Review authentication, reset, and token generation logic to ensure CSPRNG is used consistently.

Examples

Fail Example
// Weak, predictable
$token = md5(mt_rand());
Pass Example
// Strong, unpredictable
$token = bin2hex(random_bytes(32));

References