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"
18 #ifdef OPENSSL_SYS_UNIX
19 # include <sys/types.h>
21 # include <sys/time.h>
25 /* Macro to convert two thirty two bit values into a sixty four bit one */
26 #define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
28 #ifndef OPENSSL_NO_ENGINE
29 /* non-NULL if default_RAND_meth is ENGINE-provided */
30 static ENGINE *funct_ref;
31 static CRYPTO_RWLOCK *rand_engine_lock;
33 static CRYPTO_RWLOCK *rand_meth_lock;
34 static const RAND_METHOD *default_RAND_meth;
35 static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
39 #ifdef OPENSSL_RAND_SEED_RDTSC
41 * IMPORTANT NOTE: It is not currently possible to use this code
42 * because we are not sure about the amount of randomness it provides.
43 * Some SP900 tests have been run, but there is internal skepticism.
44 * So for now this code is not used.
46 # error "RDTSC enabled? Should not be possible!"
49 * Acquire entropy from high-speed clock
51 * Since we get some randomness from the low-order bits of the
52 * high-speed clock, it can help.
54 * Returns the total entropy count, if it exceeds the requested
55 * entropy count. Otherwise, returns an entropy count of 0.
57 size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool)
62 if ((OPENSSL_ia32cap_P[0] & (1 << 4)) != 0) {
63 for (i = 0; i < TSC_READ_COUNT; i++) {
64 c = (unsigned char)(OPENSSL_rdtsc() & 0xFF);
65 RAND_POOL_add(pool, &c, 1, 4);
68 return RAND_POOL_entropy_available(pool);
72 #ifdef OPENSSL_RAND_SEED_RDCPU
73 size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len);
74 size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len);
76 extern unsigned int OPENSSL_ia32cap_P[];
79 * Acquire entropy using Intel-specific cpu instructions
81 * Uses the RDSEED instruction if available, otherwise uses
82 * RDRAND if available.
84 * For the differences between RDSEED and RDRAND, and why RDSEED
85 * is the preferred choice, see https://goo.gl/oK3KcN
87 * Returns the total entropy count, if it exceeds the requested
88 * entropy count. Otherwise, returns an entropy count of 0.
90 size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool)
93 unsigned char *buffer;
95 bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/);
96 if (bytes_needed > 0) {
97 buffer = RAND_POOL_add_begin(pool, bytes_needed);
101 /* If RDSEED is available, use that. */
102 if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
103 if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed)
105 return RAND_POOL_add_end(pool,
110 /* Second choice is RDRAND. */
111 if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
112 if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed)
114 return RAND_POOL_add_end(pool,
119 return RAND_POOL_add_end(pool, 0, 0);
123 return RAND_POOL_entropy_available(pool);
129 * Implements the get_entropy() callback (see RAND_DRBG_set_callbacks())
131 * If the DRBG has a parent, then the required amount of entropy input
132 * is fetched using the parent's RAND_DRBG_generate().
134 * Otherwise, the entropy is polled from the system entropy sources
135 * using RAND_POOL_acquire_entropy().
137 * If a random pool has been added to the DRBG using RAND_add(), then
138 * its entropy will be used up first.
140 size_t rand_drbg_get_entropy(RAND_DRBG *drbg,
141 unsigned char **pout,
142 int entropy, size_t min_len, size_t max_len)
145 size_t entropy_available = 0;
146 RAND_POOL *pool = RAND_POOL_new(entropy, min_len, max_len);
153 RAND_POOL_buffer(drbg->pool),
154 RAND_POOL_length(drbg->pool),
155 RAND_POOL_entropy(drbg->pool));
156 RAND_POOL_free(drbg->pool);
161 size_t bytes_needed = RAND_POOL_bytes_needed(pool, 8);
162 unsigned char *buffer = RAND_POOL_add_begin(pool, bytes_needed);
164 if (buffer != NULL) {
168 * Get random from parent, include our state as additional input.
169 * Our lock is already held, but we need to lock our parent before
170 * generating bits from it.
172 if (drbg->parent->lock)
173 CRYPTO_THREAD_write_lock(drbg->parent->lock);
174 if (RAND_DRBG_generate(drbg->parent,
175 buffer, bytes_needed,
177 (unsigned char *)drbg, sizeof(*drbg)) != 0)
178 bytes = bytes_needed;
179 if (drbg->parent->lock)
180 CRYPTO_THREAD_unlock(drbg->parent->lock);
182 entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes);
186 /* Get entropy by polling system entropy sources. */
187 entropy_available = RAND_POOL_acquire_entropy(pool);
190 if (entropy_available > 0) {
191 ret = RAND_POOL_length(pool);
192 *pout = RAND_POOL_detach(pool);
195 RAND_POOL_free(pool);
200 * Find a suitable system time. Start with the highest resolution source
201 * and work down to the slower ones. This is added as additional data and
202 * isn't counted as randomness, so any result is acceptable.
204 static uint64_t get_timer_bits(void)
206 uint64_t res = OPENSSL_rdtsc();
215 if (QueryPerformanceCounter(&t) != 0)
217 GetSystemTimeAsFileTime(&ft);
218 return TWO32TO64(ft.dwHighDateTime, ft.dwLowDateTime);
220 #elif defined(__sun) || defined(__hpux)
226 read_wall_time(&t, TIMEBASE_SZ);
227 return TWO32TO64(t.tb_high, t.tb_low);
231 # if defined(_POSIX_C_SOURCE) \
232 && defined(_POSIX_TIMERS) \
233 && _POSIX_C_SOURCE >= 199309L \
234 && (!defined(__GLIBC__) \
235 || (defined(__GLIBC_PREREQ) && __GLIBC_PREREQ(2, 17)))
240 # ifdef CLOCK_BOOTTIME
241 cid = CLOCK_BOOTTIME;
242 # elif defined(_POSIX_MONOTONIC_CLOCK)
243 cid = CLOCK_MONOTONIC;
245 cid = CLOCK_REALTIME;
248 if (clock_gettime(cid, &ts) == 0)
249 return TWO32TO64(ts.tv_sec, ts.tv_nsec);
252 # if defined(__unix__) \
253 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
257 if (gettimeofday(&tv, NULL) == 0)
258 return TWO32TO64(tv.tv_sec, tv.tv_usec);
266 * Generate additional data that can be used for the drbg. The data does
267 * not need to contain entropy, but it's useful if it contains at least
268 * some bits that are unpredictable.
270 * Returns 0 on failure.
272 * On success it allocates a buffer at |*pout| and returns the length of
273 * the data. The buffer should get freed using OPENSSL_secure_clear_free().
275 size_t rand_drbg_get_additional_data(unsigned char **pout, size_t max_len)
278 CRYPTO_THREAD_ID thread_id;
280 #ifdef OPENSSL_SYS_UNIX
282 #elif defined(OPENSSL_SYS_WIN32)
287 pool = RAND_POOL_new(0, 0, max_len);
291 #ifdef OPENSSL_SYS_UNIX
293 RAND_POOL_add(pool, (unsigned char *)&pid, sizeof(pid), 0);
294 #elif defined(OPENSSL_SYS_WIN32)
295 pid = GetCurrentProcessId();
296 RAND_POOL_add(pool, (unsigned char *)&pid, sizeof(pid), 0);
299 thread_id = CRYPTO_THREAD_get_current_id();
301 RAND_POOL_add(pool, (unsigned char *)&thread_id, sizeof(thread_id), 0);
303 tbits = get_timer_bits();
304 RAND_POOL_add(pool, (unsigned char *)&tbits, sizeof(tbits), 0);
306 /* TODO: Use RDSEED? */
308 len = RAND_POOL_length(pool);
310 *pout = RAND_POOL_detach(pool);
311 RAND_POOL_free(pool);
317 * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
320 void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
321 unsigned char *out, size_t outlen)
323 OPENSSL_secure_clear_free(out, outlen);
331 DEFINE_RUN_ONCE_STATIC(do_rand_init)
335 #ifndef OPENSSL_NO_ENGINE
336 rand_engine_lock = CRYPTO_THREAD_lock_new();
337 ret &= rand_engine_lock != NULL;
339 rand_meth_lock = CRYPTO_THREAD_lock_new();
340 ret &= rand_meth_lock != NULL;
345 void rand_cleanup_int(void)
347 const RAND_METHOD *meth = default_RAND_meth;
349 if (meth != NULL && meth->cleanup != NULL)
351 RAND_set_rand_method(NULL);
352 #ifndef OPENSSL_NO_ENGINE
353 CRYPTO_THREAD_lock_free(rand_engine_lock);
355 CRYPTO_THREAD_lock_free(rand_meth_lock);
359 * RAND_poll() reseeds the default RNG using random input
361 * The random input is obtained from polling various entropy
362 * sources which depend on the operating system and are
363 * configurable via the --with-rand-seed configure option.
369 RAND_POOL *pool = NULL;
371 const RAND_METHOD *meth = RAND_get_rand_method();
373 if (meth == RAND_OpenSSL()) {
374 /* fill random pool and seed the master DRBG */
375 RAND_DRBG *drbg = RAND_DRBG_get0_master();
380 CRYPTO_THREAD_write_lock(drbg->lock);
381 ret = rand_drbg_restart(drbg, NULL, 0, 0);
382 CRYPTO_THREAD_unlock(drbg->lock);
387 /* fill random pool and seed the current legacy RNG */
388 pool = RAND_POOL_new(RAND_DRBG_STRENGTH,
389 RAND_DRBG_STRENGTH / 8,
390 DRBG_MINMAX_FACTOR * (RAND_DRBG_STRENGTH / 8));
394 if (RAND_POOL_acquire_entropy(pool) == 0)
397 if (meth->add == NULL
398 || meth->add(RAND_POOL_buffer(pool),
399 RAND_POOL_length(pool),
400 (RAND_POOL_entropy(pool) / 8.0)) == 0)
407 RAND_POOL_free(pool);
412 * The 'random pool' acts as a dumb container for collecting random
413 * input from various entropy sources. The pool has no knowledge about
414 * whether its randomness is fed into a legacy RAND_METHOD via RAND_add()
415 * or into a new style RAND_DRBG. It is the callers duty to 1) initialize the
416 * random pool, 2) pass it to the polling callbacks, 3) seed the RNG, and
417 * 4) cleanup the random pool again.
419 * The random pool contains no locking mechanism because its scope and
420 * lifetime is intended to be restricted to a single stack frame.
422 struct rand_pool_st {
423 unsigned char *buffer; /* points to the beginning of the random pool */
424 size_t len; /* current number of random bytes contained in the pool */
426 size_t min_len; /* minimum number of random bytes requested */
427 size_t max_len; /* maximum number of random bytes (allocated buffer size) */
428 size_t entropy; /* current entropy count in bits */
429 size_t requested_entropy; /* requested entropy count in bits */
433 * Allocate memory and initialize a new random pool
436 RAND_POOL *RAND_POOL_new(int entropy, size_t min_len, size_t max_len)
438 RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
441 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
445 pool->min_len = min_len;
446 pool->max_len = max_len;
448 pool->buffer = OPENSSL_secure_zalloc(pool->max_len);
449 if (pool->buffer == NULL) {
450 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
454 pool->requested_entropy = entropy;
464 * Free |pool|, securely erasing its buffer.
466 void RAND_POOL_free(RAND_POOL *pool)
471 OPENSSL_secure_clear_free(pool->buffer, pool->max_len);
476 * Return the |pool|'s buffer to the caller (readonly).
478 const unsigned char *RAND_POOL_buffer(RAND_POOL *pool)
484 * Return the |pool|'s entropy to the caller.
486 size_t RAND_POOL_entropy(RAND_POOL *pool)
488 return pool->entropy;
492 * Return the |pool|'s buffer length to the caller.
494 size_t RAND_POOL_length(RAND_POOL *pool)
500 * Detach the |pool| buffer and return it to the caller.
501 * It's the responsibility of the caller to free the buffer
502 * using OPENSSL_secure_clear_free().
504 unsigned char *RAND_POOL_detach(RAND_POOL *pool)
506 unsigned char *ret = pool->buffer;
513 * If every byte of the input contains |entropy_per_bytes| bits of entropy,
514 * how many bytes does one need to obtain at least |bits| bits of entropy?
516 #define ENTROPY_TO_BYTES(bits, entropy_per_bytes) \
517 (((bits) + ((entropy_per_bytes) - 1))/(entropy_per_bytes))
521 * Checks whether the |pool|'s entropy is available to the caller.
522 * This is the case when entropy count and buffer length are high enough.
525 * |entropy| if the entropy count and buffer size is large enough
528 size_t RAND_POOL_entropy_available(RAND_POOL *pool)
530 if (pool->entropy < pool->requested_entropy)
533 if (pool->len < pool->min_len)
536 return pool->entropy;
540 * Returns the (remaining) amount of entropy needed to fill
544 size_t RAND_POOL_entropy_needed(RAND_POOL *pool)
546 if (pool->entropy < pool->requested_entropy)
547 return pool->requested_entropy - pool->entropy;
553 * Returns the number of bytes needed to fill the pool, assuming
554 * the input has 'entropy_per_byte' entropy bits per byte.
555 * In case of an error, 0 is returned.
558 size_t RAND_POOL_bytes_needed(RAND_POOL *pool, unsigned int entropy_per_byte)
561 size_t entropy_needed = RAND_POOL_entropy_needed(pool);
563 if (entropy_per_byte < 1 || entropy_per_byte > 8) {
564 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
568 bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_per_byte);
570 if (bytes_needed > pool->max_len - pool->len) {
571 /* not enough space left */
572 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
576 if (pool->len < pool->min_len &&
577 bytes_needed < pool->min_len - pool->len)
578 /* to meet the min_len requirement */
579 bytes_needed = pool->min_len - pool->len;
584 /* Returns the remaining number of bytes available */
585 size_t RAND_POOL_bytes_remaining(RAND_POOL *pool)
587 return pool->max_len - pool->len;
591 * Add random bytes to the random pool.
593 * It is expected that the |buffer| contains |len| bytes of
594 * random input which contains at least |entropy| bits of
597 * Return available amount of entropy after this operation.
598 * (see RAND_POOL_entropy_available(pool))
600 size_t RAND_POOL_add(RAND_POOL *pool,
601 const unsigned char *buffer, size_t len, size_t entropy)
603 if (len > pool->max_len - pool->len) {
604 RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
609 memcpy(pool->buffer + pool->len, buffer, len);
611 pool->entropy += entropy;
614 return RAND_POOL_entropy_available(pool);
618 * Start to add random bytes to the random pool in-place.
620 * Reserves the next |len| bytes for adding random bytes in-place
621 * and returns a pointer to the buffer.
622 * The caller is allowed to copy up to |len| bytes into the buffer.
623 * If |len| == 0 this is considered a no-op and a NULL pointer
624 * is returned without producing an error message.
626 * After updating the buffer, RAND_POOL_add_end() needs to be called
627 * to finish the udpate operation (see next comment).
629 unsigned char *RAND_POOL_add_begin(RAND_POOL *pool, size_t len)
634 if (len > pool->max_len - pool->len) {
635 RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
639 return pool->buffer + pool->len;
643 * Finish to add random bytes to the random pool in-place.
645 * Finishes an in-place update of the random pool started by
646 * RAND_POOL_add_begin() (see previous comment).
647 * It is expected that |len| bytes of random input have been added
648 * to the buffer which contain at least |entropy| bits of randomness.
649 * It is allowed to add less bytes than originally reserved.
651 size_t RAND_POOL_add_end(RAND_POOL *pool, size_t len, size_t entropy)
653 if (len > pool->max_len - pool->len) {
654 RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
660 pool->entropy += entropy;
663 return RAND_POOL_entropy_available(pool);
666 int RAND_set_rand_method(const RAND_METHOD *meth)
668 if (!RUN_ONCE(&rand_init, do_rand_init))
671 CRYPTO_THREAD_write_lock(rand_meth_lock);
672 #ifndef OPENSSL_NO_ENGINE
673 ENGINE_finish(funct_ref);
676 default_RAND_meth = meth;
677 CRYPTO_THREAD_unlock(rand_meth_lock);
681 const RAND_METHOD *RAND_get_rand_method(void)
683 const RAND_METHOD *tmp_meth = NULL;
685 if (!RUN_ONCE(&rand_init, do_rand_init))
688 CRYPTO_THREAD_write_lock(rand_meth_lock);
689 if (default_RAND_meth == NULL) {
690 #ifndef OPENSSL_NO_ENGINE
693 /* If we have an engine that can do RAND, use it. */
694 if ((e = ENGINE_get_default_RAND()) != NULL
695 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
697 default_RAND_meth = tmp_meth;
700 default_RAND_meth = &rand_meth;
703 default_RAND_meth = &rand_meth;
706 tmp_meth = default_RAND_meth;
707 CRYPTO_THREAD_unlock(rand_meth_lock);
711 #ifndef OPENSSL_NO_ENGINE
712 int RAND_set_rand_engine(ENGINE *engine)
714 const RAND_METHOD *tmp_meth = NULL;
716 if (!RUN_ONCE(&rand_init, do_rand_init))
719 if (engine != NULL) {
720 if (!ENGINE_init(engine))
722 tmp_meth = ENGINE_get_RAND(engine);
723 if (tmp_meth == NULL) {
724 ENGINE_finish(engine);
728 CRYPTO_THREAD_write_lock(rand_engine_lock);
729 /* This function releases any prior ENGINE so call it first */
730 RAND_set_rand_method(tmp_meth);
732 CRYPTO_THREAD_unlock(rand_engine_lock);
737 void RAND_seed(const void *buf, int num)
739 const RAND_METHOD *meth = RAND_get_rand_method();
741 if (meth->seed != NULL)
742 meth->seed(buf, num);
745 void RAND_add(const void *buf, int num, double randomness)
747 const RAND_METHOD *meth = RAND_get_rand_method();
749 if (meth->add != NULL)
750 meth->add(buf, num, randomness);
754 * This function is not part of RAND_METHOD, so if we're not using
755 * the default method, then just call RAND_bytes(). Otherwise make
756 * sure we're instantiated and use the private DRBG.
758 int RAND_priv_bytes(unsigned char *buf, int num)
760 const RAND_METHOD *meth = RAND_get_rand_method();
764 if (meth != RAND_OpenSSL())
765 return RAND_bytes(buf, num);
767 drbg = RAND_DRBG_get0_private();
771 /* We have to lock the DRBG before generating bits from it. */
772 CRYPTO_THREAD_write_lock(drbg->lock);
773 ret = RAND_DRBG_bytes(drbg, buf, num);
774 CRYPTO_THREAD_unlock(drbg->lock);
778 int RAND_bytes(unsigned char *buf, int num)
780 const RAND_METHOD *meth = RAND_get_rand_method();
782 if (meth->bytes != NULL)
783 return meth->bytes(buf, num);
784 RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
788 #if OPENSSL_API_COMPAT < 0x10100000L
789 int RAND_pseudo_bytes(unsigned char *buf, int num)
791 const RAND_METHOD *meth = RAND_get_rand_method();
793 if (meth->pseudorand != NULL)
794 return meth->pseudorand(buf, num);
799 int RAND_status(void)
801 const RAND_METHOD *meth = RAND_get_rand_method();
803 if (meth->status != NULL)
804 return meth->status();