2 * Copyright 1995-2016 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
15 #if !(defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_DSPBIOS))
16 # include <sys/time.h>
18 #if defined(OPENSSL_SYS_VXWORKS)
22 #include <openssl/opensslconf.h>
23 #include <openssl/crypto.h>
24 #include <openssl/rand.h>
25 #include <openssl/async.h>
28 #include <openssl/err.h>
30 #include <internal/thread_once.h>
33 # include <openssl/fips.h>
36 #if defined(BN_DEBUG) || defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
40 /* #define PREDICT 1 */
42 #define STATE_SIZE 1023
43 static size_t state_num = 0, state_index = 0;
44 static unsigned char state[STATE_SIZE + MD_DIGEST_LENGTH];
45 static unsigned char md[MD_DIGEST_LENGTH];
46 static long md_count[2] = { 0, 0 };
48 static double entropy = 0;
49 static int initialized = 0;
51 static CRYPTO_RWLOCK *rand_lock = NULL;
52 static CRYPTO_RWLOCK *rand_tmp_lock = NULL;
53 static CRYPTO_ONCE rand_lock_init = CRYPTO_ONCE_STATIC_INIT;
55 /* May be set only when a thread holds rand_lock (to prevent double locking) */
56 static unsigned int crypto_lock_rand = 0;
57 /* access to locking_threadid is synchronized by rand_tmp_lock */
58 /* valid iff crypto_lock_rand is set */
59 static CRYPTO_THREAD_ID locking_threadid;
62 int rand_predictable = 0;
65 static int rand_hw_seed(EVP_MD_CTX *ctx);
67 static void rand_cleanup(void);
68 static int rand_seed(const void *buf, int num);
69 static int rand_add(const void *buf, int num, double add_entropy);
70 static int rand_bytes(unsigned char *buf, int num, int pseudo);
71 static int rand_nopseudo_bytes(unsigned char *buf, int num);
72 #if OPENSSL_API_COMPAT < 0x10100000L
73 static int rand_pseudo_bytes(unsigned char *buf, int num);
75 static int rand_status(void);
77 static RAND_METHOD rand_meth = {
82 #if OPENSSL_API_COMPAT < 0x10100000L
90 DEFINE_RUN_ONCE_STATIC(do_rand_lock_init)
92 OPENSSL_init_crypto(0, NULL);
93 rand_lock = CRYPTO_THREAD_lock_new();
94 rand_tmp_lock = CRYPTO_THREAD_lock_new();
95 return rand_lock != NULL && rand_tmp_lock != NULL;
98 RAND_METHOD *RAND_OpenSSL(void)
103 static void rand_cleanup(void)
105 OPENSSL_cleanse(state, sizeof(state));
108 OPENSSL_cleanse(md, MD_DIGEST_LENGTH);
113 CRYPTO_THREAD_lock_free(rand_lock);
114 CRYPTO_THREAD_lock_free(rand_tmp_lock);
117 static int rand_add(const void *buf, int num, double add)
121 unsigned char local_md[MD_DIGEST_LENGTH];
130 if (rand_predictable)
135 * (Based on the rand(3) manpage)
137 * The input is chopped up into units of 20 bytes (or less for
138 * the last block). Each of these blocks is run through the hash
139 * function as follows: The data passed to the hash function
140 * is the current 'md', the same number of bytes from the 'state'
141 * (the location determined by in incremented looping index) as
142 * the current 'block', the new key data 'block', and 'count'
143 * (which is incremented after each use).
144 * The result of this is kept in 'md' and also xored into the
145 * 'state' at the same locations that were used as input into the
149 m = EVP_MD_CTX_new();
153 if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
156 /* check if we already have the lock */
157 if (crypto_lock_rand) {
158 CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
159 CRYPTO_THREAD_read_lock(rand_tmp_lock);
160 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
161 CRYPTO_THREAD_unlock(rand_tmp_lock);
166 CRYPTO_THREAD_write_lock(rand_lock);
167 st_idx = state_index;
170 * use our own copies of the counters so that even if a concurrent thread
171 * seeds with exactly the same data and uses the same subarray there's
174 md_c[0] = md_count[0];
175 md_c[1] = md_count[1];
177 memcpy(local_md, md, sizeof md);
179 /* state_index <= state_num <= STATE_SIZE */
181 if (state_index >= STATE_SIZE) {
182 state_index %= STATE_SIZE;
183 state_num = STATE_SIZE;
184 } else if (state_num < STATE_SIZE) {
185 if (state_index > state_num)
186 state_num = state_index;
188 /* state_index <= state_num <= STATE_SIZE */
191 * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
192 * will use now, but other threads may use them as well
195 md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
198 CRYPTO_THREAD_unlock(rand_lock);
200 for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
202 j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
206 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
208 k = (st_idx + j) - STATE_SIZE;
210 if (!MD_Update(m, &(state[st_idx]), j - k))
212 if (!MD_Update(m, &(state[0]), k))
214 } else if (!MD_Update(m, &(state[st_idx]), j))
217 /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
218 if (!MD_Update(m, buf, j))
221 * We know that line may cause programs such as purify and valgrind
222 * to complain about use of uninitialized data. The problem is not,
223 * it's with the caller. Removing that line will make sure you get
224 * really bad randomness and thereby other problems such as very
228 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
230 if (!MD_Final(m, local_md))
234 buf = (const char *)buf + j;
236 for (k = 0; k < j; k++) {
238 * Parallel threads may interfere with this, but always each byte
239 * of the new state is the XOR of some previous value of its and
240 * local_md (intermediate values may be lost). Alway using locking
241 * could hurt performance more than necessary given that
242 * conflicts occur only when the total seeding is longer than the
245 state[st_idx++] ^= local_md[k];
246 if (st_idx >= STATE_SIZE)
252 CRYPTO_THREAD_write_lock(rand_lock);
254 * Don't just copy back local_md into md -- this could mean that other
255 * thread's seeding remains without effect (except for the incremented
256 * counter). By XORing it we keep at least as much entropy as fits into
259 for (k = 0; k < (int)sizeof(md); k++) {
260 md[k] ^= local_md[k];
262 if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
265 CRYPTO_THREAD_unlock(rand_lock);
273 static int rand_seed(const void *buf, int num)
275 return rand_add(buf, num, (double)num);
278 static int rand_bytes(unsigned char *buf, int num, int pseudo)
280 static volatile int stirred_pool = 0;
282 size_t num_ceil, st_idx, st_num;
285 unsigned char local_md[MD_DIGEST_LENGTH];
287 #ifndef GETPID_IS_MEANINGLESS
288 pid_t curr_pid = getpid();
290 time_t curr_time = time(NULL);
291 int do_stir_pool = 0;
292 /* time value for various platforms */
293 #ifdef OPENSSL_SYS_WIN32
298 SystemTimeToFileTime(&t, &tv);
300 GetSystemTimeAsFileTime(&tv);
302 #elif defined(OPENSSL_SYS_VXWORKS)
304 clock_gettime(CLOCK_REALTIME, &ts);
305 #elif defined(OPENSSL_SYS_DSPBIOS)
306 unsigned long long tv, OPENSSL_rdtsc();
307 tv = OPENSSL_rdtsc();
310 gettimeofday(&tv, NULL);
314 if (rand_predictable) {
315 unsigned char val = 1;
317 for (i = 0; i < num; i++)
326 m = EVP_MD_CTX_new();
330 /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
332 (1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
335 * (Based on the rand(3) manpage:)
337 * For each group of 10 bytes (or less), we do the following:
339 * Input into the hash function the local 'md' (which is initialized from
340 * the global 'md' before any bytes are generated), the bytes that are to
341 * be overwritten by the random bytes, and bytes from the 'state'
342 * (incrementing looping index). From this digest output (which is kept
343 * in 'md'), the top (up to) 10 bytes are returned to the caller and the
344 * bottom 10 bytes are xored into the 'state'.
346 * Finally, after we have finished 'num' random bytes for the
347 * caller, 'count' (which is incremented) and the local and global 'md'
348 * are fed into the hash function and the results are kept in the
352 if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
355 CRYPTO_THREAD_write_lock(rand_lock);
357 * We could end up in an async engine while holding this lock so ensure
358 * we don't pause and cause a deadlock
362 /* prevent rand_bytes() from trying to obtain the lock again */
363 CRYPTO_THREAD_write_lock(rand_tmp_lock);
364 locking_threadid = CRYPTO_THREAD_get_current_id();
365 CRYPTO_THREAD_unlock(rand_tmp_lock);
366 crypto_lock_rand = 1;
376 ok = (entropy >= ENTROPY_NEEDED);
379 * If the PRNG state is not yet unpredictable, then seeing the PRNG
380 * output may help attackers to determine the new state; thus we have
381 * to decrease the entropy estimate. Once we've had enough initial
382 * seeding we don't bother to adjust the entropy count, though,
383 * because we're not ambitious to provide *information-theoretic*
384 * randomness. NOTE: This approach fails if the program forks before
385 * we have enough entropy. Entropy should be collected in a separate
386 * input pool and be transferred to the output pool only when the
387 * entropy limit has been reached.
396 * In the output function only half of 'md' remains secret, so we
397 * better make sure that the required entropy gets 'evenly
398 * distributed' through 'state', our randomness pool. The input
399 * function (rand_add) chains all of 'md', which makes it more
400 * suitable for this purpose.
403 int n = STATE_SIZE; /* so that the complete pool gets accessed */
405 #if MD_DIGEST_LENGTH > 20
406 # error "Please adjust DUMMY_SEED."
408 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
410 * Note that the seed does not matter, it's just that
411 * rand_add expects to have something to hash.
413 rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
414 n -= MD_DIGEST_LENGTH;
420 st_idx = state_index;
422 md_c[0] = md_count[0];
423 md_c[1] = md_count[1];
424 memcpy(local_md, md, sizeof md);
426 state_index += num_ceil;
427 if (state_index > state_num)
428 state_index %= state_num;
431 * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
432 * ours (but other threads may use them too)
437 /* before unlocking, we must clear 'crypto_lock_rand' */
438 crypto_lock_rand = 0;
439 ASYNC_unblock_pause();
440 CRYPTO_THREAD_unlock(rand_lock);
443 /* num_ceil -= MD_DIGEST_LENGTH/2 */
444 j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
448 #ifndef GETPID_IS_MEANINGLESS
449 if (curr_pid) { /* just in the first iteration to save time */
450 if (!MD_Update(m, (unsigned char *)&curr_pid, sizeof curr_pid))
455 if (curr_time) { /* just in the first iteration to save time */
456 if (!MD_Update(m, (unsigned char *)&curr_time, sizeof curr_time))
458 if (!MD_Update(m, (unsigned char *)&tv, sizeof tv))
461 if (!rand_hw_seed(m))
464 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
466 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
469 k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
471 if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
473 if (!MD_Update(m, &(state[0]), k))
475 } else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
477 if (!MD_Final(m, local_md))
480 for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
481 /* may compete with other threads */
482 state[st_idx++] ^= local_md[i];
483 if (st_idx >= st_num)
486 *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
491 || !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
492 || !MD_Update(m, local_md, MD_DIGEST_LENGTH))
494 CRYPTO_THREAD_write_lock(rand_lock);
496 * Prevent deadlocks if we end up in an async engine
499 if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
500 CRYPTO_THREAD_unlock(rand_lock);
503 ASYNC_unblock_pause();
504 CRYPTO_THREAD_unlock(rand_lock);
512 RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
513 ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
514 "https://www.openssl.org/docs/faq.html");
518 RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
522 RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
528 static int rand_nopseudo_bytes(unsigned char *buf, int num)
530 return rand_bytes(buf, num, 0);
533 #if OPENSSL_API_COMPAT < 0x10100000L
535 * pseudo-random bytes that are guaranteed to be unique but not unpredictable
537 static int rand_pseudo_bytes(unsigned char *buf, int num)
539 return rand_bytes(buf, num, 1);
543 static int rand_status(void)
545 CRYPTO_THREAD_ID cur;
549 if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
552 cur = CRYPTO_THREAD_get_current_id();
554 * check if we already have the lock (could happen if a RAND_poll()
555 * implementation calls RAND_status())
557 if (crypto_lock_rand) {
558 CRYPTO_THREAD_read_lock(rand_tmp_lock);
559 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
560 CRYPTO_THREAD_unlock(rand_tmp_lock);
565 CRYPTO_THREAD_write_lock(rand_lock);
567 * Prevent deadlocks in case we end up in an async engine
572 * prevent rand_bytes() from trying to obtain the lock again
574 CRYPTO_THREAD_write_lock(rand_tmp_lock);
575 locking_threadid = cur;
576 CRYPTO_THREAD_unlock(rand_tmp_lock);
577 crypto_lock_rand = 1;
585 ret = entropy >= ENTROPY_NEEDED;
588 /* before unlocking, we must clear 'crypto_lock_rand' */
589 crypto_lock_rand = 0;
591 ASYNC_unblock_pause();
592 CRYPTO_THREAD_unlock(rand_lock);
599 * rand_hw_seed: get seed data from any available hardware RNG. only
600 * currently supports rdrand.
603 /* Adapted from eng_rdrand.c */
605 #if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
606 defined(__x86_64) || defined(__x86_64__) || \
607 defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
608 && !defined(OPENSSL_NO_RDRAND)
610 # define RDRAND_CALLS 4
612 size_t OPENSSL_ia32_rdrand(void);
613 extern unsigned int OPENSSL_ia32cap_P[];
615 static int rand_hw_seed(EVP_MD_CTX *ctx)
618 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
620 for (i = 0; i < RDRAND_CALLS; i++) {
622 rnd = OPENSSL_ia32_rdrand();
625 if (!MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t)))
631 /* XOR an existing buffer with random data */
633 void rand_hw_xor(unsigned char *buf, size_t num)
636 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
638 while (num >= sizeof(size_t)) {
639 rnd = OPENSSL_ia32_rdrand();
642 *((size_t *)buf) ^= rnd;
643 buf += sizeof(size_t);
644 num -= sizeof(size_t);
647 rnd = OPENSSL_ia32_rdrand();
661 static int rand_hw_seed(EVP_MD_CTX *ctx)
666 void rand_hw_xor(unsigned char *buf, size_t num)