ossl_rand.c 17.3 KB
Newer Older
R
Rich Salz 已提交
1 2
/*
 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
B
Bodo Möller 已提交
3
 *
R
Rich Salz 已提交
4 5 6 7
 * Licensed under the OpenSSL license (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
B
Bodo Möller 已提交
8
 */
9 10

#include <stdio.h>
B
Ben Laurie 已提交
11
#include <string.h>
12

13
#include "e_os.h"
14

15
#if !(defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_DSPBIOS))
16 17 18 19 20 21
# include <sys/time.h>
#endif
#if defined(OPENSSL_SYS_VXWORKS)
# include <time.h>
#endif

22
#include <openssl/opensslconf.h>
23
#include <openssl/crypto.h>
24
#include <openssl/rand.h>
M
Matt Caswell 已提交
25
#include <openssl/async.h>
26
#include <openssl/err.h>
27
#include <internal/thread_once.h>
R
Rich Salz 已提交
28
#include "rand_lcl.h"
29

30 31
#define STATE_SIZE      1023

R
Rich Salz 已提交
32 33 34 35 36
typedef struct ossl_rand_state_st OSSL_RAND_STATE;

struct ossl_rand_state_st {
    size_t num;
    size_t index;
R
Rich Salz 已提交
37 38
    unsigned char state[STATE_SIZE + SHA_DIGEST_LENGTH];
    unsigned char md[SHA_DIGEST_LENGTH];
R
Rich Salz 已提交
39 40
    long md_count[2];
};
41

R
Rich Salz 已提交
42 43 44
static OSSL_RAND_STATE global_state;
static double randomness = 0;
static int initialized = 0;
45 46
static CRYPTO_RWLOCK *rand_lock = NULL;
static CRYPTO_RWLOCK *rand_tmp_lock = NULL;
R
Rich Salz 已提交
47 48
static CRYPTO_ONCE ossl_rand_init = CRYPTO_ONCE_STATIC_INIT;
static CRYPTO_THREAD_LOCAL key;
49 50 51

/* May be set only when a thread holds rand_lock (to prevent double locking) */
static unsigned int crypto_lock_rand = 0;
R
Rich Salz 已提交
52 53 54 55
/*
 * access to locking_threadid is synchronized by rand_tmp_lock;
 * valid iff crypto_lock_rand is set
 */
56
static CRYPTO_THREAD_ID locking_threadid;
B
Bodo Möller 已提交
57

58
static int rand_hw_seed(EVP_MD_CTX *ctx);
59

R
Rich Salz 已提交
60 61 62
static void rand_thread_cleanup(void *arg)
{
    OSSL_RAND_STATE *sp = arg;
63

R
Rich Salz 已提交
64 65
    OPENSSL_clear_free(sp, sizeof(*sp));
}
66

R
Rich Salz 已提交
67
DEFINE_RUN_ONCE_STATIC(do_ossl_rand_init)
68
{
R
Rich Salz 已提交
69 70
    int ret = 1;

M
Matt Caswell 已提交
71
    OPENSSL_init_crypto(0, NULL);
72
    rand_lock = CRYPTO_THREAD_lock_new();
R
Rich Salz 已提交
73
    ret &= rand_lock != NULL;
74
    rand_tmp_lock = CRYPTO_THREAD_lock_new();
R
Rich Salz 已提交
75 76 77
    ret &= rand_tmp_lock != NULL;
    ret &= CRYPTO_THREAD_init_local(&key, rand_thread_cleanup) == 1;
    return ret;
78 79
}

R
Rich Salz 已提交
80
RAND_METHOD *RAND_OpenSSL(void)
81
{
R
Rich Salz 已提交
82
    return &openssl_rand_meth;
83
}
84

R
Rich Salz 已提交
85
static void rand_cleanup(void)
86
{
R
Rich Salz 已提交
87 88
    OPENSSL_cleanse(&global_state, sizeof(global_state));
    randomness = 0;
89
    initialized = 0;
90 91
    CRYPTO_THREAD_lock_free(rand_lock);
    CRYPTO_THREAD_lock_free(rand_tmp_lock);
92
}
93

