01 //Introduction
Most security bugs are unsafe inputs. Insecure randomness is the opposite: it is an unsafe output. The system is working exactly as its author intended, but the numbers it produces are predictable to anyone who understands how they were generated. Predictable numbers used as passwords, session IDs, password-reset tokens, crypto nonces, or CSRF tokens do not become any less predictable when wrapped in base64 or SHA-256 — they simply become predictable strings of base64 or hex.
The failure is usually not that a developer chose the wrong library. It is that they reached for the obvious function — Math.random(), rand(), java.util.Random, random.random() — without knowing that "random" in a programming language standard library almost always means "statistically random for simulations and games" and almost never means "unpredictable to an adversary." Those are two different specifications, and conflating them is the single root cause behind this entire bug class.
Two decades of real incidents make the point. In 2008, the Debian OpenSSL maintainer commented out a line that fed uninitialised memory into the PRNG, reducing the seed space to the PID (15 bits). Every SSH key, SSL certificate, and DNSSEC key generated on an affected Debian or Ubuntu system for the next 20 months was one of 32,768 possible keys. In 2010, a Hacker News contributor demonstrated that the site's session cookies were seeded from a millisecond timestamp and could be guessed within an hour. The fix in both cases was a one-line API swap — but the systems were built on the wrong abstraction from the start.
A reviewer sees `resetToken = Math.random().toString(36).slice(2)`. The token is 10 characters of base36 (~52 bits). Is that enough entropy?
02 //PRNG vs CSPRNG
Every language ships at least two random-number APIs: one designed for speed and statistical quality (good enough to pass the dieharder test suite, fine for a Monte Carlo simulation or a video game), and one designed to be unpredictable to an adversary who observes outputs. They look almost identical at the call site, and the unsafe one is almost always the shorter name.
Math.random()— JSrand() / random()— C, libcjava.util.Random— Javarandom.random()— Pythonmath/rand— Go (pre-1.20)
Fast. Seeded once. Internal state recoverable from a handful of outputs. Built for simulations, not secrets.
crypto.randomBytes— Nodewindow.crypto.getRandomValues— Browsersecrets— Python 3.6+java.security.SecureRandom— Javacrypto/rand— Go
Reseeded from OS entropy (/dev/urandom, getrandom(), BCryptGenRandom). State recovery is computationally infeasible.
If a value ever gates access, identifies a user, signs something, or becomes a secret — it must come from the right-hand column. There is no middle ground.
Safe vs Unsafe Randomness APIs by Language
| Language | Unsafe (statistical) | Safe (cryptographic) |
|---|---|---|
| JavaScript (Node) | Math.random() | crypto.randomBytes, crypto.randomUUID, crypto.randomInt |
| JavaScript (Browser) | Math.random() | window.crypto.getRandomValues, crypto.randomUUID |
| Python | random module (random.random, random.choice, random.randint) | secrets module (secrets.token_urlsafe, secrets.token_hex, secrets.choice) |
| Java | java.util.Random, Math.random() | java.security.SecureRandom |
| Go | math/rand (pre-1.22), math/rand/v2 | crypto/rand |
| Ruby | rand, Random.new | SecureRandom (hex, urlsafe_base64, uuid) |
| PHP | rand, mt_rand | random_bytes, random_int |
| C / C++ | rand, random, drand48 | getrandom(2), arc4random_buf, BCryptGenRandom |
| .NET / C# | System.Random | RandomNumberGenerator.GetBytes, RandomNumberGenerator.GetInt32 |
| Rust | rand::thread_rng (unless seeded from OsRng) | rand::rngs::OsRng, getrandom crate |
The practical review move is simple: treat every use of the left column as a finding by default, and ask the author to justify why the output is not flowing into a security-sensitive sink. The burden of proof is on the unsafe API, not on the reviewer. This inverts the usual "innocent until proven guilty" and is the right default because the cost of a false positive (a conversation) is trivial compared to the cost of a false negative (an account-takeover CVE).
1// UNSAFE — statistical PRNG (xorshift128+ in V8).
2// State is recoverable from ~5 consecutive outputs.
3const token = Math.random().toString(36).slice(2, 18);
4
5// SAFE — cryptographic PRNG, 128 bits of entropy.
6import { randomBytes } from 'node:crypto';
7const token = randomBytes(16).toString('base64url');
8
9// SAFE, short — 128-bit UUID v4 from the OS CSPRNG.
10import { randomUUID } from 'node:crypto';
11const id = randomUUID();
12
13// SAFE, integer — crypto.randomInt is unbiased by rejection sampling.
14import { randomInt } from 'node:crypto';
15const otp = randomInt(0, 1_000_000).toString().padStart(6, '0');crypto.randomUUID() in hot paths under the belief that it is slow. On modern Node it is within a factor of 2 of Math.random() on a single thread and trivially fast for any workload that is not generating millions of IDs per second per core. The performance argument is almost never load-bearing; the security argument always is.In Python, `random.choice(string.ascii_letters + string.digits)` is called in a loop to build a 32-character API key. What is the correct review comment?
03 //Predictable Seeds & State Recovery
A PRNG is a pure function from state to (state, output). Two generators in the same state will emit the same outputs forever. So the security of a PRNG-derived secret reduces to one question: how much entropy is in the initial state, and how easy is it for an attacker to reproduce it? When the seed is a timestamp, a process ID, a millisecond counter, or anything an attacker can observe or narrow down, the whole chain collapses.
A non-cryptographic PRNG is a deterministic function of its state. "It looks random in my tests" is not a property that matters — what matters is whether an adversary, given what they can observe, can compute future outputs faster than guessing.
1/* C — the textbook anti-pattern. time(NULL) is a 32-bit second-resolution
2 timestamp. An attacker who knows roughly when a token was generated
3 has at most a few thousand candidate seeds to try. */
4#include <stdlib.h>
5#include <time.h>
6srand(time(NULL));
7int token = rand(); // fully determined by the second of issuance
8
9/* Slightly worse: seed the generator inside a loop. Every iteration in
10 the same second gets the SAME output. */
11for (int i = 0; i < 10; i++) {
12 srand(time(NULL));
13 printf("%d\n", rand()); // prints the same number 10 times
14}1// Math.random in V8 is xorshift128+ (not MT), but the same principle
2// applies: with enough observed outputs, the internal state is solvable.
3//
4// Proof-of-concept attack shape:
5// 1. Attacker signs up, receives a password-reset token minted from
6// Math.random().
7// 2. Attacker observes 5 consecutive 64-bit outputs from the same
8// process (e.g. by requesting 5 tokens back-to-back).
9// 3. Attacker solves the xorshift128+ recurrence for the internal
10// 64-bit state pair (s0, s1) using a SAT solver or z3. This is a
11// well-documented exercise; multiple open-source tools do it.
12// 4. Attacker rolls the state backwards or forwards and computes the
13// NEXT victim's reset token before they click the email link.
14//
15// Mitigation: do not generate security tokens from Math.random().
16// There is no quantity of hashing/encoding/length that fixes this.SecureRandom sr = new SecureRandom(Long.toString(System.currentTimeMillis()).getBytes());. Even though the class name says "secure," the explicit seed constructor replaces the OS entropy with the caller-supplied bytes. The output is now deterministic from a millisecond timestamp. Always use SecureRandom.getInstanceStrong() or the no-arg constructor, which reseeds from the OS.1// UNSAFE — replaces OS entropy with a timestamp. Output fully recoverable.
2SecureRandom sr = new SecureRandom(
3 Long.toString(System.currentTimeMillis()).getBytes());
4byte[] token = new byte[32];
5sr.nextBytes(token);
6
7// SAFE — no seed argument: the RNG reseeds from the OS on construction.
8SecureRandom sr = new SecureRandom();
9byte[] token = new byte[32];
10sr.nextBytes(token);
11
12// BEST — getInstanceStrong() picks the algorithm configured in
13// securerandom.strongAlgorithms for this platform. Blocks on
14// Linux if /dev/random is starved; use with care on boot.
15SecureRandom sr = SecureRandom.getInstanceStrong();A service generates 6-digit email verification codes using `Math.floor(Math.random() * 1_000_000)`. Logs show tokens issued at ~50 per second. Why is changing this to crypto.randomInt a higher-priority fix than increasing the length to 8 digits?
04 //Security-Sensitive Sinks
Not every random number in a codebase is security-relevant. A jittered retry timeout, a shuffle in a game, a particle-effect seed — these are fine with Math.random(). The review job is to identify the sinks where the output flows into a security decision, and demand a cryptographic source there. The list below covers the sinks that account for almost every real-world CVE in this class.
Where Randomness Becomes Security
| Sink | Failure mode if predictable | Minimum entropy |
|---|---|---|
| Session IDs | Attacker predicts the next session ID and impersonates a user | 128 bits |
| Password-reset tokens | Attacker guesses a victim’s token before they click the email link | 128 bits |
| Email verification codes | Attacker bypasses email confirmation and activates attacker-owned accounts | 128 bits or strict rate-limit on short codes |
| CSRF tokens | Attacker forges a valid CSRF token and bypasses the protection entirely | 128 bits |
| OAuth state / PKCE verifier | CSRF on the authorization callback; PKCE verifier must be unguessable by a concurrent attacker | 128 bits (PKCE spec requires 43-128 char high-entropy string) |
| JWT jti / nonce claims | Replay protection fails; two tokens collide | 128 bits |
| Crypto IVs / nonces (AES-GCM, ChaCha20) | Nonce reuse with the same key breaks confidentiality AND integrity | 96 bits random OR a strict monotonic counter |
| TLS / SSH / signing keys | Key compromise, universal forgery | 256 bits seed material from OS CSPRNG |
| Temporary filenames (mktemp) | Symlink / race attacks if attacker predicts the path in a shared tmpdir | Use O_EXCL / mkstemp, do not roll your own |
| Captcha / OTP | Attacker predicts the challenge or bypass the second factor | 128 bits or short code + strict rate-limit + expiry |
| Password generators | Generated passwords are guessable by anyone who observes a few | 128+ bits from a CSPRNG |
1// WRONG — password reset token from Math.random.
2function makeResetToken(): string {
3 return Math.random().toString(36).slice(2, 14);
4}
5
6// WRONG — session id from Date.now() + counter.
7let counter = 0;
8function makeSessionId(): string {
9 return (Date.now().toString(36) + (counter++).toString(36));
10}
11
12// WRONG — using Math.random for an AES-GCM IV. NONCE REUSE.
13const iv = Buffer.alloc(12);
14for (let i = 0; i < 12; i++) iv[i] = Math.floor(Math.random() * 256);
15
16// RIGHT — all three fixed with the standard library.
17import { randomBytes, randomUUID } from 'node:crypto';
18const resetToken = randomBytes(32).toString('base64url'); // 256 bits
19const sessionId = randomUUID(); // 122 bits random
20const iv = randomBytes(12); // 96-bit GCM noncecrypto.randomBytes encoded to base64url. This is a surprisingly common confusion in Java codebases that reach for UUID.randomUUID() (v4, safe) vs UUIDs.timeBased() from Cassandra's driver (v1, not safe).Which of the following is the ONLY acceptable randomness source for an AES-GCM initialization vector?
05 //Bias & Modulo Reduction
Even when the underlying generator is a CSPRNG, the way a developer reduces its output to a smaller range can reintroduce bias. The classic bug is rand() % N: if N does not divide RAND_MAX + 1, the low residues are slightly more likely than the high ones. For most ranges this is a small statistical bias, but for short ranges — lottery picks, shuffled-deck positions, OTP digits — it is often enough to give an attacker a measurable edge.
1/* Suppose RAND_MAX = 32767 (a common libc value) and we do: rand() % 10
2 There are 32768 possible rand() outputs. 32768 / 10 = 3276 remainder 8.
3 So the residues 0..7 each occur 3277 times, and residues 8..9 each
4 occur 3276 times. Bias is small (~0.03%).
5
6 But try rand() % 30000 on the same RNG:
7 32768 / 30000 = 1 remainder 2768.
8 Residues 0..2767 each occur 2 times; residues 2768..29999 occur 1 time.
9 Residues 0..2767 are now roughly TWICE as likely as any other. */
10
11/* Correct: rejection sampling. */
12int randrange(int n) {
13 int limit = RAND_MAX - (RAND_MAX % n); // largest multiple of n <= RAND_MAX
14 int r;
15 do { r = rand(); } while (r >= limit);
16 return r % n;
17}Languages that give you a proper bounded-integer API hide this detail from you. Use them. crypto.randomInt(min, max) in Node, secrets.randbelow(n) in Python, java.security.SecureRandom.nextInt(int) in Java, rand.Int(rand.Reader, max) in Go — all of these perform the correct rejection sampling internally. Rolling your own with % is almost always wrong and almost never necessary.
1// Node.js — crypto.randomInt does rejection sampling under the hood.
2import { randomInt } from 'node:crypto';
3const diceRoll = randomInt(1, 7); // 1..6 inclusive, unbiased
4const otp = randomInt(0, 1_000_000); // 0..999999, unbiased
5
6// Python — secrets.randbelow(n) is the canonical API.
7import secrets
8dice_roll = secrets.randbelow(6) + 1
9otp = secrets.randbelow(1_000_000)
10
11// Java — SecureRandom.nextInt(bound) is unbiased.
12import java.security.SecureRandom;
13SecureRandom sr = new SecureRandom();
14int diceRoll = sr.nextInt(6) + 1;
15
16// Go — crypto/rand Int returns a bignum in [0, max).
17import ("crypto/rand"; "math/big")
18n, _ := rand.Int(rand.Reader, big.NewInt(6))
19diceRoll := int(n.Int64()) + 1Math.random() has two problems, but the catastrophic one is the source. Fix the source first; then fix the reduction. A reviewer who flags % 1000000 on a CSPRNG but misses the same pattern on Math.random() has their priorities inverted.A Node service generates 6-digit OTPs via `crypto.randomBytes(4).readUInt32BE(0) % 1_000_000`. Is that safe?
06 //Prevention Basics
The good news about insecure randomness is that the fix is almost always a one-line API swap, and every modern language ships the right API in its standard library. The review rule you want your team to internalise is: the only acceptable source of security-relevant randomness is the language's documented CSPRNG API, called with no explicit seed.
Safe Defaults Per Language
| Need | Node / TS | Python | Java | Go | Ruby | PHP |
|---|---|---|---|---|---|---|
| Random bytes | crypto.randomBytes(n) | secrets.token_bytes(n) | new SecureRandom().nextBytes(b) | crypto/rand.Read(b) | SecureRandom.random_bytes(n) | random_bytes(n) |
| URL-safe token | crypto.randomBytes(32).toString('base64url') | secrets.token_urlsafe(32) | Base64.getUrlEncoder().encodeToString(bytes) | base64.RawURLEncoding.EncodeToString(b) | SecureRandom.urlsafe_base64(32) | rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=') |
| Bounded integer | crypto.randomInt(0, n) | secrets.randbelow(n) | new SecureRandom().nextInt(n) | rand.Int(rand.Reader, big.NewInt(n)) | SecureRandom.random_number(n) | random_int(0, n-1) |
| UUID v4 | crypto.randomUUID() | uuid.uuid4() | UUID.randomUUID() | github.com/google/uuid.New() | SecureRandom.uuid | Ramsey\\Uuid\\Uuid::uuid4() |
| Cryptographic pick | array[crypto.randomInt(0, array.length)] | secrets.choice(seq) | seq.get(sr.nextInt(seq.size())) | seq[crand.Int(...)] | seq[SecureRandom.random_number(seq.size)] | $seq[random_int(0, count($seq)-1)] |
1// lib/secure-random.ts — import this everywhere instead of reaching for
2// crypto / randomBytes / randomUUID at the call site. Makes grep trivial.
3
4import { randomBytes, randomInt, randomUUID } from 'node:crypto';
5
6/** URL-safe opaque token. Default 32 bytes = 256 bits. */
7export function secureToken(bytes = 32): string {
8 return randomBytes(bytes).toString('base64url');
9}
10
11/** 128-bit UUID v4 — fine for opaque IDs, NOT a secret. */
12export function secureId(): string {
13 return randomUUID();
14}
15
16/** Zero-padded numeric OTP. Unbiased. */
17export function secureOtp(digits = 6): string {
18 const ceil = 10 ** digits;
19 return randomInt(0, ceil).toString().padStart(digits, '0');
20}
21
22/** Uniform choice from a non-empty array. */
23export function secureChoice<T>(xs: readonly T[]): T {
24 if (xs.length === 0) throw new Error('empty array');
25 return xs[randomInt(0, xs.length)];
26}secureToken() / secureId() helper in a shared lib have dramatically fewer insecure-randomness findings than teams that let every call site reach for crypto primitives directly. It is a one-day project with a multi-year payoff. It also makes linting trivial: grep for Math.random and new Random and nothing else.Your team adds a lint rule banning Math.random across the codebase. A developer requests an exception for `backoff = baseMs * (1 + Math.random())` in a retry library. Correct response?
07 //UUID Versions & Token Entropy
UUIDs are a frequent source of confusion because the word "UUID" covers seven incompatible formats with wildly different security properties. Most of the confusion lives between v1 (timestamp + MAC, not secret) and v4 (122 random bits, secret enough for most purposes). A newer v7 (timestamp-ordered but with a random tail) is creeping into codebases via ORMs and has its own caveats.
UUID Versions and Their Security Properties
| Version | Composition | Random bits | Use for secrets? |
|---|---|---|---|
| v1 | 60-bit timestamp + 14-bit clock seq + 48-bit MAC | 0-14 | No — leaks time and MAC |
| v3 | MD5(namespace + name) | 0 | No — deterministic |
| v4 | 122 random bits | 122 | Yes, for most session/ID use |
| v5 | SHA-1(namespace + name) | 0 | No — deterministic |
| v6 | reordered v1 (timestamp sorts correctly) | 0-14 | No — still leaks time |
| v7 | 48-bit unix ms timestamp + 74 random bits | 74 | Marginal — leaks generation time |
| v8 | Implementation-defined | Varies | Depends on impl |
For security-sensitive tokens, prefer crypto.randomBytes(32) base64url-encoded to a UUID. You get 256 bits of entropy instead of 122, no version confusion, and no risk that someone downstream reads the timestamp out of your "opaque" identifier. Use UUIDs where you want a stable, globally-unique, reasonably-opaque ID that does not gate authentication.
1// Rule of thumb — choose the length by what the token protects.
2
3// Short-lived, rate-limited (email verify, magic link): >= 128 bits
4const emailToken = randomBytes(16).toString('base64url'); // 128 bits
5
6// Session cookie, password reset (minutes-to-hours validity): >= 128 bits
7const sessionCookie = randomBytes(32).toString('base64url'); // 256 bits
8
9// API key, long-lived (months-to-years): >= 256 bits
10const apiKey = randomBytes(32).toString('base64url'); // 256 bits
11
12// Shared secret, signing key, long-lived and high-value: >= 256 bits
13const hmacKey = randomBytes(32); // 256 bits raw
14
15// Why the gap? Rate limiting caps online guessing. Long-lived secrets
16// face offline attacks if they are ever leaked (e.g. via log exposure,
17// compromised backup). 256 bits puts brute force well out of reach
18// even for nation-state adversaries.A microservice emits `UUID.randomUUID()` (Java) as the session ID and stores the mapping in Redis. The senior engineer suggests switching to UUIDv1 because it indexes better. What do you push back with?
08 //Nonce Reuse in Crypto
AES-GCM and ChaCha20-Poly1305 are the two default authenticated-encryption constructions in modern systems. Both require a nonce (a "number used once") per encryption under a given key. Both are catastrophically broken if that requirement is violated. Nonce reuse with the same key reveals the XOR of the two plaintexts and gives the attacker the authentication key, letting them forge arbitrary ciphertexts. There is no graceful degradation — the whole construction collapses.
1import { createCipheriv, randomBytes } from 'node:crypto';
2
3// WRONG #1 — constant nonce. Every message encrypted under the same key
4// uses the same IV. Classic pattern in tutorials.
5const iv = Buffer.alloc(12, 0); // all zeros, FOREVER
6
7// WRONG #2 — Math.random nonce. 96 bits but from a non-cryptographic
8// stream. Birthday bound is much lower than 2^48; collisions
9// after ~2^24 messages are plausible given state recovery.
10const iv = Buffer.alloc(12);
11for (let i = 0; i < 12; i++) iv[i] = Math.floor(Math.random() * 256);
12
13// WRONG #3 — timestamp nonce. Two encryptions in the same millisecond
14// collide. Under load, this is not hypothetical.
15const iv = Buffer.concat([
16 Buffer.from([0, 0, 0, 0]),
17 Buffer.from(Date.now().toString(16).padStart(16, '0'), 'hex'),
18]);
19
20// RIGHT — 96 random bits from crypto.randomBytes.
21// Birthday bound at 2^48 messages, which is comfortably beyond
22// what any single key is expected to encrypt in its lifetime.
23const iv = randomBytes(12);
24
25// ALSO RIGHT — a strict monotonic counter persisted across restarts,
26// keyed per (key, sender). Used by TLS and Noise.
27// Only safe if you can guarantee it never resets.If you find yourself deriving a nonce from the message content (e.g. iv = sha256(plaintext).slice(0, 12)), that is a direct nonce-reuse bug: identical plaintexts encrypt to identical ciphertexts, which is a chosen-plaintext distinguisher and, worse, a nonce-reuse against the GCM authentication. Use AES-GCM-SIV or XChaCha20-Poly1305 if you need nonce-misuse resistance, not a hand-rolled scheme.
Math.random() for IVs because it "looks random enough." On a long-lived process, V8's xorshift128+ stream is finite and repeats; combined with process restarts and the birthday bound, nonce collisions are almost guaranteed on any service that encrypts more than a few million messages per key. Always use crypto.randomBytes (Node) or crypto.getRandomValues (browser) for IVs.A payments service encrypts card metadata with AES-256-GCM. A developer proposes deriving the IV as `HMAC-SHA256(key, message_id)[0:12]` to avoid storing IVs alongside ciphertexts. What is the correct review answer?
09 //Real-World Case Studies
The bug class has a long history of industry-defining incidents. Reading them is instructive because the pattern is always the same: a developer trusted an API name, or made an optimisation that removed entropy, or used a statistical generator in a security sink. The failures scale from "one site's cookies" up to "every Debian key issued in 20 months."
- Debian OpenSSL (CVE-2008-0166) — a Debian maintainer patched OpenSSL to silence a Valgrind warning by removing a line that mixed uninitialised memory into the PRNG seed. The seed space collapsed from 2^128 to 2^15 (the PID). Every SSH, TLS, and DNSSEC key generated on Debian/Ubuntu for 20 months was one of 32,768 possibilities. Full key recovery was possible by brute force.
- Hacker News cookie predictability (2010) — the original HN implementation seeded cookie generation from a millisecond timestamp. A blog post demonstrated that observing the server’s clock and a single cookie was enough to predict future cookies within about an hour. The fix was a one-line switch to a cryptographic source.
- Kaspersky Password Manager (CVE-2020-27020) — the password generator used
Math.random()(or its C++ equivalent seeded from system time). Generated passwords were therefore predictable from the approximate generation time, which is often recorded in metadata. Researchers demonstrated recovery of passwords generated over the preceding years. - Juniper ScreenOS Dual_EC backdoor (CVE-2015-7755) — Juniper's ScreenOS firmware used Dual_EC_DRBG, a PRNG known to admit a backdoor if the attacker knows the curve parameters' discrete log. An unauthorized change to the constants by a third party enabled passive decryption of VPN traffic by anyone holding the backdoor key.
- CSGO matchmaking seed — Valve's matchmaking used a predictable seed for map selection. Players who reverse-engineered the seed could reliably force specific maps, giving a persistent competitive edge. The class of failure ("predictable game seed") is minor in isolation but illustrative of how often the pattern appears.
- MediaWiki LoginToken (CVE-2019-19910) — an older MediaWiki version generated login CSRF tokens with
mt_randseeded from time + PID on Windows. Tokens were brute-forceable, allowing login CSRF. Fixed by switching torandom_bytes.
What is the common root cause across Debian OpenSSL, Hacker News cookies, and Kaspersky Password Manager?
10 //Detection in Code Review
Insecure randomness is one of the few bug classes where grep is a first-class tool. The unsafe APIs have stable names across decades of standard libraries, and they are short enough that false positives are manageable. Combine a grep pass with a Semgrep / CodeQL rule set, and enforce the same rules in CI.
1# JavaScript / TypeScript
2rg -n 'Math\.random\(\)'
3rg -n 'new\s+Random\(' # Java, .NET
4rg -n 'random\.random|random\.choice|random\.randint' # Python
5
6# Low-level C
7rg -n '\brand\(\)|\bsrand\(|\brandom\(\)|\bdrand48\('
8
9# Seeding with time or PID — the cross-language red flag
10rg -nE 'srand\s*\(\s*time\s*\(|srand\s*\(\s*getpid|seed\(\s*Date\.now'
11
12# UUID v1 in Java / Python (usually an accidental import)
13rg -n 'UUIDs\.timeBased|uuid\.uuid1'
14
15# Explicit-seed SecureRandom constructor — the 'safe name but unsafe call' trap
16rg -nE 'new\s+SecureRandom\s*\([^)]+\)'
17
18# Crypto IVs built from non-CSPRNG sources
19rg -n 'createCipheriv\(.*Math\.random'
20
21# Passwords / tokens built from non-CSPRNG sources
22rg -n 'toString\(36\)\.slice|toString\(16\)\.slice' | rg Math\.randomSAST Tool Coverage
| Tool | Rule | Catches |
|---|---|---|
| Semgrep | javascript.lang.security.audit.insecure-randomness | Math.random in security context |
| Semgrep | python.lang.security.audit.insecure-random-module | random.* calls, not secrets.* |
| CodeQL | java/insecure-randomness | java.util.Random into crypto sinks, seeded SecureRandom |
| CodeQL | js/insecure-randomness | Math.random flow-based analysis into token sinks |
| Bandit | B311: random | Python random module usage in security-adjacent code |
| ESLint | security/detect-pseudoRandomBytes | Math.random + pseudoRandomBytes |
| SonarQube | S2245 | Pseudorandom in crypto context, multiple languages |
| gosec | G404 | math/rand in Go where crypto/rand is expected |
1# semgrep-rules/no-math-random-in-security.yaml
2rules:
3 - id: no-math-random-in-security-sinks
4 patterns:
5 - pattern-either:
6 - pattern: Math.random(...)
7 - pattern-inside: |
8 function $FN(...) {
9 ...
10 $RET = Math.random(...)
11 ...
12 }
13 - metavariable-regex:
14 metavariable: $FN
15 # any function name that smells like a secret factory
16 regex: '(?i)(token|secret|nonce|salt|session|reset|verify|otp|key|password)'
17 message: >-
18 Math.random() used inside a function whose name suggests a security
19 context ($FN). Use crypto.randomBytes / crypto.randomUUID /
20 crypto.randomInt instead.
21 languages: [javascript, typescript]
22 severity: ERRORA CodeQL scan flags `new SecureRandom(seedBytes)` as insecure. The developer argues that SecureRandom is 'in the name' so it must be fine. What is the correct response?
11 //Testing Randomness
Testing randomness is harder than most engineers expect, and almost all naive approaches are wrong. Looking at the output and seeing it "looks random" is not evidence of anything — a 32-bit LCG output looks just as random to a human as a CSPRNG output. The correct tests fall into three categories: statistical test suites (for bias and long-range structure), property tests (for API correctness), and threat-model tests (for the specific attack you care about).
- Statistical suites — NIST SP 800-22, dieharder, PractRand, TestU01’s BigCrush. These detect subtle bias and short cycles but do NOT prove cryptographic security — a well-designed statistical PRNG will pass them all while remaining trivially breakable.
- Property tests — for a bounded-integer API, draw a million samples and chi-square against a uniform distribution. Catches modulo bias. For a rejection-sampling implementation, test that the rejection actually happens on edge cases.
- Threat-model tests — for session ID generation, write a test that tries to recover internal state from N observed outputs and asserts that recovery fails (in practice, asserts "the API used is listed in an allowlist of known CSPRNGs"). This is the test that catches real vulnerabilities.
- Entropy estimation — measure the Shannon entropy of the output and compare against the theoretical maximum. Useful for catching truncation bugs (e.g. a token that accidentally only uses the lower 32 bits of a 256-bit source).
1# Catches rand() % N bias when the source is uniform but the reduction
2# is not. Run this against your own generate_otp() implementation.
3import secrets
4from collections import Counter
5from scipy.stats import chisquare
6
7N = 1_000_000 # samples
8OTP_S = 1_000_000 # 6-digit OTPs
9
10counts = Counter()
11for _ in range(N):
12 otp = generate_otp() # your function under test
13 counts[int(otp)] += 1
14
15expected = [N / OTP_S] * OTP_S
16observed = [counts.get(i, 0) for i in range(OTP_S)]
17
18chi2, p = chisquare(observed, expected)
19# Expect p > 0.01 for an unbiased generator.
20# A p-value of 1e-20 means you have measurable bias.
21assert p > 0.01, f"Bias detected: chi2={chi2}, p={p}"A teammate shows you a test: `expect(tokens).toHaveLength(new Set(tokens).size)` run over 10,000 generated tokens to 'prove' the generator is random. What is wrong with this test?
12 //Conclusion
Insecure randomness is one of the oldest and most persistent bug classes in applied security because every decade's new ecosystem ships its own statistical RNG under a name that sounds secure. The review discipline is simple: identify the sink, demand a CSPRNG source, reject timestamp / PID / counter seeds, and prefer the short stdlib API over anything hand-rolled.
Math.random() / rand() / java.util.Random / random.random() in security sinks · No explicit seeds on SecureRandom / Random · Token length ≥ 128 bits from a CSPRNG · Bounded integers via randomInt / secrets.randbelow, never bare % · AES-GCM / ChaCha20 nonces from crypto.randomBytes or a strict counter · UUIDv4 or raw bytes for opaque IDs, never v1 · One secureToken() helper per codebase · Semgrep/CodeQL rules enforced in CI.When a reviewer sees a new random-number call site in a diff, the first question is not "is this fast enough" or "is the output long enough" — it is "if an attacker observes five of these in a row, can they predict the sixth?" If the answer is anything other than "no, it is a cryptographic stream," the change needs work. Pair this module with the Cryptographic Failures, Session Fixation, and JWT Vulnerabilities guides for the adjacent classes of token-handling bugs.