Password reset tokens you can guess
A easy Java puzzle in the security mistakes family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 7. Play this one as a puzzle without the answer.
What is wrong
java.util.Random is a linear congruential generator: from a few outputs an attacker can recover its state and predict every future token. It is fine for simulations, not for secrets.
The fix
How to avoid it next time
Use SecureRandom for tokens, session ids, salts and keys.
Want the background? Read Random numbers and UUIDs in the Java concepts library.
About security mistakes
Predictable random numbers, secrets in source code, unvalidated file paths and weak hashes turn working features into vulnerabilities. They pass every functional test.
In code review: Search for java.util.Random in security contexts, literals that look like keys, paths built from user input, and MD5 or SHA-1 used for passwords.
More puzzles in this family
Frequently asked questions
What is the bug in "Password reset tokens you can guess"?
java.util.Random is a linear congruential generator: from a few outputs an attacker can recover its state and predict every future token. It is fine for simulations, not for secrets. The faulty line is line 7: return Long.toHexString(RANDOM.nextLong());
How do I fix it?
Replace it with: private static final java.security.SecureRandom RANDOM = new java.security.SecureRandom();. Use SecureRandom for tokens, session ids, salts and keys.
How do I catch security mistakes in code review?
Search for java.util.Random in security contexts, literals that look like keys, paths built from user input, and MD5 or SHA-1 used for passwords.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.