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>
32 #if defined(BN_DEBUG) || defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
36 /* #define PREDICT 1 */
38 #define STATE_SIZE 1023
39 static size_t state_num = 0, state_index = 0;
40 static unsigned char state[STATE_SIZE + MD_DIGEST_LENGTH];
41 static unsigned char md[MD_DIGEST_LENGTH];
42 static long md_count[2] = { 0, 0 };
44 static double entropy = 0;
45 static int initialized = 0;
47 static CRYPTO_RWLOCK *rand_lock = NULL;
48 static CRYPTO_RWLOCK *rand_tmp_lock = NULL;
49 static CRYPTO_ONCE rand_lock_init = CRYPTO_ONCE_STATIC_INIT;
51 /* May be set only when a thread holds rand_lock (to prevent double locking) */
52 static unsigned int crypto_lock_rand = 0;
53 /* access to locking_threadid is synchronized by rand_tmp_lock */
54 /* valid iff crypto_lock_rand is set */
55 static CRYPTO_THREAD_ID locking_threadid;
58 int rand_predictable = 0;
61 static int rand_hw_seed(EVP_MD_CTX *ctx);
63 static void rand_cleanup(void);
64 static int rand_seed(const void *buf, int num);
65 static int rand_add(const void *buf, int num, double add_entropy);
66 static int rand_bytes(unsigned char *buf, int num, int pseudo);
67 static int rand_nopseudo_bytes(unsigned char *buf, int num);
68 #if OPENSSL_API_COMPAT < 0x10100000L
69 static int rand_pseudo_bytes(unsigned char *buf, int num);
71 static int rand_status(void);
73 static RAND_METHOD rand_meth = {
78 #if OPENSSL_API_COMPAT < 0x10100000L
86 DEFINE_RUN_ONCE_STATIC(do_rand_lock_init)
88 OPENSSL_init_crypto(0, NULL);
89 rand_lock = CRYPTO_THREAD_lock_new();
90 rand_tmp_lock = CRYPTO_THREAD_lock_new();
91 return rand_lock != NULL && rand_tmp_lock != NULL;
94 RAND_METHOD *RAND_OpenSSL(void)
99 static void rand_cleanup(void)
101 OPENSSL_cleanse(state, sizeof(state));
104 OPENSSL_cleanse(md, MD_DIGEST_LENGTH);
109 CRYPTO_THREAD_lock_free(rand_lock);
110 CRYPTO_THREAD_lock_free(rand_tmp_lock);
113 static int rand_add(const void *buf, int num, double add)
117 unsigned char local_md[MD_DIGEST_LENGTH];
126 if (rand_predictable)
131 * (Based on the rand(3) manpage)
133 * The input is chopped up into units of 20 bytes (or less for
134 * the last block). Each of these blocks is run through the hash
135 * function as follows: The data passed to the hash function
136 * is the current 'md', the same number of bytes from the 'state'
137 * (the location determined by in incremented looping index) as
138 * the current 'block', the new key data 'block', and 'count'
139 * (which is incremented after each use).
140 * The result of this is kept in 'md' and also xored into the
141 * 'state' at the same locations that were used as input into the
145 m = EVP_MD_CTX_new();
149 if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
152 /* check if we already have the lock */
153 if (crypto_lock_rand) {
154 CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
155 CRYPTO_THREAD_read_lock(rand_tmp_lock);
156 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
157 CRYPTO_THREAD_unlock(rand_tmp_lock);
162 CRYPTO_THREAD_write_lock(rand_lock);
163 st_idx = state_index;
166 * use our own copies of the counters so that even if a concurrent thread
167 * seeds with exactly the same data and uses the same subarray there's
170 md_c[0] = md_count[0];
171 md_c[1] = md_count[1];
173 memcpy(local_md, md, sizeof md);
175 /* state_index <= state_num <= STATE_SIZE */
177 if (state_index >= STATE_SIZE) {
178 state_index %= STATE_SIZE;
179 state_num = STATE_SIZE;
180 } else if (state_num < STATE_SIZE) {
181 if (state_index > state_num)
182 state_num = state_index;
184 /* state_index <= state_num <= STATE_SIZE */
187 * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
188 * will use now, but other threads may use them as well
191 md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
194 CRYPTO_THREAD_unlock(rand_lock);
196 for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
198 j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
202 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
204 k = (st_idx + j) - STATE_SIZE;
206 if (!MD_Update(m, &(state[st_idx]), j - k))
208 if (!MD_Update(m, &(state[0]), k))
210 } else if (!MD_Update(m, &(state[st_idx]), j))
213 /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
214 if (!MD_Update(m, buf, j))
217 * We know that line may cause programs such as purify and valgrind
218 * to complain about use of uninitialized data. The problem is not,
219 * it's with the caller. Removing that line will make sure you get
220 * really bad randomness and thereby other problems such as very
224 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
226 if (!MD_Final(m, local_md))
230 buf = (const char *)buf + j;
232 for (k = 0; k < j; k++) {
234 * Parallel threads may interfere with this, but always each byte
235 * of the new state is the XOR of some previous value of its and
236 * local_md (intermediate values may be lost). Alway using locking
237 * could hurt performance more than necessary given that
238 * conflicts occur only when the total seeding is longer than the
241 state[st_idx++] ^= local_md[k];
242 if (st_idx >= STATE_SIZE)
248 CRYPTO_THREAD_write_lock(rand_lock);
250 * Don't just copy back local_md into md -- this could mean that other
251 * thread's seeding remains without effect (except for the incremented
252 * counter). By XORing it we keep at least as much entropy as fits into
255 for (k = 0; k < (int)sizeof(md); k++) {
256 md[k] ^= local_md[k];
258 if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
261 CRYPTO_THREAD_unlock(rand_lock);
269 static int rand_seed(const void *buf, int num)
271 return rand_add(buf, num, (double)num);
274 static int rand_bytes(unsigned char *buf, int num, int pseudo)
276 static volatile int stirred_pool = 0;
278 size_t num_ceil, st_idx, st_num;
281 unsigned char local_md[MD_DIGEST_LENGTH];
283 #ifndef GETPID_IS_MEANINGLESS
284 pid_t curr_pid = getpid();
286 time_t curr_time = time(NULL);
287 int do_stir_pool = 0;
288 /* time value for various platforms */
289 #ifdef OPENSSL_SYS_WIN32
294 SystemTimeToFileTime(&t, &tv);
296 GetSystemTimeAsFileTime(&tv);
298 #elif defined(OPENSSL_SYS_VXWORKS)
300 clock_gettime(CLOCK_REALTIME, &ts);
301 #elif defined(OPENSSL_SYS_DSPBIOS)
302 unsigned long long tv, OPENSSL_rdtsc();
303 tv = OPENSSL_rdtsc();
306 gettimeofday(&tv, NULL);
310 if (rand_predictable) {
311 unsigned char val = 1;
313 for (i = 0; i < num; i++)
322 m = EVP_MD_CTX_new();
326 /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
328 (1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
331 * (Based on the rand(3) manpage:)
333 * For each group of 10 bytes (or less), we do the following:
335 * Input into the hash function the local 'md' (which is initialized from
336 * the global 'md' before any bytes are generated), the bytes that are to
337 * be overwritten by the random bytes, and bytes from the 'state'
338 * (incrementing looping index). From this digest output (which is kept
339 * in 'md'), the top (up to) 10 bytes are returned to the caller and the
340 * bottom 10 bytes are xored into the 'state'.
342 * Finally, after we have finished 'num' random bytes for the
343 * caller, 'count' (which is incremented) and the local and global 'md'
344 * are fed into the hash function and the results are kept in the
348 if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
351 CRYPTO_THREAD_write_lock(rand_lock);
353 * We could end up in an async engine while holding this lock so ensure
354 * we don't pause and cause a deadlock
358 /* prevent rand_bytes() from trying to obtain the lock again */
359 CRYPTO_THREAD_write_lock(rand_tmp_lock);
360 locking_threadid = CRYPTO_THREAD_get_current_id();
361 CRYPTO_THREAD_unlock(rand_tmp_lock);
362 crypto_lock_rand = 1;
372 ok = (entropy >= ENTROPY_NEEDED);
375 * If the PRNG state is not yet unpredictable, then seeing the PRNG
376 * output may help attackers to determine the new state; thus we have
377 * to decrease the entropy estimate. Once we've had enough initial
378 * seeding we don't bother to adjust the entropy count, though,
379 * because we're not ambitious to provide *information-theoretic*
380 * randomness. NOTE: This approach fails if the program forks before
381 * we have enough entropy. Entropy should be collected in a separate
382 * input pool and be transferred to the output pool only when the
383 * entropy limit has been reached.
392 * In the output function only half of 'md' remains secret, so we
393 * better make sure that the required entropy gets 'evenly
394 * distributed' through 'state', our randomness pool. The input
395 * function (rand_add) chains all of 'md', which makes it more
396 * suitable for this purpose.
399 int n = STATE_SIZE; /* so that the complete pool gets accessed */
401 #if MD_DIGEST_LENGTH > 20
402 # error "Please adjust DUMMY_SEED."
404 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
406 * Note that the seed does not matter, it's just that
407 * rand_add expects to have something to hash.
409 rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
410 n -= MD_DIGEST_LENGTH;
416 st_idx = state_index;
418 md_c[0] = md_count[0];
419 md_c[1] = md_count[1];
420 memcpy(local_md, md, sizeof md);
422 state_index += num_ceil;
423 if (state_index > state_num)
424 state_index %= state_num;
427 * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
428 * ours (but other threads may use them too)
433 /* before unlocking, we must clear 'crypto_lock_rand' */
434 crypto_lock_rand = 0;
435 ASYNC_unblock_pause();
436 CRYPTO_THREAD_unlock(rand_lock);
439 /* num_ceil -= MD_DIGEST_LENGTH/2 */
440 j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
444 #ifndef GETPID_IS_MEANINGLESS
445 if (curr_pid) { /* just in the first iteration to save time */
446 if (!MD_Update(m, (unsigned char *)&curr_pid, sizeof curr_pid))
451 if (curr_time) { /* just in the first iteration to save time */
452 if (!MD_Update(m, (unsigned char *)&curr_time, sizeof curr_time))
454 if (!MD_Update(m, (unsigned char *)&tv, sizeof tv))
457 if (!rand_hw_seed(m))
460 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
462 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
465 k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
467 if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
469 if (!MD_Update(m, &(state[0]), k))
471 } else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
473 if (!MD_Final(m, local_md))
476 for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
477 /* may compete with other threads */
478 state[st_idx++] ^= local_md[i];
479 if (st_idx >= st_num)
482 *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
487 || !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
488 || !MD_Update(m, local_md, MD_DIGEST_LENGTH))
490 CRYPTO_THREAD_write_lock(rand_lock);
492 * Prevent deadlocks if we end up in an async engine
495 if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
496 CRYPTO_THREAD_unlock(rand_lock);
499 ASYNC_unblock_pause();
500 CRYPTO_THREAD_unlock(rand_lock);
508 RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
509 ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
510 "https://www.openssl.org/docs/faq.html");
514 RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
518 RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
524 static int rand_nopseudo_bytes(unsigned char *buf, int num)
526 return rand_bytes(buf, num, 0);
529 #if OPENSSL_API_COMPAT < 0x10100000L
531 * pseudo-random bytes that are guaranteed to be unique but not unpredictable
533 static int rand_pseudo_bytes(unsigned char *buf, int num)
535 return rand_bytes(buf, num, 1);
539 static int rand_status(void)
541 CRYPTO_THREAD_ID cur;
545 if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
548 cur = CRYPTO_THREAD_get_current_id();
550 * check if we already have the lock (could happen if a RAND_poll()
551 * implementation calls RAND_status())
553 if (crypto_lock_rand) {
554 CRYPTO_THREAD_read_lock(rand_tmp_lock);
555 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
556 CRYPTO_THREAD_unlock(rand_tmp_lock);
561 CRYPTO_THREAD_write_lock(rand_lock);
563 * Prevent deadlocks in case we end up in an async engine
568 * prevent rand_bytes() from trying to obtain the lock again
570 CRYPTO_THREAD_write_lock(rand_tmp_lock);
571 locking_threadid = cur;
572 CRYPTO_THREAD_unlock(rand_tmp_lock);
573 crypto_lock_rand = 1;
581 ret = entropy >= ENTROPY_NEEDED;
584 /* before unlocking, we must clear 'crypto_lock_rand' */
585 crypto_lock_rand = 0;
587 ASYNC_unblock_pause();
588 CRYPTO_THREAD_unlock(rand_lock);
595 * rand_hw_seed: get seed data from any available hardware RNG. only
596 * currently supports rdrand.
599 /* Adapted from eng_rdrand.c */
601 #if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
602 defined(__x86_64) || defined(__x86_64__) || \
603 defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
604 && !defined(OPENSSL_NO_RDRAND)
606 # define RDRAND_CALLS 4
608 size_t OPENSSL_ia32_rdrand(void);
609 extern unsigned int OPENSSL_ia32cap_P[];
611 static int rand_hw_seed(EVP_MD_CTX *ctx)
614 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
616 for (i = 0; i < RDRAND_CALLS; i++) {
618 rnd = OPENSSL_ia32_rdrand();
621 if (!MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t)))
627 /* XOR an existing buffer with random data */
629 void rand_hw_xor(unsigned char *buf, size_t num)
632 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
634 while (num >= sizeof(size_t)) {
635 rnd = OPENSSL_ia32_rdrand();
638 *((size_t *)buf) ^= rnd;
639 buf += sizeof(size_t);
640 num -= sizeof(size_t);
643 rnd = OPENSSL_ia32_rdrand();
657 static int rand_hw_seed(EVP_MD_CTX *ctx)
662 void rand_hw_xor(unsigned char *buf, size_t num)