Breaking PHP’s mt_rand() with 2 values and no bruteforce
The PHP mt_rand() function's seed can be recovered from just two output values separated by 226 others, without brute force. An attacker who obtains such outputs can predict all past and future mt_rand() values, breaking the PRNG.
ambionics.io
Published on ambionics.io
While performing a pentest on an old website, we encountered a piece of code that we had not seen in a long time:
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Not written yet. The AI write-up for this write-up has not been written yet. The Original tab links to the source.
How it worked
Root cause
Likely, the Mersenne Twister PRNG used by PHP's mt_rand() has a linear relationship between state values that allows seed recovery from two outputs, making it unsuitable for cryptographic use.
What the attacker needed
Two mt_rand() outputs 226 apart; knowledge of offset
How it was found
- Obtain two mt_rand() output values separated by 226 other values, and know the offset.
- Reverse the output transformations to get the scrambled state values.
- XOR the two scrambled states to deduce initial state 228.
- Work backwards from state 228 to the seed.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this write-up has not been written yet. The Original tab links to the source.
PHP's mt_rand() is a random number generator that is not secure for secrets. If you can see two of its outputs that are 226 apart in the sequence, you can work out the starting seed and then predict every other number it will produce. This means tokens or passwords made with mt_rand() are not safe.
What is Crypto?
Encryption, signatures, randomness or certificate checks that do not protect what they claim to.