Coverage Report

Created: 2023-06-08 06:40

/src/openssl111/crypto/rand/rand_lib.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the OpenSSL license (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
#include <stdio.h>
11
#include <time.h>
12
#include "internal/cryptlib.h"
13
#include <openssl/opensslconf.h>
14
#include "crypto/rand.h"
15
#include <openssl/engine.h>
16
#include "internal/thread_once.h"
17
#include "rand_local.h"
18
#include "e_os.h"
19
20
#ifndef OPENSSL_NO_ENGINE
21
/* non-NULL if default_RAND_meth is ENGINE-provided */
22
static ENGINE *funct_ref;
23
static CRYPTO_RWLOCK *rand_engine_lock;
24
#endif
25
static CRYPTO_RWLOCK *rand_meth_lock;
26
static const RAND_METHOD *default_RAND_meth;
27
static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
28
29
static CRYPTO_RWLOCK *rand_nonce_lock;
30
static int rand_nonce_count;
31
32
static int rand_inited = 0;
33
34
#ifdef OPENSSL_RAND_SEED_RDTSC
35
/*
36
 * IMPORTANT NOTE:  It is not currently possible to use this code
37
 * because we are not sure about the amount of randomness it provides.
38
 * Some SP900 tests have been run, but there is internal skepticism.
39
 * So for now this code is not used.
40
 */
41
# error "RDTSC enabled?  Should not be possible!"
42
43
/*
44
 * Acquire entropy from high-speed clock
45
 *
46
 * Since we get some randomness from the low-order bits of the
47
 * high-speed clock, it can help.
48
 *
49
 * Returns the total entropy count, if it exceeds the requested
50
 * entropy count. Otherwise, returns an entropy count of 0.
51
 */
52
size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool)
53
{
54
    unsigned char c;
55
    int i;
56
57
    if ((OPENSSL_ia32cap_P[0] & (1 << 4)) != 0) {
58
        for (i = 0; i < TSC_READ_COUNT; i++) {
59
            c = (unsigned char)(OPENSSL_rdtsc() & 0xFF);
60
            rand_pool_add(pool, &c, 1, 4);
61
        }
62
    }
63
    return rand_pool_entropy_available(pool);
64
}
65
#endif
66
67
#ifdef OPENSSL_RAND_SEED_RDCPU
68
size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len);
69
size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len);
70
71
extern unsigned int OPENSSL_ia32cap_P[];
72
73
/*
74
 * Acquire entropy using Intel-specific cpu instructions
75
 *
76
 * Uses the RDSEED instruction if available, otherwise uses
77
 * RDRAND if available.
78
 *
79
 * For the differences between RDSEED and RDRAND, and why RDSEED
80
 * is the preferred choice, see https://goo.gl/oK3KcN
81
 *
82
 * Returns the total entropy count, if it exceeds the requested
83
 * entropy count. Otherwise, returns an entropy count of 0.
84
 */
85
size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool)
86
{
87
    size_t bytes_needed;
88
    unsigned char *buffer;
89
90
    bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
91
    if (bytes_needed > 0) {
92
        buffer = rand_pool_add_begin(pool, bytes_needed);
93
94
        if (buffer != NULL) {
95
            /* Whichever comes first, use RDSEED, RDRAND or nothing */
96
            if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
97
                if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed)
98
                    == bytes_needed) {
99
                    rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
100
                }
101
            } else if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
102
                if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed)
103
                    == bytes_needed) {
104
                    rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
105
                }
106
            } else {
107
                rand_pool_add_end(pool, 0, 0);
108
            }
109
        }
110
    }
111
112
    return rand_pool_entropy_available(pool);
113
}
114
#endif
115
116
117
/*
118
 * Implements the get_entropy() callback (see RAND_DRBG_set_callbacks())
119
 *
120
 * If the DRBG has a parent, then the required amount of entropy input
121
 * is fetched using the parent's RAND_DRBG_generate().
122
 *
123
 * Otherwise, the entropy is polled from the system entropy sources
124
 * using rand_pool_acquire_entropy().
125
 *
126
 * If a random pool has been added to the DRBG using RAND_add(), then
127
 * its entropy will be used up first.
128
 */
129
size_t rand_drbg_get_entropy(RAND_DRBG *drbg,
130
                             unsigned char **pout,
131
                             int entropy, size_t min_len, size_t max_len,
132
                             int prediction_resistance)
