RAND_add()/RAND_seed(): fix failure on short input or low entropy
[openssl.git] / crypto / rand / drbg_lib.c
1 /*
2  * Copyright 2011-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <string.h>
11 #include <openssl/crypto.h>
12 #include <openssl/err.h>
13 #include <openssl/rand.h>
14 #include "rand_lcl.h"
15 #include "internal/thread_once.h"
16 #include "internal/rand_int.h"
17 #include "internal/cryptlib_int.h"
18
19 /*
20  * Support framework for NIST SP 800-90A DRBG
21  *
22  * See manual page RAND_DRBG(7) for a general overview.
23  *
24  * The OpenSSL model is to have new and free functions, and that new
25  * does all initialization.  That is not the NIST model, which has
26  * instantiation and un-instantiate, and re-use within a new/free
27  * lifecycle.  (No doubt this comes from the desire to support hardware
28  * DRBG, where allocation of resources on something like an HSM is
29  * a much bigger deal than just re-setting an allocated resource.)
30  */
31
32 /*
33  * The three shared DRBG instances
34  *
35  * There are three shared DRBG instances: <master>, <public>, and <private>.
36  */
37
38 /*
39  * The <master> DRBG
40  *
41  * Not used directly by the application, only for reseeding the two other
42  * DRBGs. It reseeds itself by pulling either randomness from os entropy
43  * sources or by consuming randomness which was added by RAND_add().
44  *
45  * The <master> DRBG is a global instance which is accessed concurrently by
46  * all threads. The necessary locking is managed automatically by its child
47  * DRBG instances during reseeding.
48  */
49 static RAND_DRBG *master_drbg;
50 /*
51  * The <public> DRBG
52  *
53  * Used by default for generating random bytes using RAND_bytes().
54  *
55  * The <public> DRBG is thread-local, i.e., there is one instance per thread.
56  */
57 static CRYPTO_THREAD_LOCAL public_drbg;
58 /*
59  * The <private> DRBG
60  *
61  * Used by default for generating private keys using RAND_priv_bytes()
62  *
63  * The <private> DRBG is thread-local, i.e., there is one instance per thread.
64  */
65 static CRYPTO_THREAD_LOCAL private_drbg;
66
67
68
69 /* NIST SP 800-90A DRBG recommends the use of a personalization string. */
70 static const char ossl_pers_string[] = "OpenSSL NIST SP 800-90A DRBG";
71
72 static CRYPTO_ONCE rand_drbg_init = CRYPTO_ONCE_STATIC_INIT;
73
74
75 #define RAND_DRBG_TYPE_FLAGS    ( \
76     RAND_DRBG_FLAG_MASTER | RAND_DRBG_FLAG_PUBLIC | RAND_DRBG_FLAG_PRIVATE )
77
78 #define RAND_DRBG_TYPE_MASTER                     0
79 #define RAND_DRBG_TYPE_PUBLIC                     1
80 #define RAND_DRBG_TYPE_PRIVATE                    2
81
82 /* Defaults */
83 static int rand_drbg_type[3] = {
84     RAND_DRBG_TYPE, /* Master */
85     RAND_DRBG_TYPE, /* Public */
86     RAND_DRBG_TYPE  /* Private */
87 };
88 static unsigned int rand_drbg_flags[3] = {
89     RAND_DRBG_FLAGS | RAND_DRBG_FLAG_MASTER, /* Master */
90     RAND_DRBG_FLAGS | RAND_DRBG_FLAG_PUBLIC, /* Public */
91     RAND_DRBG_FLAGS | RAND_DRBG_FLAG_PRIVATE /* Private */
92 };
93
94 static unsigned int master_reseed_interval = MASTER_RESEED_INTERVAL;
95 static unsigned int slave_reseed_interval  = SLAVE_RESEED_INTERVAL;
96
97 static time_t master_reseed_time_interval = MASTER_RESEED_TIME_INTERVAL;
98 static time_t slave_reseed_time_interval  = SLAVE_RESEED_TIME_INTERVAL;
99
100 /* A logical OR of all used DRBG flag bits (currently there is only one) */
101 static const unsigned int rand_drbg_used_flags =
102     RAND_DRBG_FLAG_CTR_NO_DF | RAND_DRBG_FLAG_HMAC | RAND_DRBG_TYPE_FLAGS;
103
104
105 static RAND_DRBG *drbg_setup(RAND_DRBG *parent, int drbg_type);
106
107 static RAND_DRBG *rand_drbg_new(int secure,
108                                 int type,
109                                 unsigned int flags,
110                                 RAND_DRBG *parent);
111
112 static int is_ctr(int type)
113 {
114     switch (type) {
115     case NID_aes_128_ctr:
116     case NID_aes_192_ctr:
117     case NID_aes_256_ctr:
118         return 1;
119     default:
120         return 0;
121     }
122 }
123
124 static int is_digest(int type)
125 {
126     switch (type) {
127     case NID_sha1:
128     case NID_sha224:
129     case NID_sha256:
130     case NID_sha384:
131     case NID_sha512:
132     case NID_sha512_224:
133     case NID_sha512_256:
134     case NID_sha3_224:
135     case NID_sha3_256:
136     case NID_sha3_384:
137     case NID_sha3_512:
138         return 1;
139     default:
140         return 0;
141     }
142 }
143
144 /*
145  * Set/initialize |drbg| to be of type |type|, with optional |flags|.
146  *
147  * If |type| and |flags| are zero, use the defaults
148  *
149  * Returns 1 on success, 0 on failure.
150  */
151 int RAND_DRBG_set(RAND_DRBG *drbg, int type, unsigned int flags)
152 {
153     int ret = 1;
154
155     if (type == 0 && flags == 0) {
156         type = rand_drbg_type[RAND_DRBG_TYPE_MASTER];
157         flags = rand_drbg_flags[RAND_DRBG_TYPE_MASTER];
158     }
159
160     /* If set is called multiple times - clear the old one */
161     if (type != drbg->type && drbg->type != 0 && drbg->meth != NULL) {
162         drbg->meth->uninstantiate(drbg);
163     }
164
165     drbg->state = DRBG_UNINITIALISED;
166     drbg->flags = flags;
167     drbg->type = type;
168
169     if (type == 0) {
170         /* Uninitialized; that's okay. */
171         return 1;
172     } else if (is_ctr(type)) {
173         ret = drbg_ctr_init(drbg);
174     } else if (is_digest(type)) {
175         if (flags & RAND_DRBG_FLAG_HMAC)
176             ret = drbg_hmac_init(drbg);
177         else
178             ret = drbg_hash_init(drbg);
179     } else {
180         RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
181         return 0;
182     }
183
184     if (ret == 0)
185         RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG);
186     return ret;
187 }
188
189 /*
190  * Set/initialize default |type| and |flag| for new drbg instances.
191  *
192  * Returns 1 on success, 0 on failure.
193  */
194 int RAND_DRBG_set_defaults(int type, unsigned int flags)
195 {
196     int all;
197     if (!(is_digest(type) || is_ctr(type))) {
198         RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_TYPE);
199         return 0;
200     }
201
202     if ((flags & ~rand_drbg_used_flags) != 0) {
203         RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_FLAGS);
204         return 0;
205     }
206
207     all = ((flags & RAND_DRBG_TYPE_FLAGS) == 0);
208     if (all || (flags & RAND_DRBG_FLAG_MASTER) != 0) {
209         rand_drbg_type[RAND_DRBG_TYPE_MASTER] = type;
210         rand_drbg_flags[RAND_DRBG_TYPE_MASTER] = flags | RAND_DRBG_FLAG_MASTER;
211     }
212     if (all || (flags & RAND_DRBG_FLAG_PUBLIC) != 0) {
213         rand_drbg_type[RAND_DRBG_TYPE_PUBLIC]  = type;
214         rand_drbg_flags[RAND_DRBG_TYPE_PUBLIC] = flags | RAND_DRBG_FLAG_PUBLIC;
215     }
216     if (all || (flags & RAND_DRBG_FLAG_PRIVATE) != 0) {
217         rand_drbg_type[RAND_DRBG_TYPE_PRIVATE] = type;
218         rand_drbg_flags[RAND_DRBG_TYPE_PRIVATE] = flags | RAND_DRBG_FLAG_PRIVATE;
219     }
220     return 1;
221 }
222
223
224 /*
225  * Allocate memory and initialize a new DRBG. The DRBG is allocated on
226  * the secure heap if |secure| is nonzero and the secure heap is enabled.
227  * The |parent|, if not NULL, will be used as random source for reseeding.
228  *
229  * Returns a pointer to the new DRBG instance on success, NULL on failure.
230  */
231 static RAND_DRBG *rand_drbg_new(int secure,
232                                 int type,
233                                 unsigned int flags,
234                                 RAND_DRBG *parent)
235 {
236     RAND_DRBG *drbg = secure ?
237         OPENSSL_secure_zalloc(sizeof(*drbg)) : OPENSSL_zalloc(sizeof(*drbg));
238
239     if (drbg == NULL) {
240         RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
241         return NULL;
242     }
243
244     drbg->secure = secure && CRYPTO_secure_allocated(drbg);
245     drbg->fork_count = rand_fork_count;
246     drbg->parent = parent;
247
248     if (parent == NULL) {
249         drbg->get_entropy = rand_drbg_get_entropy;
250         drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
251 #ifndef RAND_DRBG_GET_RANDOM_NONCE
252         drbg->get_nonce = rand_drbg_get_nonce;
253         drbg->cleanup_nonce = rand_drbg_cleanup_nonce;
254 #endif
255
256         drbg->reseed_interval = master_reseed_interval;
257         drbg->reseed_time_interval = master_reseed_time_interval;
258     } else {
259         drbg->get_entropy = rand_drbg_get_entropy;
260         drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
261         /*
262          * Do not provide nonce callbacks, the child DRBGs will
263          * obtain their nonce using random bits from the parent.
264          */
265
266         drbg->reseed_interval = slave_reseed_interval;
267         drbg->reseed_time_interval = slave_reseed_time_interval;
268     }
269
270     if (RAND_DRBG_set(drbg, type, flags) == 0)
271         goto err;
272
273     if (parent != NULL) {
274         rand_drbg_lock(parent);
275         if (drbg->strength > parent->strength) {
276             /*
277              * We currently don't support the algorithm from NIST SP 800-90C
278              * 10.1.2 to use a weaker DRBG as source
279              */
280             rand_drbg_unlock(parent);
281             RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK);
282             goto err;
283         }
284         rand_drbg_unlock(parent);
285     }
286
287     return drbg;
288
289  err:
290     if (drbg->secure)
291         OPENSSL_secure_free(drbg);
292     else
293         OPENSSL_free(drbg);
294
295     return NULL;
296 }
297
298 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
299 {
300     return rand_drbg_new(0, type, flags, parent);
301 }
302
303 RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent)
304 {
305     return rand_drbg_new(1, type, flags, parent);
306 }
307
308 /*
309  * Uninstantiate |drbg| and free all memory.
310  */
311 void RAND_DRBG_free(RAND_DRBG *drbg)
312 {
313     if (drbg == NULL)
314         return;
315
316     if (drbg->meth != NULL)
317         drbg->meth->uninstantiate(drbg);
318     CRYPTO_THREAD_lock_free(drbg->lock);
319     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
320
321     if (drbg->secure)
322         OPENSSL_secure_clear_free(drbg, sizeof(*drbg));
323     else
324         OPENSSL_clear_free(drbg, sizeof(*drbg));
325 }
326
327 /*
328  * Instantiate |drbg|, after it has been initialized.  Use |pers| and
329  * |perslen| as prediction-resistance input.
330  *
331  * Requires that drbg->lock is already locked for write, if non-null.
332  *
333  * Returns 1 on success, 0 on failure.
334  */
335 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
336                           const unsigned char *pers, size_t perslen)
337 {
338     unsigned char *nonce = NULL, *entropy = NULL;
339     size_t noncelen = 0, entropylen = 0;
340     size_t min_entropy = drbg->strength;
341     size_t min_entropylen = drbg->min_entropylen;
342     size_t max_entropylen = drbg->max_entropylen;
343
344     if (perslen > drbg->max_perslen) {
345         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
346                 RAND_R_PERSONALISATION_STRING_TOO_LONG);
347         goto end;
348     }
349
350     if (drbg->meth == NULL) {
351         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
352                 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
353         goto end;
354     }
355
356     if (drbg->state != DRBG_UNINITIALISED) {
357         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
358                 drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE
359                                           : RAND_R_ALREADY_INSTANTIATED);
360         goto end;
361     }
362
363     drbg->state = DRBG_ERROR;
364
365     /*
366      * NIST SP800-90Ar1 section 9.1 says you can combine getting the entropy
367      * and nonce in 1 call by increasing the entropy with 50% and increasing
368      * the minimum length to accomadate the length of the nonce.
369      * We do this in case a nonce is require and get_nonce is NULL.
370      */
371     if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
372         min_entropy += drbg->strength / 2;
373         min_entropylen += drbg->min_noncelen;
374         max_entropylen += drbg->max_noncelen;
375     }
376
377     if (drbg->get_entropy != NULL)
378         entropylen = drbg->get_entropy(drbg, &entropy, min_entropy,
379                                        min_entropylen, max_entropylen, 0);
380     if (entropylen < min_entropylen
381             || entropylen > max_entropylen) {
382         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
383         goto end;
384     }
385
386     if (drbg->min_noncelen > 0 && drbg->get_nonce != NULL) {
387         noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
388                                    drbg->min_noncelen, drbg->max_noncelen);
389         if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
390             RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_NONCE);
391             goto end;
392         }
393     }
394
395     if (!drbg->meth->instantiate(drbg, entropy, entropylen,
396                          nonce, noncelen, pers, perslen)) {
397         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
398         goto end;
399     }
400
401     drbg->state = DRBG_READY;
402     drbg->reseed_gen_counter = 1;
403     drbg->reseed_time = time(NULL);
404     if (drbg->reseed_prop_counter > 0) {
405         if (drbg->parent == NULL)
406             drbg->reseed_prop_counter++;
407         else
408             drbg->reseed_prop_counter = drbg->parent->reseed_prop_counter;
409     }
410
411  end:
412     if (entropy != NULL && drbg->cleanup_entropy != NULL)
413         drbg->cleanup_entropy(drbg, entropy, entropylen);
414     if (nonce != NULL && drbg->cleanup_nonce != NULL)
415         drbg->cleanup_nonce(drbg, nonce, noncelen);
416     if (drbg->pool != NULL) {
417         if (drbg->state == DRBG_READY) {
418             RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
419                     RAND_R_ERROR_ENTROPY_POOL_WAS_IGNORED);
420             drbg->state = DRBG_ERROR;
421         }
422         rand_pool_free(drbg->pool);
423         drbg->pool = NULL;
424     }
425     if (drbg->state == DRBG_READY)
426         return 1;
427     return 0;
428 }
429
430 /*
431  * Uninstantiate |drbg|. Must be instantiated before it can be used.
432  *
433  * Requires that drbg->lock is already locked for write, if non-null.
434  *
435  * Returns 1 on success, 0 on failure.
436  */
437 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
438 {
439     int index = -1, type, flags;
440     if (drbg->meth == NULL) {
441         RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
442                 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
443         return 0;
444     }
445
446     /* Clear the entire drbg->ctr struct, then reset some important
447      * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
448      * initial values.
449      */
450     drbg->meth->uninstantiate(drbg);
451
452     /* The reset uses the default values for type and flags */
453     if (drbg->flags & RAND_DRBG_FLAG_MASTER)
454         index = RAND_DRBG_TYPE_MASTER;
455     else if (drbg->flags & RAND_DRBG_FLAG_PRIVATE)
456         index = RAND_DRBG_TYPE_PRIVATE;
457     else if (drbg->flags & RAND_DRBG_FLAG_PUBLIC)
458         index = RAND_DRBG_TYPE_PUBLIC;
459
460     if (index != -1) {
461         flags = rand_drbg_flags[index];
462         type = rand_drbg_type[index];
463     } else {
464         flags = drbg->flags;
465         type = drbg->type;
466     }
467     return RAND_DRBG_set(drbg, type, flags);
468 }
469
470 /*
471  * Reseed |drbg|, mixing in the specified data
472  *
473  * Requires that drbg->lock is already locked for write, if non-null.
474  *
475  * Returns 1 on success, 0 on failure.
476  */
477 int RAND_DRBG_reseed(RAND_DRBG *drbg,
478                      const unsigned char *adin, size_t adinlen,
479                      int prediction_resistance)
480 {
481     unsigned char *entropy = NULL;
482     size_t entropylen = 0;
483
484     if (drbg->state == DRBG_ERROR) {
485         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
486         return 0;
487     }
488     if (drbg->state == DRBG_UNINITIALISED) {
489         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
490         return 0;
491     }
492
493     if (adin == NULL) {
494         adinlen = 0;
495     } else if (adinlen > drbg->max_adinlen) {
496         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
497         return 0;
498     }
499
500     drbg->state = DRBG_ERROR;
501     if (drbg->get_entropy != NULL)
502         entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
503                                        drbg->min_entropylen,
504                                        drbg->max_entropylen,
505                                        prediction_resistance);
506     if (entropylen < drbg->min_entropylen
507             || entropylen > drbg->max_entropylen) {
508         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
509         goto end;
510     }
511
512     if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
513         goto end;
514
515     drbg->state = DRBG_READY;
516     drbg->reseed_gen_counter = 1;
517     drbg->reseed_time = time(NULL);
518     if (drbg->reseed_prop_counter > 0) {
519         if (drbg->parent == NULL)
520             drbg->reseed_prop_counter++;
521         else
522             drbg->reseed_prop_counter = drbg->parent->reseed_prop_counter;
523     }
524
525  end:
526     if (entropy != NULL && drbg->cleanup_entropy != NULL)
527         drbg->cleanup_entropy(drbg, entropy, entropylen);
528     if (drbg->state == DRBG_READY)
529         return 1;
530     return 0;
531 }
532
533 /*
534  * Restart |drbg|, using the specified entropy or additional input
535  *
536  * Tries its best to get the drbg instantiated by all means,
537  * regardless of its current state.
538  *
539  * Optionally, a |buffer| of |len| random bytes can be passed,
540  * which is assumed to contain at least |entropy| bits of entropy.
541  *
542  * If |entropy| > 0, the buffer content is used as entropy input.
543  *
544  * If |entropy| == 0, the buffer content is used as additional input
545  *
546  * Returns 1 on success, 0 on failure.
547  *
548  * This function is used internally only.
549  */
550 int rand_drbg_restart(RAND_DRBG *drbg,
551                       const unsigned char *buffer, size_t len, size_t entropy)
552 {
553     int reseeded = 0;
554     const unsigned char *adin = NULL;
555     size_t adinlen = 0;
556
557     if (drbg->pool != NULL) {
558         RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
559         drbg->state = DRBG_ERROR;
560         rand_pool_free(drbg->pool);
561         drbg->pool = NULL;
562         return 0;
563     }
564
565     if (buffer != NULL) {
566         if (entropy > 0) {
567             if (drbg->max_entropylen < len) {
568                 RANDerr(RAND_F_RAND_DRBG_RESTART,
569                     RAND_R_ENTROPY_INPUT_TOO_LONG);
570                 drbg->state = DRBG_ERROR;
571                 return 0;
572             }
573
574             if (entropy > 8 * len) {
575                 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
576                 drbg->state = DRBG_ERROR;
577                 return 0;
578             }
579
580             /* will be picked up by the rand_drbg_get_entropy() callback */
581             drbg->pool = rand_pool_attach(buffer, len, entropy);
582             if (drbg->pool == NULL)
583                 return 0;
584         } else {
585             if (drbg->max_adinlen < len) {
586                 RANDerr(RAND_F_RAND_DRBG_RESTART,
587                         RAND_R_ADDITIONAL_INPUT_TOO_LONG);
588                 drbg->state = DRBG_ERROR;
589                 return 0;
590             }
591             adin = buffer;
592             adinlen = len;
593         }
594     }
595
596     /* repair error state */
597     if (drbg->state == DRBG_ERROR)
598         RAND_DRBG_uninstantiate(drbg);
599
600     /* repair uninitialized state */
601     if (drbg->state == DRBG_UNINITIALISED) {
602         /* reinstantiate drbg */
603         RAND_DRBG_instantiate(drbg,
604                               (const unsigned char *) ossl_pers_string,
605                               sizeof(ossl_pers_string) - 1);
606         /* already reseeded. prevent second reseeding below */
607         reseeded = (drbg->state == DRBG_READY);
608     }
609
610     /* refresh current state if entropy or additional input has been provided */
611     if (drbg->state == DRBG_READY) {
612         if (adin != NULL) {
613             /*
614              * mix in additional input without reseeding
615              *
616              * Similar to RAND_DRBG_reseed(), but the provided additional
617              * data |adin| is mixed into the current state without pulling
618              * entropy from the trusted entropy source using get_entropy().
619              * This is not a reseeding in the strict sense of NIST SP 800-90A.
620              */
621             drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
622         } else if (reseeded == 0) {
623             /* do a full reseeding if it has not been done yet above */
624             RAND_DRBG_reseed(drbg, NULL, 0, 0);
625         }
626     }
627
628     /* check whether a given entropy pool was cleared properly during reseed */
629     if (drbg->pool != NULL) {
630         drbg->state = DRBG_ERROR;
631         RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
632         rand_pool_free(drbg->pool);
633         drbg->pool = NULL;
634         return 0;
635     }
636
637     return drbg->state == DRBG_READY;
638 }
639
640 /*
641  * Generate |outlen| bytes into the buffer at |out|.  Reseed if we need
642  * to or if |prediction_resistance| is set.  Additional input can be
643  * sent in |adin| and |adinlen|.
644  *
645  * Requires that drbg->lock is already locked for write, if non-null.
646  *
647  * Returns 1 on success, 0 on failure.
648  *
649  */
650 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
651                        int prediction_resistance,
652                        const unsigned char *adin, size_t adinlen)
653 {
654     int reseed_required = 0;
655
656     if (drbg->state != DRBG_READY) {
657         /* try to recover from previous errors */
658         rand_drbg_restart(drbg, NULL, 0, 0);
659
660         if (drbg->state == DRBG_ERROR) {
661             RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
662             return 0;
663         }
664         if (drbg->state == DRBG_UNINITIALISED) {
665             RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
666             return 0;
667         }
668     }
669
670     if (outlen > drbg->max_request) {
671         RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
672         return 0;
673     }
674     if (adinlen > drbg->max_adinlen) {
675         RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
676         return 0;
677     }
678
679     if (drbg->fork_count != rand_fork_count) {
680         drbg->fork_count = rand_fork_count;
681         reseed_required = 1;
682     }
683
684     if (drbg->reseed_interval > 0) {
685         if (drbg->reseed_gen_counter > drbg->reseed_interval)
686             reseed_required = 1;
687     }
688     if (drbg->reseed_time_interval > 0) {
689         time_t now = time(NULL);
690         if (now < drbg->reseed_time
691             || now - drbg->reseed_time >= drbg->reseed_time_interval)
692             reseed_required = 1;
693     }
694     if (drbg->reseed_prop_counter > 0 && drbg->parent != NULL) {
695         if (drbg->reseed_prop_counter != drbg->parent->reseed_prop_counter)
696             reseed_required = 1;
697     }
698
699     if (reseed_required || prediction_resistance) {
700         if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
701             RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
702             return 0;
703         }
704         adin = NULL;
705         adinlen = 0;
706     }
707
708     if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
709         drbg->state = DRBG_ERROR;
710         RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
711         return 0;
712     }
713
714     drbg->reseed_gen_counter++;
715
716     return 1;
717 }
718
719 /*
720  * Generates |outlen| random bytes and stores them in |out|. It will
721  * using the given |drbg| to generate the bytes.
722  *
723  * Requires that drbg->lock is already locked for write, if non-null.
724  *
725  * Returns 1 on success 0 on failure.
726  */
727 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
728 {
729     unsigned char *additional = NULL;
730     size_t additional_len;
731     size_t chunk;
732     size_t ret;
733
734     additional_len = rand_drbg_get_additional_data(&additional, drbg->max_adinlen);
735
736     for ( ; outlen > 0; outlen -= chunk, out += chunk) {
737         chunk = outlen;
738         if (chunk > drbg->max_request)
739             chunk = drbg->max_request;
740         ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
741         if (!ret)
742             goto err;
743     }
744     ret = 1;
745
746 err:
747     if (additional_len != 0)
748         OPENSSL_secure_clear_free(additional, additional_len);
749
750     return ret;
751 }
752
753 /*
754  * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
755  *
756  * Setting the callbacks is allowed only if the drbg has not been
757  * initialized yet. Otherwise, the operation will fail.
758  *
759  * Returns 1 on success, 0 on failure.
760  */
761 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
762                             RAND_DRBG_get_entropy_fn get_entropy,
763                             RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
764                             RAND_DRBG_get_nonce_fn get_nonce,
765                             RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
766 {
767     if (drbg->state != DRBG_UNINITIALISED)
768         return 0;
769     drbg->get_entropy = get_entropy;
770     drbg->cleanup_entropy = cleanup_entropy;
771     drbg->get_nonce = get_nonce;
772     drbg->cleanup_nonce = cleanup_nonce;
773     return 1;
774 }
775
776 /*
777  * Set the reseed interval.
778  *
779  * The drbg will reseed automatically whenever the number of generate
780  * requests exceeds the given reseed interval. If the reseed interval
781  * is 0, then this feature is disabled.
782  *
783  * Returns 1 on success, 0 on failure.
784  */
785 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
786 {
787     if (interval > MAX_RESEED_INTERVAL)
788         return 0;
789     drbg->reseed_interval = interval;
790     return 1;
791 }
792
793 /*
794  * Set the reseed time interval.
795  *
796  * The drbg will reseed automatically whenever the time elapsed since
797  * the last reseeding exceeds the given reseed time interval. For safety,
798  * a reseeding will also occur if the clock has been reset to a smaller
799  * value.
800  *
801  * Returns 1 on success, 0 on failure.
802  */
803 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
804 {
805     if (interval > MAX_RESEED_TIME_INTERVAL)
806         return 0;
807     drbg->reseed_time_interval = interval;
808     return 1;
809 }
810
811 /*
812  * Set the default values for reseed (time) intervals of new DRBG instances
813  *
814  * The default values can be set independently for master DRBG instances
815  * (without a parent) and slave DRBG instances (with parent).
816  *
817  * Returns 1 on success, 0 on failure.
818  */
819
820 int RAND_DRBG_set_reseed_defaults(
821                                   unsigned int _master_reseed_interval,
822                                   unsigned int _slave_reseed_interval,
823                                   time_t _master_reseed_time_interval,
824                                   time_t _slave_reseed_time_interval
825                                   )
826 {
827     if (_master_reseed_interval > MAX_RESEED_INTERVAL
828         || _slave_reseed_interval > MAX_RESEED_INTERVAL)
829         return 0;
830
831     if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
832         || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
833         return 0;
834
835     master_reseed_interval = _master_reseed_interval;
836     slave_reseed_interval = _slave_reseed_interval;
837
838     master_reseed_time_interval = _master_reseed_time_interval;
839     slave_reseed_time_interval = _slave_reseed_time_interval;
840
841     return 1;
842 }
843
844 /*
845  * Locks the given drbg. Locking a drbg which does not have locking
846  * enabled is considered a successful no-op.
847  *
848  * Returns 1 on success, 0 on failure.
849  */
850 int rand_drbg_lock(RAND_DRBG *drbg)
851 {
852     if (drbg->lock != NULL)
853         return CRYPTO_THREAD_write_lock(drbg->lock);
854
855     return 1;
856 }
857
858 /*
859  * Unlocks the given drbg. Unlocking a drbg which does not have locking
860  * enabled is considered a successful no-op.
861  *
862  * Returns 1 on success, 0 on failure.
863  */
864 int rand_drbg_unlock(RAND_DRBG *drbg)
865 {
866     if (drbg->lock != NULL)
867         return CRYPTO_THREAD_unlock(drbg->lock);
868
869     return 1;
870 }
871
872 /*
873  * Enables locking for the given drbg
874  *
875  * Locking can only be enabled if the random generator
876  * is in the uninitialized state.
877  *
878  * Returns 1 on success, 0 on failure.
879  */
880 int rand_drbg_enable_locking(RAND_DRBG *drbg)
881 {
882     if (drbg->state != DRBG_UNINITIALISED) {
883         RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
884                 RAND_R_DRBG_ALREADY_INITIALIZED);
885         return 0;
886     }
887
888     if (drbg->lock == NULL) {
889         if (drbg->parent != NULL && drbg->parent->lock == NULL) {
890             RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
891                     RAND_R_PARENT_LOCKING_NOT_ENABLED);
892             return 0;
893         }
894
895         drbg->lock = CRYPTO_THREAD_lock_new();
896         if (drbg->lock == NULL) {
897             RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
898                     RAND_R_FAILED_TO_CREATE_LOCK);
899             return 0;
900         }
901     }
902
903     return 1;
904 }
905
906 /*
907  * Get and set the EXDATA
908  */
909 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
910 {
911     return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
912 }
913
914 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
915 {
916     return CRYPTO_get_ex_data(&drbg->ex_data, idx);
917 }
918
919
920 /*
921  * The following functions provide a RAND_METHOD that works on the
922  * global DRBG.  They lock.
923  */
924
925 /*
926  * Allocates a new global DRBG on the secure heap (if enabled) and
927  * initializes it with default settings.
928  *
929  * Returns a pointer to the new DRBG instance on success, NULL on failure.
930  */
931 static RAND_DRBG *drbg_setup(RAND_DRBG *parent, int drbg_type)
932 {
933     RAND_DRBG *drbg;
934
935     drbg = RAND_DRBG_secure_new(rand_drbg_type[drbg_type],
936                                 rand_drbg_flags[drbg_type], parent);
937     if (drbg == NULL)
938         return NULL;
939
940     /* Only the master DRBG needs to have a lock */
941     if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
942         goto err;
943
944     /* enable seed propagation */
945     drbg->reseed_prop_counter = 1;
946
947     /*
948      * Ignore instantiation error to support just-in-time instantiation.
949      *
950      * The state of the drbg will be checked in RAND_DRBG_generate() and
951      * an automatic recovery is attempted.
952      */
953     (void)RAND_DRBG_instantiate(drbg,
954                                 (const unsigned char *) ossl_pers_string,
955                                 sizeof(ossl_pers_string) - 1);
956     return drbg;
957
958 err:
959     RAND_DRBG_free(drbg);
960     return NULL;
961 }
962
963 /*
964  * Initialize the global DRBGs on first use.
965  * Returns 1 on success, 0 on failure.
966  */
967 DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
968 {
969     /*
970      * ensure that libcrypto is initialized, otherwise the
971      * DRBG locks are not cleaned up properly
972      */
973     if (!OPENSSL_init_crypto(0, NULL))
974         return 0;
975
976     if (!CRYPTO_THREAD_init_local(&private_drbg, NULL))
977         return 0;
978
979     if (!CRYPTO_THREAD_init_local(&public_drbg, NULL))
980         goto err1;
981
982     master_drbg = drbg_setup(NULL, RAND_DRBG_TYPE_MASTER);
983     if (master_drbg == NULL)
984         goto err2;
985
986     return 1;
987
988 err2:
989     CRYPTO_THREAD_cleanup_local(&public_drbg);
990 err1:
991     CRYPTO_THREAD_cleanup_local(&private_drbg);
992     return 0;
993 }
994
995 /* Clean up the global DRBGs before exit */
996 void rand_drbg_cleanup_int(void)
997 {
998     if (master_drbg != NULL) {
999         RAND_DRBG_free(master_drbg);
1000         master_drbg = NULL;
1001
1002         CRYPTO_THREAD_cleanup_local(&private_drbg);
1003         CRYPTO_THREAD_cleanup_local(&public_drbg);
1004     }
1005 }
1006
1007 void drbg_delete_thread_state(void)
1008 {
1009     RAND_DRBG *drbg;
1010
1011     drbg = CRYPTO_THREAD_get_local(&public_drbg);
1012     CRYPTO_THREAD_set_local(&public_drbg, NULL);
1013     RAND_DRBG_free(drbg);
1014
1015     drbg = CRYPTO_THREAD_get_local(&private_drbg);
1016     CRYPTO_THREAD_set_local(&private_drbg, NULL);
1017     RAND_DRBG_free(drbg);
1018 }
1019
1020 /* Implements the default OpenSSL RAND_bytes() method */
1021 static int drbg_bytes(unsigned char *out, int count)
1022 {
1023     int ret;
1024     RAND_DRBG *drbg = RAND_DRBG_get0_public();
1025
1026     if (drbg == NULL)
1027         return 0;
1028
1029     ret = RAND_DRBG_bytes(drbg, out, count);
1030
1031     return ret;
1032 }
1033
1034 /*
1035  * Calculates the minimum length of a full entropy buffer
1036  * which is necessary to seed (i.e. instantiate) the DRBG
1037  * successfully.
1038  *
1039  * NOTE: There is a copy of this function in drbgtest.c.
1040  *       If you change anything here, you need to update
1041  *       the copy accordingly.
1042  */
1043 static size_t rand_drbg_seedlen(RAND_DRBG *drbg)
1044 {
1045     /*
1046      * If no os entropy source is available then RAND_seed(buffer, bufsize)
1047      * is expected to succeed if and only if the buffer length satisfies
1048      * the following requirements, which follow from the calculations
1049      * in RAND_DRBG_instantiate().
1050      */
1051     size_t min_entropy = drbg->strength;
1052     size_t min_entropylen = drbg->min_entropylen;
1053
1054     /*
1055      * Extra entropy for the random nonce in the absence of a
1056      * get_nonce callback, see comment in RAND_DRBG_instantiate().
1057      */
1058     if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
1059         min_entropy += drbg->strength / 2;
1060         min_entropylen += drbg->min_noncelen;
1061     }
1062
1063     /*
1064      * Convert entropy requirement from bits to bytes
1065      * (dividing by 8 without rounding upwards, because
1066      * all entropy requirements are divisible by 8).
1067      */
1068     min_entropy >>= 3;
1069
1070     /* Return a value that satisfies both requirements */
1071     return min_entropy > min_entropylen ? min_entropy : min_entropylen;
1072 }
1073
1074 /* Implements the default OpenSSL RAND_add() method */
1075 static int drbg_add(const void *buf, int num, double randomness)
1076 {
1077     int ret = 0;
1078     RAND_DRBG *drbg = RAND_DRBG_get0_master();
1079     size_t buflen;
1080     size_t seedlen = rand_drbg_seedlen(drbg);
1081
1082     if (drbg == NULL)
1083         return 0;
1084
1085     if (num < 0 || randomness < 0.0)
1086         return 0;
1087
1088     buflen = (size_t)num;
1089
1090     if (buflen < seedlen || randomness < (double) seedlen) {
1091 #if defined(OPENSSL_RAND_SEED_NONE)
1092         /*
1093          * If no os entropy source is available, a reseeding will fail
1094          * inevitably. So we use a trick to mix the buffer contents into
1095          * the DRBG state without forcing a reseeding: we generate a
1096          * dummy random byte, using the buffer content as additional data.
1097          */
1098         unsigned char dummy[1];
1099
1100         return RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
1101 #else
1102         /*
1103          * If an os entropy source is avaible then we declare the buffer content
1104          * as additional data by setting randomness to zero and trigger a regular
1105          * reseeding.
1106          */
1107         randomness = 0.0;
1108 #endif
1109     }
1110
1111
1112     if (randomness > (double)seedlen) {
1113         /*
1114          * The purpose of this check is to bound |randomness| by a
1115          * relatively small value in order to prevent an integer
1116          * overflow when multiplying by 8 in the rand_drbg_restart()
1117          * call below. Note that randomness is measured in bytes,
1118          * not bits, so this value corresponds to eight times the
1119          * security strength.
1120          */
1121         randomness = (double)seedlen;
1122     }
1123
1124     rand_drbg_lock(drbg);
1125     ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
1126     rand_drbg_unlock(drbg);
1127
1128     return ret;
1129 }
1130
1131 /* Implements the default OpenSSL RAND_seed() method */
1132 static int drbg_seed(const void *buf, int num)
1133 {
1134     return drbg_add(buf, num, num);
1135 }
1136
1137 /* Implements the default OpenSSL RAND_status() method */
1138 static int drbg_status(void)
1139 {
1140     int ret;
1141     RAND_DRBG *drbg = RAND_DRBG_get0_master();
1142
1143     if (drbg == NULL)
1144         return 0;
1145
1146     rand_drbg_lock(drbg);
1147     ret = drbg->state == DRBG_READY ? 1 : 0;
1148     rand_drbg_unlock(drbg);
1149     return ret;
1150 }
1151
1152 /*
1153  * Get the master DRBG.
1154  * Returns pointer to the DRBG on success, NULL on failure.
1155  *
1156  */
1157 RAND_DRBG *RAND_DRBG_get0_master(void)
1158 {
1159     if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1160         return NULL;
1161
1162     return master_drbg;
1163 }
1164
1165 /*
1166  * Get the public DRBG.
1167  * Returns pointer to the DRBG on success, NULL on failure.
1168  */
1169 RAND_DRBG *RAND_DRBG_get0_public(void)
1170 {
1171     RAND_DRBG *drbg;
1172
1173     if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1174         return NULL;
1175
1176     drbg = CRYPTO_THREAD_get_local(&public_drbg);
1177     if (drbg == NULL) {
1178         if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1179             return NULL;
1180         drbg = drbg_setup(master_drbg, RAND_DRBG_TYPE_PUBLIC);
1181         CRYPTO_THREAD_set_local(&public_drbg, drbg);
1182     }
1183     return drbg;
1184 }
1185
1186 /*
1187  * Get the private DRBG.
1188  * Returns pointer to the DRBG on success, NULL on failure.
1189  */
1190 RAND_DRBG *RAND_DRBG_get0_private(void)
1191 {
1192     RAND_DRBG *drbg;
1193
1194     if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1195         return NULL;
1196
1197     drbg = CRYPTO_THREAD_get_local(&private_drbg);
1198     if (drbg == NULL) {
1199         if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1200             return NULL;
1201         drbg = drbg_setup(master_drbg, RAND_DRBG_TYPE_PRIVATE);
1202         CRYPTO_THREAD_set_local(&private_drbg, drbg);
1203     }
1204     return drbg;
1205 }
1206
1207 RAND_METHOD rand_meth = {
1208     drbg_seed,
1209     drbg_bytes,
1210     NULL,
1211     drbg_add,
1212     drbg_bytes,
1213     drbg_status
1214 };
1215
1216 RAND_METHOD *RAND_OpenSSL(void)
1217 {
1218     return &rand_meth;
1219 }