/[winpt]/trunk/Gnupg/random.c
ViewVC logotype

Annotation of /trunk/Gnupg/random.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2 - (hide annotations)
Mon Jan 31 11:02:21 2005 UTC (20 years, 1 month ago) by twoaday
File MIME type: text/plain
File size: 16293 byte(s)
WinPT initial checkin.


1 twoaday 2 /* random.c - random number generator
2     * Copyright (C) 1998, 2000, 2001 Free Software Foundation, Inc.
3     * Copyright (C) 2001, 2002, 2003 Timo Schulz
4     *
5     * This file is part of GPGLIB.
6     *
7     * GPGLIB 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 2 of the License, or
10     * (at your option) any later version.
11     *
12     * GPGLIB 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 GPGLIB; if not, write to the Free Software Foundation,
19     * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
20     *
21     * ChangeLog:
22     *
23     * - Heavily modified to get rid of the log_xxx functions and other stuff
24     * that uses the console.
25     * - Applied the XOR bug fix -ts 2002
26     * - Removed Libgcrypt malloc stubs and use malloc, calloc and friends directly.
27     */
28    
29     /****************
30     * This random number generator is modelled after the one described
31     * in Peter Gutmann's Paper: "Software Generation of Practically
32     * Strong Random Numbers".
33     */
34    
35     #include <windows.h>
36     #include <stdio.h>
37     #include <stdlib.h>
38     #include <assert.h>
39     #include <errno.h>
40     #include <string.h>
41     #include <sys/types.h>
42     #include <sys/stat.h>
43     #include <time.h>
44     #include <process.h>
45    
46     #include "openpgp.h"
47     #include "md.h"
48    
49    
50     int gather_random_fast( void (*add)(const void*, size_t, int), int requester );
51    
52     void _gpg_secure_random_alloc( void );
53     int _gpg_quick_random_gen( int onoff );
54     int _gpg_random_is_faked(void);
55     byte *_gpg_get_random_bits( size_t nbits, int level, int secure );
56     void _gpg_fast_random_poll( void );
57     int gather_random( void (*add)(const void*, size_t, int), int requester,
58     size_t length, int level );
59    
60     #define fast_random_poll() _gpg_fast_random_poll ()
61    
62     #define SIZEOF_UNSIGNED_LONG 4
63    
64     #if SIZEOF_UNSIGNED_LONG == 8
65     #define ADD_VALUE 0xa5a5a5a5a5a5a5a5
66     #elif SIZEOF_UNSIGNED_LONG == 4
67     #define ADD_VALUE 0xa5a5a5a5
68     #else
69     #error "weird size for an unsigned long"
70     #endif
71    
72     #define BLOCKLEN 64 /* hash this amount of bytes */
73     #define DIGESTLEN 20 /* into a digest of this length (rmd160) */
74     /* poolblocks is the number of digests which make up the pool
75     * and poolsize must be a multiple of the digest length
76     * to make the AND operations faster, the size should also be
77     * a multiple of u32
78     */
79     #define POOLBLOCKS 30
80     #define POOLSIZE (POOLBLOCKS*DIGESTLEN)
81     #if (POOLSIZE % SIZEOF_UNSIGNED_LONG)
82     #error Please make sure that poolsize is a multiple of u32
83     #endif
84     #define POOLWORDS (POOLSIZE / SIZEOF_UNSIGNED_LONG)
85    
86    
87     static int is_initialized;
88     #define MASK_LEVEL(a) do {if( a > 2 ) a = 2; else if( a < 0 ) a = 0; } while(0)
89     static char *rndpool; /* allocated size is POOLSIZE+BLOCKLEN */
90     static char *keypool; /* allocated size is POOLSIZE+BLOCKLEN */
91     static size_t pool_readpos;
92     static size_t pool_writepos;
93     static int pool_filled;
94     static int pool_balance;
95     static int just_mixed;
96     static int did_initial_extra_seeding;
97     static char *seed_file_name;
98     static int allow_seed_file_update;
99    
100     static int secure_alloc;
101     static int quick_test;
102     static int faked_rng;
103    
104    
105     static byte *get_random_bytes( size_t nbytes, int level, int secure );
106     static void read_pool( byte *buffer, size_t length, int level );
107     static void add_randomness( const void *buffer, size_t length, int source );
108     static void random_poll(void);
109     static void read_random_source( int requester, size_t length, int level);
110     static int gather_faked( void (*add)(const void*, size_t, int), int requester,
111     size_t length, int level );
112    
113     static struct {
114     u32 mixrnd;
115     u32 mixkey;
116     u32 slowpolls;
117     u32 fastpolls;
118     u32 getbytes1;
119     u32 ngetbytes1;
120     u32 getbytes2;
121     u32 ngetbytes2;
122     u32 addbytes;
123     u32 naddbytes;
124     } rndstats;
125    
126     static void
127     initialize(void)
128     {
129     /* The data buffer is allocated somewhat larger, so that
130     * we can use this extra space (which is allocated in secure memory)
131     * as a temporary hash buffer */
132     rndpool = secure_alloc ? calloc(1,POOLSIZE+BLOCKLEN)
133     : calloc(1,POOLSIZE+BLOCKLEN);
134     keypool = secure_alloc ? calloc(1,POOLSIZE+BLOCKLEN)
135     : calloc(1,POOLSIZE+BLOCKLEN);
136     is_initialized = 1;
137     }
138    
139     static void
140     burn_stack (int bytes)
141     {
142     char buf[128];
143    
144     memset (buf, 0, sizeof buf);
145     bytes -= sizeof buf;
146     if (bytes > 0)
147     burn_stack (bytes);
148     }
149    
150     static void
151     random_err(const char *format, ...)
152     {
153     char log[8192];
154     va_list arg_ptr;
155    
156     va_start( arg_ptr, format );
157     _vsnprintf( log, sizeof log-1, format, arg_ptr );
158     MessageBox( NULL, log, "Crypto RNG", MB_ICONERROR|MB_OK );
159     va_end( arg_ptr );
160     } /* random_err */
161    
162    
163     void
164     _gpg_secure_random_alloc( void )
165     {
166     secure_alloc = 1;
167     }
168    
169    
170     int
171     gpg_quick_random_gen( int onoff )
172     {
173     int last;
174    
175     read_random_source(0,0,0); /* init */
176     last = quick_test;
177     if( onoff != -1 )
178     quick_test = onoff;
179     return faked_rng? 1 : last;
180     }
181    
182    
183     /****************
184     * Fill the buffer with LENGTH bytes of cryptographically strong
185     * random bytes. level 0 is not very strong, 1 is strong enough
186     * for most usage, 2 is good for key generation stuff but may be very slow.
187     */
188     void
189     gpg_randomize( byte *buffer, size_t length, int level )
190     {
191     char *p = get_random_bytes( length, level, 1 );
192     memcpy( buffer, p, length );
193     free(p);
194     }
195    
196    
197     char
198     gpg_random_char( int level )
199     {
200     byte c = 0;
201    
202     while ( !isalnum( (int)c ) )
203     gpg_randomize(&c, 1, level);
204     return c % 127;
205     }
206    
207    
208     int
209     _gpg_random_is_faked()
210     {
211     if( !is_initialized )
212     initialize();
213     return faked_rng || quick_test;
214     }
215    
216     /****************
217     * Return a pointer to a randomized buffer of level 0 and LENGTH bits
218     * caller must free the buffer.
219     * Note: The returned value is rounded up to bytes.
220     */
221     static byte *
222     get_random_bytes( size_t nbytes, int level, int secure )
223     {
224     byte *buf, *p;
225    
226     if( quick_test && level > 1 )
227     level = 1;
228     MASK_LEVEL(level);
229     if( level == 1 ) {
230     rndstats.getbytes1 += nbytes;
231     rndstats.ngetbytes1++;
232     }
233     else if( level >= 2 ) {
234     rndstats.getbytes2 += nbytes;
235     rndstats.ngetbytes2++;
236     }
237    
238     buf = secure && secure_alloc ? malloc( nbytes ) : malloc( nbytes );
239     for( p = buf; nbytes > 0; ) {
240     size_t n = nbytes > POOLSIZE? POOLSIZE : nbytes;
241     read_pool( p, n, level );
242     nbytes -= n;
243     p += n;
244     }
245     return buf;
246     }
247    
248     void *
249     gpg_random_bytes( size_t nbytes, int level )
250     {
251     return get_random_bytes( nbytes, level, 0 );
252     }
253    
254     void *
255     gpg_random_bytes_secure( size_t nbytes, int level )
256     {
257     return get_random_bytes( nbytes, level, 1 );
258     }
259    
260    
261     /****************
262     * Mix the pool
263     */
264     static void
265     mix_pool(byte *pool)
266     {
267     char *hashbuf = pool + POOLSIZE;
268     char *p, *pend;
269     int i, n;
270     RMD160_CONTEXT md;
271    
272     rmd160_init( &md );
273     /* loop over the pool */
274     pend = pool + POOLSIZE;
275     memcpy(hashbuf, pend - DIGESTLEN, DIGESTLEN );
276     memcpy(hashbuf+DIGESTLEN, pool, BLOCKLEN-DIGESTLEN);
277     rmd160_mixblock( &md, hashbuf);
278     memcpy(pool, hashbuf, 20 );
279    
280     p = pool;
281     for( n=1; n < POOLBLOCKS; n++ ) {
282     memcpy(hashbuf, p, DIGESTLEN );
283     p += DIGESTLEN;
284     if( p+DIGESTLEN+BLOCKLEN < pend )
285     memcpy(hashbuf+DIGESTLEN, p+DIGESTLEN, BLOCKLEN-DIGESTLEN);
286     else {
287     char *pp = p+DIGESTLEN;
288     for(i=DIGESTLEN; i < BLOCKLEN; i++ ) {
289     if( pp >= pend )
290     pp = pool;
291     hashbuf[i] = *pp++;
292     }
293     }
294     rmd160_mixblock( &md, hashbuf);
295     memcpy(p, hashbuf, 20 );
296     }
297     burn_stack (200); /* for the rmd160_mixblock() */
298     }
299    
300     void
301     _gpg_set_random_seed_file( const char *name )
302     {
303     if( seed_file_name )
304     random_err("Ohhh jeee, this is a BUG; File %s, Line %d", __FILE__, __LINE__);
305     seed_file_name = strdup( name );
306     }
307    
308     /****************
309     * Read in a seed form the random_seed file
310     * and return true if this was successful
311     */
312     static int
313     read_seed_file()
314     {
315     int fd;
316     FILE *fp;
317     struct stat sb;
318     unsigned char buffer[POOLSIZE];
319     int n;
320    
321     if( !seed_file_name )
322     return 0;
323    
324     fp = fopen( seed_file_name, "rb" );
325     if( fp == NULL && errno == ENOENT) {
326     allow_seed_file_update = 1;
327     return 0;
328     }
329     if( fp == NULL ) {
330     random_err("can't open `%s': %s", seed_file_name, strerror(errno));
331     return 0;
332     }
333     fd = fileno(fp);
334     if( fstat( fd, &sb ) ) {
335     random_err("can't stat `%s': %s", seed_file_name, strerror(errno));
336     fclose(fp);
337     return 0;
338     }
339     if( !(sb.st_mode & _S_IFREG) ) {
340     fclose(fp);
341     return 0;
342     }
343     if( !sb.st_size ) {
344     fclose(fp);
345     allow_seed_file_update = 1;
346     return 0;
347     }
348     if( sb.st_size != POOLSIZE ) {
349     fclose(fp);
350     return 0;
351     }
352     do {
353     n = fread( buffer, 1, POOLSIZE, fp );
354     } while( n == -1 && errno == EINTR );
355     if( n != POOLSIZE ) {
356     random_err("can't read `%s': %s", seed_file_name,strerror(errno));
357     fclose(fp);
358     return 0;
359     }
360     fclose(fp);
361    
362     add_randomness( buffer, POOLSIZE, 0 );
363     /* add some minor entropy to the pool now (this will also force a mixing) */
364     { int x = getpid();
365     add_randomness( &x, sizeof(x), 0 );
366     }
367     { time_t x = time(NULL);
368     add_randomness( &x, sizeof(x), 0 );
369     }
370     { clock_t x = clock();
371     add_randomness( &x, sizeof(x), 0 );
372     }
373     /* And read a few bytes from our entropy source. By using
374     * a level of 0 this will not block and might not return anything
375     * with some entropy drivers, however the rndlinux driver will use
376     * /dev/urandom and return some stuff - Do not read to much as we
377     * want to be friendly to the scare system entropy resource. */
378     read_random_source( 0, 16, 0 );
379    
380     allow_seed_file_update = 1;
381     return 1;
382     }
383    
384     void
385     _gpg_update_random_seed_file()
386     {
387     u32 *sp, *dp;
388     int i;
389     FILE *fp;
390    
391     if( !seed_file_name || !is_initialized || !pool_filled )
392     return;
393     if( !allow_seed_file_update )
394     return;
395    
396     /* copy the entropy pool to a scratch pool and mix both of them */
397     for(i=0,dp=(u32*)keypool, sp=(u32*)rndpool; i < POOLWORDS; i++, dp++, sp++ ) {
398     *dp = *sp + ADD_VALUE;
399     }
400     mix_pool(rndpool); rndstats.mixrnd++;
401     mix_pool(keypool); rndstats.mixkey++;
402    
403     fp = fopen( seed_file_name, "w+b");
404     if( fp == NULL ) {
405     random_err("can't create `%s': %s\n", seed_file_name, strerror(errno));
406     return;
407     }
408     do {
409     i = fwrite( keypool, 1, POOLSIZE, fp );
410     } while( i == -1 && errno == EINTR );
411     if( i != POOLSIZE ) {
412     random_err("can't write `%s': %s\n", seed_file_name, strerror(errno));
413     }
414     if( fclose(fp) ) {
415     random_err("can't close `%s': %s\n", seed_file_name, strerror(errno));
416     }
417     }
418    
419    
420     static void
421     read_pool( byte *buffer, size_t length, int level )
422     {
423     int i;
424     u32 *sp, *dp;
425    
426     if( length >= POOLSIZE ) {
427     random_err("too many random bits requested; the limit is %d\n", POOLSIZE*8-1);
428     }
429     if( !pool_filled ) {
430     if( read_seed_file() )
431     pool_filled = 1;
432     }
433    
434     /* For level 2 quality (key generation) we alwas make
435     * sure that the pool has been seeded enough initially */
436     if( level == 2 && !did_initial_extra_seeding ) {
437     size_t needed;
438    
439     pool_balance = 0;
440     needed = length - pool_balance;
441     if( needed < POOLSIZE/2 )
442     needed = POOLSIZE/2;
443     else if( needed > POOLSIZE )
444     random_err("Ohhh jeee this is a BUG; File %s, Line %d", __FILE__, __LINE__);
445     read_random_source( 3, needed, 2 );
446     pool_balance += needed;
447     did_initial_extra_seeding=1;
448     }
449    
450     /* for level 2 make sure that there is enough random in the pool */
451     if( level == 2 && pool_balance < length ) {
452     size_t needed;
453    
454     if( pool_balance < 0 )
455     pool_balance = 0;
456     needed = length - pool_balance;
457     if( needed > POOLSIZE )
458     random_err("Ohhh jeee this is a BUG; File %s, Line %d", __FILE__, __LINE__);
459     read_random_source( 3, needed, 2 );
460     pool_balance += needed;
461     }
462    
463     /* make sure the pool is filled */
464     while( !pool_filled )
465     random_poll();
466    
467     /* do always a fast random poll */
468     fast_random_poll();
469    
470     if( !level ) { /* no need for cryptographic strong random */
471     /* create a new pool */
472     for(i=0,dp=(u32*)keypool, sp=(u32*)rndpool; i < POOLWORDS; i++, dp++, sp++ )
473     *dp = *sp + ADD_VALUE;
474     /* must mix both pools */
475     mix_pool(rndpool); rndstats.mixrnd++;
476     mix_pool(keypool); rndstats.mixkey++;
477     memcpy( buffer, keypool, length );
478     }
479     else {
480     /* mix the pool (if add_randomness() didn't it) */
481     if( !just_mixed ) {
482     mix_pool(rndpool);
483     rndstats.mixrnd++;
484     }
485     /* create a new pool */
486     for(i=0,dp=(u32*)keypool, sp=(u32*)rndpool;
487     i < POOLWORDS; i++, dp++, sp++ )
488     *dp = *sp + ADD_VALUE;
489     /* and mix both pools */
490     mix_pool(rndpool); rndstats.mixrnd++;
491     mix_pool(keypool); rndstats.mixkey++;
492     /* read the required data
493     * we use a readpoiter to read from a different postion each
494     * time */
495     while( length-- ) {
496     *buffer++ = keypool[pool_readpos++];
497     if( pool_readpos >= POOLSIZE )
498     pool_readpos = 0;
499     pool_balance--;
500     }
501     if( pool_balance < 0 )
502     pool_balance = 0;
503     /* and clear the keypool */
504     memset( keypool, 0, POOLSIZE );
505     }
506     }
507    
508    
509     /****************
510     * Add LENGTH bytes of randomness from buffer to the pool.
511     * source may be used to specify the randomness source.
512     * Source is:
513     * 0 - used ony for initialization
514     * 1 - fast random poll function
515     * 2 - normal poll function
516     * 3 - used when level 2 random quality has been requested
517     * to do an extra pool seed.
518     */
519     static void
520     add_randomness( const void *buffer, size_t length, int source )
521     {
522     const byte *p = buffer;
523    
524     if( !is_initialized )
525     initialize();
526     rndstats.addbytes += length;
527     rndstats.naddbytes++;
528     while( length-- ) {
529     rndpool[pool_writepos++] ^= *p++;
530     if( pool_writepos >= POOLSIZE ) {
531     if( source > 1 )
532     pool_filled = 1;
533     pool_writepos = 0;
534     mix_pool(rndpool); rndstats.mixrnd++;
535     just_mixed = !length;
536     }
537     }
538     }
539    
540     static void
541     random_poll( void )
542     {
543     rndstats.slowpolls++;
544     read_random_source( 2, POOLSIZE/5, 1 );
545     }
546    
547     void
548     _gpg_fast_random_poll( void )
549     {
550     static void (*fnc)( void (*)(const void*, size_t, int), int) = NULL;
551     static int initialized = 0;
552    
553     rndstats.fastpolls++;
554     if( !initialized ) {
555     if( !is_initialized )
556     initialize();
557     initialized = 1;
558     fnc = gather_random_fast;
559     }
560     if( fnc ) {
561     (*fnc)( add_randomness, 1 );
562     return;
563     }
564    
565     /* fall back to the generic function */
566    
567     /* time and clock are availabe on all systems - so
568     * we better do it just in case one of the above functions
569     * didn't work */
570     { time_t x = time(NULL);
571     add_randomness( &x, sizeof(x), 1 );
572     }
573     { clock_t x = clock();
574     add_randomness( &x, sizeof(x), 1 );
575     }
576     }
577    
578     static void
579     read_random_source( int requester, size_t length, int level )
580     {
581     static int (*fnc)(void (*)(const void*, size_t, int), int,
582     size_t, int) = NULL;
583     if( !fnc ) {
584     if( !is_initialized )
585     initialize();
586     fnc = gather_random;
587     if( !fnc ) {
588     faked_rng = 1;
589     fnc = gather_faked;
590     }
591     if( !requester && !length && !level )
592     return; /* init only */
593     }
594     if( (*fnc)( add_randomness, requester, length, level ) < 0 )
595     random_err("No way to gather entropy for the RNG\n");
596     }
597    
598    
599     static int
600     gather_faked( void (*add)(const void*, size_t, int), int requester,
601     size_t length, int level )
602     {
603     static int initialized=0;
604     size_t n;
605     char *buffer, *p;
606    
607     if( !initialized ) {
608     random_err("WARNING: using insecure random number generator!!\n");
609     initialized=1;
610     srand( time(NULL)*getpid());
611     }
612    
613     p = buffer = malloc( length );
614     n = length;
615     while( n-- )
616     *p++ = ((unsigned)(1 + (int) (256.0*rand()/(RAND_MAX+1.0)))-1);
617     add_randomness( buffer, length, requester );
618     free(buffer);
619     return 0; /* okay */
620     }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26