1 /* random.c  -	random number generator
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002,
3  *               2003, 2006 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <http://www.gnu.org/licenses/>.
19  */
20 
21 
22 /****************
23  * This random number generator is modelled after the one described
24  * in Peter Gutmann's Paper: "Software Generation of Practically
25  * Strong Random Numbers".
26  */
27 
28 
29 #include <config.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <assert.h>
33 #include <errno.h>
34 #include <string.h>
35 #include <time.h>
36 #ifndef _WIN32
37 #include <sys/time.h>
38 #endif
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <unistd.h>
42 #include <fcntl.h>
43 #ifdef HAVE_GETHRTIME
44 #include <sys/times.h>
45 #endif
46 #ifdef HAVE_GETTIMEOFDAY
47 #include <sys/time.h>
48 #endif
49 #ifdef HAVE_TIMES
50 #include <sys/times.h>
51 #endif
52 #ifdef HAVE_GETRUSAGE
53 #include <sys/resource.h>
54 #endif
55 #ifdef _WIN32
56 #include <process.h>
57 #endif
58 #include "util.h"
59 #include "rmd.h"
60 #include "ttyio.h"
61 #include "i18n.h"
62 #include "random.h"
63 #include "rand-internal.h"
64 #include "algorithms.h"
65 
66 #ifdef __VMS
67 # include <rmsdef.h>
68 # include "vms.h"
69 #endif /* def __VMS */
70 
71 #ifndef RAND_MAX   /* for SunOS */
72 #define RAND_MAX 32767
73 #endif
74 
75 /* 2008-03-31  SMS.
76  * VMS C RTL before V8.3 lacks byte-range file locking, but by default,
77  * a file opened for write access is not shared, so mutual exclusion can
78  * most generally be handled at the open().  */
79 
80 /* Check whether we can lock the seed file read write. */
81 #if defined(HAVE_FCNTL) && defined(HAVE_FTRUNCATE)      \
82   && !defined(HAVE_W32_SYSTEM) && !defined(__VMS)
83 #define LOCK_SEED_FILE 1
84 #else
85 #define LOCK_SEED_FILE 0
86 #endif
87 
88 
89 #if SIZEOF_UNSIGNED_LONG == 8
90 #define ADD_VALUE 0xa5a5a5a5a5a5a5a5
91 #elif SIZEOF_UNSIGNED_LONG == 4
92 #define ADD_VALUE 0xa5a5a5a5
93 #else
94 #error weird size for an unsigned long
95 #endif
96 
97 #define BLOCKLEN  64   /* hash this amount of bytes */
98 #define DIGESTLEN 20   /* into a digest of this length (rmd160) */
99 /* poolblocks is the number of digests which make up the pool
100  * and poolsize must be a multiple of the digest length
101  * to make the AND operations faster, the size should also be
102  * a multiple of ulong
103  */
104 #define POOLBLOCKS 30
105 #define POOLSIZE (POOLBLOCKS*DIGESTLEN)
106 #if (POOLSIZE % SIZEOF_UNSIGNED_LONG)
107 #error Please make sure that poolsize is a multiple of ulong
108 #endif
109 #define POOLWORDS (POOLSIZE / SIZEOF_UNSIGNED_LONG)
110 
111 
112 static int is_initialized;
113 #define MASK_LEVEL(a) do {if( a > 2 ) a = 2; else if( a < 0 ) a = 0; } while(0)
114 static char *rndpool;	/* allocated size is POOLSIZE+BLOCKLEN */
115 static char *keypool;	/* allocated size is POOLSIZE+BLOCKLEN */
116 static size_t pool_readpos;
117 static size_t pool_writepos;
118 static int pool_filled;
119 static int pool_balance;
120 static int just_mixed;
121 static int did_initial_extra_seeding;
122 static char *seed_file_name;
123 static int allow_seed_file_update;
124 static int no_seed_file_locking;
125 
126 static int secure_alloc;
127 static int quick_test;
128 static int faked_rng;
129 
130 
131 static void read_pool( byte *buffer, size_t length, int level );
132 static void add_randomness( const void *buffer, size_t length, int source );
133 static void random_poll(void);
134 static void read_random_source( int requester, size_t length, int level);
135 static int gather_faked( void (*add)(const void*, size_t, int), int requester,
136 						    size_t length, int level );
137 
138 static struct {
139     ulong mixrnd;
140     ulong mixkey;
141     ulong slowpolls;
142     ulong fastpolls;
143     ulong getbytes1;
144     ulong ngetbytes1;
145     ulong getbytes2;
146     ulong ngetbytes2;
147     ulong addbytes;
148     ulong naddbytes;
149 } rndstats;
150 
151 
152 static int (*
getfnc_gather_random(void)153 getfnc_gather_random (void))(void (*)(const void*, size_t, int), int,
154                         size_t, int)
155 {
156 #ifdef USE_ALL_RANDOM_MODULES
157   static int (*fnc)(void (*)(const void*, size_t, int), int, size_t, int);
158 
159   if (fnc)
160     return fnc;
161 # ifdef USE_RNDLINUX
162   if ( !access (NAME_OF_DEV_RANDOM, R_OK)
163        && !access (NAME_OF_DEV_URANDOM, R_OK))
164     {
165       fnc = rndlinux_gather_random;
166       return fnc;
167     }
168 # endif
169 # ifdef USE_RNDEGD
170   if ( rndegd_connect_socket (1) != -1 )
171     {
172       fnc = rndegd_gather_random;
173       return fnc;
174     }
175 # endif
176 # ifdef USE_RNDUNIX
177   fnc = rndunix_gather_random;
178   return fnc;
179 # endif
180 
181   log_fatal (_("no entropy gathering module detected\n"));
182 
183 #else
184 # ifdef USE_RNDLINUX
185   return rndlinux_gather_random;
186 # endif
187 # ifdef USE_RNDUNIX
188   return rndunix_gather_random;
189 # endif
190 # ifdef USE_RNDVMS
191   return rndvms_gather_random;
192 # endif
193 # ifdef USE_RNDEGD
194   return rndegd_gather_random;
195 # endif
196 # ifdef USE_RNDW32
197   return rndw32_gather_random;
198 # endif
199 # ifdef USE_RNDRISCOS
200   return rndriscos_gather_random;
201 # endif
202 #endif
203   return NULL;
204 }
205 
206 static int (*
getfnc_fast_random_poll(void)207 getfnc_fast_random_poll (void))( void (*)(const void*, size_t, int), int)
208 {
209 #ifdef USE_RNDW32
210   return rndw32_gather_random_fast;
211 #endif
212   return NULL;
213 }
214 
215 
216 
217 static void
initialize(void)218 initialize(void)
219 {
220     /* The data buffer is allocated somewhat larger, so that
221      * we can use this extra space (which is allocated in secure memory)
222      * as a temporary hash buffer */
223     rndpool = secure_alloc ? xmalloc_secure_clear(POOLSIZE+BLOCKLEN)
224 			   : xmalloc_clear(POOLSIZE+BLOCKLEN);
225     keypool = secure_alloc ? xmalloc_secure_clear(POOLSIZE+BLOCKLEN)
226 			   : xmalloc_clear(POOLSIZE+BLOCKLEN);
227     is_initialized = 1;
228 }
229 
230 static void
burn_stack(int bytes)231 burn_stack (int bytes)
232 {
233     char buf[128];
234 
235     wipememory(buf,sizeof buf);
236     bytes -= sizeof buf;
237     if (bytes > 0)
238         burn_stack (bytes);
239 }
240 
241 void
random_dump_stats()242 random_dump_stats()
243 {
244     fprintf(stderr,
245 	    "random usage: poolsize=%d mixed=%lu polls=%lu/%lu added=%lu/%lu\n"
246 	    "              outmix=%lu getlvl1=%lu/%lu getlvl2=%lu/%lu\n",
247 	POOLSIZE, rndstats.mixrnd, rndstats.slowpolls, rndstats.fastpolls,
248 		  rndstats.naddbytes, rndstats.addbytes,
249 	rndstats.mixkey, rndstats.ngetbytes1, rndstats.getbytes1,
250 		    rndstats.ngetbytes2, rndstats.getbytes2 );
251 }
252 
253 void
secure_randoxmalloc()254 secure_randoxmalloc()
255 {
256     secure_alloc = 1;
257 }
258 
259 
260 int
quick_random_gen(int onoff)261 quick_random_gen( int onoff )
262 {
263     int last;
264 
265     read_random_source(0,0,0); /* init */
266     last = quick_test;
267     if( onoff != -1 )
268 	quick_test = onoff;
269     return faked_rng? 1 : last;
270 }
271 
272 
273 /****************
274  * Fill the buffer with LENGTH bytes of cryptographically strong
275  * random bytes. level 0 is not very strong, 1 is strong enough
276  * for most usage, 2 is good for key generation stuff but may be very slow.
277  */
278 void
randomize_buffer(byte * buffer,size_t length,int level)279 randomize_buffer( byte *buffer, size_t length, int level )
280 {
281     char *p = get_random_bits( length*8, level, 1 );
282     memcpy( buffer, p, length );
283     xfree(p);
284 }
285 
286 
287 /* Randomize the MPI by setting it to NBITS of random of quality LEVEL.  */
288 void
randomize_mpi(MPI mpi,size_t nbits,int level)289 randomize_mpi (MPI mpi, size_t nbits, int level)
290 {
291   unsigned char *buffer;
292 
293   buffer = get_random_bits (nbits, level, mpi_is_secure (mpi));
294   mpi_set_buffer (mpi, buffer, (nbits+7)/8, 0);
295   xfree (buffer);
296 }
297 
298 
299 int
random_is_faked()300 random_is_faked()
301 {
302     if( !is_initialized )
303 	initialize();
304     return faked_rng || quick_test;
305 }
306 
307 /* Disable locking of seed files. */
308 void
random_disable_locking()309 random_disable_locking ()
310 {
311   no_seed_file_locking = 1;
312 }
313 
314 /****************
315  * Return a pointer to a randomized buffer of level 0 and LENGTH bits
316  * caller must free the buffer.
317  * Note: The returned value is rounded up to bytes.
318  */
319 byte *
get_random_bits(size_t nbits,int level,int secure)320 get_random_bits( size_t nbits, int level, int secure )
321 {
322     byte *buf, *p;
323     size_t nbytes = (nbits+7)/8;
324 
325     if( quick_test && level > 1 )
326 	level = 1;
327     MASK_LEVEL(level);
328     if( level == 1 ) {
329 	rndstats.getbytes1 += nbytes;
330 	rndstats.ngetbytes1++;
331     }
332     else if( level >= 2 ) {
333 	rndstats.getbytes2 += nbytes;
334 	rndstats.ngetbytes2++;
335     }
336 
337     buf = secure && secure_alloc ? xmalloc_secure( nbytes ) : xmalloc( nbytes );
338     for( p = buf; nbytes > 0; ) {
339 	size_t n = nbytes > POOLSIZE? POOLSIZE : nbytes;
340 	read_pool( p, n, level );
341 	nbytes -= n;
342 	p += n;
343     }
344     return buf;
345 }
346 
347 
348 /****************
349  * Mix the pool
350  */
351 static void
mix_pool(byte * pool)352 mix_pool(byte *pool)
353 {
354     char *hashbuf = pool + POOLSIZE;
355     char *p, *pend;
356     int i, n;
357     RMD160_CONTEXT md;
358 
359     rmd160_init( &md );
360 #if DIGESTLEN != 20
361 #error must have a digest length of 20 for ripe-md-160
362 #endif
363     /* pool -> pool' */
364     pend = pool + POOLSIZE;
365     memcpy(hashbuf, pend - DIGESTLEN, DIGESTLEN );
366     memcpy(hashbuf+DIGESTLEN, pool, BLOCKLEN-DIGESTLEN);
367     rmd160_mixblock( &md, hashbuf);
368     memcpy(pool, hashbuf, DIGESTLEN);
369 
370     /* Loop for the remaining iterations.  */
371     p = pool;
372     for( n=1; n < POOLBLOCKS; n++ ) {
373 	if( p + BLOCKLEN < pend )
374 	    memcpy(hashbuf, p, BLOCKLEN);
375 	else {
376 	    char *pp = p;
377 	    for(i=0; i < BLOCKLEN; i++ ) {
378 		if( pp >= pend )
379 		    pp = pool;
380 		hashbuf[i] = *pp++;
381 	    }
382 	}
383 
384 	rmd160_mixblock( &md, hashbuf);
385         p += DIGESTLEN;
386 	memcpy(p, hashbuf, DIGESTLEN);
387     }
388     burn_stack (384); /* for the rmd160_mixblock() */
389 }
390 
391 
392 void
set_random_seed_file(const char * name)393 set_random_seed_file( const char *name )
394 {
395     if( seed_file_name )
396 	BUG();
397     seed_file_name = xstrdup( name );
398 }
399 
400 
401 /* Lock an open file identified by file descriptor FD and wait a
402    reasonable time to succeed.  With FOR_WRITE set to true a Rite lock
403    will be taken.  FNAME is used only for diagnostics. Returns 0 on
404    success or -1 on error. */
405 static int
lock_seed_file(int fd,const char * fname,int for_write)406 lock_seed_file (int fd, const char *fname, int for_write)
407 {
408 #if LOCK_SEED_FILE
409   struct flock lck;
410   struct timeval tv;
411   int backoff=0;
412 
413   if (no_seed_file_locking)
414     return 0;
415 
416   /* We take a lock on the entire file. */
417   memset (&lck, 0, sizeof lck);
418   lck.l_type = for_write? F_WRLCK : F_RDLCK;
419   lck.l_whence = SEEK_SET;
420 
421   while (fcntl (fd, F_SETLK, &lck) == -1)
422     {
423       if (errno != EAGAIN && errno != EACCES)
424         {
425           log_info (_("can't lock `%s': %s\n"), fname, strerror (errno));
426           return -1;
427         }
428 
429       if (backoff > 2) /* Show the first message after ~3.75 seconds. */
430         log_info( _("waiting for lock on `%s'...\n"), fname);
431 
432       tv.tv_sec = backoff;
433       tv.tv_usec = 250000;
434       select (0, NULL, NULL, NULL, &tv);
435       if (backoff < 10)
436         backoff++ ;
437     }
438 #endif /*LOCK_SEED_FILE*/
439   return 0;
440 }
441 
442 
443 
444 /****************
445  * Read in a seed form the random_seed file
446  * and return true if this was successful
447  */
448 static int
read_seed_file(void)449 read_seed_file(void)
450 {
451     int fd;
452     struct stat sb;
453     unsigned char buffer[POOLSIZE];
454     int n;
455 
456     if( !seed_file_name )
457 	return 0;
458 
459 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
460     fd = open( seed_file_name, O_RDONLY | O_BINARY );
461 #elif defined( __VMS)
462     /* We're only reading, so allow others to do anything. */
463     fd = open( seed_file_name, O_RDONLY, 0777, "shr=get,put,upd" );
464 #else
465     fd = open( seed_file_name, O_RDONLY );
466 #endif
467     if( fd == -1 && errno == ENOENT) {
468 	allow_seed_file_update = 1;
469 	return 0;
470     }
471 
472     if( fd == -1 ) {
473 	log_info(_("can't open `%s': %s\n"), seed_file_name, strerror(errno) );
474 	return 0;
475     }
476     if (lock_seed_file (fd, seed_file_name, 0))
477       {
478         close (fd);
479         return 0;
480       }
481 
482     if( fstat( fd, &sb ) ) {
483 	log_info(_("can't stat `%s': %s\n"), seed_file_name, strerror(errno) );
484 	close(fd);
485 	return 0;
486     }
487     if( !S_ISREG(sb.st_mode) ) {
488 	log_info(_("`%s' is not a regular file - ignored\n"), seed_file_name );
489 	close(fd);
490 	return 0;
491     }
492     if( !sb.st_size ) {
493 	log_info(_("note: random_seed file is empty\n") );
494 	close(fd);
495 	allow_seed_file_update = 1;
496 	return 0;
497     }
498     if( sb.st_size != POOLSIZE ) {
499 	log_info(_("WARNING: invalid size of random_seed file - not used\n") );
500 	close(fd);
501 	return 0;
502     }
503 
504     do {
505 	n = read( fd, buffer, POOLSIZE );
506     } while( n == -1 && errno == EINTR );
507     /* The N==0, ENOENT, and N!=POOLSIZE cases may happen if another
508        process is updating the file.  For consistency we use the same
509        recovery strategy as with the pre-read checks.  */
510     if (!n) {
511         log_info(_("note: random_seed file is empty\n") );
512         allow_seed_file_update = 1;
513         close(fd);
514         return 0;
515     }
516     else if( n == -1 && errno == ENOENT) {
517         /* On a Unix system that should never happen.  However, I can
518            imagine this error code on non-inode based systems.  */
519 	log_info(_("can't read `%s': %s\n"), seed_file_name, strerror(errno));
520         allow_seed_file_update = 1;
521 	close(fd);
522 	return 0;
523     }
524     else if( n == -1 ) {
525         /* A real read error.  */
526 	log_fatal(_("can't read `%s': %s\n"), seed_file_name,strerror(errno) );
527 	close(fd);
528 	return 0;
529     }
530     else if ( n != POOLSIZE ) {
531         log_info(_("WARNING: invalid size of random_seed file - not used\n") );
532 	close(fd);
533 	return 0;
534     }
535 
536     close(fd);
537 
538     add_randomness( buffer, POOLSIZE, 0 );
539     /* add some minor entropy to the pool now (this will also force a mixing) */
540     {	pid_t x = getpid();
541 	add_randomness( &x, sizeof(x), 0 );
542     }
543     {	time_t x = time(NULL);
544 	add_randomness( &x, sizeof(x), 0 );
545     }
546     {	clock_t x = clock();
547 	add_randomness( &x, sizeof(x), 0 );
548     }
549     /* And read a few bytes from our entropy source.  By using
550      * a level of 0 this will not block and might not return anything
551      * with some entropy drivers, however the rndlinux driver will use
552      * /dev/urandom and return some stuff - Do not read too much as we
553      * want to be friendly to the scarce system entropy resource. */
554     read_random_source( 0, 16, 0 );
555 
556     allow_seed_file_update = 1;
557     return 1;
558 }
559 
560 void
update_random_seed_file()561 update_random_seed_file()
562 {
563     ulong *sp, *dp;
564     int fd, i;
565 
566     if( !seed_file_name || !is_initialized || !pool_filled )
567 	return;
568     if( !allow_seed_file_update ) {
569 	log_info(_("note: random_seed file not updated\n"));
570 	return;
571     }
572 
573 
574     /* copy the entropy pool to a scratch pool and mix both of them */
575     for(i=0,dp=(ulong*)keypool, sp=(ulong*)rndpool;
576 				    i < POOLWORDS; i++, dp++, sp++ ) {
577 	*dp = *sp + ADD_VALUE;
578     }
579     mix_pool(rndpool); rndstats.mixrnd++;
580     mix_pool(keypool); rndstats.mixkey++;
581 
582 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
583     fd = open( seed_file_name, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY,
584 							S_IRUSR|S_IWUSR );
585 #else
586 # if LOCK_SEED_FILE
587     fd = open( seed_file_name, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR );
588 # else
589 #  ifdef __VMS
590     /* Open the seed file for exclusive write access, but allow other
591      * readers.  Loop until success.  Complain after a few failures.  */
592     {
593         int backoff = 0;
594 
595         while ((fd = open( seed_file_name,
596                            O_WRONLY|O_CREAT,
597                            S_IRUSR|S_IWUSR,
598                            "shr=get")) == -1 )
599         {
600           if ((errno != EVMSERR) || (vaxc$errno != RMS$_FLK))
601             {
602               /* Some unexpected open failure. */
603               log_info (_("can't lock `%s': %s\n"),
604                         seed_file_name, strerror (errno));
605               return;
606             }
607 
608           if (backoff > 2) /* Show the first message after ~3.75 seconds. */
609             log_info( _("waiting for lock on `%s'...\n"), seed_file_name);
610 
611           wait_vms( backoff+ 0.25);
612           if (backoff < 10)
613             backoff++ ;
614         }
615     }
616 #  else /* !def __VMS */
617     fd = open( seed_file_name, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR );
618 #  endif /* !def __VMS */
619 # endif
620 #endif
621     if( fd == -1 ) {
622 	log_info(_("can't create `%s': %s\n"), seed_file_name, strerror(errno));
623 	return;
624     }
625 
626     if (lock_seed_file (fd, seed_file_name, 1))
627       {
628         close (fd);
629         return;
630       }
631 #if LOCK_SEED_FILE
632     if (ftruncate (fd, 0))
633       {
634 	log_info(_("can't write `%s': %s\n"), seed_file_name, strerror(errno));
635         close (fd);
636         return;
637       }
638 #endif /*LOCK_SEED_FILE*/
639 
640     do {
641 	i = write( fd, keypool, POOLSIZE );
642     } while( i == -1 && errno == EINTR );
643     if( i != POOLSIZE ) {
644 	log_info(_("can't write `%s': %s\n"), seed_file_name, strerror(errno) );
645     }
646     if( close(fd) )
647 	log_info(_("can't close `%s': %s\n"), seed_file_name, strerror(errno) );
648 }
649 
650 
651 static void
read_pool(byte * buffer,size_t length,int level)652 read_pool( byte *buffer, size_t length, int level )
653 {
654     int i;
655     ulong *sp, *dp;
656 
657     if( length > POOLSIZE ) {
658 	log_bug("too many random bits requested\n");
659     }
660 
661     if( !pool_filled ) {
662 	if( read_seed_file() )
663 	    pool_filled = 1;
664     }
665 
666     /* For level 2 quality (key generation) we alwas make
667      * sure that the pool has been seeded enough initially */
668     if( level == 2 && !did_initial_extra_seeding ) {
669 	size_t needed;
670 
671 	pool_balance = 0;
672 	needed = length - pool_balance;
673 	if( needed < POOLSIZE/2 )
674 	    needed = POOLSIZE/2;
675 	else if( needed > POOLSIZE )
676 	    BUG();
677 	read_random_source( 3, needed, 2 );
678 	pool_balance += needed;
679 	did_initial_extra_seeding=1;
680     }
681 
682     /* for level 2 make sure that there is enough random in the pool */
683     if( level == 2 && pool_balance < length ) {
684 	size_t needed;
685 
686 	if( pool_balance < 0 )
687 	    pool_balance = 0;
688 	needed = length - pool_balance;
689 	if( needed > POOLSIZE )
690 	    BUG();
691 	read_random_source( 3, needed, 2 );
692 	pool_balance += needed;
693     }
694 
695     /* make sure the pool is filled */
696     while( !pool_filled )
697 	random_poll();
698 
699     /* do always a fast random poll */
700     fast_random_poll();
701 
702     if( !level ) { /* no need for cryptographic strong random */
703 	/* create a new pool */
704 	for(i=0,dp=(ulong*)keypool, sp=(ulong*)rndpool;
705 				    i < POOLWORDS; i++, dp++, sp++ )
706 	    *dp = *sp + ADD_VALUE;
707 	/* must mix both pools */
708 	mix_pool(rndpool); rndstats.mixrnd++;
709 	mix_pool(keypool); rndstats.mixkey++;
710 	memcpy( buffer, keypool, length );
711     }
712     else {
713 	/* mix the pool (if add_randomness() didn't it) */
714 	if( !just_mixed ) {
715 	    mix_pool(rndpool);
716 	    rndstats.mixrnd++;
717 	}
718 	/* create a new pool */
719 	for(i=0,dp=(ulong*)keypool, sp=(ulong*)rndpool;
720 				    i < POOLWORDS; i++, dp++, sp++ )
721 	    *dp = *sp + ADD_VALUE;
722 	/* and mix both pools */
723 	mix_pool(rndpool); rndstats.mixrnd++;
724 	mix_pool(keypool); rndstats.mixkey++;
725 	/* read the required data
726 	 * we use a readpoiter to read from a different postion each
727 	 * time */
728 	while( length-- ) {
729 	    *buffer++ = keypool[pool_readpos++];
730 	    if( pool_readpos >= POOLSIZE )
731 		pool_readpos = 0;
732 	    pool_balance--;
733 	}
734 	if( pool_balance < 0 )
735 	    pool_balance = 0;
736 	/* and clear the keypool */
737 	wipememory(keypool, POOLSIZE);
738     }
739 }
740 
741 
742 /****************
743  * Add LENGTH bytes of randomness from buffer to the pool.
744  * source may be used to specify the randomness source.
745  * Source is:
746  *	0 - used ony for initialization
747  *	1 - fast random poll function
748  *	2 - normal poll function
749  *	3 - used when level 2 random quality has been requested
750  *	    to do an extra pool seed.
751  */
752 static void
add_randomness(const void * buffer,size_t length,int source)753 add_randomness( const void *buffer, size_t length, int source )
754 {
755     const byte *p = buffer;
756 
757     if( !is_initialized )
758 	initialize();
759     rndstats.addbytes += length;
760     rndstats.naddbytes++;
761     while( length-- ) {
762 	rndpool[pool_writepos++] ^= *p++;
763 	if( pool_writepos >= POOLSIZE ) {
764 	    if( source > 1 )
765 		pool_filled = 1;
766 	    pool_writepos = 0;
767 	    mix_pool(rndpool); rndstats.mixrnd++;
768 	    just_mixed = !length;
769 	}
770     }
771 }
772 
773 
774 
775 static void
random_poll()776 random_poll()
777 {
778     rndstats.slowpolls++;
779     read_random_source( 2, POOLSIZE/5, 1 );
780 }
781 
782 
783 void
fast_random_poll()784 fast_random_poll()
785 {
786     static int (*fnc)( void (*)(const void*, size_t, int), int) = NULL;
787     static int initialized = 0;
788 
789     rndstats.fastpolls++;
790     if( !initialized ) {
791 	if( !is_initialized )
792 	    initialize();
793 	initialized = 1;
794 	fnc = getfnc_fast_random_poll();
795     }
796     if( fnc ) {
797 	(*fnc)( add_randomness, 1 );
798 	return;
799     }
800 
801     /* fall back to the generic function */
802 #if defined(HAVE_GETHRTIME) && !defined(HAVE_BROKEN_GETHRTIME)
803     {	hrtime_t tv;
804         /* On some Solaris and HPUX system gethrtime raises an SIGILL, but we
805          * checked this with configure */
806 	tv = gethrtime();
807 	add_randomness( &tv, sizeof(tv), 1 );
808     }
809 #elif defined (HAVE_GETTIMEOFDAY)
810     {	struct timeval tv;
811 	if( gettimeofday( &tv, NULL ) )
812 	    BUG();
813 	add_randomness( &tv.tv_sec, sizeof(tv.tv_sec), 1 );
814 	add_randomness( &tv.tv_usec, sizeof(tv.tv_usec), 1 );
815     }
816 #elif defined (HAVE_CLOCK_GETTIME)
817     {	struct timespec tv;
818 	if( clock_gettime( CLOCK_REALTIME, &tv ) == -1 )
819 	    BUG();
820 	add_randomness( &tv.tv_sec, sizeof(tv.tv_sec), 1 );
821 	add_randomness( &tv.tv_nsec, sizeof(tv.tv_nsec), 1 );
822     }
823 #elif defined (HAVE_TIMES)
824     {	struct tms buf;
825         if( times( &buf ) == -1 )
826 	    BUG();
827 	add_randomness( &buf, sizeof buf, 1 );
828     }
829 #endif
830 #ifdef HAVE_GETRUSAGE
831 #ifndef RUSAGE_SELF
832 #ifdef __GCC__
833 #warning There is no RUSAGE_SELF on this system
834 #endif
835 #else
836     {	struct rusage buf;
837         /* QNX/Neutrino does return ENOSYS - so we just ignore it and
838          * add whatever is in buf.  In a chroot environment it might not
839          * work at all (i.e. because /proc/ is not accessible), so we better
840          * ignore all error codes and hope for the best
841          */
842         getrusage( RUSAGE_SELF, &buf );
843 
844 	add_randomness( &buf, sizeof buf, 1 );
845 	wipememory( &buf, sizeof buf );
846     }
847 #endif
848 #endif
849     /* time and clock are available on all systems - so
850      * we better do it just in case one of the above functions
851      * didn't work */
852     {	time_t x = time(NULL);
853 	add_randomness( &x, sizeof(x), 1 );
854     }
855     {	clock_t x = clock();
856 	add_randomness( &x, sizeof(x), 1 );
857     }
858 }
859 
860 
861 
862 static void
read_random_source(int requester,size_t length,int level)863 read_random_source( int requester, size_t length, int level )
864 {
865     static int (*fnc)(void (*)(const void*, size_t, int), int,
866 						    size_t, int) = NULL;
867     if( !fnc ) {
868 	if( !is_initialized )
869 	    initialize();
870 	fnc = getfnc_gather_random();
871 	if( !fnc ) {
872 	    faked_rng = 1;
873 	    fnc = gather_faked;
874 	}
875 	if( !requester && !length && !level )
876 	    return; /* init only */
877     }
878     if( (*fnc)( add_randomness, requester, length, level ) < 0 )
879 	log_fatal("No way to gather entropy for the RNG\n");
880 }
881 
882 
883 static int
gather_faked(void (* add)(const void *,size_t,int),int requester,size_t length,int level)884 gather_faked( void (*add)(const void*, size_t, int), int requester,
885 	      size_t length, int level )
886 {
887     static int initialized=0;
888     size_t n;
889     char *buffer, *p;
890 
891     if( !initialized ) {
892 	log_info(_("WARNING: using insecure random number generator!!\n"));
893 	tty_printf(_("The random number generator is only a kludge to let\n"
894 		   "it run - it is in no way a strong RNG!\n\n"
895 		   "DON'T USE ANY DATA GENERATED BY THIS PROGRAM!!\n\n"));
896 	initialized=1;
897 #ifdef HAVE_RAND
898 	srand(make_timestamp()*getpid());
899 #else
900 	srandom(make_timestamp()*getpid());
901 #endif
902     }
903 
904     p = buffer = xmalloc( length );
905     n = length;
906 #ifdef HAVE_RAND
907     while( n-- )
908 	*p++ = ((unsigned)(1 + (int) (256.0*rand()/(RAND_MAX+1.0)))-1);
909 #else
910     while( n-- )
911 	*p++ = ((unsigned)(1 + (int) (256.0*random()/(RAND_MAX+1.0)))-1);
912 #endif
913     add_randomness( buffer, length, requester );
914     xfree(buffer);
915     return 0; /* okay */
916 }
917