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>
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 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));
163 * We need to ensure that base libcrypto thread handling has been
166 OPENSSL_init_crypto(0, NULL);
169 if (!CRYPTO_THREAD_init_local(&dgbl->private_drbg, NULL))
172 if (!CRYPTO_THREAD_init_local(&dgbl->public_drbg, NULL))
175 dgbl->master_drbg = drbg_setup(libctx, NULL, RAND_DRBG_TYPE_MASTER);
176 if (dgbl->master_drbg == NULL)
182 CRYPTO_THREAD_cleanup_local(&dgbl->public_drbg);
184 CRYPTO_THREAD_cleanup_local(&dgbl->private_drbg);
190 static void drbg_ossl_ctx_free(void *vdgbl)
192 DRBG_GLOBAL *dgbl = vdgbl;
197 RAND_DRBG_free(dgbl->master_drbg);
198 CRYPTO_THREAD_cleanup_local(&dgbl->private_drbg);
199 CRYPTO_THREAD_cleanup_local(&dgbl->public_drbg);
204 static const OPENSSL_CTX_METHOD drbg_ossl_ctx_method = {
210 * drbg_ossl_ctx_new() calls drgb_setup() which calls rand_drbg_get_nonce()
211 * which needs to get the rand_nonce_lock out of the OPENSSL_CTX...but since
212 * drbg_ossl_ctx_new() hasn't finished running yet we need the rand_nonce_lock
213 * to be in a different global data object. Otherwise we will go into an
214 * infinite recursion loop.
216 static void *drbg_nonce_ossl_ctx_new(OPENSSL_CTX *libctx)
218 DRBG_NONCE_GLOBAL *dngbl = OPENSSL_zalloc(sizeof(*dngbl));
223 dngbl->rand_nonce_lock = CRYPTO_THREAD_lock_new();
224 if (dngbl->rand_nonce_lock == NULL) {
232 static void drbg_nonce_ossl_ctx_free(void *vdngbl)
234 DRBG_NONCE_GLOBAL *dngbl = vdngbl;
239 CRYPTO_THREAD_lock_free(dngbl->rand_nonce_lock);
244 static const OPENSSL_CTX_METHOD drbg_nonce_ossl_ctx_method = {
245 drbg_nonce_ossl_ctx_new,
246 drbg_nonce_ossl_ctx_free,
249 static DRBG_GLOBAL *drbg_get_global(OPENSSL_CTX *libctx)
251 return openssl_ctx_get_data(libctx, OPENSSL_CTX_DRBG_INDEX,
252 &drbg_ossl_ctx_method);
255 /* Implements the get_nonce() callback (see RAND_DRBG_set_callbacks()) */
256 size_t rand_drbg_get_nonce(RAND_DRBG *drbg,
257 unsigned char **pout,
258 int entropy, size_t min_len, size_t max_len)
262 DRBG_NONCE_GLOBAL *dngbl
263 = openssl_ctx_get_data(drbg->libctx, OPENSSL_CTX_DRBG_NONCE_INDEX,
264 &drbg_nonce_ossl_ctx_method);
273 memset(&data, 0, sizeof(data));
274 pool = rand_pool_new(0, 0, min_len, max_len);
278 if (rand_pool_add_nonce_data(pool) == 0)
281 data.instance = drbg;
282 CRYPTO_atomic_add(&dngbl->rand_nonce_count, 1, &data.count,
283 dngbl->rand_nonce_lock);
285 if (rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0) == 0)
288 ret = rand_pool_length(pool);
289 *pout = rand_pool_detach(pool);
292 rand_pool_free(pool);
298 * Implements the cleanup_nonce() callback (see RAND_DRBG_set_callbacks())
301 void rand_drbg_cleanup_nonce(RAND_DRBG *drbg,
302 unsigned char *out, size_t outlen)
304 OPENSSL_clear_free(out, outlen);
308 * Set/initialize |drbg| to be of type |type|, with optional |flags|.
310 * If |type| and |flags| are zero, use the defaults
312 * Returns 1 on success, 0 on failure.
314 int RAND_DRBG_set(RAND_DRBG *drbg, int type, unsigned int flags)
318 if (type == 0 && flags == 0) {
319 type = rand_drbg_type[RAND_DRBG_TYPE_MASTER];
320 flags = rand_drbg_flags[RAND_DRBG_TYPE_MASTER];
323 /* If set is called multiple times - clear the old one */
324 if (drbg->type != 0 && (type != drbg->type || flags != drbg->flags)) {
325 drbg->meth->uninstantiate(drbg);
326 rand_pool_free(drbg->adin_pool);
327 drbg->adin_pool = NULL;
330 drbg->state = DRBG_UNINITIALISED;
335 /* Uninitialized; that's okay. */
338 } else if (is_ctr(type)) {
339 ret = drbg_ctr_init(drbg);
340 } else if (is_digest(type)) {
341 if (flags & RAND_DRBG_FLAG_HMAC)
342 ret = drbg_hmac_init(drbg);
344 ret = drbg_hash_init(drbg);
349 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
354 drbg->state = DRBG_ERROR;
355 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG);
361 * Set/initialize default |type| and |flag| for new drbg instances.
363 * Returns 1 on success, 0 on failure.
365 int RAND_DRBG_set_defaults(int type, unsigned int flags)
368 if (!(is_digest(type) || is_ctr(type))) {
369 RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_TYPE);
373 if ((flags & ~rand_drbg_used_flags) != 0) {
374 RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_FLAGS);
378 all = ((flags & RAND_DRBG_TYPE_FLAGS) == 0);
379 if (all || (flags & RAND_DRBG_FLAG_MASTER) != 0) {
380 rand_drbg_type[RAND_DRBG_TYPE_MASTER] = type;
381 rand_drbg_flags[RAND_DRBG_TYPE_MASTER] = flags | RAND_DRBG_FLAG_MASTER;
383 if (all || (flags & RAND_DRBG_FLAG_PUBLIC) != 0) {
384 rand_drbg_type[RAND_DRBG_TYPE_PUBLIC] = type;
385 rand_drbg_flags[RAND_DRBG_TYPE_PUBLIC] = flags | RAND_DRBG_FLAG_PUBLIC;
387 if (all || (flags & RAND_DRBG_FLAG_PRIVATE) != 0) {
388 rand_drbg_type[RAND_DRBG_TYPE_PRIVATE] = type;
389 rand_drbg_flags[RAND_DRBG_TYPE_PRIVATE] = flags | RAND_DRBG_FLAG_PRIVATE;
396 * Allocate memory and initialize a new DRBG. The DRBG is allocated on
397 * the secure heap if |secure| is nonzero and the secure heap is enabled.
398 * The |parent|, if not NULL, will be used as random source for reseeding.
400 * Returns a pointer to the new DRBG instance on success, NULL on failure.
402 static RAND_DRBG *rand_drbg_new(OPENSSL_CTX *ctx,
408 RAND_DRBG *drbg = secure ? OPENSSL_secure_zalloc(sizeof(*drbg))
409 : OPENSSL_zalloc(sizeof(*drbg));
412 RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
417 drbg->secure = secure && CRYPTO_secure_allocated(drbg);
418 drbg->fork_id = openssl_get_fork_id();
419 drbg->parent = parent;
421 if (parent == NULL) {
423 drbg->get_entropy = rand_crngt_get_entropy;
424 drbg->cleanup_entropy = rand_crngt_cleanup_entropy;
426 drbg->get_entropy = rand_drbg_get_entropy;
427 drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
429 #ifndef RAND_DRBG_GET_RANDOM_NONCE
430 drbg->get_nonce = rand_drbg_get_nonce;
431 drbg->cleanup_nonce = rand_drbg_cleanup_nonce;
434 drbg->reseed_interval = master_reseed_interval;
435 drbg->reseed_time_interval = master_reseed_time_interval;
437 drbg->get_entropy = rand_drbg_get_entropy;
438 drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
440 * Do not provide nonce callbacks, the child DRBGs will
441 * obtain their nonce using random bits from the parent.
444 drbg->reseed_interval = slave_reseed_interval;
445 drbg->reseed_time_interval = slave_reseed_time_interval;
448 if (RAND_DRBG_set(drbg, type, flags) == 0)
451 if (parent != NULL) {
452 rand_drbg_lock(parent);
453 if (drbg->strength > parent->strength) {
455 * We currently don't support the algorithm from NIST SP 800-90C
456 * 10.1.2 to use a weaker DRBG as source
458 rand_drbg_unlock(parent);
459 RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK);
462 rand_drbg_unlock(parent);
468 RAND_DRBG_free(drbg);
473 RAND_DRBG *RAND_DRBG_new_ex(OPENSSL_CTX *ctx, int type, unsigned int flags,
476 return rand_drbg_new(ctx, 0, type, flags, parent);
479 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
481 return RAND_DRBG_new_ex(NULL, type, flags, parent);
484 RAND_DRBG *RAND_DRBG_secure_new_ex(OPENSSL_CTX *ctx, int type,
485 unsigned int flags, RAND_DRBG *parent)
487 return rand_drbg_new(ctx, 1, type, flags, parent);
490 RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent)
492 return RAND_DRBG_secure_new_ex(NULL, type, flags, parent);
495 * Uninstantiate |drbg| and free all memory.
497 void RAND_DRBG_free(RAND_DRBG *drbg)
502 if (drbg->meth != NULL)
503 drbg->meth->uninstantiate(drbg);
504 rand_pool_free(drbg->adin_pool);
505 CRYPTO_THREAD_lock_free(drbg->lock);
507 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_RAND_DRBG, drbg, &drbg->ex_data);
511 OPENSSL_secure_clear_free(drbg, sizeof(*drbg));
513 OPENSSL_clear_free(drbg, sizeof(*drbg));
517 * Instantiate |drbg|, after it has been initialized. Use |pers| and
518 * |perslen| as prediction-resistance input.
520 * Requires that drbg->lock is already locked for write, if non-null.
522 * Returns 1 on success, 0 on failure.
524 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
525 const unsigned char *pers, size_t perslen)
527 unsigned char *nonce = NULL, *entropy = NULL;
528 size_t noncelen = 0, entropylen = 0;
529 size_t min_entropy = drbg->strength;
530 size_t min_entropylen = drbg->min_entropylen;
531 size_t max_entropylen = drbg->max_entropylen;
533 if (perslen > drbg->max_perslen) {
534 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
535 RAND_R_PERSONALISATION_STRING_TOO_LONG);
539 if (drbg->meth == NULL) {
540 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
541 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
545 if (drbg->state != DRBG_UNINITIALISED) {
546 if (drbg->state == DRBG_ERROR)
547 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_IN_ERROR_STATE);
549 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ALREADY_INSTANTIATED);
553 drbg->state = DRBG_ERROR;
556 * NIST SP800-90Ar1 section 9.1 says you can combine getting the entropy
557 * and nonce in 1 call by increasing the entropy with 50% and increasing
558 * the minimum length to accommodate the length of the nonce.
559 * We do this in case a nonce is require and get_nonce is NULL.
561 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
562 min_entropy += drbg->strength / 2;
563 min_entropylen += drbg->min_noncelen;
564 max_entropylen += drbg->max_noncelen;
567 drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
568 if (drbg->reseed_next_counter) {
569 drbg->reseed_next_counter++;
570 if(!drbg->reseed_next_counter)
571 drbg->reseed_next_counter = 1;
574 if (drbg->get_entropy != NULL)
575 entropylen = drbg->get_entropy(drbg, &entropy, min_entropy,
576 min_entropylen, max_entropylen, 0);
577 if (entropylen < min_entropylen
578 || entropylen > max_entropylen) {
579 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
583 if (drbg->min_noncelen > 0 && drbg->get_nonce != NULL) {
584 noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
585 drbg->min_noncelen, drbg->max_noncelen);
586 if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
587 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_NONCE);
592 if (!drbg->meth->instantiate(drbg, entropy, entropylen,
593 nonce, noncelen, pers, perslen)) {
594 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
598 drbg->state = DRBG_READY;
599 drbg->reseed_gen_counter = 1;
600 drbg->reseed_time = time(NULL);
601 tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
604 if (entropy != NULL && drbg->cleanup_entropy != NULL)
605 drbg->cleanup_entropy(drbg, entropy, entropylen);
606 if (nonce != NULL && drbg->cleanup_nonce != NULL)
607 drbg->cleanup_nonce(drbg, nonce, noncelen);
608 if (drbg->state == DRBG_READY)
614 * Uninstantiate |drbg|. Must be instantiated before it can be used.
616 * Requires that drbg->lock is already locked for write, if non-null.
618 * Returns 1 on success, 0 on failure.
620 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
622 int index = -1, type, flags;
623 if (drbg->meth == NULL) {
624 drbg->state = DRBG_ERROR;
625 RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
626 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
630 /* Clear the entire drbg->ctr struct, then reset some important
631 * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
634 drbg->meth->uninstantiate(drbg);
636 /* The reset uses the default values for type and flags */
637 if (drbg->flags & RAND_DRBG_FLAG_MASTER)
638 index = RAND_DRBG_TYPE_MASTER;
639 else if (drbg->flags & RAND_DRBG_FLAG_PRIVATE)
640 index = RAND_DRBG_TYPE_PRIVATE;
641 else if (drbg->flags & RAND_DRBG_FLAG_PUBLIC)
642 index = RAND_DRBG_TYPE_PUBLIC;
645 flags = rand_drbg_flags[index];
646 type = rand_drbg_type[index];
651 return RAND_DRBG_set(drbg, type, flags);
655 * Reseed |drbg|, mixing in the specified data
657 * Requires that drbg->lock is already locked for write, if non-null.
659 * Returns 1 on success, 0 on failure.
661 int RAND_DRBG_reseed(RAND_DRBG *drbg,
662 const unsigned char *adin, size_t adinlen,
663 int prediction_resistance)
665 unsigned char *entropy = NULL;
666 size_t entropylen = 0;
668 if (drbg->state == DRBG_ERROR) {
669 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
672 if (drbg->state == DRBG_UNINITIALISED) {
673 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
679 } else if (adinlen > drbg->max_adinlen) {
680 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
684 drbg->state = DRBG_ERROR;
686 drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
687 if (drbg->reseed_next_counter) {
688 drbg->reseed_next_counter++;
689 if(!drbg->reseed_next_counter)
690 drbg->reseed_next_counter = 1;
693 if (drbg->get_entropy != NULL)
694 entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
695 drbg->min_entropylen,
696 drbg->max_entropylen,
697 prediction_resistance);
698 if (entropylen < drbg->min_entropylen
699 || entropylen > drbg->max_entropylen) {
700 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
704 if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
707 drbg->state = DRBG_READY;
708 drbg->reseed_gen_counter = 1;
709 drbg->reseed_time = time(NULL);
710 tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
713 if (entropy != NULL && drbg->cleanup_entropy != NULL)
714 drbg->cleanup_entropy(drbg, entropy, entropylen);
715 if (drbg->state == DRBG_READY)
721 * Restart |drbg|, using the specified entropy or additional input
723 * Tries its best to get the drbg instantiated by all means,
724 * regardless of its current state.
726 * Optionally, a |buffer| of |len| random bytes can be passed,
727 * which is assumed to contain at least |entropy| bits of entropy.
729 * If |entropy| > 0, the buffer content is used as entropy input.
731 * If |entropy| == 0, the buffer content is used as additional input
733 * Returns 1 on success, 0 on failure.
735 * This function is used internally only.
737 int rand_drbg_restart(RAND_DRBG *drbg,
738 const unsigned char *buffer, size_t len, size_t entropy)
741 const unsigned char *adin = NULL;
744 if (drbg->seed_pool != NULL) {
745 RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
746 drbg->state = DRBG_ERROR;
747 rand_pool_free(drbg->seed_pool);
748 drbg->seed_pool = NULL;
752 if (buffer != NULL) {
754 if (drbg->max_entropylen < len) {
755 RANDerr(RAND_F_RAND_DRBG_RESTART,
756 RAND_R_ENTROPY_INPUT_TOO_LONG);
757 drbg->state = DRBG_ERROR;
761 if (entropy > 8 * len) {
762 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
763 drbg->state = DRBG_ERROR;
767 /* will be picked up by the rand_drbg_get_entropy() callback */
768 drbg->seed_pool = rand_pool_attach(buffer, len, entropy);
769 if (drbg->seed_pool == NULL)
772 if (drbg->max_adinlen < len) {
773 RANDerr(RAND_F_RAND_DRBG_RESTART,
774 RAND_R_ADDITIONAL_INPUT_TOO_LONG);
775 drbg->state = DRBG_ERROR;
783 /* repair error state */
784 if (drbg->state == DRBG_ERROR)
785 RAND_DRBG_uninstantiate(drbg);
787 /* repair uninitialized state */
788 if (drbg->state == DRBG_UNINITIALISED) {
789 /* reinstantiate drbg */
790 RAND_DRBG_instantiate(drbg,
791 (const unsigned char *) ossl_pers_string,
792 sizeof(ossl_pers_string) - 1);
793 /* already reseeded. prevent second reseeding below */
794 reseeded = (drbg->state == DRBG_READY);
797 /* refresh current state if entropy or additional input has been provided */
798 if (drbg->state == DRBG_READY) {
801 * mix in additional input without reseeding
803 * Similar to RAND_DRBG_reseed(), but the provided additional
804 * data |adin| is mixed into the current state without pulling
805 * entropy from the trusted entropy source using get_entropy().
806 * This is not a reseeding in the strict sense of NIST SP 800-90A.
808 drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
809 } else if (reseeded == 0) {
810 /* do a full reseeding if it has not been done yet above */
811 RAND_DRBG_reseed(drbg, NULL, 0, 0);
815 rand_pool_free(drbg->seed_pool);
816 drbg->seed_pool = NULL;
818 return drbg->state == DRBG_READY;
822 * Generate |outlen| bytes into the buffer at |out|. Reseed if we need
823 * to or if |prediction_resistance| is set. Additional input can be
824 * sent in |adin| and |adinlen|.
826 * Requires that drbg->lock is already locked for write, if non-null.
828 * Returns 1 on success, 0 on failure.
831 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
832 int prediction_resistance,
833 const unsigned char *adin, size_t adinlen)
836 int reseed_required = 0;
838 if (drbg->state != DRBG_READY) {
839 /* try to recover from previous errors */
840 rand_drbg_restart(drbg, NULL, 0, 0);
842 if (drbg->state == DRBG_ERROR) {
843 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
846 if (drbg->state == DRBG_UNINITIALISED) {
847 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
852 if (outlen > drbg->max_request) {
853 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
856 if (adinlen > drbg->max_adinlen) {
857 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
861 fork_id = openssl_get_fork_id();
863 if (drbg->fork_id != fork_id) {
864 drbg->fork_id = fork_id;
868 if (drbg->reseed_interval > 0) {
869 if (drbg->reseed_gen_counter > drbg->reseed_interval)
872 if (drbg->reseed_time_interval > 0) {
873 time_t now = time(NULL);
874 if (now < drbg->reseed_time
875 || now - drbg->reseed_time >= drbg->reseed_time_interval)
878 if (drbg->parent != NULL) {
879 unsigned int reseed_counter = tsan_load(&drbg->reseed_prop_counter);
880 if (reseed_counter > 0
881 && tsan_load(&drbg->parent->reseed_prop_counter)
886 if (reseed_required || prediction_resistance) {
887 if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
888 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
895 if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
896 drbg->state = DRBG_ERROR;
897 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
901 drbg->reseed_gen_counter++;
907 * Generates |outlen| random bytes and stores them in |out|. It will
908 * using the given |drbg| to generate the bytes.
910 * Requires that drbg->lock is already locked for write, if non-null.
912 * Returns 1 on success 0 on failure.
914 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
916 unsigned char *additional = NULL;
917 size_t additional_len;
921 if (drbg->adin_pool == NULL) {
924 drbg->adin_pool = rand_pool_new(0, 0, 0, drbg->max_adinlen);
925 if (drbg->adin_pool == NULL)
929 additional_len = rand_drbg_get_additional_data(drbg->adin_pool,
932 for ( ; outlen > 0; outlen -= chunk, out += chunk) {
934 if (chunk > drbg->max_request)
935 chunk = drbg->max_request;
936 ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
943 if (additional != NULL)
944 rand_drbg_cleanup_additional_data(drbg->adin_pool, additional);
950 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
952 * Setting the callbacks is allowed only if the drbg has not been
953 * initialized yet. Otherwise, the operation will fail.
955 * Returns 1 on success, 0 on failure.
957 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
958 RAND_DRBG_get_entropy_fn get_entropy,
959 RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
960 RAND_DRBG_get_nonce_fn get_nonce,
961 RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
963 if (drbg->state != DRBG_UNINITIALISED
964 || drbg->parent != NULL)
966 drbg->get_entropy = get_entropy;
967 drbg->cleanup_entropy = cleanup_entropy;
968 drbg->get_nonce = get_nonce;
969 drbg->cleanup_nonce = cleanup_nonce;
974 * Set the reseed interval.
976 * The drbg will reseed automatically whenever the number of generate
977 * requests exceeds the given reseed interval. If the reseed interval
978 * is 0, then this feature is disabled.
980 * Returns 1 on success, 0 on failure.
982 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
984 if (interval > MAX_RESEED_INTERVAL)
986 drbg->reseed_interval = interval;
991 * Set the reseed time interval.
993 * The drbg will reseed automatically whenever the time elapsed since
994 * the last reseeding exceeds the given reseed time interval. For safety,
995 * a reseeding will also occur if the clock has been reset to a smaller
998 * Returns 1 on success, 0 on failure.
1000 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
1002 if (interval > MAX_RESEED_TIME_INTERVAL)
1004 drbg->reseed_time_interval = interval;
1009 * Set the default values for reseed (time) intervals of new DRBG instances
1011 * The default values can be set independently for master DRBG instances
1012 * (without a parent) and slave DRBG instances (with parent).
1014 * Returns 1 on success, 0 on failure.
1017 int RAND_DRBG_set_reseed_defaults(
1018 unsigned int _master_reseed_interval,
1019 unsigned int _slave_reseed_interval,
1020 time_t _master_reseed_time_interval,
1021 time_t _slave_reseed_time_interval
1024 if (_master_reseed_interval > MAX_RESEED_INTERVAL
1025 || _slave_reseed_interval > MAX_RESEED_INTERVAL)
1028 if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
1029 || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
1032 master_reseed_interval = _master_reseed_interval;
1033 slave_reseed_interval = _slave_reseed_interval;
1035 master_reseed_time_interval = _master_reseed_time_interval;
1036 slave_reseed_time_interval = _slave_reseed_time_interval;
1042 * Locks the given drbg. Locking a drbg which does not have locking
1043 * enabled is considered a successful no-op.
1045 * Returns 1 on success, 0 on failure.
1047 int rand_drbg_lock(RAND_DRBG *drbg)
1049 if (drbg->lock != NULL)
1050 return CRYPTO_THREAD_write_lock(drbg->lock);
1056 * Unlocks the given drbg. Unlocking a drbg which does not have locking
1057 * enabled is considered a successful no-op.
1059 * Returns 1 on success, 0 on failure.
1061 int rand_drbg_unlock(RAND_DRBG *drbg)
1063 if (drbg->lock != NULL)
1064 return CRYPTO_THREAD_unlock(drbg->lock);
1070 * Enables locking for the given drbg
1072 * Locking can only be enabled if the random generator
1073 * is in the uninitialized state.
1075 * Returns 1 on success, 0 on failure.
1077 int rand_drbg_enable_locking(RAND_DRBG *drbg)
1079 if (drbg->state != DRBG_UNINITIALISED) {
1080 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
1081 RAND_R_DRBG_ALREADY_INITIALIZED);
1085 if (drbg->lock == NULL) {
1086 if (drbg->parent != NULL && drbg->parent->lock == NULL) {
1087 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
1088 RAND_R_PARENT_LOCKING_NOT_ENABLED);
1092 drbg->lock = CRYPTO_THREAD_lock_new();
1093 if (drbg->lock == NULL) {
1094 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
1095 RAND_R_FAILED_TO_CREATE_LOCK);
1105 * Get and set the EXDATA
1107 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
1109 return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
1112 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
1114 return CRYPTO_get_ex_data(&drbg->ex_data, idx);
1119 * The following functions provide a RAND_METHOD that works on the
1120 * global DRBG. They lock.
1124 * Allocates a new global DRBG on the secure heap (if enabled) and
1125 * initializes it with default settings.
1127 * Returns a pointer to the new DRBG instance on success, NULL on failure.
1129 static RAND_DRBG *drbg_setup(OPENSSL_CTX *ctx, RAND_DRBG *parent, int drbg_type)
1133 drbg = RAND_DRBG_secure_new_ex(ctx, rand_drbg_type[drbg_type],
1134 rand_drbg_flags[drbg_type], parent);
1138 /* Only the master DRBG needs to have a lock */
1139 if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
1142 /* enable seed propagation */
1143 tsan_store(&drbg->reseed_prop_counter, 1);
1146 * Ignore instantiation error to support just-in-time instantiation.
1148 * The state of the drbg will be checked in RAND_DRBG_generate() and
1149 * an automatic recovery is attempted.
1151 (void)RAND_DRBG_instantiate(drbg,
1152 (const unsigned char *) ossl_pers_string,
1153 sizeof(ossl_pers_string) - 1);
1157 RAND_DRBG_free(drbg);
1161 static void drbg_delete_thread_state(void *arg)
1163 OPENSSL_CTX *ctx = arg;
1164 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1169 drbg = CRYPTO_THREAD_get_local(&dgbl->public_drbg);
1170 CRYPTO_THREAD_set_local(&dgbl->public_drbg, NULL);
1171 RAND_DRBG_free(drbg);
1173 drbg = CRYPTO_THREAD_get_local(&dgbl->private_drbg);
1174 CRYPTO_THREAD_set_local(&dgbl->private_drbg, NULL);
1175 RAND_DRBG_free(drbg);
1178 /* Implements the default OpenSSL RAND_bytes() method */
1179 static int drbg_bytes(unsigned char *out, int count)
1182 RAND_DRBG *drbg = RAND_DRBG_get0_public();
1187 ret = RAND_DRBG_bytes(drbg, out, count);
1193 * Calculates the minimum length of a full entropy buffer
1194 * which is necessary to seed (i.e. instantiate) the DRBG
1197 size_t rand_drbg_seedlen(RAND_DRBG *drbg)
1200 * If no os entropy source is available then RAND_seed(buffer, bufsize)
1201 * is expected to succeed if and only if the buffer length satisfies
1202 * the following requirements, which follow from the calculations
1203 * in RAND_DRBG_instantiate().
1205 size_t min_entropy = drbg->strength;
1206 size_t min_entropylen = drbg->min_entropylen;
1209 * Extra entropy for the random nonce in the absence of a
1210 * get_nonce callback, see comment in RAND_DRBG_instantiate().
1212 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
1213 min_entropy += drbg->strength / 2;
1214 min_entropylen += drbg->min_noncelen;
1218 * Convert entropy requirement from bits to bytes
1219 * (dividing by 8 without rounding upwards, because
1220 * all entropy requirements are divisible by 8).
1224 /* Return a value that satisfies both requirements */
1225 return min_entropy > min_entropylen ? min_entropy : min_entropylen;
1228 /* Implements the default OpenSSL RAND_add() method */
1229 static int drbg_add(const void *buf, int num, double randomness)
1232 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1239 if (num < 0 || randomness < 0.0)
1242 rand_drbg_lock(drbg);
1243 seedlen = rand_drbg_seedlen(drbg);
1245 buflen = (size_t)num;
1249 * NIST SP-800-90A mandates that entropy *shall not* be provided
1250 * by the consuming application. By setting the randomness to zero,
1251 * we ensure that the buffer contents will be added to the internal
1252 * state of the DRBG only as additional data.
1254 * (NIST SP-800-90Ar1, Sections 9.1 and 9.2)
1258 if (buflen < seedlen || randomness < (double) seedlen) {
1259 #if defined(OPENSSL_RAND_SEED_NONE)
1261 * If no os entropy source is available, a reseeding will fail
1262 * inevitably. So we use a trick to mix the buffer contents into
1263 * the DRBG state without forcing a reseeding: we generate a
1264 * dummy random byte, using the buffer content as additional data.
1265 * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
1267 unsigned char dummy[1];
1269 ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
1270 rand_drbg_unlock(drbg);
1274 * If an os entropy source is available then we declare the buffer content
1275 * as additional data by setting randomness to zero and trigger a regular
1282 if (randomness > (double)seedlen) {
1284 * The purpose of this check is to bound |randomness| by a
1285 * relatively small value in order to prevent an integer
1286 * overflow when multiplying by 8 in the rand_drbg_restart()
1287 * call below. Note that randomness is measured in bytes,
1288 * not bits, so this value corresponds to eight times the
1289 * security strength.
1291 randomness = (double)seedlen;
1294 ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
1295 rand_drbg_unlock(drbg);
1300 /* Implements the default OpenSSL RAND_seed() method */
1301 static int drbg_seed(const void *buf, int num)
1303 return drbg_add(buf, num, num);
1306 /* Implements the default OpenSSL RAND_status() method */
1307 static int drbg_status(void)
1310 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1315 rand_drbg_lock(drbg);
1316 ret = drbg->state == DRBG_READY ? 1 : 0;
1317 rand_drbg_unlock(drbg);
1322 * Get the master DRBG.
1323 * Returns pointer to the DRBG on success, NULL on failure.
1326 RAND_DRBG *OPENSSL_CTX_get0_master_drbg(OPENSSL_CTX *ctx)
1328 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1333 return dgbl->master_drbg;
1336 RAND_DRBG *RAND_DRBG_get0_master(void)
1338 return OPENSSL_CTX_get0_master_drbg(NULL);
1342 * Get the public DRBG.
1343 * Returns pointer to the DRBG on success, NULL on failure.
1345 RAND_DRBG *OPENSSL_CTX_get0_public_drbg(OPENSSL_CTX *ctx)
1347 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1353 drbg = CRYPTO_THREAD_get_local(&dgbl->public_drbg);
1355 ctx = openssl_ctx_get_concrete(ctx);
1357 * If the private_drbg is also NULL then this is the first time we've
1360 if (CRYPTO_THREAD_get_local(&dgbl->private_drbg) == NULL
1361 && !ossl_init_thread_start(NULL, ctx, drbg_delete_thread_state))
1363 drbg = drbg_setup(ctx, dgbl->master_drbg, RAND_DRBG_TYPE_PUBLIC);
1364 CRYPTO_THREAD_set_local(&dgbl->public_drbg, drbg);
1369 RAND_DRBG *RAND_DRBG_get0_public(void)
1371 return OPENSSL_CTX_get0_public_drbg(NULL);
1375 * Get the private DRBG.
1376 * Returns pointer to the DRBG on success, NULL on failure.
1378 RAND_DRBG *OPENSSL_CTX_get0_private_drbg(OPENSSL_CTX *ctx)
1380 DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
1386 drbg = CRYPTO_THREAD_get_local(&dgbl->private_drbg);
1388 ctx = openssl_ctx_get_concrete(ctx);
1390 * If the public_drbg is also NULL then this is the first time we've
1393 if (CRYPTO_THREAD_get_local(&dgbl->public_drbg) == NULL
1394 && !ossl_init_thread_start(NULL, ctx, drbg_delete_thread_state))
1396 drbg = drbg_setup(ctx, dgbl->master_drbg, RAND_DRBG_TYPE_PRIVATE);
1397 CRYPTO_THREAD_set_local(&dgbl->private_drbg, drbg);
1402 RAND_DRBG *RAND_DRBG_get0_private(void)
1404 return OPENSSL_CTX_get0_private_drbg(NULL);
1407 RAND_METHOD rand_meth = {
1416 RAND_METHOD *RAND_OpenSSL(void)