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/cryptlib.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 rand_drbg_set(RAND_DRBG *drbg, int type, unsigned int flags);
119 static int rand_drbg_init_method(RAND_DRBG *drbg);
121 static int is_ctr(int type)
124 case NID_aes_128_ctr:
125 case NID_aes_192_ctr:
126 case NID_aes_256_ctr:
133 static int is_digest(int type)
154 * Initialize the OPENSSL_CTX global DRBGs on first use.
155 * Returns the allocated global data on success or NULL on failure.
157 static void *drbg_ossl_ctx_new(OPENSSL_CTX *libctx)
159 DRBG_GLOBAL *dgbl = OPENSSL_zalloc(sizeof(*dgbl));
166 * We need to ensure that base libcrypto thread handling has been
169 OPENSSL_init_crypto(0, NULL);
172 if (!CRYPTO_THREAD_init_local(&dgbl->private_drbg, NULL))
175 if (!CRYPTO_THREAD_init_local(&dgbl->public_drbg, NULL))
178 dgbl->master_drbg = drbg_setup(libctx, NULL, RAND_DRBG_TYPE_MASTER);
179 if (dgbl->master_drbg == NULL)
185 CRYPTO_THREAD_cleanup_local(&dgbl->public_drbg);
187 CRYPTO_THREAD_cleanup_local(&dgbl->private_drbg);
193 static void drbg_ossl_ctx_free(void *vdgbl)
195 DRBG_GLOBAL *dgbl = vdgbl;
200 RAND_DRBG_free(dgbl->master_drbg);
201 CRYPTO_THREAD_cleanup_local(&dgbl->private_drbg);
202 CRYPTO_THREAD_cleanup_local(&dgbl->public_drbg);
207 static const OPENSSL_CTX_METHOD drbg_ossl_ctx_method = {
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.
219 static void *drbg_nonce_ossl_ctx_new(OPENSSL_CTX *libctx)
221 DRBG_NONCE_GLOBAL *dngbl = OPENSSL_zalloc(sizeof(*dngbl));
226 dngbl->rand_nonce_lock = CRYPTO_THREAD_lock_new();
227 if (dngbl->rand_nonce_lock == NULL) {
235 static void drbg_nonce_ossl_ctx_free(void *vdngbl)
237 DRBG_NONCE_GLOBAL *dngbl = vdngbl;
242 CRYPTO_THREAD_lock_free(dngbl->rand_nonce_lock);
247 static const OPENSSL_CTX_METHOD drbg_nonce_ossl_ctx_method = {
248 drbg_nonce_ossl_ctx_new,
249 drbg_nonce_ossl_ctx_free,
252 static DRBG_GLOBAL *drbg_get_global(OPENSSL_CTX *libctx)
254 return openssl_ctx_get_data(libctx, OPENSSL_CTX_DRBG_INDEX,
255 &drbg_ossl_ctx_method);
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)
265 DRBG_NONCE_GLOBAL *dngbl
266 = openssl_ctx_get_data(drbg->libctx, OPENSSL_CTX_DRBG_NONCE_INDEX,
267 &drbg_nonce_ossl_ctx_method);
276 memset(&data, 0, sizeof(data));
277 pool = rand_pool_new(0, 0, min_len, max_len);
281 if (rand_pool_add_nonce_data(pool) == 0)
284 data.instance = drbg;
285 CRYPTO_atomic_add(&dngbl->rand_nonce_count, 1, &data.count,
286 dngbl->rand_nonce_lock);
288 if (rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0) == 0)
291 ret = rand_pool_length(pool);
292 *pout = rand_pool_detach(pool);
295 rand_pool_free(pool);
301 * Implements the cleanup_nonce() callback (see RAND_DRBG_set_callbacks())
304 void rand_drbg_cleanup_nonce(RAND_DRBG *drbg,
305 unsigned char *out, size_t outlen)
307 OPENSSL_clear_free(out, outlen);
311 * Set the |drbg|'s callback data pointer for the entropy and nonce callbacks
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.
317 * Setting the callback data is allowed only if the drbg has not been
318 * initialized yet. Otherwise, the operation will fail.
320 * Returns 1 on success, 0 on failure.
322 int RAND_DRBG_set_callback_data(RAND_DRBG *drbg, void *data)
324 if (drbg->state != DRBG_UNINITIALISED
325 || drbg->parent != NULL)
328 drbg->callback_data = data;
332 /* Retrieve the callback data pointer */
333 void *RAND_DRBG_get_callback_data(RAND_DRBG *drbg)
335 return drbg->callback_data;
339 * Set/initialize |drbg| to be of type |type|, with optional |flags|.
341 * If |type| and |flags| are zero, use the defaults
343 * Returns 1 on success, 0 on failure.
345 int RAND_DRBG_set(RAND_DRBG *drbg, int type, unsigned int flags)
347 return rand_drbg_set(drbg, type, flags) && rand_drbg_init_method(drbg);
350 static int rand_drbg_set(RAND_DRBG *drbg, int type, unsigned int flags)
352 if (type == 0 && flags == 0) {
353 type = rand_drbg_type[RAND_DRBG_TYPE_MASTER];
354 flags = rand_drbg_flags[RAND_DRBG_TYPE_MASTER];
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;
365 drbg->state = DRBG_UNINITIALISED;
370 if (type == 0 || is_ctr(type) || is_digest(type))
375 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
380 static int rand_drbg_init_method(RAND_DRBG *drbg)
384 if (drbg->meth != NULL)
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);
393 ret = drbg_hash_init(drbg);
395 /* other cases should already be excluded */
396 RANDerr(RAND_F_RAND_DRBG_INIT_METHOD, ERR_R_INTERNAL_ERROR);
403 drbg->state = DRBG_ERROR;
404 RANDerr(RAND_F_RAND_DRBG_INIT_METHOD, RAND_R_ERROR_INITIALISING_DRBG);
410 * Set/initialize default |type| and |flag| for new drbg instances.
412 * Returns 1 on success, 0 on failure.
414 int RAND_DRBG_set_defaults(int type, unsigned int flags)
417 if (!(is_digest(type) || is_ctr(type))) {
418 RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_TYPE);
422 if ((flags & ~rand_drbg_used_flags) != 0) {
423 RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_FLAGS);
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;
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;
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;
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.
449 * Returns a pointer to the new DRBG instance on success, NULL on failure.
451 static RAND_DRBG *rand_drbg_new(OPENSSL_CTX *ctx,
457 RAND_DRBG *drbg = secure ? OPENSSL_secure_zalloc(sizeof(*drbg))
458 : OPENSSL_zalloc(sizeof(*drbg));
461 RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
466 drbg->secure = secure && CRYPTO_secure_allocated(drbg);
467 drbg->fork_id = openssl_get_fork_id();
468 drbg->parent = parent;
470 if (parent == NULL) {
472 drbg->get_entropy = rand_crngt_get_entropy;
473 drbg->cleanup_entropy = rand_crngt_cleanup_entropy;
475 drbg->get_entropy = rand_drbg_get_entropy;
476 drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
478 #ifndef RAND_DRBG_GET_RANDOM_NONCE
479 drbg->get_nonce = rand_drbg_get_nonce;
480 drbg->cleanup_nonce = rand_drbg_cleanup_nonce;
483 drbg->reseed_interval = master_reseed_interval;
484 drbg->reseed_time_interval = master_reseed_time_interval;
486 drbg->get_entropy = rand_drbg_get_entropy;
487 drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
489 * Do not provide nonce callbacks, the child DRBGs will
490 * obtain their nonce using random bits from the parent.
493 drbg->reseed_interval = slave_reseed_interval;
494 drbg->reseed_time_interval = slave_reseed_time_interval;
497 if (RAND_DRBG_set(drbg, type, flags) == 0)
500 if (parent != NULL) {
501 rand_drbg_lock(parent);
502 if (drbg->strength > parent->strength) {
504 * We currently don't support the algorithm from NIST SP 800-90C
505 * 10.1.2 to use a weaker DRBG as source
507 rand_drbg_unlock(parent);
508 RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK);
511 rand_drbg_unlock(parent);
517 RAND_DRBG_free(drbg);
522 RAND_DRBG *RAND_DRBG_new_ex(OPENSSL_CTX *ctx, int type, unsigned int flags,
525 return rand_drbg_new(ctx, 0, type, flags, parent);
528 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
530 return RAND_DRBG_new_ex(NULL, type, flags, parent);
533 RAND_DRBG *RAND_DRBG_secure_new_ex(OPENSSL_CTX *ctx, int type,
534 unsigned int flags, RAND_DRBG *parent)
536 return rand_drbg_new(ctx, 1, type, flags, parent);
539 RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent)
541 return RAND_DRBG_secure_new_ex(NULL, type, flags, parent);
544 * Uninstantiate |drbg| and free all memory.
546 void RAND_DRBG_free(RAND_DRBG *drbg)
551 if (drbg->meth != NULL)
552 drbg->meth->uninstantiate(drbg);
553 rand_pool_free(drbg->adin_pool);
554 CRYPTO_THREAD_lock_free(drbg->lock);
556 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_RAND_DRBG, drbg, &drbg->ex_data);
560 OPENSSL_secure_clear_free(drbg, sizeof(*drbg));
562 OPENSSL_clear_free(drbg, sizeof(*drbg));
566 * Instantiate |drbg|, after it has been initialized. Use |pers| and
567 * |perslen| as prediction-resistance input.
569 * Requires that drbg->lock is already locked for write, if non-null.
571 * Returns 1 on success, 0 on failure.
573 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
574 const unsigned char *pers, size_t perslen)
576 unsigned char *nonce = NULL, *entropy = NULL;
577 size_t noncelen = 0, entropylen = 0;
578 size_t min_entropy, min_entropylen, max_entropylen;
580 if (drbg->meth == NULL && !rand_drbg_init_method(drbg)) {
581 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
582 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
586 min_entropy = drbg->strength;
587 min_entropylen = drbg->min_entropylen;
588 max_entropylen = drbg->max_entropylen;
590 if (perslen > drbg->max_perslen) {
591 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
592 RAND_R_PERSONALISATION_STRING_TOO_LONG);
596 if (drbg->state != DRBG_UNINITIALISED) {
597 if (drbg->state == DRBG_ERROR)
598 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_IN_ERROR_STATE);
600 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ALREADY_INSTANTIATED);
604 drbg->state = DRBG_ERROR;
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.
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;
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;
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);
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);
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);
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);
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)
665 * Uninstantiate |drbg|. Must be instantiated before it can be used.
667 * Requires that drbg->lock is already locked for write, if non-null.
669 * Returns 1 on success, 0 on failure.
671 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
673 int index = -1, type, flags;
674 if (drbg->meth != NULL) {
675 drbg->meth->uninstantiate(drbg);
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;
688 flags = rand_drbg_flags[index];
689 type = rand_drbg_type[index];
694 return rand_drbg_set(drbg, type, flags);
698 * Reseed |drbg|, mixing in the specified data
700 * Requires that drbg->lock is already locked for write, if non-null.
702 * Returns 1 on success, 0 on failure.
704 int RAND_DRBG_reseed(RAND_DRBG *drbg,
705 const unsigned char *adin, size_t adinlen,
706 int prediction_resistance)
708 unsigned char *entropy = NULL;
709 size_t entropylen = 0;
711 if (drbg->state == DRBG_ERROR) {
712 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
715 if (drbg->state == DRBG_UNINITIALISED) {
716 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
722 } else if (adinlen > drbg->max_adinlen) {
723 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
727 drbg->state = DRBG_ERROR;
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;
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);
747 if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
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);
756 if (entropy != NULL && drbg->cleanup_entropy != NULL)
757 drbg->cleanup_entropy(drbg, entropy, entropylen);
758 if (drbg->state == DRBG_READY)
764 * Restart |drbg|, using the specified entropy or additional input
766 * Tries its best to get the drbg instantiated by all means,
767 * regardless of its current state.
769 * Optionally, a |buffer| of |len| random bytes can be passed,
770 * which is assumed to contain at least |entropy| bits of entropy.
772 * If |entropy| > 0, the buffer content is used as entropy input.
774 * If |entropy| == 0, the buffer content is used as additional input
776 * Returns 1 on success, 0 on failure.
778 * This function is used internally only.
780 int rand_drbg_restart(RAND_DRBG *drbg,
781 const unsigned char *buffer, size_t len, size_t entropy)
784 const unsigned char *adin = NULL;
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;
795 if (buffer != NULL) {
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;
804 if (entropy > 8 * len) {
805 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
806 drbg->state = DRBG_ERROR;
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)
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;
826 /* repair error state */
827 if (drbg->state == DRBG_ERROR)
828 RAND_DRBG_uninstantiate(drbg);
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);
840 /* refresh current state if entropy or additional input has been provided */
841 if (drbg->state == DRBG_READY) {
844 * mix in additional input without reseeding
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.
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);
858 rand_pool_free(drbg->seed_pool);
859 drbg->seed_pool = NULL;
861 return drbg->state == DRBG_READY;
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|.
869 * Requires that drbg->lock is already locked for write, if non-null.
871 * Returns 1 on success, 0 on failure.
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)
879 int reseed_required = 0;
881 if (drbg->state != DRBG_READY) {
882 /* try to recover from previous errors */
883 rand_drbg_restart(drbg, NULL, 0, 0);
885 if (drbg->state == DRBG_ERROR) {
886 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
889 if (drbg->state == DRBG_UNINITIALISED) {
890 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
895 if (outlen > drbg->max_request) {
896 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
899 if (adinlen > drbg->max_adinlen) {
900 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
904 fork_id = openssl_get_fork_id();
906 if (drbg->fork_id != fork_id) {
907 drbg->fork_id = fork_id;
911 if (drbg->reseed_interval > 0) {
912 if (drbg->reseed_gen_counter > drbg->reseed_interval)
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)
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)
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);
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);
944 drbg->reseed_gen_counter++;
950 * Generates |outlen| random bytes and stores them in |out|. It will
951 * using the given |drbg| to generate the bytes.
953 * Requires that drbg->lock is already locked for write, if non-null.
955 * Returns 1 on success 0 on failure.
957 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
959 unsigned char *additional = NULL;
960 size_t additional_len;
964 if (drbg->adin_pool == NULL) {
967 drbg->adin_pool = rand_pool_new(0, 0, 0, drbg->max_adinlen);
968 if (drbg->adin_pool == NULL)
972 additional_len = rand_drbg_get_additional_data(drbg->adin_pool,
975 for ( ; outlen > 0; outlen -= chunk, out += chunk) {
977 if (chunk > drbg->max_request)
978 chunk = drbg->max_request;
979 ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
986 if (additional != NULL)
987 rand_drbg_cleanup_additional_data(drbg->adin_pool, additional);
993 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
995 * Setting the callbacks is allowed only if the drbg has not been
996 * initialized yet. Otherwise, the operation will fail.
998 * Returns 1 on success, 0 on failure.
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)
1006 if (drbg->state != DRBG_UNINITIALISED
1007 || drbg->parent != NULL)
1009 drbg->get_entropy = get_entropy;
1010 drbg->cleanup_entropy = cleanup_entropy;
1011 drbg->get_nonce = get_nonce;
1012 drbg->cleanup_nonce = cleanup_nonce;
1017 * Set the reseed interval.
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.
1023 * Returns 1 on success, 0 on failure.
1025 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
1027 if (interval > MAX_RESEED_INTERVAL)
1029 drbg->reseed_interval = interval;
1034 * Set the reseed time interval.
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
1041 * Returns 1 on success, 0 on failure.
1043 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
1045 if (interval > MAX_RESEED_TIME_INTERVAL)
1047 drbg->reseed_time_interval = interval;
1052 * Set the default values for reseed (time) intervals of new DRBG instances
1054 * The default values can be set independently for master DRBG instances
1055 * (without a parent) and slave DRBG instances (with parent).
1057 * Returns 1 on success, 0 on failure.
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
1067 if (_master_reseed_interval > MAX_RESEED_INTERVAL
1068 || _slave_reseed_interval > MAX_RESEED_INTERVAL)
1071 if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
1072 || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
1075 master_reseed_interval = _master_reseed_interval;
1076 slave_reseed_interval = _slave_reseed_interval;
1078 master_reseed_time_interval = _master_reseed_time_interval;
1079 slave_reseed_time_interval = _slave_reseed_time_interval;
1085 * Locks the given drbg. Locking a drbg which does not have locking
1086 * enabled is considered a successful no-op.
1088 * Returns 1 on success, 0 on failure.
1090 int rand_drbg_lock(RAND_DRBG *drbg)
1092 if (drbg->lock != NULL)
1093 return CRYPTO_THREAD_write_lock(drbg->lock);
1099 * Unlocks the given drbg. Unlocking a drbg which does not have locking
1100 * enabled is considered a successful no-op.
1102 * Returns 1 on success, 0 on failure.
1104 int rand_drbg_unlock(RAND_DRBG *drbg)
1106 if (drbg->lock != NULL)
1107 return CRYPTO_THREAD_unlock(drbg->lock);
1113 * Enables locking for the given drbg
1115 * Locking can only be enabled if the random generator
1116 * is in the uninitialized state.
1118 * Returns 1 on success, 0 on failure.
1120 int rand_drbg_enable_locking(RAND_DRBG *drbg)
1122 if (drbg->state != DRBG_UNINITIALISED) {
1123 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
1124 RAND_R_DRBG_ALREADY_INITIALIZED);
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);
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);
1148 * Get and set the EXDATA
1150 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
1152 return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
1155 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
1157 return CRYPTO_get_ex_data(&drbg->ex_data, idx);
1162 * The following functions provide a RAND_METHOD that works on the
1163 * global DRBG. They lock.
1167 * Allocates a new global DRBG on the secure heap (if enabled) and
1168 * initializes it with default settings.
1170 * Returns a pointer to the new DRBG instance on success, NULL on failure.
1172 static RAND_DRBG *drbg_setup(OPENSSL_CTX *ctx, RAND_DRBG *parent, int drbg_type)
1176 drbg = RAND_DRBG_secure_new_ex(ctx, rand_drbg_type[drbg_type],
1177 rand_drbg_flags[drbg_type], parent);
1181 /* Only the master DRBG needs to have a lock */
1182 if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
1185 /* enable seed propagation */
1186 tsan_store(&drbg->reseed_prop_counter, 1);
1189 * Ignore instantiation error to support just-in-time instantiation.
1191 * The state of the drbg will be checked in RAND_DRBG_generate() and
1192 * an automatic recovery is attempted.
1194 (void)RAND_DRBG_instantiate(drbg,
1195 (const unsigned char *) ossl_pers_string,
1196 sizeof(ossl_pers_string) - 1);
1200 RAND_DRBG_free(drbg);
1204 static void drbg_delete_thread_state(void *arg)
1206 OPENSSL_CTX *ctx = arg;
1207 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1212 drbg = CRYPTO_THREAD_get_local(&dgbl->public_drbg);
1213 CRYPTO_THREAD_set_local(&dgbl->public_drbg, NULL);
1214 RAND_DRBG_free(drbg);
1216 drbg = CRYPTO_THREAD_get_local(&dgbl->private_drbg);
1217 CRYPTO_THREAD_set_local(&dgbl->private_drbg, NULL);
1218 RAND_DRBG_free(drbg);
1221 /* Implements the default OpenSSL RAND_bytes() method */
1222 static int drbg_bytes(unsigned char *out, int count)
1225 RAND_DRBG *drbg = RAND_DRBG_get0_public();
1230 ret = RAND_DRBG_bytes(drbg, out, count);
1236 * Calculates the minimum length of a full entropy buffer
1237 * which is necessary to seed (i.e. instantiate) the DRBG
1240 size_t rand_drbg_seedlen(RAND_DRBG *drbg)
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().
1248 size_t min_entropy = drbg->strength;
1249 size_t min_entropylen = drbg->min_entropylen;
1252 * Extra entropy for the random nonce in the absence of a
1253 * get_nonce callback, see comment in RAND_DRBG_instantiate().
1255 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
1256 min_entropy += drbg->strength / 2;
1257 min_entropylen += drbg->min_noncelen;
1261 * Convert entropy requirement from bits to bytes
1262 * (dividing by 8 without rounding upwards, because
1263 * all entropy requirements are divisible by 8).
1267 /* Return a value that satisfies both requirements */
1268 return min_entropy > min_entropylen ? min_entropy : min_entropylen;
1271 /* Implements the default OpenSSL RAND_add() method */
1272 static int drbg_add(const void *buf, int num, double randomness)
1275 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1282 if (num < 0 || randomness < 0.0)
1285 rand_drbg_lock(drbg);
1286 seedlen = rand_drbg_seedlen(drbg);
1288 buflen = (size_t)num;
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.
1297 * (NIST SP-800-90Ar1, Sections 9.1 and 9.2)
1301 if (buflen < seedlen || randomness < (double) seedlen) {
1302 #if defined(OPENSSL_RAND_SEED_NONE)
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.
1310 unsigned char dummy[1];
1312 ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
1313 rand_drbg_unlock(drbg);
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
1325 if (randomness > (double)seedlen) {
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.
1334 randomness = (double)seedlen;
1337 ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
1338 rand_drbg_unlock(drbg);
1343 /* Implements the default OpenSSL RAND_seed() method */
1344 static int drbg_seed(const void *buf, int num)
1346 return drbg_add(buf, num, num);
1349 /* Implements the default OpenSSL RAND_status() method */
1350 static int drbg_status(void)
1353 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1358 rand_drbg_lock(drbg);
1359 ret = drbg->state == DRBG_READY ? 1 : 0;
1360 rand_drbg_unlock(drbg);
1365 * Get the master DRBG.
1366 * Returns pointer to the DRBG on success, NULL on failure.
1369 RAND_DRBG *OPENSSL_CTX_get0_master_drbg(OPENSSL_CTX *ctx)
1371 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1376 return dgbl->master_drbg;
1379 RAND_DRBG *RAND_DRBG_get0_master(void)
1381 return OPENSSL_CTX_get0_master_drbg(NULL);
1385 * Get the public DRBG.
1386 * Returns pointer to the DRBG on success, NULL on failure.
1388 RAND_DRBG *OPENSSL_CTX_get0_public_drbg(OPENSSL_CTX *ctx)
1390 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1396 drbg = CRYPTO_THREAD_get_local(&dgbl->public_drbg);
1398 ctx = openssl_ctx_get_concrete(ctx);
1400 * If the private_drbg is also NULL then this is the first time we've
1403 if (CRYPTO_THREAD_get_local(&dgbl->private_drbg) == NULL
1404 && !ossl_init_thread_start(NULL, ctx, drbg_delete_thread_state))
1406 drbg = drbg_setup(ctx, dgbl->master_drbg, RAND_DRBG_TYPE_PUBLIC);
1407 CRYPTO_THREAD_set_local(&dgbl->public_drbg, drbg);
1412 RAND_DRBG *RAND_DRBG_get0_public(void)
1414 return OPENSSL_CTX_get0_public_drbg(NULL);
1418 * Get the private DRBG.
1419 * Returns pointer to the DRBG on success, NULL on failure.
1421 RAND_DRBG *OPENSSL_CTX_get0_private_drbg(OPENSSL_CTX *ctx)
1423 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1429 drbg = CRYPTO_THREAD_get_local(&dgbl->private_drbg);
1431 ctx = openssl_ctx_get_concrete(ctx);
1433 * If the public_drbg is also NULL then this is the first time we've
1436 if (CRYPTO_THREAD_get_local(&dgbl->public_drbg) == NULL
1437 && !ossl_init_thread_start(NULL, ctx, drbg_delete_thread_state))
1439 drbg = drbg_setup(ctx, dgbl->master_drbg, RAND_DRBG_TYPE_PRIVATE);
1440 CRYPTO_THREAD_set_local(&dgbl->private_drbg, drbg);
1445 RAND_DRBG *RAND_DRBG_get0_private(void)
1447 return OPENSSL_CTX_get0_private_drbg(NULL);
1450 RAND_METHOD rand_meth = {
1459 RAND_METHOD *RAND_OpenSSL(void)