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"
129 #include <openssl/err.h>
132 # include <openssl/fips.h>
139 /* #define PREDICT 1 */
141 #define STATE_SIZE 1023
142 static int state_num = 0, state_index = 0;
143 static unsigned char state[STATE_SIZE + MD_DIGEST_LENGTH];
144 static unsigned char md[MD_DIGEST_LENGTH];
145 static long md_count[2] = { 0, 0 };
147 static double entropy = 0;
148 static int initialized = 0;
150 static CRYPTO_RWLOCK *rand_lock = NULL;
151 static CRYPTO_RWLOCK *rand_tmp_lock = NULL;
152 static CRYPTO_ONCE rand_lock_init = CRYPTO_ONCE_STATIC_INIT;
154 /* May be set only when a thread holds rand_lock (to prevent double locking) */
155 static unsigned int crypto_lock_rand = 0;
156 /* access to locking_threadid is synchronized by rand_tmp_lock */
157 /* valid iff crypto_lock_rand is set */
158 static CRYPTO_THREAD_ID locking_threadid;
161 int rand_predictable = 0;
164 static void rand_hw_seed(EVP_MD_CTX *ctx);
166 static void rand_cleanup(void);
167 static int rand_seed(const void *buf, int num);
168 static int rand_add(const void *buf, int num, double add_entropy);
169 static int rand_bytes(unsigned char *buf, int num, int pseudo);
170 static int rand_nopseudo_bytes(unsigned char *buf, int num);
171 #if OPENSSL_API_COMPAT < 0x10100000L
172 static int rand_pseudo_bytes(unsigned char *buf, int num);
174 static int rand_status(void);
176 static RAND_METHOD rand_meth = {
181 #if OPENSSL_API_COMPAT < 0x10100000L
189 static void do_rand_lock_init(void)
191 rand_lock = CRYPTO_THREAD_lock_new();
192 rand_tmp_lock = CRYPTO_THREAD_lock_new();
195 RAND_METHOD *RAND_OpenSSL(void)
200 static void rand_cleanup(void)
202 OPENSSL_cleanse(state, sizeof(state));
205 OPENSSL_cleanse(md, MD_DIGEST_LENGTH);
210 CRYPTO_THREAD_lock_free(rand_lock);
211 CRYPTO_THREAD_lock_free(rand_tmp_lock);
214 static int rand_add(const void *buf, int num, double add)
218 unsigned char local_md[MD_DIGEST_LENGTH];
227 * (Based on the rand(3) manpage)
229 * The input is chopped up into units of 20 bytes (or less for
230 * the last block). Each of these blocks is run through the hash
231 * function as follows: The data passed to the hash function
232 * is the current 'md', the same number of bytes from the 'state'
233 * (the location determined by in incremented looping index) as
234 * the current 'block', the new key data 'block', and 'count'
235 * (which is incremented after each use).
236 * The result of this is kept in 'md' and also xored into the
237 * 'state' at the same locations that were used as input into the
241 m = EVP_MD_CTX_new();
245 CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
247 /* check if we already have the lock */
248 if (crypto_lock_rand) {
249 CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
250 CRYPTO_THREAD_read_lock(rand_tmp_lock);
251 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
252 CRYPTO_THREAD_unlock(rand_tmp_lock);
257 CRYPTO_THREAD_write_lock(rand_lock);
258 st_idx = state_index;
261 * use our own copies of the counters so that even if a concurrent thread
262 * seeds with exactly the same data and uses the same subarray there's
265 md_c[0] = md_count[0];
266 md_c[1] = md_count[1];
268 memcpy(local_md, md, sizeof md);
270 /* state_index <= state_num <= STATE_SIZE */
272 if (state_index >= STATE_SIZE) {
273 state_index %= STATE_SIZE;
274 state_num = STATE_SIZE;
275 } else if (state_num < STATE_SIZE) {
276 if (state_index > state_num)
277 state_num = state_index;
279 /* state_index <= state_num <= STATE_SIZE */
282 * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
283 * will use now, but other threads may use them as well
286 md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
289 CRYPTO_THREAD_unlock(rand_lock);
291 for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
293 j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
297 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
299 k = (st_idx + j) - STATE_SIZE;
301 if (!MD_Update(m, &(state[st_idx]), j - k))
303 if (!MD_Update(m, &(state[0]), k))
305 } else if (!MD_Update(m, &(state[st_idx]), j))
308 /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
309 if (!MD_Update(m, buf, j))
312 * We know that line may cause programs such as purify and valgrind
313 * to complain about use of uninitialized data. The problem is not,
314 * it's with the caller. Removing that line will make sure you get
315 * really bad randomness and thereby other problems such as very
319 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
321 if (!MD_Final(m, local_md))
325 buf = (const char *)buf + j;
327 for (k = 0; k < j; k++) {
329 * Parallel threads may interfere with this, but always each byte
330 * of the new state is the XOR of some previous value of its and
331 * local_md (intermediate values may be lost). Alway using locking
332 * could hurt performance more than necessary given that
333 * conflicts occur only when the total seeding is longer than the
336 state[st_idx++] ^= local_md[k];
337 if (st_idx >= STATE_SIZE)
343 CRYPTO_THREAD_write_lock(rand_lock);
345 * Don't just copy back local_md into md -- this could mean that other
346 * thread's seeding remains without effect (except for the incremented
347 * counter). By XORing it we keep at least as much entropy as fits into
350 for (k = 0; k < (int)sizeof(md); k++) {
351 md[k] ^= local_md[k];
353 if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
356 CRYPTO_THREAD_unlock(rand_lock);
364 static int rand_seed(const void *buf, int num)
366 return rand_add(buf, num, (double)num);
369 static int rand_bytes(unsigned char *buf, int num, int pseudo)
371 static volatile int stirred_pool = 0;
372 int i, j, k, st_num, st_idx;
376 unsigned char local_md[MD_DIGEST_LENGTH];
378 #ifndef GETPID_IS_MEANINGLESS
379 pid_t curr_pid = getpid();
381 time_t curr_time = time(NULL);
382 int do_stir_pool = 0;
383 /* time value for various platforms */
384 #ifdef OPENSSL_SYS_WIN32
389 SystemTimeToFileTime(&t, &tv);
391 GetSystemTimeAsFileTime(&tv);
393 #elif defined(OPENSSL_SYS_VXWORKS)
395 clock_gettime(CLOCK_REALTIME, &ts);
396 #elif defined(OPENSSL_SYS_DSPBIOS)
397 unsigned long long tv, OPENSSL_rdtsc();
398 tv = OPENSSL_rdtsc();
401 gettimeofday(&tv, NULL);
405 if (rand_predictable) {
406 static unsigned char val = 0;
408 for (i = 0; i < num; i++)
417 m = EVP_MD_CTX_new();
421 /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
423 (1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
426 * (Based on the rand(3) manpage:)
428 * For each group of 10 bytes (or less), we do the following:
430 * Input into the hash function the local 'md' (which is initialized from
431 * the global 'md' before any bytes are generated), the bytes that are to
432 * be overwritten by the random bytes, and bytes from the 'state'
433 * (incrementing looping index). From this digest output (which is kept
434 * in 'md'), the top (up to) 10 bytes are returned to the caller and the
435 * bottom 10 bytes are xored into the 'state'.
437 * Finally, after we have finished 'num' random bytes for the
438 * caller, 'count' (which is incremented) and the local and global 'md'
439 * are fed into the hash function and the results are kept in the
443 CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
444 CRYPTO_THREAD_write_lock(rand_lock);
446 * We could end up in an async engine while holding this lock so ensure
447 * we don't pause and cause a deadlock
451 /* prevent rand_bytes() from trying to obtain the lock again */
452 CRYPTO_THREAD_write_lock(rand_tmp_lock);
453 locking_threadid = CRYPTO_THREAD_get_current_id();
454 CRYPTO_THREAD_unlock(rand_tmp_lock);
455 crypto_lock_rand = 1;
465 ok = (entropy >= ENTROPY_NEEDED);
468 * If the PRNG state is not yet unpredictable, then seeing the PRNG
469 * output may help attackers to determine the new state; thus we have
470 * to decrease the entropy estimate. Once we've had enough initial
471 * seeding we don't bother to adjust the entropy count, though,
472 * because we're not ambitious to provide *information-theoretic*
473 * randomness. NOTE: This approach fails if the program forks before
474 * we have enough entropy. Entropy should be collected in a separate
475 * input pool and be transferred to the output pool only when the
476 * entropy limit has been reached.
485 * In the output function only half of 'md' remains secret, so we
486 * better make sure that the required entropy gets 'evenly
487 * distributed' through 'state', our randomness pool. The input
488 * function (rand_add) chains all of 'md', which makes it more
489 * suitable for this purpose.
492 int n = STATE_SIZE; /* so that the complete pool gets accessed */
494 #if MD_DIGEST_LENGTH > 20
495 # error "Please adjust DUMMY_SEED."
497 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
499 * Note that the seed does not matter, it's just that
500 * rand_add expects to have something to hash.
502 rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
503 n -= MD_DIGEST_LENGTH;
509 st_idx = state_index;
511 md_c[0] = md_count[0];
512 md_c[1] = md_count[1];
513 memcpy(local_md, md, sizeof md);
515 state_index += num_ceil;
516 if (state_index > state_num)
517 state_index %= state_num;
520 * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
521 * ours (but other threads may use them too)
526 /* before unlocking, we must clear 'crypto_lock_rand' */
527 crypto_lock_rand = 0;
528 ASYNC_unblock_pause();
529 CRYPTO_THREAD_unlock(rand_lock);
532 /* num_ceil -= MD_DIGEST_LENGTH/2 */
533 j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
537 #ifndef GETPID_IS_MEANINGLESS
538 if (curr_pid) { /* just in the first iteration to save time */
539 if (!MD_Update(m, (unsigned char *)&curr_pid, sizeof curr_pid))
544 if (curr_time) { /* just in the first iteration to save time */
545 if (!MD_Update(m, (unsigned char *)&curr_time, sizeof curr_time))
547 if (!MD_Update(m, (unsigned char *)&tv, sizeof tv))
552 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
554 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
557 k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
559 if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
561 if (!MD_Update(m, &(state[0]), k))
563 } else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
565 if (!MD_Final(m, local_md))
568 for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
569 /* may compete with other threads */
570 state[st_idx++] ^= local_md[i];
571 if (st_idx >= st_num)
574 *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
579 || !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
580 || !MD_Update(m, local_md, MD_DIGEST_LENGTH))
582 CRYPTO_THREAD_write_lock(rand_lock);
584 * Prevent deadlocks if we end up in an async engine
587 if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
588 CRYPTO_THREAD_unlock(rand_lock);
591 ASYNC_unblock_pause();
592 CRYPTO_THREAD_unlock(rand_lock);
600 RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
601 ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
602 "https://www.openssl.org/docs/faq.html");
606 RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
610 RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
616 static int rand_nopseudo_bytes(unsigned char *buf, int num)
618 return rand_bytes(buf, num, 0);
621 #if OPENSSL_API_COMPAT < 0x10100000L
623 * pseudo-random bytes that are guaranteed to be unique but not unpredictable
625 static int rand_pseudo_bytes(unsigned char *buf, int num)
627 return rand_bytes(buf, num, 1);
631 static int rand_status(void)
633 CRYPTO_THREAD_ID cur;
637 CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
638 cur = CRYPTO_THREAD_get_current_id();
640 * check if we already have the lock (could happen if a RAND_poll()
641 * implementation calls RAND_status())
643 if (crypto_lock_rand) {
644 CRYPTO_THREAD_read_lock(rand_tmp_lock);
645 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
646 CRYPTO_THREAD_unlock(rand_tmp_lock);
651 CRYPTO_THREAD_write_lock(rand_lock);
653 * Prevent deadlocks in case we end up in an async engine
658 * prevent rand_bytes() from trying to obtain the lock again
660 CRYPTO_THREAD_write_lock(rand_tmp_lock);
661 locking_threadid = cur;
662 CRYPTO_THREAD_unlock(rand_tmp_lock);
663 crypto_lock_rand = 1;
671 ret = entropy >= ENTROPY_NEEDED;
674 /* before unlocking, we must clear 'crypto_lock_rand' */
675 crypto_lock_rand = 0;
677 ASYNC_unblock_pause();
678 CRYPTO_THREAD_unlock(rand_lock);
685 * rand_hw_seed: get seed data from any available hardware RNG. only
686 * currently supports rdrand.
689 /* Adapted from eng_rdrand.c */
691 #if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
692 defined(__x86_64) || defined(__x86_64__) || \
693 defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
694 && !defined(OPENSSL_NO_RDRAND)
696 # define RDRAND_CALLS 4
698 size_t OPENSSL_ia32_rdrand(void);
699 extern unsigned int OPENSSL_ia32cap_P[];
701 static void rand_hw_seed(EVP_MD_CTX *ctx)
704 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
706 for (i = 0; i < RDRAND_CALLS; i++) {
708 rnd = OPENSSL_ia32_rdrand();
711 MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t));
715 /* XOR an existing buffer with random data */
717 void rand_hw_xor(unsigned char *buf, size_t num)
720 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
722 while (num >= sizeof(size_t)) {
723 rnd = OPENSSL_ia32_rdrand();
726 *((size_t *)buf) ^= rnd;
727 buf += sizeof(size_t);
728 num -= sizeof(size_t);
731 rnd = OPENSSL_ia32_rdrand();
745 static void rand_hw_seed(EVP_MD_CTX *ctx)
750 void rand_hw_xor(unsigned char *buf, size_t num)