2 * Copyright 2011-2017 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"
19 * Support framework for NIST SP 800-90A DRBG, AES-CTR mode.
20 * The RAND_DRBG is OpenSSL's pointer to an instance of the DRBG.
22 * The OpenSSL model is to have new and free functions, and that new
23 * does all initialization. That is not the NIST model, which has
24 * instantiation and un-instantiate, and re-use within a new/free
25 * lifecycle. (No doubt this comes from the desire to support hardware
26 * DRBG, where allocation of resources on something like an HSM is
27 * a much bigger deal than just re-setting an allocated resource.)
31 * THE THREE SHARED DRBGs
33 * There are three shared DRBGs (master, public and private), which are
34 * accessed concurrently by all threads.
38 * Not used directly by the application, only for reseeding the two other
39 * DRBGs. It reseeds itself by pulling either randomness from os entropy
40 * sources or by consuming randomnes which was added by RAND_add()
42 static RAND_DRBG drbg_master;
46 * Used by default for generating random bytes using RAND_bytes().
48 static RAND_DRBG drbg_public;
52 * Used by default for generating private keys using RAND_priv_bytes()
54 static RAND_DRBG drbg_private;
58 * In addition there are DRBGs, which are not shared, but used only by a
59 * single thread at every time, for example the DRBGs which are owned by
60 * an SSL context. All DRBGs are organized in a hierarchical fashion
61 * with the <master> DRBG as root.
63 * This gives the following overall picture:
65 * <os entropy sources>
67 * RAND_add() ==> <master> \
68 * / \ | shared DRBGs (with locking)
69 * <public> <private> /
71 * <ssl> owned by an SSL context
75 * Before satisfying a generate request, a DRBG reseeds itself automatically
76 * if the number of generate requests since the last reseeding exceeds a
77 * certain threshold, the so called |reseed_interval|. This automatic
78 * reseeding can be disabled by setting the |reseed_interval| to 0.
82 * For the three shared DRBGs (and only for these) there is a way to reseed
83 * them manually by calling RAND_seed() (or RAND_add() with a positive
84 * |randomness| argument). This will immediately reseed the <master> DRBG.
85 * Its immediate children (<public> and <private> DRBG) will detect this
86 * on their next generate call and reseed, pulling randomness from <master>.
90 /* NIST SP 800-90A DRBG recommends the use of a personalization string. */
91 static const char ossl_pers_string[] = "OpenSSL NIST SP 800-90A DRBG";
93 static CRYPTO_ONCE rand_drbg_init = CRYPTO_ONCE_STATIC_INIT;
95 static int drbg_setup(RAND_DRBG *drbg, const char *name, RAND_DRBG *parent);
98 * Set/initialize |drbg| to be of type |nid|, with optional |flags|.
99 * Return -2 if the type is not supported, 1 on success and -1 on
102 int RAND_DRBG_set(RAND_DRBG *drbg, int nid, unsigned int flags)
106 drbg->state = DRBG_UNINITIALISED;
112 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
115 /* Uninitialized; that's okay. */
117 case NID_aes_128_ctr:
118 case NID_aes_192_ctr:
119 case NID_aes_256_ctr:
120 ret = ctr_init(drbg);
125 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG);
130 * Allocate memory and initialize a new DRBG. The |parent|, if not
131 * NULL, will be used to auto-seed this RAND_DRBG as needed.
133 * Returns a pointer to the new DRBG instance on success, NULL on failure.
135 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
137 RAND_DRBG *drbg = OPENSSL_zalloc(sizeof(*drbg));
140 RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
143 drbg->fork_count = rand_fork_count;
144 drbg->parent = parent;
145 if (RAND_DRBG_set(drbg, type, flags) < 0)
148 if (!RAND_DRBG_set_callbacks(drbg, rand_drbg_get_entropy,
149 rand_drbg_cleanup_entropy,
161 * Uninstantiate |drbg| and free all memory.
163 void RAND_DRBG_free(RAND_DRBG *drbg)
168 ctr_uninstantiate(drbg);
169 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
170 OPENSSL_clear_free(drbg, sizeof(*drbg));
174 * Instantiate |drbg|, after it has been initialized. Use |pers| and
175 * |perslen| as prediction-resistance input.
177 * Requires that drbg->lock is already locked for write, if non-null.
179 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
180 const unsigned char *pers, size_t perslen)
182 unsigned char *nonce = NULL, *entropy = NULL;
183 size_t noncelen = 0, entropylen = 0;
185 if (perslen > drbg->max_perslen) {
186 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
187 RAND_R_PERSONALISATION_STRING_TOO_LONG);
190 if (drbg->state != DRBG_UNINITIALISED) {
191 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
192 drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE
193 : RAND_R_ALREADY_INSTANTIATED);
197 drbg->state = DRBG_ERROR;
198 if (drbg->get_entropy != NULL)
199 entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
200 drbg->min_entropylen, drbg->max_entropylen);
201 if (entropylen < drbg->min_entropylen
202 || entropylen > drbg->max_entropylen) {
203 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
207 if (drbg->max_noncelen > 0 && drbg->get_nonce != NULL) {
208 noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
209 drbg->min_noncelen, drbg->max_noncelen);
210 if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
211 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
212 RAND_R_ERROR_RETRIEVING_NONCE);
217 if (!ctr_instantiate(drbg, entropy, entropylen,
218 nonce, noncelen, pers, perslen)) {
219 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
223 drbg->state = DRBG_READY;
224 drbg->generate_counter = 0;
226 if (drbg->reseed_counter > 0) {
227 if (drbg->parent == NULL)
228 drbg->reseed_counter++;
230 drbg->reseed_counter = drbg->parent->reseed_counter;
234 if (entropy != NULL && drbg->cleanup_entropy != NULL)
235 drbg->cleanup_entropy(drbg, entropy, entropylen);
236 if (nonce != NULL && drbg->cleanup_nonce!= NULL )
237 drbg->cleanup_nonce(drbg, nonce, noncelen);
238 if (drbg->pool != NULL) {
239 if (drbg->state == DRBG_READY) {
240 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
241 RAND_R_ERROR_ENTROPY_POOL_WAS_IGNORED);
242 drbg->state = DRBG_ERROR;
244 RAND_POOL_free(drbg->pool);
247 if (drbg->state == DRBG_READY)
253 * Uninstantiate |drbg|. Must be instantiated before it can be used.
255 * Requires that drbg->lock is already locked for write, if non-null.
257 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
259 int ret = ctr_uninstantiate(drbg);
261 drbg->state = DRBG_UNINITIALISED;
266 * Reseed |drbg|, mixing in the specified data
268 * Requires that drbg->lock is already locked for write, if non-null.
270 int RAND_DRBG_reseed(RAND_DRBG *drbg,
271 const unsigned char *adin, size_t adinlen)
273 unsigned char *entropy = NULL;
274 size_t entropylen = 0;
276 if (drbg->state == DRBG_ERROR) {
277 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
280 if (drbg->state == DRBG_UNINITIALISED) {
281 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
287 else if (adinlen > drbg->max_adinlen) {
288 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
292 drbg->state = DRBG_ERROR;
293 if (drbg->get_entropy != NULL)
294 entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
295 drbg->min_entropylen, drbg->max_entropylen);
296 if (entropylen < drbg->min_entropylen
297 || entropylen > drbg->max_entropylen) {
298 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
302 if (!ctr_reseed(drbg, entropy, entropylen, adin, adinlen))
305 drbg->state = DRBG_READY;
306 drbg->generate_counter = 0;
308 if (drbg->reseed_counter > 0) {
309 if (drbg->parent == NULL)
310 drbg->reseed_counter++;
312 drbg->reseed_counter = drbg->parent->reseed_counter;
316 if (entropy != NULL && drbg->cleanup_entropy != NULL)
317 drbg->cleanup_entropy(drbg, entropy, entropylen);
318 if (drbg->state == DRBG_READY)
324 * Restart |drbg|, using the specified entropy or additional input
326 * Tries its best to get the drbg instantiated by all means,
327 * regardless of its current state.
329 * Optionally, a |buffer| of |len| random bytes can be passed,
330 * which is assumed to contain at least |entropy| bits of entropy.
332 * If |entropy| > 0, the buffer content is used as entropy input.
334 * If |entropy| == 0, the buffer content is used as additional input
336 * Returns 1 on success, 0 on failure.
338 * This function is used internally only.
340 int rand_drbg_restart(RAND_DRBG *drbg,
341 const unsigned char *buffer, size_t len, size_t entropy)
344 const unsigned char *adin = NULL;
347 if (drbg->pool != NULL) {
348 RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
349 RAND_POOL_free(drbg->pool);
353 if (buffer != NULL) {
355 if (drbg->max_entropylen < len) {
356 RANDerr(RAND_F_RAND_DRBG_RESTART,
357 RAND_R_ENTROPY_INPUT_TOO_LONG);
361 if (entropy > 8 * len) {
362 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
366 /* will be picked up by the rand_drbg_get_entropy() callback */
367 drbg->pool = RAND_POOL_new(entropy, len, len);
368 if (drbg->pool == NULL)
371 RAND_POOL_add(drbg->pool, buffer, len, entropy);
373 if (drbg->max_adinlen < len) {
374 RANDerr(RAND_F_RAND_DRBG_RESTART,
375 RAND_R_ADDITIONAL_INPUT_TOO_LONG);
383 /* repair error state */
384 if (drbg->state == DRBG_ERROR) {
385 RAND_DRBG_uninstantiate(drbg);
386 /* The drbg->ctr member needs to be reinitialized before reinstantiation */
387 RAND_DRBG_set(drbg, drbg->nid, drbg->flags);
390 /* repair uninitialized state */
391 if (drbg->state == DRBG_UNINITIALISED) {
392 /* reinstantiate drbg */
393 RAND_DRBG_instantiate(drbg,
394 (const unsigned char *) ossl_pers_string,
395 sizeof(ossl_pers_string) - 1);
396 /* already reseeded. prevent second reseeding below */
397 reseeded = (drbg->state == DRBG_READY);
400 /* refresh current state if entropy or additional input has been provided */
401 if (drbg->state == DRBG_READY) {
404 * mix in additional input without reseeding
406 * Similar to RAND_DRBG_reseed(), but the provided additional
407 * data |adin| is mixed into the current state without pulling
408 * entropy from the trusted entropy source using get_entropy().
409 * This is not a reseeding in the strict sense of NIST SP 800-90A.
411 ctr_reseed(drbg, adin, adinlen, NULL, 0);
412 } else if (reseeded == 0) {
413 /* do a full reseeding if it has not been done yet above */
414 RAND_DRBG_reseed(drbg, NULL, 0);
418 /* check whether a given entropy pool was cleared properly during reseed */
419 if (drbg->pool != NULL) {
420 drbg->state = DRBG_ERROR;
421 RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
422 RAND_POOL_free(drbg->pool);
427 return drbg->state == DRBG_READY;
431 * Generate |outlen| bytes into the buffer at |out|. Reseed if we need
432 * to or if |prediction_resistance| is set. Additional input can be
433 * sent in |adin| and |adinlen|.
435 * Requires that drbg->lock is already locked for write, if non-null.
437 * Returns 1 on success, 0 on failure.
440 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
441 int prediction_resistance,
442 const unsigned char *adin, size_t adinlen)
444 int reseed_required = 0;
446 if (drbg->state != DRBG_READY) {
447 /* try to recover from previous errors */
448 rand_drbg_restart(drbg, NULL, 0, 0);
450 if (drbg->state == DRBG_ERROR) {
451 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
454 if (drbg->state == DRBG_UNINITIALISED) {
455 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
460 if (outlen > drbg->max_request) {
461 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
464 if (adinlen > drbg->max_adinlen) {
465 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
469 if (drbg->fork_count != rand_fork_count) {
470 drbg->fork_count = rand_fork_count;
474 if (drbg->reseed_interval > 0) {
475 if (drbg->generate_counter >= drbg->reseed_interval)
479 if (drbg->reseed_counter > 0 && drbg->parent != NULL) {
480 if (drbg->reseed_counter != drbg->parent->reseed_counter)
484 if (reseed_required || prediction_resistance) {
485 if (!RAND_DRBG_reseed(drbg, adin, adinlen)) {
486 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
493 if (!ctr_generate(drbg, out, outlen, adin, adinlen)) {
494 drbg->state = DRBG_ERROR;
495 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
499 drbg->generate_counter++;
505 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
507 * In the following, the signature and the semantics of the
508 * get_entropy() and cleanup_entropy() callbacks are explained.
512 * size_t get_entropy(RAND_DRBG *ctx,
513 * unsigned char **pout,
515 * size_t min_len, size_t max_len);
517 * This is a request to allocate and fill a buffer of size
518 * |min_len| <= size <= |max_len| (in bytes) which contains
519 * at least |entropy| bits of randomness. The buffer's address is
520 * to be returned in |*pout| and the number of collected
521 * randomness bytes (which may be less than the allocated size
522 * of the buffer) as return value.
524 * If the callback fails to acquire at least |entropy| bits of
525 * randomness, it shall return a buffer length of 0.
529 * void cleanup_entropy(RAND_DRBG *ctx,
530 * unsigned char *out, size_t outlen);
532 * A request to clear and free the buffer allocated by get_entropy().
533 * The values |out| and |outlen| are expected to be the random buffer's
534 * address and length, as returned by the get_entropy() callback.
536 * GET_NONCE, CLEANUP_NONCE
538 * Signature and semantics of the get_nonce() and cleanup_nonce()
539 * callbacks are analogous to get_entropy() and cleanup_entropy().
540 * Currently, the nonce is used only for the known answer tests.
542 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
543 RAND_DRBG_get_entropy_fn get_entropy,
544 RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
545 RAND_DRBG_get_nonce_fn get_nonce,
546 RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
548 if (drbg->state != DRBG_UNINITIALISED)
550 drbg->get_entropy = get_entropy;
551 drbg->cleanup_entropy = cleanup_entropy;
552 drbg->get_nonce = get_nonce;
553 drbg->cleanup_nonce = cleanup_nonce;
558 * Set the reseed interval.
560 * The drbg will reseed automatically whenever the number of generate
561 * requests exceeds the given reseed interval. If the reseed interval
562 * is 0, then this automatic reseeding is disabled.
564 * Returns 1 on success, 0 on failure.
566 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
568 if (interval > MAX_RESEED_INTERVAL)
570 drbg->reseed_interval = interval;
575 * Get and set the EXDATA
577 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
579 return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
582 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
584 return CRYPTO_get_ex_data(&drbg->ex_data, idx);
589 * The following functions provide a RAND_METHOD that works on the
590 * global DRBG. They lock.
594 * Initializes the given global DRBG with default settings.
595 * A global lock for the DRBG is created with the given name.
597 * Returns a pointer to the new DRBG instance on success, NULL on failure.
599 static int drbg_setup(RAND_DRBG *drbg, const char *name, RAND_DRBG *parent)
603 if (name == NULL || drbg->lock != NULL) {
604 RANDerr(RAND_F_DRBG_SETUP, ERR_R_INTERNAL_ERROR);
608 drbg->lock = CRYPTO_THREAD_glock_new(name);
609 if (drbg->lock == NULL) {
610 RANDerr(RAND_F_DRBG_SETUP, RAND_R_FAILED_TO_CREATE_LOCK);
614 ret &= RAND_DRBG_set(drbg,
615 RAND_DRBG_NID, RAND_DRBG_FLAG_CTR_USE_DF) == 1;
616 ret &= RAND_DRBG_set_callbacks(drbg, rand_drbg_get_entropy,
617 rand_drbg_cleanup_entropy, NULL, NULL) == 1;
620 drbg->reseed_interval = MASTER_RESEED_INTERVAL;
622 drbg->parent = parent;
623 drbg->reseed_interval = SLAVE_RESEED_INTERVAL;
626 /* enable seed propagation */
627 drbg->reseed_counter = 1;
630 * Ignore instantiation error so support just-in-time instantiation.
632 * The state of the drbg will be checked in RAND_DRBG_generate() and
633 * an automatic recovery is attempted.
635 RAND_DRBG_instantiate(drbg,
636 (const unsigned char *) ossl_pers_string,
637 sizeof(ossl_pers_string) - 1);
642 * Initialize the global DRBGs on first use.
643 * Returns 1 on success, 0 on failure.
645 DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
649 ret &= drbg_setup(&drbg_master, "drbg_master", NULL);
650 ret &= drbg_setup(&drbg_public, "drbg_public", &drbg_master);
651 ret &= drbg_setup(&drbg_private, "drbg_private", &drbg_master);
656 /* Cleans up the given global DRBG */
657 static void drbg_cleanup(RAND_DRBG *drbg)
659 CRYPTO_THREAD_lock_free(drbg->lock);
660 RAND_DRBG_uninstantiate(drbg);
663 /* Clean up the global DRBGs before exit */
664 void rand_drbg_cleanup_int(void)
666 drbg_cleanup(&drbg_private);
667 drbg_cleanup(&drbg_public);
668 drbg_cleanup(&drbg_master);
671 /* Implements the default OpenSSL RAND_bytes() method */
672 static int drbg_bytes(unsigned char *out, int count)
676 RAND_DRBG *drbg = RAND_DRBG_get0_public();
681 CRYPTO_THREAD_write_lock(drbg->lock);
682 if (drbg->state == DRBG_UNINITIALISED)
685 for ( ; count > 0; count -= chunk, out += chunk) {
687 if (chunk > drbg->max_request)
688 chunk = drbg->max_request;
689 ret = RAND_DRBG_generate(drbg, out, chunk, 0, NULL, 0);
696 CRYPTO_THREAD_unlock(drbg->lock);
700 /* Implements the default OpenSSL RAND_add() method */
701 static int drbg_add(const void *buf, int num, double randomness)
704 RAND_DRBG *drbg = RAND_DRBG_get0_master();
709 if (num < 0 || randomness < 0.0)
712 if (randomness > (double)drbg->max_entropylen) {
714 * The purpose of this check is to bound |randomness| by a
715 * relatively small value in order to prevent an integer
716 * overflow when multiplying by 8 in the rand_drbg_restart()
722 CRYPTO_THREAD_write_lock(drbg->lock);
723 ret = rand_drbg_restart(drbg, buf,
724 (size_t)(unsigned int)num,
725 (size_t)(8*randomness));
726 CRYPTO_THREAD_unlock(drbg->lock);
731 /* Implements the default OpenSSL RAND_seed() method */
732 static int drbg_seed(const void *buf, int num)
734 return drbg_add(buf, num, num);
737 /* Implements the default OpenSSL RAND_status() method */
738 static int drbg_status(void)
741 RAND_DRBG *drbg = RAND_DRBG_get0_master();
746 CRYPTO_THREAD_write_lock(drbg->lock);
747 ret = drbg->state == DRBG_READY ? 1 : 0;
748 CRYPTO_THREAD_unlock(drbg->lock);
753 * Get the master DRBG.
754 * Returns pointer to the DRBG on success, NULL on failure.
757 RAND_DRBG *RAND_DRBG_get0_master(void)
759 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
766 * Get the public DRBG.
767 * Returns pointer to the DRBG on success, NULL on failure.
769 RAND_DRBG *RAND_DRBG_get0_public(void)
771 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
778 * Get the private DRBG.
779 * Returns pointer to the DRBG on success, NULL on failure.
781 RAND_DRBG *RAND_DRBG_get0_private(void)
783 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
786 return &drbg_private;
789 RAND_METHOD rand_meth = {
798 RAND_METHOD *RAND_OpenSSL(void)