133
0
{
134
0
    size_t ret = 0;
135
0
    size_t entropy_available = 0;
136
0
    RAND_POOL *pool;
137
138
0
    if (drbg->parent != NULL && drbg->strength > drbg->parent->strength) {
139
        /*
140
         * We currently don't support the algorithm from NIST SP 800-90C
141
         * 10.1.2 to use a weaker DRBG as source
142
         */
143
0
        RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY, RAND_R_PARENT_STRENGTH_TOO_WEAK);
144
0
        return 0;
145
0
    }
146
147
0
    if (drbg->seed_pool != NULL) {
148
0
        pool = drbg->seed_pool;
149
0
        pool->entropy_requested = entropy;
150
0
    } else {
151
0
        pool = rand_pool_new(entropy, drbg->secure, min_len, max_len);
152
0
        if (pool == NULL)
153
0
            return 0;
154
0
    }
155
156
0
    if (drbg->parent != NULL) {
157
0
        size_t bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
158
0
        unsigned char *buffer = rand_pool_add_begin(pool, bytes_needed);
159
160
0
        if (buffer != NULL) {
161
0
            size_t bytes = 0;
162
163
            /*
164
             * Get random data from parent. Include our address as additional input,
165
             * in order to provide some additional distinction between different
166
             * DRBG child instances.
167
             * Our lock is already held, but we need to lock our parent before
168
             * generating bits from it. (Note: taking the lock will be a no-op
169
             * if locking if drbg->parent->lock == NULL.)
170
             */
171
0
            rand_drbg_lock(drbg->parent);
172
0
            if (RAND_DRBG_generate(drbg->parent,
173
0
                                   buffer, bytes_needed,
174
0
                                   prediction_resistance,
175
0
                                   (unsigned char *)&drbg, sizeof(drbg)) != 0) {
176
0
                bytes = bytes_needed;
177
0
                if (drbg->enable_reseed_propagation)
178
0
                    tsan_store(&drbg->reseed_counter,
179
0
                               tsan_load(&drbg->parent->reseed_counter));
180
0
            }
181
0
            rand_drbg_unlock(drbg->parent);
182
183
0
            rand_pool_add_end(pool, bytes, 8 * bytes);
184
0
            entropy_available = rand_pool_entropy_available(pool);
185
0
        }
186
187
0
    } else {
188
0
        if (prediction_resistance) {
189
            /*
190
             * We don't have any entropy sources that comply with the NIST
191
             * standard to provide prediction resistance (see NIST SP 800-90C,
192
             * Section 5.4).
193
             */
194
0
            RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY,
195
0
                    RAND_R_PREDICTION_RESISTANCE_NOT_SUPPORTED);
196
0
            goto err;
197
0
        }
198
199
        /* Get entropy by polling system entropy sources. */
200
0
        entropy_available = rand_pool_acquire_entropy(pool);
201
0
    }
202
203
0
    if (entropy_available > 0) {
204
0
        ret   = rand_pool_length(pool);
205
0
        *pout = rand_pool_detach(pool);
206
0
    }
207
208
0
 err:
209
0
    if (drbg->seed_pool == NULL)
210
0
        rand_pool_free(pool);
211
0
    return ret;
212
0
}
213
214
/*
215
 * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
216
 *
217
 */
218
void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
219
                               unsigned char *out, size_t outlen)
220
0
{
221
0
    if (drbg->seed_pool == NULL) {
222
0
        if (drbg->secure)
223
0
            OPENSSL_secure_clear_free(out, outlen);
224
0
        else
225
0
            OPENSSL_clear_free(out, outlen);
226
0
    }
227
0
}
228
229
230
/*
231
 * Implements the get_nonce() callback (see RAND_DRBG_set_callbacks())
232
 *
233
 */
234
size_t rand_drbg_get_nonce(RAND_DRBG *drbg,
235
                           unsigned char **pout,
236
                           int entropy, size_t min_len, size_t max_len)
237
0
{
238
0
    size_t ret = 0;
239
0
    RAND_POOL *pool;
240
241
0
    struct {
242
0
        void * instance;
243
0
        int count;
244
0
    } data;
245
246
0
    memset(&data, 0, sizeof(data));
247
0
    pool = rand_pool_new(0, 0, min_len, max_len);
248
0
    if (pool == NULL)
249
0
        return 0;
250
251
0
    if (rand_pool_add_nonce_data(pool) == 0)
252
0
        goto err;
253
254
0
    data.instance = drbg;
255
0
    CRYPTO_atomic_add(&rand_nonce_count, 1, &data.count, rand_nonce_lock);
256
257
0
    if (rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0) == 0)
