highCWE-338A02:2021

Insecure Randomness

Using Math.random() for security-sensitive values like tokens or IDs is predictable and can be brute-forced.

How It Works

Math.random() uses a deterministic algorithm seeded from system time. It's not cryptographically random — given a few observed outputs, an attacker can predict past and future values. Using it for password reset tokens, session IDs, or CSRF tokens makes those values guessable.

Vulnerable Code
// BAD: Math.random is not cryptographically secure
const resetToken = Math.random().toString(36).slice(2);
const userId = 'user_' + Math.random().toString(36).slice(2);
Secure Code
// GOOD: use crypto.randomBytes for all security-sensitive values
import { randomBytes } from 'crypto';
const resetToken = randomBytes(32).toString('hex'); // 256 bits of real entropy
const userId = 'user_' + randomBytes(16).toString('hex');

Real-World Example

Multiple password reset vulnerabilities have been reported where tokens generated with Math.random() were brute-forced in seconds using V8 engine seed prediction techniques documented in academic research.

How to Prevent It

  • Always use crypto.randomBytes() (Node.js) or crypto.getRandomValues() (browser) for tokens and IDs
  • Use uuid v4 from the 'uuid' package for IDs — it uses crypto.randomUUID() internally
  • Minimum 128 bits of entropy for tokens, 256 bits preferred for high-value operations
  • Search your codebase for Math.random() and audit every usage

Affected Technologies

Node.jsjavascript

Data Hogo detects this vulnerability automatically.

Scan Your Repo Free

Related Vulnerabilities