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