258
0
        goto err;
259
260
0
    ret   = rand_pool_length(pool);
261
0
    *pout = rand_pool_detach(pool);
262
263
0
 err:
264
0
    rand_pool_free(pool);
265
266
0
    return ret;
267
0
}
268
269
/*
270
 * Implements the cleanup_nonce() callback (see RAND_DRBG_set_callbacks())
271
 *
272
 */
273
void rand_drbg_cleanup_nonce(RAND_DRBG *drbg,
274
                             unsigned char *out, size_t outlen)
275
0
{
276
0
    OPENSSL_clear_free(out, outlen);
277
0
}
278
279
/*
280
 * Generate additional data that can be used for the drbg. The data does
281
 * not need to contain entropy, but it's useful if it contains at least
282
 * some bits that are unpredictable.
283
 *
284
 * Returns 0 on failure.
285
 *
286
 * On success it allocates a buffer at |*pout| and returns the length of
287
 * the data. The buffer should get freed using OPENSSL_secure_clear_free().
288
 */
289
size_t rand_drbg_get_additional_data(RAND_POOL *pool, unsigned char **pout)
290
0
{
291
0
    size_t ret = 0;
292
293
0
    if (rand_pool_add_additional_data(pool) == 0)
294
0
        goto err;
295
296
0
    ret = rand_pool_length(pool);
297
0
    *pout = rand_pool_detach(pool);
298
299
0
 err:
300
0
    return ret;
301
0
}
302
303
void rand_drbg_cleanup_additional_data(RAND_POOL *pool, unsigned char *out)
304
0
{
305
0
    rand_pool_reattach(pool, out);
306
0
}
307
308
DEFINE_RUN_ONCE_STATIC(do_rand_init)
309
0
{
310
0
#ifndef OPENSSL_NO_ENGINE
311
0
    rand_engine_lock = CRYPTO_THREAD_lock_new();
312
0
    if (rand_engine_lock == NULL)
313
0
        return 0;
314
0
#endif
315
316
0
    rand_meth_lock = CRYPTO_THREAD_lock_new();
317
0
    if (rand_meth_lock == NULL)
318
0
        goto err1;
319
320
0
    rand_nonce_lock = CRYPTO_THREAD_lock_new();
321
0
    if (rand_nonce_lock == NULL)
322
0
        goto err2;
323
324
0
    if (!rand_pool_init())
325
0
        goto err3;
326
327
0
    rand_inited = 1;
328
0
    return 1;
329
330
0
err3:
331
0
    CRYPTO_THREAD_lock_free(rand_nonce_lock);
332
0
    rand_nonce_lock = NULL;
333
0
err2:
334
0
    CRYPTO_THREAD_lock_free(rand_meth_lock);
335
0
    rand_meth_lock = NULL;
336
0
err1:
337
0
#ifndef OPENSSL_NO_ENGINE
338
0
    CRYPTO_THREAD_lock_free(rand_engine_lock);
339
0
    rand_engine_lock = NULL;
340
0
#endif
341
0
    return 0;
342
0
}
343
344
void rand_cleanup_int(void)
345
2
{
346
2
    const RAND_METHOD *meth = default_RAND_meth;
347
348
2
    if (!rand_inited)
349
2
        return;
350
351
0
    if (meth != NULL && meth->cleanup != NULL)
352
0
        meth->cleanup();
353
0
    RAND_set_rand_method(NULL);
354
0
    rand_pool_cleanup();
355
0
#ifndef OPENSSL_NO_ENGINE
356
0
    CRYPTO_THREAD_lock_free(rand_engine_lock);
357
0
    rand_engine_lock = NULL;
358
0
#endif
359
0
    CRYPTO_THREAD_lock_free(rand_meth_lock);
360
0
    rand_meth_lock = NULL;
361
0
    CRYPTO_THREAD_lock_free(rand_nonce_lock);
362
0
    rand_nonce_lock = NULL;
363
0
    rand_inited = 0;
364
0
}
365
366
/*
367
 * RAND_close_seed_files() ensures that any seed file descriptors are
368
 * closed after use.
369
 */
