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 #define STATE_SIZE 1023
32 typedef struct ossl_rand_state_st OSSL_RAND_STATE;
34 struct ossl_rand_state_st {
37 unsigned char state[STATE_SIZE + SHA_DIGEST_LENGTH];
38 unsigned char md[SHA_DIGEST_LENGTH];
42 static OSSL_RAND_STATE global_state;
43 static double randomness = 0;
44 static int initialized = 0;
45 static CRYPTO_RWLOCK *rand_lock = NULL;
46 static CRYPTO_RWLOCK *rand_tmp_lock = NULL;
47 static CRYPTO_ONCE ossl_rand_init = CRYPTO_ONCE_STATIC_INIT;
48 static CRYPTO_THREAD_LOCAL key;
50 /* May be set only when a thread holds rand_lock (to prevent double locking) */
51 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
56 static CRYPTO_THREAD_ID locking_threadid;
58 static int rand_hw_seed(EVP_MD_CTX *ctx);
60 static void rand_thread_cleanup(void *arg)
62 OSSL_RAND_STATE *sp = arg;
64 OPENSSL_clear_free(sp, sizeof(*sp));
67 DEFINE_RUN_ONCE_STATIC(do_ossl_rand_init)
71 OPENSSL_init_crypto(0, NULL);
72 rand_lock = CRYPTO_THREAD_lock_new();
73 ret &= rand_lock != NULL;
74 rand_tmp_lock = CRYPTO_THREAD_lock_new();
75 ret &= rand_tmp_lock != NULL;
76 ret &= CRYPTO_THREAD_init_local(&key, rand_thread_cleanup) == 1;
80 RAND_METHOD *RAND_OpenSSL(void)
82 return &openssl_rand_meth;
85 static void rand_cleanup(void)
87 OPENSSL_cleanse(&global_state, sizeof(global_state));
90 CRYPTO_THREAD_lock_free(rand_lock);
91 CRYPTO_THREAD_lock_free(rand_tmp_lock);
94 static int rand_add(const void *buf, int num, double add)
98 unsigned char local_md[SHA_DIGEST_LENGTH];
102 OSSL_RAND_STATE *sp = &global_state;
108 * (Based on the rand(3) manpage)
110 * The input is chopped up into units of 20 bytes (or less for
111 * the last block). Each of these blocks is run through the hash
112 * function as follows: The data passed to the hash function
113 * is the current 'md', the same number of bytes from the 'state'
114 * (the location determined by in incremented looping index) as
115 * the current 'block', the new key data 'block', and 'count'
116 * (which is incremented after each use).
117 * The result of this is kept in 'md' and also xored into the
118 * 'state' at the same locations that were used as input into the
122 m = EVP_MD_CTX_new();
126 if (!RUN_ONCE(&ossl_rand_init, do_ossl_rand_init))
129 /* check if we already have the lock */
130 if (crypto_lock_rand) {
131 CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
132 CRYPTO_THREAD_read_lock(rand_tmp_lock);
133 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
134 CRYPTO_THREAD_unlock(rand_tmp_lock);
139 CRYPTO_THREAD_write_lock(rand_lock);
143 * use our own copies of the counters so that even if a concurrent thread
144 * seeds with exactly the same data and uses the same subarray there's
147 md_c[0] = sp->md_count[0];
148 md_c[1] = sp->md_count[1];
150 memcpy(local_md, sp->md, sizeof(sp->md));
152 /* sp->index <= sp->num <= STATE_SIZE */
154 if (sp->index >= STATE_SIZE) {
155 sp->index %= STATE_SIZE;
156 sp->num = STATE_SIZE;
157 } else if (sp->num < STATE_SIZE) {
158 if (sp->index > sp->num)
161 /* sp->index <= sp->num <= STATE_SIZE */
164 * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
165 * will use now, but other threads may use them as well
168 sp->md_count[1] += (num / SHA_DIGEST_LENGTH) + (num % SHA_DIGEST_LENGTH > 0);
171 CRYPTO_THREAD_unlock(rand_lock);
173 for (i = 0; i < num; i += SHA_DIGEST_LENGTH) {
175 j = (j > SHA_DIGEST_LENGTH) ? SHA_DIGEST_LENGTH : j;
177 if (!EVP_DigestInit_ex(m, EVP_sha1(), NULL))
179 if (!EVP_DigestUpdate(m, local_md, SHA_DIGEST_LENGTH))
181 k = (st_idx + j) - STATE_SIZE;
183 if (!EVP_DigestUpdate(m, &sp->state[st_idx], j - k))
185 if (!EVP_DigestUpdate(m, &sp->state[0], k))
187 } else if (!EVP_DigestUpdate(m, &sp->state[st_idx], j))
190 /* DO NOT REMOVE THE FOLLOWING CALL TO EVP_DigestUpdate()! */
191 if (!EVP_DigestUpdate(m, buf, j))
194 * We know that line may cause programs such as purify and valgrind
195 * to complain about use of uninitialized data. The problem is not,
196 * it's with the caller. Removing that line will make sure you get
197 * really bad randomness and thereby other problems such as very
201 if (!EVP_DigestUpdate(m, (unsigned char *)md_c, sizeof(md_c)))
203 if (!EVP_DigestFinal_ex(m, local_md, NULL))
207 buf = (const char *)buf + j;
209 for (k = 0; k < j; k++) {
211 * Parallel threads may interfere with this, but always each byte
212 * of the new state is the XOR of some previous value of its and
213 * local_md (intermediate values may be lost). Alway using locking
214 * could hurt performance more than necessary given that
215 * conflicts occur only when the total seeding is longer than the
218 sp->state[st_idx++] ^= local_md[k];
219 if (st_idx >= STATE_SIZE)
225 CRYPTO_THREAD_write_lock(rand_lock);
227 * Don't just copy back local_md into md -- this could mean that other
228 * thread's seeding remains without effect (except for the incremented
229 * counter). By XORing it we keep at least as much randomness as fits into
232 for (k = 0; k < (int)sizeof(sp->md); k++) {
233 sp->md[k] ^= local_md[k];
235 if (randomness < RANDOMNESS_NEEDED) /* stop counting when we have enough */
238 CRYPTO_THREAD_unlock(rand_lock);
246 static int rand_seed(const void *buf, int num)
248 return rand_add(buf, num, (double)num);
251 static int rand_bytes(unsigned char *buf, int num)
253 static volatile int stirred_pool = 0;
255 size_t num_ceil, st_idx, st_num;
258 unsigned char local_md[SHA_DIGEST_LENGTH];
260 OSSL_RAND_STATE *sp = &global_state;
261 #ifndef GETPID_IS_MEANINGLESS
262 pid_t curr_pid = getpid();
264 time_t curr_time = time(NULL);
265 int do_stir_pool = 0;
266 /* time value for various platforms */
267 #ifdef OPENSSL_SYS_WIN32
272 SystemTimeToFileTime(&t, &tv);
274 GetSystemTimeAsFileTime(&tv);
276 #elif defined(OPENSSL_SYS_VXWORKS)
278 clock_gettime(CLOCK_REALTIME, &ts);
279 #elif defined(OPENSSL_SYS_DSPBIOS)
280 unsigned long long tv, OPENSSL_rdtsc();
281 tv = OPENSSL_rdtsc();
284 gettimeofday(&tv, NULL);
290 m = EVP_MD_CTX_new();
294 /* round upwards to multiple of SHA_DIGEST_LENGTH/2 */
296 (1 + (num - 1) / (SHA_DIGEST_LENGTH / 2)) * (SHA_DIGEST_LENGTH / 2);
299 * (Based on the rand(3) manpage:)
301 * For each group of 10 bytes (or less), we do the following:
303 * Input into the hash function the local 'md' (which is initialized from
304 * the global 'md' before any bytes are generated), the bytes that are to
305 * be overwritten by the random bytes, and bytes from the 'state'
306 * (incrementing looping index). From this digest output (which is kept
307 * in 'md'), the top (up to) 10 bytes are returned to the caller and the
308 * bottom 10 bytes are xored into the 'state'.
310 * Finally, after we have finished 'num' random bytes for the
311 * caller, 'count' (which is incremented) and the local and global 'md'
312 * are fed into the hash function and the results are kept in the
316 if (!RUN_ONCE(&ossl_rand_init, do_ossl_rand_init))
319 CRYPTO_THREAD_write_lock(rand_lock);
321 * We could end up in an async engine while holding this lock so ensure
322 * we don't pause and cause a deadlock
326 /* prevent rand_bytes() from trying to obtain the lock again */
327 CRYPTO_THREAD_write_lock(rand_tmp_lock);
328 locking_threadid = CRYPTO_THREAD_get_current_id();
329 CRYPTO_THREAD_unlock(rand_tmp_lock);
330 crypto_lock_rand = 1;
340 ok = (randomness >= RANDOMNESS_NEEDED);
343 * If the PRNG state is not yet unpredictable, then seeing the PRNG
344 * output may help attackers to determine the new state; thus we have
345 * to decrease the randomness estimate. Once we've had enough initial
346 * seeding we don't bother to adjust the randomness count, though,
347 * because we're not ambitious to provide *information-theoretic*
348 * randomness. NOTE: This approach fails if the program forks before
349 * we have enough randomness. Randomness should be collected in a
350 * separate input pool and be transferred to the output pool only
351 * when the randomness limit has been reached.
360 * In the output function only half of 'md' remains secret, so we
361 * better make sure that the required randomness gets 'evenly
362 * distributed' through 'state', our randomness pool. The input
363 * function (rand_add) chains all of 'md', which makes it more
364 * suitable for this purpose.
367 int n = STATE_SIZE; /* so that the complete pool gets accessed */
369 #if SHA_DIGEST_LENGTH > 20
370 # error "Please adjust DUMMY_SEED."
372 #define DUMMY_SEED "...................." /* at least SHA_DIGEST_LENGTH */
374 * Note that the seed does not matter, it's just that
375 * rand_add expects to have something to hash.
377 rand_add(DUMMY_SEED, SHA_DIGEST_LENGTH, 0.0);
378 n -= SHA_DIGEST_LENGTH;
386 md_c[0] = sp->md_count[0];
387 md_c[1] = sp->md_count[1];
388 memcpy(local_md, sp->md, sizeof sp->md);
390 sp->index += num_ceil;
391 if (sp->index > sp->num)
392 sp->index %= sp->num;
395 * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
396 * ours (but other threads may use them too)
399 sp->md_count[0] += 1;
401 /* before unlocking, we must clear 'crypto_lock_rand' */
402 crypto_lock_rand = 0;
403 ASYNC_unblock_pause();
404 CRYPTO_THREAD_unlock(rand_lock);
407 /* num_ceil -= SHA_DIGEST_LENGTH / 2 */
408 j = (num >= SHA_DIGEST_LENGTH / 2) ? SHA_DIGEST_LENGTH / 2 : num;
410 if (!EVP_DigestInit_ex(m, EVP_sha1(), NULL))
412 #ifndef GETPID_IS_MEANINGLESS
413 if (curr_pid) { /* just in the first iteration to save time */
414 if (!EVP_DigestUpdate(m, (unsigned char *)&curr_pid, sizeof curr_pid))
419 if (curr_time) { /* just in the first iteration to save time */
420 if (!EVP_DigestUpdate(m, (unsigned char *)&curr_time, sizeof curr_time))
422 if (!EVP_DigestUpdate(m, (unsigned char *)&tv, sizeof tv))
425 if (!rand_hw_seed(m))
428 if (!EVP_DigestUpdate(m, local_md, SHA_DIGEST_LENGTH))
430 if (!EVP_DigestUpdate(m, (unsigned char *)md_c, sizeof(md_c)))
433 k = (st_idx + SHA_DIGEST_LENGTH / 2) - st_num;
435 if (!EVP_DigestUpdate(m, &sp->state[st_idx], SHA_DIGEST_LENGTH / 2 - k))
437 if (!EVP_DigestUpdate(m, &sp->state[0], k))
439 } else if (!EVP_DigestUpdate(m, &sp->state[st_idx], SHA_DIGEST_LENGTH / 2))
441 if (!EVP_DigestFinal_ex(m, local_md, NULL))
444 for (i = 0; i < SHA_DIGEST_LENGTH / 2; i++) {
445 /* may compete with other threads */
446 sp->state[st_idx++] ^= local_md[i];
447 if (st_idx >= st_num)
450 *(buf++) = local_md[i + SHA_DIGEST_LENGTH / 2];
454 if (!EVP_DigestInit_ex(m, EVP_sha1(), NULL)
455 || !EVP_DigestUpdate(m, (unsigned char *)md_c, sizeof(md_c))
456 || !EVP_DigestUpdate(m, local_md, SHA_DIGEST_LENGTH))
458 CRYPTO_THREAD_write_lock(rand_lock);
460 * Prevent deadlocks if we end up in an async engine
463 if (!EVP_DigestUpdate(m, sp->md, sizeof(sp->md))
464 || !EVP_DigestFinal_ex(m, sp->md, NULL)) {
465 ASYNC_unblock_pause();
466 CRYPTO_THREAD_unlock(rand_lock);
469 ASYNC_unblock_pause();
470 CRYPTO_THREAD_unlock(rand_lock);
475 RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
476 ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
477 "https://www.openssl.org/docs/faq.html");
480 RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
484 RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
490 static int rand_status(void)
492 CRYPTO_THREAD_ID cur;
496 if (!RUN_ONCE(&ossl_rand_init, do_ossl_rand_init))
499 cur = CRYPTO_THREAD_get_current_id();
501 * check if we already have the lock (could happen if a RAND_poll()
502 * implementation calls RAND_status())
504 if (crypto_lock_rand) {
505 CRYPTO_THREAD_read_lock(rand_tmp_lock);
506 do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
507 CRYPTO_THREAD_unlock(rand_tmp_lock);
512 CRYPTO_THREAD_write_lock(rand_lock);
514 * Prevent deadlocks in case we end up in an async engine
519 * prevent rand_bytes() from trying to obtain the lock again
521 CRYPTO_THREAD_write_lock(rand_tmp_lock);
522 locking_threadid = cur;
523 CRYPTO_THREAD_unlock(rand_tmp_lock);
524 crypto_lock_rand = 1;
532 ret = randomness >= RANDOMNESS_NEEDED;
535 /* before unlocking, we must clear 'crypto_lock_rand' */
536 crypto_lock_rand = 0;
538 ASYNC_unblock_pause();
539 CRYPTO_THREAD_unlock(rand_lock);
546 * rand_hw_seed: get seed data from any available hardware RNG. only
547 * currently supports rdrand.
549 #if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
550 defined(__x86_64) || defined(__x86_64__) || \
551 defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
552 && !defined(OPENSSL_NO_RDRAND)
554 # define RDRAND_CALLS 4
556 size_t OPENSSL_ia32_rdrand(void);
557 extern unsigned int OPENSSL_ia32cap_P[];
559 static int rand_hw_seed(EVP_MD_CTX *ctx)
562 if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
564 for (i = 0; i < RDRAND_CALLS; i++) {
566 rnd = OPENSSL_ia32_rdrand();
569 if (!EVP_DigestUpdate(ctx, (unsigned char *)&rnd, sizeof(size_t)))
577 static int rand_hw_seed(EVP_MD_CTX *ctx)
585 RAND_METHOD openssl_rand_meth = {