2 * Copyright 1995-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
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 #ifndef OPENSSL_NO_ENGINE
26 /* non-NULL if default_RAND_meth is ENGINE-provided */
27 static ENGINE *funct_ref;
28 static CRYPTO_RWLOCK *rand_engine_lock;
30 static CRYPTO_RWLOCK *rand_meth_lock;
31 static const RAND_METHOD *default_RAND_meth;
32 static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
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, 8 /*entropy_per_byte*/);
93 if (bytes_needed > 0) {
94 buffer = RAND_POOL_add_begin(pool, bytes_needed);
98 /* If RDSEED is available, use that. */
99 if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
100 if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed)
102 return RAND_POOL_add_end(pool,
107 /* Second choice is RDRAND. */
108 if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
109 if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed)
111 return RAND_POOL_add_end(pool,
116 return RAND_POOL_add_end(pool, 0, 0);
120 return RAND_POOL_entropy_available(pool);
126 * Implements the get_entropy() callback (see RAND_DRBG_set_callbacks())
128 * If the DRBG has a parent, then the required amount of entropy input
129 * is fetched using the parent's RAND_DRBG_generate().
131 * Otherwise, the entropy is polled from the system entropy sources
132 * using RAND_POOL_acquire_entropy().
134 * If a random pool has been added to the DRBG using RAND_add(), then
135 * its entropy will be used up first.
137 size_t rand_drbg_get_entropy(RAND_DRBG *drbg,
138 unsigned char **pout,
139 int entropy, size_t min_len, size_t max_len)
142 size_t entropy_available = 0;
143 RAND_POOL *pool = RAND_POOL_new(entropy, min_len, max_len);
150 RAND_POOL_buffer(drbg->pool),
151 RAND_POOL_length(drbg->pool),
152 RAND_POOL_entropy(drbg->pool));
153 RAND_POOL_free(drbg->pool);
158 size_t bytes_needed = RAND_POOL_bytes_needed(pool, 8);
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.
169 if (drbg->parent->lock)
170 CRYPTO_THREAD_write_lock(drbg->parent->lock);
171 if (RAND_DRBG_generate(drbg->parent,
172 buffer, bytes_needed,
174 (unsigned char *)drbg, sizeof(*drbg)) != 0)
175 bytes = bytes_needed;
176 if (drbg->parent->lock)
177 CRYPTO_THREAD_unlock(drbg->parent->lock);
179 entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes);
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 RAND_POOL_free(pool);
197 * Generate additional data that can be used for the drbg. The data does
198 * not need to contain entropy, but it's useful if it contains at least
199 * some bits that are unpredictable.
201 * Returns 0 on failure.
203 * On success it allocates a buffer at |*pout| and returns the length of
204 * the data. The buffer should get freed using OPENSSL_secure_clear_free().
206 size_t rand_drbg_get_additional_data(unsigned char **pout, size_t max_len)
209 CRYPTO_THREAD_ID thread_id;
211 #ifdef OPENSSL_SYS_UNIX
214 #elif defined(OPENSSL_SYS_WIN32)
219 #ifdef OPENSSL_CPUID_OBJ
223 pool = RAND_POOL_new(0, 0, max_len);
227 #ifdef OPENSSL_SYS_UNIX
229 RAND_POOL_add(pool, (unsigned char *)&pid, sizeof(pid), 0);
230 #elif defined(OPENSSL_SYS_WIN32)
231 pid = GetCurrentProcessId();
232 RAND_POOL_add(pool, (unsigned char *)&pid, sizeof(pid), 0);
235 thread_id = CRYPTO_THREAD_get_current_id();
237 RAND_POOL_add(pool, (unsigned char *)&thread_id, sizeof(thread_id), 0);
239 #ifdef OPENSSL_CPUID_OBJ
240 tsc = OPENSSL_rdtsc();
242 RAND_POOL_add(pool, (unsigned char *)&tsc, sizeof(tsc), 0);
245 #ifdef OPENSSL_SYS_UNIX
246 if (gettimeofday(&tv, NULL) == 0)
247 RAND_POOL_add(pool, (unsigned char *)&tv, sizeof(tv), 0);
248 #elif defined(OPENSSL_SYS_WIN32)
249 if (QueryPerformanceCounter(&pc) != 0)
250 RAND_POOL_add(pool, (unsigned char *)&pc, sizeof(pc), 0);
251 GetSystemTimeAsFileTime(&ft);
252 RAND_POOL_add(pool, (unsigned char *)&ft, sizeof(ft), 0);
255 /* TODO: Use RDSEED? */
257 len = RAND_POOL_length(pool);
259 *pout = RAND_POOL_detach(pool);
260 RAND_POOL_free(pool);
266 * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
269 void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
270 unsigned char *out, size_t outlen)
272 OPENSSL_secure_clear_free(out, outlen);
280 DEFINE_RUN_ONCE_STATIC(do_rand_init)
284 #ifndef OPENSSL_NO_ENGINE
285 rand_engine_lock = CRYPTO_THREAD_glock_new("rand_engine");
286 ret &= rand_engine_lock != NULL;
288 rand_meth_lock = CRYPTO_THREAD_glock_new("rand_meth");
289 ret &= rand_meth_lock != NULL;
294 void rand_cleanup_int(void)
296 const RAND_METHOD *meth = default_RAND_meth;
298 if (meth != NULL && meth->cleanup != NULL)
300 RAND_set_rand_method(NULL);
301 #ifndef OPENSSL_NO_ENGINE
302 CRYPTO_THREAD_lock_free(rand_engine_lock);
304 CRYPTO_THREAD_lock_free(rand_meth_lock);
308 * RAND_poll() reseeds the default RNG using random input
310 * The random input is obtained from polling various entropy
311 * sources which depend on the operating system and are
312 * configurable via the --with-rand-seed configure option.
318 RAND_POOL *pool = NULL;
320 const RAND_METHOD *meth = RAND_get_rand_method();
322 if (meth == RAND_OpenSSL()) {
323 /* fill random pool and seed the master DRBG */
324 RAND_DRBG *drbg = RAND_DRBG_get0_master();
329 CRYPTO_THREAD_write_lock(drbg->lock);
330 ret = rand_drbg_restart(drbg, NULL, 0, 0);
331 CRYPTO_THREAD_unlock(drbg->lock);
336 /* fill random pool and seed the current legacy RNG */
337 pool = RAND_POOL_new(RAND_DRBG_STRENGTH,
338 RAND_DRBG_STRENGTH / 8,
339 DRBG_MINMAX_FACTOR * (RAND_DRBG_STRENGTH / 8));
343 if (RAND_POOL_acquire_entropy(pool) == 0)
346 if (meth->add == NULL
347 || meth->add(RAND_POOL_buffer(pool),
348 RAND_POOL_length(pool),
349 (RAND_POOL_entropy(pool) / 8.0)) == 0)
356 RAND_POOL_free(pool);
361 * The 'random pool' acts as a dumb container for collecting random
362 * input from various entropy sources. The pool has no knowledge about
363 * whether its randomness is fed into a legacy RAND_METHOD via RAND_add()
364 * or into a new style RAND_DRBG. It is the callers duty to 1) initialize the
365 * random pool, 2) pass it to the polling callbacks, 3) seed the RNG, and
366 * 4) cleanup the random pool again.
368 * The random pool contains no locking mechanism because its scope and
369 * lifetime is intended to be restricted to a single stack frame.
371 struct rand_pool_st {
372 unsigned char *buffer; /* points to the beginning of the random pool */
373 size_t len; /* current number of random bytes contained in the pool */
375 size_t min_len; /* minimum number of random bytes requested */
376 size_t max_len; /* maximum number of random bytes (allocated buffer size) */
377 size_t entropy; /* current entropy count in bits */
378 size_t requested_entropy; /* requested entropy count in bits */
382 * Allocate memory and initialize a new random pool
385 RAND_POOL *RAND_POOL_new(int entropy, size_t min_len, size_t max_len)
387 RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
390 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
394 pool->min_len = min_len;
395 pool->max_len = max_len;
397 pool->buffer = OPENSSL_secure_zalloc(pool->max_len);
398 if (pool->buffer == NULL) {
399 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
403 pool->requested_entropy = entropy;
413 * Free |pool|, securely erasing its buffer.
415 void RAND_POOL_free(RAND_POOL *pool)
420 OPENSSL_secure_clear_free(pool->buffer, pool->max_len);
425 * Return the |pool|'s buffer to the caller (readonly).
427 const unsigned char *RAND_POOL_buffer(RAND_POOL *pool)
433 * Return the |pool|'s entropy to the caller.
435 size_t RAND_POOL_entropy(RAND_POOL *pool)
437 return pool->entropy;
441 * Return the |pool|'s buffer length to the caller.
443 size_t RAND_POOL_length(RAND_POOL *pool)
449 * Detach the |pool| buffer and return it to the caller.
450 * It's the responsibility of the caller to free the buffer
451 * using OPENSSL_secure_clear_free().
453 unsigned char *RAND_POOL_detach(RAND_POOL *pool)
455 unsigned char *ret = pool->buffer;
462 * If every byte of the input contains |entropy_per_bytes| bits of entropy,
463 * how many bytes does one need to obtain at least |bits| bits of entropy?
465 #define ENTROPY_TO_BYTES(bits, entropy_per_bytes) \
466 (((bits) + ((entropy_per_bytes) - 1))/(entropy_per_bytes))
470 * Checks whether the |pool|'s entropy is available to the caller.
471 * This is the case when entropy count and buffer length are high enough.
474 * |entropy| if the entropy count and buffer size is large enough
477 size_t RAND_POOL_entropy_available(RAND_POOL *pool)
479 if (pool->entropy < pool->requested_entropy)
482 if (pool->len < pool->min_len)
485 return pool->entropy;
489 * Returns the (remaining) amount of entropy needed to fill
493 size_t RAND_POOL_entropy_needed(RAND_POOL *pool)
495 if (pool->entropy < pool->requested_entropy)
496 return pool->requested_entropy - pool->entropy;
502 * Returns the number of bytes needed to fill the pool, assuming
503 * the input has 'entropy_per_byte' entropy bits per byte.
504 * In case of an error, 0 is returned.
507 size_t RAND_POOL_bytes_needed(RAND_POOL *pool, unsigned int entropy_per_byte)
510 size_t entropy_needed = RAND_POOL_entropy_needed(pool);
512 if (entropy_per_byte < 1 || entropy_per_byte > 8) {
513 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
517 bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_per_byte);
519 if (bytes_needed > pool->max_len - pool->len) {
520 /* not enough space left */
521 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
525 if (pool->len < pool->min_len &&
526 bytes_needed < pool->min_len - pool->len)
527 /* to meet the min_len requirement */
528 bytes_needed = pool->min_len - pool->len;
533 /* Returns the remaining number of bytes available */
534 size_t RAND_POOL_bytes_remaining(RAND_POOL *pool)
536 return pool->max_len - pool->len;
540 * Add random bytes to the random pool.
542 * It is expected that the |buffer| contains |len| bytes of
543 * random input which contains at least |entropy| bits of
546 * Return available amount of entropy after this operation.
547 * (see RAND_POOL_entropy_available(pool))
549 size_t RAND_POOL_add(RAND_POOL *pool,
550 const unsigned char *buffer, size_t len, size_t entropy)
552 if (len > pool->max_len - pool->len) {
553 RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
558 memcpy(pool->buffer + pool->len, buffer, len);
560 pool->entropy += entropy;
563 return RAND_POOL_entropy_available(pool);
567 * Start to add random bytes to the random pool in-place.
569 * Reserves the next |len| bytes for adding random bytes in-place
570 * and returns a pointer to the buffer.
571 * The caller is allowed to copy up to |len| bytes into the buffer.
572 * If |len| == 0 this is considered a no-op and a NULL pointer
573 * is returned without producing an error message.
575 * After updating the buffer, RAND_POOL_add_end() needs to be called
576 * to finish the udpate operation (see next comment).
578 unsigned char *RAND_POOL_add_begin(RAND_POOL *pool, size_t len)
583 if (len > pool->max_len - pool->len) {
584 RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
588 return pool->buffer + pool->len;
592 * Finish to add random bytes to the random pool in-place.
594 * Finishes an in-place update of the random pool started by
595 * RAND_POOL_add_begin() (see previous comment).
596 * It is expected that |len| bytes of random input have been added
597 * to the buffer which contain at least |entropy| bits of randomness.
598 * It is allowed to add less bytes than originally reserved.
600 size_t RAND_POOL_add_end(RAND_POOL *pool, size_t len, size_t entropy)
602 if (len > pool->max_len - pool->len) {
603 RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
609 pool->entropy += entropy;
612 return RAND_POOL_entropy_available(pool);
615 int RAND_set_rand_method(const RAND_METHOD *meth)
617 if (!RUN_ONCE(&rand_init, do_rand_init))
620 CRYPTO_THREAD_write_lock(rand_meth_lock);
621 #ifndef OPENSSL_NO_ENGINE
622 ENGINE_finish(funct_ref);
625 default_RAND_meth = meth;
626 CRYPTO_THREAD_unlock(rand_meth_lock);
630 const RAND_METHOD *RAND_get_rand_method(void)
632 const RAND_METHOD *tmp_meth = NULL;
634 if (!RUN_ONCE(&rand_init, do_rand_init))
637 CRYPTO_THREAD_write_lock(rand_meth_lock);
638 if (default_RAND_meth == NULL) {
639 #ifndef OPENSSL_NO_ENGINE
642 /* If we have an engine that can do RAND, use it. */
643 if ((e = ENGINE_get_default_RAND()) != NULL
644 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
646 default_RAND_meth = tmp_meth;
649 default_RAND_meth = &rand_meth;
652 default_RAND_meth = &rand_meth;
655 tmp_meth = default_RAND_meth;
656 CRYPTO_THREAD_unlock(rand_meth_lock);
660 #ifndef OPENSSL_NO_ENGINE
661 int RAND_set_rand_engine(ENGINE *engine)
663 const RAND_METHOD *tmp_meth = NULL;
665 if (!RUN_ONCE(&rand_init, do_rand_init))
668 if (engine != NULL) {
669 if (!ENGINE_init(engine))
671 tmp_meth = ENGINE_get_RAND(engine);
672 if (tmp_meth == NULL) {
673 ENGINE_finish(engine);
677 CRYPTO_THREAD_write_lock(rand_engine_lock);
678 /* This function releases any prior ENGINE so call it first */
679 RAND_set_rand_method(tmp_meth);
681 CRYPTO_THREAD_unlock(rand_engine_lock);
686 void RAND_seed(const void *buf, int num)
688 const RAND_METHOD *meth = RAND_get_rand_method();
690 if (meth->seed != NULL)
691 meth->seed(buf, num);
694 void RAND_add(const void *buf, int num, double randomness)
696 const RAND_METHOD *meth = RAND_get_rand_method();
698 if (meth->add != NULL)
699 meth->add(buf, num, randomness);
703 * This function is not part of RAND_METHOD, so if we're not using
704 * the default method, then just call RAND_bytes(). Otherwise make
705 * sure we're instantiated and use the private DRBG.
707 int RAND_priv_bytes(unsigned char *buf, int num)
709 const RAND_METHOD *meth = RAND_get_rand_method();
713 if (meth != RAND_OpenSSL())
714 return RAND_bytes(buf, num);
716 drbg = RAND_DRBG_get0_private();
720 /* We have to lock the DRBG before generating bits from it. */
721 CRYPTO_THREAD_write_lock(drbg->lock);
722 ret = RAND_DRBG_generate(drbg, buf, num, 0, NULL, 0);
723 CRYPTO_THREAD_unlock(drbg->lock);
727 int RAND_bytes(unsigned char *buf, int num)
729 const RAND_METHOD *meth = RAND_get_rand_method();
731 if (meth->bytes != NULL)
732 return meth->bytes(buf, num);
733 RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
737 #if OPENSSL_API_COMPAT < 0x10100000L
738 int RAND_pseudo_bytes(unsigned char *buf, int num)
740 const RAND_METHOD *meth = RAND_get_rand_method();
742 if (meth->pseudorand != NULL)
743 return meth->pseudorand(buf, num);
748 int RAND_status(void)
750 const RAND_METHOD *meth = RAND_get_rand_method();
752 if (meth->status != NULL)
753 return meth->status();