2 * Copyright 2011-2018 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 #include <openssl/crypto.h>
12 #include <openssl/err.h>
13 #include <openssl/rand.h>
15 #include "internal/thread_once.h"
16 #include "internal/rand_int.h"
17 #include "internal/cryptlib_int.h"
20 * Support framework for NIST SP 800-90A DRBG
22 * See manual page RAND_DRBG(7) for a general overview.
24 * The OpenSSL model is to have new and free functions, and that new
25 * does all initialization. That is not the NIST model, which has
26 * instantiation and un-instantiate, and re-use within a new/free
27 * lifecycle. (No doubt this comes from the desire to support hardware
28 * DRBG, where allocation of resources on something like an HSM is
29 * a much bigger deal than just re-setting an allocated resource.)
33 * The three shared DRBG instances
35 * There are three shared DRBG instances: <master>, <public>, and <private>.
41 * Not used directly by the application, only for reseeding the two other
42 * DRBGs. It reseeds itself by pulling either randomness from os entropy
43 * sources or by consuming randomness which was added by RAND_add().
45 * The <master> DRBG is a global instance which is accessed concurrently by
46 * all threads. The necessary locking is managed automatically by its child
47 * DRBG instances during reseeding.
49 static RAND_DRBG *master_drbg;
53 * Used by default for generating random bytes using RAND_bytes().
55 * The <public> DRBG is thread-local, i.e., there is one instance per thread.
57 static CRYPTO_THREAD_LOCAL public_drbg;
61 * Used by default for generating private keys using RAND_priv_bytes()
63 * The <private> DRBG is thread-local, i.e., there is one instance per thread.
65 static CRYPTO_THREAD_LOCAL private_drbg;
69 /* NIST SP 800-90A DRBG recommends the use of a personalization string. */
70 static const char ossl_pers_string[] = "OpenSSL NIST SP 800-90A DRBG";
72 static CRYPTO_ONCE rand_drbg_init = CRYPTO_ONCE_STATIC_INIT;
76 static int rand_drbg_type = RAND_DRBG_TYPE;
77 static unsigned int rand_drbg_flags = RAND_DRBG_FLAGS;
79 static unsigned int master_reseed_interval = MASTER_RESEED_INTERVAL;
80 static unsigned int slave_reseed_interval = SLAVE_RESEED_INTERVAL;
82 static time_t master_reseed_time_interval = MASTER_RESEED_TIME_INTERVAL;
83 static time_t slave_reseed_time_interval = SLAVE_RESEED_TIME_INTERVAL;
85 /* A logical OR of all used DRBG flag bits (currently there is only one) */
86 static const unsigned int rand_drbg_used_flags =
87 RAND_DRBG_FLAG_CTR_NO_DF;
89 static RAND_DRBG *drbg_setup(RAND_DRBG *parent);
91 static RAND_DRBG *rand_drbg_new(int secure,
97 * Set/initialize |drbg| to be of type |type|, with optional |flags|.
99 * If |type| and |flags| are zero, use the defaults
101 * Returns 1 on success, 0 on failure.
103 int RAND_DRBG_set(RAND_DRBG *drbg, int type, unsigned int flags)
107 if (type == 0 && flags == 0) {
108 type = rand_drbg_type;
109 flags = rand_drbg_flags;
112 drbg->state = DRBG_UNINITIALISED;
121 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
124 /* Uninitialized; that's okay. */
126 case NID_aes_128_ctr:
127 case NID_aes_192_ctr:
128 case NID_aes_256_ctr:
129 ret = drbg_ctr_init(drbg);
134 drbg->state = DRBG_ERROR;
135 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG);
141 * Set/initialize default |type| and |flag| for new drbg instances.
143 * Returns 1 on success, 0 on failure.
145 int RAND_DRBG_set_defaults(int type, unsigned int flags)
151 RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_TYPE);
153 case NID_aes_128_ctr:
154 case NID_aes_192_ctr:
155 case NID_aes_256_ctr:
159 if ((flags & ~rand_drbg_used_flags) != 0) {
160 RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_FLAGS);
164 rand_drbg_type = type;
165 rand_drbg_flags = flags;
172 * Allocate memory and initialize a new DRBG. The DRBG is allocated on
173 * the secure heap if |secure| is nonzero and the secure heap is enabled.
174 * The |parent|, if not NULL, will be used as random source for reseeding.
176 * Returns a pointer to the new DRBG instance on success, NULL on failure.
178 static RAND_DRBG *rand_drbg_new(int secure,
183 RAND_DRBG *drbg = secure ?
184 OPENSSL_secure_zalloc(sizeof(*drbg)) : OPENSSL_zalloc(sizeof(*drbg));
187 RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
191 drbg->secure = secure && CRYPTO_secure_allocated(drbg);
192 drbg->fork_count = rand_fork_count;
193 drbg->parent = parent;
195 if (parent == NULL) {
196 drbg->get_entropy = rand_drbg_get_entropy;
197 drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
198 #ifndef RAND_DRBG_GET_RANDOM_NONCE
199 drbg->get_nonce = rand_drbg_get_nonce;
200 drbg->cleanup_nonce = rand_drbg_cleanup_nonce;
203 drbg->reseed_interval = master_reseed_interval;
204 drbg->reseed_time_interval = master_reseed_time_interval;
206 drbg->get_entropy = rand_drbg_get_entropy;
207 drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
209 * Do not provide nonce callbacks, the child DRBGs will
210 * obtain their nonce using random bits from the parent.
213 drbg->reseed_interval = slave_reseed_interval;
214 drbg->reseed_time_interval = slave_reseed_time_interval;
217 if (RAND_DRBG_set(drbg, type, flags) == 0)
220 if (parent != NULL) {
221 rand_drbg_lock(parent);
222 if (drbg->strength > parent->strength) {
224 * We currently don't support the algorithm from NIST SP 800-90C
225 * 10.1.2 to use a weaker DRBG as source
227 rand_drbg_unlock(parent);
228 RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK);
231 rand_drbg_unlock(parent);
238 OPENSSL_secure_free(drbg);
245 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
247 return rand_drbg_new(0, type, flags, parent);
250 RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent)
252 return rand_drbg_new(1, type, flags, parent);
256 * Uninstantiate |drbg| and free all memory.
258 void RAND_DRBG_free(RAND_DRBG *drbg)
263 if (drbg->meth != NULL)
264 drbg->meth->uninstantiate(drbg);
265 CRYPTO_THREAD_lock_free(drbg->lock);
266 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
269 OPENSSL_secure_clear_free(drbg, sizeof(*drbg));
271 OPENSSL_clear_free(drbg, sizeof(*drbg));
275 * Instantiate |drbg|, after it has been initialized. Use |pers| and
276 * |perslen| as prediction-resistance input.
278 * Requires that drbg->lock is already locked for write, if non-null.
280 * Returns 1 on success, 0 on failure.
282 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
283 const unsigned char *pers, size_t perslen)
285 unsigned char *nonce = NULL, *entropy = NULL;
286 size_t noncelen = 0, entropylen = 0;
287 size_t min_entropy = drbg->strength;
288 size_t min_entropylen = drbg->min_entropylen;
289 size_t max_entropylen = drbg->max_entropylen;
291 if (perslen > drbg->max_perslen) {
292 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
293 RAND_R_PERSONALISATION_STRING_TOO_LONG);
297 if (drbg->meth == NULL) {
298 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
299 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
303 if (drbg->state != DRBG_UNINITIALISED) {
304 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
305 drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE
306 : RAND_R_ALREADY_INSTANTIATED);
310 drbg->state = DRBG_ERROR;
313 * NIST SP800-90Ar1 section 9.1 says you can combine getting the entropy
314 * and nonce in 1 call by increasing the entropy with 50% and increasing
315 * the minimum length to accomadate the length of the nonce.
316 * We do this in case a nonce is require and get_nonce is NULL.
318 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
319 min_entropy += drbg->strength / 2;
320 min_entropylen += drbg->min_noncelen;
321 max_entropylen += drbg->max_noncelen;
324 drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
325 if (drbg->reseed_next_counter) {
326 drbg->reseed_next_counter++;
327 if(!drbg->reseed_next_counter)
328 drbg->reseed_next_counter = 1;
331 if (drbg->get_entropy != NULL)
332 entropylen = drbg->get_entropy(drbg, &entropy, min_entropy,
333 min_entropylen, max_entropylen, 0);
334 if (entropylen < min_entropylen
335 || entropylen > max_entropylen) {
336 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
340 if (drbg->min_noncelen > 0 && drbg->get_nonce != NULL) {
341 noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
342 drbg->min_noncelen, drbg->max_noncelen);
343 if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
344 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_NONCE);
349 if (!drbg->meth->instantiate(drbg, entropy, entropylen,
350 nonce, noncelen, pers, perslen)) {
351 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
355 drbg->state = DRBG_READY;
356 drbg->reseed_gen_counter = 0;
357 drbg->reseed_time = time(NULL);
358 tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
361 if (entropy != NULL && drbg->cleanup_entropy != NULL)
362 drbg->cleanup_entropy(drbg, entropy, entropylen);
363 if (nonce != NULL && drbg->cleanup_nonce != NULL)
364 drbg->cleanup_nonce(drbg, nonce, noncelen);
365 if (drbg->state == DRBG_READY)
371 * Uninstantiate |drbg|. Must be instantiated before it can be used.
373 * Requires that drbg->lock is already locked for write, if non-null.
375 * Returns 1 on success, 0 on failure.
377 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
379 if (drbg->meth == NULL) {
380 RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
381 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
385 /* Clear the entire drbg->ctr struct, then reset some important
386 * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
389 drbg->meth->uninstantiate(drbg);
390 return RAND_DRBG_set(drbg, drbg->type, drbg->flags);
394 * Reseed |drbg|, mixing in the specified data
396 * Requires that drbg->lock is already locked for write, if non-null.
398 * Returns 1 on success, 0 on failure.
400 int RAND_DRBG_reseed(RAND_DRBG *drbg,
401 const unsigned char *adin, size_t adinlen,
402 int prediction_resistance)
404 unsigned char *entropy = NULL;
405 size_t entropylen = 0;
407 if (drbg->state == DRBG_ERROR) {
408 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
411 if (drbg->state == DRBG_UNINITIALISED) {
412 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
418 } else if (adinlen > drbg->max_adinlen) {
419 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
423 drbg->state = DRBG_ERROR;
425 drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
426 if (drbg->reseed_next_counter) {
427 drbg->reseed_next_counter++;
428 if(!drbg->reseed_next_counter)
429 drbg->reseed_next_counter = 1;
432 if (drbg->get_entropy != NULL)
433 entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
434 drbg->min_entropylen,
435 drbg->max_entropylen,
436 prediction_resistance);
437 if (entropylen < drbg->min_entropylen
438 || entropylen > drbg->max_entropylen) {
439 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
443 if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
446 drbg->state = DRBG_READY;
447 drbg->reseed_gen_counter = 0;
448 drbg->reseed_time = time(NULL);
449 tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
452 if (entropy != NULL && drbg->cleanup_entropy != NULL)
453 drbg->cleanup_entropy(drbg, entropy, entropylen);
454 if (drbg->state == DRBG_READY)
460 * Restart |drbg|, using the specified entropy or additional input
462 * Tries its best to get the drbg instantiated by all means,
463 * regardless of its current state.
465 * Optionally, a |buffer| of |len| random bytes can be passed,
466 * which is assumed to contain at least |entropy| bits of entropy.
468 * If |entropy| > 0, the buffer content is used as entropy input.
470 * If |entropy| == 0, the buffer content is used as additional input
472 * Returns 1 on success, 0 on failure.
474 * This function is used internally only.
476 int rand_drbg_restart(RAND_DRBG *drbg,
477 const unsigned char *buffer, size_t len, size_t entropy)
480 const unsigned char *adin = NULL;
483 if (drbg->pool != NULL) {
484 RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
485 drbg->state = DRBG_ERROR;
486 rand_pool_free(drbg->pool);
491 if (buffer != NULL) {
493 if (drbg->max_entropylen < len) {
494 RANDerr(RAND_F_RAND_DRBG_RESTART,
495 RAND_R_ENTROPY_INPUT_TOO_LONG);
496 drbg->state = DRBG_ERROR;
500 if (entropy > 8 * len) {
501 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
502 drbg->state = DRBG_ERROR;
506 /* will be picked up by the rand_drbg_get_entropy() callback */
507 drbg->pool = rand_pool_attach(buffer, len, entropy);
508 if (drbg->pool == NULL)
511 if (drbg->max_adinlen < len) {
512 RANDerr(RAND_F_RAND_DRBG_RESTART,
513 RAND_R_ADDITIONAL_INPUT_TOO_LONG);
514 drbg->state = DRBG_ERROR;
522 /* repair error state */
523 if (drbg->state == DRBG_ERROR)
524 RAND_DRBG_uninstantiate(drbg);
526 /* repair uninitialized state */
527 if (drbg->state == DRBG_UNINITIALISED) {
528 /* reinstantiate drbg */
529 RAND_DRBG_instantiate(drbg,
530 (const unsigned char *) ossl_pers_string,
531 sizeof(ossl_pers_string) - 1);
532 /* already reseeded. prevent second reseeding below */
533 reseeded = (drbg->state == DRBG_READY);
536 /* refresh current state if entropy or additional input has been provided */
537 if (drbg->state == DRBG_READY) {
540 * mix in additional input without reseeding
542 * Similar to RAND_DRBG_reseed(), but the provided additional
543 * data |adin| is mixed into the current state without pulling
544 * entropy from the trusted entropy source using get_entropy().
545 * This is not a reseeding in the strict sense of NIST SP 800-90A.
547 drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
548 } else if (reseeded == 0) {
549 /* do a full reseeding if it has not been done yet above */
550 RAND_DRBG_reseed(drbg, NULL, 0, 0);
554 rand_pool_free(drbg->pool);
557 return drbg->state == DRBG_READY;
561 * Generate |outlen| bytes into the buffer at |out|. Reseed if we need
562 * to or if |prediction_resistance| is set. Additional input can be
563 * sent in |adin| and |adinlen|.
565 * Requires that drbg->lock is already locked for write, if non-null.
567 * Returns 1 on success, 0 on failure.
570 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
571 int prediction_resistance,
572 const unsigned char *adin, size_t adinlen)
574 int reseed_required = 0;
576 if (drbg->state != DRBG_READY) {
577 /* try to recover from previous errors */
578 rand_drbg_restart(drbg, NULL, 0, 0);
580 if (drbg->state == DRBG_ERROR) {
581 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
584 if (drbg->state == DRBG_UNINITIALISED) {
585 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
590 if (outlen > drbg->max_request) {
591 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
594 if (adinlen > drbg->max_adinlen) {
595 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
599 if (drbg->fork_count != rand_fork_count) {
600 drbg->fork_count = rand_fork_count;
604 if (drbg->reseed_interval > 0) {
605 if (drbg->reseed_gen_counter >= drbg->reseed_interval)
608 if (drbg->reseed_time_interval > 0) {
609 time_t now = time(NULL);
610 if (now < drbg->reseed_time
611 || now - drbg->reseed_time >= drbg->reseed_time_interval)
614 if (drbg->parent != NULL) {
615 unsigned int reseed_counter = tsan_load(&drbg->reseed_prop_counter);
616 if (reseed_counter > 0
617 && tsan_load(&drbg->parent->reseed_prop_counter)
622 if (reseed_required || prediction_resistance) {
623 if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
624 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
631 if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
632 drbg->state = DRBG_ERROR;
633 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
637 drbg->reseed_gen_counter++;
643 * Generates |outlen| random bytes and stores them in |out|. It will
644 * using the given |drbg| to generate the bytes.
646 * Requires that drbg->lock is already locked for write, if non-null.
648 * Returns 1 on success 0 on failure.
650 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
652 unsigned char *additional = NULL;
653 size_t additional_len;
657 additional_len = rand_drbg_get_additional_data(&additional, drbg->max_adinlen);
659 for ( ; outlen > 0; outlen -= chunk, out += chunk) {
661 if (chunk > drbg->max_request)
662 chunk = drbg->max_request;
663 ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
670 if (additional_len != 0)
671 OPENSSL_secure_clear_free(additional, additional_len);
677 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
679 * Setting the callbacks is allowed only if the drbg has not been
680 * initialized yet. Otherwise, the operation will fail.
682 * Returns 1 on success, 0 on failure.
684 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
685 RAND_DRBG_get_entropy_fn get_entropy,
686 RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
687 RAND_DRBG_get_nonce_fn get_nonce,
688 RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
690 if (drbg->state != DRBG_UNINITIALISED
691 || drbg->parent != NULL)
693 drbg->get_entropy = get_entropy;
694 drbg->cleanup_entropy = cleanup_entropy;
695 drbg->get_nonce = get_nonce;
696 drbg->cleanup_nonce = cleanup_nonce;
701 * Set the reseed interval.
703 * The drbg will reseed automatically whenever the number of generate
704 * requests exceeds the given reseed interval. If the reseed interval
705 * is 0, then this feature is disabled.
707 * Returns 1 on success, 0 on failure.
709 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
711 if (interval > MAX_RESEED_INTERVAL)
713 drbg->reseed_interval = interval;
718 * Set the reseed time interval.
720 * The drbg will reseed automatically whenever the time elapsed since
721 * the last reseeding exceeds the given reseed time interval. For safety,
722 * a reseeding will also occur if the clock has been reset to a smaller
725 * Returns 1 on success, 0 on failure.
727 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
729 if (interval > MAX_RESEED_TIME_INTERVAL)
731 drbg->reseed_time_interval = interval;
736 * Set the default values for reseed (time) intervals of new DRBG instances
738 * The default values can be set independently for master DRBG instances
739 * (without a parent) and slave DRBG instances (with parent).
741 * Returns 1 on success, 0 on failure.
744 int RAND_DRBG_set_reseed_defaults(
745 unsigned int _master_reseed_interval,
746 unsigned int _slave_reseed_interval,
747 time_t _master_reseed_time_interval,
748 time_t _slave_reseed_time_interval
751 if (_master_reseed_interval > MAX_RESEED_INTERVAL
752 || _slave_reseed_interval > MAX_RESEED_INTERVAL)
755 if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
756 || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
759 master_reseed_interval = _master_reseed_interval;
760 slave_reseed_interval = _slave_reseed_interval;
762 master_reseed_time_interval = _master_reseed_time_interval;
763 slave_reseed_time_interval = _slave_reseed_time_interval;
769 * Locks the given drbg. Locking a drbg which does not have locking
770 * enabled is considered a successful no-op.
772 * Returns 1 on success, 0 on failure.
774 int rand_drbg_lock(RAND_DRBG *drbg)
776 if (drbg->lock != NULL)
777 return CRYPTO_THREAD_write_lock(drbg->lock);
783 * Unlocks the given drbg. Unlocking a drbg which does not have locking
784 * enabled is considered a successful no-op.
786 * Returns 1 on success, 0 on failure.
788 int rand_drbg_unlock(RAND_DRBG *drbg)
790 if (drbg->lock != NULL)
791 return CRYPTO_THREAD_unlock(drbg->lock);
797 * Enables locking for the given drbg
799 * Locking can only be enabled if the random generator
800 * is in the uninitialized state.
802 * Returns 1 on success, 0 on failure.
804 int rand_drbg_enable_locking(RAND_DRBG *drbg)
806 if (drbg->state != DRBG_UNINITIALISED) {
807 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
808 RAND_R_DRBG_ALREADY_INITIALIZED);
812 if (drbg->lock == NULL) {
813 if (drbg->parent != NULL && drbg->parent->lock == NULL) {
814 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
815 RAND_R_PARENT_LOCKING_NOT_ENABLED);
819 drbg->lock = CRYPTO_THREAD_lock_new();
820 if (drbg->lock == NULL) {
821 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
822 RAND_R_FAILED_TO_CREATE_LOCK);
831 * Get and set the EXDATA
833 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
835 return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
838 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
840 return CRYPTO_get_ex_data(&drbg->ex_data, idx);
845 * The following functions provide a RAND_METHOD that works on the
846 * global DRBG. They lock.
850 * Allocates a new global DRBG on the secure heap (if enabled) and
851 * initializes it with default settings.
853 * Returns a pointer to the new DRBG instance on success, NULL on failure.
855 static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
859 drbg = RAND_DRBG_secure_new(rand_drbg_type, rand_drbg_flags, parent);
863 /* Only the master DRBG needs to have a lock */
864 if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
867 /* enable seed propagation */
868 tsan_store(&drbg->reseed_prop_counter, 1);
871 * Ignore instantiation error to support just-in-time instantiation.
873 * The state of the drbg will be checked in RAND_DRBG_generate() and
874 * an automatic recovery is attempted.
876 (void)RAND_DRBG_instantiate(drbg,
877 (const unsigned char *) ossl_pers_string,
878 sizeof(ossl_pers_string) - 1);
882 RAND_DRBG_free(drbg);
887 * Initialize the global DRBGs on first use.
888 * Returns 1 on success, 0 on failure.
890 DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
893 * ensure that libcrypto is initialized, otherwise the
894 * DRBG locks are not cleaned up properly
896 if (!OPENSSL_init_crypto(0, NULL))
899 if (!CRYPTO_THREAD_init_local(&private_drbg, NULL))
902 if (!CRYPTO_THREAD_init_local(&public_drbg, NULL))
905 master_drbg = drbg_setup(NULL);
906 if (master_drbg == NULL)
912 CRYPTO_THREAD_cleanup_local(&public_drbg);
914 CRYPTO_THREAD_cleanup_local(&private_drbg);
918 /* Clean up the global DRBGs before exit */
919 void rand_drbg_cleanup_int(void)
921 if (master_drbg != NULL) {
922 RAND_DRBG_free(master_drbg);
925 CRYPTO_THREAD_cleanup_local(&private_drbg);
926 CRYPTO_THREAD_cleanup_local(&public_drbg);
930 void drbg_delete_thread_state(void)
934 drbg = CRYPTO_THREAD_get_local(&public_drbg);
935 CRYPTO_THREAD_set_local(&public_drbg, NULL);
936 RAND_DRBG_free(drbg);
938 drbg = CRYPTO_THREAD_get_local(&private_drbg);
939 CRYPTO_THREAD_set_local(&private_drbg, NULL);
940 RAND_DRBG_free(drbg);
943 /* Implements the default OpenSSL RAND_bytes() method */
944 static int drbg_bytes(unsigned char *out, int count)
947 RAND_DRBG *drbg = RAND_DRBG_get0_public();
952 ret = RAND_DRBG_bytes(drbg, out, count);
958 * Calculates the minimum length of a full entropy buffer
959 * which is necessary to seed (i.e. instantiate) the DRBG
962 * NOTE: There is a copy of this function in drbgtest.c.
963 * If you change anything here, you need to update
964 * the copy accordingly.
966 static size_t rand_drbg_seedlen(RAND_DRBG *drbg)
969 * If no os entropy source is available then RAND_seed(buffer, bufsize)
970 * is expected to succeed if and only if the buffer length satisfies
971 * the following requirements, which follow from the calculations
972 * in RAND_DRBG_instantiate().
974 size_t min_entropy = drbg->strength;
975 size_t min_entropylen = drbg->min_entropylen;
978 * Extra entropy for the random nonce in the absence of a
979 * get_nonce callback, see comment in RAND_DRBG_instantiate().
981 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
982 min_entropy += drbg->strength / 2;
983 min_entropylen += drbg->min_noncelen;
987 * Convert entropy requirement from bits to bytes
988 * (dividing by 8 without rounding upwards, because
989 * all entropy requirements are divisible by 8).
993 /* Return a value that satisfies both requirements */
994 return min_entropy > min_entropylen ? min_entropy : min_entropylen;
997 /* Implements the default OpenSSL RAND_add() method */
998 static int drbg_add(const void *buf, int num, double randomness)
1001 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1008 if (num < 0 || randomness < 0.0)
1011 rand_drbg_lock(drbg);
1012 seedlen = rand_drbg_seedlen(drbg);
1014 buflen = (size_t)num;
1016 if (buflen < seedlen || randomness < (double) seedlen) {
1017 #if defined(OPENSSL_RAND_SEED_NONE)
1019 * If no os entropy source is available, a reseeding will fail
1020 * inevitably. So we use a trick to mix the buffer contents into
1021 * the DRBG state without forcing a reseeding: we generate a
1022 * dummy random byte, using the buffer content as additional data.
1023 * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
1025 unsigned char dummy[1];
1027 ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
1028 rand_drbg_unlock(drbg);
1032 * If an os entropy source is avaible then we declare the buffer content
1033 * as additional data by setting randomness to zero and trigger a regular
1041 if (randomness > (double)seedlen) {
1043 * The purpose of this check is to bound |randomness| by a
1044 * relatively small value in order to prevent an integer
1045 * overflow when multiplying by 8 in the rand_drbg_restart()
1046 * call below. Note that randomness is measured in bytes,
1047 * not bits, so this value corresponds to eight times the
1048 * security strength.
1050 randomness = (double)seedlen;
1053 ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
1054 rand_drbg_unlock(drbg);
1059 /* Implements the default OpenSSL RAND_seed() method */
1060 static int drbg_seed(const void *buf, int num)
1062 return drbg_add(buf, num, num);
1065 /* Implements the default OpenSSL RAND_status() method */
1066 static int drbg_status(void)
1069 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1074 rand_drbg_lock(drbg);
1075 ret = drbg->state == DRBG_READY ? 1 : 0;
1076 rand_drbg_unlock(drbg);
1081 * Get the master DRBG.
1082 * Returns pointer to the DRBG on success, NULL on failure.
1085 RAND_DRBG *RAND_DRBG_get0_master(void)
1087 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1094 * Get the public DRBG.
1095 * Returns pointer to the DRBG on success, NULL on failure.
1097 RAND_DRBG *RAND_DRBG_get0_public(void)
1101 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1104 drbg = CRYPTO_THREAD_get_local(&public_drbg);
1106 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1108 drbg = drbg_setup(master_drbg);
1109 CRYPTO_THREAD_set_local(&public_drbg, drbg);
1115 * Get the private DRBG.
1116 * Returns pointer to the DRBG on success, NULL on failure.
1118 RAND_DRBG *RAND_DRBG_get0_private(void)
1122 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1125 drbg = CRYPTO_THREAD_get_local(&private_drbg);
1127 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1129 drbg = drbg_setup(master_drbg);
1130 CRYPTO_THREAD_set_local(&private_drbg, drbg);
1135 RAND_METHOD rand_meth = {
1144 RAND_METHOD *RAND_OpenSSL(void)