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