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>
31 # include <openssl/fips.h>
38 /* #define PREDICT 1 */
40 #define STATE_SIZE 1023
41 static size_t state_num = 0, state_index = 0;
42 static unsigned char state[STATE_SIZE + MD_DIGEST_LENGTH];
43 static unsigned char md[MD_DIGEST_LENGTH];
44 static long md_count[2] = { 0, 0 };
46 static double entropy = 0;
47 static int initialized = 0;
49 static CRYPTO_RWLOCK *rand_lock = NULL;
50 static CRYPTO_RWLOCK *rand_tmp_lock = NULL;
51 static CRYPTO_ONCE rand_lock_init = CRYPTO_ONCE_STATIC_INIT;
53 /* May be set only when a thread holds rand_lock (to prevent double locking) */
54 static unsigned int crypto_lock_rand = 0;
55 /* access to locking_threadid is synchronized by rand_tmp_lock */
56 /* valid iff crypto_lock_rand is set */
57 static CRYPTO_THREAD_ID locking_threadid;
60 int rand_predictable = 0;
63 static void rand_hw_seed(EVP_MD_CTX *ctx);
65 static void rand_cleanup(void);
66 static int rand_seed(const void *buf, int num);
67 static int rand_add(const void *buf, int num, double add_entropy);
68 static int rand_bytes(unsigned char *buf, int num, int pseudo);
69 static int rand_nopseudo_bytes(unsigned char *buf, int num);
70 #if OPENSSL_API_COMPAT < 0x10100000L
71 static int rand_pseudo_bytes(unsigned char *buf, int num);
73 static int rand_status(void);
75 static RAND_METHOD rand_meth = {
80 #if OPENSSL_API_COMPAT < 0x10100000L
88 static void do_rand_lock_init(void)
90 rand_lock = CRYPTO_THREAD_lock_new();
91 rand_tmp_lock = CRYPTO_THREAD_lock_new();
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 * (Based on the rand(3) manpage)
128 * The input is chopped up into units of 20 bytes (or less for
129 * the last block). Each of these blocks is run through the hash
130 * function as follows: The data passed to the hash function
131 * is the current 'md', the same number of bytes from the 'state'
132 * (the location determined by in incremented looping index) as
133 * the current 'block', the new key data 'block', and 'count'
134 * (which is incremented after each use).
135 * The result of this is kept in 'md' and also xored into the
136 * 'state' at the same locations that were used as input into the
140 m = EVP_MD_CTX_new();
144 CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
146 /* check if we already have the lock */
147 if (crypto_lock_rand) {
148 CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
149 CRYPTO_THREAD_read_lock(rand_tmp_lock);
150 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
151 CRYPTO_THREAD_unlock(rand_tmp_lock);
156 CRYPTO_THREAD_write_lock(rand_lock);
157 st_idx = state_index;
160 * use our own copies of the counters so that even if a concurrent thread
161 * seeds with exactly the same data and uses the same subarray there's
164 md_c[0] = md_count[0];
165 md_c[1] = md_count[1];
167 memcpy(local_md, md, sizeof md);
169 /* state_index <= state_num <= STATE_SIZE */
171 if (state_index >= STATE_SIZE) {
172 state_index %= STATE_SIZE;
173 state_num = STATE_SIZE;
174 } else if (state_num < STATE_SIZE) {
175 if (state_index > state_num)
176 state_num = state_index;
178 /* state_index <= state_num <= STATE_SIZE */
181 * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
182 * will use now, but other threads may use them as well
185 md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
188 CRYPTO_THREAD_unlock(rand_lock);
190 for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
192 j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
196 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
198 k = (st_idx + j) - STATE_SIZE;
200 if (!MD_Update(m, &(state[st_idx]), j - k))
202 if (!MD_Update(m, &(state[0]), k))
204 } else if (!MD_Update(m, &(state[st_idx]), j))
207 /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
208 if (!MD_Update(m, buf, j))
211 * We know that line may cause programs such as purify and valgrind
212 * to complain about use of uninitialized data. The problem is not,
213 * it's with the caller. Removing that line will make sure you get
214 * really bad randomness and thereby other problems such as very
218 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
220 if (!MD_Final(m, local_md))
224 buf = (const char *)buf + j;
226 for (k = 0; k < j; k++) {
228 * Parallel threads may interfere with this, but always each byte
229 * of the new state is the XOR of some previous value of its and
230 * local_md (intermediate values may be lost). Alway using locking
231 * could hurt performance more than necessary given that
232 * conflicts occur only when the total seeding is longer than the
235 state[st_idx++] ^= local_md[k];
236 if (st_idx >= STATE_SIZE)
242 CRYPTO_THREAD_write_lock(rand_lock);
244 * Don't just copy back local_md into md -- this could mean that other
245 * thread's seeding remains without effect (except for the incremented
246 * counter). By XORing it we keep at least as much entropy as fits into
249 for (k = 0; k < (int)sizeof(md); k++) {
250 md[k] ^= local_md[k];
252 if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
255 CRYPTO_THREAD_unlock(rand_lock);
263 static int rand_seed(const void *buf, int num)
265 return rand_add(buf, num, (double)num);
268 static int rand_bytes(unsigned char *buf, int num, int pseudo)
270 static volatile int stirred_pool = 0;
272 size_t num_ceil, st_idx, st_num;
275 unsigned char local_md[MD_DIGEST_LENGTH];
277 #ifndef GETPID_IS_MEANINGLESS
278 pid_t curr_pid = getpid();
280 time_t curr_time = time(NULL);
281 int do_stir_pool = 0;
282 /* time value for various platforms */
283 #ifdef OPENSSL_SYS_WIN32
288 SystemTimeToFileTime(&t, &tv);
290 GetSystemTimeAsFileTime(&tv);
292 #elif defined(OPENSSL_SYS_VXWORKS)
294 clock_gettime(CLOCK_REALTIME, &ts);
295 #elif defined(OPENSSL_SYS_DSPBIOS)
296 unsigned long long tv, OPENSSL_rdtsc();
297 tv = OPENSSL_rdtsc();
300 gettimeofday(&tv, NULL);
304 if (rand_predictable) {
305 static unsigned char val = 0;
307 for (i = 0; i < num; i++)
316 m = EVP_MD_CTX_new();
320 /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
322 (1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
325 * (Based on the rand(3) manpage:)
327 * For each group of 10 bytes (or less), we do the following:
329 * Input into the hash function the local 'md' (which is initialized from
330 * the global 'md' before any bytes are generated), the bytes that are to
331 * be overwritten by the random bytes, and bytes from the 'state'
332 * (incrementing looping index). From this digest output (which is kept
333 * in 'md'), the top (up to) 10 bytes are returned to the caller and the
334 * bottom 10 bytes are xored into the 'state'.
336 * Finally, after we have finished 'num' random bytes for the
337 * caller, 'count' (which is incremented) and the local and global 'md'
338 * are fed into the hash function and the results are kept in the
342 CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
343 CRYPTO_THREAD_write_lock(rand_lock);
345 * We could end up in an async engine while holding this lock so ensure
346 * we don't pause and cause a deadlock
350 /* prevent rand_bytes() from trying to obtain the lock again */
351 CRYPTO_THREAD_write_lock(rand_tmp_lock);
352 locking_threadid = CRYPTO_THREAD_get_current_id();
353 CRYPTO_THREAD_unlock(rand_tmp_lock);
354 crypto_lock_rand = 1;
364 ok = (entropy >= ENTROPY_NEEDED);
367 * If the PRNG state is not yet unpredictable, then seeing the PRNG
368 * output may help attackers to determine the new state; thus we have
369 * to decrease the entropy estimate. Once we've had enough initial
370 * seeding we don't bother to adjust the entropy count, though,
371 * because we're not ambitious to provide *information-theoretic*
372 * randomness. NOTE: This approach fails if the program forks before
373 * we have enough entropy. Entropy should be collected in a separate
374 * input pool and be transferred to the output pool only when the
375 * entropy limit has been reached.
384 * In the output function only half of 'md' remains secret, so we
385 * better make sure that the required entropy gets 'evenly
386 * distributed' through 'state', our randomness pool. The input
387 * function (rand_add) chains all of 'md', which makes it more
388 * suitable for this purpose.
391 int n = STATE_SIZE; /* so that the complete pool gets accessed */
393 #if MD_DIGEST_LENGTH > 20
394 # error "Please adjust DUMMY_SEED."
396 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
398 * Note that the seed does not matter, it's just that
399 * rand_add expects to have something to hash.
401 rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
402 n -= MD_DIGEST_LENGTH;
408 st_idx = state_index;
410 md_c[0] = md_count[0];
411 md_c[1] = md_count[1];
412 memcpy(local_md, md, sizeof md);
414 state_index += num_ceil;
415 if (state_index > state_num)
416 state_index %= state_num;
419 * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
420 * ours (but other threads may use them too)
425 /* before unlocking, we must clear 'crypto_lock_rand' */
426 crypto_lock_rand = 0;
427 ASYNC_unblock_pause();
428 CRYPTO_THREAD_unlock(rand_lock);
431 /* num_ceil -= MD_DIGEST_LENGTH/2 */
432 j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
436 #ifndef GETPID_IS_MEANINGLESS
437 if (curr_pid) { /* just in the first iteration to save time */
438 if (!MD_Update(m, (unsigned char *)&curr_pid, sizeof curr_pid))
443 if (curr_time) { /* just in the first iteration to save time */
444 if (!MD_Update(m, (unsigned char *)&curr_time, sizeof curr_time))
446 if (!MD_Update(m, (unsigned char *)&tv, sizeof tv))
451 if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
453 if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
456 k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
458 if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
460 if (!MD_Update(m, &(state[0]), k))
462 } else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
464 if (!MD_Final(m, local_md))
467 for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
468 /* may compete with other threads */
469 state[st_idx++] ^= local_md[i];
470 if (st_idx >= st_num)
473 *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
478 || !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
479 || !MD_Update(m, local_md, MD_DIGEST_LENGTH))
481 CRYPTO_THREAD_write_lock(rand_lock);
483 * Prevent deadlocks if we end up in an async engine
486 if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
487 CRYPTO_THREAD_unlock(rand_lock);
490 ASYNC_unblock_pause();
491 CRYPTO_THREAD_unlock(rand_lock);
499 RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
500 ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
501 "https://www.openssl.org/docs/faq.html");
505 RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
509 RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
515 static int rand_nopseudo_bytes(unsigned char *buf, int num)
517 return rand_bytes(buf, num, 0);
520 #if OPENSSL_API_COMPAT < 0x10100000L
522 * pseudo-random bytes that are guaranteed to be unique but not unpredictable
524 static int rand_pseudo_bytes(unsigned char *buf, int num)
526 return rand_bytes(buf, num, 1);
530 static int rand_status(void)
532 CRYPTO_THREAD_ID cur;
536 CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
537 cur = CRYPTO_THREAD_get_current_id();
539 * check if we already have the lock (could happen if a RAND_poll()
540 * implementation calls RAND_status())
542 if (crypto_lock_rand) {
543 CRYPTO_THREAD_read_lock(rand_tmp_lock);
544 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
545 CRYPTO_THREAD_unlock(rand_tmp_lock);
550 CRYPTO_THREAD_write_lock(rand_lock);
552 * Prevent deadlocks in case we end up in an async engine
557 * prevent rand_bytes() from trying to obtain the lock again
559 CRYPTO_THREAD_write_lock(rand_tmp_lock);
560 locking_threadid = cur;
561 CRYPTO_THREAD_unlock(rand_tmp_lock);
562 crypto_lock_rand = 1;
570 ret = entropy >= ENTROPY_NEEDED;
573 /* before unlocking, we must clear 'crypto_lock_rand' */
574 crypto_lock_rand = 0;
576 ASYNC_unblock_pause();
577 CRYPTO_THREAD_unlock(rand_lock);
584 * rand_hw_seed: get seed data from any available hardware RNG. only
585 * currently supports rdrand.
588 /* Adapted from eng_rdrand.c */
590 #if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
591 defined(__x86_64) || defined(__x86_64__) || \
592 defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
593 && !defined(OPENSSL_NO_RDRAND)
595 # define RDRAND_CALLS 4
597 size_t OPENSSL_ia32_rdrand(void);
598 extern unsigned int OPENSSL_ia32cap_P[];
600 static void rand_hw_seed(EVP_MD_CTX *ctx)
603 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
605 for (i = 0; i < RDRAND_CALLS; i++) {
607 rnd = OPENSSL_ia32_rdrand();
610 MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t));
614 /* XOR an existing buffer with random data */
616 void rand_hw_xor(unsigned char *buf, size_t num)
619 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
621 while (num >= sizeof(size_t)) {
622 rnd = OPENSSL_ia32_rdrand();
625 *((size_t *)buf) ^= rnd;
626 buf += sizeof(size_t);
627 num -= sizeof(size_t);
630 rnd = OPENSSL_ia32_rdrand();
644 static void rand_hw_seed(EVP_MD_CTX *ctx)
649 void rand_hw_xor(unsigned char *buf, size_t num)