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>
26 #include <openssl/err.h>
27 #include <internal/thread_once.h>
30 #if defined(BN_DEBUG) || defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
34 #define STATE_SIZE 1023
36 typedef struct ossl_rand_state_st OSSL_RAND_STATE;
38 struct ossl_rand_state_st {
41 unsigned char state[STATE_SIZE + SHA_DIGEST_LENGTH];
42 unsigned char md[SHA_DIGEST_LENGTH];
46 static OSSL_RAND_STATE global_state;
47 static double randomness = 0;
48 static int initialized = 0;
49 static CRYPTO_RWLOCK *rand_lock = NULL;
50 static CRYPTO_RWLOCK *rand_tmp_lock = NULL;
51 static CRYPTO_ONCE ossl_rand_init = CRYPTO_ONCE_STATIC_INIT;
52 static CRYPTO_THREAD_LOCAL key;
54 /* May be set only when a thread holds rand_lock (to prevent double locking) */
55 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
60 static CRYPTO_THREAD_ID locking_threadid;
63 int rand_predictable = 0;
66 static int rand_hw_seed(EVP_MD_CTX *ctx);
68 static void rand_thread_cleanup(void *arg)
70 OSSL_RAND_STATE *sp = arg;
72 OPENSSL_clear_free(sp, sizeof(*sp));
75 DEFINE_RUN_ONCE_STATIC(do_ossl_rand_init)
79 OPENSSL_init_crypto(0, NULL);
80 rand_lock = CRYPTO_THREAD_lock_new();
81 ret &= rand_lock != NULL;
82 rand_tmp_lock = CRYPTO_THREAD_lock_new();
83 ret &= rand_tmp_lock != NULL;
84 ret &= CRYPTO_THREAD_init_local(&key, rand_thread_cleanup) == 1;
88 RAND_METHOD *RAND_OpenSSL(void)
90 return &openssl_rand_meth;
93 static void rand_cleanup(void)
95 OPENSSL_cleanse(&global_state, sizeof(global_state));
98 CRYPTO_THREAD_lock_free(rand_lock);
99 CRYPTO_THREAD_lock_free(rand_tmp_lock);
102 static int rand_add(const void *buf, int num, double add)
106 unsigned char local_md[SHA_DIGEST_LENGTH];
110 OSSL_RAND_STATE *sp = &global_state;
116 if (rand_predictable)
121 * (Based on the rand(3) manpage)
123 * The input is chopped up into units of 20 bytes (or less for
124 * the last block). Each of these blocks is run through the hash
125 * function as follows: The data passed to the hash function
126 * is the current 'md', the same number of bytes from the 'state'
127 * (the location determined by in incremented looping index) as
128 * the current 'block', the new key data 'block', and 'count'
129 * (which is incremented after each use).
130 * The result of this is kept in 'md' and also xored into the
131 * 'state' at the same locations that were used as input into the
135 m = EVP_MD_CTX_new();
139 if (!RUN_ONCE(&ossl_rand_init, do_ossl_rand_init))
142 /* check if we already have the lock */
143 if (crypto_lock_rand) {
144 CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
145 CRYPTO_THREAD_read_lock(rand_tmp_lock);
146 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
147 CRYPTO_THREAD_unlock(rand_tmp_lock);
152 CRYPTO_THREAD_write_lock(rand_lock);
156 * use our own copies of the counters so that even if a concurrent thread
157 * seeds with exactly the same data and uses the same subarray there's
160 md_c[0] = sp->md_count[0];
161 md_c[1] = sp->md_count[1];
163 memcpy(local_md, sp->md, sizeof(sp->md));
165 /* sp->index <= sp->num <= STATE_SIZE */
167 if (sp->index >= STATE_SIZE) {
168 sp->index %= STATE_SIZE;
169 sp->num = STATE_SIZE;
170 } else if (sp->num < STATE_SIZE) {
171 if (sp->index > sp->num)
174 /* sp->index <= sp->num <= STATE_SIZE */
177 * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
178 * will use now, but other threads may use them as well
181 sp->md_count[1] += (num / SHA_DIGEST_LENGTH) + (num % SHA_DIGEST_LENGTH > 0);
184 CRYPTO_THREAD_unlock(rand_lock);
186 for (i = 0; i < num; i += SHA_DIGEST_LENGTH) {
188 j = (j > SHA_DIGEST_LENGTH) ? SHA_DIGEST_LENGTH : j;
190 if (!EVP_DigestInit_ex(m, EVP_sha1(), NULL))
192 if (!EVP_DigestUpdate(m, local_md, SHA_DIGEST_LENGTH))
194 k = (st_idx + j) - STATE_SIZE;
196 if (!EVP_DigestUpdate(m, &sp->state[st_idx], j - k))
198 if (!EVP_DigestUpdate(m, &sp->state[0], k))
200 } else if (!EVP_DigestUpdate(m, &sp->state[st_idx], j))
203 /* DO NOT REMOVE THE FOLLOWING CALL TO EVP_DigestUpdate()! */
204 if (!EVP_DigestUpdate(m, buf, j))
207 * We know that line may cause programs such as purify and valgrind
208 * to complain about use of uninitialized data. The problem is not,
209 * it's with the caller. Removing that line will make sure you get
210 * really bad randomness and thereby other problems such as very
214 if (!EVP_DigestUpdate(m, (unsigned char *)md_c, sizeof(md_c)))
216 if (!EVP_DigestFinal_ex(m, local_md, NULL))
220 buf = (const char *)buf + j;
222 for (k = 0; k < j; k++) {
224 * Parallel threads may interfere with this, but always each byte
225 * of the new state is the XOR of some previous value of its and
226 * local_md (intermediate values may be lost). Alway using locking
227 * could hurt performance more than necessary given that
228 * conflicts occur only when the total seeding is longer than the
231 sp->state[st_idx++] ^= local_md[k];
232 if (st_idx >= STATE_SIZE)
238 CRYPTO_THREAD_write_lock(rand_lock);
240 * Don't just copy back local_md into md -- this could mean that other
241 * thread's seeding remains without effect (except for the incremented
242 * counter). By XORing it we keep at least as much randomness as fits into
245 for (k = 0; k < (int)sizeof(sp->md); k++) {
246 sp->md[k] ^= local_md[k];
248 if (randomness < RANDOMNESS_NEEDED) /* stop counting when we have enough */
251 CRYPTO_THREAD_unlock(rand_lock);
259 static int rand_seed(const void *buf, int num)
261 return rand_add(buf, num, (double)num);
264 static int rand_bytes(unsigned char *buf, int num)
266 static volatile int stirred_pool = 0;
268 size_t num_ceil, st_idx, st_num;
271 unsigned char local_md[SHA_DIGEST_LENGTH];
273 OSSL_RAND_STATE *sp = &global_state;
274 #ifndef GETPID_IS_MEANINGLESS
275 pid_t curr_pid = getpid();
277 time_t curr_time = time(NULL);
278 int do_stir_pool = 0;
279 /* time value for various platforms */
280 #ifdef OPENSSL_SYS_WIN32
285 SystemTimeToFileTime(&t, &tv);
287 GetSystemTimeAsFileTime(&tv);
289 #elif defined(OPENSSL_SYS_VXWORKS)
291 clock_gettime(CLOCK_REALTIME, &ts);
292 #elif defined(OPENSSL_SYS_DSPBIOS)
293 unsigned long long tv, OPENSSL_rdtsc();
294 tv = OPENSSL_rdtsc();
297 gettimeofday(&tv, NULL);
301 if (rand_predictable) {
302 unsigned char val = 1;
304 for (i = 0; i < num; i++)
313 m = EVP_MD_CTX_new();
317 /* round upwards to multiple of SHA_DIGEST_LENGTH/2 */
319 (1 + (num - 1) / (SHA_DIGEST_LENGTH / 2)) * (SHA_DIGEST_LENGTH / 2);
322 * (Based on the rand(3) manpage:)
324 * For each group of 10 bytes (or less), we do the following:
326 * Input into the hash function the local 'md' (which is initialized from
327 * the global 'md' before any bytes are generated), the bytes that are to
328 * be overwritten by the random bytes, and bytes from the 'state'
329 * (incrementing looping index). From this digest output (which is kept
330 * in 'md'), the top (up to) 10 bytes are returned to the caller and the
331 * bottom 10 bytes are xored into the 'state'.
333 * Finally, after we have finished 'num' random bytes for the
334 * caller, 'count' (which is incremented) and the local and global 'md'
335 * are fed into the hash function and the results are kept in the
339 if (!RUN_ONCE(&ossl_rand_init, do_ossl_rand_init))
342 CRYPTO_THREAD_write_lock(rand_lock);
344 * We could end up in an async engine while holding this lock so ensure
345 * we don't pause and cause a deadlock
349 /* prevent rand_bytes() from trying to obtain the lock again */
350 CRYPTO_THREAD_write_lock(rand_tmp_lock);
351 locking_threadid = CRYPTO_THREAD_get_current_id();
352 CRYPTO_THREAD_unlock(rand_tmp_lock);
353 crypto_lock_rand = 1;
363 ok = (randomness >= RANDOMNESS_NEEDED);
366 * If the PRNG state is not yet unpredictable, then seeing the PRNG
367 * output may help attackers to determine the new state; thus we have
368 * to decrease the randomness estimate. Once we've had enough initial
369 * seeding we don't bother to adjust the randomness count, though,
370 * because we're not ambitious to provide *information-theoretic*
371 * randomness. NOTE: This approach fails if the program forks before
372 * we have enough randomness. Randomness should be collected in a
373 * separate input pool and be transferred to the output pool only
374 * when the randomness limit has been reached.
383 * In the output function only half of 'md' remains secret, so we
384 * better make sure that the required randomness gets 'evenly
385 * distributed' through 'state', our randomness pool. The input
386 * function (rand_add) chains all of 'md', which makes it more
387 * suitable for this purpose.
390 int n = STATE_SIZE; /* so that the complete pool gets accessed */
392 #if SHA_DIGEST_LENGTH > 20
393 # error "Please adjust DUMMY_SEED."
395 #define DUMMY_SEED "...................." /* at least SHA_DIGEST_LENGTH */
397 * Note that the seed does not matter, it's just that
398 * rand_add expects to have something to hash.
400 rand_add(DUMMY_SEED, SHA_DIGEST_LENGTH, 0.0);
401 n -= SHA_DIGEST_LENGTH;
409 md_c[0] = sp->md_count[0];
410 md_c[1] = sp->md_count[1];
411 memcpy(local_md, sp->md, sizeof sp->md);
413 sp->index += num_ceil;
414 if (sp->index > sp->num)
415 sp->index %= sp->num;
418 * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
419 * ours (but other threads may use them too)
422 sp->md_count[0] += 1;
424 /* before unlocking, we must clear 'crypto_lock_rand' */
425 crypto_lock_rand = 0;
426 ASYNC_unblock_pause();
427 CRYPTO_THREAD_unlock(rand_lock);
430 /* num_ceil -= SHA_DIGEST_LENGTH / 2 */
431 j = (num >= SHA_DIGEST_LENGTH / 2) ? SHA_DIGEST_LENGTH / 2 : num;
433 if (!EVP_DigestInit_ex(m, EVP_sha1(), NULL))
435 #ifndef GETPID_IS_MEANINGLESS
436 if (curr_pid) { /* just in the first iteration to save time */
437 if (!EVP_DigestUpdate(m, (unsigned char *)&curr_pid, sizeof curr_pid))
442 if (curr_time) { /* just in the first iteration to save time */
443 if (!EVP_DigestUpdate(m, (unsigned char *)&curr_time, sizeof curr_time))
445 if (!EVP_DigestUpdate(m, (unsigned char *)&tv, sizeof tv))
448 if (!rand_hw_seed(m))
451 if (!EVP_DigestUpdate(m, local_md, SHA_DIGEST_LENGTH))
453 if (!EVP_DigestUpdate(m, (unsigned char *)md_c, sizeof(md_c)))
456 k = (st_idx + SHA_DIGEST_LENGTH / 2) - st_num;
458 if (!EVP_DigestUpdate(m, &sp->state[st_idx], SHA_DIGEST_LENGTH / 2 - k))
460 if (!EVP_DigestUpdate(m, &sp->state[0], k))
462 } else if (!EVP_DigestUpdate(m, &sp->state[st_idx], SHA_DIGEST_LENGTH / 2))
464 if (!EVP_DigestFinal_ex(m, local_md, NULL))
467 for (i = 0; i < SHA_DIGEST_LENGTH / 2; i++) {
468 /* may compete with other threads */
469 sp->state[st_idx++] ^= local_md[i];
470 if (st_idx >= st_num)
473 *(buf++) = local_md[i + SHA_DIGEST_LENGTH / 2];
477 if (!EVP_DigestInit_ex(m, EVP_sha1(), NULL)
478 || !EVP_DigestUpdate(m, (unsigned char *)md_c, sizeof(md_c))
479 || !EVP_DigestUpdate(m, local_md, SHA_DIGEST_LENGTH))
481 CRYPTO_THREAD_write_lock(rand_lock);
483 * Prevent deadlocks if we end up in an async engine
486 if (!EVP_DigestUpdate(m, sp->md, sizeof(sp->md))
487 || !EVP_DigestFinal_ex(m, sp->md, NULL)) {
488 ASYNC_unblock_pause();
489 CRYPTO_THREAD_unlock(rand_lock);
492 ASYNC_unblock_pause();
493 CRYPTO_THREAD_unlock(rand_lock);
498 RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
499 ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
500 "https://www.openssl.org/docs/faq.html");
503 RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
507 RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
513 static int rand_status(void)
515 CRYPTO_THREAD_ID cur;
519 if (!RUN_ONCE(&ossl_rand_init, do_ossl_rand_init))
522 cur = CRYPTO_THREAD_get_current_id();
524 * check if we already have the lock (could happen if a RAND_poll()
525 * implementation calls RAND_status())
527 if (crypto_lock_rand) {
528 CRYPTO_THREAD_read_lock(rand_tmp_lock);
529 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
530 CRYPTO_THREAD_unlock(rand_tmp_lock);
535 CRYPTO_THREAD_write_lock(rand_lock);
537 * Prevent deadlocks in case we end up in an async engine
542 * prevent rand_bytes() from trying to obtain the lock again
544 CRYPTO_THREAD_write_lock(rand_tmp_lock);
545 locking_threadid = cur;
546 CRYPTO_THREAD_unlock(rand_tmp_lock);
547 crypto_lock_rand = 1;
555 ret = randomness >= RANDOMNESS_NEEDED;
558 /* before unlocking, we must clear 'crypto_lock_rand' */
559 crypto_lock_rand = 0;
561 ASYNC_unblock_pause();
562 CRYPTO_THREAD_unlock(rand_lock);
569 * rand_hw_seed: get seed data from any available hardware RNG. only
570 * currently supports rdrand.
572 #if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
573 defined(__x86_64) || defined(__x86_64__) || \
574 defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
575 && !defined(OPENSSL_NO_RDRAND)
577 # define RDRAND_CALLS 4
579 size_t OPENSSL_ia32_rdrand(void);
580 extern unsigned int OPENSSL_ia32cap_P[];
582 static int rand_hw_seed(EVP_MD_CTX *ctx)
585 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
587 for (i = 0; i < RDRAND_CALLS; i++) {
589 rnd = OPENSSL_ia32_rdrand();
592 if (!EVP_DigestUpdate(ctx, (unsigned char *)&rnd, sizeof(size_t)))
600 static int rand_hw_seed(EVP_MD_CTX *ctx)
608 RAND_METHOD openssl_rand_meth = {