370
void RAND_keep_random_devices_open(int keep)
371
0
{
372
0
    if (RUN_ONCE(&rand_init, do_rand_init))
373
0
        rand_pool_keep_random_devices_open(keep);
374
0
}
375
376
/*
377
 * RAND_poll() reseeds the default RNG using random input
378
 *
379
 * The random input is obtained from polling various entropy
380
 * sources which depend on the operating system and are
381
 * configurable via the --with-rand-seed configure option.
382
 */
383
int RAND_poll(void)
384
0
{
385
0
    int ret = 0;
386
387
0
    RAND_POOL *pool = NULL;
388
389
0
    const RAND_METHOD *meth = RAND_get_rand_method();
390
391
0
    if (meth == NULL)
392
0
        return 0;
393
394
0
    if (meth == RAND_OpenSSL()) {
395
        /* fill random pool and seed the master DRBG */
396
0
        RAND_DRBG *drbg = RAND_DRBG_get0_master();
397
398
0
        if (drbg == NULL)
399
0
            return 0;
400
401
0
        rand_drbg_lock(drbg);
402
0
        ret = rand_drbg_restart(drbg, NULL, 0, 0);
403
0
        rand_drbg_unlock(drbg);
404
405
0
        return ret;
406
407
0
    } else {
408
        /* fill random pool and seed the current legacy RNG */
409
0
        pool = rand_pool_new(RAND_DRBG_STRENGTH, 1,
410
0
                             (RAND_DRBG_STRENGTH + 7) / 8,
411
0
                             RAND_POOL_MAX_LENGTH);
412
0
        if (pool == NULL)
413
0
            return 0;
414
415
0
        if (rand_pool_acquire_entropy(pool) == 0)
416
0
            goto err;
417
418
0
        if (meth->add == NULL
419
0
            || meth->add(rand_pool_buffer(pool),
420
0
                         rand_pool_length(pool),
421
0
                         (rand_pool_entropy(pool) / 8.0)) == 0)
422
0
            goto err;
423
424
0
        ret = 1;
425
0
    }
426
427
0
err:
428
0
    rand_pool_free(pool);
429
0
    return ret;
430
0
}
431
432
/*
433
 * Allocate memory and initialize a new random pool
434
 */
435
436
RAND_POOL *rand_pool_new(int entropy_requested, int secure,
437
                         size_t min_len, size_t max_len)
438
0
{
439
0
    RAND_POOL *pool;
440
0
    size_t min_alloc_size = RAND_POOL_MIN_ALLOCATION(secure);
441
442
0
    if (!RUN_ONCE(&rand_init, do_rand_init))
443
0
        return NULL;
444
445
0
    pool = OPENSSL_zalloc(sizeof(*pool));
446
0
    if (pool == NULL) {
447
0
        RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
448
0
        return NULL;
449
0
    }
450
451
0
    pool->min_len = min_len;
452
0
    pool->max_len = (max_len > RAND_POOL_MAX_LENGTH) ?
453
0
        RAND_POOL_MAX_LENGTH : max_len;
454
0
    pool->alloc_len = min_len < min_alloc_size ? min_alloc_size : min_len;
455
0
    if (pool->alloc_len > pool->max_len)
456
0
        pool->alloc_len = pool->max_len;
457
458
0
    if (secure)
459
0
        pool->buffer = OPENSSL_secure_zalloc(pool->alloc_len);
460
0
    else
461
0
        pool->buffer = OPENSSL_zalloc(pool->alloc_len);
462
463
0
    if (pool->buffer == NULL) {
464
0
        RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
465
0
        goto err;
466
0
    }
467
468
0
    pool->entropy_requested = entropy_requested;
469
0
    pool->secure = secure;
470
471
0
    return pool;
472
473
0
err:
474
0
    OPENSSL_free(pool);
475
0
    return NULL;
476
0
}
477
478
/*
479
 * Attach new random pool to the given buffer
480
 *
481
 * This function is intended to be used only for feeding random data
482
 * provided by RAND_add() and RAND_seed() into the <master> DRBG.
483
 */
484
RAND_POOL *rand_pool_attach(const unsigned char *buffer, size_t len,
485
                            size_t entropy)
