2 * Copyright 2011-2019 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 /* If set is called multiple times - clear the old one */
113 if (drbg->type != 0 && (type != drbg->type || flags != drbg->flags)) {
114 drbg->meth->uninstantiate(drbg);
115 rand_pool_free(drbg->adin_pool);
116 drbg->adin_pool = NULL;
119 drbg->state = DRBG_UNINITIALISED;
128 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
131 /* Uninitialized; that's okay. */
134 case NID_aes_128_ctr:
135 case NID_aes_192_ctr:
136 case NID_aes_256_ctr:
137 ret = drbg_ctr_init(drbg);
142 drbg->state = DRBG_ERROR;
143 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG);
149 * Set/initialize default |type| and |flag| for new drbg instances.
151 * Returns 1 on success, 0 on failure.
153 int RAND_DRBG_set_defaults(int type, unsigned int flags)
159 RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_TYPE);
161 case NID_aes_128_ctr:
162 case NID_aes_192_ctr:
163 case NID_aes_256_ctr:
167 if ((flags & ~rand_drbg_used_flags) != 0) {
168 RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_FLAGS);
172 rand_drbg_type = type;
173 rand_drbg_flags = flags;
180 * Allocate memory and initialize a new DRBG. The DRBG is allocated on
181 * the secure heap if |secure| is nonzero and the secure heap is enabled.
182 * The |parent|, if not NULL, will be used as random source for reseeding.
184 * Returns a pointer to the new DRBG instance on success, NULL on failure.
186 static RAND_DRBG *rand_drbg_new(int secure,
191 RAND_DRBG *drbg = secure ? OPENSSL_secure_zalloc(sizeof(*drbg))
192 : OPENSSL_zalloc(sizeof(*drbg));
195 RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
199 drbg->secure = secure && CRYPTO_secure_allocated(drbg);
200 drbg->fork_count = rand_fork_count;
201 drbg->parent = parent;
203 if (parent == NULL) {
204 drbg->get_entropy = rand_drbg_get_entropy;
205 drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
206 #ifndef RAND_DRBG_GET_RANDOM_NONCE
207 drbg->get_nonce = rand_drbg_get_nonce;
208 drbg->cleanup_nonce = rand_drbg_cleanup_nonce;
211 drbg->reseed_interval = master_reseed_interval;
212 drbg->reseed_time_interval = master_reseed_time_interval;
214 drbg->get_entropy = rand_drbg_get_entropy;
215 drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
217 * Do not provide nonce callbacks, the child DRBGs will
218 * obtain their nonce using random bits from the parent.
221 drbg->reseed_interval = slave_reseed_interval;
222 drbg->reseed_time_interval = slave_reseed_time_interval;
225 if (RAND_DRBG_set(drbg, type, flags) == 0)
228 if (parent != NULL) {
229 rand_drbg_lock(parent);
230 if (drbg->strength > parent->strength) {
232 * We currently don't support the algorithm from NIST SP 800-90C
233 * 10.1.2 to use a weaker DRBG as source
235 rand_drbg_unlock(parent);
236 RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK);
239 rand_drbg_unlock(parent);
245 RAND_DRBG_free(drbg);
250 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
252 return rand_drbg_new(0, type, flags, parent);
255 RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent)
257 return rand_drbg_new(1, type, flags, parent);
261 * Uninstantiate |drbg| and free all memory.
263 void RAND_DRBG_free(RAND_DRBG *drbg)
268 if (drbg->meth != NULL)
269 drbg->meth->uninstantiate(drbg);
270 rand_pool_free(drbg->adin_pool);
271 CRYPTO_THREAD_lock_free(drbg->lock);
272 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
275 OPENSSL_secure_clear_free(drbg, sizeof(*drbg));
277 OPENSSL_clear_free(drbg, sizeof(*drbg));
281 * Instantiate |drbg|, after it has been initialized. Use |pers| and
282 * |perslen| as prediction-resistance input.
284 * Requires that drbg->lock is already locked for write, if non-null.
286 * Returns 1 on success, 0 on failure.
288 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
289 const unsigned char *pers, size_t perslen)
291 unsigned char *nonce = NULL, *entropy = NULL;
292 size_t noncelen = 0, entropylen = 0;
293 size_t min_entropy = drbg->strength;
294 size_t min_entropylen = drbg->min_entropylen;
295 size_t max_entropylen = drbg->max_entropylen;
297 if (perslen > drbg->max_perslen) {
298 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
299 RAND_R_PERSONALISATION_STRING_TOO_LONG);
303 if (drbg->meth == NULL) {
304 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
305 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
309 if (drbg->state != DRBG_UNINITIALISED) {
310 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
311 drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE
312 : RAND_R_ALREADY_INSTANTIATED);
316 drbg->state = DRBG_ERROR;
319 * NIST SP800-90Ar1 section 9.1 says you can combine getting the entropy
320 * and nonce in 1 call by increasing the entropy with 50% and increasing
321 * the minimum length to accomadate the length of the nonce.
322 * We do this in case a nonce is require and get_nonce is NULL.
324 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
325 min_entropy += drbg->strength / 2;
326 min_entropylen += drbg->min_noncelen;
327 max_entropylen += drbg->max_noncelen;
330 drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
331 if (drbg->reseed_next_counter) {
332 drbg->reseed_next_counter++;
333 if(!drbg->reseed_next_counter)
334 drbg->reseed_next_counter = 1;
337 if (drbg->get_entropy != NULL)
338 entropylen = drbg->get_entropy(drbg, &entropy, min_entropy,
339 min_entropylen, max_entropylen, 0);
340 if (entropylen < min_entropylen
341 || entropylen > max_entropylen) {
342 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
346 if (drbg->min_noncelen > 0 && drbg->get_nonce != NULL) {
347 noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
348 drbg->min_noncelen, drbg->max_noncelen);
349 if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
350 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_NONCE);
355 if (!drbg->meth->instantiate(drbg, entropy, entropylen,
356 nonce, noncelen, pers, perslen)) {
357 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
361 drbg->state = DRBG_READY;
362 drbg->reseed_gen_counter = 1;
363 drbg->reseed_time = time(NULL);
364 tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
367 if (entropy != NULL && drbg->cleanup_entropy != NULL)
368 drbg->cleanup_entropy(drbg, entropy, entropylen);
369 if (nonce != NULL && drbg->cleanup_nonce != NULL)
370 drbg->cleanup_nonce(drbg, nonce, noncelen);
371 if (drbg->state == DRBG_READY)
377 * Uninstantiate |drbg|. Must be instantiated before it can be used.
379 * Requires that drbg->lock is already locked for write, if non-null.
381 * Returns 1 on success, 0 on failure.
383 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
385 if (drbg->meth == NULL) {
386 drbg->state = DRBG_ERROR;
387 RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
388 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
392 /* Clear the entire drbg->ctr struct, then reset some important
393 * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
396 drbg->meth->uninstantiate(drbg);
397 return RAND_DRBG_set(drbg, drbg->type, drbg->flags);
401 * Reseed |drbg|, mixing in the specified data
403 * Requires that drbg->lock is already locked for write, if non-null.
405 * Returns 1 on success, 0 on failure.
407 int RAND_DRBG_reseed(RAND_DRBG *drbg,
408 const unsigned char *adin, size_t adinlen,
409 int prediction_resistance)
411 unsigned char *entropy = NULL;
412 size_t entropylen = 0;
414 if (drbg->state == DRBG_ERROR) {
415 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
418 if (drbg->state == DRBG_UNINITIALISED) {
419 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
425 } else if (adinlen > drbg->max_adinlen) {
426 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
430 drbg->state = DRBG_ERROR;
432 drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
433 if (drbg->reseed_next_counter) {
434 drbg->reseed_next_counter++;
435 if(!drbg->reseed_next_counter)
436 drbg->reseed_next_counter = 1;
439 if (drbg->get_entropy != NULL)
440 entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
441 drbg->min_entropylen,
442 drbg->max_entropylen,
443 prediction_resistance);
444 if (entropylen < drbg->min_entropylen
445 || entropylen > drbg->max_entropylen) {
446 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
450 if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
453 drbg->state = DRBG_READY;
454 drbg->reseed_gen_counter = 1;
455 drbg->reseed_time = time(NULL);
456 tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
459 if (entropy != NULL && drbg->cleanup_entropy != NULL)
460 drbg->cleanup_entropy(drbg, entropy, entropylen);
461 if (drbg->state == DRBG_READY)
467 * Restart |drbg|, using the specified entropy or additional input
469 * Tries its best to get the drbg instantiated by all means,
470 * regardless of its current state.
472 * Optionally, a |buffer| of |len| random bytes can be passed,
473 * which is assumed to contain at least |entropy| bits of entropy.
475 * If |entropy| > 0, the buffer content is used as entropy input.
477 * If |entropy| == 0, the buffer content is used as additional input
479 * Returns 1 on success, 0 on failure.
481 * This function is used internally only.
483 int rand_drbg_restart(RAND_DRBG *drbg,
484 const unsigned char *buffer, size_t len, size_t entropy)
487 const unsigned char *adin = NULL;
490 if (drbg->seed_pool != NULL) {
491 RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
492 drbg->state = DRBG_ERROR;
493 rand_pool_free(drbg->seed_pool);
494 drbg->seed_pool = NULL;
498 if (buffer != NULL) {
500 if (drbg->max_entropylen < len) {
501 RANDerr(RAND_F_RAND_DRBG_RESTART,
502 RAND_R_ENTROPY_INPUT_TOO_LONG);
503 drbg->state = DRBG_ERROR;
507 if (entropy > 8 * len) {
508 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
509 drbg->state = DRBG_ERROR;
513 /* will be picked up by the rand_drbg_get_entropy() callback */
514 drbg->seed_pool = rand_pool_attach(buffer, len, entropy);
515 if (drbg->seed_pool == NULL)
518 if (drbg->max_adinlen < len) {
519 RANDerr(RAND_F_RAND_DRBG_RESTART,
520 RAND_R_ADDITIONAL_INPUT_TOO_LONG);
521 drbg->state = DRBG_ERROR;
529 /* repair error state */
530 if (drbg->state == DRBG_ERROR)
531 RAND_DRBG_uninstantiate(drbg);
533 /* repair uninitialized state */
534 if (drbg->state == DRBG_UNINITIALISED) {
535 /* reinstantiate drbg */
536 RAND_DRBG_instantiate(drbg,
537 (const unsigned char *) ossl_pers_string,
538 sizeof(ossl_pers_string) - 1);
539 /* already reseeded. prevent second reseeding below */
540 reseeded = (drbg->state == DRBG_READY);
543 /* refresh current state if entropy or additional input has been provided */
544 if (drbg->state == DRBG_READY) {
547 * mix in additional input without reseeding
549 * Similar to RAND_DRBG_reseed(), but the provided additional
550 * data |adin| is mixed into the current state without pulling
551 * entropy from the trusted entropy source using get_entropy().
552 * This is not a reseeding in the strict sense of NIST SP 800-90A.
554 drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
555 } else if (reseeded == 0) {
556 /* do a full reseeding if it has not been done yet above */
557 RAND_DRBG_reseed(drbg, NULL, 0, 0);
561 rand_pool_free(drbg->seed_pool);
562 drbg->seed_pool = NULL;
564 return drbg->state == DRBG_READY;
568 * Generate |outlen| bytes into the buffer at |out|. Reseed if we need
569 * to or if |prediction_resistance| is set. Additional input can be
570 * sent in |adin| and |adinlen|.
572 * Requires that drbg->lock is already locked for write, if non-null.
574 * Returns 1 on success, 0 on failure.
577 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
578 int prediction_resistance,
579 const unsigned char *adin, size_t adinlen)
581 int reseed_required = 0;
583 if (drbg->state != DRBG_READY) {
584 /* try to recover from previous errors */
585 rand_drbg_restart(drbg, NULL, 0, 0);
587 if (drbg->state == DRBG_ERROR) {
588 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
591 if (drbg->state == DRBG_UNINITIALISED) {
592 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
597 if (outlen > drbg->max_request) {
598 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
601 if (adinlen > drbg->max_adinlen) {
602 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
606 if (drbg->fork_count != rand_fork_count) {
607 drbg->fork_count = rand_fork_count;
611 if (drbg->reseed_interval > 0) {
612 if (drbg->reseed_gen_counter >= drbg->reseed_interval)
615 if (drbg->reseed_time_interval > 0) {
616 time_t now = time(NULL);
617 if (now < drbg->reseed_time
618 || now - drbg->reseed_time >= drbg->reseed_time_interval)
621 if (drbg->parent != NULL) {
622 unsigned int reseed_counter = tsan_load(&drbg->reseed_prop_counter);
623 if (reseed_counter > 0
624 && tsan_load(&drbg->parent->reseed_prop_counter)
629 if (reseed_required || prediction_resistance) {
630 if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
631 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
638 if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
639 drbg->state = DRBG_ERROR;
640 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
644 drbg->reseed_gen_counter++;
650 * Generates |outlen| random bytes and stores them in |out|. It will
651 * using the given |drbg| to generate the bytes.
653 * Requires that drbg->lock is already locked for write, if non-null.
655 * Returns 1 on success 0 on failure.
657 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
659 unsigned char *additional = NULL;
660 size_t additional_len;
664 if (drbg->adin_pool == NULL) {
667 drbg->adin_pool = rand_pool_new(0, 0, drbg->max_adinlen);
668 if (drbg->adin_pool == NULL)
672 additional_len = rand_drbg_get_additional_data(drbg->adin_pool,
675 for ( ; outlen > 0; outlen -= chunk, out += chunk) {
677 if (chunk > drbg->max_request)
678 chunk = drbg->max_request;
679 ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
686 if (additional != NULL)
687 rand_drbg_cleanup_additional_data(drbg->adin_pool, additional);
693 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
695 * Setting the callbacks is allowed only if the drbg has not been
696 * initialized yet. Otherwise, the operation will fail.
698 * Returns 1 on success, 0 on failure.
700 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
701 RAND_DRBG_get_entropy_fn get_entropy,
702 RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
703 RAND_DRBG_get_nonce_fn get_nonce,
704 RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
706 if (drbg->state != DRBG_UNINITIALISED
707 || drbg->parent != NULL)
709 drbg->get_entropy = get_entropy;
710 drbg->cleanup_entropy = cleanup_entropy;
711 drbg->get_nonce = get_nonce;
712 drbg->cleanup_nonce = cleanup_nonce;
717 * Set the reseed interval.
719 * The drbg will reseed automatically whenever the number of generate
720 * requests exceeds the given reseed interval. If the reseed interval
721 * is 0, then this feature is disabled.
723 * Returns 1 on success, 0 on failure.
725 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
727 if (interval > MAX_RESEED_INTERVAL)
729 drbg->reseed_interval = interval;
734 * Set the reseed time interval.
736 * The drbg will reseed automatically whenever the time elapsed since
737 * the last reseeding exceeds the given reseed time interval. For safety,
738 * a reseeding will also occur if the clock has been reset to a smaller
741 * Returns 1 on success, 0 on failure.
743 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
745 if (interval > MAX_RESEED_TIME_INTERVAL)
747 drbg->reseed_time_interval = interval;
752 * Set the default values for reseed (time) intervals of new DRBG instances
754 * The default values can be set independently for master DRBG instances
755 * (without a parent) and slave DRBG instances (with parent).
757 * Returns 1 on success, 0 on failure.
760 int RAND_DRBG_set_reseed_defaults(
761 unsigned int _master_reseed_interval,
762 unsigned int _slave_reseed_interval,
763 time_t _master_reseed_time_interval,
764 time_t _slave_reseed_time_interval
767 if (_master_reseed_interval > MAX_RESEED_INTERVAL
768 || _slave_reseed_interval > MAX_RESEED_INTERVAL)
771 if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
772 || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
775 master_reseed_interval = _master_reseed_interval;
776 slave_reseed_interval = _slave_reseed_interval;
778 master_reseed_time_interval = _master_reseed_time_interval;
779 slave_reseed_time_interval = _slave_reseed_time_interval;
785 * Locks the given drbg. Locking a drbg which does not have locking
786 * enabled is considered a successful no-op.
788 * Returns 1 on success, 0 on failure.
790 int rand_drbg_lock(RAND_DRBG *drbg)
792 if (drbg->lock != NULL)
793 return CRYPTO_THREAD_write_lock(drbg->lock);
799 * Unlocks the given drbg. Unlocking a drbg which does not have locking
800 * enabled is considered a successful no-op.
802 * Returns 1 on success, 0 on failure.
804 int rand_drbg_unlock(RAND_DRBG *drbg)
806 if (drbg->lock != NULL)
807 return CRYPTO_THREAD_unlock(drbg->lock);
813 * Enables locking for the given drbg
815 * Locking can only be enabled if the random generator
816 * is in the uninitialized state.
818 * Returns 1 on success, 0 on failure.
820 int rand_drbg_enable_locking(RAND_DRBG *drbg)
822 if (drbg->state != DRBG_UNINITIALISED) {
823 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
824 RAND_R_DRBG_ALREADY_INITIALIZED);
828 if (drbg->lock == NULL) {
829 if (drbg->parent != NULL && drbg->parent->lock == NULL) {
830 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
831 RAND_R_PARENT_LOCKING_NOT_ENABLED);
835 drbg->lock = CRYPTO_THREAD_lock_new();
836 if (drbg->lock == NULL) {
837 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
838 RAND_R_FAILED_TO_CREATE_LOCK);
847 * Get and set the EXDATA
849 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
851 return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
854 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
856 return CRYPTO_get_ex_data(&drbg->ex_data, idx);
861 * The following functions provide a RAND_METHOD that works on the
862 * global DRBG. They lock.
866 * Allocates a new global DRBG on the secure heap (if enabled) and
867 * initializes it with default settings.
869 * Returns a pointer to the new DRBG instance on success, NULL on failure.
871 static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
875 drbg = RAND_DRBG_secure_new(rand_drbg_type, rand_drbg_flags, parent);
879 /* Only the master DRBG needs to have a lock */
880 if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
883 /* enable seed propagation */
884 tsan_store(&drbg->reseed_prop_counter, 1);
887 * Ignore instantiation error to support just-in-time instantiation.
889 * The state of the drbg will be checked in RAND_DRBG_generate() and
890 * an automatic recovery is attempted.
892 (void)RAND_DRBG_instantiate(drbg,
893 (const unsigned char *) ossl_pers_string,
894 sizeof(ossl_pers_string) - 1);
898 RAND_DRBG_free(drbg);
903 * Initialize the global DRBGs on first use.
904 * Returns 1 on success, 0 on failure.
906 DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
909 * ensure that libcrypto is initialized, otherwise the
910 * DRBG locks are not cleaned up properly
912 if (!OPENSSL_init_crypto(0, NULL))
915 if (!CRYPTO_THREAD_init_local(&private_drbg, NULL))
918 if (!CRYPTO_THREAD_init_local(&public_drbg, NULL))
921 master_drbg = drbg_setup(NULL);
922 if (master_drbg == NULL)
928 CRYPTO_THREAD_cleanup_local(&public_drbg);
930 CRYPTO_THREAD_cleanup_local(&private_drbg);
934 /* Clean up the global DRBGs before exit */
935 void rand_drbg_cleanup_int(void)
937 if (master_drbg != NULL) {
938 RAND_DRBG_free(master_drbg);
941 CRYPTO_THREAD_cleanup_local(&private_drbg);
942 CRYPTO_THREAD_cleanup_local(&public_drbg);
946 void drbg_delete_thread_state(void)
950 drbg = CRYPTO_THREAD_get_local(&public_drbg);
951 CRYPTO_THREAD_set_local(&public_drbg, NULL);
952 RAND_DRBG_free(drbg);
954 drbg = CRYPTO_THREAD_get_local(&private_drbg);
955 CRYPTO_THREAD_set_local(&private_drbg, NULL);
956 RAND_DRBG_free(drbg);
959 /* Implements the default OpenSSL RAND_bytes() method */
960 static int drbg_bytes(unsigned char *out, int count)
963 RAND_DRBG *drbg = RAND_DRBG_get0_public();
968 ret = RAND_DRBG_bytes(drbg, out, count);
974 * Calculates the minimum length of a full entropy buffer
975 * which is necessary to seed (i.e. instantiate) the DRBG
978 size_t rand_drbg_seedlen(RAND_DRBG *drbg)
981 * If no os entropy source is available then RAND_seed(buffer, bufsize)
982 * is expected to succeed if and only if the buffer length satisfies
983 * the following requirements, which follow from the calculations
984 * in RAND_DRBG_instantiate().
986 size_t min_entropy = drbg->strength;
987 size_t min_entropylen = drbg->min_entropylen;
990 * Extra entropy for the random nonce in the absence of a
991 * get_nonce callback, see comment in RAND_DRBG_instantiate().
993 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
994 min_entropy += drbg->strength / 2;
995 min_entropylen += drbg->min_noncelen;
999 * Convert entropy requirement from bits to bytes
1000 * (dividing by 8 without rounding upwards, because
1001 * all entropy requirements are divisible by 8).
1005 /* Return a value that satisfies both requirements */
1006 return min_entropy > min_entropylen ? min_entropy : min_entropylen;
1009 /* Implements the default OpenSSL RAND_add() method */
1010 static int drbg_add(const void *buf, int num, double randomness)
1013 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1020 if (num < 0 || randomness < 0.0)
1023 rand_drbg_lock(drbg);
1024 seedlen = rand_drbg_seedlen(drbg);
1026 buflen = (size_t)num;
1028 if (buflen < seedlen || randomness < (double) seedlen) {
1029 #if defined(OPENSSL_RAND_SEED_NONE)
1031 * If no os entropy source is available, a reseeding will fail
1032 * inevitably. So we use a trick to mix the buffer contents into
1033 * the DRBG state without forcing a reseeding: we generate a
1034 * dummy random byte, using the buffer content as additional data.
1035 * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
1037 unsigned char dummy[1];
1039 ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
1040 rand_drbg_unlock(drbg);
1044 * If an os entropy source is avaible then we declare the buffer content
1045 * as additional data by setting randomness to zero and trigger a regular
1053 if (randomness > (double)seedlen) {
1055 * The purpose of this check is to bound |randomness| by a
1056 * relatively small value in order to prevent an integer
1057 * overflow when multiplying by 8 in the rand_drbg_restart()
1058 * call below. Note that randomness is measured in bytes,
1059 * not bits, so this value corresponds to eight times the
1060 * security strength.
1062 randomness = (double)seedlen;
1065 ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
1066 rand_drbg_unlock(drbg);
1071 /* Implements the default OpenSSL RAND_seed() method */
1072 static int drbg_seed(const void *buf, int num)
1074 return drbg_add(buf, num, num);
1077 /* Implements the default OpenSSL RAND_status() method */
1078 static int drbg_status(void)
1081 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1086 rand_drbg_lock(drbg);
1087 ret = drbg->state == DRBG_READY ? 1 : 0;
1088 rand_drbg_unlock(drbg);
1093 * Get the master DRBG.
1094 * Returns pointer to the DRBG on success, NULL on failure.
1097 RAND_DRBG *RAND_DRBG_get0_master(void)
1099 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1106 * Get the public DRBG.
1107 * Returns pointer to the DRBG on success, NULL on failure.
1109 RAND_DRBG *RAND_DRBG_get0_public(void)
1113 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1116 drbg = CRYPTO_THREAD_get_local(&public_drbg);
1118 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1120 drbg = drbg_setup(master_drbg);
1121 CRYPTO_THREAD_set_local(&public_drbg, drbg);
1127 * Get the private DRBG.
1128 * Returns pointer to the DRBG on success, NULL on failure.
1130 RAND_DRBG *RAND_DRBG_get0_private(void)
1134 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1137 drbg = CRYPTO_THREAD_get_local(&private_drbg);
1139 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1141 drbg = drbg_setup(master_drbg);
1142 CRYPTO_THREAD_set_local(&private_drbg, drbg);
1147 RAND_METHOD rand_meth = {
1156 RAND_METHOD *RAND_OpenSSL(void)