diff options
author | dequis <dx@dxzone.com.ar> | 2014-07-10 08:07:51 -0300 |
---|---|---|
committer | dequis <dx@dxzone.com.ar> | 2015-01-26 00:27:24 -0300 |
commit | 5eab298f82c97d9181f2fb07deea51db567750b2 (patch) | |
tree | 52cf08cd26f32661a9fd30fa04904fd85b5dab65 /lib/misc.c | |
parent | 11e782892c33d6ecae949bc610c075107c0cda89 (diff) |
random_bytes: Use /dev/urandom only, don't bother trying /dev/random
Also abort() if there's no /dev/urandom
See http://www.2uo.de/myths-about-urandom/ for details.
Diffstat (limited to 'lib/misc.c')
-rw-r--r-- | lib/misc.c | 69 |
1 files changed, 10 insertions, 59 deletions
@@ -413,69 +413,20 @@ signed int do_iconv( char *from_cs, char *to_cs, char *src, char *dst, size_t si return outbuf - dst; } -/* A pretty reliable random number generator. Tries to use the /dev/random - devices first, and falls back to the random number generator from libc - when it fails. Opens randomizer devices with O_NONBLOCK to make sure a - lack of entropy won't halt BitlBee. */ +/* A wrapper for /dev/urandom. + * If /dev/urandom is not present or not usable, it calls abort() + * to prevent bitlbee from working without a decent entropy source */ void random_bytes( unsigned char *buf, int count ) { - static int use_dev = -1; - - /* Actually this probing code isn't really necessary, is it? */ - if( use_dev == -1 ) + int fd; + if( ( ( fd = open( "/dev/urandom", O_RDONLY ) ) == -1 ) || + ( read( fd, buf, count ) == -1 ) ) { - if( access( "/dev/random", R_OK ) == 0 || access( "/dev/urandom", R_OK ) == 0 ) - use_dev = 1; - else - { - use_dev = 0; - srand( ( getpid() << 16 ) ^ time( NULL ) ); - } - } - - if( use_dev ) - { - int fd; - - /* At least on Linux, /dev/random can block if there's not - enough entropy. We really don't want that, so if it can't - give anything, use /dev/urandom instead. */ - if( ( fd = open( "/dev/random", O_RDONLY | O_NONBLOCK ) ) >= 0 ) - if( read( fd, buf, count ) == count ) - { - close( fd ); - return; - } - close( fd ); - - /* urandom isn't supposed to block at all, but just to be - sure. If it blocks, we'll disable use_dev and use the libc - randomizer instead. */ - if( ( fd = open( "/dev/urandom", O_RDONLY | O_NONBLOCK ) ) >= 0 ) - if( read( fd, buf, count ) == count ) - { - close( fd ); - return; - } - close( fd ); - - /* If /dev/random blocks once, we'll still try to use it - again next time. If /dev/urandom also fails for some - reason, stick with libc during this session. */ - - use_dev = 0; - srand( ( getpid() << 16 ) ^ time( NULL ) ); - } - - if( !use_dev ) - { - int i; - - /* Possibly the LSB of rand() isn't very random on some - platforms. Seems okay on at least Linux and OSX though. */ - for( i = 0; i < count; i ++ ) - buf[i] = rand() & 0xff; + log_message( LOGLVL_ERROR, "/dev/urandom not present - aborting" ); + abort(); } + + close( fd ); } int is_bool( char *value ) |