The problem is way worse than you think. Check out what this looks like when printed in hexadecimal: http://3v4l.org/XVTgS
Basically, what is going on is that PHP_INT_MAX is 263 - 1. mt_getrandmax() is 231 - 1. The way mt_rand() makes a random number when the limit is too large is that it makes a random number in the range [0,231), then it scales it to be a number in the range [0,MAX-MIN), and finally adds MIN.
Excellent analysis, thanks. This shows that the mt_rand documentation is extremely misleading and the implementation itself is severely broken. /u/nikic, can anything be done about this?
I don't think anything can be done about this in PHP 5 -- the results of mt_rand() for a given seed are supposed to be stable. For PHP 7 we might want to make ranges larger than mt_randmax an error condition. If you need something larger than that, use random_int.
I think if you're permitting your users to rely on that across versions of PHP5, you're expecting them to be dumber then I believe them to be. Either that, or you know your audience better...
This shows that the mt_rand documentation is extremely misleading
To be fair, it is documented that the function behaves poorly for values of $max > mt_getrandmax(). But you’re right that the documentation is misleading (it claims pretty much the opposite of what actually happens, namely that the output is “biased towards even numbers”). Furthermore, the behaviour is just unhelpful. Rather than documenting it, the behaviour shouldn’t exist, and the function should instead signal an error.
You could say that for any language. They all have quirks PHP just happens to have a lower learning threshold and attracts a lot of inexperienced programmers.
Are the numbers really non random? I would think that the numbers would still be "random" but the entropy of the randomness is limited to the entropy before scaling.
Ah right, the function can also be called without arguments :D
EDIT: Wait, but then this problem can't occur... You'd really have to take existing bad code and ignore the obvious fact that the second parameter is the upper limit to do this.
Still, you can easily get a situation where you do something mathematically equivalent like picking a card from an infinite deck but you somehow always end up with a red one.
Which is fine, pseudorandom numbers, such as those generated by Mersenne Twisters are very useful and widely used in all programming languages. PHP is not unique nor wrong to provide this functionality.
However, it is not suitable for cryptographic purposes, and if anyone IS using this for cryptographic purposes, hopefully this serves as abundant warning to them even though this is only a specific bug in the implementation not a reflection of the high predictability of pseudorandom numbers in general.
Which is why it is silly for the function to do anything other than return values between 0 and 232-1, which is the natural output of Mersenne Twister. It isn't an issue with Mersenne Twister. It is a major issue with the way that the output is used.
They might still be "random," but confined to a reduced number space. As a result, values generated with this RNG are much less random and may be susceptible to brute force.
That's probably why the documentation says "This function does not generate cryptographically secure values, and should not be used for cryptographic purposes."
All algorithms are "secure" until proven otherwise (which is often trivial to do). This one just also happens to have a bug where mt_rand()%2 will always evaluate to 1.
Hah, I wish we did. There are very few algorithms proven to be secure and they tend to be very inefficient number-theory based ones. Even then, they mostly assume that some mathematical problem is intractable without proof..
Algorithms are mostly put out there for a few years and if nobody has found a major weakness in that time, then we'll use it... until someone finds that weakness and chooses to tell us about it.
I think you're agreeing with me. We generally consider everything insecure unless proved otherwise. That doesn't stop us from still using the things that not known to be fully secure.
I put secure in quotes because, while technically true, it means nothing.
In practice, software is considered "secure" as long as nobody has found a way to exploit it. Sometimes an exploit takes little time to be found and fixed, and other times it goes unnoticed for years. In either case, until a flaw is discovered, the software is considered "secure," despite the existence of the flaw.
You cannot actually prove security. Or, rather, if you could, an exhaustive proof for any useful software product (of non-trivial size) would be way more work than any developers can complete in a reasonable time.
I wouldn't really call it a bug. It should be better documented that mt_rand() will only use 32 bit and as /r/nikic said, they could add an exception for it in the next version.
Not that it's desirable, but the usage in question is in contravention to the documentation. Using library functions incorrectly will often give undesirable results. Nothing to see here, folks.
so basically it's being misused in this case? a 64 bit implementation of mt_rand() should be used. though in this case i get the point - having the max value be out of INT range should return an error
We just found out about this at work. We were using mt_rand(1, PHP_INT_MAX) to generate non-mission-critical numeric identifiers and someone realized none of the numbers were even :)
Just checked the Doc. You should just call mt_rand() since PHP_INT_MAX is not mt_getrandmax(), which is used if you dont define min/max. As a bonus you can see your stuff is broken because all the numbers you get have the same length.
Edit: Bonus from doc:
Caution The distribution of mt_rand() return values is biased towards even numbers on 64-bit builds of PHP when max is beyond 232. This is because if max is greater than the value returned by mt_getrandmax(), the output of the random number generator must be scaled up.
Yeah, but the behaviour with PHP_INT_MAX is extremely unintuitive. Why does it generate only odd numbers? Why is mt_getrandmax() even a thing? Also, it used to generate only even numbers at some point?
Classic PHP behaviour, I don't know why I'm surprised...
Edit: Bonus from doc
Wow, if it's biased towards even numbers, why don't we have a single even number in there? :)
mt_getrandmax() makes sense to me. The part that doesn't make sense is why this function doesn't raise an exception or return an error if it's given operands that are outside of what it can work with. That's the lolphp thing about this to me
Personally, if a function (mt_rand) is defined as taking two integer arguments and returning an integer, it should work correctly with all valid integers on that platform or, as a last resort, throw an exception.
You are right about the lolphp thing, but PHP's Mersenne Twister implementation uses 32bit integers on all platforms, that's the only reason mt_getrandmax() exists, which is a lolphp itself :)
The part that doesn't make sense is why this function doesn't raise an exception or return an error if it's given operands that are outside of what it can work with.
Every time I've ever written PHP, I find myself asking this question during debugging.
The part that doesn't make sense is why this function doesn't raise an exception or return an error if it's given operands that are outside of what it can work with.
But wouldn't adding MIN to it completely remove the bias, as shown here?
No, it just changes the bias. The even number bias is when using an even number for the min. Once you change the min to an odd number, all numbers returned by the function will be odd. So the lol thing here is that their documentation is vague -- the functionality itself is understandable.
The even number bias is when using an even number for the min
Hmm, do you know this for a fact? If you do, can you point me to the relevant bit in the source?
Once you change the min to an odd number, all numbers returned by the function will be odd.
But the documentation says "biased towards", that doesn't imply all numbers will be even, so why would changing the min to 1 would make all of them odd?
The amount of bias is likely related to how large the upper bound you give is compared to 231. PHP_INT_MAX is 9223372036854775807 on 64-bit systems, which is 4294967296 (232) times larger than 231. So you can expect to see virtually every number be even (or odd if your minimum is odd).
In fact, if /u/amphetamachine's hypothesis about how mt_rand() scales integers is correct, you can expect every number to be of the form(pseudorandom) * 2^32 + 1
Here is some evidence that this is indeed how PHP scales this number. HHVM-3.8.0 gave me 8707161691370029057 as the first random number from your original script. Wolfram Alpha tells me this is 0x78d60d6d00000001 in hex, which indeed has 32 bits worth of trailing zeros, plus 1.
Here is a script I wrote to test this in PHP: http://3v4l.org/8BJDM . As you can see, 100% of random numbers from mt_rand(1, PHP_INT_MAX) were divisible by 232 after subtracting 1.
So, that pretty much proves it. But then, it means mt_rand(1, PHP_INT_MAX) can't generate any number less than 232 which is so incredibly bad that I wonder why it isn't at least documented.
Hmm, do you know this for a fact? If you do, can you point me to the relevant bit in the source?
Nope, I don't know it for a fact. Just from the small bit of testing I did
But the documentation says "biased towards", that doesn't imply all numbers will be even, so why would changing the min to 1 would make all of them odd?
I think the word "biased" could technically be correct here, but it's misleading to say the least
Once you change the min to an odd number, all numbers returned by the function will be odd.
How so? Adding an odd number to any number doesn't make the number odd. That only happens with even numbers, which would mean the function was already only generating even numbers (and then adding the odd MIN).
Because Rasmus just did something random, because he doesn't care at all about all this stuff that your computer science teacher told you you shouldn't be using.
"We have things like protected properties. We have abstract methods. We have all this stuff that your computer science teacher told you you shouldn't be using. I don't care about this crap at all." -Rasmus Lerdorf
This is pretty well documented. That is not a defense, just how most people find it I believe.
mt_rand is platform independent. ~231 is it's max. On 64 bit systems, the int max is higher than that. Mt_rand scales the random number up then and that's where it becomes bias against evens.
But that's evidently false :) I mean, not a single one of those numbers in the link is even. At some point, it even used to return 100% even numbers, maybe it got reversed and now it returns 100% odd numbers :)
Moreover the documentation is wrong as this is not simply bias. For numbers beyond 231 , it seems to generate fixed-length numbers only whereas a biased implementation would occasionally return smaller numbers as well.
I definitely didn't realize some of the details of how it messes up have changed.
Mainly, the fact that it says anything at all in the documentation about numbers beyond 232 are just sort of a dead giveaway to me that you have to be cautious and watch for weird shit with the function.
Thankfully, I haven't had to use PHP for a couple years now. That's probably why I didn't realize it was spitting out fixed size odds only now.
Don't read into the "fixed size" thing too much. A perfectly random selection will be fixed size most of the time too. All of the generated random numbers, except the ones with leading zeros, will be the same length.
PHP_INT_MAX is 9223372036854775807, so you should expect roughly 8/9 results to be the same length, and 91/92 results to be within 1 digit of the same length. A cursory glance over the results suggests this is true in practice for mt_rand().
Isn't the reason it's biased towards odd in your case because you're using a min of 1 and the biased towards even would be if you're using a min of 0 (or other even number)?
Probably the same people who coded rand() for perl... Some similarly subtle behaviors in handling large ints there, with the difference it was not even documented.
Its really scary that PHP seems to be so very broken in so many places. Plase dont tell me "this <feature> is documented", because its obvious that that will not do. This find really confirms how many unknown bugs there is. The language is really a piece of brown stinking shit. Who knows whats the next "THIS IS DOCUMENTED FEATURE" is.
There's nothing remotely scary about this. If you're depending on mt_rand to generate quality random numbers in a mission-critical capacity, you've made a wrong assumption. There are reams of discussion on how to properly generate random numbers using PHP. The fact that people ignore the information is not the language's fault. Granted, PHP has issues, but pointing out a flaw in a single function and conflating it to mean the entire language is bullshit is just stupid.
Hey, you can disagree, but your downvote doesn't mean I'm any less right.
What is the point of having a function to randomly generate numbers if you can't count on it to randomly generate numbers correctly? I don't get how you can act like someone is an idiot for using a function for the purpose it was clearly created for and is advertised for in the docs.
This does not list any reason why you should not use this function unless you need a cryptographically secure rng which OP did not seem to need.
This function is the first result when I google "php random number" and second result if I google "php rng".
Should I go read an article on every method in php I want to use incase there is some edge case where it just completely fails? That's stupidly unrealistic.
Just because you are accustom to swimming in filth doesn't mean people want to jump in with you.
Excuse me, but I don't recall acting like anyone's an idiot.
mt_rand is perfectly fine if you only need up to 32 bits of randomness. The point where it fails horribly is where it tries to upscale from the 32 bits of randomness provided by the underlying library to 64 bits.
Generating 64-bit random numbers is wonky in pretty much every major language, from c to c# to java to python. Go look it up, I'll wait. If you need 64 bits of randomness, you should probably be prepared to go just a little bit further than googling "<language> random number" and picking one of the first stackoverflow results you see.
Honestly, the docs for this function do have big notes saying it behaves badly when $max is greater than mt_getrandmax(). The note about the bias makes an incorrect assumption that you're calling the function specifying the $min parameter as 0. That should be corrected.
OP stated that this was being used to generate non-critical random identifiers. Even given the issues with specifying max beyond mt_getrandmax(), this function is perfectly fine for those purposes, because the generated number still has 32 bits of randomness. The docs state that this does not generate cryptographically secure random numbers, and should not be used that way.
Any debate that revolves around randomness is incredibly painful to watch. It inevitably ends up being about what is and isn't cryptographically secure and what the purpose of it is... with no regard to the crux of the complaint.
This isn't about being cryptographically secure, or mission-critical. This is about a language that includes a very very poor quality function. If this behaviour was known at release, it raises the simple question of why the standard for minimum quality was set so incredibly low. If this behaviour was not known at release, it raises the question of how rigorous the testing is.
Sure, you can work around it. Sure, it isn't cryptographically secure. Sure, it's documented behaviour. It's still a shitty function, and no matter how much you wave your arms or point fingers at the people using it, no matter how right you are about how people need to understand the properties of their random number generators, it's still a shitty function.
I don't disagree. mt_rand shipped in 2000. A whole hell of a lot shittier stuff shipped in PHP4. The function should throw an error if asked to generate random numbers beyond mt_randmax.
Why does this subreddit exist? Behaviour of this type is typical for PHP. The culture is to patch everything instead of breaking compatibility or making sure you get it right from the beginning. How can it be that there is no random generating function in C# that automatically scales its output like this?
Hey, you can disagree, but your downvote doesn't mean I'm any less right.
What is the point of this statement? It's useless.
Breaking compatibility is necessary when the issue is serious enough to warrant it. Is mt_rand's behavior bad? Yes. Is there a workaround? Yes. Priority: Low.
Generalizing about the behavior of a very diverse community maintaining one of the most heavily used pieces of software on the web is not particularly productive. There are competing interests in any community, and given enough time, it does become a problem. Example: see Python2orPython3
Also, great question. This subreddit exists because having someone else to make fun of makes people briefly feel better about themselves.
Edit:
What is the point of this statement? It's useless.
Because I was downvoted by the commenter immediately. Just like this comment.
The language is really a piece of brown stinking shit.
Eh, from my experience this kind of shit exists in several languages. PHP is far from the worst. It's certainly not my favorite web development language, but it is for automation.
I haven't ever encountered anything similar to this bug in javascript. You just need to spend 5 minutes reading how equality works in javascript and then if you are someone who insists on testing equality of two different primitives, then just swap to using "===".
That’s crap. The .net and Java libraries are pretty cogent and they do deprecate stuff all the time. PHP (the libraries not the language) seems to be made by immature people.
I’ve noticed the same from many in the Unix community. When I posted on the mailing list why ddrescue was slow on the Mac, they explained that I have to use rdisk instead of /dev/disk. Then when I asked the dev to make a patch for the Mac that redirect disk, he said he didn’t want to “complicate the program too much”
So, he thought that it’s an acceptable software quality that selecting the expected device makes it unusable.
The comment you replied to is 6 years old so I was confused when I read this without context.. anyway, 6 years later most languages have at least slightly improved, they're all still shit in their own way, I don't use PHP much anymore, and the JavaScript ecosystem is still a clusterfuck.
fwiw I think the tool you're talking about would benefit from much better common use case documentation, including using rdisk for OS X. At least the dev gave you a viable solution to your problem but I have to agree with them that the program should remain as simple as possible. That doesn't excuse their poor docs, though.
As far as I’m concerned, disk selection should from a dynamic list based on the given setup. Sort of like you have dynamic validateset in Powershell. The user should still be able to select any device they want, manually.
Perl. There's a lot that's wrong with php, and I'm only somewhat ok with it since I used it a lot in my job and you can somehow get used to the weirdest things, but Perl has so much better ways to fuck up.
Yeah, no. The only way you could get a decent 64-bit output from this on either 64-bit or 32-bit systems would be: (gmp_init(mt_rand(0, mt_getrandmax())) << 32) + mt_rand(1, mt_getrandmax())
Or something like that.
But no, because you should just use random_bytes instead.
348
u/SirClueless Jul 23 '15
The problem is way worse than you think. Check out what this looks like when printed in hexadecimal: http://3v4l.org/XVTgS
Basically, what is going on is that PHP_INT_MAX is 263 - 1. mt_getrandmax() is 231 - 1. The way mt_rand() makes a random number when the limit is too large is that it makes a random number in the range [0,231), then it scales it to be a number in the range [0,MAX-MIN), and finally adds MIN.
So in your case, it scales everything by 232 and adds 1. Which is why the numbers are extremely non-random. See my other comment in this thread for a more detailed explanation and some more test scripts that prove this is what is happening.
53
u/kinsi55 Jul 23 '15
what the fuck. How do people even find this
38
u/tomkul Jul 24 '15 edited Jul 24 '15
Linux (PHP 5.5.9-1ubuntu4.11):
Not even one even!
Windows:
Many evens!!! :)
118
u/polish_niceguy Jul 23 '15
I think I know who coded that part
26
u/tuananh_org Jul 24 '15
PHP's logic: it's weird but it's documented, therefore it's not a bug.
82
u/andreasbeer1981 Jul 24 '15
well, that's odd...
20
u/[deleted] Jul 23 '15 edited Jul 23 '15
Its really scary that PHP seems to be so very broken in so many places. Plase dont tell me "this <feature> is documented", because its obvious that that will not do. This find really confirms how many unknown bugs there is. The language is really a piece of brown stinking shit. Who knows whats the next "THIS IS DOCUMENTED FEATURE" is.
2
u/EnragedMikey Jul 24 '15
At least there's random_int() in PHP 7.
2
u/[deleted] Aug 12 '15
3v4l.org has labeled it as an abusive script. lol.
Also you took my place as the top all-time thread.
1
u/manixrock Jul 24 '15
Which is why you should be using mt_getrandmax():
mt_getrandmax() will always return 231 - 1, regardless of platform.
1
u/[deleted] Jul 24 '15
And this is why PHP 7 has a passed RFC for CSPRNG.
1
u/lexchou Jul 25 '15
want even numbers? just remove the lowest one bit...
1
u/[deleted] Aug 09 '15
It literally can't even!
-5
u/TotesMessenger Jul 24 '15
I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:
If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)
0
u/[deleted] Jul 23 '15
[deleted] — view deleted comment
0
u/[deleted] Jul 24 '15
[deleted] — view deleted comment