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