Skip to content

Instantly share code, notes, and snippets.

@natmchugh
Last active July 26, 2021 09:07
Show Gist options
  • Save natmchugh/df9886658ad02fde0d6a to your computer and use it in GitHub Desktop.
Save natmchugh/df9886658ad02fde0d6a to your computer and use it in GitHub Desktop.
An example of how to guess the seed used in first call to PHP's mt_rand()
$time = time(0);
$pid = getmypid();
echo 'time is: ',$time,' (just the unix timestamp so very guessable)',PHP_EOL;
echo 'pid is: ',$pid, ' (process id of current PHP process usually in 1000s )',PHP_EOL;
$rand = mt_rand();
echo 'Output of 1st call to uninitialized to mt_rand is: '.$rand,PHP_EOL;
echo 'Output of 2nd call to uninitialized to mt_rand is: '.mt_rand(),PHP_EOL;
echo 'Output of 3rd call to uninitialized to mt_rand is: '.mt_rand(),PHP_EOL;
echo 'Guessing the seed now: ',PHP_EOL;
for ($i = 0; $i < 1000000; $i++) {
$seed = (($time * $pid) ^ $i);
mt_srand($seed);
if ($rand == mt_rand()) {
echo 'seed was : ',$seed,PHP_EOL;
mt_srand($seed);
echo 'Now we can guess the random',PHP_EOL;
echo '1st: ',mt_rand(),PHP_EOL;
echo '2nd: ',mt_rand(),PHP_EOL;
echo '3rd: ',mt_rand(),PHP_EOL;
break;
}
}
@natmchugh
Copy link
Author

Example output on PHP 7.0.3

time is: 1455634510 (just the unix timestamp so very guessable)
pid is: 23688 (process id of current PHP process usually in 1000s )
Output of 1st call to uninitialized to mt_rand is: 605310210
Output of 2nd call to uninitialized to mt_rand is: 1097357143
Output of 3rd call to uninitialized to mt_rand is: 1279652743
Guessing the seed now:
seed was : 34481070227260
Now we can guess the random
1st: 605310210
2nd: 1097357143
3rd: 1279652743

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment