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