Coverage Report

Created: 2025-07-12 07:07

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