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 rand_lock = CRYPTO_THREAD_lock_new();
93 rand_tmp_lock = CRYPTO_THREAD_lock_new();
94 return rand_lock != NULL && rand_tmp_lock != NULL;
97 RAND_METHOD *RAND_OpenSSL(void)
102 static void rand_cleanup(void)
104 OPENSSL_cleanse(state, sizeof(state));
107 OPENSSL_cleanse(md, MD_DIGEST_LENGTH);
112 CRYPTO_THREAD_lock_free(rand_lock);
113 CRYPTO_THREAD_lock_free(rand_tmp_lock);
116 static int rand_add(const void *buf, int num, double add)
120 unsigned char local_md[MD_DIGEST_LENGTH];
129 * (Based on the rand(3) manpage)
131 * The input is chopped up into units of 20 bytes (or less for
132 * the last block). Each of these blocks is run through the hash
133 * function as follows: The data passed to the hash function
134 * is the current 'md', the same number of bytes from the 'state'
135 * (the location determined by in incremented looping index) as
136 * the current 'block', the new key data 'block', and 'count'
137 * (which is incremented after each use).
138 * The result of this is kept in 'md' and also xored into the
139 * 'state' at the same locations that were used as input into the
143 m = EVP_MD_CTX_new();
147 if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
150 /* check if we already have the lock */
151 if (crypto_lock_rand) {
152 CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
153 CRYPTO_THREAD_read_lock(rand_tmp_lock);
154 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
155 CRYPTO_THREAD_unlock(rand_tmp_lock);
160 CRYPTO_THREAD_write_lock(rand_lock);
161 st_idx = state_index;
164 * use our own copies of the counters so that even if a concurrent thread
165 * seeds with exactly the same data and uses the same subarray there's
168 md_c[0] = md_count[0];
169 md_c[1] = md_count[1];
171 memcpy(local_md, md, sizeof md);
173 /* state_index <= state_num <= STATE_SIZE */
175 if (state_index >= STATE_SIZE) {
176 state_index %= STATE_SIZE;
177 state_num = STATE_SIZE;
178 } else if (state_num < STATE_SIZE) {
179 if (state_index > state_num)
180 state_num = state_index;
182 /* state_index <= state_num <= STATE_SIZE */
185 * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
186 * will use now, but other threads may use them as well
189 md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
192 CRYPTO_THREAD_unlock(rand_lock);
194 for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
196 j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
200 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
202 k = (st_idx + j) - STATE_SIZE;
204 if (!MD_Update(m, &(state[st_idx]), j - k))
206 if (!MD_Update(m, &(state[0]), k))
208 } else if (!MD_Update(m, &(state[st_idx]), j))
211 /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
212 if (!MD_Update(m, buf, j))
215 * We know that line may cause programs such as purify and valgrind
216 * to complain about use of uninitialized data. The problem is not,
217 * it's with the caller. Removing that line will make sure you get
218 * really bad randomness and thereby other problems such as very
222 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
224 if (!MD_Final(m, local_md))
228 buf = (const char *)buf + j;
230 for (k = 0; k < j; k++) {
232 * Parallel threads may interfere with this, but always each byte
233 * of the new state is the XOR of some previous value of its and
234 * local_md (intermediate values may be lost). Alway using locking
235 * could hurt performance more than necessary given that
236 * conflicts occur only when the total seeding is longer than the
239 state[st_idx++] ^= local_md[k];
240 if (st_idx >= STATE_SIZE)
246 CRYPTO_THREAD_write_lock(rand_lock);
248 * Don't just copy back local_md into md -- this could mean that other
249 * thread's seeding remains without effect (except for the incremented
250 * counter). By XORing it we keep at least as much entropy as fits into
253 for (k = 0; k < (int)sizeof(md); k++) {
254 md[k] ^= local_md[k];
256 if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
259 CRYPTO_THREAD_unlock(rand_lock);
267 static int rand_seed(const void *buf, int num)
269 return rand_add(buf, num, (double)num);
272 static int rand_bytes(unsigned char *buf, int num, int pseudo)
274 static volatile int stirred_pool = 0;
276 size_t num_ceil, st_idx, st_num;
279 unsigned char local_md[MD_DIGEST_LENGTH];
281 #ifndef GETPID_IS_MEANINGLESS
282 pid_t curr_pid = getpid();
284 time_t curr_time = time(NULL);
285 int do_stir_pool = 0;
286 /* time value for various platforms */
287 #ifdef OPENSSL_SYS_WIN32
292 SystemTimeToFileTime(&t, &tv);
294 GetSystemTimeAsFileTime(&tv);
296 #elif defined(OPENSSL_SYS_VXWORKS)
298 clock_gettime(CLOCK_REALTIME, &ts);
299 #elif defined(OPENSSL_SYS_DSPBIOS)
300 unsigned long long tv, OPENSSL_rdtsc();
301 tv = OPENSSL_rdtsc();
304 gettimeofday(&tv, NULL);
308 if (rand_predictable) {
309 static unsigned char val = 0;
311 for (i = 0; i < num; i++)
320 m = EVP_MD_CTX_new();
324 /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
326 (1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
329 * (Based on the rand(3) manpage:)
331 * For each group of 10 bytes (or less), we do the following:
333 * Input into the hash function the local 'md' (which is initialized from
334 * the global 'md' before any bytes are generated), the bytes that are to
335 * be overwritten by the random bytes, and bytes from the 'state'
336 * (incrementing looping index). From this digest output (which is kept
337 * in 'md'), the top (up to) 10 bytes are returned to the caller and the
338 * bottom 10 bytes are xored into the 'state'.
340 * Finally, after we have finished 'num' random bytes for the
341 * caller, 'count' (which is incremented) and the local and global 'md'
342 * are fed into the hash function and the results are kept in the
346 if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
349 CRYPTO_THREAD_write_lock(rand_lock);
351 * We could end up in an async engine while holding this lock so ensure
352 * we don't pause and cause a deadlock
356 /* prevent rand_bytes() from trying to obtain the lock again */
357 CRYPTO_THREAD_write_lock(rand_tmp_lock);
358 locking_threadid = CRYPTO_THREAD_get_current_id();
359 CRYPTO_THREAD_unlock(rand_tmp_lock);
360 crypto_lock_rand = 1;
370 ok = (entropy >= ENTROPY_NEEDED);
373 * If the PRNG state is not yet unpredictable, then seeing the PRNG
374 * output may help attackers to determine the new state; thus we have
375 * to decrease the entropy estimate. Once we've had enough initial
376 * seeding we don't bother to adjust the entropy count, though,
377 * because we're not ambitious to provide *information-theoretic*
378 * randomness. NOTE: This approach fails if the program forks before
379 * we have enough entropy. Entropy should be collected in a separate
380 * input pool and be transferred to the output pool only when the
381 * entropy limit has been reached.
390 * In the output function only half of 'md' remains secret, so we
391 * better make sure that the required entropy gets 'evenly
392 * distributed' through 'state', our randomness pool. The input
393 * function (rand_add) chains all of 'md', which makes it more
394 * suitable for this purpose.
397 int n = STATE_SIZE; /* so that the complete pool gets accessed */
399 #if MD_DIGEST_LENGTH > 20
400 # error "Please adjust DUMMY_SEED."
402 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
404 * Note that the seed does not matter, it's just that
405 * rand_add expects to have something to hash.
407 rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
408 n -= MD_DIGEST_LENGTH;
414 st_idx = state_index;
416 md_c[0] = md_count[0];
417 md_c[1] = md_count[1];
418 memcpy(local_md, md, sizeof md);
420 state_index += num_ceil;
421 if (state_index > state_num)
422 state_index %= state_num;
425 * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
426 * ours (but other threads may use them too)
431 /* before unlocking, we must clear 'crypto_lock_rand' */
432 crypto_lock_rand = 0;
433 ASYNC_unblock_pause();
434 CRYPTO_THREAD_unlock(rand_lock);
437 /* num_ceil -= MD_DIGEST_LENGTH/2 */
438 j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
442 #ifndef GETPID_IS_MEANINGLESS
443 if (curr_pid) { /* just in the first iteration to save time */
444 if (!MD_Update(m, (unsigned char *)&curr_pid, sizeof curr_pid))
449 if (curr_time) { /* just in the first iteration to save time */
450 if (!MD_Update(m, (unsigned char *)&curr_time, sizeof curr_time))
452 if (!MD_Update(m, (unsigned char *)&tv, sizeof tv))
455 if (!rand_hw_seed(m))
458 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
460 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
463 k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
465 if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
467 if (!MD_Update(m, &(state[0]), k))
469 } else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
471 if (!MD_Final(m, local_md))
474 for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
475 /* may compete with other threads */
476 state[st_idx++] ^= local_md[i];
477 if (st_idx >= st_num)
480 *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
485 || !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
486 || !MD_Update(m, local_md, MD_DIGEST_LENGTH))
488 CRYPTO_THREAD_write_lock(rand_lock);
490 * Prevent deadlocks if we end up in an async engine
493 if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
494 CRYPTO_THREAD_unlock(rand_lock);
497 ASYNC_unblock_pause();
498 CRYPTO_THREAD_unlock(rand_lock);
506 RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
507 ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
508 "https://www.openssl.org/docs/faq.html");
512 RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
516 RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
522 static int rand_nopseudo_bytes(unsigned char *buf, int num)
524 return rand_bytes(buf, num, 0);
527 #if OPENSSL_API_COMPAT < 0x10100000L
529 * pseudo-random bytes that are guaranteed to be unique but not unpredictable
531 static int rand_pseudo_bytes(unsigned char *buf, int num)
533 return rand_bytes(buf, num, 1);
537 static int rand_status(void)
539 CRYPTO_THREAD_ID cur;
543 if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
546 cur = CRYPTO_THREAD_get_current_id();
548 * check if we already have the lock (could happen if a RAND_poll()
549 * implementation calls RAND_status())
551 if (crypto_lock_rand) {
552 CRYPTO_THREAD_read_lock(rand_tmp_lock);
553 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
554 CRYPTO_THREAD_unlock(rand_tmp_lock);
559 CRYPTO_THREAD_write_lock(rand_lock);
561 * Prevent deadlocks in case we end up in an async engine
566 * prevent rand_bytes() from trying to obtain the lock again
568 CRYPTO_THREAD_write_lock(rand_tmp_lock);
569 locking_threadid = cur;
570 CRYPTO_THREAD_unlock(rand_tmp_lock);
571 crypto_lock_rand = 1;
579 ret = entropy >= ENTROPY_NEEDED;
582 /* before unlocking, we must clear 'crypto_lock_rand' */
583 crypto_lock_rand = 0;
585 ASYNC_unblock_pause();
586 CRYPTO_THREAD_unlock(rand_lock);
593 * rand_hw_seed: get seed data from any available hardware RNG. only
594 * currently supports rdrand.
597 /* Adapted from eng_rdrand.c */
599 #if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
600 defined(__x86_64) || defined(__x86_64__) || \
601 defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
602 && !defined(OPENSSL_NO_RDRAND)
604 # define RDRAND_CALLS 4
606 size_t OPENSSL_ia32_rdrand(void);
607 extern unsigned int OPENSSL_ia32cap_P[];
609 static int rand_hw_seed(EVP_MD_CTX *ctx)
612 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
614 for (i = 0; i < RDRAND_CALLS; i++) {
616 rnd = OPENSSL_ia32_rdrand();
619 if (!MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t)))
625 /* XOR an existing buffer with random data */
627 void rand_hw_xor(unsigned char *buf, size_t num)
630 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
632 while (num >= sizeof(size_t)) {
633 rnd = OPENSSL_ia32_rdrand();
636 *((size_t *)buf) ^= rnd;
637 buf += sizeof(size_t);
638 num -= sizeof(size_t);
641 rnd = OPENSSL_ia32_rdrand();
655 static int rand_hw_seed(EVP_MD_CTX *ctx)
660 void rand_hw_xor(unsigned char *buf, size_t num)