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