R
Rich Salz 已提交
94
static int rand_add(const void *buf, int num, double add)
95 96 97
{
    int i, j, k, st_idx;
    long md_c[2];
R
Rich Salz 已提交
98
    unsigned char local_md[SHA_DIGEST_LENGTH];
99
    EVP_MD_CTX *m;
100 101
    int do_not_lock;
    int rv = 0;
R
Rich Salz 已提交
102
    OSSL_RAND_STATE *sp = &global_state;
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

    if (!num)
        return 1;

    /*
     * (Based on the rand(3) manpage)
     *
     * The input is chopped up into units of 20 bytes (or less for
     * the last block).  Each of these blocks is run through the hash
     * function as follows:  The data passed to the hash function
     * is the current 'md', the same number of bytes from the 'state'
     * (the location determined by in incremented looping index) as
     * the current 'block', the new key data 'block', and 'count'
     * (which is incremented after each use).
     * The result of this is kept in 'md' and also xored into the
     * 'state' at the same locations that were used as input into the
     * hash function.
     */

122
    m = EVP_MD_CTX_new();
123 124 125
    if (m == NULL)
        goto err;

R
Rich Salz 已提交
126
    if (!RUN_ONCE(&ossl_rand_init, do_ossl_rand_init))
127
        goto err;
128

129 130
    /* check if we already have the lock */
    if (crypto_lock_rand) {
131 132 133 134
        CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
        CRYPTO_THREAD_read_lock(rand_tmp_lock);
        do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
        CRYPTO_THREAD_unlock(rand_tmp_lock);
135 136 137 138
    } else
        do_not_lock = 0;

    if (!do_not_lock)
139
        CRYPTO_THREAD_write_lock(rand_lock);
R
Rich Salz 已提交
140
    st_idx = sp->index;
141 142 143 144 145 146

    /*
     * use our own copies of the counters so that even if a concurrent thread
     * seeds with exactly the same data and uses the same subarray there's
     * _some_ difference
     */
R
Rich Salz 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159
    md_c[0] = sp->md_count[0];
    md_c[1] = sp->md_count[1];

    memcpy(local_md, sp->md, sizeof(sp->md));

    /* sp->index <= sp->num <= STATE_SIZE */
    sp->index += num;
    if (sp->index >= STATE_SIZE) {
        sp->index %= STATE_SIZE;
        sp->num = STATE_SIZE;
    } else if (sp->num < STATE_SIZE) {
        if (sp->index > sp->num)
            sp->num = sp->index;
160
    }
R
Rich Salz 已提交
161
    /* sp->index <= sp->num <= STATE_SIZE */
162 163 164 165 166 167

    /*
     * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
     * will use now, but other threads may use them as well
     */

R
Rich Salz 已提交
168
    sp->md_count[1] += (num / SHA_DIGEST_LENGTH) + (num % SHA_DIGEST_LENGTH > 0);
169 170

    if (!do_not_lock)
171
        CRYPTO_THREAD_unlock(rand_lock);
172

R
Rich Salz 已提交
173
    for (i = 0; i < num; i += SHA_DIGEST_LENGTH) {
174
        j = (num - i);
R
Rich Salz 已提交
175
        j = (j > SHA_DIGEST_LENGTH) ? SHA_DIGEST_LENGTH : j;
176

R
Rich Salz 已提交
177
        if (!EVP_DigestInit_ex(m, EVP_sha1(), NULL))
178
            goto err;
R
Rich Salz 已提交
179
        if (!EVP_DigestUpdate(m, local_md, SHA_DIGEST_LENGTH))
180 181 182
            goto err;
        k = (st_idx + j) - STATE_SIZE;
        if (k > 0) {
R
Rich Salz 已提交
183
            if (!EVP_DigestUpdate(m, &sp->state[st_idx], j - k))
184
                goto err;
R
Rich Salz 已提交
185
            if (!EVP_DigestUpdate(m, &sp->state[0], k))
186
                goto err;
R
Rich Salz 已提交
187
        } else if (!EVP_DigestUpdate(m, &sp->state[st_idx], j))
188 189
            goto err;

R
Rich Salz 已提交
190 191
        /* DO NOT REMOVE THE FOLLOWING CALL TO EVP_DigestUpdate()! */
        if (!EVP_DigestUpdate(m, buf, j))
192 193 194 195 196 197 198 199 200
            goto err;
        /*
         * We know that line may cause programs such as purify and valgrind
         * to complain about use of uninitialized data.  The problem is not,
         * it's with the caller.  Removing that line will make sure you get
         * really bad randomness and thereby other problems such as very
         * insecure keys.
         */

R
Rich Salz 已提交
201
        if (!EVP_DigestUpdate(m, (unsigned char *)md_c, sizeof(md_c)))
202
            goto err;
R
Rich Salz 已提交
203
        if (!EVP_DigestFinal_ex(m, local_md, NULL))
204 205 206 207 208 209 210 211 212
            goto err;
        md_c[1]++;

        buf = (const char *)buf + j;

        for (k = 0; k < j; k++) {
            /*
             * Parallel threads may interfere with this, but always each byte
             * of the new state is the XOR of some previous value of its and
F
FdaSilvaYY 已提交
213
             * local_md (intermediate values may be lost). Alway using locking
214 215 216 217
             * could hurt performance more than necessary given that
             * conflicts occur only when the total seeding is longer than the
             * random state.
             */
R
Rich Salz 已提交
218
            sp->state[st_idx++] ^= local_md[k];
219 220 221 222 223 224
            if (st_idx >= STATE_SIZE)
                st_idx = 0;
        }
    }

    if (!do_not_lock)
225
        CRYPTO_THREAD_write_lock(rand_lock);
226 227 228
    /*
     * Don't just copy back local_md into md -- this could mean that other
     * thread's seeding remains without effect (except for the incremented
R
Rich Salz 已提交
229
     * counter).  By XORing it we keep at least as much randomness as fits into
230 231
     * md.
     */
R
Rich Salz 已提交
232 233
    for (k = 0; k < (int)sizeof(sp->md); k++) {
        sp->md[k] ^= local_md[k];
234
    }
R
Rich Salz 已提交
235 236
    if (randomness < RANDOMNESS_NEEDED) /* stop counting when we have enough */
        randomness += add;
237
    if (!do_not_lock)
238
        CRYPTO_THREAD_unlock(rand_lock);
239 240 241

    rv = 1;
 err:
242
    EVP_MD_CTX_free(m);
243 244
    return rv;
}
245

