0d25aeb532b6e7a31b6ff60da78e5b77c8b13b31
[openssl.git] / crypto / rand / md_rand.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
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
8  */
9
10 #include <stdio.h>
11 #include <string.h>
12
13 #include "e_os.h"
14
15 #if !(defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_DSPBIOS))
16 # include <sys/time.h>
17 #endif
18 #if defined(OPENSSL_SYS_VXWORKS)
19 # include <time.h>
20 #endif
21
22 #include <openssl/opensslconf.h>
23 #include <openssl/crypto.h>
24 #include <openssl/rand.h>
25 #include <openssl/async.h>
26 #include "rand_lcl.h"
27
28 #include <openssl/err.h>
29
30 #ifdef OPENSSL_FIPS
31 # include <openssl/fips.h>
32 #endif
33
34 #ifdef BN_DEBUG
35 # define PREDICT
36 #endif
37
38 /* #define PREDICT      1 */
39
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 };
45
46 static double entropy = 0;
47 static int initialized = 0;
48
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;
52
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;
58
59 #ifdef PREDICT
60 int rand_predictable = 0;
61 #endif
62
63 static int rand_hw_seed(EVP_MD_CTX *ctx);
64
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);
72 #endif
73 static int rand_status(void);
74
75 static RAND_METHOD rand_meth = {
76     rand_seed,
77     rand_nopseudo_bytes,
78     rand_cleanup,
79     rand_add,
80 #if OPENSSL_API_COMPAT < 0x10100000L
81     rand_pseudo_bytes,
82 #else
83     NULL,
84 #endif
85     rand_status
86 };
87
88 static void do_rand_lock_init(void)
89 {
90     rand_lock = CRYPTO_THREAD_lock_new();
91     rand_tmp_lock = CRYPTO_THREAD_lock_new();
92 }
93
94 RAND_METHOD *RAND_OpenSSL(void)
95 {
96     return (&rand_meth);
97 }
98
99 static void rand_cleanup(void)
100 {
101     OPENSSL_cleanse(state, sizeof(state));
102     state_num = 0;
103     state_index = 0;
104     OPENSSL_cleanse(md, MD_DIGEST_LENGTH);
105     md_count[0] = 0;
106     md_count[1] = 0;
107     entropy = 0;
108     initialized = 0;
109     CRYPTO_THREAD_lock_free(rand_lock);
110     CRYPTO_THREAD_lock_free(rand_tmp_lock);
111 }
112
113 static int rand_add(const void *buf, int num, double add)
114 {
115     int i, j, k, st_idx;
116     long md_c[2];
117     unsigned char local_md[MD_DIGEST_LENGTH];
118     EVP_MD_CTX *m;
119     int do_not_lock;
120     int rv = 0;
121
122     if (!num)
123         return 1;
124
125     /*
126      * (Based on the rand(3) manpage)
127      *
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
137      * hash function.
138      */
139
140     m = EVP_MD_CTX_new();
141     if (m == NULL)
142         goto err;
143
144     CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
145
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);
152     } else
153         do_not_lock = 0;
154
155     if (!do_not_lock)
156         CRYPTO_THREAD_write_lock(rand_lock);
157     st_idx = state_index;
158
159     /*
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
162      * _some_ difference
163      */
164     md_c[0] = md_count[0];
165     md_c[1] = md_count[1];
166
167     memcpy(local_md, md, sizeof md);
168
169     /* state_index <= state_num <= STATE_SIZE */
170     state_index += num;
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;
177     }
178     /* state_index <= state_num <= STATE_SIZE */
179
180     /*
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
183      */
184
185     md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
186
187     if (!do_not_lock)
188         CRYPTO_THREAD_unlock(rand_lock);
189
190     for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
191         j = (num - i);
192         j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
193
194         if (!MD_Init(m))
195             goto err;
196         if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
197             goto err;
198         k = (st_idx + j) - STATE_SIZE;
199         if (k > 0) {
200             if (!MD_Update(m, &(state[st_idx]), j - k))
201                 goto err;
202             if (!MD_Update(m, &(state[0]), k))
203                 goto err;
204         } else if (!MD_Update(m, &(state[st_idx]), j))
205             goto err;
206
207         /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
208         if (!MD_Update(m, buf, j))
209             goto err;
210         /*
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
215          * insecure keys.
216          */
217
218         if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
219             goto err;
220         if (!MD_Final(m, local_md))
221             goto err;
222         md_c[1]++;
223
224         buf = (const char *)buf + j;
225
226         for (k = 0; k < j; k++) {
227             /*
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
233              * random state.
234              */
235             state[st_idx++] ^= local_md[k];
236             if (st_idx >= STATE_SIZE)
237                 st_idx = 0;
238         }
239     }
240
241     if (!do_not_lock)
242         CRYPTO_THREAD_write_lock(rand_lock);
243     /*
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
247      * md.
248      */
249     for (k = 0; k < (int)sizeof(md); k++) {
250         md[k] ^= local_md[k];
251     }
252     if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
253         entropy += add;
254     if (!do_not_lock)
255         CRYPTO_THREAD_unlock(rand_lock);
256
257     rv = 1;
258  err:
259     EVP_MD_CTX_free(m);
260     return rv;
261 }
262
263 static int rand_seed(const void *buf, int num)
264 {
265     return rand_add(buf, num, (double)num);
266 }
267
268 static int rand_bytes(unsigned char *buf, int num, int pseudo)
269 {
270     static volatile int stirred_pool = 0;
271     int i, j, k;
272     size_t num_ceil, st_idx, st_num;
273     int ok;
274     long md_c[2];
275     unsigned char local_md[MD_DIGEST_LENGTH];
276     EVP_MD_CTX *m;
277 #ifndef GETPID_IS_MEANINGLESS
278     pid_t curr_pid = getpid();
279 #endif
280     time_t curr_time = time(NULL);
281     int do_stir_pool = 0;
282 /* time value for various platforms */
283 #ifdef OPENSSL_SYS_WIN32
284     FILETIME tv;
285 # ifdef _WIN32_WCE
286     SYSTEMTIME t;
287     GetSystemTime(&t);
288     SystemTimeToFileTime(&t, &tv);
289 # else
290     GetSystemTimeAsFileTime(&tv);
291 # endif
292 #elif defined(OPENSSL_SYS_VXWORKS)
293     struct timespec tv;
294     clock_gettime(CLOCK_REALTIME, &ts);
295 #elif defined(OPENSSL_SYS_DSPBIOS)
296     unsigned long long tv, OPENSSL_rdtsc();
297     tv = OPENSSL_rdtsc();
298 #else
299     struct timeval tv;
300     gettimeofday(&tv, NULL);
301 #endif
302
303 #ifdef PREDICT
304     if (rand_predictable) {
305         static unsigned char val = 0;
306
307         for (i = 0; i < num; i++)
308             buf[i] = val++;
309         return (1);
310     }
311 #endif
312
313     if (num <= 0)
314         return 1;
315
316     m = EVP_MD_CTX_new();
317     if (m == NULL)
318         goto err_mem;
319
320     /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
321     num_ceil =
322         (1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
323
324     /*
325      * (Based on the rand(3) manpage:)
326      *
327      * For each group of 10 bytes (or less), we do the following:
328      *
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'.
335      *
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
339      * global 'md'.
340      */
341
342     CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
343     CRYPTO_THREAD_write_lock(rand_lock);
344     /*
345      * We could end up in an async engine while holding this lock so ensure
346      * we don't pause and cause a deadlock
347      */
348     ASYNC_block_pause();
349
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;
355
356     if (!initialized) {
357         RAND_poll();
358         initialized = 1;
359     }
360
361     if (!stirred_pool)
362         do_stir_pool = 1;
363
364     ok = (entropy >= ENTROPY_NEEDED);
365     if (!ok) {
366         /*
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.
376          */
377         entropy -= num;
378         if (entropy < 0)
379             entropy = 0;
380     }
381
382     if (do_stir_pool) {
383         /*
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.
389          */
390
391         int n = STATE_SIZE;     /* so that the complete pool gets accessed */
392         while (n > 0) {
393 #if MD_DIGEST_LENGTH > 20
394 # error "Please adjust DUMMY_SEED."
395 #endif
396 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
397             /*
398              * Note that the seed does not matter, it's just that
399              * rand_add expects to have something to hash.
400              */
401             rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
402             n -= MD_DIGEST_LENGTH;
403         }
404         if (ok)
405             stirred_pool = 1;
406     }
407
408     st_idx = state_index;
409     st_num = state_num;
410     md_c[0] = md_count[0];
411     md_c[1] = md_count[1];
412     memcpy(local_md, md, sizeof md);
413
414     state_index += num_ceil;
415     if (state_index > state_num)
416         state_index %= state_num;
417
418     /*
419      * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
420      * ours (but other threads may use them too)
421      */
422
423     md_count[0] += 1;
424
425     /* before unlocking, we must clear 'crypto_lock_rand' */
426     crypto_lock_rand = 0;
427     ASYNC_unblock_pause();
428     CRYPTO_THREAD_unlock(rand_lock);
429
430     while (num > 0) {
431         /* num_ceil -= MD_DIGEST_LENGTH/2 */
432         j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
433         num -= j;
434         if (!MD_Init(m))
435             goto err;
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))
439                 goto err;
440             curr_pid = 0;
441         }
442 #endif
443         if (curr_time) {        /* just in the first iteration to save time */
444             if (!MD_Update(m, (unsigned char *)&curr_time, sizeof curr_time))
445                 goto err;
446             if (!MD_Update(m, (unsigned char *)&tv, sizeof tv))
447                 goto err;
448             curr_time = 0;
449             if (!rand_hw_seed(m))
450                 goto err;
451         }
452         if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
453             goto err;
454         if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
455             goto err;
456
457         k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
458         if (k > 0) {
459             if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
460                 goto err;
461             if (!MD_Update(m, &(state[0]), k))
462                 goto err;
463         } else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
464             goto err;
465         if (!MD_Final(m, local_md))
466             goto err;
467
468         for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
469             /* may compete with other threads */
470             state[st_idx++] ^= local_md[i];
471             if (st_idx >= st_num)
472                 st_idx = 0;
473             if (i < j)
474                 *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
475         }
476     }
477
478     if (!MD_Init(m)
479         || !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
480         || !MD_Update(m, local_md, MD_DIGEST_LENGTH))
481         goto err;
482     CRYPTO_THREAD_write_lock(rand_lock);
483     /*
484      * Prevent deadlocks if we end up in an async engine
485      */
486     ASYNC_block_pause();
487     if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
488         CRYPTO_THREAD_unlock(rand_lock);
489         goto err;
490     }
491     ASYNC_unblock_pause();
492     CRYPTO_THREAD_unlock(rand_lock);
493
494     EVP_MD_CTX_free(m);
495     if (ok)
496         return (1);
497     else if (pseudo)
498         return 0;
499     else {
500         RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
501         ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
502                            "https://www.openssl.org/docs/faq.html");
503         return (0);
504     }
505  err:
506     RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
507     EVP_MD_CTX_free(m);
508     return 0;
509  err_mem:
510     RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
511     EVP_MD_CTX_free(m);
512     return 0;
513
514 }
515
516 static int rand_nopseudo_bytes(unsigned char *buf, int num)
517 {
518     return rand_bytes(buf, num, 0);
519 }
520
521 #if OPENSSL_API_COMPAT < 0x10100000L
522 /*
523  * pseudo-random bytes that are guaranteed to be unique but not unpredictable
524  */
525 static int rand_pseudo_bytes(unsigned char *buf, int num)
526 {
527     return rand_bytes(buf, num, 1);
528 }
529 #endif
530
531 static int rand_status(void)
532 {
533     CRYPTO_THREAD_ID cur;
534     int ret;
535     int do_not_lock;
536
537     CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
538     cur = CRYPTO_THREAD_get_current_id();
539     /*
540      * check if we already have the lock (could happen if a RAND_poll()
541      * implementation calls RAND_status())
542      */
543     if (crypto_lock_rand) {
544         CRYPTO_THREAD_read_lock(rand_tmp_lock);
545         do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
546         CRYPTO_THREAD_unlock(rand_tmp_lock);
547     } else
548         do_not_lock = 0;
549
550     if (!do_not_lock) {
551         CRYPTO_THREAD_write_lock(rand_lock);
552         /*
553          * Prevent deadlocks in case we end up in an async engine
554          */
555         ASYNC_block_pause();
556
557         /*
558          * prevent rand_bytes() from trying to obtain the lock again
559          */
560         CRYPTO_THREAD_write_lock(rand_tmp_lock);
561         locking_threadid = cur;
562         CRYPTO_THREAD_unlock(rand_tmp_lock);
563         crypto_lock_rand = 1;
564     }
565
566     if (!initialized) {
567         RAND_poll();
568         initialized = 1;
569     }
570
571     ret = entropy >= ENTROPY_NEEDED;
572
573     if (!do_not_lock) {
574         /* before unlocking, we must clear 'crypto_lock_rand' */
575         crypto_lock_rand = 0;
576
577         ASYNC_unblock_pause();
578         CRYPTO_THREAD_unlock(rand_lock);
579     }
580
581     return ret;
582 }
583
584 /*
585  * rand_hw_seed: get seed data from any available hardware RNG. only
586  * currently supports rdrand.
587  */
588
589 /* Adapted from eng_rdrand.c */
590
591 #if (defined(__i386)   || defined(__i386__)   || defined(_M_IX86) || \
592      defined(__x86_64) || defined(__x86_64__) || \
593      defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
594      && !defined(OPENSSL_NO_RDRAND)
595
596 # define RDRAND_CALLS    4
597
598 size_t OPENSSL_ia32_rdrand(void);
599 extern unsigned int OPENSSL_ia32cap_P[];
600
601 static int rand_hw_seed(EVP_MD_CTX *ctx)
602 {
603     int i;
604     if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
605         return 1;
606     for (i = 0; i < RDRAND_CALLS; i++) {
607         size_t rnd;
608         rnd = OPENSSL_ia32_rdrand();
609         if (rnd == 0)
610             return 1;
611         if (!MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t)))
612             return 0;
613     }
614     return 1;
615 }
616
617 /* XOR an existing buffer with random data */
618
619 void rand_hw_xor(unsigned char *buf, size_t num)
620 {
621     size_t rnd;
622     if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
623         return;
624     while (num >= sizeof(size_t)) {
625         rnd = OPENSSL_ia32_rdrand();
626         if (rnd == 0)
627             return;
628         *((size_t *)buf) ^= rnd;
629         buf += sizeof(size_t);
630         num -= sizeof(size_t);
631     }
632     if (num) {
633         rnd = OPENSSL_ia32_rdrand();
634         if (rnd == 0)
635             return;
636         while (num) {
637             *buf ^= rnd & 0xff;
638             rnd >>= 8;
639             buf++;
640             num--;
641         }
642     }
643 }
644
645 #else
646
647 static void rand_hw_seed(EVP_MD_CTX *ctx)
648 {
649     return;
650 }
651
652 void rand_hw_xor(unsigned char *buf, size_t num)
653 {
654     return;
655 }
656
657 #endif