2 * Copyright 2011-2018 The OpenSSL Project Authors. All Rights Reserved.
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
11 #include <openssl/crypto.h>
12 #include <openssl/err.h>
13 #include <openssl/rand.h>
15 #include "internal/thread_once.h"
16 #include "internal/rand_int.h"
17 #include "internal/cryptlib_int.h"
20 * Support framework for NIST SP 800-90A DRBG
22 * See manual page RAND_DRBG(7) for a general overview.
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.)
33 typedef struct drbg_global_st {
35 * The three shared DRBG instances
37 * There are three shared DRBG instances: <master>, <public>, and <private>.
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().
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.
51 RAND_DRBG *master_drbg;
55 * Used by default for generating random bytes using RAND_bytes().
57 * The <public> DRBG is thread-local, i.e., there is one instance per
60 CRYPTO_THREAD_LOCAL public_drbg;
64 * Used by default for generating private keys using RAND_priv_bytes()
66 * The <private> DRBG is thread-local, i.e., there is one instance per
69 CRYPTO_THREAD_LOCAL private_drbg;
72 typedef struct drbg_nonce_global_st {
73 CRYPTO_RWLOCK *rand_nonce_lock;
77 /* NIST SP 800-90A DRBG recommends the use of a personalization string. */
78 static const char ossl_pers_string[] = DRBG_DEFAULT_PERS_STRING;
80 #define RAND_DRBG_TYPE_FLAGS ( \
81 RAND_DRBG_FLAG_MASTER | RAND_DRBG_FLAG_PUBLIC | RAND_DRBG_FLAG_PRIVATE )
83 #define RAND_DRBG_TYPE_MASTER 0
84 #define RAND_DRBG_TYPE_PUBLIC 1
85 #define RAND_DRBG_TYPE_PRIVATE 2
88 static int rand_drbg_type[3] = {
89 RAND_DRBG_TYPE, /* Master */
90 RAND_DRBG_TYPE, /* Public */
91 RAND_DRBG_TYPE /* Private */
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 */
99 static unsigned int master_reseed_interval = MASTER_RESEED_INTERVAL;
100 static unsigned int slave_reseed_interval = SLAVE_RESEED_INTERVAL;
102 static time_t master_reseed_time_interval = MASTER_RESEED_TIME_INTERVAL;
103 static time_t slave_reseed_time_interval = SLAVE_RESEED_TIME_INTERVAL;
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;
110 static RAND_DRBG *drbg_setup(OPENSSL_CTX *ctx, RAND_DRBG *parent, int drbg_type);
112 static RAND_DRBG *rand_drbg_new(OPENSSL_CTX *ctx,
118 static int is_ctr(int type)
121 case NID_aes_128_ctr:
122 case NID_aes_192_ctr:
123 case NID_aes_256_ctr:
130 static int is_digest(int type)
151 * Initialize the OPENSSL_CTX global DRBGs on first use.
152 * Returns the allocated global data on success or NULL on failure.
154 static void *drbg_ossl_ctx_new(OPENSSL_CTX *libctx)
156 DRBG_GLOBAL *dgbl = OPENSSL_zalloc(sizeof(*dgbl));
161 if (!CRYPTO_THREAD_init_local(&dgbl->private_drbg, NULL))
164 if (!CRYPTO_THREAD_init_local(&dgbl->public_drbg, NULL))
167 dgbl->master_drbg = drbg_setup(libctx, NULL, RAND_DRBG_TYPE_MASTER);
168 if (dgbl->master_drbg == NULL)
174 CRYPTO_THREAD_cleanup_local(&dgbl->public_drbg);
176 CRYPTO_THREAD_cleanup_local(&dgbl->private_drbg);
182 static void drbg_ossl_ctx_free(void *vdgbl)
184 DRBG_GLOBAL *dgbl = vdgbl;
186 RAND_DRBG_free(dgbl->master_drbg);
187 CRYPTO_THREAD_cleanup_local(&dgbl->private_drbg);
188 CRYPTO_THREAD_cleanup_local(&dgbl->public_drbg);
193 static const OPENSSL_CTX_METHOD drbg_ossl_ctx_method = {
199 * drbg_ossl_ctx_new() calls drgb_setup() which calls rand_drbg_get_nonce()
200 * which needs to get the rand_nonce_lock out of the OPENSSL_CTX...but since
201 * drbg_ossl_ctx_new() hasn't finished running yet we need the rand_nonce_lock
202 * to be in a different global data object. Otherwise we will go into an
203 * infinite recursion loop.
205 static void *drbg_nonce_ossl_ctx_new(OPENSSL_CTX *libctx)
207 DRBG_NONCE_GLOBAL *dngbl = OPENSSL_zalloc(sizeof(*dngbl));
212 dngbl->rand_nonce_lock = CRYPTO_THREAD_lock_new();
213 if (dngbl->rand_nonce_lock == NULL) {
221 static void drbg_nonce_ossl_ctx_free(void *vdngbl)
223 DRBG_NONCE_GLOBAL *dngbl = vdngbl;
225 CRYPTO_THREAD_lock_free(dngbl->rand_nonce_lock);
230 static const OPENSSL_CTX_METHOD drbg_nonce_ossl_ctx_method = {
231 drbg_nonce_ossl_ctx_new,
232 drbg_nonce_ossl_ctx_free,
235 static DRBG_GLOBAL *drbg_get_global(OPENSSL_CTX *libctx)
237 return openssl_ctx_get_data(libctx, OPENSSL_CTX_DRBG_INDEX,
238 &drbg_ossl_ctx_method);
241 /* Implements the get_nonce() callback (see RAND_DRBG_set_callbacks()) */
242 size_t rand_drbg_get_nonce(RAND_DRBG *drbg,
243 unsigned char **pout,
244 int entropy, size_t min_len, size_t max_len)
248 DRBG_NONCE_GLOBAL *dngbl
249 = openssl_ctx_get_data(drbg->libctx, OPENSSL_CTX_DRBG_NONCE_INDEX,
250 &drbg_nonce_ossl_ctx_method);
259 memset(&data, 0, sizeof(data));
260 pool = rand_pool_new(0, min_len, max_len);
264 if (rand_pool_add_nonce_data(pool) == 0)
267 data.instance = drbg;
268 CRYPTO_atomic_add(&dngbl->rand_nonce_count, 1, &data.count,
269 dngbl->rand_nonce_lock);
271 if (rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0) == 0)
274 ret = rand_pool_length(pool);
275 *pout = rand_pool_detach(pool);
278 rand_pool_free(pool);
284 * Implements the cleanup_nonce() callback (see RAND_DRBG_set_callbacks())
287 void rand_drbg_cleanup_nonce(RAND_DRBG *drbg,
288 unsigned char *out, size_t outlen)
290 OPENSSL_secure_clear_free(out, outlen);
294 * Set/initialize |drbg| to be of type |type|, with optional |flags|.
296 * If |type| and |flags| are zero, use the defaults
298 * Returns 1 on success, 0 on failure.
300 int RAND_DRBG_set(RAND_DRBG *drbg, int type, unsigned int flags)
304 if (type == 0 && flags == 0) {
305 type = rand_drbg_type[RAND_DRBG_TYPE_MASTER];
306 flags = rand_drbg_flags[RAND_DRBG_TYPE_MASTER];
309 /* If set is called multiple times - clear the old one */
310 if (drbg->type != 0 && (type != drbg->type || flags != drbg->flags)) {
311 drbg->meth->uninstantiate(drbg);
312 rand_pool_free(drbg->adin_pool);
313 drbg->adin_pool = NULL;
316 drbg->state = DRBG_UNINITIALISED;
321 /* Uninitialized; that's okay. */
324 } else if (is_ctr(type)) {
325 ret = drbg_ctr_init(drbg);
326 } else if (is_digest(type)) {
327 if (flags & RAND_DRBG_FLAG_HMAC)
328 ret = drbg_hmac_init(drbg);
330 ret = drbg_hash_init(drbg);
335 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
340 drbg->state = DRBG_ERROR;
341 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG);
347 * Set/initialize default |type| and |flag| for new drbg instances.
349 * Returns 1 on success, 0 on failure.
351 int RAND_DRBG_set_defaults(int type, unsigned int flags)
354 if (!(is_digest(type) || is_ctr(type))) {
355 RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_TYPE);
359 if ((flags & ~rand_drbg_used_flags) != 0) {
360 RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_FLAGS);
364 all = ((flags & RAND_DRBG_TYPE_FLAGS) == 0);
365 if (all || (flags & RAND_DRBG_FLAG_MASTER) != 0) {
366 rand_drbg_type[RAND_DRBG_TYPE_MASTER] = type;
367 rand_drbg_flags[RAND_DRBG_TYPE_MASTER] = flags | RAND_DRBG_FLAG_MASTER;
369 if (all || (flags & RAND_DRBG_FLAG_PUBLIC) != 0) {
370 rand_drbg_type[RAND_DRBG_TYPE_PUBLIC] = type;
371 rand_drbg_flags[RAND_DRBG_TYPE_PUBLIC] = flags | RAND_DRBG_FLAG_PUBLIC;
373 if (all || (flags & RAND_DRBG_FLAG_PRIVATE) != 0) {
374 rand_drbg_type[RAND_DRBG_TYPE_PRIVATE] = type;
375 rand_drbg_flags[RAND_DRBG_TYPE_PRIVATE] = flags | RAND_DRBG_FLAG_PRIVATE;
382 * Allocate memory and initialize a new DRBG. The DRBG is allocated on
383 * the secure heap if |secure| is nonzero and the secure heap is enabled.
384 * The |parent|, if not NULL, will be used as random source for reseeding.
386 * Returns a pointer to the new DRBG instance on success, NULL on failure.
388 static RAND_DRBG *rand_drbg_new(OPENSSL_CTX *ctx,
394 RAND_DRBG *drbg = secure ? OPENSSL_secure_zalloc(sizeof(*drbg))
395 : OPENSSL_zalloc(sizeof(*drbg));
398 RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
403 drbg->secure = secure && CRYPTO_secure_allocated(drbg);
404 drbg->fork_count = rand_fork_count;
405 drbg->parent = parent;
407 if (parent == NULL) {
409 drbg->get_entropy = rand_crngt_get_entropy;
410 drbg->cleanup_entropy = rand_crngt_cleanup_entropy;
412 drbg->get_entropy = rand_drbg_get_entropy;
413 drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
415 #ifndef RAND_DRBG_GET_RANDOM_NONCE
416 drbg->get_nonce = rand_drbg_get_nonce;
417 drbg->cleanup_nonce = rand_drbg_cleanup_nonce;
420 drbg->reseed_interval = master_reseed_interval;
421 drbg->reseed_time_interval = master_reseed_time_interval;
423 drbg->get_entropy = rand_drbg_get_entropy;
424 drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
426 * Do not provide nonce callbacks, the child DRBGs will
427 * obtain their nonce using random bits from the parent.
430 drbg->reseed_interval = slave_reseed_interval;
431 drbg->reseed_time_interval = slave_reseed_time_interval;
434 if (RAND_DRBG_set(drbg, type, flags) == 0)
437 if (parent != NULL) {
438 rand_drbg_lock(parent);
439 if (drbg->strength > parent->strength) {
441 * We currently don't support the algorithm from NIST SP 800-90C
442 * 10.1.2 to use a weaker DRBG as source
444 rand_drbg_unlock(parent);
445 RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK);
448 rand_drbg_unlock(parent);
454 RAND_DRBG_free(drbg);
459 RAND_DRBG *RAND_DRBG_new_ex(OPENSSL_CTX *ctx, int type, unsigned int flags,
462 return rand_drbg_new(ctx, 0, type, flags, parent);
465 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
467 return RAND_DRBG_new_ex(NULL, type, flags, parent);
470 RAND_DRBG *RAND_DRBG_secure_new_ex(OPENSSL_CTX *ctx, int type,
471 unsigned int flags, RAND_DRBG *parent)
473 return rand_drbg_new(ctx, 1, type, flags, parent);
476 RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent)
478 return RAND_DRBG_secure_new_ex(NULL, type, flags, parent);
481 * Uninstantiate |drbg| and free all memory.
483 void RAND_DRBG_free(RAND_DRBG *drbg)
488 if (drbg->meth != NULL)
489 drbg->meth->uninstantiate(drbg);
490 rand_pool_free(drbg->adin_pool);
491 CRYPTO_THREAD_lock_free(drbg->lock);
492 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
495 OPENSSL_secure_clear_free(drbg, sizeof(*drbg));
497 OPENSSL_clear_free(drbg, sizeof(*drbg));
501 * Instantiate |drbg|, after it has been initialized. Use |pers| and
502 * |perslen| as prediction-resistance input.
504 * Requires that drbg->lock is already locked for write, if non-null.
506 * Returns 1 on success, 0 on failure.
508 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
509 const unsigned char *pers, size_t perslen)
511 unsigned char *nonce = NULL, *entropy = NULL;
512 size_t noncelen = 0, entropylen = 0;
513 size_t min_entropy = drbg->strength;
514 size_t min_entropylen = drbg->min_entropylen;
515 size_t max_entropylen = drbg->max_entropylen;
517 if (perslen > drbg->max_perslen) {
518 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
519 RAND_R_PERSONALISATION_STRING_TOO_LONG);
523 if (drbg->meth == NULL) {
524 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
525 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
529 if (drbg->state != DRBG_UNINITIALISED) {
530 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
531 drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE
532 : RAND_R_ALREADY_INSTANTIATED);
536 drbg->state = DRBG_ERROR;
539 * NIST SP800-90Ar1 section 9.1 says you can combine getting the entropy
540 * and nonce in 1 call by increasing the entropy with 50% and increasing
541 * the minimum length to accomadate the length of the nonce.
542 * We do this in case a nonce is require and get_nonce is NULL.
544 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
545 min_entropy += drbg->strength / 2;
546 min_entropylen += drbg->min_noncelen;
547 max_entropylen += drbg->max_noncelen;
550 drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
551 if (drbg->reseed_next_counter) {
552 drbg->reseed_next_counter++;
553 if(!drbg->reseed_next_counter)
554 drbg->reseed_next_counter = 1;
557 if (drbg->get_entropy != NULL)
558 entropylen = drbg->get_entropy(drbg, &entropy, min_entropy,
559 min_entropylen, max_entropylen, 0);
560 if (entropylen < min_entropylen
561 || entropylen > max_entropylen) {
562 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
566 if (drbg->min_noncelen > 0 && drbg->get_nonce != NULL) {
567 noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
568 drbg->min_noncelen, drbg->max_noncelen);
569 if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
570 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_NONCE);
575 if (!drbg->meth->instantiate(drbg, entropy, entropylen,
576 nonce, noncelen, pers, perslen)) {
577 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
581 drbg->state = DRBG_READY;
582 drbg->reseed_gen_counter = 1;
583 drbg->reseed_time = time(NULL);
584 tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
587 if (entropy != NULL && drbg->cleanup_entropy != NULL)
588 drbg->cleanup_entropy(drbg, entropy, entropylen);
589 if (nonce != NULL && drbg->cleanup_nonce != NULL)
590 drbg->cleanup_nonce(drbg, nonce, noncelen);
591 if (drbg->state == DRBG_READY)
597 * Uninstantiate |drbg|. Must be instantiated before it can be used.
599 * Requires that drbg->lock is already locked for write, if non-null.
601 * Returns 1 on success, 0 on failure.
603 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
605 int index = -1, type, flags;
606 if (drbg->meth == NULL) {
607 drbg->state = DRBG_ERROR;
608 RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
609 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
613 /* Clear the entire drbg->ctr struct, then reset some important
614 * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
617 drbg->meth->uninstantiate(drbg);
619 /* The reset uses the default values for type and flags */
620 if (drbg->flags & RAND_DRBG_FLAG_MASTER)
621 index = RAND_DRBG_TYPE_MASTER;
622 else if (drbg->flags & RAND_DRBG_FLAG_PRIVATE)
623 index = RAND_DRBG_TYPE_PRIVATE;
624 else if (drbg->flags & RAND_DRBG_FLAG_PUBLIC)
625 index = RAND_DRBG_TYPE_PUBLIC;
628 flags = rand_drbg_flags[index];
629 type = rand_drbg_type[index];
634 return RAND_DRBG_set(drbg, type, flags);
638 * Reseed |drbg|, mixing in the specified data
640 * Requires that drbg->lock is already locked for write, if non-null.
642 * Returns 1 on success, 0 on failure.
644 int RAND_DRBG_reseed(RAND_DRBG *drbg,
645 const unsigned char *adin, size_t adinlen,
646 int prediction_resistance)
648 unsigned char *entropy = NULL;
649 size_t entropylen = 0;
651 if (drbg->state == DRBG_ERROR) {
652 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
655 if (drbg->state == DRBG_UNINITIALISED) {
656 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
662 } else if (adinlen > drbg->max_adinlen) {
663 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
667 drbg->state = DRBG_ERROR;
669 drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
670 if (drbg->reseed_next_counter) {
671 drbg->reseed_next_counter++;
672 if(!drbg->reseed_next_counter)
673 drbg->reseed_next_counter = 1;
676 if (drbg->get_entropy != NULL)
677 entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
678 drbg->min_entropylen,
679 drbg->max_entropylen,
680 prediction_resistance);
681 if (entropylen < drbg->min_entropylen
682 || entropylen > drbg->max_entropylen) {
683 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
687 if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
690 drbg->state = DRBG_READY;
691 drbg->reseed_gen_counter = 1;
692 drbg->reseed_time = time(NULL);
693 tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
696 if (entropy != NULL && drbg->cleanup_entropy != NULL)
697 drbg->cleanup_entropy(drbg, entropy, entropylen);
698 if (drbg->state == DRBG_READY)
704 * Restart |drbg|, using the specified entropy or additional input
706 * Tries its best to get the drbg instantiated by all means,
707 * regardless of its current state.
709 * Optionally, a |buffer| of |len| random bytes can be passed,
710 * which is assumed to contain at least |entropy| bits of entropy.
712 * If |entropy| > 0, the buffer content is used as entropy input.
714 * If |entropy| == 0, the buffer content is used as additional input
716 * Returns 1 on success, 0 on failure.
718 * This function is used internally only.
720 int rand_drbg_restart(RAND_DRBG *drbg,
721 const unsigned char *buffer, size_t len, size_t entropy)
724 const unsigned char *adin = NULL;
727 if (drbg->seed_pool != NULL) {
728 RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
729 drbg->state = DRBG_ERROR;
730 rand_pool_free(drbg->seed_pool);
731 drbg->seed_pool = NULL;
735 if (buffer != NULL) {
737 if (drbg->max_entropylen < len) {
738 RANDerr(RAND_F_RAND_DRBG_RESTART,
739 RAND_R_ENTROPY_INPUT_TOO_LONG);
740 drbg->state = DRBG_ERROR;
744 if (entropy > 8 * len) {
745 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
746 drbg->state = DRBG_ERROR;
750 /* will be picked up by the rand_drbg_get_entropy() callback */
751 drbg->seed_pool = rand_pool_attach(buffer, len, entropy);
752 if (drbg->seed_pool == NULL)
755 if (drbg->max_adinlen < len) {
756 RANDerr(RAND_F_RAND_DRBG_RESTART,
757 RAND_R_ADDITIONAL_INPUT_TOO_LONG);
758 drbg->state = DRBG_ERROR;
766 /* repair error state */
767 if (drbg->state == DRBG_ERROR)
768 RAND_DRBG_uninstantiate(drbg);
770 /* repair uninitialized state */
771 if (drbg->state == DRBG_UNINITIALISED) {
772 /* reinstantiate drbg */
773 RAND_DRBG_instantiate(drbg,
774 (const unsigned char *) ossl_pers_string,
775 sizeof(ossl_pers_string) - 1);
776 /* already reseeded. prevent second reseeding below */
777 reseeded = (drbg->state == DRBG_READY);
780 /* refresh current state if entropy or additional input has been provided */
781 if (drbg->state == DRBG_READY) {
784 * mix in additional input without reseeding
786 * Similar to RAND_DRBG_reseed(), but the provided additional
787 * data |adin| is mixed into the current state without pulling
788 * entropy from the trusted entropy source using get_entropy().
789 * This is not a reseeding in the strict sense of NIST SP 800-90A.
791 drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
792 } else if (reseeded == 0) {
793 /* do a full reseeding if it has not been done yet above */
794 RAND_DRBG_reseed(drbg, NULL, 0, 0);
798 rand_pool_free(drbg->seed_pool);
799 drbg->seed_pool = NULL;
801 return drbg->state == DRBG_READY;
805 * Generate |outlen| bytes into the buffer at |out|. Reseed if we need
806 * to or if |prediction_resistance| is set. Additional input can be
807 * sent in |adin| and |adinlen|.
809 * Requires that drbg->lock is already locked for write, if non-null.
811 * Returns 1 on success, 0 on failure.
814 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
815 int prediction_resistance,
816 const unsigned char *adin, size_t adinlen)
818 int reseed_required = 0;
820 if (drbg->state != DRBG_READY) {
821 /* try to recover from previous errors */
822 rand_drbg_restart(drbg, NULL, 0, 0);
824 if (drbg->state == DRBG_ERROR) {
825 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
828 if (drbg->state == DRBG_UNINITIALISED) {
829 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
834 if (outlen > drbg->max_request) {
835 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
838 if (adinlen > drbg->max_adinlen) {
839 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
843 if (drbg->fork_count != rand_fork_count) {
844 drbg->fork_count = rand_fork_count;
848 if (drbg->reseed_interval > 0) {
849 if (drbg->reseed_gen_counter > drbg->reseed_interval)
852 if (drbg->reseed_time_interval > 0) {
853 time_t now = time(NULL);
854 if (now < drbg->reseed_time
855 || now - drbg->reseed_time >= drbg->reseed_time_interval)
858 if (drbg->parent != NULL) {
859 unsigned int reseed_counter = tsan_load(&drbg->reseed_prop_counter);
860 if (reseed_counter > 0
861 && tsan_load(&drbg->parent->reseed_prop_counter)
866 if (reseed_required || prediction_resistance) {
867 if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
868 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
875 if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
876 drbg->state = DRBG_ERROR;
877 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
881 drbg->reseed_gen_counter++;
887 * Generates |outlen| random bytes and stores them in |out|. It will
888 * using the given |drbg| to generate the bytes.
890 * Requires that drbg->lock is already locked for write, if non-null.
892 * Returns 1 on success 0 on failure.
894 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
896 unsigned char *additional = NULL;
897 size_t additional_len;
901 if (drbg->adin_pool == NULL) {
904 drbg->adin_pool = rand_pool_new(0, 0, drbg->max_adinlen);
905 if (drbg->adin_pool == NULL)
909 additional_len = rand_drbg_get_additional_data(drbg->adin_pool,
912 for ( ; outlen > 0; outlen -= chunk, out += chunk) {
914 if (chunk > drbg->max_request)
915 chunk = drbg->max_request;
916 ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
923 if (additional != NULL)
924 rand_drbg_cleanup_additional_data(drbg->adin_pool, additional);
930 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
932 * Setting the callbacks is allowed only if the drbg has not been
933 * initialized yet. Otherwise, the operation will fail.
935 * Returns 1 on success, 0 on failure.
937 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
938 RAND_DRBG_get_entropy_fn get_entropy,
939 RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
940 RAND_DRBG_get_nonce_fn get_nonce,
941 RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
943 if (drbg->state != DRBG_UNINITIALISED
944 || drbg->parent != NULL)
946 drbg->get_entropy = get_entropy;
947 drbg->cleanup_entropy = cleanup_entropy;
948 drbg->get_nonce = get_nonce;
949 drbg->cleanup_nonce = cleanup_nonce;
954 * Set the reseed interval.
956 * The drbg will reseed automatically whenever the number of generate
957 * requests exceeds the given reseed interval. If the reseed interval
958 * is 0, then this feature is disabled.
960 * Returns 1 on success, 0 on failure.
962 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
964 if (interval > MAX_RESEED_INTERVAL)
966 drbg->reseed_interval = interval;
971 * Set the reseed time interval.
973 * The drbg will reseed automatically whenever the time elapsed since
974 * the last reseeding exceeds the given reseed time interval. For safety,
975 * a reseeding will also occur if the clock has been reset to a smaller
978 * Returns 1 on success, 0 on failure.
980 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
982 if (interval > MAX_RESEED_TIME_INTERVAL)
984 drbg->reseed_time_interval = interval;
989 * Set the default values for reseed (time) intervals of new DRBG instances
991 * The default values can be set independently for master DRBG instances
992 * (without a parent) and slave DRBG instances (with parent).
994 * Returns 1 on success, 0 on failure.
997 int RAND_DRBG_set_reseed_defaults(
998 unsigned int _master_reseed_interval,
999 unsigned int _slave_reseed_interval,
1000 time_t _master_reseed_time_interval,
1001 time_t _slave_reseed_time_interval
1004 if (_master_reseed_interval > MAX_RESEED_INTERVAL
1005 || _slave_reseed_interval > MAX_RESEED_INTERVAL)
1008 if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
1009 || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
1012 master_reseed_interval = _master_reseed_interval;
1013 slave_reseed_interval = _slave_reseed_interval;
1015 master_reseed_time_interval = _master_reseed_time_interval;
1016 slave_reseed_time_interval = _slave_reseed_time_interval;
1022 * Locks the given drbg. Locking a drbg which does not have locking
1023 * enabled is considered a successful no-op.
1025 * Returns 1 on success, 0 on failure.
1027 int rand_drbg_lock(RAND_DRBG *drbg)
1029 if (drbg->lock != NULL)
1030 return CRYPTO_THREAD_write_lock(drbg->lock);
1036 * Unlocks the given drbg. Unlocking a drbg which does not have locking
1037 * enabled is considered a successful no-op.
1039 * Returns 1 on success, 0 on failure.
1041 int rand_drbg_unlock(RAND_DRBG *drbg)
1043 if (drbg->lock != NULL)
1044 return CRYPTO_THREAD_unlock(drbg->lock);
1050 * Enables locking for the given drbg
1052 * Locking can only be enabled if the random generator
1053 * is in the uninitialized state.
1055 * Returns 1 on success, 0 on failure.
1057 int rand_drbg_enable_locking(RAND_DRBG *drbg)
1059 if (drbg->state != DRBG_UNINITIALISED) {
1060 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
1061 RAND_R_DRBG_ALREADY_INITIALIZED);
1065 if (drbg->lock == NULL) {
1066 if (drbg->parent != NULL && drbg->parent->lock == NULL) {
1067 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
1068 RAND_R_PARENT_LOCKING_NOT_ENABLED);
1072 drbg->lock = CRYPTO_THREAD_lock_new();
1073 if (drbg->lock == NULL) {
1074 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
1075 RAND_R_FAILED_TO_CREATE_LOCK);
1084 * Get and set the EXDATA
1086 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
1088 return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
1091 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
1093 return CRYPTO_get_ex_data(&drbg->ex_data, idx);
1098 * The following functions provide a RAND_METHOD that works on the
1099 * global DRBG. They lock.
1103 * Allocates a new global DRBG on the secure heap (if enabled) and
1104 * initializes it with default settings.
1106 * Returns a pointer to the new DRBG instance on success, NULL on failure.
1108 static RAND_DRBG *drbg_setup(OPENSSL_CTX *ctx, RAND_DRBG *parent, int drbg_type)
1112 drbg = RAND_DRBG_secure_new_ex(ctx, rand_drbg_type[drbg_type],
1113 rand_drbg_flags[drbg_type], parent);
1117 /* Only the master DRBG needs to have a lock */
1118 if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
1121 /* enable seed propagation */
1122 tsan_store(&drbg->reseed_prop_counter, 1);
1125 * Ignore instantiation error to support just-in-time instantiation.
1127 * The state of the drbg will be checked in RAND_DRBG_generate() and
1128 * an automatic recovery is attempted.
1130 (void)RAND_DRBG_instantiate(drbg,
1131 (const unsigned char *) ossl_pers_string,
1132 sizeof(ossl_pers_string) - 1);
1136 RAND_DRBG_free(drbg);
1140 void drbg_delete_thread_state(void)
1142 /* TODO(3.0): Other PRs will pass the ctx as a param to this function */
1143 OPENSSL_CTX *ctx = NULL;
1144 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1149 drbg = CRYPTO_THREAD_get_local(&dgbl->public_drbg);
1150 CRYPTO_THREAD_set_local(&dgbl->public_drbg, NULL);
1151 RAND_DRBG_free(drbg);
1153 drbg = CRYPTO_THREAD_get_local(&dgbl->private_drbg);
1154 CRYPTO_THREAD_set_local(&dgbl->private_drbg, NULL);
1155 RAND_DRBG_free(drbg);
1158 /* Implements the default OpenSSL RAND_bytes() method */
1159 static int drbg_bytes(unsigned char *out, int count)
1162 RAND_DRBG *drbg = RAND_DRBG_get0_public();
1167 ret = RAND_DRBG_bytes(drbg, out, count);
1173 * Calculates the minimum length of a full entropy buffer
1174 * which is necessary to seed (i.e. instantiate) the DRBG
1177 size_t rand_drbg_seedlen(RAND_DRBG *drbg)
1180 * If no os entropy source is available then RAND_seed(buffer, bufsize)
1181 * is expected to succeed if and only if the buffer length satisfies
1182 * the following requirements, which follow from the calculations
1183 * in RAND_DRBG_instantiate().
1185 size_t min_entropy = drbg->strength;
1186 size_t min_entropylen = drbg->min_entropylen;
1189 * Extra entropy for the random nonce in the absence of a
1190 * get_nonce callback, see comment in RAND_DRBG_instantiate().
1192 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
1193 min_entropy += drbg->strength / 2;
1194 min_entropylen += drbg->min_noncelen;
1198 * Convert entropy requirement from bits to bytes
1199 * (dividing by 8 without rounding upwards, because
1200 * all entropy requirements are divisible by 8).
1204 /* Return a value that satisfies both requirements */
1205 return min_entropy > min_entropylen ? min_entropy : min_entropylen;
1208 /* Implements the default OpenSSL RAND_add() method */
1209 static int drbg_add(const void *buf, int num, double randomness)
1212 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1219 if (num < 0 || randomness < 0.0)
1222 rand_drbg_lock(drbg);
1223 seedlen = rand_drbg_seedlen(drbg);
1225 buflen = (size_t)num;
1229 * NIST SP-800-90A mandates that entropy *shall not* be provided
1230 * by the consuming application. By setting the randomness to zero,
1231 * we ensure that the buffer contents will be added to the internal
1232 * state of the DRBG only as additional data.
1234 * (NIST SP-800-90Ar1, Sections 9.1 and 9.2)
1238 if (buflen < seedlen || randomness < (double) seedlen) {
1239 #if defined(OPENSSL_RAND_SEED_NONE)
1241 * If no os entropy source is available, a reseeding will fail
1242 * inevitably. So we use a trick to mix the buffer contents into
1243 * the DRBG state without forcing a reseeding: we generate a
1244 * dummy random byte, using the buffer content as additional data.
1245 * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
1247 unsigned char dummy[1];
1249 ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
1250 rand_drbg_unlock(drbg);
1254 * If an os entropy source is available then we declare the buffer content
1255 * as additional data by setting randomness to zero and trigger a regular
1262 if (randomness > (double)seedlen) {
1264 * The purpose of this check is to bound |randomness| by a
1265 * relatively small value in order to prevent an integer
1266 * overflow when multiplying by 8 in the rand_drbg_restart()
1267 * call below. Note that randomness is measured in bytes,
1268 * not bits, so this value corresponds to eight times the
1269 * security strength.
1271 randomness = (double)seedlen;
1274 ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
1275 rand_drbg_unlock(drbg);
1280 /* Implements the default OpenSSL RAND_seed() method */
1281 static int drbg_seed(const void *buf, int num)
1283 return drbg_add(buf, num, num);
1286 /* Implements the default OpenSSL RAND_status() method */
1287 static int drbg_status(void)
1290 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1295 rand_drbg_lock(drbg);
1296 ret = drbg->state == DRBG_READY ? 1 : 0;
1297 rand_drbg_unlock(drbg);
1302 * Get the master DRBG.
1303 * Returns pointer to the DRBG on success, NULL on failure.
1306 RAND_DRBG *OPENSSL_CTX_get0_master_drbg(OPENSSL_CTX *ctx)
1308 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1313 return dgbl->master_drbg;
1316 RAND_DRBG *RAND_DRBG_get0_master(void)
1318 return OPENSSL_CTX_get0_master_drbg(NULL);
1322 * Get the public DRBG.
1323 * Returns pointer to the DRBG on success, NULL on failure.
1325 RAND_DRBG *OPENSSL_CTX_get0_public_drbg(OPENSSL_CTX *ctx)
1327 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1333 drbg = CRYPTO_THREAD_get_local(&dgbl->public_drbg);
1335 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1337 drbg = drbg_setup(ctx, dgbl->master_drbg, RAND_DRBG_TYPE_PUBLIC);
1338 CRYPTO_THREAD_set_local(&dgbl->public_drbg, drbg);
1343 RAND_DRBG *RAND_DRBG_get0_public(void)
1345 return OPENSSL_CTX_get0_public_drbg(NULL);
1349 * Get the private DRBG.
1350 * Returns pointer to the DRBG on success, NULL on failure.
1352 RAND_DRBG *OPENSSL_CTX_get0_private_drbg(OPENSSL_CTX *ctx)
1354 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1360 drbg = CRYPTO_THREAD_get_local(&dgbl->private_drbg);
1362 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1364 drbg = drbg_setup(ctx, dgbl->master_drbg, RAND_DRBG_TYPE_PRIVATE);
1365 CRYPTO_THREAD_set_local(&dgbl->private_drbg, drbg);
1370 RAND_DRBG *RAND_DRBG_get0_private(void)
1372 return OPENSSL_CTX_get0_private_drbg(NULL);
1375 RAND_METHOD rand_meth = {
1384 RAND_METHOD *RAND_OpenSSL(void)