R
Rich Salz 已提交
246
static int rand_seed(const void *buf, int num)
247
{
R
Rich Salz 已提交
248
    return rand_add(buf, num, (double)num);
249
}
250

R
Rich Salz 已提交
251
static int rand_bytes(unsigned char *buf, int num)
252 253
{
    static volatile int stirred_pool = 0;
R
Rich Salz 已提交
254 255
    int i, j, k;
    size_t num_ceil, st_idx, st_num;
256 257
    int ok;
    long md_c[2];
R
Rich Salz 已提交
258
    unsigned char local_md[SHA_DIGEST_LENGTH];
259
    EVP_MD_CTX *m;
R
Rich Salz 已提交
260
    OSSL_RAND_STATE *sp = &global_state;
A
Andy Polyakov 已提交
261
#ifndef GETPID_IS_MEANINGLESS
262
    pid_t curr_pid = getpid();
B
Bodo Möller 已提交
263
#endif
264 265
    time_t curr_time = time(NULL);
    int do_stir_pool = 0;
266 267
/* time value for various platforms */
#ifdef OPENSSL_SYS_WIN32
268
    FILETIME tv;
269
# ifdef _WIN32_WCE
270 271 272
    SYSTEMTIME t;
    GetSystemTime(&t);
    SystemTimeToFileTime(&t, &tv);
273
# else
274
    GetSystemTimeAsFileTime(&tv);
275 276
# endif
#elif defined(OPENSSL_SYS_VXWORKS)
277 278
    struct timespec tv;
    clock_gettime(CLOCK_REALTIME, &ts);
279
#elif defined(OPENSSL_SYS_DSPBIOS)
280 281
    unsigned long long tv, OPENSSL_rdtsc();
    tv = OPENSSL_rdtsc();
282
#else
283 284
    struct timeval tv;
    gettimeofday(&tv, NULL);
285
#endif
286

287 288 289
    if (num <= 0)
        return 1;

290
    m = EVP_MD_CTX_new();
291 292 293
    if (m == NULL)
        goto err_mem;

R
Rich Salz 已提交
294
    /* round upwards to multiple of SHA_DIGEST_LENGTH/2 */
295
    num_ceil =
R
Rich Salz 已提交
296
        (1 + (num - 1) / (SHA_DIGEST_LENGTH / 2)) * (SHA_DIGEST_LENGTH / 2);
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315

    /*
     * (Based on the rand(3) manpage:)
     *
     * For each group of 10 bytes (or less), we do the following:
     *
     * Input into the hash function the local 'md' (which is initialized from
     * the global 'md' before any bytes are generated), the bytes that are to
     * be overwritten by the random bytes, and bytes from the 'state'
     * (incrementing looping index). From this digest output (which is kept
     * in 'md'), the top (up to) 10 bytes are returned to the caller and the
     * bottom 10 bytes are xored into the 'state'.
     *
     * Finally, after we have finished 'num' random bytes for the
     * caller, 'count' (which is incremented) and the local and global 'md'
     * are fed into the hash function and the results are kept in the
     * global 'md'.
     */

R
Rich Salz 已提交
316
    if (!RUN_ONCE(&ossl_rand_init, do_ossl_rand_init))
317 318
        goto err_mem;

319
    CRYPTO_THREAD_write_lock(rand_lock);
M
Matt Caswell 已提交
320 321 322 323 324
    /*
     * We could end up in an async engine while holding this lock so ensure
     * we don't pause and cause a deadlock
     */
    ASYNC_block_pause();
325

R
Rich Salz 已提交
326
    /* prevent rand_bytes() from trying to obtain the lock again */
327 328 329
    CRYPTO_THREAD_write_lock(rand_tmp_lock);
    locking_threadid = CRYPTO_THREAD_get_current_id();
    CRYPTO_THREAD_unlock(rand_tmp_lock);
330 331 332 333 334 335 336 337 338 339
    crypto_lock_rand = 1;

    if (!initialized) {
        RAND_poll();
        initialized = 1;
    }

    if (!stirred_pool)
        do_stir_pool = 1;

R
Rich Salz 已提交
340
    ok = (randomness >= RANDOMNESS_NEEDED);
341 342 343 344
    if (!ok) {
        /*
         * If the PRNG state is not yet unpredictable, then seeing the PRNG
         * output may help attackers to determine the new state; thus we have
R
Rich Salz 已提交
345 346
         * to decrease the randomness estimate. Once we've had enough initial
         * seeding we don't bother to adjust the randomness count, though,
347 348
         * because we're not ambitious to provide *information-theoretic*
         * randomness. NOTE: This approach fails if the program forks before
R
Rich Salz 已提交
349 350 351
         * we have enough randomness. Randomness should be collected in a
         * separate input pool and be transferred to the output pool only
         * when the randomness limit has been reached.
352
         */
R
Rich Salz 已提交
353 354 355
        randomness -= num;
        if (randomness < 0)
            randomness = 0;
356 357 358 359 360
    }

    if (do_stir_pool) {
        /*
         * In the output function only half of 'md' remains secret, so we
R
Rich Salz 已提交
361
         * better make sure that the required randomness gets 'evenly
362
         * distributed' through 'state', our randomness pool. The input
R
Rich Salz 已提交
363
         * function (rand_add) chains all of 'md', which makes it more
364 365 366 367 368
         * suitable for this purpose.
         */

        int n = STATE_SIZE;     /* so that the complete pool gets accessed */
        while (n > 0) {
R
Rich Salz 已提交
369
#if SHA_DIGEST_LENGTH > 20
B
Bodo Möller 已提交
370 371
# error "Please adjust DUMMY_SEED."
#endif
R
Rich Salz 已提交
372
#define DUMMY_SEED "...................." /* at least SHA_DIGEST_LENGTH */
373 374
            /*
             * Note that the seed does not matter, it's just that
R
Rich Salz 已提交
375
             * rand_add expects to have something to hash.
376
             */
R
Rich Salz 已提交
377 378
            rand_add(DUMMY_SEED, SHA_DIGEST_LENGTH, 0.0);
            n -= SHA_DIGEST_LENGTH;
379 380 381 382 383
        }
        if (ok)
            stirred_pool = 1;
    }

R
Rich Salz 已提交
384 385 386 387 388
    st_idx = sp->index;
    st_num = sp->num;
    md_c[0] = sp->md_count[0];
    md_c[1] = sp->md_count[1];
    memcpy(local_md, sp->md, sizeof sp->md);
389

R
Rich Salz 已提交
390 391 392
    sp->index += num_ceil;
    if (sp->index > sp->num)
        sp->index %= sp->num;
393 394 395 396 397 398

    /*
     * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
     * ours (but other threads may use them too)
     */

R
Rich Salz 已提交
399
    sp->md_count[0] += 1;
400 401 402

    /* before unlocking, we must clear 'crypto_lock_rand' */
    crypto_lock_rand = 0;
M
Matt Caswell 已提交
403
    ASYNC_unblock_pause();
404
    CRYPTO_THREAD_unlock(rand_lock);
405 406

    while (num > 0) {
R
Rich Salz 已提交
407 408
        /* num_ceil -= SHA_DIGEST_LENGTH / 2 */
        j = (num >= SHA_DIGEST_LENGTH / 2) ? SHA_DIGEST_LENGTH / 2 : num;
409
        num -= j;
R
Rich Salz 已提交
410
        if (!EVP_DigestInit_ex(m, EVP_sha1(), NULL))
411
            goto err;
A
Andy Polyakov 已提交
412
#ifndef GETPID_IS_MEANINGLESS
413
        if (curr_pid) {         /* just in the first iteration to save time */
R
Rich Salz 已提交
414
            if (!EVP_DigestUpdate(m, (unsigned char *)&curr_pid, sizeof curr_pid))
415 416 417
                goto err;
            curr_pid = 0;
        }
418
#endif
419
        if (curr_time) {        /* just in the first iteration to save time */
R
Rich Salz 已提交
420
            if (!EVP_DigestUpdate(m, (unsigned char *)&curr_time, sizeof curr_time))
421
                goto err;
R
Rich Salz 已提交
422
            if (!EVP_DigestUpdate(m, (unsigned char *)&tv, sizeof tv))
423 424
                goto err;
            curr_time = 0;
425 426
            if (!rand_hw_seed(m))
                goto err;
427
        }
R
Rich Salz 已提交
428
        if (!EVP_DigestUpdate(m, local_md, SHA_DIGEST_LENGTH))
429
            goto err;
R
Rich Salz 已提交
430
        if (!EVP_DigestUpdate(m, (unsigned char *)md_c, sizeof(md_c)))
431 432
            goto err;

R
Rich Salz 已提交
433
        k = (st_idx + SHA_DIGEST_LENGTH / 2) - st_num;
434
        if (k > 0) {
R
Rich Salz 已提交
435
            if (!EVP_DigestUpdate(m, &sp->state[st_idx], SHA_DIGEST_LENGTH / 2 - k))
436
                goto err;
R
Rich Salz 已提交
437
            if (!EVP_DigestUpdate(m, &sp->state[0], k))
438
                goto err;
R
Rich Salz 已提交
439
        } else if (!EVP_DigestUpdate(m, &sp->state[st_idx], SHA_DIGEST_LENGTH / 2))
440
            goto err;
R
Rich Salz 已提交
441
        if (!EVP_DigestFinal_ex(m, local_md, NULL))
442 443
            goto err;

R
Rich Salz 已提交
444
        for (i = 0; i < SHA_DIGEST_LENGTH / 2; i++) {
445
            /* may compete with other threads */
R
Rich Salz 已提交
446
            sp->state[st_idx++] ^= local_md[i];
447 448 449
            if (st_idx >= st_num)
                st_idx = 0;
            if (i < j)
R
Rich Salz 已提交
450
                *(buf++) = local_md[i + SHA_DIGEST_LENGTH / 2];
451 452 453
        }
    }

R
Rich Salz 已提交
454
    if (!EVP_DigestInit_ex(m, EVP_sha1(), NULL)
R
Rich Salz 已提交
455
        || !EVP_DigestUpdate(m, (unsigned char *)md_c, sizeof(md_c))
R
Rich Salz 已提交
456
        || !EVP_DigestUpdate(m, local_md, SHA_DIGEST_LENGTH))
457
        goto err;
458
    CRYPTO_THREAD_write_lock(rand_lock);
M
Matt Caswell 已提交
459 460 461 462
    /*
     * Prevent deadlocks if we end up in an async engine
     */
    ASYNC_block_pause();
R
Rich Salz 已提交
463 464
    if (!EVP_DigestUpdate(m, sp->md, sizeof(sp->md))
            || !EVP_DigestFinal_ex(m, sp->md, NULL)) {
465
        ASYNC_unblock_pause();
466
        CRYPTO_THREAD_unlock(rand_lock);
467 468
        goto err;
    }
M
Matt Caswell 已提交
469
    ASYNC_unblock_pause();
470
    CRYPTO_THREAD_unlock(rand_lock);
471

472
    EVP_MD_CTX_free(m);
473 474
    if (ok)
        return (1);
R
Rich Salz 已提交
475 476 477 478
    RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
    ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
                       "https://www.openssl.org/docs/faq.html");
    return (0);