486
0
{
487
0
    RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
488
489
0
    if (pool == NULL) {
490
0
        RANDerr(RAND_F_RAND_POOL_ATTACH, ERR_R_MALLOC_FAILURE);
491
0
        return NULL;
492
0
    }
493
494
    /*
495
     * The const needs to be cast away, but attached buffers will not be
496
     * modified (in contrary to allocated buffers which are zeroed and
497
     * freed in the end).
498
     */
499
0
    pool->buffer = (unsigned char *) buffer;
500
0
    pool->len = len;
501
502
0
    pool->attached = 1;
503
504
0
    pool->min_len = pool->max_len = pool->alloc_len = pool->len;
505
0
    pool->entropy = entropy;
506
507
0
    return pool;
508
0
}
509
510
/*
511
 * Free |pool|, securely erasing its buffer.
512
 */
513
void rand_pool_free(RAND_POOL *pool)
514
0
{
515
0
    if (pool == NULL)
516
0
        return;
517
518
    /*
519
     * Although it would be advisable from a cryptographical viewpoint,
520
     * we are not allowed to clear attached buffers, since they are passed
521
     * to rand_pool_attach() as `const unsigned char*`.
522
     * (see corresponding comment in rand_pool_attach()).
523
     */
524
0
    if (!pool->attached) {
525
0
        if (pool->secure)
526
0
            OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
527
0
        else
528
0
            OPENSSL_clear_free(pool->buffer, pool->alloc_len);
529
0
    }
530
531
0
    OPENSSL_free(pool);
532
0
}
533
534
/*
535
 * Return the |pool|'s buffer to the caller (readonly).
536
 */
537
const unsigned char *rand_pool_buffer(RAND_POOL *pool)
538
0
{
539
0
    return pool->buffer;
540
0
}
541
542
/*
543
 * Return the |pool|'s entropy to the caller.
544
 */
545
size_t rand_pool_entropy(RAND_POOL *pool)
546
0
{
547
0
    return pool->entropy;
548
0
}
549
550
/*
551
 * Return the |pool|'s buffer length to the caller.
552
 */
553
size_t rand_pool_length(RAND_POOL *pool)
554
0
{
555
0
    return pool->len;
556
0
}
557
558
/*
559
 * Detach the |pool| buffer and return it to the caller.
560
 * It's the responsibility of the caller to free the buffer
561
 * using OPENSSL_secure_clear_free() or to re-attach it
562
 * again to the pool using rand_pool_reattach().
563
 */
564
unsigned char *rand_pool_detach(RAND_POOL *pool)
565
0
{
566
0
    unsigned char *ret = pool->buffer;
567
0
    pool->buffer = NULL;
568
0
    pool->entropy = 0;
569
0
    return ret;
570
0
}
571
572
/*
573
 * Re-attach the |pool| buffer. It is only allowed to pass
574
 * the |buffer| which was previously detached from the same pool.
575
 */
576
void rand_pool_reattach(RAND_POOL *pool, unsigned char *buffer)
577
0
{
578
0
    pool->buffer = buffer;
579
0
    OPENSSL_cleanse(pool->buffer, pool->len);
580
0
    pool->len = 0;
581
0
}
582
583
/*
584
 * If |entropy_factor| bits contain 1 bit of entropy, how many bytes does one
585
 * need to obtain at least |bits| bits of entropy?
586
 */
587
#define ENTROPY_TO_BYTES(bits, entropy_factor) \
588
0
    (((bits) * (entropy_factor) + 7) / 8)
589
590
591
/*
592
 * Checks whether the |pool|'s entropy is available to the caller.
593
 * This is the case when entropy count and buffer length are high enough.
594
 * Returns
595
 *
596
 *  |entropy|  if the entropy count and buffer size is large enough
597
 *      0      otherwise
598
 */
599
size_t rand_pool_entropy_available(RAND_POOL *pool)
600
0
{
601
0
    if (pool->entropy < pool->entropy_requested)
602
0
        return 0;
603
604
0
    if (pool->len < pool->min_len)
605
0
        return 0;
606
607
0
    return pool->entropy;
608
0
}
609
610
/*
611
 * Returns the (remaining) amount of entropy needed to fill
612
 * the random pool.
613
 */
