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