Skip to content

Lesson 4 of 13 · 18m

Randomness That Matters: CSPRNGs, urandom, and Predictable Tokens

Why Math.random and mt_rand reset tokens get guessed, the Debian OpenSSL seed disaster, and the CSPRNG API table per language.

Every key, nonce, salt, IV, reset token, and session ID you'll ever generate comes out of one function. If that function is predictable, nothing built on top of it matters — the strongest cipher in the world is wrapping a key an attacker can just guess.

What actually happens

Your OS keeps an entropy pool fed by hardware noise — interrupt timing, disk jitter, CPU jitter, and a hardware RNG like Intel's RDRAND/RDSEED when present. On Linux you read it through getrandom(2) or /dev/urandom; on everything else there's a syscall equivalent, and your language wraps it. The output is cryptographically random: seeded well, stirred constantly, and designed so that even the kernel can't predict the next byte from the last gigabyte.

That's the only source you're allowed to use. The bugs come from the other random functions — the ones designed for simulations and Math.random() for shuffling a playlist.

The wrong mental model: "random enough"

random.random(), Math.random(), rand(), mt_rand(), java.util.Random — every one of these is a deterministic PRNG seeded from something observable (time, PID, previous outputs). Mersenne Twister — the engine behind Python's random and most "default random" APIs — has ~2^19937 states but hands you its entire internal state after ~624 outputs. Collect that many tokens off a leaky endpoint and you can predict every future value. PHP's mt_rand has been broken from a single sample for years.

The horror stories are real: Debian's 2008 OpenSSL package patch accidentally removed the entropy source, and every key generated on Debian-derived systems for two years came from a space of ~32,768 possibilities. SSH host keys, TLS certificates, OpenVPN keys — all brute-forceable, all regenerated in a panicked openssl-blacklist package. NetBSD had a similar early-boot entropy hole that let attackers predict /dev/urandom output after boot.

The API table — memorize it

  • Python: secrets.token_bytes(32), secrets.token_urlsafe(), os.urandom() — never random.* for security.
  • Node/browser: crypto.randomBytes() / crypto.getRandomValues() / crypto.randomUUID() — never Math.random().
  • Go: crypto/rand — never math/rand (and vet your deps; math/rand slips in through helpers).
  • Rust/C: getrandom crate, arc4random, RAND_bytes() — the syscall or a vetted wrapper.
  • Shell: openssl rand -hex 32, or read /dev/urandom — never $RANDOM.
import secrets
token = secrets.token_urlsafe(32)   # password reset token: ~256 bits
key   = secrets.token_bytes(32)     # symmetric key
nonce = secrets.token_bytes(12)     # AES-GCM nonce

Where this actually breaks

  • Tokens and IDs. Math.random().toString(36) reset links are enumerable. Session IDs, CSRF tokens, API keys — anything an attacker guesses is anything they steal. Minimum sensible size: 128 bits.
  • ECDSA nonces. Per-signature nonce reuse (or a weak PRNG for k) leaks the private key — the PS3 signing key and the 2013 Android Bitcoin wallets both fell this way. This is why Ed25519 is deterministic.
  • Forks and VM snapshots. A process that seeds a PRNG and then forks shares state; a VM resumed from a snapshot replays entropy. Post-2018 kernels re-seed getrandom on fork/restore, but user-space PRNGs you seeded yourself don't get that memo.
  • Early boot. Embedded devices generating host keys at first boot have almost no entropy. Generate keys on first login, or use the hardware RNG — not on a cold boot with four sources of noise.

Practice

grep -rn "Math.random\|mt_rand\|random.random\|rand()" --include="*.ts" --include="*.py" .

Every hit that feeds a token, key, ID, or nonce is a finding. Replace with the CSPRNG row of the table above, and give every security token at least 128 bits of entropy.

Field notes

  • crypto.randomUUID() is fine for IDs but gives you ~122 bits — good, not generous. For anything that is a credential, go to 128–256 bits raw.

  • /dev/random vs /dev/urandom is a solved debate: use urandom (i.e., getrandom). Blocking on "not enough entropy" is a feature nobody needs post-boot.

  • If a library generates key material through mt_rand or Math.random, it doesn't matter how good the rest is — it's broken. Audit the dependency, not just your code.

  • Modulo bias is the quiet bug: getRandomValues(buf) % 62 skews toward low values unless the range divides the space evenly. crypto.randomInt and secrets.randbelow do rejection sampling for you — use them for bounded draws.

  • random.shuffle and array.sort(() => Math.random() - 0.5) aren't CSPRNG-safe either — a shuffle feeding a deal order or a raffle is a token leak with extra steps.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.