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);
72 extern unsigned int OPENSSL_ia32cap_P[];
75 * Acquire entropy using Intel-specific cpu instructions
77 * Uses the RDSEED instruction if available, otherwise uses
78 * RDRAND if available.
80 * For the differences between RDSEED and RDRAND, and why RDSEED
81 * is the preferred choice, see https://goo.gl/oK3KcN
83 * Returns the total entropy count, if it exceeds the requested
84 * entropy count. Otherwise, returns an entropy count of 0.
86 size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool)
89 unsigned char *buffer;
91 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
92 if (bytes_needed > 0) {
93 buffer = rand_pool_add_begin(pool, bytes_needed);
96 /* Whichever comes first, use RDSEED, RDRAND or nothing */
97 if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
98 if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed)
100 rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
102 } else if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
103 if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed)
105 rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
108 rand_pool_add_end(pool, 0, 0);
113 return rand_pool_entropy_available(pool);
119 * Implements the get_entropy() callback (see RAND_DRBG_set_callbacks())
121 * If the DRBG has a parent, then the required amount of entropy input
122 * is fetched using the parent's RAND_DRBG_generate().
124 * Otherwise, the entropy is polled from the system entropy sources
125 * using rand_pool_acquire_entropy().
127 * If a random pool has been added to the DRBG using RAND_add(), then
128 * its entropy will be used up first.
130 size_t rand_drbg_get_entropy(RAND_DRBG *drbg,
131 unsigned char **pout,
132 int entropy, size_t min_len, size_t max_len,
133 int prediction_resistance)
136 size_t entropy_available = 0;
139 if (drbg->parent != NULL && drbg->strength > drbg->parent->strength) {
141 * We currently don't support the algorithm from NIST SP 800-90C
142 * 10.1.2 to use a weaker DRBG as source
144 RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY, RAND_R_PARENT_STRENGTH_TOO_WEAK);
148 if (drbg->seed_pool != NULL) {
149 pool = drbg->seed_pool;
150 pool->entropy_requested = entropy;
152 pool = rand_pool_new(entropy, min_len, max_len);
157 if (drbg->parent != NULL) {
158 size_t bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
159 unsigned char *buffer = rand_pool_add_begin(pool, bytes_needed);
161 if (buffer != NULL) {
165 * Get random from parent, include our state as additional input.
166 * Our lock is already held, but we need to lock our parent before
167 * generating bits from it. (Note: taking the lock will be a no-op
168 * if locking if drbg->parent->lock == NULL.)
170 rand_drbg_lock(drbg->parent);
171 if (RAND_DRBG_generate(drbg->parent,
172 buffer, bytes_needed,
173 prediction_resistance,
175 bytes = bytes_needed;
176 drbg->reseed_next_counter
177 = tsan_load(&drbg->parent->reseed_prop_counter);
178 rand_drbg_unlock(drbg->parent);
180 rand_pool_add_end(pool, bytes, 8 * bytes);
181 entropy_available = rand_pool_entropy_available(pool);
185 /* Get entropy by polling system entropy sources. */
186 entropy_available = rand_pool_acquire_entropy(pool);
189 if (entropy_available > 0) {
190 ret = rand_pool_length(pool);
191 *pout = rand_pool_detach(pool);
194 if (drbg->seed_pool == NULL)
195 rand_pool_free(pool);
200 * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
203 void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
204 unsigned char *out, size_t outlen)
206 if (drbg->seed_pool == NULL)
207 OPENSSL_secure_clear_free(out, outlen);
211 * Generate additional data that can be used for the drbg. The data does
212 * not need to contain entropy, but it's useful if it contains at least
213 * some bits that are unpredictable.
215 * Returns 0 on failure.
217 * On success it allocates a buffer at |*pout| and returns the length of
218 * the data. The buffer should get freed using OPENSSL_secure_clear_free().
220 size_t rand_drbg_get_additional_data(RAND_POOL *pool, unsigned char **pout)
224 if (rand_pool_add_additional_data(pool) == 0)
227 ret = rand_pool_length(pool);
228 *pout = rand_pool_detach(pool);
234 void rand_drbg_cleanup_additional_data(RAND_POOL *pool, unsigned char *out)
236 rand_pool_reattach(pool, out);
245 DEFINE_RUN_ONCE_STATIC(do_rand_init)
247 # ifndef OPENSSL_NO_ENGINE
248 rand_engine_lock = CRYPTO_THREAD_lock_new();
249 if (rand_engine_lock == NULL)
253 rand_meth_lock = CRYPTO_THREAD_lock_new();
254 if (rand_meth_lock == NULL)
257 if (!rand_pool_init())
264 CRYPTO_THREAD_lock_free(rand_meth_lock);
265 rand_meth_lock = NULL;
266 # ifndef OPENSSL_NO_ENGINE
267 CRYPTO_THREAD_lock_free(rand_engine_lock);
268 rand_engine_lock = NULL;
273 void rand_cleanup_int(void)
275 const RAND_METHOD *meth = default_RAND_meth;
280 if (meth != NULL && meth->cleanup != NULL)
282 RAND_set_rand_method(NULL);
284 # ifndef OPENSSL_NO_ENGINE
285 CRYPTO_THREAD_lock_free(rand_engine_lock);
286 rand_engine_lock = NULL;
288 CRYPTO_THREAD_lock_free(rand_meth_lock);
289 rand_meth_lock = NULL;
293 /* TODO(3.0): Do we need to handle this somehow in the FIPS module? */
295 * RAND_close_seed_files() ensures that any seed file decriptors are
298 void RAND_keep_random_devices_open(int keep)
300 if (RUN_ONCE(&rand_init, do_rand_init))
301 rand_pool_keep_random_devices_open(keep);
305 * RAND_poll() reseeds the default RNG using random input
307 * The random input is obtained from polling various entropy
308 * sources which depend on the operating system and are
309 * configurable via the --with-rand-seed configure option.
315 const RAND_METHOD *meth = RAND_get_rand_method();
317 if (meth == RAND_OpenSSL()) {
318 /* fill random pool and seed the master DRBG */
319 RAND_DRBG *drbg = RAND_DRBG_get0_master();
324 rand_drbg_lock(drbg);
325 ret = rand_drbg_restart(drbg, NULL, 0, 0);
326 rand_drbg_unlock(drbg);
331 RAND_POOL *pool = NULL;
333 /* fill random pool and seed the current legacy RNG */
334 pool = rand_pool_new(RAND_DRBG_STRENGTH,
335 (RAND_DRBG_STRENGTH + 7) / 8,
336 RAND_POOL_MAX_LENGTH);
340 if (rand_pool_acquire_entropy(pool) == 0)
343 if (meth->add == NULL
344 || meth->add(rand_pool_buffer(pool),
345 rand_pool_length(pool),
346 (rand_pool_entropy(pool) / 8.0)) == 0)
352 rand_pool_free(pool);
357 #endif /* FIPS_MODE */
360 * Allocate memory and initialize a new random pool
363 RAND_POOL *rand_pool_new(int entropy_requested, size_t min_len, size_t max_len)
365 RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
368 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
372 pool->min_len = min_len;
373 pool->max_len = (max_len > RAND_POOL_MAX_LENGTH) ?
374 RAND_POOL_MAX_LENGTH : max_len;
376 pool->buffer = OPENSSL_secure_zalloc(pool->max_len);
377 if (pool->buffer == NULL) {
378 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
382 pool->entropy_requested = entropy_requested;
392 * Attach new random pool to the given buffer
394 * This function is intended to be used only for feeding random data
395 * provided by RAND_add() and RAND_seed() into the <master> DRBG.
397 RAND_POOL *rand_pool_attach(const unsigned char *buffer, size_t len,
400 RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
403 RANDerr(RAND_F_RAND_POOL_ATTACH, ERR_R_MALLOC_FAILURE);
408 * The const needs to be cast away, but attached buffers will not be
409 * modified (in contrary to allocated buffers which are zeroed and
412 pool->buffer = (unsigned char *) buffer;
417 pool->min_len = pool->max_len = pool->len;
418 pool->entropy = entropy;
424 * Free |pool|, securely erasing its buffer.
426 void rand_pool_free(RAND_POOL *pool)
432 * Although it would be advisable from a cryptographical viewpoint,
433 * we are not allowed to clear attached buffers, since they are passed
434 * to rand_pool_attach() as `const unsigned char*`.
435 * (see corresponding comment in rand_pool_attach()).
438 OPENSSL_secure_clear_free(pool->buffer, pool->max_len);
443 * Return the |pool|'s buffer to the caller (readonly).
445 const unsigned char *rand_pool_buffer(RAND_POOL *pool)
451 * Return the |pool|'s entropy to the caller.
453 size_t rand_pool_entropy(RAND_POOL *pool)
455 return pool->entropy;
459 * Return the |pool|'s buffer length to the caller.
461 size_t rand_pool_length(RAND_POOL *pool)
467 * Detach the |pool| buffer and return it to the caller.
468 * It's the responsibility of the caller to free the buffer
469 * using OPENSSL_secure_clear_free() or to re-attach it
470 * again to the pool using rand_pool_reattach().
472 unsigned char *rand_pool_detach(RAND_POOL *pool)
474 unsigned char *ret = pool->buffer;
481 * Re-attach the |pool| buffer. It is only allowed to pass
482 * the |buffer| which was previously detached from the same pool.
484 void rand_pool_reattach(RAND_POOL *pool, unsigned char *buffer)
486 pool->buffer = buffer;
487 OPENSSL_cleanse(pool->buffer, pool->len);
492 * If |entropy_factor| bits contain 1 bit of entropy, how many bytes does one
493 * need to obtain at least |bits| bits of entropy?
495 #define ENTROPY_TO_BYTES(bits, entropy_factor) \
496 (((bits) * (entropy_factor) + 7) / 8)
500 * Checks whether the |pool|'s entropy is available to the caller.
501 * This is the case when entropy count and buffer length are high enough.
504 * |entropy| if the entropy count and buffer size is large enough
507 size_t rand_pool_entropy_available(RAND_POOL *pool)
509 if (pool->entropy < pool->entropy_requested)
512 if (pool->len < pool->min_len)
515 return pool->entropy;
519 * Returns the (remaining) amount of entropy needed to fill
523 size_t rand_pool_entropy_needed(RAND_POOL *pool)
525 if (pool->entropy < pool->entropy_requested)
526 return pool->entropy_requested - pool->entropy;
532 * Returns the number of bytes needed to fill the pool, assuming
533 * the input has 1 / |entropy_factor| entropy bits per data bit.
534 * In case of an error, 0 is returned.
537 size_t rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor)
540 size_t entropy_needed = rand_pool_entropy_needed(pool);
542 if (entropy_factor < 1) {
543 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
547 bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_factor);
549 if (bytes_needed > pool->max_len - pool->len) {
550 /* not enough space left */
551 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
555 if (pool->len < pool->min_len &&
556 bytes_needed < pool->min_len - pool->len)
557 /* to meet the min_len requirement */
558 bytes_needed = pool->min_len - pool->len;
563 /* Returns the remaining number of bytes available */
564 size_t rand_pool_bytes_remaining(RAND_POOL *pool)
566 return pool->max_len - pool->len;
570 * Add random bytes to the random pool.
572 * It is expected that the |buffer| contains |len| bytes of
573 * random input which contains at least |entropy| bits of
576 * Returns 1 if the added amount is adequate, otherwise 0
578 int rand_pool_add(RAND_POOL *pool,
579 const unsigned char *buffer, size_t len, size_t entropy)
581 if (len > pool->max_len - pool->len) {
582 RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
586 if (pool->buffer == NULL) {
587 RANDerr(RAND_F_RAND_POOL_ADD, ERR_R_INTERNAL_ERROR);
592 memcpy(pool->buffer + pool->len, buffer, len);
594 pool->entropy += entropy;
601 * Start to add random bytes to the random pool in-place.
603 * Reserves the next |len| bytes for adding random bytes in-place
604 * and returns a pointer to the buffer.
605 * The caller is allowed to copy up to |len| bytes into the buffer.
606 * If |len| == 0 this is considered a no-op and a NULL pointer
607 * is returned without producing an error message.
609 * After updating the buffer, rand_pool_add_end() needs to be called
610 * to finish the udpate operation (see next comment).
612 unsigned char *rand_pool_add_begin(RAND_POOL *pool, size_t len)
617 if (len > pool->max_len - pool->len) {
618 RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
622 if (pool->buffer == NULL) {
623 RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, ERR_R_INTERNAL_ERROR);
627 return pool->buffer + pool->len;
631 * Finish to add random bytes to the random pool in-place.
633 * Finishes an in-place update of the random pool started by
634 * rand_pool_add_begin() (see previous comment).
635 * It is expected that |len| bytes of random input have been added
636 * to the buffer which contain at least |entropy| bits of randomness.
637 * It is allowed to add less bytes than originally reserved.
639 int rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy)
641 if (len > pool->max_len - pool->len) {
642 RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
648 pool->entropy += entropy;
655 int RAND_set_rand_method(const RAND_METHOD *meth)
657 if (!RUN_ONCE(&rand_init, do_rand_init))
660 CRYPTO_THREAD_write_lock(rand_meth_lock);
661 # ifndef OPENSSL_NO_ENGINE
662 ENGINE_finish(funct_ref);
665 default_RAND_meth = meth;
666 CRYPTO_THREAD_unlock(rand_meth_lock);
671 const RAND_METHOD *RAND_get_rand_method(void)
676 const RAND_METHOD *tmp_meth = NULL;
678 if (!RUN_ONCE(&rand_init, do_rand_init))
681 CRYPTO_THREAD_write_lock(rand_meth_lock);
682 if (default_RAND_meth == NULL) {
683 # ifndef OPENSSL_NO_ENGINE
686 /* If we have an engine that can do RAND, use it. */
687 if ((e = ENGINE_get_default_RAND()) != NULL
688 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
690 default_RAND_meth = tmp_meth;
693 default_RAND_meth = &rand_meth;
696 default_RAND_meth = &rand_meth;
699 tmp_meth = default_RAND_meth;
700 CRYPTO_THREAD_unlock(rand_meth_lock);
705 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODE)
706 int RAND_set_rand_engine(ENGINE *engine)
708 const RAND_METHOD *tmp_meth = NULL;
710 if (!RUN_ONCE(&rand_init, do_rand_init))
713 if (engine != NULL) {
714 if (!ENGINE_init(engine))
716 tmp_meth = ENGINE_get_RAND(engine);
717 if (tmp_meth == NULL) {
718 ENGINE_finish(engine);
722 CRYPTO_THREAD_write_lock(rand_engine_lock);
723 /* This function releases any prior ENGINE so call it first */
724 RAND_set_rand_method(tmp_meth);
726 CRYPTO_THREAD_unlock(rand_engine_lock);
731 void RAND_seed(const void *buf, int num)
733 const RAND_METHOD *meth = RAND_get_rand_method();
735 if (meth->seed != NULL)
736 meth->seed(buf, num);
739 void RAND_add(const void *buf, int num, double randomness)
741 const RAND_METHOD *meth = RAND_get_rand_method();
743 if (meth->add != NULL)
744 meth->add(buf, num, randomness);
748 * This function is not part of RAND_METHOD, so if we're not using
749 * the default method, then just call RAND_bytes(). Otherwise make
750 * sure we're instantiated and use the private DRBG.
752 int RAND_priv_bytes(unsigned char *buf, int num)
756 const RAND_METHOD *meth = RAND_get_rand_method();
758 if (meth != RAND_OpenSSL())
759 return RAND_bytes(buf, num);
761 drbg = RAND_DRBG_get0_private();
765 ret = RAND_DRBG_bytes(drbg, buf, num);
769 int RAND_bytes(unsigned char *buf, int num)
771 const RAND_METHOD *meth = RAND_get_rand_method();
773 if (meth->bytes != NULL)
774 return meth->bytes(buf, num);
775 RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
779 #if !OPENSSL_API_1_1_0 && !defined(FIPS_MODE)
780 int RAND_pseudo_bytes(unsigned char *buf, int num)
782 const RAND_METHOD *meth = RAND_get_rand_method();
784 if (meth->pseudorand != NULL)
785 return meth->pseudorand(buf, num);
790 int RAND_status(void)
792 const RAND_METHOD *meth = RAND_get_rand_method();
794 if (meth->status != NULL)
795 return meth->status();