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"
19 #ifndef OPENSSL_NO_ENGINE
20 /* non-NULL if default_RAND_meth is ENGINE-provided */
21 static ENGINE *funct_ref;
22 static CRYPTO_RWLOCK *rand_engine_lock;
24 static CRYPTO_RWLOCK *rand_meth_lock;
25 static const RAND_METHOD *default_RAND_meth;
26 static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
30 #ifdef OPENSSL_RAND_SEED_RDTSC
32 * IMPORTANT NOTE: It is not currently possible to use this code
33 * because we are not sure about the amount of randomness it provides.
34 * Some SP900 tests have been run, but there is internal skepticism.
35 * So for now this code is not used.
37 # error "RDTSC enabled? Should not be possible!"
40 * Acquire entropy from high-speed clock
42 * Since we get some randomness from the low-order bits of the
43 * high-speed clock, it can help.
45 * Returns the total entropy count, if it exceeds the requested
46 * entropy count. Otherwise, returns an entropy count of 0.
48 size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool)
53 if ((OPENSSL_ia32cap_P[0] & (1 << 4)) != 0) {
54 for (i = 0; i < TSC_READ_COUNT; i++) {
55 c = (unsigned char)(OPENSSL_rdtsc() & 0xFF);
56 RAND_POOL_add(pool, &c, 1, 4);
59 return RAND_POOL_entropy_available(pool);
63 #ifdef OPENSSL_RAND_SEED_RDCPU
64 size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len);
65 size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len);
67 extern unsigned int OPENSSL_ia32cap_P[];
70 * Acquire entropy using Intel-specific cpu instructions
72 * Uses the RDSEED instruction if available, otherwise uses
73 * RDRAND if available.
75 * For the differences between RDSEED and RDRAND, and why RDSEED
76 * is the preferred choice, see https://goo.gl/oK3KcN
78 * Returns the total entropy count, if it exceeds the requested
79 * entropy count. Otherwise, returns an entropy count of 0.
81 size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool)
84 unsigned char *buffer;
86 bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/);
87 if (bytes_needed > 0) {
88 buffer = RAND_POOL_add_begin(pool, bytes_needed);
92 /* If RDSEED is available, use that. */
93 if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
94 if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed)
96 return RAND_POOL_add_end(pool,
101 /* Second choice is RDRAND. */
102 if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
103 if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed)
105 return RAND_POOL_add_end(pool,
110 return 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)
136 size_t entropy_available = 0;
137 RAND_POOL *pool = RAND_POOL_new(entropy, min_len, max_len);
144 RAND_POOL_buffer(drbg->pool),
145 RAND_POOL_length(drbg->pool),
146 RAND_POOL_entropy(drbg->pool));
147 RAND_POOL_free(drbg->pool);
152 size_t bytes_needed = RAND_POOL_bytes_needed(pool, 8);
153 unsigned char *buffer = RAND_POOL_add_begin(pool, bytes_needed);
155 if (buffer != NULL) {
159 * Get random from parent, include our state as additional input.
160 * Our lock is already held, but we need to lock our parent before
161 * generating bits from it.
163 if (drbg->parent->lock)
164 CRYPTO_THREAD_write_lock(drbg->parent->lock);
165 if (RAND_DRBG_generate(drbg->parent,
166 buffer, bytes_needed,
168 (unsigned char *)drbg, sizeof(*drbg)) != 0)
169 bytes = bytes_needed;
170 if (drbg->parent->lock)
171 CRYPTO_THREAD_unlock(drbg->parent->lock);
173 entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes);
177 /* Get entropy by polling system entropy sources. */
178 entropy_available = RAND_POOL_acquire_entropy(pool);
181 if (entropy_available > 0) {
182 ret = RAND_POOL_length(pool);
183 *pout = RAND_POOL_detach(pool);
186 RAND_POOL_free(pool);
192 * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
195 void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
196 unsigned char *out, size_t outlen)
198 OPENSSL_secure_clear_free(out, outlen);
206 DEFINE_RUN_ONCE_STATIC(do_rand_init)
210 #ifndef OPENSSL_NO_ENGINE
211 rand_engine_lock = CRYPTO_THREAD_glock_new("rand_engine");
212 ret &= rand_engine_lock != NULL;
214 rand_meth_lock = CRYPTO_THREAD_glock_new("rand_meth");
215 ret &= rand_meth_lock != NULL;
220 void rand_cleanup_int(void)
222 const RAND_METHOD *meth = default_RAND_meth;
224 if (meth != NULL && meth->cleanup != NULL)
226 RAND_set_rand_method(NULL);
227 #ifndef OPENSSL_NO_ENGINE
228 CRYPTO_THREAD_lock_free(rand_engine_lock);
230 CRYPTO_THREAD_lock_free(rand_meth_lock);
234 * RAND_poll() reseeds the default RNG using random input
236 * The random input is obtained from polling various entropy
237 * sources which depend on the operating system and are
238 * configurable via the --with-rand-seed configure option.
244 RAND_POOL *pool = NULL;
246 const RAND_METHOD *meth = RAND_get_rand_method();
248 if (meth == RAND_OpenSSL()) {
249 /* fill random pool and seed the default DRBG */
250 RAND_DRBG *drbg = RAND_DRBG_get0_global();
255 CRYPTO_THREAD_write_lock(drbg->lock);
256 ret = rand_drbg_restart(drbg, NULL, 0, 0);
257 CRYPTO_THREAD_unlock(drbg->lock);
262 /* fill random pool and seed the current legacy RNG */
263 pool = RAND_POOL_new(RAND_DRBG_STRENGTH,
264 RAND_DRBG_STRENGTH / 8,
265 DRBG_MINMAX_FACTOR * (RAND_DRBG_STRENGTH / 8));
269 if (RAND_POOL_acquire_entropy(pool) == 0)
272 if (meth->add == NULL
273 || meth->add(RAND_POOL_buffer(pool),
274 RAND_POOL_length(pool),
275 (RAND_POOL_entropy(pool) / 8.0)) == 0)
282 RAND_POOL_free(pool);
287 * The 'random pool' acts as a dumb container for collecting random
288 * input from various entropy sources. The pool has no knowledge about
289 * whether its randomness is fed into a legacy RAND_METHOD via RAND_add()
290 * or into a new style RAND_DRBG. It is the callers duty to 1) initialize the
291 * random pool, 2) pass it to the polling callbacks, 3) seed the RNG, and
292 * 4) cleanup the random pool again.
294 * The random pool contains no locking mechanism because its scope and
295 * lifetime is intended to be restricted to a single stack frame.
297 struct rand_pool_st {
298 unsigned char *buffer; /* points to the beginning of the random pool */
299 size_t len; /* current number of random bytes contained in the pool */
301 size_t min_len; /* minimum number of random bytes requested */
302 size_t max_len; /* maximum number of random bytes (allocated buffer size) */
303 size_t entropy; /* current entropy count in bits */
304 size_t requested_entropy; /* requested entropy count in bits */
308 * Allocate memory and initialize a new random pool
311 RAND_POOL *RAND_POOL_new(int entropy, size_t min_len, size_t max_len)
313 RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
316 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
320 pool->min_len = min_len;
321 pool->max_len = max_len;
323 pool->buffer = OPENSSL_secure_zalloc(pool->max_len);
324 if (pool->buffer == NULL) {
325 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
329 pool->requested_entropy = entropy;
339 * Free |pool|, securely erasing its buffer.
341 void RAND_POOL_free(RAND_POOL *pool)
346 OPENSSL_secure_clear_free(pool->buffer, pool->max_len);
351 * Return the |pool|'s buffer to the caller (readonly).
353 const unsigned char *RAND_POOL_buffer(RAND_POOL *pool)
359 * Return the |pool|'s entropy to the caller.
361 size_t RAND_POOL_entropy(RAND_POOL *pool)
363 return pool->entropy;
367 * Return the |pool|'s buffer length to the caller.
369 size_t RAND_POOL_length(RAND_POOL *pool)
375 * Detach the |pool| buffer and return it to the caller.
376 * It's the responsibility of the caller to free the buffer
377 * using OPENSSL_secure_clear_free().
379 unsigned char *RAND_POOL_detach(RAND_POOL *pool)
381 unsigned char *ret = pool->buffer;
388 * If every byte of the input contains |entropy_per_bytes| bits of entropy,
389 * how many bytes does one need to obtain at least |bits| bits of entropy?
391 #define ENTROPY_TO_BYTES(bits, entropy_per_bytes) \
392 (((bits) + ((entropy_per_bytes) - 1))/(entropy_per_bytes))
396 * Checks whether the |pool|'s entropy is available to the caller.
397 * This is the case when entropy count and buffer length are high enough.
400 * |entropy| if the entropy count and buffer size is large enough
403 size_t RAND_POOL_entropy_available(RAND_POOL *pool)
405 if (pool->entropy < pool->requested_entropy)
408 if (pool->len < pool->min_len)
411 return pool->entropy;
415 * Returns the (remaining) amount of entropy needed to fill
419 size_t RAND_POOL_entropy_needed(RAND_POOL *pool)
421 if (pool->entropy < pool->requested_entropy)
422 return pool->requested_entropy - pool->entropy;
428 * Returns the number of bytes needed to fill the pool, assuming
429 * the input has 'entropy_per_byte' entropy bits per byte.
430 * In case of an error, 0 is returned.
433 size_t RAND_POOL_bytes_needed(RAND_POOL *pool, unsigned int entropy_per_byte)
436 size_t entropy_needed = RAND_POOL_entropy_needed(pool);
438 if (entropy_per_byte < 1 || entropy_per_byte > 8) {
439 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
443 bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_per_byte);
445 if (bytes_needed > pool->max_len - pool->len) {
446 /* not enough space left */
447 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
451 if (pool->len < pool->min_len &&
452 bytes_needed < pool->min_len - pool->len)
453 /* to meet the min_len requirement */
454 bytes_needed = pool->min_len - pool->len;
459 /* Returns the remaining number of bytes available */
460 size_t RAND_POOL_bytes_remaining(RAND_POOL *pool)
462 return pool->max_len - pool->len;
466 * Add random bytes to the random pool.
468 * It is expected that the |buffer| contains |len| bytes of
469 * random input which contains at least |entropy| bits of
472 * Return available amount of entropy after this operation.
473 * (see RAND_POOL_entropy_available(pool))
475 size_t RAND_POOL_add(RAND_POOL *pool,
476 const unsigned char *buffer, size_t len, size_t entropy)
478 if (len > pool->max_len - pool->len) {
479 RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
484 memcpy(pool->buffer + pool->len, buffer, len);
486 pool->entropy += entropy;
489 return RAND_POOL_entropy_available(pool);
493 * Start to add random bytes to the random pool in-place.
495 * Reserves the next |len| bytes for adding random bytes in-place
496 * and returns a pointer to the buffer.
497 * The caller is allowed to copy up to |len| bytes into the buffer.
498 * If |len| == 0 this is considered a no-op and a NULL pointer
499 * is returned without producing an error message.
501 * After updating the buffer, RAND_POOL_add_end() needs to be called
502 * to finish the udpate operation (see next comment).
504 unsigned char *RAND_POOL_add_begin(RAND_POOL *pool, size_t len)
509 if (len > pool->max_len - pool->len) {
510 RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
514 return pool->buffer + pool->len;
518 * Finish to add random bytes to the random pool in-place.
520 * Finishes an in-place update of the random pool started by
521 * RAND_POOL_add_begin() (see previous comment).
522 * It is expected that |len| bytes of random input have been added
523 * to the buffer which contain at least |entropy| bits of randomness.
524 * It is allowed to add less bytes than originally reserved.
526 size_t RAND_POOL_add_end(RAND_POOL *pool, size_t len, size_t entropy)
528 if (len > pool->max_len - pool->len) {
529 RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
535 pool->entropy += entropy;
538 return RAND_POOL_entropy_available(pool);
541 int RAND_set_rand_method(const RAND_METHOD *meth)
543 if (!RUN_ONCE(&rand_init, do_rand_init))
546 CRYPTO_THREAD_write_lock(rand_meth_lock);
547 #ifndef OPENSSL_NO_ENGINE
548 ENGINE_finish(funct_ref);
551 default_RAND_meth = meth;
552 CRYPTO_THREAD_unlock(rand_meth_lock);
556 const RAND_METHOD *RAND_get_rand_method(void)
558 const RAND_METHOD *tmp_meth = NULL;
560 if (!RUN_ONCE(&rand_init, do_rand_init))
563 CRYPTO_THREAD_write_lock(rand_meth_lock);
564 if (default_RAND_meth == NULL) {
565 #ifndef OPENSSL_NO_ENGINE
568 /* If we have an engine that can do RAND, use it. */
569 if ((e = ENGINE_get_default_RAND()) != NULL
570 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
572 default_RAND_meth = tmp_meth;
575 default_RAND_meth = &rand_meth;
578 default_RAND_meth = &rand_meth;
581 tmp_meth = default_RAND_meth;
582 CRYPTO_THREAD_unlock(rand_meth_lock);
586 #ifndef OPENSSL_NO_ENGINE
587 int RAND_set_rand_engine(ENGINE *engine)
589 const RAND_METHOD *tmp_meth = NULL;
591 if (!RUN_ONCE(&rand_init, do_rand_init))
594 if (engine != NULL) {
595 if (!ENGINE_init(engine))
597 tmp_meth = ENGINE_get_RAND(engine);
598 if (tmp_meth == NULL) {
599 ENGINE_finish(engine);
603 CRYPTO_THREAD_write_lock(rand_engine_lock);
604 /* This function releases any prior ENGINE so call it first */
605 RAND_set_rand_method(tmp_meth);
607 CRYPTO_THREAD_unlock(rand_engine_lock);
612 void RAND_seed(const void *buf, int num)
614 const RAND_METHOD *meth = RAND_get_rand_method();
616 if (meth->seed != NULL)
617 meth->seed(buf, num);
620 void RAND_add(const void *buf, int num, double randomness)
622 const RAND_METHOD *meth = RAND_get_rand_method();
624 if (meth->add != NULL)
625 meth->add(buf, num, randomness);
629 * This function is not part of RAND_METHOD, so if we're not using
630 * the default method, then just call RAND_bytes(). Otherwise make
631 * sure we're instantiated and use the private DRBG.
633 int RAND_priv_bytes(unsigned char *buf, int num)
635 const RAND_METHOD *meth = RAND_get_rand_method();
639 if (meth != RAND_OpenSSL())
640 return RAND_bytes(buf, num);
642 drbg = RAND_DRBG_get0_priv_global();
646 /* We have to lock the DRBG before generating bits from it. */
647 CRYPTO_THREAD_write_lock(drbg->lock);
648 ret = RAND_DRBG_generate(drbg, buf, num, 0, NULL, 0);
649 CRYPTO_THREAD_unlock(drbg->lock);
653 int RAND_bytes(unsigned char *buf, int num)
655 const RAND_METHOD *meth = RAND_get_rand_method();
657 if (meth->bytes != NULL)
658 return meth->bytes(buf, num);
659 RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
663 #if OPENSSL_API_COMPAT < 0x10100000L
664 int RAND_pseudo_bytes(unsigned char *buf, int num)
666 const RAND_METHOD *meth = RAND_get_rand_method();
668 if (meth->pseudorand != NULL)
669 return meth->pseudorand(buf, num);
674 int RAND_status(void)
676 const RAND_METHOD *meth = RAND_get_rand_method();
678 if (meth->status != NULL)
679 return meth->status();