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

Annotation of /trunk/Gnupg/random.c

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:eol-style native

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26