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>
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 * (Based on the rand(3) manpage)
132 * The input is chopped up into units of 20 bytes (or less for
133 * the last block). Each of these blocks is run through the hash
134 * function as follows: The data passed to the hash function
135 * is the current 'md', the same number of bytes from the 'state'
136 * (the location determined by in incremented looping index) as
137 * the current 'block', the new key data 'block', and 'count'
138 * (which is incremented after each use).
139 * The result of this is kept in 'md' and also xored into the
140 * 'state' at the same locations that were used as input into the
144 m = EVP_MD_CTX_new();
148 if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
151 /* check if we already have the lock */
152 if (crypto_lock_rand) {
153 CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
154 CRYPTO_THREAD_read_lock(rand_tmp_lock);
155 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
156 CRYPTO_THREAD_unlock(rand_tmp_lock);
161 CRYPTO_THREAD_write_lock(rand_lock);
162 st_idx = state_index;
165 * use our own copies of the counters so that even if a concurrent thread
166 * seeds with exactly the same data and uses the same subarray there's
169 md_c[0] = md_count[0];
170 md_c[1] = md_count[1];
172 memcpy(local_md, md, sizeof md);
174 /* state_index <= state_num <= STATE_SIZE */
176 if (state_index >= STATE_SIZE) {
177 state_index %= STATE_SIZE;
178 state_num = STATE_SIZE;
179 } else if (state_num < STATE_SIZE) {
180 if (state_index > state_num)
181 state_num = state_index;
183 /* state_index <= state_num <= STATE_SIZE */
186 * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
187 * will use now, but other threads may use them as well
190 md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
193 CRYPTO_THREAD_unlock(rand_lock);
195 for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
197 j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
201 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
203 k = (st_idx + j) - STATE_SIZE;
205 if (!MD_Update(m, &(state[st_idx]), j - k))
207 if (!MD_Update(m, &(state[0]), k))
209 } else if (!MD_Update(m, &(state[st_idx]), j))
212 /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
213 if (!MD_Update(m, buf, j))
216 * We know that line may cause programs such as purify and valgrind
217 * to complain about use of uninitialized data. The problem is not,
218 * it's with the caller. Removing that line will make sure you get
219 * really bad randomness and thereby other problems such as very
223 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
225 if (!MD_Final(m, local_md))
229 buf = (const char *)buf + j;
231 for (k = 0; k < j; k++) {
233 * Parallel threads may interfere with this, but always each byte
234 * of the new state is the XOR of some previous value of its and
235 * local_md (intermediate values may be lost). Alway using locking
236 * could hurt performance more than necessary given that
237 * conflicts occur only when the total seeding is longer than the
240 state[st_idx++] ^= local_md[k];
241 if (st_idx >= STATE_SIZE)
247 CRYPTO_THREAD_write_lock(rand_lock);
249 * Don't just copy back local_md into md -- this could mean that other
250 * thread's seeding remains without effect (except for the incremented
251 * counter). By XORing it we keep at least as much entropy as fits into
254 for (k = 0; k < (int)sizeof(md); k++) {
255 md[k] ^= local_md[k];
257 if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
260 CRYPTO_THREAD_unlock(rand_lock);
268 static int rand_seed(const void *buf, int num)
270 return rand_add(buf, num, (double)num);
273 static int rand_bytes(unsigned char *buf, int num, int pseudo)
275 static volatile int stirred_pool = 0;
277 size_t num_ceil, st_idx, st_num;
280 unsigned char local_md[MD_DIGEST_LENGTH];
282 #ifndef GETPID_IS_MEANINGLESS
283 pid_t curr_pid = getpid();
285 time_t curr_time = time(NULL);
286 int do_stir_pool = 0;
287 /* time value for various platforms */
288 #ifdef OPENSSL_SYS_WIN32
293 SystemTimeToFileTime(&t, &tv);
295 GetSystemTimeAsFileTime(&tv);
297 #elif defined(OPENSSL_SYS_VXWORKS)
299 clock_gettime(CLOCK_REALTIME, &ts);
300 #elif defined(OPENSSL_SYS_DSPBIOS)
301 unsigned long long tv, OPENSSL_rdtsc();
302 tv = OPENSSL_rdtsc();
305 gettimeofday(&tv, NULL);
309 if (rand_predictable) {
310 static unsigned char val = 0;
312 for (i = 0; i < num; i++)
321 m = EVP_MD_CTX_new();
325 /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
327 (1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
330 * (Based on the rand(3) manpage:)
332 * For each group of 10 bytes (or less), we do the following:
334 * Input into the hash function the local 'md' (which is initialized from
335 * the global 'md' before any bytes are generated), the bytes that are to
336 * be overwritten by the random bytes, and bytes from the 'state'
337 * (incrementing looping index). From this digest output (which is kept
338 * in 'md'), the top (up to) 10 bytes are returned to the caller and the
339 * bottom 10 bytes are xored into the 'state'.
341 * Finally, after we have finished 'num' random bytes for the
342 * caller, 'count' (which is incremented) and the local and global 'md'
343 * are fed into the hash function and the results are kept in the
347 if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
350 CRYPTO_THREAD_write_lock(rand_lock);
352 * We could end up in an async engine while holding this lock so ensure
353 * we don't pause and cause a deadlock
357 /* prevent rand_bytes() from trying to obtain the lock again */
358 CRYPTO_THREAD_write_lock(rand_tmp_lock);
359 locking_threadid = CRYPTO_THREAD_get_current_id();
360 CRYPTO_THREAD_unlock(rand_tmp_lock);
361 crypto_lock_rand = 1;
371 ok = (entropy >= ENTROPY_NEEDED);
374 * If the PRNG state is not yet unpredictable, then seeing the PRNG
375 * output may help attackers to determine the new state; thus we have
376 * to decrease the entropy estimate. Once we've had enough initial
377 * seeding we don't bother to adjust the entropy count, though,
378 * because we're not ambitious to provide *information-theoretic*
379 * randomness. NOTE: This approach fails if the program forks before
380 * we have enough entropy. Entropy should be collected in a separate
381 * input pool and be transferred to the output pool only when the
382 * entropy limit has been reached.
391 * In the output function only half of 'md' remains secret, so we
392 * better make sure that the required entropy gets 'evenly
393 * distributed' through 'state', our randomness pool. The input
394 * function (rand_add) chains all of 'md', which makes it more
395 * suitable for this purpose.
398 int n = STATE_SIZE; /* so that the complete pool gets accessed */
400 #if MD_DIGEST_LENGTH > 20
401 # error "Please adjust DUMMY_SEED."
403 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
405 * Note that the seed does not matter, it's just that
406 * rand_add expects to have something to hash.
408 rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
409 n -= MD_DIGEST_LENGTH;
415 st_idx = state_index;
417 md_c[0] = md_count[0];
418 md_c[1] = md_count[1];
419 memcpy(local_md, md, sizeof md);
421 state_index += num_ceil;
422 if (state_index > state_num)
423 state_index %= state_num;
426 * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
427 * ours (but other threads may use them too)
432 /* before unlocking, we must clear 'crypto_lock_rand' */
433 crypto_lock_rand = 0;
434 ASYNC_unblock_pause();
435 CRYPTO_THREAD_unlock(rand_lock);
438 /* num_ceil -= MD_DIGEST_LENGTH/2 */
439 j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
443 #ifndef GETPID_IS_MEANINGLESS
444 if (curr_pid) { /* just in the first iteration to save time */
445 if (!MD_Update(m, (unsigned char *)&curr_pid, sizeof curr_pid))
450 if (curr_time) { /* just in the first iteration to save time */
451 if (!MD_Update(m, (unsigned char *)&curr_time, sizeof curr_time))
453 if (!MD_Update(m, (unsigned char *)&tv, sizeof tv))
456 if (!rand_hw_seed(m))
459 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
461 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
464 k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
466 if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
468 if (!MD_Update(m, &(state[0]), k))
470 } else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
472 if (!MD_Final(m, local_md))
475 for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
476 /* may compete with other threads */
477 state[st_idx++] ^= local_md[i];
478 if (st_idx >= st_num)
481 *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
486 || !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
487 || !MD_Update(m, local_md, MD_DIGEST_LENGTH))
489 CRYPTO_THREAD_write_lock(rand_lock);
491 * Prevent deadlocks if we end up in an async engine
494 if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
495 CRYPTO_THREAD_unlock(rand_lock);
498 ASYNC_unblock_pause();
499 CRYPTO_THREAD_unlock(rand_lock);
507 RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
508 ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
509 "https://www.openssl.org/docs/faq.html");
513 RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
517 RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
523 static int rand_nopseudo_bytes(unsigned char *buf, int num)
525 return rand_bytes(buf, num, 0);
528 #if OPENSSL_API_COMPAT < 0x10100000L
530 * pseudo-random bytes that are guaranteed to be unique but not unpredictable
532 static int rand_pseudo_bytes(unsigned char *buf, int num)
534 return rand_bytes(buf, num, 1);
538 static int rand_status(void)
540 CRYPTO_THREAD_ID cur;
544 if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
547 cur = CRYPTO_THREAD_get_current_id();
549 * check if we already have the lock (could happen if a RAND_poll()
550 * implementation calls RAND_status())
552 if (crypto_lock_rand) {
553 CRYPTO_THREAD_read_lock(rand_tmp_lock);
554 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
555 CRYPTO_THREAD_unlock(rand_tmp_lock);
560 CRYPTO_THREAD_write_lock(rand_lock);
562 * Prevent deadlocks in case we end up in an async engine
567 * prevent rand_bytes() from trying to obtain the lock again
569 CRYPTO_THREAD_write_lock(rand_tmp_lock);
570 locking_threadid = cur;
571 CRYPTO_THREAD_unlock(rand_tmp_lock);
572 crypto_lock_rand = 1;
580 ret = entropy >= ENTROPY_NEEDED;
583 /* before unlocking, we must clear 'crypto_lock_rand' */
584 crypto_lock_rand = 0;
586 ASYNC_unblock_pause();
587 CRYPTO_THREAD_unlock(rand_lock);
594 * rand_hw_seed: get seed data from any available hardware RNG. only
595 * currently supports rdrand.
598 /* Adapted from eng_rdrand.c */
600 #if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
601 defined(__x86_64) || defined(__x86_64__) || \
602 defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
603 && !defined(OPENSSL_NO_RDRAND)
605 # define RDRAND_CALLS 4
607 size_t OPENSSL_ia32_rdrand(void);
608 extern unsigned int OPENSSL_ia32cap_P[];
610 static int rand_hw_seed(EVP_MD_CTX *ctx)
613 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
615 for (i = 0; i < RDRAND_CALLS; i++) {
617 rnd = OPENSSL_ia32_rdrand();
620 if (!MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t)))
626 /* XOR an existing buffer with random data */
628 void rand_hw_xor(unsigned char *buf, size_t num)
631 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
633 while (num >= sizeof(size_t)) {
634 rnd = OPENSSL_ia32_rdrand();
637 *((size_t *)buf) ^= rnd;
638 buf += sizeof(size_t);
639 num -= sizeof(size_t);
642 rnd = OPENSSL_ia32_rdrand();
656 static int rand_hw_seed(EVP_MD_CTX *ctx)
661 void rand_hw_xor(unsigned char *buf, size_t num)