Re: Concurrent access to /dev/urandom

Theodore Ts'o
2004-12-08T01:31:17Z

On Tue, Dec 07, 2004 at 06:41:12PM -0500, Bernard Normier wrote:
> Reading concurrently /proc/sys/kernel/random/uuid also returns duplicates
> quite quickly ... which definitely looks like a bug. I included a small
> python test-case below.
> Can anybody suggest a work-around, for example a simple way to serialize
> access to /dev/urandom from multiple threads/processes on the same box?

This has been fixed in 2.6, but not yet in 2.4. Really, this should
be fixed in the kernel, but if you need to worry about this from the
perspective of user-level programs that might be running on unfixed
distribution kernels, the best way to deal with the problem is to use
/dev/urandom to seed a cryptographic random number generator, and then
mix in your pid and time/date into the CRNG.

For example (in Pseudo code):

char key[16];
int counter;

seed_random_number_generator()
{
key <- SHA(20 bytes from /dev/random || pid || time(0));
counter = 0;
}

get_random_bytes()
{
return SHA(counter++ || key);
}

This by the way is a generally a good thing to do in all cases;
/dev/urandom is designed to be used to seed a cryptographic random
generator. If you need a large number of cryptographic random
numbers, it's much faster to do it in user space than to try to do it
in the kernel.

- Ted