Reformat evptests.txt
[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 #if defined(BN_DEBUG) || defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
33 # define PREDICT
34 #endif
35
36 /* #define PREDICT      1 */
37
38 #define STATE_SIZE      1023
39 static size_t state_num = 0, state_index = 0;
40 static unsigned char state[STATE_SIZE + MD_DIGEST_LENGTH];
41 static unsigned char md[MD_DIGEST_LENGTH];
42 static long md_count[2] = { 0, 0 };
43
44 static double entropy = 0;
45 static int initialized = 0;
46
47 static CRYPTO_RWLOCK *rand_lock = NULL;
48 static CRYPTO_RWLOCK *rand_tmp_lock = NULL;
49 static CRYPTO_ONCE rand_lock_init = CRYPTO_ONCE_STATIC_INIT;
50
51 /* May be set only when a thread holds rand_lock (to prevent double locking) */
52 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 */
55 static CRYPTO_THREAD_ID locking_threadid;
56
57 #ifdef PREDICT
58 int rand_predictable = 0;
59 #endif
60
61 static int rand_hw_seed(EVP_MD_CTX *ctx);
62
63 static void rand_cleanup(void);
64 static int rand_seed(const void *buf, int num);
65 static int rand_add(const void *buf, int num, double add_entropy);
66 static int rand_bytes(unsigned char *buf, int num, int pseudo);
67 static int rand_nopseudo_bytes(unsigned char *buf, int num);
68 #if OPENSSL_API_COMPAT < 0x10100000L
69 static int rand_pseudo_bytes(unsigned char *buf, int num);
70 #endif
71 static int rand_status(void);
72
73 static RAND_METHOD rand_meth = {
74     rand_seed,
75     rand_nopseudo_bytes,
76     rand_cleanup,
77     rand_add,
78 #if OPENSSL_API_COMPAT < 0x10100000L
79     rand_pseudo_bytes,
80 #else
81     NULL,
82 #endif
83     rand_status
84 };
85
86 DEFINE_RUN_ONCE_STATIC(do_rand_lock_init)
87 {
88     OPENSSL_init_crypto(0, NULL);
89     rand_lock = CRYPTO_THREAD_lock_new();
90     rand_tmp_lock = CRYPTO_THREAD_lock_new();
91     return rand_lock != NULL && rand_tmp_lock != NULL;
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 #ifdef PREDICT
126     if (rand_predictable)
127         return 1;
128 #endif
129
130     /*
131      * (Based on the rand(3) manpage)
132      *
133      * The input is chopped up into units of 20 bytes (or less for
134      * the last block).  Each of these blocks is run through the hash
135      * function as follows:  The data passed to the hash function
136      * is the current 'md', the same number of bytes from the 'state'
137      * (the location determined by in incremented looping index) as
138      * the current 'block', the new key data 'block', and 'count'
139      * (which is incremented after each use).
140      * The result of this is kept in 'md' and also xored into the
141      * 'state' at the same locations that were used as input into the
142      * hash function.
143      */
144
145     m = EVP_MD_CTX_new();
146     if (m == NULL)
147         goto err;
148
149     if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
150         goto err;
151
152     /* check if we already have the lock */
153     if (crypto_lock_rand) {
154         CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
155         CRYPTO_THREAD_read_lock(rand_tmp_lock);
156         do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
157         CRYPTO_THREAD_unlock(rand_tmp_lock);
158     } else
159         do_not_lock = 0;
160
161     if (!do_not_lock)
162         CRYPTO_THREAD_write_lock(rand_lock);
163     st_idx = state_index;
164
165     /*
166      * use our own copies of the counters so that even if a concurrent thread
167      * seeds with exactly the same data and uses the same subarray there's
168      * _some_ difference
169      */
170     md_c[0] = md_count[0];
171     md_c[1] = md_count[1];
172
173     memcpy(local_md, md, sizeof md);
174
175     /* state_index <= state_num <= STATE_SIZE */
176     state_index += num;
177     if (state_index >= STATE_SIZE) {
178         state_index %= STATE_SIZE;
179         state_num = STATE_SIZE;
180     } else if (state_num < STATE_SIZE) {
181         if (state_index > state_num)
182             state_num = state_index;
183     }
184     /* state_index <= state_num <= STATE_SIZE */
185
186     /*
187      * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
188      * will use now, but other threads may use them as well
189      */
190
191     md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
192
193     if (!do_not_lock)
194         CRYPTO_THREAD_unlock(rand_lock);
195
196     for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
197         j = (num - i);
198         j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
199
200         if (!MD_Init(m))
201             goto err;
202         if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
203             goto err;
204         k = (st_idx + j) - STATE_SIZE;
205         if (k > 0) {
206             if (!MD_Update(m, &(state[st_idx]), j - k))
207                 goto err;
208             if (!MD_Update(m, &(state[0]), k))
209                 goto err;
210         } else if (!MD_Update(m, &(state[st_idx]), j))
211             goto err;
212
213         /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
214         if (!MD_Update(m, buf, j))
215             goto err;
216         /*
217          * We know that line may cause programs such as purify and valgrind
218          * to complain about use of uninitialized data.  The problem is not,
219          * it's with the caller.  Removing that line will make sure you get
220          * really bad randomness and thereby other problems such as very
221          * insecure keys.
222          */
223
224         if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
225             goto err;
226         if (!MD_Final(m, local_md))
227             goto err;
228         md_c[1]++;
229
230         buf = (const char *)buf + j;
231
232         for (k = 0; k < j; k++) {
233             /*
234              * Parallel threads may interfere with this, but always each byte
235              * of the new state is the XOR of some previous value of its and
236              * local_md (intermediate values may be lost). Alway using locking
237              * could hurt performance more than necessary given that
238              * conflicts occur only when the total seeding is longer than the
239              * random state.
240              */
241             state[st_idx++] ^= local_md[k];
242             if (st_idx >= STATE_SIZE)
243                 st_idx = 0;
244         }
245     }
246
247     if (!do_not_lock)
248         CRYPTO_THREAD_write_lock(rand_lock);
249     /*
250      * Don't just copy back local_md into md -- this could mean that other
251      * thread's seeding remains without effect (except for the incremented
252      * counter).  By XORing it we keep at least as much entropy as fits into
253      * md.
254      */
255     for (k = 0; k < (int)sizeof(md); k++) {
256         md[k] ^= local_md[k];
257     }
258     if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
259         entropy += add;
260     if (!do_not_lock)
261         CRYPTO_THREAD_unlock(rand_lock);
262
263     rv = 1;
264  err:
265     EVP_MD_CTX_free(m);
266     return rv;
267 }
268
269 static int rand_seed(const void *buf, int num)
270 {
271     return rand_add(buf, num, (double)num);
272 }
273
274 static int rand_bytes(unsigned char *buf, int num, int pseudo)
275 {
276     static volatile int stirred_pool = 0;
277     int i, j, k;
278     size_t num_ceil, st_idx, st_num;
279     int ok;
280     long md_c[2];
281     unsigned char local_md[MD_DIGEST_LENGTH];
282     EVP_MD_CTX *m;
283 #ifndef GETPID_IS_MEANINGLESS
284     pid_t curr_pid = getpid();
285 #endif
286     time_t curr_time = time(NULL);
287     int do_stir_pool = 0;
288 /* time value for various platforms */
289 #ifdef OPENSSL_SYS_WIN32
290     FILETIME tv;
291 # ifdef _WIN32_WCE
292     SYSTEMTIME t;
293     GetSystemTime(&t);
294     SystemTimeToFileTime(&t, &tv);
295 # else
296     GetSystemTimeAsFileTime(&tv);
297 # endif
298 #elif defined(OPENSSL_SYS_VXWORKS)
299     struct timespec tv;
300     clock_gettime(CLOCK_REALTIME, &ts);
301 #elif defined(OPENSSL_SYS_DSPBIOS)
302     unsigned long long tv, OPENSSL_rdtsc();
303     tv = OPENSSL_rdtsc();
304 #else
305     struct timeval tv;
306     gettimeofday(&tv, NULL);
307 #endif
308
309 #ifdef PREDICT
310     if (rand_predictable) {
311         unsigned char val = 1;
312
313         for (i = 0; i < num; i++)
314             buf[i] = val++;
315         return (1);
316     }
317 #endif
318
319     if (num <= 0)
320         return 1;
321
322     m = EVP_MD_CTX_new();
323     if (m == NULL)
324         goto err_mem;
325
326     /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
327     num_ceil =
328         (1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
329
330     /*
331      * (Based on the rand(3) manpage:)
332      *
333      * For each group of 10 bytes (or less), we do the following:
334      *
335      * Input into the hash function the local 'md' (which is initialized from
336      * the global 'md' before any bytes are generated), the bytes that are to
337      * be overwritten by the random bytes, and bytes from the 'state'
338      * (incrementing looping index). From this digest output (which is kept
339      * in 'md'), the top (up to) 10 bytes are returned to the caller and the
340      * bottom 10 bytes are xored into the 'state'.
341      *
342      * Finally, after we have finished 'num' random bytes for the
343      * caller, 'count' (which is incremented) and the local and global 'md'
344      * are fed into the hash function and the results are kept in the
345      * global 'md'.
346      */
347
348     if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
349         goto err_mem;
350
351     CRYPTO_THREAD_write_lock(rand_lock);
352     /*
353      * We could end up in an async engine while holding this lock so ensure
354      * we don't pause and cause a deadlock
355      */
356     ASYNC_block_pause();
357
358     /* prevent rand_bytes() from trying to obtain the lock again */
359     CRYPTO_THREAD_write_lock(rand_tmp_lock);
360     locking_threadid = CRYPTO_THREAD_get_current_id();
361     CRYPTO_THREAD_unlock(rand_tmp_lock);
362     crypto_lock_rand = 1;
363
364     if (!initialized) {
365         RAND_poll();
366         initialized = 1;
367     }
368
369     if (!stirred_pool)
370         do_stir_pool = 1;
371
372     ok = (entropy >= ENTROPY_NEEDED);
373     if (!ok) {
374         /*
375          * If the PRNG state is not yet unpredictable, then seeing the PRNG
376          * output may help attackers to determine the new state; thus we have
377          * to decrease the entropy estimate. Once we've had enough initial
378          * seeding we don't bother to adjust the entropy count, though,
379          * because we're not ambitious to provide *information-theoretic*
380          * randomness. NOTE: This approach fails if the program forks before
381          * we have enough entropy. Entropy should be collected in a separate
382          * input pool and be transferred to the output pool only when the
383          * entropy limit has been reached.
384          */
385         entropy -= num;
386         if (entropy < 0)
387             entropy = 0;
388     }
389
390     if (do_stir_pool) {
391         /*
392          * In the output function only half of 'md' remains secret, so we
393          * better make sure that the required entropy gets 'evenly
394          * distributed' through 'state', our randomness pool. The input
395          * function (rand_add) chains all of 'md', which makes it more
396          * suitable for this purpose.
397          */
398
399         int n = STATE_SIZE;     /* so that the complete pool gets accessed */
400         while (n > 0) {
401 #if MD_DIGEST_LENGTH > 20
402 # error "Please adjust DUMMY_SEED."
403 #endif
404 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
405             /*
406              * Note that the seed does not matter, it's just that
407              * rand_add expects to have something to hash.
408              */
409             rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
410             n -= MD_DIGEST_LENGTH;
411         }
412         if (ok)
413             stirred_pool = 1;
414     }
415
416     st_idx = state_index;
417     st_num = state_num;
418     md_c[0] = md_count[0];
419     md_c[1] = md_count[1];
420     memcpy(local_md, md, sizeof md);
421
422     state_index += num_ceil;
423     if (state_index > state_num)
424         state_index %= state_num;
425
426     /*
427      * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
428      * ours (but other threads may use them too)
429      */
430
431     md_count[0] += 1;
432
433     /* before unlocking, we must clear 'crypto_lock_rand' */
434     crypto_lock_rand = 0;
435     ASYNC_unblock_pause();
436     CRYPTO_THREAD_unlock(rand_lock);
437
438     while (num > 0) {
439         /* num_ceil -= MD_DIGEST_LENGTH/2 */
440         j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
441         num -= j;
442         if (!MD_Init(m))
443             goto err;
444 #ifndef GETPID_IS_MEANINGLESS
445         if (curr_pid) {         /* just in the first iteration to save time */
446             if (!MD_Update(m, (unsigned char *)&curr_pid, sizeof curr_pid))
447                 goto err;
448             curr_pid = 0;
449         }
450 #endif
451         if (curr_time) {        /* just in the first iteration to save time */
452             if (!MD_Update(m, (unsigned char *)&curr_time, sizeof curr_time))
453                 goto err;
454             if (!MD_Update(m, (unsigned char *)&tv, sizeof tv))
455                 goto err;
456             curr_time = 0;
457             if (!rand_hw_seed(m))
458                 goto err;
459         }
460         if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
461             goto err;
462         if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
463             goto err;
464
465         k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
466         if (k > 0) {
467             if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
468                 goto err;
469             if (!MD_Update(m, &(state[0]), k))
470                 goto err;
471         } else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
472             goto err;
473         if (!MD_Final(m, local_md))
474             goto err;
475
476         for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
477             /* may compete with other threads */
478             state[st_idx++] ^= local_md[i];
479             if (st_idx >= st_num)
480                 st_idx = 0;
481             if (i < j)
482                 *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
483         }
484     }
485
486     if (!MD_Init(m)
487         || !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
488         || !MD_Update(m, local_md, MD_DIGEST_LENGTH))
489         goto err;
490     CRYPTO_THREAD_write_lock(rand_lock);
491     /*
492      * Prevent deadlocks if we end up in an async engine
493      */
494     ASYNC_block_pause();
495     if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
496         CRYPTO_THREAD_unlock(rand_lock);
497         goto err;
498     }
499     ASYNC_unblock_pause();
500     CRYPTO_THREAD_unlock(rand_lock);
501
502     EVP_MD_CTX_free(m);
503     if (ok)
504         return (1);
505     else if (pseudo)
506         return 0;
507     else {
508         RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
509         ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
510                            "https://www.openssl.org/docs/faq.html");
511         return (0);
512     }
513  err:
514     RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
515     EVP_MD_CTX_free(m);
516     return 0;
517  err_mem:
518     RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
519     EVP_MD_CTX_free(m);
520     return 0;
521
522 }
523
524 static int rand_nopseudo_bytes(unsigned char *buf, int num)
525 {
526     return rand_bytes(buf, num, 0);
527 }
528
529 #if OPENSSL_API_COMPAT < 0x10100000L
530 /*
531  * pseudo-random bytes that are guaranteed to be unique but not unpredictable
532  */
533 static int rand_pseudo_bytes(unsigned char *buf, int num)
534 {
535     return rand_bytes(buf, num, 1);
536 }
537 #endif
538
539 static int rand_status(void)
540 {
541     CRYPTO_THREAD_ID cur;
542     int ret;
543     int do_not_lock;
544
545     if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
546         return 0;
547
548     cur = CRYPTO_THREAD_get_current_id();
549     /*
550      * check if we already have the lock (could happen if a RAND_poll()
551      * implementation calls RAND_status())
552      */
553     if (crypto_lock_rand) {
554         CRYPTO_THREAD_read_lock(rand_tmp_lock);
555         do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
556         CRYPTO_THREAD_unlock(rand_tmp_lock);
557     } else
558         do_not_lock = 0;
559
560     if (!do_not_lock) {
561         CRYPTO_THREAD_write_lock(rand_lock);
562         /*
563          * Prevent deadlocks in case we end up in an async engine
564          */
565         ASYNC_block_pause();
566
567         /*
568          * prevent rand_bytes() from trying to obtain the lock again
569          */
570         CRYPTO_THREAD_write_lock(rand_tmp_lock);
571         locking_threadid = cur;
572         CRYPTO_THREAD_unlock(rand_tmp_lock);
573         crypto_lock_rand = 1;
574     }
575
576     if (!initialized) {
577         RAND_poll();
578         initialized = 1;
579     }
580
581     ret = entropy >= ENTROPY_NEEDED;
582
583     if (!do_not_lock) {
584         /* before unlocking, we must clear 'crypto_lock_rand' */
585         crypto_lock_rand = 0;
586
587         ASYNC_unblock_pause();
588         CRYPTO_THREAD_unlock(rand_lock);
589     }
590
591     return ret;
592 }
593
594 /*
595  * rand_hw_seed: get seed data from any available hardware RNG. only
596  * currently supports rdrand.
597  */
598
599 /* Adapted from eng_rdrand.c */
600
601 #if (defined(__i386)   || defined(__i386__)   || defined(_M_IX86) || \
602      defined(__x86_64) || defined(__x86_64__) || \
603      defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
604      && !defined(OPENSSL_NO_RDRAND)
605
606 # define RDRAND_CALLS    4
607
608 size_t OPENSSL_ia32_rdrand(void);
609 extern unsigned int OPENSSL_ia32cap_P[];
610
611 static int rand_hw_seed(EVP_MD_CTX *ctx)
612 {
613     int i;
614     if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
615         return 1;
616     for (i = 0; i < RDRAND_CALLS; i++) {
617         size_t rnd;
618         rnd = OPENSSL_ia32_rdrand();
619         if (rnd == 0)
620             return 1;
621         if (!MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t)))
622             return 0;
623     }
624     return 1;
625 }
626
627 /* XOR an existing buffer with random data */
628
629 void rand_hw_xor(unsigned char *buf, size_t num)
630 {
631     size_t rnd;
632     if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
633         return;
634     while (num >= sizeof(size_t)) {
635         rnd = OPENSSL_ia32_rdrand();
636         if (rnd == 0)
637             return;
638         *((size_t *)buf) ^= rnd;
639         buf += sizeof(size_t);
640         num -= sizeof(size_t);
641     }
642     if (num) {
643         rnd = OPENSSL_ia32_rdrand();
644         if (rnd == 0)
645             return;
646         while (num) {
647             *buf ^= rnd & 0xff;
648             rnd >>= 8;
649             buf++;
650             num--;
651         }
652     }
653 }
654
655 #else
656
657 static int rand_hw_seed(EVP_MD_CTX *ctx)
658 {
659     return 1;
660 }
661
662 void rand_hw_xor(unsigned char *buf, size_t num)
663 {
664     return;
665 }
666
667 #endif