1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
57 /* ====================================================================
58 * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
86 * 6. Redistributions of any form whatsoever must retain the following
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com).
116 #if !(defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_DSPBIOS))
117 # include <sys/time.h>
119 #if defined(OPENSSL_SYS_VXWORKS)
123 #include <openssl/opensslconf.h>
124 #include <openssl/crypto.h>
125 #include <openssl/rand.h>
126 #include <openssl/async.h>
127 #include "rand_lcl.h"
128 #include "internal/threads.h"
130 #include <openssl/err.h>
133 # include <openssl/fips.h>
140 /* #define PREDICT 1 */
142 #define STATE_SIZE 1023
143 static int state_num = 0, state_index = 0;
144 static unsigned char state[STATE_SIZE + MD_DIGEST_LENGTH];
145 static unsigned char md[MD_DIGEST_LENGTH];
146 static long md_count[2] = { 0, 0 };
148 static double entropy = 0;
149 static int initialized = 0;
151 static CRYPTO_RWLOCK *rand_lock = NULL;
152 static CRYPTO_RWLOCK *rand_tmp_lock = NULL;
153 static CRYPTO_ONCE rand_lock_init = CRYPTO_ONCE_STATIC_INIT;
155 /* May be set only when a thread holds rand_lock (to prevent double locking) */
156 static unsigned int crypto_lock_rand = 0;
157 /* access to locking_threadid is synchronized by rand_tmp_lock */
158 /* valid iff crypto_lock_rand is set */
159 static CRYPTO_THREAD_ID locking_threadid;
162 int rand_predictable = 0;
165 static void rand_hw_seed(EVP_MD_CTX *ctx);
167 static void rand_cleanup(void);
168 static int rand_seed(const void *buf, int num);
169 static int rand_add(const void *buf, int num, double add_entropy);
170 static int rand_bytes(unsigned char *buf, int num, int pseudo);
171 static int rand_nopseudo_bytes(unsigned char *buf, int num);
172 #if OPENSSL_API_COMPAT < 0x10100000L
173 static int rand_pseudo_bytes(unsigned char *buf, int num);
175 static int rand_status(void);
177 static RAND_METHOD rand_meth = {
182 #if OPENSSL_API_COMPAT < 0x10100000L
190 static void do_rand_lock_init(void)
192 rand_lock = CRYPTO_THREAD_lock_new();
193 rand_tmp_lock = CRYPTO_THREAD_lock_new();
196 RAND_METHOD *RAND_OpenSSL(void)
201 static void rand_cleanup(void)
203 OPENSSL_cleanse(state, sizeof(state));
206 OPENSSL_cleanse(md, MD_DIGEST_LENGTH);
211 CRYPTO_THREAD_lock_free(rand_lock);
212 CRYPTO_THREAD_lock_free(rand_tmp_lock);
215 static int rand_add(const void *buf, int num, double add)
219 unsigned char local_md[MD_DIGEST_LENGTH];
228 * (Based on the rand(3) manpage)
230 * The input is chopped up into units of 20 bytes (or less for
231 * the last block). Each of these blocks is run through the hash
232 * function as follows: The data passed to the hash function
233 * is the current 'md', the same number of bytes from the 'state'
234 * (the location determined by in incremented looping index) as
235 * the current 'block', the new key data 'block', and 'count'
236 * (which is incremented after each use).
237 * The result of this is kept in 'md' and also xored into the
238 * 'state' at the same locations that were used as input into the
242 m = EVP_MD_CTX_new();
246 CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
248 /* check if we already have the lock */
249 if (crypto_lock_rand) {
250 CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
251 CRYPTO_THREAD_read_lock(rand_tmp_lock);
252 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
253 CRYPTO_THREAD_unlock(rand_tmp_lock);
258 CRYPTO_THREAD_write_lock(rand_lock);
259 st_idx = state_index;
262 * use our own copies of the counters so that even if a concurrent thread
263 * seeds with exactly the same data and uses the same subarray there's
266 md_c[0] = md_count[0];
267 md_c[1] = md_count[1];
269 memcpy(local_md, md, sizeof md);
271 /* state_index <= state_num <= STATE_SIZE */
273 if (state_index >= STATE_SIZE) {
274 state_index %= STATE_SIZE;
275 state_num = STATE_SIZE;
276 } else if (state_num < STATE_SIZE) {
277 if (state_index > state_num)
278 state_num = state_index;
280 /* state_index <= state_num <= STATE_SIZE */
283 * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
284 * will use now, but other threads may use them as well
287 md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
290 CRYPTO_THREAD_unlock(rand_lock);
292 for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
294 j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
298 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
300 k = (st_idx + j) - STATE_SIZE;
302 if (!MD_Update(m, &(state[st_idx]), j - k))
304 if (!MD_Update(m, &(state[0]), k))
306 } else if (!MD_Update(m, &(state[st_idx]), j))
309 /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
310 if (!MD_Update(m, buf, j))
313 * We know that line may cause programs such as purify and valgrind
314 * to complain about use of uninitialized data. The problem is not,
315 * it's with the caller. Removing that line will make sure you get
316 * really bad randomness and thereby other problems such as very
320 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
322 if (!MD_Final(m, local_md))
326 buf = (const char *)buf + j;
328 for (k = 0; k < j; k++) {
330 * Parallel threads may interfere with this, but always each byte
331 * of the new state is the XOR of some previous value of its and
332 * local_md (intermediate values may be lost). Alway using locking
333 * could hurt performance more than necessary given that
334 * conflicts occur only when the total seeding is longer than the
337 state[st_idx++] ^= local_md[k];
338 if (st_idx >= STATE_SIZE)
344 CRYPTO_THREAD_write_lock(rand_lock);
346 * Don't just copy back local_md into md -- this could mean that other
347 * thread's seeding remains without effect (except for the incremented
348 * counter). By XORing it we keep at least as much entropy as fits into
351 for (k = 0; k < (int)sizeof(md); k++) {
352 md[k] ^= local_md[k];
354 if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
357 CRYPTO_THREAD_unlock(rand_lock);
365 static int rand_seed(const void *buf, int num)
367 return rand_add(buf, num, (double)num);
370 static int rand_bytes(unsigned char *buf, int num, int pseudo)
372 static volatile int stirred_pool = 0;
373 int i, j, k, st_num, st_idx;
377 unsigned char local_md[MD_DIGEST_LENGTH];
379 #ifndef GETPID_IS_MEANINGLESS
380 pid_t curr_pid = getpid();
382 time_t curr_time = time(NULL);
383 int do_stir_pool = 0;
384 /* time value for various platforms */
385 #ifdef OPENSSL_SYS_WIN32
390 SystemTimeToFileTime(&t, &tv);
392 GetSystemTimeAsFileTime(&tv);
394 #elif defined(OPENSSL_SYS_VXWORKS)
396 clock_gettime(CLOCK_REALTIME, &ts);
397 #elif defined(OPENSSL_SYS_DSPBIOS)
398 unsigned long long tv, OPENSSL_rdtsc();
399 tv = OPENSSL_rdtsc();
402 gettimeofday(&tv, NULL);
406 if (rand_predictable) {
407 static unsigned char val = 0;
409 for (i = 0; i < num; i++)
418 m = EVP_MD_CTX_new();
422 /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
424 (1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
427 * (Based on the rand(3) manpage:)
429 * For each group of 10 bytes (or less), we do the following:
431 * Input into the hash function the local 'md' (which is initialized from
432 * the global 'md' before any bytes are generated), the bytes that are to
433 * be overwritten by the random bytes, and bytes from the 'state'
434 * (incrementing looping index). From this digest output (which is kept
435 * in 'md'), the top (up to) 10 bytes are returned to the caller and the
436 * bottom 10 bytes are xored into the 'state'.
438 * Finally, after we have finished 'num' random bytes for the
439 * caller, 'count' (which is incremented) and the local and global 'md'
440 * are fed into the hash function and the results are kept in the
444 CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
445 CRYPTO_THREAD_write_lock(rand_lock);
447 * We could end up in an async engine while holding this lock so ensure
448 * we don't pause and cause a deadlock
452 /* prevent rand_bytes() from trying to obtain the lock again */
453 CRYPTO_THREAD_write_lock(rand_tmp_lock);
454 locking_threadid = CRYPTO_THREAD_get_current_id();
455 CRYPTO_THREAD_unlock(rand_tmp_lock);
456 crypto_lock_rand = 1;
466 ok = (entropy >= ENTROPY_NEEDED);
469 * If the PRNG state is not yet unpredictable, then seeing the PRNG
470 * output may help attackers to determine the new state; thus we have
471 * to decrease the entropy estimate. Once we've had enough initial
472 * seeding we don't bother to adjust the entropy count, though,
473 * because we're not ambitious to provide *information-theoretic*
474 * randomness. NOTE: This approach fails if the program forks before
475 * we have enough entropy. Entropy should be collected in a separate
476 * input pool and be transferred to the output pool only when the
477 * entropy limit has been reached.
486 * In the output function only half of 'md' remains secret, so we
487 * better make sure that the required entropy gets 'evenly
488 * distributed' through 'state', our randomness pool. The input
489 * function (rand_add) chains all of 'md', which makes it more
490 * suitable for this purpose.
493 int n = STATE_SIZE; /* so that the complete pool gets accessed */
495 #if MD_DIGEST_LENGTH > 20
496 # error "Please adjust DUMMY_SEED."
498 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
500 * Note that the seed does not matter, it's just that
501 * rand_add expects to have something to hash.
503 rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
504 n -= MD_DIGEST_LENGTH;
510 st_idx = state_index;
512 md_c[0] = md_count[0];
513 md_c[1] = md_count[1];
514 memcpy(local_md, md, sizeof md);
516 state_index += num_ceil;
517 if (state_index > state_num)
518 state_index %= state_num;
521 * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
522 * ours (but other threads may use them too)
527 /* before unlocking, we must clear 'crypto_lock_rand' */
528 crypto_lock_rand = 0;
529 ASYNC_unblock_pause();
530 CRYPTO_THREAD_unlock(rand_lock);
533 /* num_ceil -= MD_DIGEST_LENGTH/2 */
534 j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
538 #ifndef GETPID_IS_MEANINGLESS
539 if (curr_pid) { /* just in the first iteration to save time */
540 if (!MD_Update(m, (unsigned char *)&curr_pid, sizeof curr_pid))
545 if (curr_time) { /* just in the first iteration to save time */
546 if (!MD_Update(m, (unsigned char *)&curr_time, sizeof curr_time))
548 if (!MD_Update(m, (unsigned char *)&tv, sizeof tv))
553 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
555 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
558 k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
560 if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
562 if (!MD_Update(m, &(state[0]), k))
564 } else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
566 if (!MD_Final(m, local_md))
569 for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
570 /* may compete with other threads */
571 state[st_idx++] ^= local_md[i];
572 if (st_idx >= st_num)
575 *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
580 || !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
581 || !MD_Update(m, local_md, MD_DIGEST_LENGTH))
583 CRYPTO_THREAD_write_lock(rand_lock);
585 * Prevent deadlocks if we end up in an async engine
588 if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
589 CRYPTO_THREAD_unlock(rand_lock);
592 ASYNC_unblock_pause();
593 CRYPTO_THREAD_unlock(rand_lock);
601 RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
602 ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
603 "https://www.openssl.org/docs/faq.html");
607 RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
611 RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
617 static int rand_nopseudo_bytes(unsigned char *buf, int num)
619 return rand_bytes(buf, num, 0);
622 #if OPENSSL_API_COMPAT < 0x10100000L
624 * pseudo-random bytes that are guaranteed to be unique but not unpredictable
626 static int rand_pseudo_bytes(unsigned char *buf, int num)
628 return rand_bytes(buf, num, 1);
632 static int rand_status(void)
634 CRYPTO_THREAD_ID cur;
638 CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
639 cur = CRYPTO_THREAD_get_current_id();
641 * check if we already have the lock (could happen if a RAND_poll()
642 * implementation calls RAND_status())
644 if (crypto_lock_rand) {
645 CRYPTO_THREAD_read_lock(rand_tmp_lock);
646 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
647 CRYPTO_THREAD_unlock(rand_tmp_lock);
652 CRYPTO_THREAD_write_lock(rand_lock);
654 * Prevent deadlocks in case we end up in an async engine
659 * prevent rand_bytes() from trying to obtain the lock again
661 CRYPTO_THREAD_write_lock(rand_tmp_lock);
662 locking_threadid = cur;
663 CRYPTO_THREAD_unlock(rand_tmp_lock);
664 crypto_lock_rand = 1;
672 ret = entropy >= ENTROPY_NEEDED;
675 /* before unlocking, we must clear 'crypto_lock_rand' */
676 crypto_lock_rand = 0;
678 ASYNC_unblock_pause();
679 CRYPTO_THREAD_unlock(rand_lock);
686 * rand_hw_seed: get seed data from any available hardware RNG. only
687 * currently supports rdrand.
690 /* Adapted from eng_rdrand.c */
692 #if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
693 defined(__x86_64) || defined(__x86_64__) || \
694 defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
695 && !defined(OPENSSL_NO_RDRAND)
697 # define RDRAND_CALLS 4
699 size_t OPENSSL_ia32_rdrand(void);
700 extern unsigned int OPENSSL_ia32cap_P[];
702 static void rand_hw_seed(EVP_MD_CTX *ctx)
705 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
707 for (i = 0; i < RDRAND_CALLS; i++) {
709 rnd = OPENSSL_ia32_rdrand();
712 MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t));
716 /* XOR an existing buffer with random data */
718 void rand_hw_xor(unsigned char *buf, size_t num)
721 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
723 while (num >= sizeof(size_t)) {
724 rnd = OPENSSL_ia32_rdrand();
727 *((size_t *)buf) ^= rnd;
728 buf += sizeof(size_t);
729 num -= sizeof(size_t);
732 rnd = OPENSSL_ia32_rdrand();
746 static void rand_hw_seed(EVP_MD_CTX *ctx)
751 void rand_hw_xor(unsigned char *buf, size_t num)