logo

Database

Javascript Predictable Math Random

Description

Detects usage of Math.random() in JavaScript code, which generates predictable pseudo-random numbers that are not cryptographically secure. Using weak random number generators in security-sensitive contexts can lead to vulnerabilities like predictable tokens or keys.

Weakness:

034 - Insecure generation of random numbers

Category: Probabilistic Techniques

Detection Strategy

    Identifies calls to JavaScript's Math.random() function in source code

    Reports a vulnerability when Math.random() is used in security contexts like generating tokens, keys, or passwords

    Does not report Math.random() usage for non-security purposes like animations or non-critical randomization

    Recommends using crypto.getRandomValues() or other cryptographically secure alternatives instead

Vulnerable code example

const express = require('express');
const jwt = require('express-jwt');

// VULNERABLE: Using Math.random() for secrets is cryptographically weak
const jwtSecret = '' + Math.random();  

app.get('/login', (req, res) => {
    // VULNERABLE: Math.random() should not be used for security-sensitive values...

✅ Secure code example

const express = require('express');
const jwt = require('express-jwt');
const crypto = require('crypto');  // Use crypto for secure random values

// Generate a strong secret using crypto.randomBytes()
const jwtSecret = crypto.randomBytes(32).toString('hex');  // Secure random secret

app.get('/login', (req, res) => {...