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 drbg->state = DRBG_ERROR;
378 RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
379 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
383 /* Clear the entire drbg->ctr struct, then reset some important
384 * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
387 drbg->meth->uninstantiate(drbg);
388 return RAND_DRBG_set(drbg, drbg->type, drbg->flags);
392 * Reseed |drbg|, mixing in the specified data
394 * Requires that drbg->lock is already locked for write, if non-null.
396 * Returns 1 on success, 0 on failure.
398 int RAND_DRBG_reseed(RAND_DRBG *drbg,
399 const unsigned char *adin, size_t adinlen,
400 int prediction_resistance)
402 unsigned char *entropy = NULL;
403 size_t entropylen = 0;
405 if (drbg->state == DRBG_ERROR) {
406 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
409 if (drbg->state == DRBG_UNINITIALISED) {
410 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
416 } else if (adinlen > drbg->max_adinlen) {
417 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
421 drbg->state = DRBG_ERROR;
423 drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
424 if (drbg->reseed_next_counter) {
425 drbg->reseed_next_counter++;
426 if(!drbg->reseed_next_counter)
427 drbg->reseed_next_counter = 1;
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->reseed_gen_counter = 0;
446 drbg->reseed_time = time(NULL);
447 tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
450 if (entropy != NULL && drbg->cleanup_entropy != NULL)
451 drbg->cleanup_entropy(drbg, entropy, entropylen);
452 if (drbg->state == DRBG_READY)
458 * Restart |drbg|, using the specified entropy or additional input
460 * Tries its best to get the drbg instantiated by all means,
461 * regardless of its current state.
463 * Optionally, a |buffer| of |len| random bytes can be passed,
464 * which is assumed to contain at least |entropy| bits of entropy.
466 * If |entropy| > 0, the buffer content is used as entropy input.
468 * If |entropy| == 0, the buffer content is used as additional input
470 * Returns 1 on success, 0 on failure.
472 * This function is used internally only.
474 int rand_drbg_restart(RAND_DRBG *drbg,
475 const unsigned char *buffer, size_t len, size_t entropy)
478 const unsigned char *adin = NULL;
481 if (drbg->pool != NULL) {
482 RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
483 drbg->state = DRBG_ERROR;
484 rand_pool_free(drbg->pool);
489 if (buffer != NULL) {
491 if (drbg->max_entropylen < len) {
492 RANDerr(RAND_F_RAND_DRBG_RESTART,
493 RAND_R_ENTROPY_INPUT_TOO_LONG);
494 drbg->state = DRBG_ERROR;
498 if (entropy > 8 * len) {
499 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
500 drbg->state = DRBG_ERROR;
504 /* will be picked up by the rand_drbg_get_entropy() callback */
505 drbg->pool = rand_pool_attach(buffer, len, entropy);
506 if (drbg->pool == NULL)
509 if (drbg->max_adinlen < len) {
510 RANDerr(RAND_F_RAND_DRBG_RESTART,
511 RAND_R_ADDITIONAL_INPUT_TOO_LONG);
512 drbg->state = DRBG_ERROR;
520 /* repair error state */
521 if (drbg->state == DRBG_ERROR)
522 RAND_DRBG_uninstantiate(drbg);
524 /* repair uninitialized state */
525 if (drbg->state == DRBG_UNINITIALISED) {
526 /* reinstantiate drbg */
527 RAND_DRBG_instantiate(drbg,
528 (const unsigned char *) ossl_pers_string,
529 sizeof(ossl_pers_string) - 1);
530 /* already reseeded. prevent second reseeding below */
531 reseeded = (drbg->state == DRBG_READY);
534 /* refresh current state if entropy or additional input has been provided */
535 if (drbg->state == DRBG_READY) {
538 * mix in additional input without reseeding
540 * Similar to RAND_DRBG_reseed(), but the provided additional
541 * data |adin| is mixed into the current state without pulling
542 * entropy from the trusted entropy source using get_entropy().
543 * This is not a reseeding in the strict sense of NIST SP 800-90A.
545 drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
546 } else if (reseeded == 0) {
547 /* do a full reseeding if it has not been done yet above */
548 RAND_DRBG_reseed(drbg, NULL, 0, 0);
552 rand_pool_free(drbg->pool);
555 return drbg->state == DRBG_READY;
559 * Generate |outlen| bytes into the buffer at |out|. Reseed if we need
560 * to or if |prediction_resistance| is set. Additional input can be
561 * sent in |adin| and |adinlen|.
563 * Requires that drbg->lock is already locked for write, if non-null.
565 * Returns 1 on success, 0 on failure.
568 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
569 int prediction_resistance,
570 const unsigned char *adin, size_t adinlen)
572 int reseed_required = 0;
574 if (drbg->state != DRBG_READY) {
575 /* try to recover from previous errors */
576 rand_drbg_restart(drbg, NULL, 0, 0);
578 if (drbg->state == DRBG_ERROR) {
579 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
582 if (drbg->state == DRBG_UNINITIALISED) {
583 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
588 if (outlen > drbg->max_request) {
589 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
592 if (adinlen > drbg->max_adinlen) {
593 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
597 if (drbg->fork_count != rand_fork_count) {
598 drbg->fork_count = rand_fork_count;
602 if (drbg->reseed_interval > 0) {
603 if (drbg->reseed_gen_counter >= drbg->reseed_interval)
606 if (drbg->reseed_time_interval > 0) {
607 time_t now = time(NULL);
608 if (now < drbg->reseed_time
609 || now - drbg->reseed_time >= drbg->reseed_time_interval)
612 if (drbg->parent != NULL) {
613 unsigned int reseed_counter = tsan_load(&drbg->reseed_prop_counter);
614 if (reseed_counter > 0
615 && tsan_load(&drbg->parent->reseed_prop_counter)
620 if (reseed_required || prediction_resistance) {
621 if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
622 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
629 if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
630 drbg->state = DRBG_ERROR;
631 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
635 drbg->reseed_gen_counter++;
641 * Generates |outlen| random bytes and stores them in |out|. It will
642 * using the given |drbg| to generate the bytes.
644 * Requires that drbg->lock is already locked for write, if non-null.
646 * Returns 1 on success 0 on failure.
648 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
650 unsigned char *additional = NULL;
651 size_t additional_len;
655 additional_len = rand_drbg_get_additional_data(&additional, drbg->max_adinlen);
657 for ( ; outlen > 0; outlen -= chunk, out += chunk) {
659 if (chunk > drbg->max_request)
660 chunk = drbg->max_request;
661 ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
668 if (additional_len != 0)
669 OPENSSL_secure_clear_free(additional, additional_len);
675 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
677 * Setting the callbacks is allowed only if the drbg has not been
678 * initialized yet. Otherwise, the operation will fail.
680 * Returns 1 on success, 0 on failure.
682 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
683 RAND_DRBG_get_entropy_fn get_entropy,
684 RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
685 RAND_DRBG_get_nonce_fn get_nonce,
686 RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
688 if (drbg->state != DRBG_UNINITIALISED
689 || drbg->parent != NULL)
691 drbg->get_entropy = get_entropy;
692 drbg->cleanup_entropy = cleanup_entropy;
693 drbg->get_nonce = get_nonce;
694 drbg->cleanup_nonce = cleanup_nonce;
699 * Set the reseed interval.
701 * The drbg will reseed automatically whenever the number of generate
702 * requests exceeds the given reseed interval. If the reseed interval
703 * is 0, then this feature is disabled.
705 * Returns 1 on success, 0 on failure.
707 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
709 if (interval > MAX_RESEED_INTERVAL)
711 drbg->reseed_interval = interval;
716 * Set the reseed time interval.
718 * The drbg will reseed automatically whenever the time elapsed since
719 * the last reseeding exceeds the given reseed time interval. For safety,
720 * a reseeding will also occur if the clock has been reset to a smaller
723 * Returns 1 on success, 0 on failure.
725 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
727 if (interval > MAX_RESEED_TIME_INTERVAL)
729 drbg->reseed_time_interval = interval;
734 * Set the default values for reseed (time) intervals of new DRBG instances
736 * The default values can be set independently for master DRBG instances
737 * (without a parent) and slave DRBG instances (with parent).
739 * Returns 1 on success, 0 on failure.
742 int RAND_DRBG_set_reseed_defaults(
743 unsigned int _master_reseed_interval,
744 unsigned int _slave_reseed_interval,
745 time_t _master_reseed_time_interval,
746 time_t _slave_reseed_time_interval
749 if (_master_reseed_interval > MAX_RESEED_INTERVAL
750 || _slave_reseed_interval > MAX_RESEED_INTERVAL)
753 if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
754 || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
757 master_reseed_interval = _master_reseed_interval;
758 slave_reseed_interval = _slave_reseed_interval;
760 master_reseed_time_interval = _master_reseed_time_interval;
761 slave_reseed_time_interval = _slave_reseed_time_interval;
767 * Locks the given drbg. Locking a drbg which does not have locking
768 * enabled is considered a successful no-op.
770 * Returns 1 on success, 0 on failure.
772 int rand_drbg_lock(RAND_DRBG *drbg)
774 if (drbg->lock != NULL)
775 return CRYPTO_THREAD_write_lock(drbg->lock);
781 * Unlocks the given drbg. Unlocking a drbg which does not have locking
782 * enabled is considered a successful no-op.
784 * Returns 1 on success, 0 on failure.
786 int rand_drbg_unlock(RAND_DRBG *drbg)
788 if (drbg->lock != NULL)
789 return CRYPTO_THREAD_unlock(drbg->lock);
795 * Enables locking for the given drbg
797 * Locking can only be enabled if the random generator
798 * is in the uninitialized state.
800 * Returns 1 on success, 0 on failure.
802 int rand_drbg_enable_locking(RAND_DRBG *drbg)
804 if (drbg->state != DRBG_UNINITIALISED) {
805 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
806 RAND_R_DRBG_ALREADY_INITIALIZED);
810 if (drbg->lock == NULL) {
811 if (drbg->parent != NULL && drbg->parent->lock == NULL) {
812 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
813 RAND_R_PARENT_LOCKING_NOT_ENABLED);
817 drbg->lock = CRYPTO_THREAD_lock_new();
818 if (drbg->lock == NULL) {
819 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
820 RAND_R_FAILED_TO_CREATE_LOCK);
829 * Get and set the EXDATA
831 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
833 return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
836 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
838 return CRYPTO_get_ex_data(&drbg->ex_data, idx);
843 * The following functions provide a RAND_METHOD that works on the
844 * global DRBG. They lock.
848 * Allocates a new global DRBG on the secure heap (if enabled) and
849 * initializes it with default settings.
851 * Returns a pointer to the new DRBG instance on success, NULL on failure.
853 static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
857 drbg = RAND_DRBG_secure_new(rand_drbg_type, rand_drbg_flags, parent);
861 /* Only the master DRBG needs to have a lock */
862 if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
865 /* enable seed propagation */
866 tsan_store(&drbg->reseed_prop_counter, 1);
869 * Ignore instantiation error to support just-in-time instantiation.
871 * The state of the drbg will be checked in RAND_DRBG_generate() and
872 * an automatic recovery is attempted.
874 (void)RAND_DRBG_instantiate(drbg,
875 (const unsigned char *) ossl_pers_string,
876 sizeof(ossl_pers_string) - 1);
880 RAND_DRBG_free(drbg);
885 * Initialize the global DRBGs on first use.
886 * Returns 1 on success, 0 on failure.
888 DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
891 * ensure that libcrypto is initialized, otherwise the
892 * DRBG locks are not cleaned up properly
894 if (!OPENSSL_init_crypto(0, NULL))
897 if (!CRYPTO_THREAD_init_local(&private_drbg, NULL))
900 if (!CRYPTO_THREAD_init_local(&public_drbg, NULL))
903 master_drbg = drbg_setup(NULL);
904 if (master_drbg == NULL)
910 CRYPTO_THREAD_cleanup_local(&public_drbg);
912 CRYPTO_THREAD_cleanup_local(&private_drbg);
916 /* Clean up the global DRBGs before exit */
917 void rand_drbg_cleanup_int(void)
919 if (master_drbg != NULL) {
920 RAND_DRBG_free(master_drbg);
923 CRYPTO_THREAD_cleanup_local(&private_drbg);
924 CRYPTO_THREAD_cleanup_local(&public_drbg);
928 void drbg_delete_thread_state(void)
932 drbg = CRYPTO_THREAD_get_local(&public_drbg);
933 CRYPTO_THREAD_set_local(&public_drbg, NULL);
934 RAND_DRBG_free(drbg);
936 drbg = CRYPTO_THREAD_get_local(&private_drbg);
937 CRYPTO_THREAD_set_local(&private_drbg, NULL);
938 RAND_DRBG_free(drbg);
941 /* Implements the default OpenSSL RAND_bytes() method */
942 static int drbg_bytes(unsigned char *out, int count)
945 RAND_DRBG *drbg = RAND_DRBG_get0_public();
950 ret = RAND_DRBG_bytes(drbg, out, count);
956 * Calculates the minimum length of a full entropy buffer
957 * which is necessary to seed (i.e. instantiate) the DRBG
960 * NOTE: There is a copy of this function in drbgtest.c.
961 * If you change anything here, you need to update
962 * the copy accordingly.
964 static size_t rand_drbg_seedlen(RAND_DRBG *drbg)
967 * If no os entropy source is available then RAND_seed(buffer, bufsize)
968 * is expected to succeed if and only if the buffer length satisfies
969 * the following requirements, which follow from the calculations
970 * in RAND_DRBG_instantiate().
972 size_t min_entropy = drbg->strength;
973 size_t min_entropylen = drbg->min_entropylen;
976 * Extra entropy for the random nonce in the absence of a
977 * get_nonce callback, see comment in RAND_DRBG_instantiate().
979 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
980 min_entropy += drbg->strength / 2;
981 min_entropylen += drbg->min_noncelen;
985 * Convert entropy requirement from bits to bytes
986 * (dividing by 8 without rounding upwards, because
987 * all entropy requirements are divisible by 8).
991 /* Return a value that satisfies both requirements */
992 return min_entropy > min_entropylen ? min_entropy : min_entropylen;
995 /* Implements the default OpenSSL RAND_add() method */
996 static int drbg_add(const void *buf, int num, double randomness)
999 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1006 if (num < 0 || randomness < 0.0)
1009 rand_drbg_lock(drbg);
1010 seedlen = rand_drbg_seedlen(drbg);
1012 buflen = (size_t)num;
1014 if (buflen < seedlen || randomness < (double) seedlen) {
1015 #if defined(OPENSSL_RAND_SEED_NONE)
1017 * If no os entropy source is available, a reseeding will fail
1018 * inevitably. So we use a trick to mix the buffer contents into
1019 * the DRBG state without forcing a reseeding: we generate a
1020 * dummy random byte, using the buffer content as additional data.
1021 * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
1023 unsigned char dummy[1];
1025 ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
1026 rand_drbg_unlock(drbg);
1030 * If an os entropy source is avaible then we declare the buffer content
1031 * as additional data by setting randomness to zero and trigger a regular
1039 if (randomness > (double)seedlen) {
1041 * The purpose of this check is to bound |randomness| by a
1042 * relatively small value in order to prevent an integer
1043 * overflow when multiplying by 8 in the rand_drbg_restart()
1044 * call below. Note that randomness is measured in bytes,
1045 * not bits, so this value corresponds to eight times the
1046 * security strength.
1048 randomness = (double)seedlen;
1051 ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
1052 rand_drbg_unlock(drbg);
1057 /* Implements the default OpenSSL RAND_seed() method */
1058 static int drbg_seed(const void *buf, int num)
1060 return drbg_add(buf, num, num);
1063 /* Implements the default OpenSSL RAND_status() method */
1064 static int drbg_status(void)
1067 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1072 rand_drbg_lock(drbg);
1073 ret = drbg->state == DRBG_READY ? 1 : 0;
1074 rand_drbg_unlock(drbg);
1079 * Get the master DRBG.
1080 * Returns pointer to the DRBG on success, NULL on failure.
1083 RAND_DRBG *RAND_DRBG_get0_master(void)
1085 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1092 * Get the public DRBG.
1093 * Returns pointer to the DRBG on success, NULL on failure.
1095 RAND_DRBG *RAND_DRBG_get0_public(void)
1099 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1102 drbg = CRYPTO_THREAD_get_local(&public_drbg);
1104 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1106 drbg = drbg_setup(master_drbg);
1107 CRYPTO_THREAD_set_local(&public_drbg, drbg);
1113 * Get the private DRBG.
1114 * Returns pointer to the DRBG on success, NULL on failure.
1116 RAND_DRBG *RAND_DRBG_get0_private(void)
1120 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1123 drbg = CRYPTO_THREAD_get_local(&private_drbg);
1125 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1127 drbg = drbg_setup(master_drbg);
1128 CRYPTO_THREAD_set_local(&private_drbg, drbg);
1133 RAND_METHOD rand_meth = {
1142 RAND_METHOD *RAND_OpenSSL(void)