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