Fix some RAND bugs
[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 void 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             rand_hw_seed(m);
450         }
451         if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
452             goto err;
453         if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
454             goto err;
455
456         k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
457         if (k > 0) {
458             if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
459                 goto err;
460             if (!MD_Update(m, &(state[0]), k))
461                 goto err;
462         } else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
463             goto err;
464         if (!MD_Final(m, local_md))
465             goto err;
466
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)
471                 st_idx = 0;
472             if (i < j)
473                 *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
474         }
475     }
476
477     if (!MD_Init(m)
478         || !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
479         || !MD_Update(m, local_md, MD_DIGEST_LENGTH))
480         goto err;
481     CRYPTO_THREAD_write_lock(rand_lock);
482     /*
483      * Prevent deadlocks if we end up in an async engine
484      */
485     ASYNC_block_pause();
486     if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
487         CRYPTO_THREAD_unlock(rand_lock);
488         goto err;
489     }
490     ASYNC_unblock_pause();
491     CRYPTO_THREAD_unlock(rand_lock);
492
493     EVP_MD_CTX_free(m);
494     if (ok)
495         return (1);
496     else if (pseudo)
497         return 0;
498     else {
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");
502         return (0);
503     }
504  err:
505     RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
506     EVP_MD_CTX_free(m);
507     return 0;
508  err_mem:
509     RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
510     EVP_MD_CTX_free(m);
511     return 0;
512
513 }
514
515 static int rand_nopseudo_bytes(unsigned char *buf, int num)
516 {
517     return rand_bytes(buf, num, 0);
518 }
519
520 #if OPENSSL_API_COMPAT < 0x10100000L
521 /*
522  * pseudo-random bytes that are guaranteed to be unique but not unpredictable
523  */
524 static int rand_pseudo_bytes(unsigned char *buf, int num)
525 {
526     return rand_bytes(buf, num, 1);
527 }
528 #endif
529
530 static int rand_status(void)
531 {
532     CRYPTO_THREAD_ID cur;
533     int ret;
534     int do_not_lock;
535
536     CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
537     cur = CRYPTO_THREAD_get_current_id();
538     /*
539      * check if we already have the lock (could happen if a RAND_poll()
540      * implementation calls RAND_status())
541      */
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);
546     } else
547         do_not_lock = 0;
548
549     if (!do_not_lock) {
550         CRYPTO_THREAD_write_lock(rand_lock);
551         /*
552          * Prevent deadlocks in case we end up in an async engine
553          */
554         ASYNC_block_pause();
555
556         /*
557          * prevent rand_bytes() from trying to obtain the lock again
558          */
559         CRYPTO_THREAD_write_lock(rand_tmp_lock);
560         locking_threadid = cur;
561         CRYPTO_THREAD_unlock(rand_tmp_lock);
562         crypto_lock_rand = 1;
563     }
564
565     if (!initialized) {
566         RAND_poll();
567         initialized = 1;
568     }
569
570     ret = entropy >= ENTROPY_NEEDED;
571
572     if (!do_not_lock) {
573         /* before unlocking, we must clear 'crypto_lock_rand' */
574         crypto_lock_rand = 0;
575
576         ASYNC_unblock_pause();
577         CRYPTO_THREAD_unlock(rand_lock);
578     }
579
580     return ret;
581 }
582
583 /*
584  * rand_hw_seed: get seed data from any available hardware RNG. only
585  * currently supports rdrand.
586  */
587
588 /* Adapted from eng_rdrand.c */
589
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)
594
595 # define RDRAND_CALLS    4
596
597 size_t OPENSSL_ia32_rdrand(void);
598 extern unsigned int OPENSSL_ia32cap_P[];
599
600 static void rand_hw_seed(EVP_MD_CTX *ctx)
601 {
602     int i;
603     if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
604         return;
605     for (i = 0; i < RDRAND_CALLS; i++) {
606         size_t rnd;
607         rnd = OPENSSL_ia32_rdrand();
608         if (rnd == 0)
609             return;
610         MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t));
611     }
612 }
613
614 /* XOR an existing buffer with random data */
615
616 void rand_hw_xor(unsigned char *buf, size_t num)
617 {
618     size_t rnd;
619     if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
620         return;
621     while (num >= sizeof(size_t)) {
622         rnd = OPENSSL_ia32_rdrand();
623         if (rnd == 0)
624             return;
625         *((size_t *)buf) ^= rnd;
626         buf += sizeof(size_t);
627         num -= sizeof(size_t);
628     }
629     if (num) {
630         rnd = OPENSSL_ia32_rdrand();
631         if (rnd == 0)
632             return;
633         while (num) {
634             *buf ^= rnd & 0xff;
635             rnd >>= 8;
636             buf++;
637             num--;
638         }
639     }
640 }
641
642 #else
643
644 static void rand_hw_seed(EVP_MD_CTX *ctx)
645 {
646     return;
647 }
648
649 void rand_hw_xor(unsigned char *buf, size_t num)
650 {
651     return;
652 }
653
654 #endif