614
615
size_t rand_pool_entropy_needed(RAND_POOL *pool)
616
0
{
617
0
    if (pool->entropy < pool->entropy_requested)
618
0
        return pool->entropy_requested - pool->entropy;
619
620
0
    return 0;
621
0
}
622
623
/* Increase the allocation size -- not usable for an attached pool */
624
static int rand_pool_grow(RAND_POOL *pool, size_t len)
625
0
{
626
0
    if (len > pool->alloc_len - pool->len) {
627
0
        unsigned char *p;
628
0
        const size_t limit = pool->max_len / 2;
629
0
        size_t newlen = pool->alloc_len;
630
631
0
        if (pool->attached || len > pool->max_len - pool->len) {
632
0
            RANDerr(RAND_F_RAND_POOL_GROW, ERR_R_INTERNAL_ERROR);
633
0
            return 0;
634
0
        }
635
636
0
        do
637
0
            newlen = newlen < limit ? newlen * 2 : pool->max_len;
638
0
        while (len > newlen - pool->len);
639
640
0
        if (pool->secure)
641
0
            p = OPENSSL_secure_zalloc(newlen);
642
0
        else
643
0
            p = OPENSSL_zalloc(newlen);
644
0
        if (p == NULL) {
645
0
            RANDerr(RAND_F_RAND_POOL_GROW, ERR_R_MALLOC_FAILURE);
646
0
            return 0;
647
0
        }
648
0
        memcpy(p, pool->buffer, pool->len);
649
0
        if (pool->secure)
650
0
            OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
651
0
        else
652
0
            OPENSSL_clear_free(pool->buffer, pool->alloc_len);
653
0
        pool->buffer = p;
654
0
        pool->alloc_len = newlen;
655
0
    }
656
0
    return 1;
657
0
}
658
659
/*
660
 * Returns the number of bytes needed to fill the pool, assuming
661
 * the input has 1 / |entropy_factor| entropy bits per data bit.
662
 * In case of an error, 0 is returned.
663
 */
664
665
size_t rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor)
666
0
{
667
0
    size_t bytes_needed;
668
0
    size_t entropy_needed = rand_pool_entropy_needed(pool);
669
670
0
    if (entropy_factor < 1) {
671
0
        RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
672
0
        return 0;
673
0
    }
674
675
0
    bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_factor);
676
677
0
    if (bytes_needed > pool->max_len - pool->len) {
678
        /* not enough space left */
679
0
        RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
680
0
        return 0;
681
0
    }
682
683
0
    if (pool->len < pool->min_len &&
684
0
        bytes_needed < pool->min_len - pool->len)
685
        /* to meet the min_len requirement */
686
0
        bytes_needed = pool->min_len - pool->len;
687
688
    /*
689
     * Make sure the buffer is large enough for the requested amount
690
     * of data. This guarantees that existing code patterns where
691
     * rand_pool_add_begin, rand_pool_add_end or rand_pool_add
692
     * are used to collect entropy data without any error handling
693
     * whatsoever, continue to be valid.
694
     * Furthermore if the allocation here fails once, make sure that
695
     * we don't fall back to a less secure or even blocking random source,
696
     * as that could happen by the existing code patterns.
697
     * This is not a concern for additional data, therefore that
698
     * is not needed if rand_pool_grow fails in other places.
699
     */
700
0
    if (!rand_pool_grow(pool, bytes_needed)) {
701
        /* persistent error for this pool */
702
0
        pool->max_len = pool->len = 0;
703
0
        return 0;
704
0
    }
705
706
0
    return bytes_needed;
707
0
}
708
709
/* Returns the remaining number of bytes available */
710
size_t rand_pool_bytes_remaining(RAND_POOL *pool)
711
0
{
712
0
    return pool->max_len - pool->len;
713
0
}
714
715
/*
716
 * Add random bytes to the random pool.
717
 *
718
 * It is expected that the |buffer| contains |len| bytes of
719
 * random input which contains at least |entropy| bits of
720
 * randomness.
721
 *
722
 * Returns 1 if the added amount is adequate, otherwise 0
723
 */
724
int rand_pool_add(RAND_POOL *pool,
725
                  const unsigned char *buffer, size_t len, size_t entropy)
