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