Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

modulo bias in rand() usage #540

Closed
guijan opened this issue Dec 8, 2023 · 1 comment
Closed

modulo bias in rand() usage #540

guijan opened this issue Dec 8, 2023 · 1 comment

Comments

@guijan
Copy link
Contributor

guijan commented Dec 8, 2023

This article is an excellent writeup on modulo bias and its solution:
https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/

The gist of it is that in this code:

i = rand() % proxy_count;

Some values of i are more common than others, because if you have a rand0_5() (example) function that generates random numbers between 0 and 5 inclusive, and you want a number between 0-4 inclusive, then if you write a program that does rand0_5() % 5, getting a result of 0 is twice as common as every other result because only one possible return value of rand0_5() gives you each of 1-4, while two possible return values of rand0_5() give you 0:

rand0_5() return value: 0 1 2 3 4 5
rand0_5() % 5 result:   0 1 2 3 4 0

The general solution to this problem is modulo rejection, as explained in the article. Here's a C version:
https://github.com/openbsd/src/blob/dd1c5868edaa80b7ad9df54e8b3eae1c49c42319/lib/libc/crypt/arc4random_uniform.c#L32-L56

@rofl0r
Copy link
Owner

rofl0r commented Dec 8, 2023

rand() produces a 31-bit result, so the bias there should be minimal. also this is not a usage that needs to be cryptographically secure. apart from that, i believe that usage of rand_chain is not very common, as there are various issues with that approach.

@rofl0r rofl0r closed this as not planned Won't fix, can't repro, duplicate, stale Dec 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants