2 * Copyright 1995-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
12 #include "internal/cryptlib.h"
13 #include <openssl/opensslconf.h>
14 #include "internal/rand_int.h"
15 #include <openssl/engine.h>
16 #include "internal/thread_once.h"
20 #ifndef OPENSSL_NO_ENGINE
21 /* non-NULL if default_RAND_meth is ENGINE-provided */
22 static ENGINE *funct_ref;
23 static CRYPTO_RWLOCK *rand_engine_lock;
25 static CRYPTO_RWLOCK *rand_meth_lock;
26 static const RAND_METHOD *default_RAND_meth;
27 static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
31 static CRYPTO_RWLOCK *rand_nonce_lock;
32 static int rand_nonce_count;
34 static int rand_cleaning_up = 0;
36 #ifdef OPENSSL_RAND_SEED_RDTSC
38 * IMPORTANT NOTE: It is not currently possible to use this code
39 * because we are not sure about the amount of randomness it provides.
40 * Some SP900 tests have been run, but there is internal skepticism.
41 * So for now this code is not used.
43 # error "RDTSC enabled? Should not be possible!"
46 * Acquire entropy from high-speed clock
48 * Since we get some randomness from the low-order bits of the
49 * high-speed clock, it can help.
51 * Returns the total entropy count, if it exceeds the requested
52 * entropy count. Otherwise, returns an entropy count of 0.
54 size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool)
59 if ((OPENSSL_ia32cap_P[0] & (1 << 4)) != 0) {
60 for (i = 0; i < TSC_READ_COUNT; i++) {
61 c = (unsigned char)(OPENSSL_rdtsc() & 0xFF);
62 rand_pool_add(pool, &c, 1, 4);
65 return rand_pool_entropy_available(pool);
69 #ifdef OPENSSL_RAND_SEED_RDCPU
70 size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len);
71 size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len);
73 extern unsigned int OPENSSL_ia32cap_P[];
76 * Acquire entropy using Intel-specific cpu instructions
78 * Uses the RDSEED instruction if available, otherwise uses
79 * RDRAND if available.
81 * For the differences between RDSEED and RDRAND, and why RDSEED
82 * is the preferred choice, see https://goo.gl/oK3KcN
84 * Returns the total entropy count, if it exceeds the requested
85 * entropy count. Otherwise, returns an entropy count of 0.
87 size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool)
90 unsigned char *buffer;
92 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
93 if (bytes_needed > 0) {
94 buffer = rand_pool_add_begin(pool, bytes_needed);
97 /* Whichever comes first, use RDSEED, RDRAND or nothing */
98 if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
99 if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed)
101 rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
103 } else if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
104 if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed)
106 rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
109 rand_pool_add_end(pool, 0, 0);
114 return rand_pool_entropy_available(pool);
120 * Implements the get_entropy() callback (see RAND_DRBG_set_callbacks())
122 * If the DRBG has a parent, then the required amount of entropy input
123 * is fetched using the parent's RAND_DRBG_generate().
125 * Otherwise, the entropy is polled from the system entropy sources
126 * using rand_pool_acquire_entropy().
128 * If a random pool has been added to the DRBG using RAND_add(), then
129 * its entropy will be used up first.
131 size_t rand_drbg_get_entropy(RAND_DRBG *drbg,
132 unsigned char **pout,
133 int entropy, size_t min_len, size_t max_len,
134 int prediction_resistance)
137 size_t entropy_available = 0;
140 if (drbg->parent && drbg->strength > drbg->parent->strength) {
142 * We currently don't support the algorithm from NIST SP 800-90C
143 * 10.1.2 to use a weaker DRBG as source
145 RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY, RAND_R_PARENT_STRENGTH_TOO_WEAK);
149 if (drbg->pool != NULL) {
151 pool->entropy_requested = entropy;
153 pool = rand_pool_new(entropy, min_len, max_len);
159 size_t bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
160 unsigned char *buffer = rand_pool_add_begin(pool, bytes_needed);
162 if (buffer != NULL) {
166 * Get random from parent, include our state as additional input.
167 * Our lock is already held, but we need to lock our parent before
168 * generating bits from it. (Note: taking the lock will be a no-op
169 * if locking if drbg->parent->lock == NULL.)
171 rand_drbg_lock(drbg->parent);
172 if (RAND_DRBG_generate(drbg->parent,
173 buffer, bytes_needed,
174 prediction_resistance,
176 bytes = bytes_needed;
177 drbg->reseed_next_counter
178 = tsan_load(&drbg->parent->reseed_prop_counter);
179 rand_drbg_unlock(drbg->parent);
181 rand_pool_add_end(pool, bytes, 8 * bytes);
182 entropy_available = rand_pool_entropy_available(pool);
186 if (prediction_resistance) {
188 * We don't have any entropy sources that comply with the NIST
189 * standard to provide prediction resistance (see NIST SP 800-90C,
192 RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY,
193 RAND_R_PREDICTION_RESISTANCE_NOT_SUPPORTED);
197 /* Get entropy by polling system entropy sources. */
198 entropy_available = rand_pool_acquire_entropy(pool);
201 if (entropy_available > 0) {
202 ret = rand_pool_length(pool);
203 *pout = rand_pool_detach(pool);
207 if (drbg->pool == NULL)
208 rand_pool_free(pool);
213 * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
216 void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
217 unsigned char *out, size_t outlen)
219 if (drbg->pool == NULL)
220 OPENSSL_secure_clear_free(out, outlen);
225 * Implements the get_nonce() callback (see RAND_DRBG_set_callbacks())
228 size_t rand_drbg_get_nonce(RAND_DRBG *drbg,
229 unsigned char **pout,
230 int entropy, size_t min_len, size_t max_len)
240 pool = rand_pool_new(0, min_len, max_len);
244 if (rand_pool_add_nonce_data(pool) == 0)
247 data.instance = drbg;
248 CRYPTO_atomic_add(&rand_nonce_count, 1, &data.count, rand_nonce_lock);
250 if (rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0) == 0)
253 ret = rand_pool_length(pool);
254 *pout = rand_pool_detach(pool);
257 rand_pool_free(pool);
263 * Implements the cleanup_nonce() callback (see RAND_DRBG_set_callbacks())
266 void rand_drbg_cleanup_nonce(RAND_DRBG *drbg,
267 unsigned char *out, size_t outlen)
269 OPENSSL_secure_clear_free(out, outlen);
273 * Generate additional data that can be used for the drbg. The data does
274 * not need to contain entropy, but it's useful if it contains at least
275 * some bits that are unpredictable.
277 * Returns 0 on failure.
279 * On success it allocates a buffer at |*pout| and returns the length of
280 * the data. The buffer should get freed using OPENSSL_secure_clear_free().
282 size_t rand_drbg_get_additional_data(unsigned char **pout, size_t max_len)
287 pool = rand_pool_new(0, 0, max_len);
291 if (rand_pool_add_additional_data(pool) == 0)
294 ret = rand_pool_length(pool);
295 *pout = rand_pool_detach(pool);
298 rand_pool_free(pool);
303 void rand_drbg_cleanup_additional_data(unsigned char *out, size_t outlen)
305 OPENSSL_secure_clear_free(out, outlen);
313 DEFINE_RUN_ONCE_STATIC(do_rand_init)
315 #ifndef OPENSSL_NO_ENGINE
316 rand_engine_lock = CRYPTO_THREAD_lock_new();
317 if (rand_engine_lock == NULL)
321 rand_meth_lock = CRYPTO_THREAD_lock_new();
322 if (rand_meth_lock == NULL)
325 rand_nonce_lock = CRYPTO_THREAD_lock_new();
326 if (rand_nonce_lock == NULL)
329 if (!rand_cleaning_up && !rand_pool_init())
337 CRYPTO_THREAD_lock_free(rand_meth_lock);
338 rand_meth_lock = NULL;
340 #ifndef OPENSSL_NO_ENGINE
341 CRYPTO_THREAD_lock_free(rand_engine_lock);
342 rand_engine_lock = NULL;
347 void rand_cleanup_int(void)
349 const RAND_METHOD *meth = default_RAND_meth;
351 rand_cleaning_up = 1;
353 if (meth != NULL && meth->cleanup != NULL)
355 RAND_set_rand_method(NULL);
357 #ifndef OPENSSL_NO_ENGINE
358 CRYPTO_THREAD_lock_free(rand_engine_lock);
359 rand_engine_lock = NULL;
361 CRYPTO_THREAD_lock_free(rand_meth_lock);
362 rand_meth_lock = NULL;
363 CRYPTO_THREAD_lock_free(rand_nonce_lock);
364 rand_nonce_lock = NULL;
368 * RAND_close_seed_files() ensures that any seed file decriptors are
371 void RAND_keep_random_devices_open(int keep)
373 rand_pool_keep_random_devices_open(keep);
377 * RAND_poll() reseeds the default RNG using random input
379 * The random input is obtained from polling various entropy
380 * sources which depend on the operating system and are
381 * configurable via the --with-rand-seed configure option.
387 RAND_POOL *pool = NULL;
389 const RAND_METHOD *meth = RAND_get_rand_method();
391 if (meth == RAND_OpenSSL()) {
392 /* fill random pool and seed the master DRBG */
393 RAND_DRBG *drbg = RAND_DRBG_get0_master();
398 rand_drbg_lock(drbg);
399 ret = rand_drbg_restart(drbg, NULL, 0, 0);
400 rand_drbg_unlock(drbg);
405 /* fill random pool and seed the current legacy RNG */
406 pool = rand_pool_new(RAND_DRBG_STRENGTH,
407 RAND_DRBG_STRENGTH / 8,
408 RAND_POOL_MAX_LENGTH);
412 if (rand_pool_acquire_entropy(pool) == 0)
415 if (meth->add == NULL
416 || meth->add(rand_pool_buffer(pool),
417 rand_pool_length(pool),
418 (rand_pool_entropy(pool) / 8.0)) == 0)
425 rand_pool_free(pool);
430 * Allocate memory and initialize a new random pool
433 RAND_POOL *rand_pool_new(int entropy_requested, size_t min_len, size_t max_len)
435 RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
438 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
442 pool->min_len = min_len;
443 pool->max_len = (max_len > RAND_POOL_MAX_LENGTH) ?
444 RAND_POOL_MAX_LENGTH : max_len;
446 pool->buffer = OPENSSL_secure_zalloc(pool->max_len);
447 if (pool->buffer == NULL) {
448 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
452 pool->entropy_requested = entropy_requested;
462 * Attach new random pool to the given buffer
464 * This function is intended to be used only for feeding random data
465 * provided by RAND_add() and RAND_seed() into the <master> DRBG.
467 RAND_POOL *rand_pool_attach(const unsigned char *buffer, size_t len,
470 RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
473 RANDerr(RAND_F_RAND_POOL_ATTACH, ERR_R_MALLOC_FAILURE);
478 * The const needs to be cast away, but attached buffers will not be
479 * modified (in contrary to allocated buffers which are zeroed and
482 pool->buffer = (unsigned char *) buffer;
487 pool->min_len = pool->max_len = pool->len;
488 pool->entropy = entropy;
494 * Free |pool|, securely erasing its buffer.
496 void rand_pool_free(RAND_POOL *pool)
502 * Although it would be advisable from a cryptographical viewpoint,
503 * we are not allowed to clear attached buffers, since they are passed
504 * to rand_pool_attach() as `const unsigned char*`.
505 * (see corresponding comment in rand_pool_attach()).
508 OPENSSL_secure_clear_free(pool->buffer, pool->max_len);
513 * Return the |pool|'s buffer to the caller (readonly).
515 const unsigned char *rand_pool_buffer(RAND_POOL *pool)
521 * Return the |pool|'s entropy to the caller.
523 size_t rand_pool_entropy(RAND_POOL *pool)
525 return pool->entropy;
529 * Return the |pool|'s buffer length to the caller.
531 size_t rand_pool_length(RAND_POOL *pool)
537 * Detach the |pool| buffer and return it to the caller.
538 * It's the responsibility of the caller to free the buffer
539 * using OPENSSL_secure_clear_free().
541 unsigned char *rand_pool_detach(RAND_POOL *pool)
543 unsigned char *ret = pool->buffer;
552 * If |entropy_factor| bits contain 1 bit of entropy, how many bytes does one
553 * need to obtain at least |bits| bits of entropy?
555 #define ENTROPY_TO_BYTES(bits, entropy_factor) \
556 (((bits) * (entropy_factor) + 7) / 8)
560 * Checks whether the |pool|'s entropy is available to the caller.
561 * This is the case when entropy count and buffer length are high enough.
564 * |entropy| if the entropy count and buffer size is large enough
567 size_t rand_pool_entropy_available(RAND_POOL *pool)
569 if (pool->entropy < pool->entropy_requested)
572 if (pool->len < pool->min_len)
575 return pool->entropy;
579 * Returns the (remaining) amount of entropy needed to fill
583 size_t rand_pool_entropy_needed(RAND_POOL *pool)
585 if (pool->entropy < pool->entropy_requested)
586 return pool->entropy_requested - pool->entropy;
592 * Returns the number of bytes needed to fill the pool, assuming
593 * the input has 1 / |entropy_factor| entropy bits per data bit.
594 * In case of an error, 0 is returned.
597 size_t rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor)
600 size_t entropy_needed = rand_pool_entropy_needed(pool);
602 if (entropy_factor < 1) {
603 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
607 bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_factor);
609 if (bytes_needed > pool->max_len - pool->len) {
610 /* not enough space left */
611 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
615 if (pool->len < pool->min_len &&
616 bytes_needed < pool->min_len - pool->len)
617 /* to meet the min_len requirement */
618 bytes_needed = pool->min_len - pool->len;
623 /* Returns the remaining number of bytes available */
624 size_t rand_pool_bytes_remaining(RAND_POOL *pool)
626 return pool->max_len - pool->len;
630 * Add random bytes to the random pool.
632 * It is expected that the |buffer| contains |len| bytes of
633 * random input which contains at least |entropy| bits of
636 * Returns 1 if the added amount is adequate, otherwise 0
638 int rand_pool_add(RAND_POOL *pool,
639 const unsigned char *buffer, size_t len, size_t entropy)
641 if (len > pool->max_len - pool->len) {
642 RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
647 memcpy(pool->buffer + pool->len, buffer, len);
649 pool->entropy += entropy;
656 * Start to add random bytes to the random pool in-place.
658 * Reserves the next |len| bytes for adding random bytes in-place
659 * and returns a pointer to the buffer.
660 * The caller is allowed to copy up to |len| bytes into the buffer.
661 * If |len| == 0 this is considered a no-op and a NULL pointer
662 * is returned without producing an error message.
664 * After updating the buffer, rand_pool_add_end() needs to be called
665 * to finish the udpate operation (see next comment).
667 unsigned char *rand_pool_add_begin(RAND_POOL *pool, size_t len)
672 if (len > pool->max_len - pool->len) {
673 RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
677 return pool->buffer + pool->len;
681 * Finish to add random bytes to the random pool in-place.
683 * Finishes an in-place update of the random pool started by
684 * rand_pool_add_begin() (see previous comment).
685 * It is expected that |len| bytes of random input have been added
686 * to the buffer which contain at least |entropy| bits of randomness.
687 * It is allowed to add less bytes than originally reserved.
689 int rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy)
691 if (len > pool->max_len - pool->len) {
692 RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
698 pool->entropy += entropy;
704 int RAND_set_rand_method(const RAND_METHOD *meth)
706 if (!RUN_ONCE(&rand_init, do_rand_init))
709 CRYPTO_THREAD_write_lock(rand_meth_lock);
710 #ifndef OPENSSL_NO_ENGINE
711 ENGINE_finish(funct_ref);
714 default_RAND_meth = meth;
715 CRYPTO_THREAD_unlock(rand_meth_lock);
719 const RAND_METHOD *RAND_get_rand_method(void)
721 const RAND_METHOD *tmp_meth = NULL;
723 if (!RUN_ONCE(&rand_init, do_rand_init))
726 CRYPTO_THREAD_write_lock(rand_meth_lock);
727 if (default_RAND_meth == NULL) {
728 #ifndef OPENSSL_NO_ENGINE
731 /* If we have an engine that can do RAND, use it. */
732 if ((e = ENGINE_get_default_RAND()) != NULL
733 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
735 default_RAND_meth = tmp_meth;
738 default_RAND_meth = &rand_meth;
741 default_RAND_meth = &rand_meth;
744 tmp_meth = default_RAND_meth;
745 CRYPTO_THREAD_unlock(rand_meth_lock);
749 #ifndef OPENSSL_NO_ENGINE
750 int RAND_set_rand_engine(ENGINE *engine)
752 const RAND_METHOD *tmp_meth = NULL;
754 if (!RUN_ONCE(&rand_init, do_rand_init))
757 if (engine != NULL) {
758 if (!ENGINE_init(engine))
760 tmp_meth = ENGINE_get_RAND(engine);
761 if (tmp_meth == NULL) {
762 ENGINE_finish(engine);
766 CRYPTO_THREAD_write_lock(rand_engine_lock);
767 /* This function releases any prior ENGINE so call it first */
768 RAND_set_rand_method(tmp_meth);
770 CRYPTO_THREAD_unlock(rand_engine_lock);
775 void RAND_seed(const void *buf, int num)
777 const RAND_METHOD *meth = RAND_get_rand_method();
779 if (meth->seed != NULL)
780 meth->seed(buf, num);
783 void RAND_add(const void *buf, int num, double randomness)
785 const RAND_METHOD *meth = RAND_get_rand_method();
787 if (meth->add != NULL)
788 meth->add(buf, num, randomness);
792 * This function is not part of RAND_METHOD, so if we're not using
793 * the default method, then just call RAND_bytes(). Otherwise make
794 * sure we're instantiated and use the private DRBG.
796 int RAND_priv_bytes(unsigned char *buf, int num)
798 const RAND_METHOD *meth = RAND_get_rand_method();
802 if (meth != RAND_OpenSSL())
803 return RAND_bytes(buf, num);
805 drbg = RAND_DRBG_get0_private();
809 ret = RAND_DRBG_bytes(drbg, buf, num);
813 int RAND_bytes(unsigned char *buf, int num)
815 const RAND_METHOD *meth = RAND_get_rand_method();
817 if (meth->bytes != NULL)
818 return meth->bytes(buf, num);
819 RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
823 #if OPENSSL_API_COMPAT < 0x10100000L
824 int RAND_pseudo_bytes(unsigned char *buf, int num)
826 const RAND_METHOD *meth = RAND_get_rand_method();
828 if (meth->pseudorand != NULL)
829 return meth->pseudorand(buf, num);
834 int RAND_status(void)
836 const RAND_METHOD *meth = RAND_get_rand_method();
838 if (meth->status != NULL)
839 return meth->status();