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.
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) => {...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' hacking team, fill out this contact form.