479
 err:
R
Rich Salz 已提交
480
    RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
481
    EVP_MD_CTX_free(m);
482 483 484
    return 0;
 err_mem:
    RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
485
    EVP_MD_CTX_free(m);
486 487 488
    return 0;

}
489

R
Rich Salz 已提交
490
static int rand_status(void)
491
{
492
    CRYPTO_THREAD_ID cur;
493 494 495
    int ret;
    int do_not_lock;

R
Rich Salz 已提交
496
    if (!RUN_ONCE(&ossl_rand_init, do_ossl_rand_init))
497 498
        return 0;

499
    cur = CRYPTO_THREAD_get_current_id();
500 501 502 503 504
    /*
     * check if we already have the lock (could happen if a RAND_poll()
     * implementation calls RAND_status())
     */
    if (crypto_lock_rand) {
505 506 507
        CRYPTO_THREAD_read_lock(rand_tmp_lock);
        do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
        CRYPTO_THREAD_unlock(rand_tmp_lock);
508 509 510 511
    } else
        do_not_lock = 0;

    if (!do_not_lock) {
512
        CRYPTO_THREAD_write_lock(rand_lock);
M
Matt Caswell 已提交
513 514 515 516
        /*
         * Prevent deadlocks in case we end up in an async engine
         */
        ASYNC_block_pause();
517 518

        /*
R
Rich Salz 已提交
519
         * prevent rand_bytes() from trying to obtain the lock again
520
         */
521 522 523
        CRYPTO_THREAD_write_lock(rand_tmp_lock);
        locking_threadid = cur;
        CRYPTO_THREAD_unlock(rand_tmp_lock);
524 525 526 527 528 529 530 531
        crypto_lock_rand = 1;
    }

    if (!initialized) {
        RAND_poll();
        initialized = 1;
    }

R
Rich Salz 已提交
532
    ret = randomness >= RANDOMNESS_NEEDED;
533 534 535 536 537

    if (!do_not_lock) {
        /* before unlocking, we must clear 'crypto_lock_rand' */
        crypto_lock_rand = 0;

M
Matt Caswell 已提交
538
        ASYNC_unblock_pause();
539
        CRYPTO_THREAD_unlock(rand_lock);
540 541 542 543 544 545 546 547
    }

    return ret;
}

