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);
237 RAND_DRBG_free(drbg);
242 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
244 return rand_drbg_new(0, type, flags, parent);
247 RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent)
249 return rand_drbg_new(1, type, flags, parent);
253 * Uninstantiate |drbg| and free all memory.
255 void RAND_DRBG_free(RAND_DRBG *drbg)
260 if (drbg->meth != NULL)
261 drbg->meth->uninstantiate(drbg);
262 CRYPTO_THREAD_lock_free(drbg->lock);
263 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
266 OPENSSL_secure_clear_free(drbg, sizeof(*drbg));
268 OPENSSL_clear_free(drbg, sizeof(*drbg));
272 * Instantiate |drbg|, after it has been initialized. Use |pers| and
273 * |perslen| as prediction-resistance input.
275 * Requires that drbg->lock is already locked for write, if non-null.
277 * Returns 1 on success, 0 on failure.
279 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
280 const unsigned char *pers, size_t perslen)
282 unsigned char *nonce = NULL, *entropy = NULL;
283 size_t noncelen = 0, entropylen = 0;
284 size_t min_entropy = drbg->strength;
285 size_t min_entropylen = drbg->min_entropylen;
286 size_t max_entropylen = drbg->max_entropylen;
288 if (perslen > drbg->max_perslen) {
289 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
290 RAND_R_PERSONALISATION_STRING_TOO_LONG);
294 if (drbg->meth == NULL) {
295 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
296 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
300 if (drbg->state != DRBG_UNINITIALISED) {
301 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
302 drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE
303 : RAND_R_ALREADY_INSTANTIATED);
307 drbg->state = DRBG_ERROR;
310 * NIST SP800-90Ar1 section 9.1 says you can combine getting the entropy
311 * and nonce in 1 call by increasing the entropy with 50% and increasing
312 * the minimum length to accomadate the length of the nonce.
313 * We do this in case a nonce is require and get_nonce is NULL.
315 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
316 min_entropy += drbg->strength / 2;
317 min_entropylen += drbg->min_noncelen;
318 max_entropylen += drbg->max_noncelen;
321 drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
322 if (drbg->reseed_next_counter) {
323 drbg->reseed_next_counter++;
324 if(!drbg->reseed_next_counter)
325 drbg->reseed_next_counter = 1;
328 if (drbg->get_entropy != NULL)
329 entropylen = drbg->get_entropy(drbg, &entropy, min_entropy,
330 min_entropylen, max_entropylen, 0);
331 if (entropylen < min_entropylen
332 || entropylen > max_entropylen) {
333 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
337 if (drbg->min_noncelen > 0 && drbg->get_nonce != NULL) {
338 noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
339 drbg->min_noncelen, drbg->max_noncelen);
340 if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
341 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_NONCE);
346 if (!drbg->meth->instantiate(drbg, entropy, entropylen,
347 nonce, noncelen, pers, perslen)) {
348 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
352 drbg->state = DRBG_READY;
353 drbg->reseed_gen_counter = 0;
354 drbg->reseed_time = time(NULL);
355 tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
358 if (entropy != NULL && drbg->cleanup_entropy != NULL)
359 drbg->cleanup_entropy(drbg, entropy, entropylen);
360 if (nonce != NULL && drbg->cleanup_nonce != NULL)
361 drbg->cleanup_nonce(drbg, nonce, noncelen);
362 if (drbg->state == DRBG_READY)
368 * Uninstantiate |drbg|. Must be instantiated before it can be used.
370 * Requires that drbg->lock is already locked for write, if non-null.
372 * Returns 1 on success, 0 on failure.
374 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
376 if (drbg->meth == NULL) {
377 RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
378 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
382 /* Clear the entire drbg->ctr struct, then reset some important
383 * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
386 drbg->meth->uninstantiate(drbg);
387 return RAND_DRBG_set(drbg, drbg->type, drbg->flags);
391 * Reseed |drbg|, mixing in the specified data
393 * Requires that drbg->lock is already locked for write, if non-null.
395 * Returns 1 on success, 0 on failure.
397 int RAND_DRBG_reseed(RAND_DRBG *drbg,
398 const unsigned char *adin, size_t adinlen,
399 int prediction_resistance)
401 unsigned char *entropy = NULL;
402 size_t entropylen = 0;
404 if (drbg->state == DRBG_ERROR) {
405 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
408 if (drbg->state == DRBG_UNINITIALISED) {
409 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
415 } else if (adinlen > drbg->max_adinlen) {
416 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
420 drbg->state = DRBG_ERROR;
422 drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
423 if (drbg->reseed_next_counter) {
424 drbg->reseed_next_counter++;
425 if(!drbg->reseed_next_counter)
426 drbg->reseed_next_counter = 1;
429 if (drbg->get_entropy != NULL)
430 entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
431 drbg->min_entropylen,
432 drbg->max_entropylen,
433 prediction_resistance);
434 if (entropylen < drbg->min_entropylen
435 || entropylen > drbg->max_entropylen) {
436 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
440 if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
443 drbg->state = DRBG_READY;
444 drbg->reseed_gen_counter = 0;
445 drbg->reseed_time = time(NULL);
446 tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
449 if (entropy != NULL && drbg->cleanup_entropy != NULL)
450 drbg->cleanup_entropy(drbg, entropy, entropylen);
451 if (drbg->state == DRBG_READY)
457 * Restart |drbg|, using the specified entropy or additional input
459 * Tries its best to get the drbg instantiated by all means,
460 * regardless of its current state.
462 * Optionally, a |buffer| of |len| random bytes can be passed,
463 * which is assumed to contain at least |entropy| bits of entropy.
465 * If |entropy| > 0, the buffer content is used as entropy input.
467 * If |entropy| == 0, the buffer content is used as additional input
469 * Returns 1 on success, 0 on failure.
471 * This function is used internally only.
473 int rand_drbg_restart(RAND_DRBG *drbg,
474 const unsigned char *buffer, size_t len, size_t entropy)
477 const unsigned char *adin = NULL;
480 if (drbg->pool != NULL) {
481 RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
482 drbg->state = DRBG_ERROR;
483 rand_pool_free(drbg->pool);
488 if (buffer != NULL) {
490 if (drbg->max_entropylen < len) {
491 RANDerr(RAND_F_RAND_DRBG_RESTART,
492 RAND_R_ENTROPY_INPUT_TOO_LONG);
493 drbg->state = DRBG_ERROR;
497 if (entropy > 8 * len) {
498 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
499 drbg->state = DRBG_ERROR;
503 /* will be picked up by the rand_drbg_get_entropy() callback */
504 drbg->pool = rand_pool_attach(buffer, len, entropy);
505 if (drbg->pool == NULL)
508 if (drbg->max_adinlen < len) {
509 RANDerr(RAND_F_RAND_DRBG_RESTART,
510 RAND_R_ADDITIONAL_INPUT_TOO_LONG);
511 drbg->state = DRBG_ERROR;
519 /* repair error state */
520 if (drbg->state == DRBG_ERROR)
521 RAND_DRBG_uninstantiate(drbg);
523 /* repair uninitialized state */
524 if (drbg->state == DRBG_UNINITIALISED) {
525 /* reinstantiate drbg */
526 RAND_DRBG_instantiate(drbg,
527 (const unsigned char *) ossl_pers_string,
528 sizeof(ossl_pers_string) - 1);
529 /* already reseeded. prevent second reseeding below */
530 reseeded = (drbg->state == DRBG_READY);
533 /* refresh current state if entropy or additional input has been provided */
534 if (drbg->state == DRBG_READY) {
537 * mix in additional input without reseeding
539 * Similar to RAND_DRBG_reseed(), but the provided additional
540 * data |adin| is mixed into the current state without pulling
541 * entropy from the trusted entropy source using get_entropy().
542 * This is not a reseeding in the strict sense of NIST SP 800-90A.
544 drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
545 } else if (reseeded == 0) {
546 /* do a full reseeding if it has not been done yet above */
547 RAND_DRBG_reseed(drbg, NULL, 0, 0);
551 rand_pool_free(drbg->pool);
554 return drbg->state == DRBG_READY;
558 * Generate |outlen| bytes into the buffer at |out|. Reseed if we need
559 * to or if |prediction_resistance| is set. Additional input can be
560 * sent in |adin| and |adinlen|.
562 * Requires that drbg->lock is already locked for write, if non-null.
564 * Returns 1 on success, 0 on failure.
567 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
568 int prediction_resistance,
569 const unsigned char *adin, size_t adinlen)
571 int reseed_required = 0;
573 if (drbg->state != DRBG_READY) {
574 /* try to recover from previous errors */
575 rand_drbg_restart(drbg, NULL, 0, 0);
577 if (drbg->state == DRBG_ERROR) {
578 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
581 if (drbg->state == DRBG_UNINITIALISED) {
582 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
587 if (outlen > drbg->max_request) {
588 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
591 if (adinlen > drbg->max_adinlen) {
592 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
596 if (drbg->fork_count != rand_fork_count) {
597 drbg->fork_count = rand_fork_count;
601 if (drbg->reseed_interval > 0) {
602 if (drbg->reseed_gen_counter >= drbg->reseed_interval)
605 if (drbg->reseed_time_interval > 0) {
606 time_t now = time(NULL);
607 if (now < drbg->reseed_time
608 || now - drbg->reseed_time >= drbg->reseed_time_interval)
611 if (drbg->parent != NULL) {
612 unsigned int reseed_counter = tsan_load(&drbg->reseed_prop_counter);
613 if (reseed_counter > 0
614 && tsan_load(&drbg->parent->reseed_prop_counter)
619 if (reseed_required || prediction_resistance) {
620 if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
621 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
628 if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
629 drbg->state = DRBG_ERROR;
630 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
634 drbg->reseed_gen_counter++;
640 * Generates |outlen| random bytes and stores them in |out|. It will
641 * using the given |drbg| to generate the bytes.
643 * Requires that drbg->lock is already locked for write, if non-null.
645 * Returns 1 on success 0 on failure.
647 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
649 unsigned char *additional = NULL;
650 size_t additional_len;
654 additional_len = rand_drbg_get_additional_data(&additional, drbg->max_adinlen);
656 for ( ; outlen > 0; outlen -= chunk, out += chunk) {
658 if (chunk > drbg->max_request)
659 chunk = drbg->max_request;
660 ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
667 if (additional_len != 0)
668 OPENSSL_secure_clear_free(additional, additional_len);
674 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
676 * Setting the callbacks is allowed only if the drbg has not been
677 * initialized yet. Otherwise, the operation will fail.
679 * Returns 1 on success, 0 on failure.
681 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
682 RAND_DRBG_get_entropy_fn get_entropy,
683 RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
684 RAND_DRBG_get_nonce_fn get_nonce,
685 RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
687 if (drbg->state != DRBG_UNINITIALISED
688 || drbg->parent != NULL)
690 drbg->get_entropy = get_entropy;
691 drbg->cleanup_entropy = cleanup_entropy;
692 drbg->get_nonce = get_nonce;
693 drbg->cleanup_nonce = cleanup_nonce;
698 * Set the reseed interval.
700 * The drbg will reseed automatically whenever the number of generate
701 * requests exceeds the given reseed interval. If the reseed interval
702 * is 0, then this feature is disabled.
704 * Returns 1 on success, 0 on failure.
706 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
708 if (interval > MAX_RESEED_INTERVAL)
710 drbg->reseed_interval = interval;
715 * Set the reseed time interval.
717 * The drbg will reseed automatically whenever the time elapsed since
718 * the last reseeding exceeds the given reseed time interval. For safety,
719 * a reseeding will also occur if the clock has been reset to a smaller
722 * Returns 1 on success, 0 on failure.
724 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
726 if (interval > MAX_RESEED_TIME_INTERVAL)
728 drbg->reseed_time_interval = interval;
733 * Set the default values for reseed (time) intervals of new DRBG instances
735 * The default values can be set independently for master DRBG instances
736 * (without a parent) and slave DRBG instances (with parent).
738 * Returns 1 on success, 0 on failure.
741 int RAND_DRBG_set_reseed_defaults(
742 unsigned int _master_reseed_interval,
743 unsigned int _slave_reseed_interval,
744 time_t _master_reseed_time_interval,
745 time_t _slave_reseed_time_interval
748 if (_master_reseed_interval > MAX_RESEED_INTERVAL
749 || _slave_reseed_interval > MAX_RESEED_INTERVAL)
752 if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
753 || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
756 master_reseed_interval = _master_reseed_interval;
757 slave_reseed_interval = _slave_reseed_interval;
759 master_reseed_time_interval = _master_reseed_time_interval;
760 slave_reseed_time_interval = _slave_reseed_time_interval;
766 * Locks the given drbg. Locking a drbg which does not have locking
767 * enabled is considered a successful no-op.
769 * Returns 1 on success, 0 on failure.
771 int rand_drbg_lock(RAND_DRBG *drbg)
773 if (drbg->lock != NULL)
774 return CRYPTO_THREAD_write_lock(drbg->lock);
780 * Unlocks the given drbg. Unlocking a drbg which does not have locking
781 * enabled is considered a successful no-op.
783 * Returns 1 on success, 0 on failure.
785 int rand_drbg_unlock(RAND_DRBG *drbg)
787 if (drbg->lock != NULL)
788 return CRYPTO_THREAD_unlock(drbg->lock);
794 * Enables locking for the given drbg
796 * Locking can only be enabled if the random generator
797 * is in the uninitialized state.
799 * Returns 1 on success, 0 on failure.
801 int rand_drbg_enable_locking(RAND_DRBG *drbg)
803 if (drbg->state != DRBG_UNINITIALISED) {
804 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
805 RAND_R_DRBG_ALREADY_INITIALIZED);
809 if (drbg->lock == NULL) {
810 if (drbg->parent != NULL && drbg->parent->lock == NULL) {
811 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
812 RAND_R_PARENT_LOCKING_NOT_ENABLED);
816 drbg->lock = CRYPTO_THREAD_lock_new();
817 if (drbg->lock == NULL) {
818 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
819 RAND_R_FAILED_TO_CREATE_LOCK);
828 * Get and set the EXDATA
830 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
832 return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
835 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
837 return CRYPTO_get_ex_data(&drbg->ex_data, idx);
842 * The following functions provide a RAND_METHOD that works on the
843 * global DRBG. They lock.
847 * Allocates a new global DRBG on the secure heap (if enabled) and
848 * initializes it with default settings.
850 * Returns a pointer to the new DRBG instance on success, NULL on failure.
852 static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
856 drbg = RAND_DRBG_secure_new(rand_drbg_type, rand_drbg_flags, parent);
860 /* Only the master DRBG needs to have a lock */
861 if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
864 /* enable seed propagation */
865 tsan_store(&drbg->reseed_prop_counter, 1);
868 * Ignore instantiation error to support just-in-time instantiation.
870 * The state of the drbg will be checked in RAND_DRBG_generate() and
871 * an automatic recovery is attempted.
873 (void)RAND_DRBG_instantiate(drbg,
874 (const unsigned char *) ossl_pers_string,
875 sizeof(ossl_pers_string) - 1);
879 RAND_DRBG_free(drbg);
884 * Initialize the global DRBGs on first use.
885 * Returns 1 on success, 0 on failure.
887 DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
890 * ensure that libcrypto is initialized, otherwise the
891 * DRBG locks are not cleaned up properly
893 if (!OPENSSL_init_crypto(0, NULL))
896 if (!CRYPTO_THREAD_init_local(&private_drbg, NULL))
899 if (!CRYPTO_THREAD_init_local(&public_drbg, NULL))
902 master_drbg = drbg_setup(NULL);
903 if (master_drbg == NULL)
909 CRYPTO_THREAD_cleanup_local(&public_drbg);
911 CRYPTO_THREAD_cleanup_local(&private_drbg);
915 /* Clean up the global DRBGs before exit */
916 void rand_drbg_cleanup_int(void)
918 if (master_drbg != NULL) {
919 RAND_DRBG_free(master_drbg);
922 CRYPTO_THREAD_cleanup_local(&private_drbg);
923 CRYPTO_THREAD_cleanup_local(&public_drbg);
927 void drbg_delete_thread_state(void)
931 drbg = CRYPTO_THREAD_get_local(&public_drbg);
932 CRYPTO_THREAD_set_local(&public_drbg, NULL);
933 RAND_DRBG_free(drbg);
935 drbg = CRYPTO_THREAD_get_local(&private_drbg);
936 CRYPTO_THREAD_set_local(&private_drbg, NULL);
937 RAND_DRBG_free(drbg);
940 /* Implements the default OpenSSL RAND_bytes() method */
941 static int drbg_bytes(unsigned char *out, int count)
944 RAND_DRBG *drbg = RAND_DRBG_get0_public();
949 ret = RAND_DRBG_bytes(drbg, out, count);
955 * Calculates the minimum length of a full entropy buffer
956 * which is necessary to seed (i.e. instantiate) the DRBG
959 * NOTE: There is a copy of this function in drbgtest.c.
960 * If you change anything here, you need to update
961 * the copy accordingly.
963 static size_t rand_drbg_seedlen(RAND_DRBG *drbg)
966 * If no os entropy source is available then RAND_seed(buffer, bufsize)
967 * is expected to succeed if and only if the buffer length satisfies
968 * the following requirements, which follow from the calculations
969 * in RAND_DRBG_instantiate().
971 size_t min_entropy = drbg->strength;
972 size_t min_entropylen = drbg->min_entropylen;
975 * Extra entropy for the random nonce in the absence of a
976 * get_nonce callback, see comment in RAND_DRBG_instantiate().
978 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
979 min_entropy += drbg->strength / 2;
980 min_entropylen += drbg->min_noncelen;
984 * Convert entropy requirement from bits to bytes
985 * (dividing by 8 without rounding upwards, because
986 * all entropy requirements are divisible by 8).
990 /* Return a value that satisfies both requirements */
991 return min_entropy > min_entropylen ? min_entropy : min_entropylen;
994 /* Implements the default OpenSSL RAND_add() method */
995 static int drbg_add(const void *buf, int num, double randomness)
998 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1005 if (num < 0 || randomness < 0.0)
1008 rand_drbg_lock(drbg);
1009 seedlen = rand_drbg_seedlen(drbg);
1011 buflen = (size_t)num;
1013 if (buflen < seedlen || randomness < (double) seedlen) {
1014 #if defined(OPENSSL_RAND_SEED_NONE)
1016 * If no os entropy source is available, a reseeding will fail
1017 * inevitably. So we use a trick to mix the buffer contents into
1018 * the DRBG state without forcing a reseeding: we generate a
1019 * dummy random byte, using the buffer content as additional data.
1020 * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
1022 unsigned char dummy[1];
1024 ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
1025 rand_drbg_unlock(drbg);
1029 * If an os entropy source is avaible then we declare the buffer content
1030 * as additional data by setting randomness to zero and trigger a regular
1038 if (randomness > (double)seedlen) {
1040 * The purpose of this check is to bound |randomness| by a
1041 * relatively small value in order to prevent an integer
1042 * overflow when multiplying by 8 in the rand_drbg_restart()
1043 * call below. Note that randomness is measured in bytes,
1044 * not bits, so this value corresponds to eight times the
1045 * security strength.
1047 randomness = (double)seedlen;
1050 ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
1051 rand_drbg_unlock(drbg);
1056 /* Implements the default OpenSSL RAND_seed() method */
1057 static int drbg_seed(const void *buf, int num)
1059 return drbg_add(buf, num, num);
1062 /* Implements the default OpenSSL RAND_status() method */
1063 static int drbg_status(void)
1066 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1071 rand_drbg_lock(drbg);
1072 ret = drbg->state == DRBG_READY ? 1 : 0;
1073 rand_drbg_unlock(drbg);
1078 * Get the master DRBG.
1079 * Returns pointer to the DRBG on success, NULL on failure.
1082 RAND_DRBG *RAND_DRBG_get0_master(void)
1084 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1091 * Get the public DRBG.
1092 * Returns pointer to the DRBG on success, NULL on failure.
1094 RAND_DRBG *RAND_DRBG_get0_public(void)
1098 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1101 drbg = CRYPTO_THREAD_get_local(&public_drbg);
1103 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1105 drbg = drbg_setup(master_drbg);
1106 CRYPTO_THREAD_set_local(&public_drbg, drbg);
1112 * Get the private DRBG.
1113 * Returns pointer to the DRBG on success, NULL on failure.
1115 RAND_DRBG *RAND_DRBG_get0_private(void)
1119 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1122 drbg = CRYPTO_THREAD_get_local(&private_drbg);
1124 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1126 drbg = drbg_setup(master_drbg);
1127 CRYPTO_THREAD_set_local(&private_drbg, drbg);
1132 RAND_METHOD rand_meth = {
1141 RAND_METHOD *RAND_OpenSSL(void)