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) {
158 /* Get entropy from parent, include our state as additional input */
159 if (RAND_DRBG_generate(drbg->parent,
160 buffer, bytes_needed,
162 (unsigned char *)drbg, sizeof(*drbg)) != 0)
163 bytes = bytes_needed;
165 entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes);
169 /* Get entropy by polling system entropy sources. */
170 entropy_available = RAND_POOL_acquire_entropy(pool);
173 if (entropy_available > 0) {
174 ret = RAND_POOL_length(pool);
175 *pout = RAND_POOL_detach(pool);
178 RAND_POOL_free(pool);
184 * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
187 void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
188 unsigned char *out, size_t outlen)
190 OPENSSL_secure_clear_free(out, outlen);
198 DEFINE_RUN_ONCE_STATIC(do_rand_init)
202 #ifndef OPENSSL_NO_ENGINE
203 rand_engine_lock = CRYPTO_THREAD_glock_new("rand_engine");
204 ret &= rand_engine_lock != NULL;
206 rand_meth_lock = CRYPTO_THREAD_glock_new("rand_meth");
207 ret &= rand_meth_lock != NULL;
212 void rand_cleanup_int(void)
214 const RAND_METHOD *meth = default_RAND_meth;
216 if (meth != NULL && meth->cleanup != NULL)
218 RAND_set_rand_method(NULL);
219 #ifndef OPENSSL_NO_ENGINE
220 CRYPTO_THREAD_lock_free(rand_engine_lock);
222 CRYPTO_THREAD_lock_free(rand_meth_lock);
226 * RAND_poll() reseeds the default RNG using random input
228 * The random input is obtained from polling various entropy
229 * sources which depend on the operating system and are
230 * configurable via the --with-rand-seed configure option.
236 RAND_POOL *pool = NULL;
238 const RAND_METHOD *meth = RAND_get_rand_method();
240 if (meth == RAND_OpenSSL()) {
241 /* fill random pool and seed the default DRBG */
242 RAND_DRBG *drbg = RAND_DRBG_get0_global();
247 CRYPTO_THREAD_write_lock(drbg->lock);
248 ret = rand_drbg_restart(drbg, NULL, 0, 0);
249 CRYPTO_THREAD_unlock(drbg->lock);
254 /* fill random pool and seed the current legacy RNG */
255 pool = RAND_POOL_new(RAND_DRBG_STRENGTH,
256 RAND_DRBG_STRENGTH / 8,
257 DRBG_MINMAX_FACTOR * (RAND_DRBG_STRENGTH / 8));
261 if (RAND_POOL_acquire_entropy(pool) == 0)
264 if (meth->add == NULL
265 || meth->add(RAND_POOL_buffer(pool),
266 RAND_POOL_length(pool),
267 (RAND_POOL_entropy(pool) / 8.0)) == 0)
274 RAND_POOL_free(pool);
279 * The 'random pool' acts as a dumb container for collecting random
280 * input from various entropy sources. The pool has no knowledge about
281 * whether its randomness is fed into a legacy RAND_METHOD via RAND_add()
282 * or into a new style RAND_DRBG. It is the callers duty to 1) initialize the
283 * random pool, 2) pass it to the polling callbacks, 3) seed the RNG, and
284 * 4) cleanup the random pool again.
286 * The random pool contains no locking mechanism because its scope and
287 * lifetime is intended to be restricted to a single stack frame.
289 struct rand_pool_st {
290 unsigned char *buffer; /* points to the beginning of the random pool */
291 size_t len; /* current number of random bytes contained in the pool */
293 size_t min_len; /* minimum number of random bytes requested */
294 size_t max_len; /* maximum number of random bytes (allocated buffer size) */
295 size_t entropy; /* current entropy count in bits */
296 size_t requested_entropy; /* requested entropy count in bits */
300 * Allocate memory and initialize a new random pool
303 RAND_POOL *RAND_POOL_new(int entropy, size_t min_len, size_t max_len)
305 RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
308 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
312 pool->min_len = min_len;
313 pool->max_len = max_len;
315 pool->buffer = OPENSSL_secure_zalloc(pool->max_len);
316 if (pool->buffer == NULL) {
317 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
321 pool->requested_entropy = entropy;
331 * Free |pool|, securely erasing its buffer.
333 void RAND_POOL_free(RAND_POOL *pool)
338 OPENSSL_secure_clear_free(pool->buffer, pool->max_len);
343 * Return the |pool|'s buffer to the caller (readonly).
345 const unsigned char *RAND_POOL_buffer(RAND_POOL *pool)
351 * Return the |pool|'s entropy to the caller.
353 size_t RAND_POOL_entropy(RAND_POOL *pool)
355 return pool->entropy;
359 * Return the |pool|'s buffer length to the caller.
361 size_t RAND_POOL_length(RAND_POOL *pool)
367 * Detach the |pool| buffer and return it to the caller.
368 * It's the responsibility of the caller to free the buffer
369 * using OPENSSL_secure_clear_free().
371 unsigned char *RAND_POOL_detach(RAND_POOL *pool)
373 unsigned char *ret = pool->buffer;
380 * If every byte of the input contains |entropy_per_bytes| bits of entropy,
381 * how many bytes does one need to obtain at least |bits| bits of entropy?
383 #define ENTROPY_TO_BYTES(bits, entropy_per_bytes) \
384 (((bits) + ((entropy_per_bytes) - 1))/(entropy_per_bytes))
388 * Checks whether the |pool|'s entropy is available to the caller.
389 * This is the case when entropy count and buffer length are high enough.
392 * |entropy| if the entropy count and buffer size is large enough
395 size_t RAND_POOL_entropy_available(RAND_POOL *pool)
397 if (pool->entropy < pool->requested_entropy)
400 if (pool->len < pool->min_len)
403 return pool->entropy;
407 * Returns the (remaining) amount of entropy needed to fill
411 size_t RAND_POOL_entropy_needed(RAND_POOL *pool)
413 if (pool->entropy < pool->requested_entropy)
414 return pool->requested_entropy - pool->entropy;
420 * Returns the number of bytes needed to fill the pool, assuming
421 * the input has 'entropy_per_byte' entropy bits per byte.
422 * In case of an error, 0 is returned.
425 size_t RAND_POOL_bytes_needed(RAND_POOL *pool, unsigned int entropy_per_byte)
428 size_t entropy_needed = RAND_POOL_entropy_needed(pool);
430 if (entropy_per_byte < 1 || entropy_per_byte > 8) {
431 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
435 bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_per_byte);
437 if (bytes_needed > pool->max_len - pool->len) {
438 /* not enough space left */
439 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
443 if (pool->len < pool->min_len &&
444 bytes_needed < pool->min_len - pool->len)
445 /* to meet the min_len requirement */
446 bytes_needed = pool->min_len - pool->len;
451 /* Returns the remaining number of bytes available */
452 size_t RAND_POOL_bytes_remaining(RAND_POOL *pool)
454 return pool->max_len - pool->len;
458 * Add random bytes to the random pool.
460 * It is expected that the |buffer| contains |len| bytes of
461 * random input which contains at least |entropy| bits of
464 * Return available amount of entropy after this operation.
465 * (see RAND_POOL_entropy_available(pool))
467 size_t RAND_POOL_add(RAND_POOL *pool,
468 const unsigned char *buffer, size_t len, size_t entropy)
470 if (len > pool->max_len - pool->len) {
471 RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
476 memcpy(pool->buffer + pool->len, buffer, len);
478 pool->entropy += entropy;
481 return RAND_POOL_entropy_available(pool);
485 * Start to add random bytes to the random pool in-place.
487 * Reserves the next |len| bytes for adding random bytes in-place
488 * and returns a pointer to the buffer.
489 * The caller is allowed to copy up to |len| bytes into the buffer.
490 * If |len| == 0 this is considered a no-op and a NULL pointer
491 * is returned without producing an error message.
493 * After updating the buffer, RAND_POOL_add_end() needs to be called
494 * to finish the udpate operation (see next comment).
496 unsigned char *RAND_POOL_add_begin(RAND_POOL *pool, size_t len)
501 if (len > pool->max_len - pool->len) {
502 RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
506 return pool->buffer + pool->len;
510 * Finish to add random bytes to the random pool in-place.
512 * Finishes an in-place update of the random pool started by
513 * RAND_POOL_add_begin() (see previous comment).
514 * It is expected that |len| bytes of random input have been added
515 * to the buffer which contain at least |entropy| bits of randomness.
516 * It is allowed to add less bytes than originally reserved.
518 size_t RAND_POOL_add_end(RAND_POOL *pool, size_t len, size_t entropy)
520 if (len > pool->max_len - pool->len) {
521 RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
527 pool->entropy += entropy;
530 return RAND_POOL_entropy_available(pool);
533 int RAND_set_rand_method(const RAND_METHOD *meth)
535 if (!RUN_ONCE(&rand_init, do_rand_init))
538 CRYPTO_THREAD_write_lock(rand_meth_lock);
539 #ifndef OPENSSL_NO_ENGINE
540 ENGINE_finish(funct_ref);
543 default_RAND_meth = meth;
544 CRYPTO_THREAD_unlock(rand_meth_lock);
548 const RAND_METHOD *RAND_get_rand_method(void)
550 const RAND_METHOD *tmp_meth = NULL;
552 if (!RUN_ONCE(&rand_init, do_rand_init))
555 CRYPTO_THREAD_write_lock(rand_meth_lock);
556 if (default_RAND_meth == NULL) {
557 #ifndef OPENSSL_NO_ENGINE
560 /* If we have an engine that can do RAND, use it. */
561 if ((e = ENGINE_get_default_RAND()) != NULL
562 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
564 default_RAND_meth = tmp_meth;
567 default_RAND_meth = &rand_meth;
570 default_RAND_meth = &rand_meth;
573 tmp_meth = default_RAND_meth;
574 CRYPTO_THREAD_unlock(rand_meth_lock);
578 #ifndef OPENSSL_NO_ENGINE
579 int RAND_set_rand_engine(ENGINE *engine)
581 const RAND_METHOD *tmp_meth = NULL;
583 if (!RUN_ONCE(&rand_init, do_rand_init))
586 if (engine != NULL) {
587 if (!ENGINE_init(engine))
589 tmp_meth = ENGINE_get_RAND(engine);
590 if (tmp_meth == NULL) {
591 ENGINE_finish(engine);
595 CRYPTO_THREAD_write_lock(rand_engine_lock);
596 /* This function releases any prior ENGINE so call it first */
597 RAND_set_rand_method(tmp_meth);
599 CRYPTO_THREAD_unlock(rand_engine_lock);
604 void RAND_seed(const void *buf, int num)
606 const RAND_METHOD *meth = RAND_get_rand_method();
608 if (meth->seed != NULL)
609 meth->seed(buf, num);
612 void RAND_add(const void *buf, int num, double randomness)
614 const RAND_METHOD *meth = RAND_get_rand_method();
616 if (meth->add != NULL)
617 meth->add(buf, num, randomness);
621 * This function is not part of RAND_METHOD, so if we're not using
622 * the default method, then just call RAND_bytes(). Otherwise make
623 * sure we're instantiated and use the private DRBG.
625 int RAND_priv_bytes(unsigned char *buf, int num)
627 const RAND_METHOD *meth = RAND_get_rand_method();
630 if (meth != RAND_OpenSSL())
631 return RAND_bytes(buf, num);
633 drbg = RAND_DRBG_get0_priv_global();
637 return RAND_DRBG_generate(drbg, buf, num, 0, NULL, 0);
640 int RAND_bytes(unsigned char *buf, int num)
642 const RAND_METHOD *meth = RAND_get_rand_method();
644 if (meth->bytes != NULL)
645 return meth->bytes(buf, num);
646 RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
650 #if OPENSSL_API_COMPAT < 0x10100000L
651 int RAND_pseudo_bytes(unsigned char *buf, int num)
653 const RAND_METHOD *meth = RAND_get_rand_method();
655 if (meth->pseudorand != NULL)
656 return meth->pseudorand(buf, num);
661 int RAND_status(void)
663 const RAND_METHOD *meth = RAND_get_rand_method();
665 if (meth->status != NULL)
666 return meth->status();