/*
 * rand_hw_seed: get seed data from any available hardware RNG. only
 * currently supports rdrand.
548 549 550
 */
#if (defined(__i386)   || defined(__i386__)   || defined(_M_IX86) || \
     defined(__x86_64) || defined(__x86_64__) || \
M
Matt Caswell 已提交
551 552
     defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
     && !defined(OPENSSL_NO_RDRAND)
553

554
# define RDRAND_CALLS    4
555 556 557 558

size_t OPENSSL_ia32_rdrand(void);
extern unsigned int OPENSSL_ia32cap_P[];

559
static int rand_hw_seed(EVP_MD_CTX *ctx)
560 561 562
{
    int i;
    if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
563
        return 1;
564 565 566 567
    for (i = 0; i < RDRAND_CALLS; i++) {
        size_t rnd;
        rnd = OPENSSL_ia32_rdrand();
        if (rnd == 0)
568
            return 1;
R
Rich Salz 已提交
569
        if (!EVP_DigestUpdate(ctx, (unsigned char *)&rnd, sizeof(size_t)))
570
            return 0;
571
    }
572
    return 1;
573
}
574 575 576

#else

577
static int rand_hw_seed(EVP_MD_CTX *ctx)
578
{
579
    return 1;
580
}
581 582

#endif
R
Rich Salz 已提交
583 584 585 586 587 588 589 590 591 592


RAND_METHOD openssl_rand_meth = {
    rand_seed,
    rand_bytes,
    rand_cleanup,
    rand_add,
    rand_bytes,
    rand_status
};