726
0
{
727
0
    if (len > pool->max_len - pool->len) {
728
0
        RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
729
0
        return 0;
730
0
    }
731
732
0
    if (pool->buffer == NULL) {
733
0
        RANDerr(RAND_F_RAND_POOL_ADD, ERR_R_INTERNAL_ERROR);
734
0
        return 0;
735
0
    }
736
737
0
    if (len > 0) {
738
        /*
739
         * This is to protect us from accidentally passing the buffer
740
         * returned from rand_pool_add_begin.
741
         * The check for alloc_len makes sure we do not compare the
742
         * address of the end of the allocated memory to something
743
         * different, since that comparison would have an
744
         * indeterminate result.
745
         */
746
0
        if (pool->alloc_len > pool->len && pool->buffer + pool->len == buffer) {
747
0
            RANDerr(RAND_F_RAND_POOL_ADD, ERR_R_INTERNAL_ERROR);
748
0
            return 0;
749
0
        }
750
        /*
751
         * We have that only for cases when a pool is used to collect
752
         * additional data.
753
         * For entropy data, as long as the allocation request stays within
754
         * the limits given by rand_pool_bytes_needed this rand_pool_grow
755
         * below is guaranteed to succeed, thus no allocation happens.
756
         */
757
0
        if (!rand_pool_grow(pool, len))
758
0
            return 0;
759
0
        memcpy(pool->buffer + pool->len, buffer, len);
760
0
        pool->len += len;
761
0
        pool->entropy += entropy;
762
0
    }
763
764
0
    return 1;
765
0
}
766
767
/*
768
 * Start to add random bytes to the random pool in-place.
769
 *
770
 * Reserves the next |len| bytes for adding random bytes in-place
771
 * and returns a pointer to the buffer.
772
 * The caller is allowed to copy up to |len| bytes into the buffer.
773
 * If |len| == 0 this is considered a no-op and a NULL pointer
774
 * is returned without producing an error message.
775
 *
776
 * After updating the buffer, rand_pool_add_end() needs to be called
777
 * to finish the update operation (see next comment).
778
 */
779
unsigned char *rand_pool_add_begin(RAND_POOL *pool, size_t len)
780
0
{
781
0
    if (len == 0)
782
0
        return NULL;
783
784
0
    if (len > pool->max_len - pool->len) {
785
0
        RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
786
0
        return NULL;
787
0
    }
788
789
0
    if (pool->buffer == NULL) {
790
0
        RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, ERR_R_INTERNAL_ERROR);
791
0
        return NULL;
792
0
    }
793
794
    /*
795
     * As long as the allocation request stays within the limits given
796
     * by rand_pool_bytes_needed this rand_pool_grow below is guaranteed
797
     * to succeed, thus no allocation happens.
798
     * We have that only for cases when a pool is used to collect
799
     * additional data. Then the buffer might need to grow here,
800
     * and of course the caller is responsible to check the return
801
     * value of this function.
802
     */
803
0
    if (!rand_pool_grow(pool, len))
804
0
        return NULL;
805
806
0
    return pool->buffer + pool->len;
807
0
}
808
809
/*
810
 * Finish to add random bytes to the random pool in-place.
811
 *
812
 * Finishes an in-place update of the random pool started by
813
 * rand_pool_add_begin() (see previous comment).
814
 * It is expected that |len| bytes of random input have been added
815
 * to the buffer which contain at least |entropy| bits of randomness.
816
 * It is allowed to add less bytes than originally reserved.
817
 */
