GH975 Add ex_data functions for X509_STORE
[openssl.git] / crypto / rand / md_rand.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2001 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110
111 #include <stdio.h>
112 #include <string.h>
113
114 #include "e_os.h"
115
116 #if !(defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_DSPBIOS))
117 # include <sys/time.h>
118 #endif
119 #if defined(OPENSSL_SYS_VXWORKS)
120 # include <time.h>
121 #endif
122
123 #include <openssl/opensslconf.h>
124 #include <openssl/crypto.h>
125 #include <openssl/rand.h>
126 #include <openssl/async.h>
127 #include "rand_lcl.h"
128 #include "internal/threads.h"
129
130 #include <openssl/err.h>
131
132 #ifdef OPENSSL_FIPS
133 # include <openssl/fips.h>
134 #endif
135
136 #ifdef BN_DEBUG
137 # define PREDICT
138 #endif
139
140 /* #define PREDICT      1 */
141
142 #define STATE_SIZE      1023
143 static int state_num = 0, state_index = 0;
144 static unsigned char state[STATE_SIZE + MD_DIGEST_LENGTH];
145 static unsigned char md[MD_DIGEST_LENGTH];
146 static long md_count[2] = { 0, 0 };
147
148 static double entropy = 0;
149 static int initialized = 0;
150
151 static CRYPTO_RWLOCK *rand_lock = NULL;
152 static CRYPTO_RWLOCK *rand_tmp_lock = NULL;
153 static CRYPTO_ONCE rand_lock_init = CRYPTO_ONCE_STATIC_INIT;
154
155 /* May be set only when a thread holds rand_lock (to prevent double locking) */
156 static unsigned int crypto_lock_rand = 0;
157 /* access to locking_threadid is synchronized by rand_tmp_lock */
158 /* valid iff crypto_lock_rand is set */
159 static CRYPTO_THREAD_ID locking_threadid;
160
161 #ifdef PREDICT
162 int rand_predictable = 0;
163 #endif
164
165 static void rand_hw_seed(EVP_MD_CTX *ctx);
166
167 static void rand_cleanup(void);
168 static int rand_seed(const void *buf, int num);
169 static int rand_add(const void *buf, int num, double add_entropy);
170 static int rand_bytes(unsigned char *buf, int num, int pseudo);
171 static int rand_nopseudo_bytes(unsigned char *buf, int num);
172 #if OPENSSL_API_COMPAT < 0x10100000L
173 static int rand_pseudo_bytes(unsigned char *buf, int num);
174 #endif
175 static int rand_status(void);
176
177 static RAND_METHOD rand_meth = {
178     rand_seed,
179     rand_nopseudo_bytes,
180     rand_cleanup,
181     rand_add,
182 #if OPENSSL_API_COMPAT < 0x10100000L
183     rand_pseudo_bytes,
184 #else
185     NULL,
186 #endif
187     rand_status
188 };
189
190 static void do_rand_lock_init(void)
191 {
192     rand_lock = CRYPTO_THREAD_lock_new();
193     rand_tmp_lock = CRYPTO_THREAD_lock_new();
194 }
195
196 RAND_METHOD *RAND_OpenSSL(void)
197 {
198     return (&rand_meth);
199 }
200
201 static void rand_cleanup(void)
202 {
203     OPENSSL_cleanse(state, sizeof(state));
204     state_num = 0;
205     state_index = 0;
206     OPENSSL_cleanse(md, MD_DIGEST_LENGTH);
207     md_count[0] = 0;
208     md_count[1] = 0;
209     entropy = 0;
210     initialized = 0;
211     CRYPTO_THREAD_lock_free(rand_lock);
212     CRYPTO_THREAD_lock_free(rand_tmp_lock);
213 }
214
215 static int rand_add(const void *buf, int num, double add)
216 {
217     int i, j, k, st_idx;
218     long md_c[2];
219     unsigned char local_md[MD_DIGEST_LENGTH];
220     EVP_MD_CTX *m;
221     int do_not_lock;
222     int rv = 0;
223
224     if (!num)
225         return 1;
226
227     /*
228      * (Based on the rand(3) manpage)
229      *
230      * The input is chopped up into units of 20 bytes (or less for
231      * the last block).  Each of these blocks is run through the hash
232      * function as follows:  The data passed to the hash function
233      * is the current 'md', the same number of bytes from the 'state'
234      * (the location determined by in incremented looping index) as
235      * the current 'block', the new key data 'block', and 'count'
236      * (which is incremented after each use).
237      * The result of this is kept in 'md' and also xored into the
238      * 'state' at the same locations that were used as input into the
239      * hash function.
240      */
241
242     m = EVP_MD_CTX_new();
243     if (m == NULL)
244         goto err;
245
246     CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
247
248     /* check if we already have the lock */
249     if (crypto_lock_rand) {
250         CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
251         CRYPTO_THREAD_read_lock(rand_tmp_lock);
252         do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
253         CRYPTO_THREAD_unlock(rand_tmp_lock);
254     } else
255         do_not_lock = 0;
256
257     if (!do_not_lock)
258         CRYPTO_THREAD_write_lock(rand_lock);
259     st_idx = state_index;
260
261     /*
262      * use our own copies of the counters so that even if a concurrent thread
263      * seeds with exactly the same data and uses the same subarray there's
264      * _some_ difference
265      */
266     md_c[0] = md_count[0];
267     md_c[1] = md_count[1];
268
269     memcpy(local_md, md, sizeof md);
270
271     /* state_index <= state_num <= STATE_SIZE */
272     state_index += num;
273     if (state_index >= STATE_SIZE) {
274         state_index %= STATE_SIZE;
275         state_num = STATE_SIZE;
276     } else if (state_num < STATE_SIZE) {
277         if (state_index > state_num)
278             state_num = state_index;
279     }
280     /* state_index <= state_num <= STATE_SIZE */
281
282     /*
283      * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
284      * will use now, but other threads may use them as well
285      */
286
287     md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
288
289     if (!do_not_lock)
290         CRYPTO_THREAD_unlock(rand_lock);
291
292     for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
293         j = (num - i);
294         j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
295
296         if (!MD_Init(m))
297             goto err;
298         if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
299             goto err;
300         k = (st_idx + j) - STATE_SIZE;
301         if (k > 0) {
302             if (!MD_Update(m, &(state[st_idx]), j - k))
303                 goto err;
304             if (!MD_Update(m, &(state[0]), k))
305                 goto err;
306         } else if (!MD_Update(m, &(state[st_idx]), j))
307             goto err;
308
309         /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
310         if (!MD_Update(m, buf, j))
311             goto err;
312         /*
313          * We know that line may cause programs such as purify and valgrind
314          * to complain about use of uninitialized data.  The problem is not,
315          * it's with the caller.  Removing that line will make sure you get
316          * really bad randomness and thereby other problems such as very
317          * insecure keys.
318          */
319
320         if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
321             goto err;
322         if (!MD_Final(m, local_md))
323             goto err;
324         md_c[1]++;
325
326         buf = (const char *)buf + j;
327
328         for (k = 0; k < j; k++) {
329             /*
330              * Parallel threads may interfere with this, but always each byte
331              * of the new state is the XOR of some previous value of its and
332              * local_md (intermediate values may be lost). Alway using locking
333              * could hurt performance more than necessary given that
334              * conflicts occur only when the total seeding is longer than the
335              * random state.
336              */
337             state[st_idx++] ^= local_md[k];
338             if (st_idx >= STATE_SIZE)
339                 st_idx = 0;
340         }
341     }
342
343     if (!do_not_lock)
344         CRYPTO_THREAD_write_lock(rand_lock);
345     /*
346      * Don't just copy back local_md into md -- this could mean that other
347      * thread's seeding remains without effect (except for the incremented
348      * counter).  By XORing it we keep at least as much entropy as fits into
349      * md.
350      */
351     for (k = 0; k < (int)sizeof(md); k++) {
352         md[k] ^= local_md[k];
353     }
354     if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
355         entropy += add;
356     if (!do_not_lock)
357         CRYPTO_THREAD_unlock(rand_lock);
358
359     rv = 1;
360  err:
361     EVP_MD_CTX_free(m);
362     return rv;
363 }
364
365 static int rand_seed(const void *buf, int num)
366 {
367     return rand_add(buf, num, (double)num);
368 }
369
370 static int rand_bytes(unsigned char *buf, int num, int pseudo)
371 {
372     static volatile int stirred_pool = 0;
373     int i, j, k, st_num, st_idx;
374     int num_ceil;
375     int ok;
376     long md_c[2];
377     unsigned char local_md[MD_DIGEST_LENGTH];
378     EVP_MD_CTX *m;
379 #ifndef GETPID_IS_MEANINGLESS
380     pid_t curr_pid = getpid();
381 #endif
382     time_t curr_time = time(NULL);
383     int do_stir_pool = 0;
384 /* time value for various platforms */
385 #ifdef OPENSSL_SYS_WIN32
386     FILETIME tv;
387 # ifdef _WIN32_WCE
388     SYSTEMTIME t;
389     GetSystemTime(&t);
390     SystemTimeToFileTime(&t, &tv);
391 # else
392     GetSystemTimeAsFileTime(&tv);
393 # endif
394 #elif defined(OPENSSL_SYS_VXWORKS)
395     struct timespec tv;
396     clock_gettime(CLOCK_REALTIME, &ts);
397 #elif defined(OPENSSL_SYS_DSPBIOS)
398     unsigned long long tv, OPENSSL_rdtsc();
399     tv = OPENSSL_rdtsc();
400 #else
401     struct timeval tv;
402     gettimeofday(&tv, NULL);
403 #endif
404
405 #ifdef PREDICT
406     if (rand_predictable) {
407         static unsigned char val = 0;
408
409         for (i = 0; i < num; i++)
410             buf[i] = val++;
411         return (1);
412     }
413 #endif
414
415     if (num <= 0)
416         return 1;
417
418     m = EVP_MD_CTX_new();
419     if (m == NULL)
420         goto err_mem;
421
422     /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
423     num_ceil =
424         (1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
425
426     /*
427      * (Based on the rand(3) manpage:)
428      *
429      * For each group of 10 bytes (or less), we do the following:
430      *
431      * Input into the hash function the local 'md' (which is initialized from
432      * the global 'md' before any bytes are generated), the bytes that are to
433      * be overwritten by the random bytes, and bytes from the 'state'
434      * (incrementing looping index). From this digest output (which is kept
435      * in 'md'), the top (up to) 10 bytes are returned to the caller and the
436      * bottom 10 bytes are xored into the 'state'.
437      *
438      * Finally, after we have finished 'num' random bytes for the
439      * caller, 'count' (which is incremented) and the local and global 'md'
440      * are fed into the hash function and the results are kept in the
441      * global 'md'.
442      */
443
444     CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
445     CRYPTO_THREAD_write_lock(rand_lock);
446     /*
447      * We could end up in an async engine while holding this lock so ensure
448      * we don't pause and cause a deadlock
449      */
450     ASYNC_block_pause();
451
452     /* prevent rand_bytes() from trying to obtain the lock again */
453     CRYPTO_THREAD_write_lock(rand_tmp_lock);
454     locking_threadid = CRYPTO_THREAD_get_current_id();
455     CRYPTO_THREAD_unlock(rand_tmp_lock);
456     crypto_lock_rand = 1;
457
458     if (!initialized) {
459         RAND_poll();
460         initialized = 1;
461     }
462
463     if (!stirred_pool)
464         do_stir_pool = 1;
465
466     ok = (entropy >= ENTROPY_NEEDED);
467     if (!ok) {
468         /*
469          * If the PRNG state is not yet unpredictable, then seeing the PRNG
470          * output may help attackers to determine the new state; thus we have
471          * to decrease the entropy estimate. Once we've had enough initial
472          * seeding we don't bother to adjust the entropy count, though,
473          * because we're not ambitious to provide *information-theoretic*
474          * randomness. NOTE: This approach fails if the program forks before
475          * we have enough entropy. Entropy should be collected in a separate
476          * input pool and be transferred to the output pool only when the
477          * entropy limit has been reached.
478          */
479         entropy -= num;
480         if (entropy < 0)
481             entropy = 0;
482     }
483
484     if (do_stir_pool) {
485         /*
486          * In the output function only half of 'md' remains secret, so we
487          * better make sure that the required entropy gets 'evenly
488          * distributed' through 'state', our randomness pool. The input
489          * function (rand_add) chains all of 'md', which makes it more
490          * suitable for this purpose.
491          */
492
493         int n = STATE_SIZE;     /* so that the complete pool gets accessed */
494         while (n > 0) {
495 #if MD_DIGEST_LENGTH > 20
496 # error "Please adjust DUMMY_SEED."
497 #endif
498 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
499             /*
500              * Note that the seed does not matter, it's just that
501              * rand_add expects to have something to hash.
502              */
503             rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
504             n -= MD_DIGEST_LENGTH;
505         }
506         if (ok)
507             stirred_pool = 1;
508     }
509
510     st_idx = state_index;
511     st_num = state_num;
512     md_c[0] = md_count[0];
513     md_c[1] = md_count[1];
514     memcpy(local_md, md, sizeof md);
515
516     state_index += num_ceil;
517     if (state_index > state_num)
518         state_index %= state_num;
519
520     /*
521      * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
522      * ours (but other threads may use them too)
523      */
524
525     md_count[0] += 1;
526
527     /* before unlocking, we must clear 'crypto_lock_rand' */
528     crypto_lock_rand = 0;
529     ASYNC_unblock_pause();
530     CRYPTO_THREAD_unlock(rand_lock);
531
532     while (num > 0) {
533         /* num_ceil -= MD_DIGEST_LENGTH/2 */
534         j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
535         num -= j;
536         if (!MD_Init(m))
537             goto err;
538 #ifndef GETPID_IS_MEANINGLESS
539         if (curr_pid) {         /* just in the first iteration to save time */
540             if (!MD_Update(m, (unsigned char *)&curr_pid, sizeof curr_pid))
541                 goto err;
542             curr_pid = 0;
543         }
544 #endif
545         if (curr_time) {        /* just in the first iteration to save time */
546             if (!MD_Update(m, (unsigned char *)&curr_time, sizeof curr_time))
547                 goto err;
548             if (!MD_Update(m, (unsigned char *)&tv, sizeof tv))
549                 goto err;
550             curr_time = 0;
551             rand_hw_seed(m);
552         }
553         if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
554             goto err;
555         if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
556             goto err;
557
558         k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
559         if (k > 0) {
560             if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
561                 goto err;
562             if (!MD_Update(m, &(state[0]), k))
563                 goto err;
564         } else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
565             goto err;
566         if (!MD_Final(m, local_md))
567             goto err;
568
569         for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
570             /* may compete with other threads */
571             state[st_idx++] ^= local_md[i];
572             if (st_idx >= st_num)
573                 st_idx = 0;
574             if (i < j)
575                 *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
576         }
577     }
578
579     if (!MD_Init(m)
580         || !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
581         || !MD_Update(m, local_md, MD_DIGEST_LENGTH))
582         goto err;
583     CRYPTO_THREAD_write_lock(rand_lock);
584     /*
585      * Prevent deadlocks if we end up in an async engine
586      */
587     ASYNC_block_pause();
588     if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
589         CRYPTO_THREAD_unlock(rand_lock);
590         goto err;
591     }
592     ASYNC_unblock_pause();
593     CRYPTO_THREAD_unlock(rand_lock);
594
595     EVP_MD_CTX_free(m);
596     if (ok)
597         return (1);
598     else if (pseudo)
599         return 0;
600     else {
601         RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
602         ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
603                            "https://www.openssl.org/docs/faq.html");
604         return (0);
605     }
606  err:
607     RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
608     EVP_MD_CTX_free(m);
609     return 0;
610  err_mem:
611     RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
612     EVP_MD_CTX_free(m);
613     return 0;
614
615 }
616
617 static int rand_nopseudo_bytes(unsigned char *buf, int num)
618 {
619     return rand_bytes(buf, num, 0);
620 }
621
622 #if OPENSSL_API_COMPAT < 0x10100000L
623 /*
624  * pseudo-random bytes that are guaranteed to be unique but not unpredictable
625  */
626 static int rand_pseudo_bytes(unsigned char *buf, int num)
627 {
628     return rand_bytes(buf, num, 1);
629 }
630 #endif
631
632 static int rand_status(void)
633 {
634     CRYPTO_THREAD_ID cur;
635     int ret;
636     int do_not_lock;
637
638     CRYPTO_THREAD_run_once(&rand_lock_init, do_rand_lock_init);
639     cur = CRYPTO_THREAD_get_current_id();
640     /*
641      * check if we already have the lock (could happen if a RAND_poll()
642      * implementation calls RAND_status())
643      */
644     if (crypto_lock_rand) {
645         CRYPTO_THREAD_read_lock(rand_tmp_lock);
646         do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
647         CRYPTO_THREAD_unlock(rand_tmp_lock);
648     } else
649         do_not_lock = 0;
650
651     if (!do_not_lock) {
652         CRYPTO_THREAD_write_lock(rand_lock);
653         /*
654          * Prevent deadlocks in case we end up in an async engine
655          */
656         ASYNC_block_pause();
657
658         /*
659          * prevent rand_bytes() from trying to obtain the lock again
660          */
661         CRYPTO_THREAD_write_lock(rand_tmp_lock);
662         locking_threadid = cur;
663         CRYPTO_THREAD_unlock(rand_tmp_lock);
664         crypto_lock_rand = 1;
665     }
666
667     if (!initialized) {
668         RAND_poll();
669         initialized = 1;
670     }
671
672     ret = entropy >= ENTROPY_NEEDED;
673
674     if (!do_not_lock) {
675         /* before unlocking, we must clear 'crypto_lock_rand' */
676         crypto_lock_rand = 0;
677
678         ASYNC_unblock_pause();
679         CRYPTO_THREAD_unlock(rand_lock);
680     }
681
682     return ret;
683 }
684
685 /*
686  * rand_hw_seed: get seed data from any available hardware RNG. only
687  * currently supports rdrand.
688  */
689
690 /* Adapted from eng_rdrand.c */
691
692 #if (defined(__i386)   || defined(__i386__)   || defined(_M_IX86) || \
693      defined(__x86_64) || defined(__x86_64__) || \
694      defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
695      && !defined(OPENSSL_NO_RDRAND)
696
697 # define RDRAND_CALLS    4
698
699 size_t OPENSSL_ia32_rdrand(void);
700 extern unsigned int OPENSSL_ia32cap_P[];
701
702 static void rand_hw_seed(EVP_MD_CTX *ctx)
703 {
704     int i;
705     if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
706         return;
707     for (i = 0; i < RDRAND_CALLS; i++) {
708         size_t rnd;
709         rnd = OPENSSL_ia32_rdrand();
710         if (rnd == 0)
711             return;
712         MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t));
713     }
714 }
715
716 /* XOR an existing buffer with random data */
717
718 void rand_hw_xor(unsigned char *buf, size_t num)
719 {
720     size_t rnd;
721     if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
722         return;
723     while (num >= sizeof(size_t)) {
724         rnd = OPENSSL_ia32_rdrand();
725         if (rnd == 0)
726             return;
727         *((size_t *)buf) ^= rnd;
728         buf += sizeof(size_t);
729         num -= sizeof(size_t);
730     }
731     if (num) {
732         rnd = OPENSSL_ia32_rdrand();
733         if (rnd == 0)
734             return;
735         while (num) {
736             *buf ^= rnd & 0xff;
737             rnd >>= 8;
738             buf++;
739             num--;
740         }
741     }
742 }
743
744 #else
745
746 static void rand_hw_seed(EVP_MD_CTX *ctx)
747 {
748     return;
749 }
750
751 void rand_hw_xor(unsigned char *buf, size_t num)
752 {
753     return;
754 }
755
756 #endif