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