818
int rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy)
819
0
{
820
0
    if (len > pool->alloc_len - pool->len) {
821
0
        RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
822
0
        return 0;
823
0
    }
824
825
0
    if (len > 0) {
826
0
        pool->len += len;
827
0
        pool->entropy += entropy;
828
0
    }
829
830
0
    return 1;
831
0
}
832
833
int RAND_set_rand_method(const RAND_METHOD *meth)
834
0
{
835
0
    if (!RUN_ONCE(&rand_init, do_rand_init))
836
0
        return 0;
837
838
0
    CRYPTO_THREAD_write_lock(rand_meth_lock);
839
0
#ifndef OPENSSL_NO_ENGINE
840
0
    ENGINE_finish(funct_ref);
841
0
    funct_ref = NULL;
842
0
#endif
843
0
    default_RAND_meth = meth;
844
0
    CRYPTO_THREAD_unlock(rand_meth_lock);
845
0
    return 1;
846
0
}
847
848
const RAND_METHOD *RAND_get_rand_method(void)
849
0
{
850
0
    const RAND_METHOD *tmp_meth = NULL;
851
852
0
    if (!RUN_ONCE(&rand_init, do_rand_init))
853
0
        return NULL;
854
855
0
    CRYPTO_THREAD_write_lock(rand_meth_lock);
856
0
    if (default_RAND_meth == NULL) {
857
0
#ifndef OPENSSL_NO_ENGINE
858
0
        ENGINE *e;
859
860
        /* If we have an engine that can do RAND, use it. */
861
0
        if ((e = ENGINE_get_default_RAND()) != NULL
862
0
                && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
863
0
            funct_ref = e;
864
0
            default_RAND_meth = tmp_meth;
865
0
        } else {
866
0
            ENGINE_finish(e);
867
0
            default_RAND_meth = &rand_meth;
868
0
        }
869
#else
870
        default_RAND_meth = &rand_meth;
871
#endif
872
0
    }
873
0
    tmp_meth = default_RAND_meth;
874
0
    CRYPTO_THREAD_unlock(rand_meth_lock);
875
0
    return tmp_meth;
876
0
}
877
878
#ifndef OPENSSL_NO_ENGINE
879
int RAND_set_rand_engine(ENGINE *engine)
880
0
{
881
0
    const RAND_METHOD *tmp_meth = NULL;
882
883
0
    if (!RUN_ONCE(&rand_init, do_rand_init))
884
0
        return 0;
885
886
0
    if (engine != NULL) {
887
0
        if (!ENGINE_init(engine))
888
0
            return 0;
889
0
        tmp_meth = ENGINE_get_RAND(engine);
890
0
        if (tmp_meth == NULL) {
891
0
            ENGINE_finish(engine);
892
0
            return 0;
893
0
        }
894
0
    }
895
0
    CRYPTO_THREAD_write_lock(rand_engine_lock);
896
    /* This function releases any prior ENGINE so call it first */
897
0
    RAND_set_rand_method(tmp_meth);
898
0
    funct_ref = engine;
899
0
    CRYPTO_THREAD_unlock(rand_engine_lock);
900
0
    return 1;
901
0
}
902
#endif
903
904
void RAND_seed(const void *buf, int num)
905
0
{
906
0
    const RAND_METHOD *meth = RAND_get_rand_method();
907
908
0
    if (meth != NULL && meth->seed != NULL)
909
0
        meth->seed(buf, num);
910
0
}
911
912
void RAND_add(const void *buf, int num, double randomness)
913
0
{
914
0
    const RAND_METHOD *meth = RAND_get_rand_method();
915
916
0
    if (meth != NULL && meth->add != NULL)
917
0
        meth->add(buf, num, randomness);
918
0
}
919
920
/*
921
 * This function is not part of RAND_METHOD, so if we're not using
922
 * the default method, then just call RAND_bytes().  Otherwise make
923
 * sure we're instantiated and use the private DRBG.
924
 */
925
int RAND_priv_bytes(unsigned char *buf, int num)
926
0
{
927
0
    const RAND_METHOD *meth = RAND_get_rand_method();
928
0
    RAND_DRBG *drbg;
929
930
0
    if (meth != NULL && meth != RAND_OpenSSL())
931
0
        return RAND_bytes(buf, num);
932
933
0
    drbg = RAND_DRBG_get0_private();
934
0
    if (drbg != NULL)
935
0
        return RAND_DRBG_bytes(drbg, buf, num);
936
937
0
    return 0;
938
0
}
939
940
int RAND_bytes(unsigned char *buf, int num)
941
0
{
942
0
    const RAND_METHOD *meth = RAND_get_rand_method();
943
944
0
    if (meth != NULL && meth->bytes != NULL)
945
0
        return meth->bytes(buf, num);
946
0
    RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
947
0
    return -1;
948
0
}
949
950
#if OPENSSL_API_COMPAT < 0x10100000L
951
int RAND_pseudo_bytes(unsigned char *buf, int num)
952
0
{
953
0
    const RAND_METHOD *meth = RAND_get_rand_method();
954
955
0
    if (meth != NULL && meth->pseudorand != NULL)
956
0
        return meth->pseudorand(buf, num);
957
0
    RANDerr(RAND_F_RAND_PSEUDO_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
958
0
    return -1;
959
0
}
960
#endif
961
962
int RAND_status(void)
963
0
{
964
0
    const RAND_METHOD *meth = RAND_get_rand_method();
965
966
0
    if (meth != NULL && meth->status != NULL)
967
0
        return meth->status();
968
0
    return 0;
969
0
}