2 * Copyright 2011-2020 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>
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 * 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_id = openssl_get_fork_id();
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 accommodate 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 if (drbg->get_entropy != NULL)
331 entropylen = drbg->get_entropy(drbg, &entropy, min_entropy,
332 min_entropylen, max_entropylen, 0);
333 if (entropylen < min_entropylen
334 || entropylen > max_entropylen) {
335 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
339 if (drbg->min_noncelen > 0 && drbg->get_nonce != NULL) {
340 noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
341 drbg->min_noncelen, drbg->max_noncelen);
342 if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
343 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_NONCE);
348 if (!drbg->meth->instantiate(drbg, entropy, entropylen,
349 nonce, noncelen, pers, perslen)) {
350 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
354 drbg->state = DRBG_READY;
355 drbg->generate_counter = 1;
356 drbg->reseed_time = time(NULL);
357 if (drbg->enable_reseed_propagation) {
358 if (drbg->parent == NULL)
359 tsan_counter(&drbg->reseed_counter);
361 tsan_store(&drbg->reseed_counter,
362 tsan_load(&drbg->parent->reseed_counter));
366 if (entropy != NULL && drbg->cleanup_entropy != NULL)
367 drbg->cleanup_entropy(drbg, entropy, entropylen);
368 if (nonce != NULL && drbg->cleanup_nonce != NULL)
369 drbg->cleanup_nonce(drbg, nonce, noncelen);
370 if (drbg->state == DRBG_READY)
376 * Uninstantiate |drbg|. Must be instantiated before it can be used.
378 * Requires that drbg->lock is already locked for write, if non-null.
380 * Returns 1 on success, 0 on failure.
382 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
384 if (drbg->meth == NULL) {
385 drbg->state = DRBG_ERROR;
386 RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
387 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
391 /* Clear the entire drbg->ctr struct, then reset some important
392 * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
395 drbg->meth->uninstantiate(drbg);
396 return RAND_DRBG_set(drbg, drbg->type, drbg->flags);
400 * Reseed |drbg|, mixing in the specified data
402 * Requires that drbg->lock is already locked for write, if non-null.
404 * Returns 1 on success, 0 on failure.
406 int RAND_DRBG_reseed(RAND_DRBG *drbg,
407 const unsigned char *adin, size_t adinlen,
408 int prediction_resistance)
410 unsigned char *entropy = NULL;
411 size_t entropylen = 0;
413 if (drbg->state == DRBG_ERROR) {
414 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
417 if (drbg->state == DRBG_UNINITIALISED) {
418 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
424 } else if (adinlen > drbg->max_adinlen) {
425 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
429 drbg->state = DRBG_ERROR;
430 if (drbg->get_entropy != NULL)
431 entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
432 drbg->min_entropylen,
433 drbg->max_entropylen,
434 prediction_resistance);
435 if (entropylen < drbg->min_entropylen
436 || entropylen > drbg->max_entropylen) {
437 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
441 if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
444 drbg->state = DRBG_READY;
445 drbg->generate_counter = 1;
446 drbg->reseed_time = time(NULL);
447 if (drbg->enable_reseed_propagation) {
448 if (drbg->parent == NULL)
449 tsan_counter(&drbg->reseed_counter);
451 tsan_store(&drbg->reseed_counter,
452 tsan_load(&drbg->parent->reseed_counter));
456 if (entropy != NULL && drbg->cleanup_entropy != NULL)
457 drbg->cleanup_entropy(drbg, entropy, entropylen);
458 if (drbg->state == DRBG_READY)
464 * Restart |drbg|, using the specified entropy or additional input
466 * Tries its best to get the drbg instantiated by all means,
467 * regardless of its current state.
469 * Optionally, a |buffer| of |len| random bytes can be passed,
470 * which is assumed to contain at least |entropy| bits of entropy.
472 * If |entropy| > 0, the buffer content is used as entropy input.
474 * If |entropy| == 0, the buffer content is used as additional input
476 * Returns 1 on success, 0 on failure.
478 * This function is used internally only.
480 int rand_drbg_restart(RAND_DRBG *drbg,
481 const unsigned char *buffer, size_t len, size_t entropy)
484 const unsigned char *adin = NULL;
487 if (drbg->seed_pool != NULL) {
488 RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
489 drbg->state = DRBG_ERROR;
490 rand_pool_free(drbg->seed_pool);
491 drbg->seed_pool = NULL;
495 if (buffer != NULL) {
497 if (drbg->max_entropylen < len) {
498 RANDerr(RAND_F_RAND_DRBG_RESTART,
499 RAND_R_ENTROPY_INPUT_TOO_LONG);
500 drbg->state = DRBG_ERROR;
504 if (entropy > 8 * len) {
505 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
506 drbg->state = DRBG_ERROR;
510 /* will be picked up by the rand_drbg_get_entropy() callback */
511 drbg->seed_pool = rand_pool_attach(buffer, len, entropy);
512 if (drbg->seed_pool == NULL)
515 if (drbg->max_adinlen < len) {
516 RANDerr(RAND_F_RAND_DRBG_RESTART,
517 RAND_R_ADDITIONAL_INPUT_TOO_LONG);
518 drbg->state = DRBG_ERROR;
526 /* repair error state */
527 if (drbg->state == DRBG_ERROR)
528 RAND_DRBG_uninstantiate(drbg);
530 /* repair uninitialized state */
531 if (drbg->state == DRBG_UNINITIALISED) {
532 /* reinstantiate drbg */
533 RAND_DRBG_instantiate(drbg,
534 (const unsigned char *) ossl_pers_string,
535 sizeof(ossl_pers_string) - 1);
536 /* already reseeded. prevent second reseeding below */
537 reseeded = (drbg->state == DRBG_READY);
540 /* refresh current state if entropy or additional input has been provided */
541 if (drbg->state == DRBG_READY) {
544 * mix in additional input without reseeding
546 * Similar to RAND_DRBG_reseed(), but the provided additional
547 * data |adin| is mixed into the current state without pulling
548 * entropy from the trusted entropy source using get_entropy().
549 * This is not a reseeding in the strict sense of NIST SP 800-90A.
551 drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
552 } else if (reseeded == 0) {
553 /* do a full reseeding if it has not been done yet above */
554 if (!RAND_DRBG_reseed(drbg, NULL, 0, 0)) {
555 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_RESEED_ERROR);
560 rand_pool_free(drbg->seed_pool);
561 drbg->seed_pool = NULL;
563 return drbg->state == DRBG_READY;
567 * Generate |outlen| bytes into the buffer at |out|. Reseed if we need
568 * to or if |prediction_resistance| is set. Additional input can be
569 * sent in |adin| and |adinlen|.
571 * Requires that drbg->lock is already locked for write, if non-null.
573 * Returns 1 on success, 0 on failure.
576 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
577 int prediction_resistance,
578 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 fork_id = openssl_get_fork_id();
608 if (drbg->fork_id != fork_id) {
609 drbg->fork_id = fork_id;
613 if (drbg->reseed_interval > 0) {
614 if (drbg->generate_counter >= drbg->reseed_interval)
617 if (drbg->reseed_time_interval > 0) {
618 time_t now = time(NULL);
619 if (now < drbg->reseed_time
620 || now - drbg->reseed_time >= drbg->reseed_time_interval)
623 if (drbg->enable_reseed_propagation && drbg->parent != NULL) {
624 if (drbg->reseed_counter != tsan_load(&drbg->parent->reseed_counter))
628 if (reseed_required || prediction_resistance) {
629 if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
630 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
637 if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
638 drbg->state = DRBG_ERROR;
639 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
643 drbg->generate_counter++;
649 * Generates |outlen| random bytes and stores them in |out|. It will
650 * using the given |drbg| to generate the bytes.
652 * Requires that drbg->lock is already locked for write, if non-null.
654 * Returns 1 on success 0 on failure.
656 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
658 unsigned char *additional = NULL;
659 size_t additional_len;
663 if (drbg->adin_pool == NULL) {
666 drbg->adin_pool = rand_pool_new(0, 0, 0, drbg->max_adinlen);
667 if (drbg->adin_pool == NULL)
671 additional_len = rand_drbg_get_additional_data(drbg->adin_pool,
674 for ( ; outlen > 0; outlen -= chunk, out += chunk) {
676 if (chunk > drbg->max_request)
677 chunk = drbg->max_request;
678 ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
685 if (additional != NULL)
686 rand_drbg_cleanup_additional_data(drbg->adin_pool, additional);
692 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
694 * Setting the callbacks is allowed only if the drbg has not been
695 * initialized yet. Otherwise, the operation will fail.
697 * Returns 1 on success, 0 on failure.
699 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
700 RAND_DRBG_get_entropy_fn get_entropy,
701 RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
702 RAND_DRBG_get_nonce_fn get_nonce,
703 RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
705 if (drbg->state != DRBG_UNINITIALISED)
707 drbg->get_entropy = get_entropy;
708 drbg->cleanup_entropy = cleanup_entropy;
709 drbg->get_nonce = get_nonce;
710 drbg->cleanup_nonce = cleanup_nonce;
715 * Set the reseed interval.
717 * The drbg will reseed automatically whenever the number of generate
718 * requests exceeds the given reseed interval. If the reseed interval
719 * is 0, then this feature is disabled.
721 * Returns 1 on success, 0 on failure.
723 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
725 if (interval > MAX_RESEED_INTERVAL)
727 drbg->reseed_interval = interval;
732 * Set the reseed time interval.
734 * The drbg will reseed automatically whenever the time elapsed since
735 * the last reseeding exceeds the given reseed time interval. For safety,
736 * a reseeding will also occur if the clock has been reset to a smaller
739 * Returns 1 on success, 0 on failure.
741 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
743 if (interval > MAX_RESEED_TIME_INTERVAL)
745 drbg->reseed_time_interval = interval;
750 * Set the default values for reseed (time) intervals of new DRBG instances
752 * The default values can be set independently for master DRBG instances
753 * (without a parent) and slave DRBG instances (with parent).
755 * Returns 1 on success, 0 on failure.
758 int RAND_DRBG_set_reseed_defaults(
759 unsigned int _master_reseed_interval,
760 unsigned int _slave_reseed_interval,
761 time_t _master_reseed_time_interval,
762 time_t _slave_reseed_time_interval
765 if (_master_reseed_interval > MAX_RESEED_INTERVAL
766 || _slave_reseed_interval > MAX_RESEED_INTERVAL)
769 if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
770 || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
773 master_reseed_interval = _master_reseed_interval;
774 slave_reseed_interval = _slave_reseed_interval;
776 master_reseed_time_interval = _master_reseed_time_interval;
777 slave_reseed_time_interval = _slave_reseed_time_interval;
783 * Locks the given drbg. Locking 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_lock(RAND_DRBG *drbg)
790 if (drbg->lock != NULL)
791 return CRYPTO_THREAD_write_lock(drbg->lock);
797 * Unlocks the given drbg. Unlocking a drbg which does not have locking
798 * enabled is considered a successful no-op.
800 * Returns 1 on success, 0 on failure.
802 int rand_drbg_unlock(RAND_DRBG *drbg)
804 if (drbg->lock != NULL)
805 return CRYPTO_THREAD_unlock(drbg->lock);
811 * Enables locking for the given drbg
813 * Locking can only be enabled if the random generator
814 * is in the uninitialized state.
816 * Returns 1 on success, 0 on failure.
818 int rand_drbg_enable_locking(RAND_DRBG *drbg)
820 if (drbg->state != DRBG_UNINITIALISED) {
821 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
822 RAND_R_DRBG_ALREADY_INITIALIZED);
826 if (drbg->lock == NULL) {
827 if (drbg->parent != NULL && drbg->parent->lock == NULL) {
828 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
829 RAND_R_PARENT_LOCKING_NOT_ENABLED);
833 drbg->lock = CRYPTO_THREAD_lock_new();
834 if (drbg->lock == NULL) {
835 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
836 RAND_R_FAILED_TO_CREATE_LOCK);
845 * Get and set the EXDATA
847 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
849 return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
852 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
854 return CRYPTO_get_ex_data(&drbg->ex_data, idx);
859 * The following functions provide a RAND_METHOD that works on the
860 * global DRBG. They lock.
864 * Allocates a new global DRBG on the secure heap (if enabled) and
865 * initializes it with default settings.
867 * Returns a pointer to the new DRBG instance on success, NULL on failure.
869 static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
873 drbg = RAND_DRBG_secure_new(rand_drbg_type, rand_drbg_flags, parent);
877 /* Only the master DRBG needs to have a lock */
878 if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
881 /* enable reseed propagation */
882 drbg->enable_reseed_propagation = 1;
883 drbg->reseed_counter = 1;
886 * Ignore instantiation error to support just-in-time instantiation.
888 * The state of the drbg will be checked in RAND_DRBG_generate() and
889 * an automatic recovery is attempted.
891 (void)RAND_DRBG_instantiate(drbg,
892 (const unsigned char *) ossl_pers_string,
893 sizeof(ossl_pers_string) - 1);
897 RAND_DRBG_free(drbg);
902 * Initialize the global DRBGs on first use.
903 * Returns 1 on success, 0 on failure.
905 DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
908 * ensure that libcrypto is initialized, otherwise the
909 * DRBG locks are not cleaned up properly
911 if (!OPENSSL_init_crypto(0, NULL))
914 if (!CRYPTO_THREAD_init_local(&private_drbg, NULL))
917 if (!CRYPTO_THREAD_init_local(&public_drbg, NULL))
920 master_drbg = drbg_setup(NULL);
921 if (master_drbg == NULL)
927 CRYPTO_THREAD_cleanup_local(&public_drbg);
929 CRYPTO_THREAD_cleanup_local(&private_drbg);
933 /* Clean up the global DRBGs before exit */
934 void rand_drbg_cleanup_int(void)
936 if (master_drbg != NULL) {
937 RAND_DRBG_free(master_drbg);
940 CRYPTO_THREAD_cleanup_local(&private_drbg);
941 CRYPTO_THREAD_cleanup_local(&public_drbg);
945 void drbg_delete_thread_state(void)
949 drbg = CRYPTO_THREAD_get_local(&public_drbg);
950 CRYPTO_THREAD_set_local(&public_drbg, NULL);
951 RAND_DRBG_free(drbg);
953 drbg = CRYPTO_THREAD_get_local(&private_drbg);
954 CRYPTO_THREAD_set_local(&private_drbg, NULL);
955 RAND_DRBG_free(drbg);
958 /* Implements the default OpenSSL RAND_bytes() method */
959 static int drbg_bytes(unsigned char *out, int count)
962 RAND_DRBG *drbg = RAND_DRBG_get0_public();
967 ret = RAND_DRBG_bytes(drbg, out, count);
973 * Calculates the minimum length of a full entropy buffer
974 * which is necessary to seed (i.e. instantiate) the DRBG
977 size_t rand_drbg_seedlen(RAND_DRBG *drbg)
980 * If no os entropy source is available then RAND_seed(buffer, bufsize)
981 * is expected to succeed if and only if the buffer length satisfies
982 * the following requirements, which follow from the calculations
983 * in RAND_DRBG_instantiate().
985 size_t min_entropy = drbg->strength;
986 size_t min_entropylen = drbg->min_entropylen;
989 * Extra entropy for the random nonce in the absence of a
990 * get_nonce callback, see comment in RAND_DRBG_instantiate().
992 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
993 min_entropy += drbg->strength / 2;
994 min_entropylen += drbg->min_noncelen;
998 * Convert entropy requirement from bits to bytes
999 * (dividing by 8 without rounding upwards, because
1000 * all entropy requirements are divisible by 8).
1004 /* Return a value that satisfies both requirements */
1005 return min_entropy > min_entropylen ? min_entropy : min_entropylen;
1008 /* Implements the default OpenSSL RAND_add() method */
1009 static int drbg_add(const void *buf, int num, double randomness)
1012 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1019 if (num < 0 || randomness < 0.0)
1022 rand_drbg_lock(drbg);
1023 seedlen = rand_drbg_seedlen(drbg);
1025 buflen = (size_t)num;
1027 if (buflen < seedlen || randomness < (double) seedlen) {
1028 #if defined(OPENSSL_RAND_SEED_NONE)
1030 * If no os entropy source is available, a reseeding will fail
1031 * inevitably. So we use a trick to mix the buffer contents into
1032 * the DRBG state without forcing a reseeding: we generate a
1033 * dummy random byte, using the buffer content as additional data.
1034 * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
1036 unsigned char dummy[1];
1038 ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
1039 rand_drbg_unlock(drbg);
1043 * If an os entropy source is available then we declare the buffer content
1044 * as additional data by setting randomness to zero and trigger a regular
1052 if (randomness > (double)seedlen) {
1054 * The purpose of this check is to bound |randomness| by a
1055 * relatively small value in order to prevent an integer
1056 * overflow when multiplying by 8 in the rand_drbg_restart()
1057 * call below. Note that randomness is measured in bytes,
1058 * not bits, so this value corresponds to eight times the
1059 * security strength.
1061 randomness = (double)seedlen;
1064 ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
1065 rand_drbg_unlock(drbg);
1070 /* Implements the default OpenSSL RAND_seed() method */
1071 static int drbg_seed(const void *buf, int num)
1073 return drbg_add(buf, num, num);
1076 /* Implements the default OpenSSL RAND_status() method */
1077 static int drbg_status(void)
1080 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1085 rand_drbg_lock(drbg);
1086 ret = drbg->state == DRBG_READY ? 1 : 0;
1087 rand_drbg_unlock(drbg);
1092 * Get the master DRBG.
1093 * Returns pointer to the DRBG on success, NULL on failure.
1096 RAND_DRBG *RAND_DRBG_get0_master(void)
1098 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1105 * Get the public DRBG.
1106 * Returns pointer to the DRBG on success, NULL on failure.
1108 RAND_DRBG *RAND_DRBG_get0_public(void)
1112 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1115 drbg = CRYPTO_THREAD_get_local(&public_drbg);
1117 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1119 drbg = drbg_setup(master_drbg);
1120 CRYPTO_THREAD_set_local(&public_drbg, drbg);
1126 * Get the private DRBG.
1127 * Returns pointer to the DRBG on success, NULL on failure.
1129 RAND_DRBG *RAND_DRBG_get0_private(void)
1133 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1136 drbg = CRYPTO_THREAD_get_local(&private_drbg);
1138 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1140 drbg = drbg_setup(master_drbg);
1141 CRYPTO_THREAD_set_local(&private_drbg, drbg);
1146 RAND_METHOD rand_meth = {
1155 RAND_METHOD *RAND_OpenSSL(void)