2 * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (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"
21 # ifndef OPENSSL_NO_ENGINE
22 /* non-NULL if default_RAND_meth is ENGINE-provided */
23 static ENGINE *funct_ref;
24 static CRYPTO_RWLOCK *rand_engine_lock;
26 static CRYPTO_RWLOCK *rand_meth_lock;
27 static const RAND_METHOD *default_RAND_meth;
28 static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
30 static int rand_inited = 0;
31 #endif /* FIPS_MODE */
35 #ifdef OPENSSL_RAND_SEED_RDTSC
37 * IMPORTANT NOTE: It is not currently possible to use this code
38 * because we are not sure about the amount of randomness it provides.
39 * Some SP900 tests have been run, but there is internal skepticism.
40 * So for now this code is not used.
42 # error "RDTSC enabled? Should not be possible!"
45 * Acquire entropy from high-speed clock
47 * Since we get some randomness from the low-order bits of the
48 * high-speed clock, it can help.
50 * Returns the total entropy count, if it exceeds the requested
51 * entropy count. Otherwise, returns an entropy count of 0.
53 size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool)
58 if ((OPENSSL_ia32cap_P[0] & (1 << 4)) != 0) {
59 for (i = 0; i < TSC_READ_COUNT; i++) {
60 c = (unsigned char)(OPENSSL_rdtsc() & 0xFF);
61 rand_pool_add(pool, &c, 1, 4);
64 return rand_pool_entropy_available(pool);
68 #ifdef OPENSSL_RAND_SEED_RDCPU
69 size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len);
70 size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len);
73 * Acquire entropy using Intel-specific cpu instructions
75 * Uses the RDSEED instruction if available, otherwise uses
76 * RDRAND if available.
78 * For the differences between RDSEED and RDRAND, and why RDSEED
79 * is the preferred choice, see https://goo.gl/oK3KcN
81 * Returns the total entropy count, if it exceeds the requested
82 * entropy count. Otherwise, returns an entropy count of 0.
84 size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool)
87 unsigned char *buffer;
89 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
90 if (bytes_needed > 0) {
91 buffer = rand_pool_add_begin(pool, bytes_needed);
94 /* Whichever comes first, use RDSEED, RDRAND or nothing */
95 if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
96 if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed)
98 rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
100 } else if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
101 if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed)
103 rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
106 rand_pool_add_end(pool, 0, 0);
111 return rand_pool_entropy_available(pool);
117 * Implements the get_entropy() callback (see RAND_DRBG_set_callbacks())
119 * If the DRBG has a parent, then the required amount of entropy input
120 * is fetched using the parent's RAND_DRBG_generate().
122 * Otherwise, the entropy is polled from the system entropy sources
123 * using rand_pool_acquire_entropy().
125 * If a random pool has been added to the DRBG using RAND_add(), then
126 * its entropy will be used up first.
128 size_t rand_drbg_get_entropy(RAND_DRBG *drbg,
129 unsigned char **pout,
130 int entropy, size_t min_len, size_t max_len,
131 int prediction_resistance)
134 size_t entropy_available = 0;
137 if (drbg->parent != NULL && drbg->strength > drbg->parent->strength) {
139 * We currently don't support the algorithm from NIST SP 800-90C
140 * 10.1.2 to use a weaker DRBG as source
142 RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY, RAND_R_PARENT_STRENGTH_TOO_WEAK);
146 if (drbg->seed_pool != NULL) {
147 pool = drbg->seed_pool;
148 pool->entropy_requested = entropy;
150 pool = rand_pool_new(entropy, drbg->secure, min_len, max_len);
155 if (drbg->parent != NULL) {
156 size_t bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
157 unsigned char *buffer = rand_pool_add_begin(pool, bytes_needed);
159 if (buffer != NULL) {
163 * Get random from parent, include our state as additional input.
164 * Our lock is already held, but we need to lock our parent before
165 * generating bits from it. (Note: taking the lock will be a no-op
166 * if locking if drbg->parent->lock == NULL.)
168 rand_drbg_lock(drbg->parent);
169 if (RAND_DRBG_generate(drbg->parent,
170 buffer, bytes_needed,
171 prediction_resistance,
173 bytes = bytes_needed;
174 drbg->reseed_next_counter
175 = tsan_load(&drbg->parent->reseed_prop_counter);
176 rand_drbg_unlock(drbg->parent);
178 rand_pool_add_end(pool, bytes, 8 * bytes);
179 entropy_available = rand_pool_entropy_available(pool);
183 /* Get entropy by polling system entropy sources. */
184 entropy_available = rand_pool_acquire_entropy(pool);
187 if (entropy_available > 0) {
188 ret = rand_pool_length(pool);
189 *pout = rand_pool_detach(pool);
192 if (drbg->seed_pool == NULL)
193 rand_pool_free(pool);
198 * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
201 void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
202 unsigned char *out, size_t outlen)
204 if (drbg->seed_pool == NULL) {
206 OPENSSL_secure_clear_free(out, outlen);
208 OPENSSL_clear_free(out, outlen);
213 * Generate additional data that can be used for the drbg. The data does
214 * not need to contain entropy, but it's useful if it contains at least
215 * some bits that are unpredictable.
217 * Returns 0 on failure.
219 * On success it allocates a buffer at |*pout| and returns the length of
220 * the data. The buffer should get freed using OPENSSL_secure_clear_free().
222 size_t rand_drbg_get_additional_data(RAND_POOL *pool, unsigned char **pout)
226 if (rand_pool_add_additional_data(pool) == 0)
229 ret = rand_pool_length(pool);
230 *pout = rand_pool_detach(pool);
236 void rand_drbg_cleanup_additional_data(RAND_POOL *pool, unsigned char *out)
238 rand_pool_reattach(pool, out);
247 DEFINE_RUN_ONCE_STATIC(do_rand_init)
249 # ifndef OPENSSL_NO_ENGINE
250 rand_engine_lock = CRYPTO_THREAD_lock_new();
251 if (rand_engine_lock == NULL)
255 rand_meth_lock = CRYPTO_THREAD_lock_new();
256 if (rand_meth_lock == NULL)
259 if (!rand_pool_init())
266 CRYPTO_THREAD_lock_free(rand_meth_lock);
267 rand_meth_lock = NULL;
268 # ifndef OPENSSL_NO_ENGINE
269 CRYPTO_THREAD_lock_free(rand_engine_lock);
270 rand_engine_lock = NULL;
275 void rand_cleanup_int(void)
277 const RAND_METHOD *meth = default_RAND_meth;
282 if (meth != NULL && meth->cleanup != NULL)
284 RAND_set_rand_method(NULL);
286 # ifndef OPENSSL_NO_ENGINE
287 CRYPTO_THREAD_lock_free(rand_engine_lock);
288 rand_engine_lock = NULL;
290 CRYPTO_THREAD_lock_free(rand_meth_lock);
291 rand_meth_lock = NULL;
295 /* TODO(3.0): Do we need to handle this somehow in the FIPS module? */
297 * RAND_close_seed_files() ensures that any seed file descriptors are
300 void RAND_keep_random_devices_open(int keep)
302 if (RUN_ONCE(&rand_init, do_rand_init))
303 rand_pool_keep_random_devices_open(keep);
307 * RAND_poll() reseeds the default RNG using random input
309 * The random input is obtained from polling various entropy
310 * sources which depend on the operating system and are
311 * configurable via the --with-rand-seed configure option.
317 const RAND_METHOD *meth = RAND_get_rand_method();
319 if (meth == RAND_OpenSSL()) {
320 /* fill random pool and seed the master DRBG */
321 RAND_DRBG *drbg = RAND_DRBG_get0_master();
326 rand_drbg_lock(drbg);
327 ret = rand_drbg_restart(drbg, NULL, 0, 0);
328 rand_drbg_unlock(drbg);
333 RAND_POOL *pool = NULL;
335 /* fill random pool and seed the current legacy RNG */
336 pool = rand_pool_new(RAND_DRBG_STRENGTH, 1,
337 (RAND_DRBG_STRENGTH + 7) / 8,
338 RAND_POOL_MAX_LENGTH);
342 if (rand_pool_acquire_entropy(pool) == 0)
345 if (meth->add == NULL
346 || meth->add(rand_pool_buffer(pool),
347 rand_pool_length(pool),
348 (rand_pool_entropy(pool) / 8.0)) == 0)
354 rand_pool_free(pool);
359 #endif /* FIPS_MODE */
362 * Allocate memory and initialize a new random pool
365 RAND_POOL *rand_pool_new(int entropy_requested, int secure,
366 size_t min_len, size_t max_len)
368 RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
369 size_t min_alloc_size = RAND_POOL_MIN_ALLOCATION(secure);
372 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
376 pool->min_len = min_len;
377 pool->max_len = (max_len > RAND_POOL_MAX_LENGTH) ?
378 RAND_POOL_MAX_LENGTH : max_len;
379 pool->alloc_len = min_len < min_alloc_size ? min_alloc_size : min_len;
380 if (pool->alloc_len > pool->max_len)
381 pool->alloc_len = pool->max_len;
384 pool->buffer = OPENSSL_secure_zalloc(pool->alloc_len);
386 pool->buffer = OPENSSL_zalloc(pool->alloc_len);
388 if (pool->buffer == NULL) {
389 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
393 pool->entropy_requested = entropy_requested;
394 pool->secure = secure;
404 * Attach new random pool to the given buffer
406 * This function is intended to be used only for feeding random data
407 * provided by RAND_add() and RAND_seed() into the <master> DRBG.
409 RAND_POOL *rand_pool_attach(const unsigned char *buffer, size_t len,
412 RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
415 RANDerr(RAND_F_RAND_POOL_ATTACH, ERR_R_MALLOC_FAILURE);
420 * The const needs to be cast away, but attached buffers will not be
421 * modified (in contrary to allocated buffers which are zeroed and
424 pool->buffer = (unsigned char *) buffer;
429 pool->min_len = pool->max_len = pool->alloc_len = pool->len;
430 pool->entropy = entropy;
436 * Free |pool|, securely erasing its buffer.
438 void rand_pool_free(RAND_POOL *pool)
444 * Although it would be advisable from a cryptographical viewpoint,
445 * we are not allowed to clear attached buffers, since they are passed
446 * to rand_pool_attach() as `const unsigned char*`.
447 * (see corresponding comment in rand_pool_attach()).
449 if (!pool->attached) {
451 OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
453 OPENSSL_clear_free(pool->buffer, pool->alloc_len);
460 * Return the |pool|'s buffer to the caller (readonly).
462 const unsigned char *rand_pool_buffer(RAND_POOL *pool)
468 * Return the |pool|'s entropy to the caller.
470 size_t rand_pool_entropy(RAND_POOL *pool)
472 return pool->entropy;
476 * Return the |pool|'s buffer length to the caller.
478 size_t rand_pool_length(RAND_POOL *pool)
484 * Detach the |pool| buffer and return it to the caller.
485 * It's the responsibility of the caller to free the buffer
486 * using OPENSSL_secure_clear_free() or to re-attach it
487 * again to the pool using rand_pool_reattach().
489 unsigned char *rand_pool_detach(RAND_POOL *pool)
491 unsigned char *ret = pool->buffer;
498 * Re-attach the |pool| buffer. It is only allowed to pass
499 * the |buffer| which was previously detached from the same pool.
501 void rand_pool_reattach(RAND_POOL *pool, unsigned char *buffer)
503 pool->buffer = buffer;
504 OPENSSL_cleanse(pool->buffer, pool->len);
509 * If |entropy_factor| bits contain 1 bit of entropy, how many bytes does one
510 * need to obtain at least |bits| bits of entropy?
512 #define ENTROPY_TO_BYTES(bits, entropy_factor) \
513 (((bits) * (entropy_factor) + 7) / 8)
517 * Checks whether the |pool|'s entropy is available to the caller.
518 * This is the case when entropy count and buffer length are high enough.
521 * |entropy| if the entropy count and buffer size is large enough
524 size_t rand_pool_entropy_available(RAND_POOL *pool)
526 if (pool->entropy < pool->entropy_requested)
529 if (pool->len < pool->min_len)
532 return pool->entropy;
536 * Returns the (remaining) amount of entropy needed to fill
540 size_t rand_pool_entropy_needed(RAND_POOL *pool)
542 if (pool->entropy < pool->entropy_requested)
543 return pool->entropy_requested - pool->entropy;
548 /* Increase the allocation size -- not usable for an attached pool */
549 static int rand_pool_grow(RAND_POOL *pool, size_t len)
551 if (len > pool->alloc_len - pool->len) {
553 const size_t limit = pool->max_len / 2;
554 size_t newlen = pool->alloc_len;
556 if (pool->attached || len > pool->max_len - pool->len) {
557 RANDerr(RAND_F_RAND_POOL_GROW, ERR_R_INTERNAL_ERROR);
562 newlen = newlen < limit ? newlen * 2 : pool->max_len;
563 while (len > newlen - pool->len);
566 p = OPENSSL_secure_zalloc(newlen);
568 p = OPENSSL_zalloc(newlen);
570 RANDerr(RAND_F_RAND_POOL_GROW, ERR_R_MALLOC_FAILURE);
573 memcpy(p, pool->buffer, pool->len);
575 OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
577 OPENSSL_clear_free(pool->buffer, pool->alloc_len);
579 pool->alloc_len = newlen;
585 * Returns the number of bytes needed to fill the pool, assuming
586 * the input has 1 / |entropy_factor| entropy bits per data bit.
587 * In case of an error, 0 is returned.
590 size_t rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor)
593 size_t entropy_needed = rand_pool_entropy_needed(pool);
595 if (entropy_factor < 1) {
596 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
600 bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_factor);
602 if (bytes_needed > pool->max_len - pool->len) {
603 /* not enough space left */
604 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
608 if (pool->len < pool->min_len &&
609 bytes_needed < pool->min_len - pool->len)
610 /* to meet the min_len requirement */
611 bytes_needed = pool->min_len - pool->len;
614 * Make sure the buffer is large enough for the requested amount
615 * of data. This guarantees that existing code patterns where
616 * rand_pool_add_begin, rand_pool_add_end or rand_pool_add
617 * are used to collect entropy data without any error handling
618 * whatsoever, continue to be valid.
619 * Furthermore if the allocation here fails once, make sure that
620 * we don't fall back to a less secure or even blocking random source,
621 * as that could happen by the existing code patterns.
622 * This is not a concern for additional data, therefore that
623 * is not needed if rand_pool_grow fails in other places.
625 if (!rand_pool_grow(pool, bytes_needed)) {
626 /* persistent error for this pool */
627 pool->max_len = pool->len = 0;
634 /* Returns the remaining number of bytes available */
635 size_t rand_pool_bytes_remaining(RAND_POOL *pool)
637 return pool->max_len - pool->len;
641 * Add random bytes to the random pool.
643 * It is expected that the |buffer| contains |len| bytes of
644 * random input which contains at least |entropy| bits of
647 * Returns 1 if the added amount is adequate, otherwise 0
649 int rand_pool_add(RAND_POOL *pool,
650 const unsigned char *buffer, size_t len, size_t entropy)
652 if (len > pool->max_len - pool->len) {
653 RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
657 if (pool->buffer == NULL) {
658 RANDerr(RAND_F_RAND_POOL_ADD, ERR_R_INTERNAL_ERROR);
664 * This is to protect us from accidentally passing the buffer
665 * returned from rand_pool_add_begin.
666 * The check for alloc_len makes sure we do not compare the
667 * address of the end of the allocated memory to something
668 * different, since that comparison would have an
669 * indeterminate result.
671 if (pool->alloc_len > pool->len && pool->buffer + pool->len == buffer) {
672 RANDerr(RAND_F_RAND_POOL_ADD, ERR_R_INTERNAL_ERROR);
676 * We have that only for cases when a pool is used to collect
678 * For entropy data, as long as the allocation request stays within
679 * the limits given by rand_pool_bytes_needed this rand_pool_grow
680 * below is guaranteed to succeed, thus no allocation happens.
682 if (!rand_pool_grow(pool, len))
684 memcpy(pool->buffer + pool->len, buffer, len);
686 pool->entropy += entropy;
693 * Start to add random bytes to the random pool in-place.
695 * Reserves the next |len| bytes for adding random bytes in-place
696 * and returns a pointer to the buffer.
697 * The caller is allowed to copy up to |len| bytes into the buffer.
698 * If |len| == 0 this is considered a no-op and a NULL pointer
699 * is returned without producing an error message.
701 * After updating the buffer, rand_pool_add_end() needs to be called
702 * to finish the udpate operation (see next comment).
704 unsigned char *rand_pool_add_begin(RAND_POOL *pool, size_t len)
709 if (len > pool->max_len - pool->len) {
710 RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
714 if (pool->buffer == NULL) {
715 RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, ERR_R_INTERNAL_ERROR);
720 * As long as the allocation request stays within the limits given
721 * by rand_pool_bytes_needed this rand_pool_grow below is guaranteed
722 * to succeed, thus no allocation happens.
723 * We have that only for cases when a pool is used to collect
724 * additional data. Then the buffer might need to grow here,
725 * and of course the caller is responsible to check the return
726 * value of this function.
728 if (!rand_pool_grow(pool, len))
731 return pool->buffer + pool->len;
735 * Finish to add random bytes to the random pool in-place.
737 * Finishes an in-place update of the random pool started by
738 * rand_pool_add_begin() (see previous comment).
739 * It is expected that |len| bytes of random input have been added
740 * to the buffer which contain at least |entropy| bits of randomness.
741 * It is allowed to add less bytes than originally reserved.
743 int rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy)
745 if (len > pool->alloc_len - pool->len) {
746 RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
752 pool->entropy += entropy;
759 int RAND_set_rand_method(const RAND_METHOD *meth)
761 if (!RUN_ONCE(&rand_init, do_rand_init))
764 CRYPTO_THREAD_write_lock(rand_meth_lock);
765 # ifndef OPENSSL_NO_ENGINE
766 ENGINE_finish(funct_ref);
769 default_RAND_meth = meth;
770 CRYPTO_THREAD_unlock(rand_meth_lock);
775 const RAND_METHOD *RAND_get_rand_method(void)
780 const RAND_METHOD *tmp_meth = NULL;
782 if (!RUN_ONCE(&rand_init, do_rand_init))
785 CRYPTO_THREAD_write_lock(rand_meth_lock);
786 if (default_RAND_meth == NULL) {
787 # ifndef OPENSSL_NO_ENGINE
790 /* If we have an engine that can do RAND, use it. */
791 if ((e = ENGINE_get_default_RAND()) != NULL
792 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
794 default_RAND_meth = tmp_meth;
797 default_RAND_meth = &rand_meth;
800 default_RAND_meth = &rand_meth;
803 tmp_meth = default_RAND_meth;
804 CRYPTO_THREAD_unlock(rand_meth_lock);
809 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODE)
810 int RAND_set_rand_engine(ENGINE *engine)
812 const RAND_METHOD *tmp_meth = NULL;
814 if (!RUN_ONCE(&rand_init, do_rand_init))
817 if (engine != NULL) {
818 if (!ENGINE_init(engine))
820 tmp_meth = ENGINE_get_RAND(engine);
821 if (tmp_meth == NULL) {
822 ENGINE_finish(engine);
826 CRYPTO_THREAD_write_lock(rand_engine_lock);
827 /* This function releases any prior ENGINE so call it first */
828 RAND_set_rand_method(tmp_meth);
830 CRYPTO_THREAD_unlock(rand_engine_lock);
835 void RAND_seed(const void *buf, int num)
837 const RAND_METHOD *meth = RAND_get_rand_method();
839 if (meth->seed != NULL)
840 meth->seed(buf, num);
843 void RAND_add(const void *buf, int num, double randomness)
845 const RAND_METHOD *meth = RAND_get_rand_method();
847 if (meth->add != NULL)
848 meth->add(buf, num, randomness);
852 * This function is not part of RAND_METHOD, so if we're not using
853 * the default method, then just call RAND_bytes(). Otherwise make
854 * sure we're instantiated and use the private DRBG.
856 int rand_priv_bytes_ex(OPENSSL_CTX *ctx, unsigned char *buf, int num)
860 const RAND_METHOD *meth = RAND_get_rand_method();
862 if (meth != RAND_OpenSSL())
863 return meth->bytes(buf, num);
865 drbg = OPENSSL_CTX_get0_private_drbg(ctx);
869 ret = RAND_DRBG_bytes(drbg, buf, num);
873 int RAND_priv_bytes(unsigned char *buf, int num)
875 return rand_priv_bytes_ex(NULL, buf, num);
878 int rand_bytes_ex(OPENSSL_CTX *ctx, unsigned char *buf, int num)
882 const RAND_METHOD *meth = RAND_get_rand_method();
884 if (meth != RAND_OpenSSL()) {
885 if (meth->bytes != NULL)
886 return meth->bytes(buf, num);
887 RANDerr(RAND_F_RAND_BYTES_EX, RAND_R_FUNC_NOT_IMPLEMENTED);
891 drbg = OPENSSL_CTX_get0_public_drbg(ctx);
895 ret = RAND_DRBG_bytes(drbg, buf, num);
899 int RAND_bytes(unsigned char *buf, int num)
901 return rand_bytes_ex(NULL, buf, num);
904 #if !OPENSSL_API_1_1_0 && !defined(FIPS_MODE)
905 int RAND_pseudo_bytes(unsigned char *buf, int num)
907 const RAND_METHOD *meth = RAND_get_rand_method();
909 if (meth->pseudorand != NULL)
910 return meth->pseudorand(buf, num);
915 int RAND_status(void)
917 const RAND_METHOD *meth = RAND_get_rand_method();
919 if (meth->status != NULL)
920 return meth->status();