Archive

Posts Tagged ‘/dev/random’

Problem with random generator /dev/random

June 27th, 2013 No comments

Yesterday called my friend that he wants to migrate one website to his webserver. I’ve created hosting for him and then problem began. When he accessed one .php file browser was “working”, but nothing happened. There was no log about problems on server. Nothing.

So I started to investigate problem. CPU was fine, RAM was fine, disk queue lenght was fine. So I focused on particular .php file. I ran following command:

strace php -f PATH_TO_PHP_FILE

and I saw:

strace PHP file

and this was not moving forward. After couple tens of seconds it was moved one line futher. It looks like problem with /dev/random. When I looked into file crypt.class.php

PHP file source

I saw function mcrypt_create_iv() which creates an initialization vector from random source. And that’s it, random source is defined as /dev/random. You can change source by defining second parameter to value MCRYPT_DEV_URANDOM. When I tested it with second parameter set to value MCRYPT_DEV_URANDOM everything worked like it should. Php file was generated normally. When I tried to do cat /dev/random I received some random characters and after couple tens of second I’ve got more random characters:

Slow /dev/random

So this look like slow /dev/random. When I tried cat /dev/urandom my screen was full of random characters. I started to look for differences between /dev/random and /dev/urandom. Some random generator is implemented in linux kernel which generates random bits into entropy pool. When entropy pool is empty, reads from /dev/random will block until additional random bits are generated. Ublocked/non-blocing random source /dev/urandom will not block when entropy pool is empty (it will reuse existing random bits). You can check how many bits are generated in entropy pool by looking into file cat /proc/sys/kernel/random/entropy_avail. More info here.

So how to make faster generation of random bits into entropy pool? There is daemon which can help you out rng-tools. To make it work in Debian you have to do following:

  • apt-get install rng-tools
  • Edit file /etc/default/rng-tools
  • In file set HRNGDEVICE=/dev/urandom
  • Start up daemon /etc/init.d/rng-tools start

When I started this daemon /dev/random starts generate lots of random characters. 🙂

So this took four hours of my life. I’m working with Linux couple years, but I had no idea between /dev/random and /dev/urandom. I’m smarter now.

Have a nice day,