Debian Codegraph @

random/random.c

raw
1 /* random.c - Random number switch
2 * Copyright (C) 2003, 2006, 2008, 2012 Free Software Foundation, Inc.
3 *
4 * This file is part of Libgcrypt.
5 *
6 * Libgcrypt is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation; either version 2.1 of
9 * the License, or (at your option) any later version.
10 *
11 * Libgcrypt is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20 /*
21 This module switches between different implementations of random
22 number generators and provides a few help functions.
23 */
24
25 #include <config.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <errno.h>
29 #include <time.h>
30 #include <sys/types.h>
31 #include <unistd.h>
32 #ifdef HAVE_SYSLOG
33 # include <syslog.h>
34 #endif /*HAVE_SYSLOG*/
35 #include <ctype.h>
36
37 #include "g10lib.h"
38 #include "random.h"
39 #include "rand-internal.h"
40 #include "cipher.h" /* For _gcry_sha1_hash_buffer(). */
41
42 /* The name of a file used to globally configure the RNG.
43 * Do not use this macro directly; use get_random_conf_file. */
44 #define RANDOM_CONF_FILE "random.conf"
45
46
47 /* If not NULL a progress function called from certain places and the
48 opaque value passed along. Registered by
49 _gcry_register_random_progress (). */
50 static void (*progress_cb) (void *,const char*,int,int, int );
51 static void *progress_cb_data;
52
53 /* Flags indicating the requested RNG types. */
54 static struct
55 {
56 int standard;
57 int fips;
58 int system;
59 } rng_types;
60
61
62 /* This is the lock we use to protect the buffer used by the nonce
63 generation. */
64 GPGRT_LOCK_DEFINE (nonce_buffer_lock);
65
66
67
68 /* --- Functions --- */
69
70
71 /* Used to register a progress callback. This needs to be called
72 before any threads are created. */
73 void
74 _gcry_register_random_progress (void (*cb)(void *,const char*,int,int,int),
75 void *cb_data )
76 {
77 progress_cb = cb;
78 progress_cb_data = cb_data;
79 }
80
81
82 /* This progress function is currently used by the random modules to
83 give hints on how much more entropy is required. */
84 void
85 _gcry_random_progress (const char *what, int printchar, int current, int total)
86 {
87 if (progress_cb)
88 progress_cb (progress_cb_data, what, printchar, current, total);
89 }
90
91
92 static const char *
93 get_random_conf_file (void)
94 {
95 #ifdef HAVE_W32_SYSTEM
96 static char *fname;
97
98 if (!fname)
99 {
100 const char *sysconfdir = _gcry_get_sysconfdir();
101
102 fname = xmalloc (strlen (sysconfdir) + strlen (RANDOM_CONF_FILE) + 1);
103 strcpy (fname, sysconfdir);
104 strcat (fname, RANDOM_CONF_FILE);
105 }
106 return fname;
107 #else
108 return "/etc/gcrypt/" RANDOM_CONF_FILE;
109 #endif
110 }
111
112 /* Read a file with configure options. The file is a simple text file
113 * where empty lines and lines with the first non white-space
114 * character being '#' are ignored. Supported configure options are:
115 *
116 * disable-jent - Disable the jitter based extra entropy generator.
117 * This sets the RANDOM_CONF_DISABLE_JENT bit.
118 * only-urandom - Always use /dev/urandom instead of /dev/random.
119 * This sets the RANDOM_CONF_ONLY_URANDOM bit.
120 *
121 * The function returns a bit vector with flags read from the file.
122 */
123 unsigned int
124 _gcry_random_read_conf (void)
125 {
126 const char *fname = get_random_conf_file ();
127 FILE *fp;
128 char buffer[256];
129 char *p, *pend;
130 int lnr = 0;
131 unsigned int result = 0;
132
133 fp = fopen (fname, "r");
134 if (!fp)
135 return result;
136
137 for (;;)
138 {
139 if (!fgets (buffer, sizeof buffer, fp))
140 {
141 if (!feof (fp))
142 {
143 #ifdef HAVE_SYSLOG
144 syslog (LOG_USER|LOG_WARNING,
145 "Libgcrypt warning: error reading '%s', line %d",
146 fname, lnr);
147 #endif /*HAVE_SYSLOG*/
148 }
149 fclose (fp);
150 return result;
151 }
152 lnr++;
153 for (p=buffer; my_isascii (*p) && isspace (*p); p++)
154 ;
155 pend = strchr (p, '\n');
156 if (pend)
157 *pend = 0;
158 pend = p + (*p? (strlen (p)-1):0);
159 for ( ;pend > p; pend--)
160 if (my_isascii (*pend) && isspace (*pend))
161 *pend = 0;
162 if (!*p || *p == '#')
163 continue;
164
165 if (!strcmp (p, "disable-jent"))
166 result |= RANDOM_CONF_DISABLE_JENT;
167 else if (!strcmp (p, "only-urandom"))
168 result |= RANDOM_CONF_ONLY_URANDOM;
169 else
170 {
171 #ifdef HAVE_SYSLOG
172 syslog (LOG_USER|LOG_WARNING,
173 "Libgcrypt warning: unknown option in '%s', line %d",
174 fname, lnr);
175 #endif /*HAVE_SYSLOG*/
176 }
177 }
178 }
179
180
181 /* Set the preferred RNG type. This may be called at any time even
182 before gcry_check_version. Thus we can't assume any thread system
183 initialization. A type of 0 is used to indicate that any Libgcrypt
184 initialization has been done.*/
185 void
186 _gcry_set_preferred_rng_type (int type)
187 {
188 static int any_init;
189
190 if (!type)
191 {
192 any_init = 1;
193 }
194 else if (type == GCRY_RNG_TYPE_STANDARD)
195 {
196 rng_types.standard = 1;
197 }
198 else if (any_init)
199 {
200 /* After any initialization has been done we only allow
201 upgrading to the standard RNG (handled above). All other
202 requests are ignored. The idea is that the application needs
203 to declare a preference for a weaker RNG as soon as possible
204 and before any library sets a preference. We assume that a
205 library which uses Libgcrypt calls an init function very
206 early. This way --- even if the library gets initialized
207 early by the application --- it is unlikely that it can
208 select a lower priority RNG.
209
210 This scheme helps to ensure that existing unmodified
211 applications (e.g. gpg2), which don't known about the new RNG
212 selection system, will continue to use the standard RNG and
213 not be tricked by some library to use a lower priority RNG.
214 There are some loopholes here but at least most GnuPG stuff
215 should be save because it calls src_c{gcry_control
216 (GCRYCTL_SUSPEND_SECMEM_WARN);} quite early and thus inhibits
217 switching to a low priority RNG.
218 */
219 }
220 else if (type == GCRY_RNG_TYPE_FIPS)
221 {
222 rng_types.fips = 1;
223 }
224 else if (type == GCRY_RNG_TYPE_SYSTEM)
225 {
226 rng_types.system = 1;
227 }
228 }
229
230
231 /* Initialize this random subsystem. If FULL is false, this function
232 merely calls the basic initialization of the module and does not do
233 anything more. Doing this is not really required but when running
234 in a threaded environment we might get a race condition
235 otherwise. */
236 void
237 _gcry_random_initialize (int full)
238 {
239 if (fips_mode ())
240 _gcry_rngdrbg_inititialize (full);
241 else if (rng_types.standard)
242 _gcry_rngcsprng_initialize (full);
243 else if (rng_types.fips)
244 _gcry_rngdrbg_inititialize (full);
245 else if (rng_types.system)
246 _gcry_rngsystem_initialize (full);
247 else
248 _gcry_rngcsprng_initialize (full);
249 }
250
251
252 /* If possible close file descriptors used by the RNG. */
253 void
254 _gcry_random_close_fds (void)
255 {
256 /* Note that we can't do that directly because each random system
257 has its own lock functions which need to be used for accessing
258 the entropy gatherer. */
259
260 if (fips_mode ())
261 _gcry_rngdrbg_close_fds ();
262 else if (rng_types.standard)
263 _gcry_rngcsprng_close_fds ();
264 else if (rng_types.fips)
265 _gcry_rngdrbg_close_fds ();
266 else if (rng_types.system)
267 _gcry_rngsystem_close_fds ();
268 else
269 _gcry_rngcsprng_close_fds ();
270 }
271
272
273 /* Return the current RNG type. IGNORE_FIPS_MODE is a flag used to
274 skip the test for FIPS. This is useful, so that we are able to
275 return the type of the RNG even before we have setup FIPS mode
276 (note that FIPS mode is enabled by default until it is switched off
277 by the initialization). This is mostly useful for the regression
278 test. */
279 int
280 _gcry_get_rng_type (int ignore_fips_mode)
281 {
282 if (!ignore_fips_mode && fips_mode ())
283 return GCRY_RNG_TYPE_FIPS;
284 else if (rng_types.standard)
285 return GCRY_RNG_TYPE_STANDARD;
286 else if (rng_types.fips)
287 return GCRY_RNG_TYPE_FIPS;
288 else if (rng_types.system)
289 return GCRY_RNG_TYPE_SYSTEM;
290 else
291 return GCRY_RNG_TYPE_STANDARD;
292 }
293
294
295 void
296 _gcry_random_dump_stats (void)
297 {
298 if (fips_mode ())
299 _gcry_rngdrbg_dump_stats ();
300 else
301 _gcry_rngcsprng_dump_stats ();
302 _gcry_rndjent_dump_stats ();
303 }
304
305
306 /* This function should be called during initialization and before
307 initialization of this module to place the random pools into secure
308 memory. */
309 void
310 _gcry_secure_random_alloc (void)
311 {
312 if (fips_mode ())
313 ; /* Not used; the FIPS RNG is always in secure mode. */
314 else
315 _gcry_rngcsprng_secure_alloc ();
316 }
317
318
319 /* This may be called before full initialization to degrade the
320 quality of the RNG for the sake of a faster running test suite. */
321 void
322 _gcry_enable_quick_random_gen (void)
323 {
324 if (fips_mode ())
325 ; /* Not used. */
326 else
327 _gcry_rngcsprng_enable_quick_gen ();
328 }
329
330
331 /* This function returns true if no real RNG is available or the
332 quality of the RNG has been degraded for test purposes. */
333 int
334 _gcry_random_is_faked (void)
335 {
336 if (fips_mode ())
337 return _gcry_rngdrbg_is_faked ();
338 else
339 return _gcry_rngcsprng_is_faked ();
340 }
341
342
343 /* Add BUFLEN bytes from BUF to the internal random pool. QUALITY
344 should be in the range of 0..100 to indicate the goodness of the
345 entropy added, or -1 for goodness not known. */
346 gcry_err_code_t
347 _gcry_random_add_bytes (const void *buf, size_t buflen, int quality)
348 {
349 if (fips_mode ())
350 return 0; /* No need for this in fips mode. */
351 else if (rng_types.standard)
352 return gpg_err_code (_gcry_rngcsprng_add_bytes (buf, buflen, quality));
353 else if (rng_types.fips)
354 return 0;
355 else if (rng_types.system)
356 return 0;
357 else /* default */
358 return gpg_err_code (_gcry_rngcsprng_add_bytes (buf, buflen, quality));
359 }
360
361
362 /* Helper function. */
363 static void
364 do_randomize (void *buffer, size_t length, enum gcry_random_level level)
365 {
366 if (fips_mode ())
367 _gcry_rngdrbg_randomize (buffer, length, level);
368 else if (rng_types.standard)
369 _gcry_rngcsprng_randomize (buffer, length, level);
370 else if (rng_types.fips)
371 _gcry_rngdrbg_randomize (buffer, length, level);
372 else if (rng_types.system)
373 _gcry_rngsystem_randomize (buffer, length, level);
374 else /* default */
375 _gcry_rngcsprng_randomize (buffer, length, level);
376 }
377
378 /* The public function to return random data of the quality LEVEL.
379 Returns a pointer to a newly allocated and randomized buffer of
380 LEVEL and NBYTES length. Caller must free the buffer. */
381 void *
382 _gcry_random_bytes (size_t nbytes, enum gcry_random_level level)
383 {
384 void *buffer;
385
386 buffer = xmalloc (nbytes);
387 do_randomize (buffer, nbytes, level);
388 return buffer;
389 }
390
391
392 /* The public function to return random data of the quality LEVEL;
393 this version of the function returns the random in a buffer allocated
394 in secure memory. Caller must free the buffer. */
395 void *
396 _gcry_random_bytes_secure (size_t nbytes, enum gcry_random_level level)
397 {
398 void *buffer;
399
400 /* Historical note (1.3.0--1.4.1): The buffer was only allocated
401 in secure memory if the pool in random-csprng.c was also set to
402 use secure memory. */
403 buffer = xmalloc_secure (nbytes);
404 do_randomize (buffer, nbytes, level);
405 return buffer;
406 }
407
408
409 /* Public function to fill the buffer with LENGTH bytes of
410 cryptographically strong random bytes. Level GCRY_WEAK_RANDOM is
411 not very strong, GCRY_STRONG_RANDOM is strong enough for most
412 usage, GCRY_VERY_STRONG_RANDOM is good for key generation stuff but
413 may be very slow. */
414 void
415 _gcry_randomize (void *buffer, size_t length, enum gcry_random_level level)
416 {
417 do_randomize (buffer, length, level);
418 }
419
420
421 /* This function may be used to specify the file to be used as a seed
422 file for the PRNG. This function should be called prior to the
423 initialization of the random module. NAME may not be NULL. */
424 void
425 _gcry_set_random_seed_file (const char *name)
426 {
427 if (fips_mode ())
428 ; /* No need for this in fips mode. */
429 else if (rng_types.standard)
430 _gcry_rngcsprng_set_seed_file (name);
431 else if (rng_types.fips)
432 ;
433 else if (rng_types.system)
434 ;
435 else /* default */
436 _gcry_rngcsprng_set_seed_file (name);
437 }
438
439
440 /* If a seed file has been setup, this function may be used to write
441 back the random numbers entropy pool. */
442 void
443 _gcry_update_random_seed_file (void)
444 {
445 if (fips_mode ())
446 ; /* No need for this in fips mode. */
447 else if (rng_types.standard)
448 _gcry_rngcsprng_update_seed_file ();
449 else if (rng_types.fips)
450 ;
451 else if (rng_types.system)
452 ;
453 else /* default */
454 _gcry_rngcsprng_update_seed_file ();
455 }
456
457
458
459 /* The fast random pool function as called at some places in
460 libgcrypt. This is merely a wrapper to make sure that this module
461 is initialized and to lock the pool. Note, that this function is a
462 NOP unless a random function has been used or _gcry_initialize (1)
463 has been used. We use this hack so that the internal use of this
464 function in cipher_open and md_open won't start filling up the
465 random pool, even if no random will be required by the process. */
466 void
467 _gcry_fast_random_poll (void)
468 {
469 if (fips_mode ())
470 ; /* No need for this in fips mode. */
471 else if (rng_types.standard)
472 _gcry_rngcsprng_fast_poll ();
473 else if (rng_types.fips)
474 ;
475 else if (rng_types.system)
476 ;
477 else /* default */
478 _gcry_rngcsprng_fast_poll ();
479 }
480
481
482
483 /* Create an unpredicable nonce of LENGTH bytes in BUFFER. */
484 void
485 _gcry_create_nonce (void *buffer, size_t length)
486 {
487 static unsigned char nonce_buffer[20+8];
488 static int nonce_buffer_initialized = 0;
489 static volatile pid_t my_pid; /* The volatile is there to make sure the
490 compiler does not optimize the code away
491 in case the getpid function is badly
492 attributed. */
493 volatile pid_t apid;
494 unsigned char *p;
495 size_t n;
496 int err;
497
498 /* First check whether we shall use the FIPS nonce generator. This
499 is only done in FIPS mode, in all other modes, we use our own
500 nonce generator which is seeded by the RNG actual in use. */
501 if (fips_mode ())
502 {
503 _gcry_rngdrbg_randomize (buffer, length, GCRY_WEAK_RANDOM);
504 return;
505 }
506
507 /* This is the nonce generator, which formerly lived in
508 random-csprng.c. It is now used by all RNG types except when in
509 FIPS mode (not that this means it is also used if the FIPS RNG
510 has been selected but we are not in fips mode). */
511
512 /* Make sure we are initialized. */
513 _gcry_random_initialize (1);
514
515 /* Acquire the nonce buffer lock. */
516 err = gpgrt_lock_lock (&nonce_buffer_lock);
517 if (err)
518 log_fatal ("failed to acquire the nonce buffer lock: %s\n",
519 gpg_strerror (err));
520
521 apid = getpid ();
522 /* The first time initialize our buffer. */
523 if (!nonce_buffer_initialized)
524 {
525 time_t atime = time (NULL);
526 pid_t xpid = apid;
527
528 my_pid = apid;
529
530 if ((sizeof apid + sizeof atime) > sizeof nonce_buffer)
531 BUG ();
532
533 /* Initialize the first 20 bytes with a reasonable value so that
534 a failure of gcry_randomize won't affect us too much. Don't
535 care about the uninitialized remaining bytes. */
536 p = nonce_buffer;
537 memcpy (p, &xpid, sizeof xpid);
538 p += sizeof xpid;
539 memcpy (p, &atime, sizeof atime);
540
541 /* Initialize the never changing private part of 64 bits. */
542 _gcry_randomize (nonce_buffer+20, 8, GCRY_WEAK_RANDOM);
543
544 nonce_buffer_initialized = 1;
545 }
546 else if ( my_pid != apid )
547 {
548 /* We forked. Need to reseed the buffer - doing this for the
549 private part should be sufficient. */
550 do_randomize (nonce_buffer+20, 8, GCRY_WEAK_RANDOM);
551 /* Update the pid so that we won't run into here again and
552 again. */
553 my_pid = apid;
554 }
555
556 /* Create the nonce by hashing the entire buffer, returning the hash
557 and updating the first 20 bytes of the buffer with this hash. */
558 for (p = buffer; length > 0; length -= n, p += n)
559 {
560 _gcry_sha1_hash_buffer (nonce_buffer,
561 nonce_buffer, sizeof nonce_buffer);
562 n = length > 20? 20 : length;
563 memcpy (p, nonce_buffer, n);
564 }
565
566 /* Release the nonce buffer lock. */
567 err = gpgrt_lock_unlock (&nonce_buffer_lock);
568 if (err)
569 log_fatal ("failed to release the nonce buffer lock: %s\n",
570 gpg_strerror (err));
571 }
572
573
574 /* Run the self-tests for the RNG. This is currently only implemented
575 for the FIPS generator. */
576 gpg_error_t
577 _gcry_random_selftest (selftest_report_func_t report)
578 {
579 if (fips_mode ())
580 return _gcry_rngdrbg_selftest (report);
581 else
582 return 0; /* No selftests yet. */
583 }