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 unsigned int crypto_lock_rand = 0; /* may be set only when a thread
151 * holds CRYPTO_LOCK_RAND (to
152 * prevent double locking) */
153 /* access to lockin_thread is synchronized by CRYPTO_LOCK_RAND2 */
154 /* valid iff crypto_lock_rand is set */
155 static CRYPTO_THREADID locking_threadid;
158 int rand_predictable = 0;
161 static void rand_hw_seed(EVP_MD_CTX *ctx);
163 static void rand_cleanup(void);
164 static int rand_seed(const void *buf, int num);
165 static int rand_add(const void *buf, int num, double add_entropy);
166 static int rand_bytes(unsigned char *buf, int num, int pseudo);
167 static int rand_nopseudo_bytes(unsigned char *buf, int num);
168 #if OPENSSL_API_COMPAT < 0x10100000L
169 static int rand_pseudo_bytes(unsigned char *buf, int num);
171 static int rand_status(void);
173 static RAND_METHOD rand_meth = {
178 #if OPENSSL_API_COMPAT < 0x10100000L
186 RAND_METHOD *RAND_OpenSSL(void)
191 static void rand_cleanup(void)
193 OPENSSL_cleanse(state, sizeof(state));
196 OPENSSL_cleanse(md, MD_DIGEST_LENGTH);
203 static int rand_add(const void *buf, int num, double add)
207 unsigned char local_md[MD_DIGEST_LENGTH];
216 * (Based on the rand(3) manpage)
218 * The input is chopped up into units of 20 bytes (or less for
219 * the last block). Each of these blocks is run through the hash
220 * function as follows: The data passed to the hash function
221 * is the current 'md', the same number of bytes from the 'state'
222 * (the location determined by in incremented looping index) as
223 * the current 'block', the new key data 'block', and 'count'
224 * (which is incremented after each use).
225 * The result of this is kept in 'md' and also xored into the
226 * 'state' at the same locations that were used as input into the
230 m = EVP_MD_CTX_new();
234 /* check if we already have the lock */
235 if (crypto_lock_rand) {
237 CRYPTO_THREADID_current(&cur);
238 CRYPTO_r_lock(CRYPTO_LOCK_RAND2);
239 do_not_lock = !CRYPTO_THREADID_cmp(&locking_threadid, &cur);
240 CRYPTO_r_unlock(CRYPTO_LOCK_RAND2);
245 CRYPTO_w_lock(CRYPTO_LOCK_RAND);
246 st_idx = state_index;
249 * use our own copies of the counters so that even if a concurrent thread
250 * seeds with exactly the same data and uses the same subarray there's
253 md_c[0] = md_count[0];
254 md_c[1] = md_count[1];
256 memcpy(local_md, md, sizeof md);
258 /* state_index <= state_num <= STATE_SIZE */
260 if (state_index >= STATE_SIZE) {
261 state_index %= STATE_SIZE;
262 state_num = STATE_SIZE;
263 } else if (state_num < STATE_SIZE) {
264 if (state_index > state_num)
265 state_num = state_index;
267 /* state_index <= state_num <= STATE_SIZE */
270 * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
271 * will use now, but other threads may use them as well
274 md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
277 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
279 for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
281 j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
285 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
287 k = (st_idx + j) - STATE_SIZE;
289 if (!MD_Update(m, &(state[st_idx]), j - k))
291 if (!MD_Update(m, &(state[0]), k))
293 } else if (!MD_Update(m, &(state[st_idx]), j))
296 /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
297 if (!MD_Update(m, buf, j))
300 * We know that line may cause programs such as purify and valgrind
301 * to complain about use of uninitialized data. The problem is not,
302 * it's with the caller. Removing that line will make sure you get
303 * really bad randomness and thereby other problems such as very
307 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
309 if (!MD_Final(m, local_md))
313 buf = (const char *)buf + j;
315 for (k = 0; k < j; k++) {
317 * Parallel threads may interfere with this, but always each byte
318 * of the new state is the XOR of some previous value of its and
319 * local_md (intermediate values may be lost). Alway using locking
320 * could hurt performance more than necessary given that
321 * conflicts occur only when the total seeding is longer than the
324 state[st_idx++] ^= local_md[k];
325 if (st_idx >= STATE_SIZE)
331 CRYPTO_w_lock(CRYPTO_LOCK_RAND);
333 * Don't just copy back local_md into md -- this could mean that other
334 * thread's seeding remains without effect (except for the incremented
335 * counter). By XORing it we keep at least as much entropy as fits into
338 for (k = 0; k < (int)sizeof(md); k++) {
339 md[k] ^= local_md[k];
341 if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
344 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
352 static int rand_seed(const void *buf, int num)
354 return rand_add(buf, num, (double)num);
357 static int rand_bytes(unsigned char *buf, int num, int pseudo)
359 static volatile int stirred_pool = 0;
360 int i, j, k, st_num, st_idx;
364 unsigned char local_md[MD_DIGEST_LENGTH];
366 #ifndef GETPID_IS_MEANINGLESS
367 pid_t curr_pid = getpid();
369 time_t curr_time = time(NULL);
370 int do_stir_pool = 0;
371 /* time value for various platforms */
372 #ifdef OPENSSL_SYS_WIN32
377 SystemTimeToFileTime(&t, &tv);
379 GetSystemTimeAsFileTime(&tv);
381 #elif defined(OPENSSL_SYS_VXWORKS)
383 clock_gettime(CLOCK_REALTIME, &ts);
384 #elif defined(OPENSSL_SYS_DSPBIOS)
385 unsigned long long tv, OPENSSL_rdtsc();
386 tv = OPENSSL_rdtsc();
389 gettimeofday(&tv, NULL);
393 if (rand_predictable) {
394 static unsigned char val = 0;
396 for (i = 0; i < num; i++)
405 m = EVP_MD_CTX_new();
409 /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
411 (1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
414 * (Based on the rand(3) manpage:)
416 * For each group of 10 bytes (or less), we do the following:
418 * Input into the hash function the local 'md' (which is initialized from
419 * the global 'md' before any bytes are generated), the bytes that are to
420 * be overwritten by the random bytes, and bytes from the 'state'
421 * (incrementing looping index). From this digest output (which is kept
422 * in 'md'), the top (up to) 10 bytes are returned to the caller and the
423 * bottom 10 bytes are xored into the 'state'.
425 * Finally, after we have finished 'num' random bytes for the
426 * caller, 'count' (which is incremented) and the local and global 'md'
427 * are fed into the hash function and the results are kept in the
431 CRYPTO_w_lock(CRYPTO_LOCK_RAND);
433 * We could end up in an async engine while holding this lock so ensure
434 * we don't pause and cause a deadlock
438 /* prevent rand_bytes() from trying to obtain the lock again */
439 CRYPTO_w_lock(CRYPTO_LOCK_RAND2);
440 CRYPTO_THREADID_current(&locking_threadid);
441 CRYPTO_w_unlock(CRYPTO_LOCK_RAND2);
442 crypto_lock_rand = 1;
452 ok = (entropy >= ENTROPY_NEEDED);
455 * If the PRNG state is not yet unpredictable, then seeing the PRNG
456 * output may help attackers to determine the new state; thus we have
457 * to decrease the entropy estimate. Once we've had enough initial
458 * seeding we don't bother to adjust the entropy count, though,
459 * because we're not ambitious to provide *information-theoretic*
460 * randomness. NOTE: This approach fails if the program forks before
461 * we have enough entropy. Entropy should be collected in a separate
462 * input pool and be transferred to the output pool only when the
463 * entropy limit has been reached.
472 * In the output function only half of 'md' remains secret, so we
473 * better make sure that the required entropy gets 'evenly
474 * distributed' through 'state', our randomness pool. The input
475 * function (rand_add) chains all of 'md', which makes it more
476 * suitable for this purpose.
479 int n = STATE_SIZE; /* so that the complete pool gets accessed */
481 #if MD_DIGEST_LENGTH > 20
482 # error "Please adjust DUMMY_SEED."
484 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
486 * Note that the seed does not matter, it's just that
487 * rand_add expects to have something to hash.
489 rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
490 n -= MD_DIGEST_LENGTH;
496 st_idx = state_index;
498 md_c[0] = md_count[0];
499 md_c[1] = md_count[1];
500 memcpy(local_md, md, sizeof md);
502 state_index += num_ceil;
503 if (state_index > state_num)
504 state_index %= state_num;
507 * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
508 * ours (but other threads may use them too)
513 /* before unlocking, we must clear 'crypto_lock_rand' */
514 crypto_lock_rand = 0;
515 ASYNC_unblock_pause();
516 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
519 /* num_ceil -= MD_DIGEST_LENGTH/2 */
520 j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
524 #ifndef GETPID_IS_MEANINGLESS
525 if (curr_pid) { /* just in the first iteration to save time */
526 if (!MD_Update(m, (unsigned char *)&curr_pid, sizeof curr_pid))
531 if (curr_time) { /* just in the first iteration to save time */
532 if (!MD_Update(m, (unsigned char *)&curr_time, sizeof curr_time))
534 if (!MD_Update(m, (unsigned char *)&tv, sizeof tv))
539 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
541 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
544 k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
546 if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
548 if (!MD_Update(m, &(state[0]), k))
550 } else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
552 if (!MD_Final(m, local_md))
555 for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
556 /* may compete with other threads */
557 state[st_idx++] ^= local_md[i];
558 if (st_idx >= st_num)
561 *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
566 || !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
567 || !MD_Update(m, local_md, MD_DIGEST_LENGTH))
569 CRYPTO_w_lock(CRYPTO_LOCK_RAND);
571 * Prevent deadlocks if we end up in an async engine
574 if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
575 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
578 ASYNC_unblock_pause();
579 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
587 RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
588 ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
589 "https://www.openssl.org/docs/faq.html");
593 RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
597 RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
603 static int rand_nopseudo_bytes(unsigned char *buf, int num)
605 return rand_bytes(buf, num, 0);
608 #if OPENSSL_API_COMPAT < 0x10100000L
610 * pseudo-random bytes that are guaranteed to be unique but not unpredictable
612 static int rand_pseudo_bytes(unsigned char *buf, int num)
614 return rand_bytes(buf, num, 1);
618 static int rand_status(void)
624 CRYPTO_THREADID_current(&cur);
626 * check if we already have the lock (could happen if a RAND_poll()
627 * implementation calls RAND_status())
629 if (crypto_lock_rand) {
630 CRYPTO_r_lock(CRYPTO_LOCK_RAND2);
631 do_not_lock = !CRYPTO_THREADID_cmp(&locking_threadid, &cur);
632 CRYPTO_r_unlock(CRYPTO_LOCK_RAND2);
637 CRYPTO_w_lock(CRYPTO_LOCK_RAND);
639 * Prevent deadlocks in case we end up in an async engine
644 * prevent rand_bytes() from trying to obtain the lock again
646 CRYPTO_w_lock(CRYPTO_LOCK_RAND2);
647 CRYPTO_THREADID_cpy(&locking_threadid, &cur);
648 CRYPTO_w_unlock(CRYPTO_LOCK_RAND2);
649 crypto_lock_rand = 1;
657 ret = entropy >= ENTROPY_NEEDED;
660 /* before unlocking, we must clear 'crypto_lock_rand' */
661 crypto_lock_rand = 0;
663 ASYNC_unblock_pause();
664 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
671 * rand_hw_seed: get seed data from any available hardware RNG. only
672 * currently supports rdrand.
675 /* Adapted from eng_rdrand.c */
677 #if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
678 defined(__x86_64) || defined(__x86_64__) || \
679 defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
680 && !defined(OPENSSL_NO_RDRAND)
682 # define RDRAND_CALLS 4
684 size_t OPENSSL_ia32_rdrand(void);
685 extern unsigned int OPENSSL_ia32cap_P[];
687 static void rand_hw_seed(EVP_MD_CTX *ctx)
690 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
692 for (i = 0; i < RDRAND_CALLS; i++) {
694 rnd = OPENSSL_ia32_rdrand();
697 MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t));
701 /* XOR an existing buffer with random data */
703 void rand_hw_xor(unsigned char *buf, size_t num)
706 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
708 while (num >= sizeof(size_t)) {
709 rnd = OPENSSL_ia32_rdrand();
712 *((size_t *)buf) ^= rnd;
713 buf += sizeof(size_t);
714 num -= sizeof(size_t);
717 rnd = OPENSSL_ia32_rdrand();
731 static void rand_hw_seed(EVP_MD_CTX *ctx)
736 void rand_hw_xor(unsigned char *buf, size_t num)