7924478e9e8973654938941c4fa44775a24adf56
[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 #include <internal/thread_once.h>
31
32 #ifdef OPENSSL_FIPS
33 # include <openssl/fips.h>
34 #endif
35
36 #ifdef BN_DEBUG
37 # define PREDICT
38 #endif
39
40 /* #define PREDICT      1 */
41
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 };
47
48 static double entropy = 0;
49 static int initialized = 0;
50
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;
54
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;
60
61 #ifdef PREDICT
62 int rand_predictable = 0;
63 #endif
64
65 static int rand_hw_seed(EVP_MD_CTX *ctx);
66
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);
74 #endif
75 static int rand_status(void);
76
77 static RAND_METHOD rand_meth = {
78     rand_seed,
79     rand_nopseudo_bytes,
80     rand_cleanup,
81     rand_add,
82 #if OPENSSL_API_COMPAT < 0x10100000L
83     rand_pseudo_bytes,
84 #else
85     NULL,
86 #endif
87     rand_status
88 };
89
90 DEFINE_RUN_ONCE_STATIC(do_rand_lock_init)
91 {
92     rand_lock = CRYPTO_THREAD_lock_new();
93     rand_tmp_lock = CRYPTO_THREAD_lock_new();
94     return rand_lock != NULL && rand_tmp_lock != NULL;
95 }
96
97 RAND_METHOD *RAND_OpenSSL(void)
98 {
99     return (&rand_meth);
100 }
101
102 static void rand_cleanup(void)
103 {
104     OPENSSL_cleanse(state, sizeof(state));
105     state_num = 0;
106     state_index = 0;
107     OPENSSL_cleanse(md, MD_DIGEST_LENGTH);
108     md_count[0] = 0;
109     md_count[1] = 0;
110     entropy = 0;
111     initialized = 0;
112     CRYPTO_THREAD_lock_free(rand_lock);
113     CRYPTO_THREAD_lock_free(rand_tmp_lock);
114 }
115
116 static int rand_add(const void *buf, int num, double add)
117 {
118     int i, j, k, st_idx;
119     long md_c[2];
120     unsigned char local_md[MD_DIGEST_LENGTH];
121     EVP_MD_CTX *m;
122     int do_not_lock;
123     int rv = 0;
124
125     if (!num)
126         return 1;
127
128     /*
129      * (Based on the rand(3) manpage)
130      *
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
140      * hash function.
141      */
142
143     m = EVP_MD_CTX_new();
144     if (m == NULL)
145         goto err;
146
147     if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
148         goto err;
149
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);
156     } else
157         do_not_lock = 0;
158
159     if (!do_not_lock)
160         CRYPTO_THREAD_write_lock(rand_lock);
161     st_idx = state_index;
162
163     /*
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
166      * _some_ difference
167      */
168     md_c[0] = md_count[0];
169     md_c[1] = md_count[1];
170
171     memcpy(local_md, md, sizeof md);
172
173     /* state_index <= state_num <= STATE_SIZE */
174     state_index += num;
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;
181     }
182     /* state_index <= state_num <= STATE_SIZE */
183
184     /*
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
187      */
188
189     md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
190
191     if (!do_not_lock)
192         CRYPTO_THREAD_unlock(rand_lock);
193
194     for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
195         j = (num - i);
196         j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
197
198         if (!MD_Init(m))
199             goto err;
200         if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
201             goto err;
202         k = (st_idx + j) - STATE_SIZE;
203         if (k > 0) {
204             if (!MD_Update(m, &(state[st_idx]), j - k))
205                 goto err;
206             if (!MD_Update(m, &(state[0]), k))
207                 goto err;
208         } else if (!MD_Update(m, &(state[st_idx]), j))
209             goto err;
210
211         /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
212         if (!MD_Update(m, buf, j))
213             goto err;
214         /*
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
219          * insecure keys.
220          */
221
222         if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
223             goto err;
224         if (!MD_Final(m, local_md))
225             goto err;
226         md_c[1]++;
227
228         buf = (const char *)buf + j;
229
230         for (k = 0; k < j; k++) {
231             /*
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
237              * random state.
238              */
239             state[st_idx++] ^= local_md[k];
240             if (st_idx >= STATE_SIZE)
241                 st_idx = 0;
242         }
243     }
244
245     if (!do_not_lock)
246         CRYPTO_THREAD_write_lock(rand_lock);
247     /*
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
251      * md.
252      */
253     for (k = 0; k < (int)sizeof(md); k++) {
254         md[k] ^= local_md[k];
255     }
256     if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
257         entropy += add;
258     if (!do_not_lock)
259         CRYPTO_THREAD_unlock(rand_lock);
260
261     rv = 1;
262  err:
263     EVP_MD_CTX_free(m);
264     return rv;
265 }
266
267 static int rand_seed(const void *buf, int num)
268 {
269     return rand_add(buf, num, (double)num);
270 }
271
272 static int rand_bytes(unsigned char *buf, int num, int pseudo)
273 {
274     static volatile int stirred_pool = 0;
275     int i, j, k;
276     size_t num_ceil, st_idx, st_num;
277     int ok;
278     long md_c[2];
279     unsigned char local_md[MD_DIGEST_LENGTH];
280     EVP_MD_CTX *m;
281 #ifndef GETPID_IS_MEANINGLESS
282     pid_t curr_pid = getpid();
283 #endif
284     time_t curr_time = time(NULL);
285     int do_stir_pool = 0;
286 /* time value for various platforms */
287 #ifdef OPENSSL_SYS_WIN32
288     FILETIME tv;
289 # ifdef _WIN32_WCE
290     SYSTEMTIME t;
291     GetSystemTime(&t);
292     SystemTimeToFileTime(&t, &tv);
293 # else
294     GetSystemTimeAsFileTime(&tv);
295 # endif
296 #elif defined(OPENSSL_SYS_VXWORKS)
297     struct timespec tv;
298     clock_gettime(CLOCK_REALTIME, &ts);
299 #elif defined(OPENSSL_SYS_DSPBIOS)
300     unsigned long long tv, OPENSSL_rdtsc();
301     tv = OPENSSL_rdtsc();
302 #else
303     struct timeval tv;
304     gettimeofday(&tv, NULL);
305 #endif
306
307 #ifdef PREDICT
308     if (rand_predictable) {
309         static unsigned char val = 0;
310
311         for (i = 0; i < num; i++)
312             buf[i] = val++;
313         return (1);
314     }
315 #endif
316
317     if (num <= 0)
318         return 1;
319
320     m = EVP_MD_CTX_new();
321     if (m == NULL)
322         goto err_mem;
323
324     /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
325     num_ceil =
326         (1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
327
328     /*
329      * (Based on the rand(3) manpage:)
330      *
331      * For each group of 10 bytes (or less), we do the following:
332      *
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'.
339      *
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
343      * global 'md'.
344      */
345
346     if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
347         goto err_mem;
348
349     CRYPTO_THREAD_write_lock(rand_lock);
350     /*
351      * We could end up in an async engine while holding this lock so ensure
352      * we don't pause and cause a deadlock
353      */
354     ASYNC_block_pause();
355
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;
361
362     if (!initialized) {
363         RAND_poll();
364         initialized = 1;
365     }
366
367     if (!stirred_pool)
368         do_stir_pool = 1;
369
370     ok = (entropy >= ENTROPY_NEEDED);
371     if (!ok) {
372         /*
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.
382          */
383         entropy -= num;
384         if (entropy < 0)
385             entropy = 0;
386     }
387
388     if (do_stir_pool) {
389         /*
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.
395          */
396
397         int n = STATE_SIZE;     /* so that the complete pool gets accessed */
398         while (n > 0) {
399 #if MD_DIGEST_LENGTH > 20
400 # error "Please adjust DUMMY_SEED."
401 #endif
402 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
403             /*
404              * Note that the seed does not matter, it's just that
405              * rand_add expects to have something to hash.
406              */
407             rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
408             n -= MD_DIGEST_LENGTH;
409         }
410         if (ok)
411             stirred_pool = 1;
412     }
413
414     st_idx = state_index;
415     st_num = state_num;
416     md_c[0] = md_count[0];
417     md_c[1] = md_count[1];
418     memcpy(local_md, md, sizeof md);
419
420     state_index += num_ceil;
421     if (state_index > state_num)
422         state_index %= state_num;
423
424     /*
425      * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
426      * ours (but other threads may use them too)
427      */
428
429     md_count[0] += 1;
430
431     /* before unlocking, we must clear 'crypto_lock_rand' */
432     crypto_lock_rand = 0;
433     ASYNC_unblock_pause();
434     CRYPTO_THREAD_unlock(rand_lock);
435
436     while (num > 0) {
437         /* num_ceil -= MD_DIGEST_LENGTH/2 */
438         j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
439         num -= j;
440         if (!MD_Init(m))
441             goto err;
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))
445                 goto err;
446             curr_pid = 0;
447         }
448 #endif
449         if (curr_time) {        /* just in the first iteration to save time */
450             if (!MD_Update(m, (unsigned char *)&curr_time, sizeof curr_time))
451                 goto err;
452             if (!MD_Update(m, (unsigned char *)&tv, sizeof tv))
453                 goto err;
454             curr_time = 0;
455             if (!rand_hw_seed(m))
456                 goto err;
457         }
458         if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
459             goto err;
460         if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
461             goto err;
462
463         k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
464         if (k > 0) {
465             if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
466                 goto err;
467             if (!MD_Update(m, &(state[0]), k))
468                 goto err;
469         } else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
470             goto err;
471         if (!MD_Final(m, local_md))
472             goto err;
473
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)
478                 st_idx = 0;
479             if (i < j)
480                 *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
481         }
482     }
483
484     if (!MD_Init(m)
485         || !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
486         || !MD_Update(m, local_md, MD_DIGEST_LENGTH))
487         goto err;
488     CRYPTO_THREAD_write_lock(rand_lock);
489     /*
490      * Prevent deadlocks if we end up in an async engine
491      */
492     ASYNC_block_pause();
493     if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
494         CRYPTO_THREAD_unlock(rand_lock);
495         goto err;
496     }
497     ASYNC_unblock_pause();
498     CRYPTO_THREAD_unlock(rand_lock);
499
500     EVP_MD_CTX_free(m);
501     if (ok)
502         return (1);
503     else if (pseudo)
504         return 0;
505     else {
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");
509         return (0);
510     }
511  err:
512     RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
513     EVP_MD_CTX_free(m);
514     return 0;
515  err_mem:
516     RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
517     EVP_MD_CTX_free(m);
518     return 0;
519
520 }
521
522 static int rand_nopseudo_bytes(unsigned char *buf, int num)
523 {
524     return rand_bytes(buf, num, 0);
525 }
526
527 #if OPENSSL_API_COMPAT < 0x10100000L
528 /*
529  * pseudo-random bytes that are guaranteed to be unique but not unpredictable
530  */
531 static int rand_pseudo_bytes(unsigned char *buf, int num)
532 {
533     return rand_bytes(buf, num, 1);
534 }
535 #endif
536
537 static int rand_status(void)
538 {
539     CRYPTO_THREAD_ID cur;
540     int ret;
541     int do_not_lock;
542
543     if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
544         return 0;
545
546     cur = CRYPTO_THREAD_get_current_id();
547     /*
548      * check if we already have the lock (could happen if a RAND_poll()
549      * implementation calls RAND_status())
550      */
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);
555     } else
556         do_not_lock = 0;
557
558     if (!do_not_lock) {
559         CRYPTO_THREAD_write_lock(rand_lock);
560         /*
561          * Prevent deadlocks in case we end up in an async engine
562          */
563         ASYNC_block_pause();
564
565         /*
566          * prevent rand_bytes() from trying to obtain the lock again
567          */
568         CRYPTO_THREAD_write_lock(rand_tmp_lock);
569         locking_threadid = cur;
570         CRYPTO_THREAD_unlock(rand_tmp_lock);
571         crypto_lock_rand = 1;
572     }
573
574     if (!initialized) {
575         RAND_poll();
576         initialized = 1;
577     }
578
579     ret = entropy >= ENTROPY_NEEDED;
580
581     if (!do_not_lock) {
582         /* before unlocking, we must clear 'crypto_lock_rand' */
583         crypto_lock_rand = 0;
584
585         ASYNC_unblock_pause();
586         CRYPTO_THREAD_unlock(rand_lock);
587     }
588
589     return ret;
590 }
591
592 /*
593  * rand_hw_seed: get seed data from any available hardware RNG. only
594  * currently supports rdrand.
595  */
596
597 /* Adapted from eng_rdrand.c */
598
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)
603
604 # define RDRAND_CALLS    4
605
606 size_t OPENSSL_ia32_rdrand(void);
607 extern unsigned int OPENSSL_ia32cap_P[];
608
609 static int rand_hw_seed(EVP_MD_CTX *ctx)
610 {
611     int i;
612     if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
613         return 1;
614     for (i = 0; i < RDRAND_CALLS; i++) {
615         size_t rnd;
616         rnd = OPENSSL_ia32_rdrand();
617         if (rnd == 0)
618             return 1;
619         if (!MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t)))
620             return 0;
621     }
622     return 1;
623 }
624
625 /* XOR an existing buffer with random data */
626
627 void rand_hw_xor(unsigned char *buf, size_t num)
628 {
629     size_t rnd;
630     if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
631         return;
632     while (num >= sizeof(size_t)) {
633         rnd = OPENSSL_ia32_rdrand();
634         if (rnd == 0)
635             return;
636         *((size_t *)buf) ^= rnd;
637         buf += sizeof(size_t);
638         num -= sizeof(size_t);
639     }
640     if (num) {
641         rnd = OPENSSL_ia32_rdrand();
642         if (rnd == 0)
643             return;
644         while (num) {
645             *buf ^= rnd & 0xff;
646             rnd >>= 8;
647             buf++;
648             num--;
649         }
650     }
651 }
652
653 #else
654
655 static int rand_hw_seed(EVP_MD_CTX *ctx)
656 {
657     return 1;
658 }
659
660 void rand_hw_xor(unsigned char *buf, size_t num)
661 {
662     return;
663 }
664
665 #endif