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))
29 * Check for the existence and support of POSIX timers. The standard
30 * says that the _POSIX_TIMERS macro will have a positive value if they
33 * However, we want an additional constraint: that the timer support does
34 * not require an extra library dependency. Early versions of glibc
35 * require -lrt to be specified on the link line to access the timers,
36 * so this needs to be checked for.
38 * It is worse because some libraries define __GLIBC__ but don't
39 * support the version testing macro (e.g. uClibc). This means
40 * an extra check is needed.
42 * The final condition is:
43 * "have posix timers and either not glibc or glibc without -lrt"
45 * The nested #if sequences are required to avoid using a parameterised
46 * macro that might be undefined.
48 #undef OSSL_POSIX_TIMER_OKAY
49 #if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
50 # if defined(__GLIBC__)
51 # if defined(__GLIBC_PREREQ)
52 # if __GLIBC_PREREQ(2, 17)
53 # define OSSL_POSIX_TIMER_OKAY
57 # define OSSL_POSIX_TIMER_OKAY
61 #ifndef OPENSSL_NO_ENGINE
62 /* non-NULL if default_RAND_meth is ENGINE-provided */
63 static ENGINE
*funct_ref
;
64 static CRYPTO_RWLOCK
*rand_engine_lock
;
66 static CRYPTO_RWLOCK
*rand_meth_lock
;
67 static const RAND_METHOD
*default_RAND_meth
;
68 static CRYPTO_ONCE rand_init
= CRYPTO_ONCE_STATIC_INIT
;
72 #ifdef OPENSSL_RAND_SEED_RDTSC
74 * IMPORTANT NOTE: It is not currently possible to use this code
75 * because we are not sure about the amount of randomness it provides.
76 * Some SP900 tests have been run, but there is internal skepticism.
77 * So for now this code is not used.
79 # error "RDTSC enabled? Should not be possible!"
82 * Acquire entropy from high-speed clock
84 * Since we get some randomness from the low-order bits of the
85 * high-speed clock, it can help.
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_tsc(RAND_POOL
*pool
)
95 if ((OPENSSL_ia32cap_P
[0] & (1 << 4)) != 0) {
96 for (i
= 0; i
< TSC_READ_COUNT
; i
++) {
97 c
= (unsigned char)(OPENSSL_rdtsc() & 0xFF);
98 rand_pool_add(pool
, &c
, 1, 4);
101 return rand_pool_entropy_available(pool
);
105 #ifdef OPENSSL_RAND_SEED_RDCPU
106 size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf
, size_t len
);
107 size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf
, size_t len
);
109 extern unsigned int OPENSSL_ia32cap_P
[];
112 * Acquire entropy using Intel-specific cpu instructions
114 * Uses the RDSEED instruction if available, otherwise uses
115 * RDRAND if available.
117 * For the differences between RDSEED and RDRAND, and why RDSEED
118 * is the preferred choice, see https://goo.gl/oK3KcN
120 * Returns the total entropy count, if it exceeds the requested
121 * entropy count. Otherwise, returns an entropy count of 0.
123 size_t rand_acquire_entropy_from_cpu(RAND_POOL
*pool
)
126 unsigned char *buffer
;
128 bytes_needed
= rand_pool_bytes_needed(pool
, 8 /*entropy_per_byte*/);
129 if (bytes_needed
> 0) {
130 buffer
= rand_pool_add_begin(pool
, bytes_needed
);
132 if (buffer
!= NULL
) {
134 /* If RDSEED is available, use that. */
135 if ((OPENSSL_ia32cap_P
[2] & (1 << 18)) != 0) {
136 if (OPENSSL_ia32_rdseed_bytes(buffer
, bytes_needed
)
138 return rand_pool_add_end(pool
,
143 /* Second choice is RDRAND. */
144 if ((OPENSSL_ia32cap_P
[1] & (1 << (62 - 32))) != 0) {
145 if (OPENSSL_ia32_rdrand_bytes(buffer
, bytes_needed
)
147 return rand_pool_add_end(pool
,
152 return rand_pool_add_end(pool
, 0, 0);
156 return rand_pool_entropy_available(pool
);
162 * Implements the get_entropy() callback (see RAND_DRBG_set_callbacks())
164 * If the DRBG has a parent, then the required amount of entropy input
165 * is fetched using the parent's RAND_DRBG_generate().
167 * Otherwise, the entropy is polled from the system entropy sources
168 * using rand_pool_acquire_entropy().
170 * If a random pool has been added to the DRBG using RAND_add(), then
171 * its entropy will be used up first.
173 size_t rand_drbg_get_entropy(RAND_DRBG
*drbg
,
174 unsigned char **pout
,
175 int entropy
, size_t min_len
, size_t max_len
,
176 int prediction_resistance
)
179 size_t entropy_available
= 0;
182 if (drbg
->parent
&& drbg
->strength
> drbg
->parent
->strength
) {
184 * We currently don't support the algorithm from NIST SP 800-90C
185 * 10.1.2 to use a weaker DRBG as source
187 RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY
, RAND_R_PARENT_STRENGTH_TOO_WEAK
);
191 pool
= rand_pool_new(entropy
, min_len
, max_len
);
197 rand_pool_buffer(drbg
->pool
),
198 rand_pool_length(drbg
->pool
),
199 rand_pool_entropy(drbg
->pool
));
200 rand_pool_free(drbg
->pool
);
205 size_t bytes_needed
= rand_pool_bytes_needed(pool
, 8);
206 unsigned char *buffer
= rand_pool_add_begin(pool
, bytes_needed
);
208 if (buffer
!= NULL
) {
212 * Get random from parent, include our state as additional input.
213 * Our lock is already held, but we need to lock our parent before
214 * generating bits from it. (Note: taking the lock will be a no-op
215 * if locking if drbg->parent->lock == NULL.)
217 rand_drbg_lock(drbg
->parent
);
218 if (RAND_DRBG_generate(drbg
->parent
,
219 buffer
, bytes_needed
,
220 prediction_resistance
,
221 (unsigned char *)drbg
, sizeof(*drbg
)) != 0)
222 bytes
= bytes_needed
;
223 rand_drbg_unlock(drbg
->parent
);
225 entropy_available
= rand_pool_add_end(pool
, bytes
, 8 * bytes
);
229 if (prediction_resistance
) {
231 * We don't have any entropy sources that comply with the NIST
232 * standard to provide prediction resistance (see NIST SP 800-90C,
235 RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY
,
236 RAND_R_PREDICTION_RESISTANCE_NOT_SUPPORTED
);
240 /* Get entropy by polling system entropy sources. */
241 entropy_available
= rand_pool_acquire_entropy(pool
);
244 if (entropy_available
> 0) {
245 ret
= rand_pool_length(pool
);
246 *pout
= rand_pool_detach(pool
);
249 rand_pool_free(pool
);
254 * Find a suitable source of time. Start with the highest resolution source
255 * and work down to the slower ones. This is added as additional data and
256 * isn't counted as randomness, so any result is acceptable.
258 * Returns 0 when we weren't able to find any time source
260 static uint64_t get_timer_bits(void)
262 uint64_t res
= OPENSSL_rdtsc();
271 if (QueryPerformanceCounter(&t
) != 0)
273 GetSystemTimeAsFileTime(&ft
);
274 return TWO32TO64(ft
.dwHighDateTime
, ft
.dwLowDateTime
);
276 #elif defined(__sun) || defined(__hpux)
282 read_wall_time(&t
, TIMEBASE_SZ
);
283 return TWO32TO64(t
.tb_high
, t
.tb_low
);
287 # if defined(OSSL_POSIX_TIMER_OKAY)
292 # ifdef CLOCK_BOOTTIME
293 cid
= CLOCK_BOOTTIME
;
294 # elif defined(_POSIX_MONOTONIC_CLOCK)
295 cid
= CLOCK_MONOTONIC
;
297 cid
= CLOCK_REALTIME
;
300 if (clock_gettime(cid
, &ts
) == 0)
301 return TWO32TO64(ts
.tv_sec
, ts
.tv_nsec
);
304 # if defined(__unix__) \
305 || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
309 if (gettimeofday(&tv
, NULL
) == 0)
310 return TWO32TO64(tv
.tv_sec
, tv
.tv_usec
);
314 time_t t
= time(NULL
);
323 * Generate additional data that can be used for the drbg. The data does
324 * not need to contain entropy, but it's useful if it contains at least
325 * some bits that are unpredictable.
327 * Returns 0 on failure.
329 * On success it allocates a buffer at |*pout| and returns the length of
330 * the data. The buffer should get freed using OPENSSL_secure_clear_free().
332 size_t rand_drbg_get_additional_data(unsigned char **pout
, size_t max_len
)
335 CRYPTO_THREAD_ID thread_id
;
337 #ifdef OPENSSL_SYS_UNIX
339 #elif defined(OPENSSL_SYS_WIN32)
344 pool
= rand_pool_new(0, 0, max_len
);
348 #ifdef OPENSSL_SYS_UNIX
350 rand_pool_add(pool
, (unsigned char *)&pid
, sizeof(pid
), 0);
351 #elif defined(OPENSSL_SYS_WIN32)
352 pid
= GetCurrentProcessId();
353 rand_pool_add(pool
, (unsigned char *)&pid
, sizeof(pid
), 0);
356 thread_id
= CRYPTO_THREAD_get_current_id();
358 rand_pool_add(pool
, (unsigned char *)&thread_id
, sizeof(thread_id
), 0);
360 tbits
= get_timer_bits();
362 rand_pool_add(pool
, (unsigned char *)&tbits
, sizeof(tbits
), 0);
364 /* TODO: Use RDSEED? */
366 len
= rand_pool_length(pool
);
368 *pout
= rand_pool_detach(pool
);
369 rand_pool_free(pool
);
375 * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
378 void rand_drbg_cleanup_entropy(RAND_DRBG
*drbg
,
379 unsigned char *out
, size_t outlen
)
381 OPENSSL_secure_clear_free(out
, outlen
);
389 DEFINE_RUN_ONCE_STATIC(do_rand_init
)
393 #ifndef OPENSSL_NO_ENGINE
394 rand_engine_lock
= CRYPTO_THREAD_lock_new();
395 ret
&= rand_engine_lock
!= NULL
;
397 rand_meth_lock
= CRYPTO_THREAD_lock_new();
398 ret
&= rand_meth_lock
!= NULL
;
403 void rand_cleanup_int(void)
405 const RAND_METHOD
*meth
= default_RAND_meth
;
407 if (meth
!= NULL
&& meth
->cleanup
!= NULL
)
409 RAND_set_rand_method(NULL
);
410 #ifndef OPENSSL_NO_ENGINE
411 CRYPTO_THREAD_lock_free(rand_engine_lock
);
413 CRYPTO_THREAD_lock_free(rand_meth_lock
);
417 * RAND_poll() reseeds the default RNG using random input
419 * The random input is obtained from polling various entropy
420 * sources which depend on the operating system and are
421 * configurable via the --with-rand-seed configure option.
427 RAND_POOL
*pool
= NULL
;
429 const RAND_METHOD
*meth
= RAND_get_rand_method();
431 if (meth
== RAND_OpenSSL()) {
432 /* fill random pool and seed the master DRBG */
433 RAND_DRBG
*drbg
= RAND_DRBG_get0_master();
438 rand_drbg_lock(drbg
);
439 ret
= rand_drbg_restart(drbg
, NULL
, 0, 0);
440 rand_drbg_unlock(drbg
);
445 /* fill random pool and seed the current legacy RNG */
446 pool
= rand_pool_new(RAND_DRBG_STRENGTH
,
447 RAND_DRBG_STRENGTH
/ 8,
448 DRBG_MINMAX_FACTOR
* (RAND_DRBG_STRENGTH
/ 8));
452 if (rand_pool_acquire_entropy(pool
) == 0)
455 if (meth
->add
== NULL
456 || meth
->add(rand_pool_buffer(pool
),
457 rand_pool_length(pool
),
458 (rand_pool_entropy(pool
) / 8.0)) == 0)
465 rand_pool_free(pool
);
470 * The 'random pool' acts as a dumb container for collecting random
471 * input from various entropy sources. The pool has no knowledge about
472 * whether its randomness is fed into a legacy RAND_METHOD via RAND_add()
473 * or into a new style RAND_DRBG. It is the callers duty to 1) initialize the
474 * random pool, 2) pass it to the polling callbacks, 3) seed the RNG, and
475 * 4) cleanup the random pool again.
477 * The random pool contains no locking mechanism because its scope and
478 * lifetime is intended to be restricted to a single stack frame.
480 struct rand_pool_st
{
481 unsigned char *buffer
; /* points to the beginning of the random pool */
482 size_t len
; /* current number of random bytes contained in the pool */
484 size_t min_len
; /* minimum number of random bytes requested */
485 size_t max_len
; /* maximum number of random bytes (allocated buffer size) */
486 size_t entropy
; /* current entropy count in bits */
487 size_t requested_entropy
; /* requested entropy count in bits */
491 * Allocate memory and initialize a new random pool
494 RAND_POOL
*rand_pool_new(int entropy
, size_t min_len
, size_t max_len
)
496 RAND_POOL
*pool
= OPENSSL_zalloc(sizeof(*pool
));
499 RANDerr(RAND_F_RAND_POOL_NEW
, ERR_R_MALLOC_FAILURE
);
503 pool
->min_len
= min_len
;
504 pool
->max_len
= max_len
;
506 pool
->buffer
= OPENSSL_secure_zalloc(pool
->max_len
);
507 if (pool
->buffer
== NULL
) {
508 RANDerr(RAND_F_RAND_POOL_NEW
, ERR_R_MALLOC_FAILURE
);
512 pool
->requested_entropy
= entropy
;
522 * Free |pool|, securely erasing its buffer.
524 void rand_pool_free(RAND_POOL
*pool
)
529 OPENSSL_secure_clear_free(pool
->buffer
, pool
->max_len
);
534 * Return the |pool|'s buffer to the caller (readonly).
536 const unsigned char *rand_pool_buffer(RAND_POOL
*pool
)
542 * Return the |pool|'s entropy to the caller.
544 size_t rand_pool_entropy(RAND_POOL
*pool
)
546 return pool
->entropy
;
550 * Return the |pool|'s buffer length to the caller.
552 size_t rand_pool_length(RAND_POOL
*pool
)
558 * Detach the |pool| buffer and return it to the caller.
559 * It's the responsibility of the caller to free the buffer
560 * using OPENSSL_secure_clear_free().
562 unsigned char *rand_pool_detach(RAND_POOL
*pool
)
564 unsigned char *ret
= pool
->buffer
;
571 * If every byte of the input contains |entropy_per_bytes| bits of entropy,
572 * how many bytes does one need to obtain at least |bits| bits of entropy?
574 #define ENTROPY_TO_BYTES(bits, entropy_per_bytes) \
575 (((bits) + ((entropy_per_bytes) - 1))/(entropy_per_bytes))
579 * Checks whether the |pool|'s entropy is available to the caller.
580 * This is the case when entropy count and buffer length are high enough.
583 * |entropy| if the entropy count and buffer size is large enough
586 size_t rand_pool_entropy_available(RAND_POOL
*pool
)
588 if (pool
->entropy
< pool
->requested_entropy
)
591 if (pool
->len
< pool
->min_len
)
594 return pool
->entropy
;
598 * Returns the (remaining) amount of entropy needed to fill
602 size_t rand_pool_entropy_needed(RAND_POOL
*pool
)
604 if (pool
->entropy
< pool
->requested_entropy
)
605 return pool
->requested_entropy
- pool
->entropy
;
611 * Returns the number of bytes needed to fill the pool, assuming
612 * the input has 'entropy_per_byte' entropy bits per byte.
613 * In case of an error, 0 is returned.
616 size_t rand_pool_bytes_needed(RAND_POOL
*pool
, unsigned int entropy_per_byte
)
619 size_t entropy_needed
= rand_pool_entropy_needed(pool
);
621 if (entropy_per_byte
< 1 || entropy_per_byte
> 8) {
622 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED
, RAND_R_ARGUMENT_OUT_OF_RANGE
);
626 bytes_needed
= ENTROPY_TO_BYTES(entropy_needed
, entropy_per_byte
);
628 if (bytes_needed
> pool
->max_len
- pool
->len
) {
629 /* not enough space left */
630 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED
, RAND_R_RANDOM_POOL_OVERFLOW
);
634 if (pool
->len
< pool
->min_len
&&
635 bytes_needed
< pool
->min_len
- pool
->len
)
636 /* to meet the min_len requirement */
637 bytes_needed
= pool
->min_len
- pool
->len
;
642 /* Returns the remaining number of bytes available */
643 size_t rand_pool_bytes_remaining(RAND_POOL
*pool
)
645 return pool
->max_len
- pool
->len
;
649 * Add random bytes to the random pool.
651 * It is expected that the |buffer| contains |len| bytes of
652 * random input which contains at least |entropy| bits of
655 * Return available amount of entropy after this operation.
656 * (see rand_pool_entropy_available(pool))
658 size_t rand_pool_add(RAND_POOL
*pool
,
659 const unsigned char *buffer
, size_t len
, size_t entropy
)
661 if (len
> pool
->max_len
- pool
->len
) {
662 RANDerr(RAND_F_RAND_POOL_ADD
, RAND_R_ENTROPY_INPUT_TOO_LONG
);
667 memcpy(pool
->buffer
+ pool
->len
, buffer
, len
);
669 pool
->entropy
+= entropy
;
672 return rand_pool_entropy_available(pool
);
676 * Start to add random bytes to the random pool in-place.
678 * Reserves the next |len| bytes for adding random bytes in-place
679 * and returns a pointer to the buffer.
680 * The caller is allowed to copy up to |len| bytes into the buffer.
681 * If |len| == 0 this is considered a no-op and a NULL pointer
682 * is returned without producing an error message.
684 * After updating the buffer, rand_pool_add_end() needs to be called
685 * to finish the udpate operation (see next comment).
687 unsigned char *rand_pool_add_begin(RAND_POOL
*pool
, size_t len
)
692 if (len
> pool
->max_len
- pool
->len
) {
693 RANDerr(RAND_F_RAND_POOL_ADD_BEGIN
, RAND_R_RANDOM_POOL_OVERFLOW
);
697 return pool
->buffer
+ pool
->len
;
701 * Finish to add random bytes to the random pool in-place.
703 * Finishes an in-place update of the random pool started by
704 * rand_pool_add_begin() (see previous comment).
705 * It is expected that |len| bytes of random input have been added
706 * to the buffer which contain at least |entropy| bits of randomness.
707 * It is allowed to add less bytes than originally reserved.
709 size_t rand_pool_add_end(RAND_POOL
*pool
, size_t len
, size_t entropy
)
711 if (len
> pool
->max_len
- pool
->len
) {
712 RANDerr(RAND_F_RAND_POOL_ADD_END
, RAND_R_RANDOM_POOL_OVERFLOW
);
718 pool
->entropy
+= entropy
;
721 return rand_pool_entropy_available(pool
);
724 int RAND_set_rand_method(const RAND_METHOD
*meth
)
726 if (!RUN_ONCE(&rand_init
, do_rand_init
))
729 CRYPTO_THREAD_write_lock(rand_meth_lock
);
730 #ifndef OPENSSL_NO_ENGINE
731 ENGINE_finish(funct_ref
);
734 default_RAND_meth
= meth
;
735 CRYPTO_THREAD_unlock(rand_meth_lock
);
739 const RAND_METHOD
*RAND_get_rand_method(void)
741 const RAND_METHOD
*tmp_meth
= NULL
;
743 if (!RUN_ONCE(&rand_init
, do_rand_init
))
746 CRYPTO_THREAD_write_lock(rand_meth_lock
);
747 if (default_RAND_meth
== NULL
) {
748 #ifndef OPENSSL_NO_ENGINE
751 /* If we have an engine that can do RAND, use it. */
752 if ((e
= ENGINE_get_default_RAND()) != NULL
753 && (tmp_meth
= ENGINE_get_RAND(e
)) != NULL
) {
755 default_RAND_meth
= tmp_meth
;
758 default_RAND_meth
= &rand_meth
;
761 default_RAND_meth
= &rand_meth
;
764 tmp_meth
= default_RAND_meth
;
765 CRYPTO_THREAD_unlock(rand_meth_lock
);
769 #ifndef OPENSSL_NO_ENGINE
770 int RAND_set_rand_engine(ENGINE
*engine
)
772 const RAND_METHOD
*tmp_meth
= NULL
;
774 if (!RUN_ONCE(&rand_init
, do_rand_init
))
777 if (engine
!= NULL
) {
778 if (!ENGINE_init(engine
))
780 tmp_meth
= ENGINE_get_RAND(engine
);
781 if (tmp_meth
== NULL
) {
782 ENGINE_finish(engine
);
786 CRYPTO_THREAD_write_lock(rand_engine_lock
);
787 /* This function releases any prior ENGINE so call it first */
788 RAND_set_rand_method(tmp_meth
);
790 CRYPTO_THREAD_unlock(rand_engine_lock
);
795 void RAND_seed(const void *buf
, int num
)
797 const RAND_METHOD
*meth
= RAND_get_rand_method();
799 if (meth
->seed
!= NULL
)
800 meth
->seed(buf
, num
);
803 void RAND_add(const void *buf
, int num
, double randomness
)
805 const RAND_METHOD
*meth
= RAND_get_rand_method();
807 if (meth
->add
!= NULL
)
808 meth
->add(buf
, num
, randomness
);
812 * This function is not part of RAND_METHOD, so if we're not using
813 * the default method, then just call RAND_bytes(). Otherwise make
814 * sure we're instantiated and use the private DRBG.
816 int RAND_priv_bytes(unsigned char *buf
, int num
)
818 const RAND_METHOD
*meth
= RAND_get_rand_method();
822 if (meth
!= RAND_OpenSSL())
823 return RAND_bytes(buf
, num
);
825 drbg
= RAND_DRBG_get0_private();
829 /* We have to lock the DRBG before generating bits from it. */
830 rand_drbg_lock(drbg
);
831 ret
= RAND_DRBG_bytes(drbg
, buf
, num
);
832 rand_drbg_unlock(drbg
);
836 int RAND_bytes(unsigned char *buf
, int num
)
838 const RAND_METHOD
*meth
= RAND_get_rand_method();
840 if (meth
->bytes
!= NULL
)
841 return meth
->bytes(buf
, num
);
842 RANDerr(RAND_F_RAND_BYTES
, RAND_R_FUNC_NOT_IMPLEMENTED
);
846 #if OPENSSL_API_COMPAT < 0x10100000L
847 int RAND_pseudo_bytes(unsigned char *buf
, int num
)
849 const RAND_METHOD
*meth
= RAND_get_rand_method();
851 if (meth
->pseudorand
!= NULL
)
852 return meth
->pseudorand(buf
, num
);
857 int RAND_status(void)
859 const RAND_METHOD
*meth
= RAND_get_rand_method();
861 if (meth
->status
!= NULL
)
862 return meth
->status();