http://qs321.pair.com?node_id=1011846


in reply to Re^2: Debugging cgi-bin script
in thread Debugging cgi-bin script

This may be a bit off topic, but...

Designing your own random number generator in a high-level language is a terrible, terrible idea. There just isn't any way for a normal process to get access to as much entropy as the operating system can gather from timing I/O completions.

How many bits of entropy are actually in the return from get_session_id? Let's add it up: essentially nothing from the call to time() (because the attacker knows what time it is), about 13 bits from the memory address from {} (estimated on perl 5.14.3 on Linux 3.6), 32 bits from the call to rand() (because an strace shows that perl seeded it by reading four bytes from /dev/urandom), and 15 bits at most from $$ (unless you change /proc/sys/kernel/pid_max and start a lot of processes on your system).

That's at most 60 bits of randomness that get_session_id tries to magically inflate into 128 bits by calling Digest::MD5::md5_hex a second time. Whatever the second call was intended to do, it's not going to be able to do it.

Both Solaris and RHEL have had /dev/urandom for a long time; it became standard in Solaris 9 in 2002 and was available as a patch since 2.6 in 1997. It's been standard in every release of RHEL, and was in the old pre-RHEL Red Hat since 4.0 in 1996.

To make sure your /dev/urandom is working, try

od -x /dev/urandom | head

To use it in your script, try this:

sub get_session_id { require Digest::MD5; open my $ur, "<", "/dev/urandom" or die "Cannot open /dev/urandom, $!"; my $buflen = sysread( $ur, my $buf, 16 ); defined $buflen or die "Failed to read /dev/urandom, $!"; $buflen == 16 or die "Tried to read 16 bytes from /dev/urandom but got $bufl +en"; Digest::MD5::md5_hex( $buf ); }

Incidentally, never use /dev/random instead of /dev/urandom in this application. For a web server, it exposes the server to a denial-of-service attack where the attacker removes entropy from the system-wide pool, by starting new sessions, faster than entropy is added to the pool, by (mostly) I/O completions.

Replies are listed 'Best First'.
Re^4: Debugging cgi-bin script
by Anonymous Monk on Jan 06, 2013 at 09:10 UTC

    Designing your own random number generator in a high-level language is a terrible, terrible idea.

    :) FWIW, merlyn didn't design it, he copied from the fallback Apache::Session::Generate::MD5

    I don't know from entrophy and randomness, but this isn't encryption we're dealing with, no authentication or authorization, no financial transactions -- if the attacker has access to the application, guessing doesn't get him anything he didn't already have access to

    You might like Re^3: Randomness encountered with CGI Session where afoken talks bits

    FYI/FMI Session::Token - Portable, secure, efficient, simple random session token generation that satisfies those OWASP recommendations