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