2 * Copyright 2011-2020 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>
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"
21 * Support framework for NIST SP 800-90A DRBG
23 * See manual page RAND_DRBG(7) for a general overview.
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.)
34 typedef struct drbg_global_st {
36 * The three shared DRBG instances
38 * There are three shared DRBG instances: <master>, <public>, and <private>.
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().
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.
52 RAND_DRBG *master_drbg;
56 * Used by default for generating random bytes using RAND_bytes().
58 * The <public> DRBG is thread-local, i.e., there is one instance per
61 CRYPTO_THREAD_LOCAL public_drbg;
65 * Used by default for generating private keys using RAND_priv_bytes()
67 * The <private> DRBG is thread-local, i.e., there is one instance per
70 CRYPTO_THREAD_LOCAL private_drbg;
73 typedef struct drbg_nonce_global_st {
74 CRYPTO_RWLOCK *rand_nonce_lock;
78 /* NIST SP 800-90A DRBG recommends the use of a personalization string. */
79 static const char ossl_pers_string[] = DRBG_DEFAULT_PERS_STRING;
81 #define RAND_DRBG_TYPE_FLAGS ( \
82 RAND_DRBG_FLAG_MASTER | RAND_DRBG_FLAG_PUBLIC | RAND_DRBG_FLAG_PRIVATE )
84 #define RAND_DRBG_TYPE_MASTER 0
85 #define RAND_DRBG_TYPE_PUBLIC 1
86 #define RAND_DRBG_TYPE_PRIVATE 2
89 static int rand_drbg_type[3] = {
90 RAND_DRBG_TYPE, /* Master */
91 RAND_DRBG_TYPE, /* Public */
92 RAND_DRBG_TYPE /* Private */
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 */
100 static unsigned int master_reseed_interval = MASTER_RESEED_INTERVAL;
101 static unsigned int slave_reseed_interval = SLAVE_RESEED_INTERVAL;
103 static time_t master_reseed_time_interval = MASTER_RESEED_TIME_INTERVAL;
104 static time_t slave_reseed_time_interval = SLAVE_RESEED_TIME_INTERVAL;
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;
111 static RAND_DRBG *drbg_setup(OPENSSL_CTX *ctx, RAND_DRBG *parent, int drbg_type);
113 static RAND_DRBG *rand_drbg_new(OPENSSL_CTX *ctx,
119 static int rand_drbg_set(RAND_DRBG *drbg, int type, unsigned int flags);
120 static int rand_drbg_init_method(RAND_DRBG *drbg);
122 static int is_ctr(int type)
125 case NID_aes_128_ctr:
126 case NID_aes_192_ctr:
127 case NID_aes_256_ctr:
134 static int is_digest(int type)
155 * Initialize the OPENSSL_CTX global DRBGs on first use.
156 * Returns the allocated global data on success or NULL on failure.
158 static void *drbg_ossl_ctx_new(OPENSSL_CTX *libctx)
160 DRBG_GLOBAL *dgbl = OPENSSL_zalloc(sizeof(*dgbl));
167 * We need to ensure that base libcrypto thread handling has been
170 OPENSSL_init_crypto(0, NULL);
173 if (!CRYPTO_THREAD_init_local(&dgbl->private_drbg, NULL))
176 if (!CRYPTO_THREAD_init_local(&dgbl->public_drbg, NULL))
179 dgbl->master_drbg = drbg_setup(libctx, NULL, RAND_DRBG_TYPE_MASTER);
180 if (dgbl->master_drbg == NULL)
186 CRYPTO_THREAD_cleanup_local(&dgbl->public_drbg);
188 CRYPTO_THREAD_cleanup_local(&dgbl->private_drbg);
194 static void drbg_ossl_ctx_free(void *vdgbl)
196 DRBG_GLOBAL *dgbl = vdgbl;
201 RAND_DRBG_free(dgbl->master_drbg);
202 CRYPTO_THREAD_cleanup_local(&dgbl->private_drbg);
203 CRYPTO_THREAD_cleanup_local(&dgbl->public_drbg);
208 static const OPENSSL_CTX_METHOD drbg_ossl_ctx_method = {
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.
220 static void *drbg_nonce_ossl_ctx_new(OPENSSL_CTX *libctx)
222 DRBG_NONCE_GLOBAL *dngbl = OPENSSL_zalloc(sizeof(*dngbl));
227 dngbl->rand_nonce_lock = CRYPTO_THREAD_lock_new();
228 if (dngbl->rand_nonce_lock == NULL) {
236 static void drbg_nonce_ossl_ctx_free(void *vdngbl)
238 DRBG_NONCE_GLOBAL *dngbl = vdngbl;
243 CRYPTO_THREAD_lock_free(dngbl->rand_nonce_lock);
248 static const OPENSSL_CTX_METHOD drbg_nonce_ossl_ctx_method = {
249 drbg_nonce_ossl_ctx_new,
250 drbg_nonce_ossl_ctx_free,
253 static DRBG_GLOBAL *drbg_get_global(OPENSSL_CTX *libctx)
255 return openssl_ctx_get_data(libctx, OPENSSL_CTX_DRBG_INDEX,
256 &drbg_ossl_ctx_method);
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)
266 DRBG_NONCE_GLOBAL *dngbl
267 = openssl_ctx_get_data(drbg->libctx, OPENSSL_CTX_DRBG_NONCE_INDEX,
268 &drbg_nonce_ossl_ctx_method);
277 memset(&data, 0, sizeof(data));
278 pool = rand_pool_new(0, 0, min_len, max_len);
282 if (rand_pool_add_nonce_data(pool) == 0)
285 data.instance = drbg;
286 CRYPTO_atomic_add(&dngbl->rand_nonce_count, 1, &data.count,
287 dngbl->rand_nonce_lock);
289 if (rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0) == 0)
292 ret = rand_pool_length(pool);
293 *pout = rand_pool_detach(pool);
296 rand_pool_free(pool);
302 * Implements the cleanup_nonce() callback (see RAND_DRBG_set_callbacks())
305 void rand_drbg_cleanup_nonce(RAND_DRBG *drbg,
306 unsigned char *out, size_t outlen)
308 OPENSSL_clear_free(out, outlen);
312 * Set the |drbg|'s callback data pointer for the entropy and nonce callbacks
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.
318 * Setting the callback data is allowed only if the drbg has not been
319 * initialized yet. Otherwise, the operation will fail.
321 * Returns 1 on success, 0 on failure.
323 int RAND_DRBG_set_callback_data(RAND_DRBG *drbg, void *data)
325 if (drbg->state != DRBG_UNINITIALISED
326 || drbg->parent != NULL)
329 drbg->callback_data = data;
333 /* Retrieve the callback data pointer */
334 void *RAND_DRBG_get_callback_data(RAND_DRBG *drbg)
336 return drbg->callback_data;
340 * Set/initialize |drbg| to be of type |type|, with optional |flags|.
342 * If |type| and |flags| are zero, use the defaults
344 * Returns 1 on success, 0 on failure.
346 int RAND_DRBG_set(RAND_DRBG *drbg, int type, unsigned int flags)
348 return rand_drbg_set(drbg, type, flags) && rand_drbg_init_method(drbg);
351 static int rand_drbg_set(RAND_DRBG *drbg, int type, unsigned int flags)
353 if (type == 0 && flags == 0) {
354 type = rand_drbg_type[RAND_DRBG_TYPE_MASTER];
355 flags = rand_drbg_flags[RAND_DRBG_TYPE_MASTER];
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;
366 drbg->state = DRBG_UNINITIALISED;
371 if (type == 0 || is_ctr(type) || is_digest(type))
376 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
381 static int rand_drbg_init_method(RAND_DRBG *drbg)
385 if (drbg->meth != NULL)
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);
394 ret = drbg_hash_init(drbg);
396 /* other cases should already be excluded */
397 RANDerr(RAND_F_RAND_DRBG_INIT_METHOD, ERR_R_INTERNAL_ERROR);
404 drbg->state = DRBG_ERROR;
405 RANDerr(RAND_F_RAND_DRBG_INIT_METHOD, RAND_R_ERROR_INITIALISING_DRBG);
411 * Set/initialize default |type| and |flag| for new drbg instances.
413 * Returns 1 on success, 0 on failure.
415 int RAND_DRBG_set_defaults(int type, unsigned int flags)
418 if (!(is_digest(type) || is_ctr(type))) {
419 RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_TYPE);
423 if ((flags & ~rand_drbg_used_flags) != 0) {
424 RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_FLAGS);
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;
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;
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;
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.
450 * Returns a pointer to the new DRBG instance on success, NULL on failure.
452 static RAND_DRBG *rand_drbg_new(OPENSSL_CTX *ctx,
458 RAND_DRBG *drbg = secure ? OPENSSL_secure_zalloc(sizeof(*drbg))
459 : OPENSSL_zalloc(sizeof(*drbg));
462 RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
467 drbg->secure = secure && CRYPTO_secure_allocated(drbg);
468 drbg->fork_id = openssl_get_fork_id();
469 drbg->parent = parent;
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;
479 drbg->reseed_interval = master_reseed_interval;
480 drbg->reseed_time_interval = master_reseed_time_interval;
482 drbg->get_entropy = rand_drbg_get_entropy;
483 drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
485 * Do not provide nonce callbacks, the child DRBGs will
486 * obtain their nonce using random bits from the parent.
489 drbg->reseed_interval = slave_reseed_interval;
490 drbg->reseed_time_interval = slave_reseed_time_interval;
493 if (RAND_DRBG_set(drbg, type, flags) == 0)
496 if (parent != NULL) {
497 rand_drbg_lock(parent);
498 if (drbg->strength > parent->strength) {
500 * We currently don't support the algorithm from NIST SP 800-90C
501 * 10.1.2 to use a weaker DRBG as source
503 rand_drbg_unlock(parent);
504 RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK);
507 rand_drbg_unlock(parent);
513 RAND_DRBG_free(drbg);
518 RAND_DRBG *RAND_DRBG_new_ex(OPENSSL_CTX *ctx, int type, unsigned int flags,
521 return rand_drbg_new(ctx, 0, type, flags, parent);
524 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
526 return RAND_DRBG_new_ex(NULL, type, flags, parent);
529 RAND_DRBG *RAND_DRBG_secure_new_ex(OPENSSL_CTX *ctx, int type,
530 unsigned int flags, RAND_DRBG *parent)
532 return rand_drbg_new(ctx, 1, type, flags, parent);
535 RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent)
537 return RAND_DRBG_secure_new_ex(NULL, type, flags, parent);
540 * Uninstantiate |drbg| and free all memory.
542 void RAND_DRBG_free(RAND_DRBG *drbg)
547 if (drbg->meth != NULL)
548 drbg->meth->uninstantiate(drbg);
549 rand_pool_free(drbg->adin_pool);
550 CRYPTO_THREAD_lock_free(drbg->lock);
552 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_RAND_DRBG, drbg, &drbg->ex_data);
556 OPENSSL_secure_clear_free(drbg, sizeof(*drbg));
558 OPENSSL_clear_free(drbg, sizeof(*drbg));
562 * Instantiate |drbg|, after it has been initialized. Use |pers| and
563 * |perslen| as prediction-resistance input.
565 * Requires that drbg->lock is already locked for write, if non-null.
567 * Returns 1 on success, 0 on failure.
569 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
570 const unsigned char *pers, size_t perslen)
572 unsigned char *nonce = NULL, *entropy = NULL;
573 size_t noncelen = 0, entropylen = 0;
574 size_t min_entropy, min_entropylen, max_entropylen;
576 if (drbg->meth == NULL && !rand_drbg_init_method(drbg)) {
577 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
578 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
582 min_entropy = drbg->strength;
583 min_entropylen = drbg->min_entropylen;
584 max_entropylen = drbg->max_entropylen;
586 if (perslen > drbg->max_perslen) {
587 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
588 RAND_R_PERSONALISATION_STRING_TOO_LONG);
592 if (drbg->state != DRBG_UNINITIALISED) {
593 if (drbg->state == DRBG_ERROR)
594 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_IN_ERROR_STATE);
596 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ALREADY_INSTANTIATED);
600 drbg->state = DRBG_ERROR;
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.
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;
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;
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);
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);
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);
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);
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)
661 * Uninstantiate |drbg|. Must be instantiated before it can be used.
663 * Requires that drbg->lock is already locked for write, if non-null.
665 * Returns 1 on success, 0 on failure.
667 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
669 int index = -1, type, flags;
670 if (drbg->meth != NULL) {
671 drbg->meth->uninstantiate(drbg);
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;
684 flags = rand_drbg_flags[index];
685 type = rand_drbg_type[index];
690 return rand_drbg_set(drbg, type, flags);
694 * Reseed |drbg|, mixing in the specified data
696 * Requires that drbg->lock is already locked for write, if non-null.
698 * Returns 1 on success, 0 on failure.
700 int RAND_DRBG_reseed(RAND_DRBG *drbg,
701 const unsigned char *adin, size_t adinlen,
702 int prediction_resistance)
704 unsigned char *entropy = NULL;
705 size_t entropylen = 0;
707 if (drbg->state == DRBG_ERROR) {
708 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
711 if (drbg->state == DRBG_UNINITIALISED) {
712 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
718 } else if (adinlen > drbg->max_adinlen) {
719 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
723 drbg->state = DRBG_ERROR;
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;
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);
743 if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
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);
752 if (entropy != NULL && drbg->cleanup_entropy != NULL)
753 drbg->cleanup_entropy(drbg, entropy, entropylen);
754 if (drbg->state == DRBG_READY)
760 * Restart |drbg|, using the specified entropy or additional input
762 * Tries its best to get the drbg instantiated by all means,
763 * regardless of its current state.
765 * Optionally, a |buffer| of |len| random bytes can be passed,
766 * which is assumed to contain at least |entropy| bits of entropy.
768 * If |entropy| > 0, the buffer content is used as entropy input.
770 * If |entropy| == 0, the buffer content is used as additional input
772 * Returns 1 on success, 0 on failure.
774 * This function is used internally only.
776 int rand_drbg_restart(RAND_DRBG *drbg,
777 const unsigned char *buffer, size_t len, size_t entropy)
780 const unsigned char *adin = NULL;
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;
791 if (buffer != NULL) {
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;
800 if (entropy > 8 * len) {
801 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
802 drbg->state = DRBG_ERROR;
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)
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;
822 /* repair error state */
823 if (drbg->state == DRBG_ERROR)
824 RAND_DRBG_uninstantiate(drbg);
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);
836 /* refresh current state if entropy or additional input has been provided */
837 if (drbg->state == DRBG_READY) {
840 * mix in additional input without reseeding
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.
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);
854 rand_pool_free(drbg->seed_pool);
855 drbg->seed_pool = NULL;
857 return drbg->state == DRBG_READY;
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|.
865 * Requires that drbg->lock is already locked for write, if non-null.
867 * Returns 1 on success, 0 on failure.
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)
875 int reseed_required = 0;
877 if (drbg->state != DRBG_READY) {
878 /* try to recover from previous errors */
879 rand_drbg_restart(drbg, NULL, 0, 0);
881 if (drbg->state == DRBG_ERROR) {
882 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
885 if (drbg->state == DRBG_UNINITIALISED) {
886 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
891 if (outlen > drbg->max_request) {
892 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
895 if (adinlen > drbg->max_adinlen) {
896 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
900 fork_id = openssl_get_fork_id();
902 if (drbg->fork_id != fork_id) {
903 drbg->fork_id = fork_id;
907 if (drbg->reseed_interval > 0) {
908 if (drbg->reseed_gen_counter > drbg->reseed_interval)
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)
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)
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);
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);
940 drbg->reseed_gen_counter++;
946 * Generates |outlen| random bytes and stores them in |out|. It will
947 * using the given |drbg| to generate the bytes.
949 * Requires that drbg->lock is already locked for write, if non-null.
951 * Returns 1 on success 0 on failure.
953 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
955 unsigned char *additional = NULL;
956 size_t additional_len;
960 if (drbg->adin_pool == NULL) {
963 drbg->adin_pool = rand_pool_new(0, 0, 0, drbg->max_adinlen);
964 if (drbg->adin_pool == NULL)
968 additional_len = rand_drbg_get_additional_data(drbg->adin_pool,
971 for ( ; outlen > 0; outlen -= chunk, out += chunk) {
973 if (chunk > drbg->max_request)
974 chunk = drbg->max_request;
975 ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
982 if (additional != NULL)
983 rand_drbg_cleanup_additional_data(drbg->adin_pool, additional);
989 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
991 * Setting the callbacks is allowed only if the drbg has not been
992 * initialized yet. Otherwise, the operation will fail.
994 * Returns 1 on success, 0 on failure.
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)
1002 if (drbg->state != DRBG_UNINITIALISED
1003 || drbg->parent != NULL)
1005 drbg->get_entropy = get_entropy;
1006 drbg->cleanup_entropy = cleanup_entropy;
1007 drbg->get_nonce = get_nonce;
1008 drbg->cleanup_nonce = cleanup_nonce;
1013 * Set the reseed interval.
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.
1019 * Returns 1 on success, 0 on failure.
1021 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
1023 if (interval > MAX_RESEED_INTERVAL)
1025 drbg->reseed_interval = interval;
1030 * Set the reseed time interval.
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
1037 * Returns 1 on success, 0 on failure.
1039 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
1041 if (interval > MAX_RESEED_TIME_INTERVAL)
1043 drbg->reseed_time_interval = interval;
1048 * Set the default values for reseed (time) intervals of new DRBG instances
1050 * The default values can be set independently for master DRBG instances
1051 * (without a parent) and slave DRBG instances (with parent).
1053 * Returns 1 on success, 0 on failure.
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
1063 if (_master_reseed_interval > MAX_RESEED_INTERVAL
1064 || _slave_reseed_interval > MAX_RESEED_INTERVAL)
1067 if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
1068 || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
1071 master_reseed_interval = _master_reseed_interval;
1072 slave_reseed_interval = _slave_reseed_interval;
1074 master_reseed_time_interval = _master_reseed_time_interval;
1075 slave_reseed_time_interval = _slave_reseed_time_interval;
1081 * Locks the given drbg. Locking a drbg which does not have locking
1082 * enabled is considered a successful no-op.
1084 * Returns 1 on success, 0 on failure.
1086 int rand_drbg_lock(RAND_DRBG *drbg)
1088 if (drbg->lock != NULL)
1089 return CRYPTO_THREAD_write_lock(drbg->lock);
1095 * Unlocks the given drbg. Unlocking a drbg which does not have locking
1096 * enabled is considered a successful no-op.
1098 * Returns 1 on success, 0 on failure.
1100 int rand_drbg_unlock(RAND_DRBG *drbg)
1102 if (drbg->lock != NULL)
1103 return CRYPTO_THREAD_unlock(drbg->lock);
1109 * Enables locking for the given drbg
1111 * Locking can only be enabled if the random generator
1112 * is in the uninitialized state.
1114 * Returns 1 on success, 0 on failure.
1116 int rand_drbg_enable_locking(RAND_DRBG *drbg)
1118 if (drbg->state != DRBG_UNINITIALISED) {
1119 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
1120 RAND_R_DRBG_ALREADY_INITIALIZED);
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);
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);
1144 * Get and set the EXDATA
1146 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
1148 return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
1151 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
1153 return CRYPTO_get_ex_data(&drbg->ex_data, idx);
1158 * The following functions provide a RAND_METHOD that works on the
1159 * global DRBG. They lock.
1163 * Allocates a new global DRBG on the secure heap (if enabled) and
1164 * initializes it with default settings.
1166 * Returns a pointer to the new DRBG instance on success, NULL on failure.
1168 static RAND_DRBG *drbg_setup(OPENSSL_CTX *ctx, RAND_DRBG *parent, int drbg_type)
1172 drbg = RAND_DRBG_secure_new_ex(ctx, rand_drbg_type[drbg_type],
1173 rand_drbg_flags[drbg_type], parent);
1177 /* Only the master DRBG needs to have a lock */
1178 if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
1181 /* enable seed propagation */
1182 tsan_store(&drbg->reseed_prop_counter, 1);
1185 * Ignore instantiation error to support just-in-time instantiation.
1187 * The state of the drbg will be checked in RAND_DRBG_generate() and
1188 * an automatic recovery is attempted.
1190 (void)RAND_DRBG_instantiate(drbg,
1191 (const unsigned char *) ossl_pers_string,
1192 sizeof(ossl_pers_string) - 1);
1196 RAND_DRBG_free(drbg);
1200 static void drbg_delete_thread_state(void *arg)
1202 OPENSSL_CTX *ctx = arg;
1203 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1208 drbg = CRYPTO_THREAD_get_local(&dgbl->public_drbg);
1209 CRYPTO_THREAD_set_local(&dgbl->public_drbg, NULL);
1210 RAND_DRBG_free(drbg);
1212 drbg = CRYPTO_THREAD_get_local(&dgbl->private_drbg);
1213 CRYPTO_THREAD_set_local(&dgbl->private_drbg, NULL);
1214 RAND_DRBG_free(drbg);
1217 /* Implements the default OpenSSL RAND_bytes() method */
1218 static int drbg_bytes(unsigned char *out, int count)
1221 RAND_DRBG *drbg = RAND_DRBG_get0_public();
1226 ret = RAND_DRBG_bytes(drbg, out, count);
1232 * Calculates the minimum length of a full entropy buffer
1233 * which is necessary to seed (i.e. instantiate) the DRBG
1236 size_t rand_drbg_seedlen(RAND_DRBG *drbg)
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().
1244 size_t min_entropy = drbg->strength;
1245 size_t min_entropylen = drbg->min_entropylen;
1248 * Extra entropy for the random nonce in the absence of a
1249 * get_nonce callback, see comment in RAND_DRBG_instantiate().
1251 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
1252 min_entropy += drbg->strength / 2;
1253 min_entropylen += drbg->min_noncelen;
1257 * Convert entropy requirement from bits to bytes
1258 * (dividing by 8 without rounding upwards, because
1259 * all entropy requirements are divisible by 8).
1263 /* Return a value that satisfies both requirements */
1264 return min_entropy > min_entropylen ? min_entropy : min_entropylen;
1267 /* Implements the default OpenSSL RAND_add() method */
1268 static int drbg_add(const void *buf, int num, double randomness)
1271 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1278 if (num < 0 || randomness < 0.0)
1281 rand_drbg_lock(drbg);
1282 seedlen = rand_drbg_seedlen(drbg);
1284 buflen = (size_t)num;
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.
1293 * (NIST SP-800-90Ar1, Sections 9.1 and 9.2)
1297 if (buflen < seedlen || randomness < (double) seedlen) {
1298 #if defined(OPENSSL_RAND_SEED_NONE)
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.
1306 unsigned char dummy[1];
1308 ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
1309 rand_drbg_unlock(drbg);
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
1321 if (randomness > (double)seedlen) {
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.
1330 randomness = (double)seedlen;
1333 ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
1334 rand_drbg_unlock(drbg);
1339 /* Implements the default OpenSSL RAND_seed() method */
1340 static int drbg_seed(const void *buf, int num)
1342 return drbg_add(buf, num, num);
1345 /* Implements the default OpenSSL RAND_status() method */
1346 static int drbg_status(void)
1349 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1354 rand_drbg_lock(drbg);
1355 ret = drbg->state == DRBG_READY ? 1 : 0;
1356 rand_drbg_unlock(drbg);
1361 * Get the master DRBG.
1362 * Returns pointer to the DRBG on success, NULL on failure.
1365 RAND_DRBG *OPENSSL_CTX_get0_master_drbg(OPENSSL_CTX *ctx)
1367 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1372 return dgbl->master_drbg;
1375 RAND_DRBG *RAND_DRBG_get0_master(void)
1377 return OPENSSL_CTX_get0_master_drbg(NULL);
1381 * Get the public DRBG.
1382 * Returns pointer to the DRBG on success, NULL on failure.
1384 RAND_DRBG *OPENSSL_CTX_get0_public_drbg(OPENSSL_CTX *ctx)
1386 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1392 drbg = CRYPTO_THREAD_get_local(&dgbl->public_drbg);
1394 ctx = openssl_ctx_get_concrete(ctx);
1396 * If the private_drbg is also NULL then this is the first time we've
1399 if (CRYPTO_THREAD_get_local(&dgbl->private_drbg) == NULL
1400 && !ossl_init_thread_start(NULL, ctx, drbg_delete_thread_state))
1402 drbg = drbg_setup(ctx, dgbl->master_drbg, RAND_DRBG_TYPE_PUBLIC);
1403 CRYPTO_THREAD_set_local(&dgbl->public_drbg, drbg);
1408 RAND_DRBG *RAND_DRBG_get0_public(void)
1410 return OPENSSL_CTX_get0_public_drbg(NULL);
1414 * Get the private DRBG.
1415 * Returns pointer to the DRBG on success, NULL on failure.
1417 RAND_DRBG *OPENSSL_CTX_get0_private_drbg(OPENSSL_CTX *ctx)
1419 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1425 drbg = CRYPTO_THREAD_get_local(&dgbl->private_drbg);
1427 ctx = openssl_ctx_get_concrete(ctx);
1429 * If the public_drbg is also NULL then this is the first time we've
1432 if (CRYPTO_THREAD_get_local(&dgbl->public_drbg) == NULL
1433 && !ossl_init_thread_start(NULL, ctx, drbg_delete_thread_state))
1435 drbg = drbg_setup(ctx, dgbl->master_drbg, RAND_DRBG_TYPE_PRIVATE);
1436 CRYPTO_THREAD_set_local(&dgbl->private_drbg, drbg);
1441 RAND_DRBG *RAND_DRBG_get0_private(void)
1443 return OPENSSL_CTX_get0_private_drbg(NULL);
1446 RAND_METHOD rand_meth = {
1455 RAND_METHOD *RAND_OpenSSL(void)