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