Coverage Report

Created: 2025-07-12 07:07

/src/irssi/subprojects/openssl-1.1.1l/crypto/rand/drbg_lib.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2011-2020 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 <string.h>
11
#include <openssl/crypto.h>
12
#include <openssl/err.h>
13
#include <openssl/rand.h>
14
#include "rand_local.h"
15
#include "internal/thread_once.h"
16
#include "crypto/rand.h"
17
#include "crypto/cryptlib.h"
18
19
/*
20
 * Support framework for NIST SP 800-90A DRBG
21
 *
22
 * See manual page RAND_DRBG(7) for a general overview.
23
 *
24
 * The OpenSSL model is to have new and free functions, and that new
25
 * does all initialization.  That is not the NIST model, which has
26
 * instantiation and un-instantiate, and re-use within a new/free
27
 * lifecycle.  (No doubt this comes from the desire to support hardware
28
 * DRBG, where allocation of resources on something like an HSM is
29
 * a much bigger deal than just re-setting an allocated resource.)
30
 */
31
32
/*
33
 * The three shared DRBG instances
34
 *
35
 * There are three shared DRBG instances: <master>, <public>, and <private>.
36
 */
37
38
/*
39
 * The <master> DRBG
40
 *
41
 * Not used directly by the application, only for reseeding the two other
42
 * DRBGs. It reseeds itself by pulling either randomness from os entropy
43
 * sources or by consuming randomness which was added by RAND_add().
44
 *
45
 * The <master> DRBG is a global instance which is accessed concurrently by
46
 * all threads. The necessary locking is managed automatically by its child
47
 * DRBG instances during reseeding.
48
 */
49
static RAND_DRBG *master_drbg;
50
/*
51
 * The <public> DRBG
52
 *
53
 * Used by default for generating random bytes using RAND_bytes().
54
 *
55
 * The <public> DRBG is thread-local, i.e., there is one instance per thread.
56
 */
57
static CRYPTO_THREAD_LOCAL public_drbg;
58
/*
59
 * The <private> DRBG
60
 *
61
 * Used by default for generating private keys using RAND_priv_bytes()
62
 *
63
 * The <private> DRBG is thread-local, i.e., there is one instance per thread.
64
 */
65
static CRYPTO_THREAD_LOCAL private_drbg;
66
67
68
69
/* NIST SP 800-90A DRBG recommends the use of a personalization string. */
70
static const char ossl_pers_string[] = "OpenSSL NIST SP 800-90A DRBG";
71
72
static CRYPTO_ONCE rand_drbg_init = CRYPTO_ONCE_STATIC_INIT;
73
74
75
76
static int rand_drbg_type = RAND_DRBG_TYPE;
77
static unsigned int rand_drbg_flags = RAND_DRBG_FLAGS;
78
79
static unsigned int master_reseed_interval = MASTER_RESEED_INTERVAL;
80
static unsigned int slave_reseed_interval  = SLAVE_RESEED_INTERVAL;
81
82
static time_t master_reseed_time_interval = MASTER_RESEED_TIME_INTERVAL;
83
static time_t slave_reseed_time_interval  = SLAVE_RESEED_TIME_INTERVAL;
84
85
/* A logical OR of all used DRBG flag bits (currently there is only one) */
86
static const unsigned int rand_drbg_used_flags =
87
    RAND_DRBG_FLAG_CTR_NO_DF;
88
89
static RAND_DRBG *drbg_setup(RAND_DRBG *parent);
90
91
static RAND_DRBG *rand_drbg_new(int secure,
92
                                int type,
93
                                unsigned int flags,
94
                                RAND_DRBG *parent);
95
96
/*
97
 * Set/initialize |drbg| to be of type |type|, with optional |flags|.
98
 *
99
 * If |type| and |flags| are zero, use the defaults
100
 *
101
 * Returns 1 on success, 0 on failure.
102
 */
103
int RAND_DRBG_set(RAND_DRBG *drbg, int type, unsigned int flags)
104
3
{
105
3
    int ret = 1;
106
107
3
    if (type == 0 && flags == 0) {
108
0
        type = rand_drbg_type;
109
0
        flags = rand_drbg_flags;
110
0
    }
111
112
    /* If set is called multiple times - clear the old one */
113
3
    if (drbg->type != 0 && (type != drbg->type || flags != drbg->flags)) {
114
0
        drbg->meth->uninstantiate(drbg);
115
0
        rand_pool_free(drbg->adin_pool);
116
0
        drbg->adin_pool = NULL;
117
0
    }
118
119
3
    drbg->state = DRBG_UNINITIALISED;
120
3
    drbg->flags = flags;
121
3
    drbg->type = type;
122
123
3
    switch (type) {
124
0
    default:
125
0
        drbg->type = 0;
126
0
        drbg->flags = 0;
127
0
        drbg->meth = NULL;
128
0
        RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
129
0
        return 0;
130
0
    case 0:
131
        /* Uninitialized; that's okay. */
132
0
        drbg->meth = NULL;
133
0
        return 1;
134
0
    case NID_aes_128_ctr:
135
0
    case NID_aes_192_ctr:
136
3
    case NID_aes_256_ctr:
137
3
        ret = drbg_ctr_init(drbg);
138
3
        break;
139
3
    }
140
141
3
    if (ret == 0) {
142
0
        drbg->state = DRBG_ERROR;
143
0
        RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG);
144
0
    }
145
3
    return ret;
146
3
}
147
148
/*
149
 * Set/initialize default |type| and |flag| for new drbg instances.
150
 *
151
 * Returns 1 on success, 0 on failure.
152
 */
153
int RAND_DRBG_set_defaults(int type, unsigned int flags)
154
0
{
155
0
    int ret = 1;
156
157
0
    switch (type) {
158
0
    default:
159
0
        RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_TYPE);
160
0
        return 0;
161
0
    case NID_aes_128_ctr:
162
0
    case NID_aes_192_ctr:
163
0
    case NID_aes_256_ctr:
164
0
        break;
165
0
    }
166
167
0
    if ((flags & ~rand_drbg_used_flags) != 0) {
168
0
        RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_FLAGS);
169
0
        return 0;
170
0
    }
171
172
0
    rand_drbg_type  = type;
173
0
    rand_drbg_flags = flags;
174
175
0
    return ret;
176
0
}
177
178
179
/*
180
 * Allocate memory and initialize a new DRBG. The DRBG is allocated on
181
 * the secure heap if |secure| is nonzero and the secure heap is enabled.
182
 * The |parent|, if not NULL, will be used as random source for reseeding.
183
 *
184
 * Returns a pointer to the new DRBG instance on success, NULL on failure.
185
 */
186
static RAND_DRBG *rand_drbg_new(int secure,
187
                                int type,
188
                                unsigned int flags,
189
                                RAND_DRBG *parent)
190
3
{
191
3
    RAND_DRBG *drbg = secure ? OPENSSL_secure_zalloc(sizeof(*drbg))
192
3
                             : OPENSSL_zalloc(sizeof(*drbg));
193
194
3
    if (drbg == NULL) {
195
0
        RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
196
0
        return NULL;
197
0
    }
198
199
3
    drbg->secure = secure && CRYPTO_secure_allocated(drbg);
200
3
    drbg->fork_id = openssl_get_fork_id();
201
3
    drbg->parent = parent;
202
203
3
    if (parent == NULL) {
204
1
        drbg->get_entropy = rand_drbg_get_entropy;
205
1
        drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
206
1
#ifndef RAND_DRBG_GET_RANDOM_NONCE
207
1
        drbg->get_nonce = rand_drbg_get_nonce;
208
1
        drbg->cleanup_nonce = rand_drbg_cleanup_nonce;
209
1
#endif
210
211
1
        drbg->reseed_interval = master_reseed_interval;
212
1
        drbg->reseed_time_interval = master_reseed_time_interval;
213
2
    } else {
214
2
        drbg->get_entropy = rand_drbg_get_entropy;
215
2
        drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
216
        /*
217
         * Do not provide nonce callbacks, the child DRBGs will
218
         * obtain their nonce using random bits from the parent.
219
         */
220
221
2
        drbg->reseed_interval = slave_reseed_interval;
222
2
        drbg->reseed_time_interval = slave_reseed_time_interval;
223
2
    }
224
225
3
    if (RAND_DRBG_set(drbg, type, flags) == 0)
226
0
        goto err;
227
228
3
    if (parent != NULL) {
229
2
        rand_drbg_lock(parent);
230
2
        if (drbg->strength > parent->strength) {
231
            /*
232
             * We currently don't support the algorithm from NIST SP 800-90C
233
             * 10.1.2 to use a weaker DRBG as source
234
             */
235
0
            rand_drbg_unlock(parent);
236
0
            RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK);
237
0
            goto err;
238
0
        }
239
2
        rand_drbg_unlock(parent);
240
2
    }
241
242
3
    return drbg;
243
244
0
 err:
245
0
    RAND_DRBG_free(drbg);
246
247
0
    return NULL;
248
3
}
249
250
RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
251
0
{
252
0
    return rand_drbg_new(0, type, flags, parent);
253
0
}
254
255
RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent)
256
3
{
257
3
    return rand_drbg_new(1, type, flags, parent);
258
3
}
259
260
/*
261
 * Uninstantiate |drbg| and free all memory.
262
 */
263
void RAND_DRBG_free(RAND_DRBG *drbg)
264
3
{
265
3
    if (drbg == NULL)
266
0
        return;
267
268
3
    if (drbg->meth != NULL)
269
3
        drbg->meth->uninstantiate(drbg);
270
3
    rand_pool_free(drbg->adin_pool);
271
3
    CRYPTO_THREAD_lock_free(drbg->lock);
272
3
    CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
273
274
3
    if (drbg->secure)
275
0
        OPENSSL_secure_clear_free(drbg, sizeof(*drbg));
276
3
    else
277
3
        OPENSSL_clear_free(drbg, sizeof(*drbg));
278
3
}
279
280
/*
281
 * Instantiate |drbg|, after it has been initialized.  Use |pers| and
282
 * |perslen| as prediction-resistance input.
283
 *
284
 * Requires that drbg->lock is already locked for write, if non-null.
285
 *
286
 * Returns 1 on success, 0 on failure.
287
 */
288
int RAND_DRBG_instantiate(RAND_DRBG *drbg,
289
                          const unsigned char *pers, size_t perslen)
290
3
{
291
3
    unsigned char *nonce = NULL, *entropy = NULL;
292
3
    size_t noncelen = 0, entropylen = 0;
293
3
    size_t min_entropy = drbg->strength;
294
3
    size_t min_entropylen = drbg->min_entropylen;
295
3
    size_t max_entropylen = drbg->max_entropylen;
296
297
3
    if (perslen > drbg->max_perslen) {
298
0
        RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
299
0
                RAND_R_PERSONALISATION_STRING_TOO_LONG);
300
0
        goto end;
301
0
    }
302
303
3
    if (drbg->meth == NULL) {
304
0
        RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
305
0
                RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
306
0
        goto end;
307
0
    }
308
309
3
    if (drbg->state != DRBG_UNINITIALISED) {
310
0
        RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
311
0
                drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE
312
0
                                          : RAND_R_ALREADY_INSTANTIATED);
313
0
        goto end;
314
0
    }
315
316
3
    drbg->state = DRBG_ERROR;
317
318
    /*
319
     * NIST SP800-90Ar1 section 9.1 says you can combine getting the entropy
320
     * and nonce in 1 call by increasing the entropy with 50% and increasing
321
     * the minimum length to accommodate the length of the nonce.
322
     * We do this in case a nonce is require and get_nonce is NULL.
323
     */
324
3
    if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
325
2
        min_entropy += drbg->strength / 2;
326
2
        min_entropylen += drbg->min_noncelen;
327
2
        max_entropylen += drbg->max_noncelen;
328
2
    }
329
330
3
    if (drbg->get_entropy != NULL)
331
3
        entropylen = drbg->get_entropy(drbg, &entropy, min_entropy,
332
3
                                       min_entropylen, max_entropylen, 0);
333
3
    if (entropylen < min_entropylen
334
3
            || entropylen > max_entropylen) {
335
0
        RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
336
0
        goto end;
337
0
    }
338
339
3
    if (drbg->min_noncelen > 0 && drbg->get_nonce != NULL) {
340
1
        noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
341
1
                                   drbg->min_noncelen, drbg->max_noncelen);
342
1
        if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
343
0
            RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_NONCE);
344
0
            goto end;
345
0
        }
346
1
    }
347
348
3
    if (!drbg->meth->instantiate(drbg, entropy, entropylen,
349
3
                         nonce, noncelen, pers, perslen)) {
350
0
        RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
351
0
        goto end;
352
0
    }
353
354
3
    drbg->state = DRBG_READY;
355
3
    drbg->generate_counter = 1;
356
3
    drbg->reseed_time = time(NULL);
357
3
    if (drbg->enable_reseed_propagation) {
358
3
        if (drbg->parent == NULL)
359
3
            tsan_counter(&drbg->reseed_counter);
360
2
        else
361
3
            tsan_store(&drbg->reseed_counter,
362
3
                       tsan_load(&drbg->parent->reseed_counter));
363
3
    }
364
365
3
 end:
366
3
    if (entropy != NULL && drbg->cleanup_entropy != NULL)
367
3
        drbg->cleanup_entropy(drbg, entropy, entropylen);
368
3
    if (nonce != NULL && drbg->cleanup_nonce != NULL)
369
1
        drbg->cleanup_nonce(drbg, nonce, noncelen);
370
3
    if (drbg->state == DRBG_READY)
371
3
        return 1;
372
0
    return 0;
373
3
}
374
375
/*
376
 * Uninstantiate |drbg|. Must be instantiated before it can be used.
377
 *
378
 * Requires that drbg->lock is already locked for write, if non-null.
379
 *
380
 * Returns 1 on success, 0 on failure.
381
 */
382
int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
383
0
{
384
0
    if (drbg->meth == NULL) {
385
0
        drbg->state = DRBG_ERROR;
386
0
        RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
387
0
                RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
388
0
        return 0;
389
0
    }
390
391
    /* Clear the entire drbg->ctr struct, then reset some important
392
     * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
393
     * initial values.
394
     */
395
0
    drbg->meth->uninstantiate(drbg);
396
0
    return RAND_DRBG_set(drbg, drbg->type, drbg->flags);
397
0
}
398
399
/*
400
 * Reseed |drbg|, mixing in the specified data
401
 *
402
 * Requires that drbg->lock is already locked for write, if non-null.
403
 *
404
 * Returns 1 on success, 0 on failure.
405
 */
406
int RAND_DRBG_reseed(RAND_DRBG *drbg,
407
                     const unsigned char *adin, size_t adinlen,
408
                     int prediction_resistance)
409
9
{
410
9
    unsigned char *entropy = NULL;
411
9
    size_t entropylen = 0;
412
413
9
    if (drbg->state == DRBG_ERROR) {
414
0
        RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
415
0
        return 0;
416
0
    }
417
9
    if (drbg->state == DRBG_UNINITIALISED) {
418
0
        RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
419
0
        return 0;
420
0
    }
421
422
9
    if (adin == NULL) {
423
0
        adinlen = 0;
424
9
    } else if (adinlen > drbg->max_adinlen) {
425
0
        RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
426
0
        return 0;
427
0
    }
428
429
9
    drbg->state = DRBG_ERROR;
430
9
    if (drbg->get_entropy != NULL)
431
9
        entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
432
9
                                       drbg->min_entropylen,
433
9
                                       drbg->max_entropylen,
434
9
                                       prediction_resistance);
435
9
    if (entropylen < drbg->min_entropylen
436
9
            || entropylen > drbg->max_entropylen) {
437
0
        RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
438
0
        goto end;
439
0
    }
440
441
9
    if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
442
0
        goto end;
443
444
9
    drbg->state = DRBG_READY;
445
9
    drbg->generate_counter = 1;
446
9
    drbg->reseed_time = time(NULL);
447
9
    if (drbg->enable_reseed_propagation) {
448
9
        if (drbg->parent == NULL)
449
9
            tsan_counter(&drbg->reseed_counter);
450
9
        else
451
9
            tsan_store(&drbg->reseed_counter,
452
9
                       tsan_load(&drbg->parent->reseed_counter));
453
9
    }
454
455
9
 end:
456
9
    if (entropy != NULL && drbg->cleanup_entropy != NULL)
457
9
        drbg->cleanup_entropy(drbg, entropy, entropylen);
458
9
    if (drbg->state == DRBG_READY)
459
9
        return 1;
460
0
    return 0;
461
9
}
462
463
/*
464
 * Restart |drbg|, using the specified entropy or additional input
465
 *
466
 * Tries its best to get the drbg instantiated by all means,
467
 * regardless of its current state.
468
 *
469
 * Optionally, a |buffer| of |len| random bytes can be passed,
470
 * which is assumed to contain at least |entropy| bits of entropy.
471
 *
472
 * If |entropy| > 0, the buffer content is used as entropy input.
473
 *
474
 * If |entropy| == 0, the buffer content is used as additional input
475
 *
476
 * Returns 1 on success, 0 on failure.
477
 *
478
 * This function is used internally only.
479
 */
480
int rand_drbg_restart(RAND_DRBG *drbg,
481
                      const unsigned char *buffer, size_t len, size_t entropy)
482
0
{
483
0
    int reseeded = 0;
484
0
    const unsigned char *adin = NULL;
485
0
    size_t adinlen = 0;
486
487
0
    if (drbg->seed_pool != NULL) {
488
0
        RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
489
0
        drbg->state = DRBG_ERROR;
490
0
        rand_pool_free(drbg->seed_pool);
491
0
        drbg->seed_pool = NULL;
492
0
        return 0;
493
0
    }
494
495
0
    if (buffer != NULL) {
496
0
        if (entropy > 0) {
497
0
            if (drbg->max_entropylen < len) {
498
0
                RANDerr(RAND_F_RAND_DRBG_RESTART,
499
0
                    RAND_R_ENTROPY_INPUT_TOO_LONG);
500
0
                drbg->state = DRBG_ERROR;
501
0
                return 0;
502
0
            }
503
504
0
            if (entropy > 8 * len) {
505
0
                RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
506
0
                drbg->state = DRBG_ERROR;
507
0
                return 0;
508
0
            }
509
510
            /* will be picked up by the rand_drbg_get_entropy() callback */
511
0
            drbg->seed_pool = rand_pool_attach(buffer, len, entropy);
512
0
            if (drbg->seed_pool == NULL)
513
0
                return 0;
514
0
        } else {
515
0
            if (drbg->max_adinlen < len) {
516
0
                RANDerr(RAND_F_RAND_DRBG_RESTART,
517
0
                        RAND_R_ADDITIONAL_INPUT_TOO_LONG);
518
0
                drbg->state = DRBG_ERROR;
519
0
                return 0;
520
0
            }
521
0
            adin = buffer;
522
0
            adinlen = len;
523
0
        }
524
0
    }
525
526
    /* repair error state */
527
0
    if (drbg->state == DRBG_ERROR)
528
0
        RAND_DRBG_uninstantiate(drbg);
529
530
    /* repair uninitialized state */
531
0
    if (drbg->state == DRBG_UNINITIALISED) {
532
        /* reinstantiate drbg */
533
0
        RAND_DRBG_instantiate(drbg,
534
0
                              (const unsigned char *) ossl_pers_string,
535
0
                              sizeof(ossl_pers_string) - 1);
536
        /* already reseeded. prevent second reseeding below */
537
0
        reseeded = (drbg->state == DRBG_READY);
538
0
    }
539
540
    /* refresh current state if entropy or additional input has been provided */
541
0
    if (drbg->state == DRBG_READY) {
542
0
        if (adin != NULL) {
543
            /*
544
             * mix in additional input without reseeding
545
             *
546
             * Similar to RAND_DRBG_reseed(), but the provided additional
547
             * data |adin| is mixed into the current state without pulling
548
             * entropy from the trusted entropy source using get_entropy().
549
             * This is not a reseeding in the strict sense of NIST SP 800-90A.
550
             */
551
0
            drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
552
0
        } else if (reseeded == 0) {
553
            /* do a full reseeding if it has not been done yet above */
554
0
            if (!RAND_DRBG_reseed(drbg, NULL, 0, 0)) {
555
0
                RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_RESEED_ERROR);
556
0
            }
557
0
        }
558
0
    }
559
560
0
    rand_pool_free(drbg->seed_pool);
561
0
    drbg->seed_pool = NULL;
562
563
0
    return drbg->state == DRBG_READY;
564
0
}
565
566
/*
567
 * Generate |outlen| bytes into the buffer at |out|.  Reseed if we need
568
 * to or if |prediction_resistance| is set.  Additional input can be
569
 * sent in |adin| and |adinlen|.
570
 *
571
 * Requires that drbg->lock is already locked for write, if non-null.
572
 *
573
 * Returns 1 on success, 0 on failure.
574
 *
575
 */
576
int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
577
                       int prediction_resistance,
578
                       const unsigned char *adin, size_t adinlen)
579
472k
{
580
472k
    int fork_id;
581
472k
    int reseed_required = 0;
582
583
472k
    if (drbg->state != DRBG_READY) {
584
        /* try to recover from previous errors */
585
0
        rand_drbg_restart(drbg, NULL, 0, 0);
586
587
0
        if (drbg->state == DRBG_ERROR) {
588
0
            RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
589
0
            return 0;
590
0
        }
591
0
        if (drbg->state == DRBG_UNINITIALISED) {
592
0
            RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
593
0
            return 0;
594
0
        }
595
0
    }
596
597
472k
    if (outlen > drbg->max_request) {
598
0
        RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
599
0
        return 0;
600
0
    }
601
472k
    if (adinlen > drbg->max_adinlen) {
602
0
        RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
603
0
        return 0;
604
0
    }
605
606
472k
    fork_id = openssl_get_fork_id();
607
608
472k
    if (drbg->fork_id != fork_id) {
609
0
        drbg->fork_id = fork_id;
610
0
        reseed_required = 1;
611
0
    }
612
613
472k
    if (drbg->reseed_interval > 0) {
614
472k
        if (drbg->generate_counter >= drbg->reseed_interval)
615
3
            reseed_required = 1;
616
472k
    }
617
472k
    if (drbg->reseed_time_interval > 0) {
618
472k
        time_t now = time(NULL);
619
472k
        if (now < drbg->reseed_time
620
472k
            || now - drbg->reseed_time >= drbg->reseed_time_interval)
621
6
            reseed_required = 1;
622
472k
    }
623
472k
    if (drbg->enable_reseed_propagation && drbg->parent != NULL) {
624
472k
        if (drbg->reseed_counter != tsan_load(&drbg->parent->reseed_counter))
625
0
            reseed_required = 1;
626
472k
    }
627
628
472k
    if (reseed_required || prediction_resistance) {
629
9
        if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
630
0
            RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
631
0
            return 0;
632
0
        }
633
9
        adin = NULL;
634
9
        adinlen = 0;
635
9
    }
636
637
472k
    if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
638
0
        drbg->state = DRBG_ERROR;
639
0
        RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
640
0
        return 0;
641
0
    }
642
643
472k
    drbg->generate_counter++;
644
645
472k
    return 1;
646
472k
}
647
648
/*
649
 * Generates |outlen| random bytes and stores them in |out|. It will
650
 * using the given |drbg| to generate the bytes.
651
 *
652
 * Requires that drbg->lock is already locked for write, if non-null.
653
 *
654
 * Returns 1 on success 0 on failure.
655
 */
656
int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
657
472k
{
658
472k
    unsigned char *additional = NULL;
659
472k
    size_t additional_len;
660
472k
    size_t chunk;
661
472k
    size_t ret = 0;
662
663
472k
    if (drbg->adin_pool == NULL) {
664
2
        if (drbg->type == 0)
665
0
            goto err;
666
2
        drbg->adin_pool = rand_pool_new(0, 0, 0, drbg->max_adinlen);
667
2
        if (drbg->adin_pool == NULL)
668
0
            goto err;
669
2
    }
670
671
472k
    additional_len = rand_drbg_get_additional_data(drbg->adin_pool,
672
472k
                                                   &additional);
673
674
945k
    for ( ; outlen > 0; outlen -= chunk, out += chunk) {
675
472k
        chunk = outlen;
676
472k
        if (chunk > drbg->max_request)
677
0
            chunk = drbg->max_request;
678
472k
        ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
679
472k
        if (!ret)
680
0
            goto err;
681
472k
    }
682
472k
    ret = 1;
683
684
472k
 err:
685
472k
    if (additional != NULL)
686
472k
        rand_drbg_cleanup_additional_data(drbg->adin_pool, additional);
687
688
472k
    return ret;
689
472k
}
690
691
/*
692
 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
693
 *
694
 * Setting the callbacks is allowed only if the drbg has not been
695
 * initialized yet. Otherwise, the operation will fail.
696
 *
697
 * Returns 1 on success, 0 on failure.
698
 */
699
int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
700
                            RAND_DRBG_get_entropy_fn get_entropy,
701
                            RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
702
                            RAND_DRBG_get_nonce_fn get_nonce,
703
                            RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
704
0
{
705
0
    if (drbg->state != DRBG_UNINITIALISED)
706
0
        return 0;
707
0
    drbg->get_entropy = get_entropy;
708
0
    drbg->cleanup_entropy = cleanup_entropy;
709
0
    drbg->get_nonce = get_nonce;
710
0
    drbg->cleanup_nonce = cleanup_nonce;
711
0
    return 1;
712
0
}
713
714
/*
715
 * Set the reseed interval.
716
 *
717
 * The drbg will reseed automatically whenever the number of generate
718
 * requests exceeds the given reseed interval. If the reseed interval
719
 * is 0, then this feature is disabled.
720
 *
721
 * Returns 1 on success, 0 on failure.
722
 */
723
int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
724
0
{
725
0
    if (interval > MAX_RESEED_INTERVAL)
726
0
        return 0;
727
0
    drbg->reseed_interval = interval;
728
0
    return 1;
729
0
}
730
731
/*
732
 * Set the reseed time interval.
733
 *
734
 * The drbg will reseed automatically whenever the time elapsed since
735
 * the last reseeding exceeds the given reseed time interval. For safety,
736
 * a reseeding will also occur if the clock has been reset to a smaller
737
 * value.
738
 *
739
 * Returns 1 on success, 0 on failure.
740
 */
741
int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
742
0
{
743
0
    if (interval > MAX_RESEED_TIME_INTERVAL)
744
0
        return 0;
745
0
    drbg->reseed_time_interval = interval;
746
0
    return 1;
747
0
}
748
749
/*
750
 * Set the default values for reseed (time) intervals of new DRBG instances
751
 *
752
 * The default values can be set independently for master DRBG instances
753
 * (without a parent) and slave DRBG instances (with parent).
754
 *
755
 * Returns 1 on success, 0 on failure.
756
 */
757
758
int RAND_DRBG_set_reseed_defaults(
759
                                  unsigned int _master_reseed_interval,
760
                                  unsigned int _slave_reseed_interval,
761
                                  time_t _master_reseed_time_interval,
762
                                  time_t _slave_reseed_time_interval
763
                                  )
764
0
{
765
0
    if (_master_reseed_interval > MAX_RESEED_INTERVAL
766
0
        || _slave_reseed_interval > MAX_RESEED_INTERVAL)
767
0
        return 0;
768
769
0
    if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
770
0
        || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
771
0
        return 0;
772
773
0
    master_reseed_interval = _master_reseed_interval;
774
0
    slave_reseed_interval = _slave_reseed_interval;
775
776
0
    master_reseed_time_interval = _master_reseed_time_interval;
777
0
    slave_reseed_time_interval = _slave_reseed_time_interval;
778
779
0
    return 1;
780
0
}
781
782
/*
783
 * Locks the given drbg. Locking a drbg which does not have locking
784
 * enabled is considered a successful no-op.
785
 *
786
 * Returns 1 on success, 0 on failure.
787
 */
788
int rand_drbg_lock(RAND_DRBG *drbg)
789
13
{
790
13
    if (drbg->lock != NULL)
791
13
        return CRYPTO_THREAD_write_lock(drbg->lock);
792
793
0
    return 1;
794
13
}
795
796
/*
797
 * Unlocks the given drbg. Unlocking a drbg which does not have locking
798
 * enabled is considered a successful no-op.
799
 *
800
 * Returns 1 on success, 0 on failure.
801
 */
802
int rand_drbg_unlock(RAND_DRBG *drbg)
803
13
{
804
13
    if (drbg->lock != NULL)
805
13
        return CRYPTO_THREAD_unlock(drbg->lock);
806
807
0
    return 1;
808
13
}
809
810
/*
811
 * Enables locking for the given drbg
812
 *
813
 * Locking can only be enabled if the random generator
814
 * is in the uninitialized state.
815
 *
816
 * Returns 1 on success, 0 on failure.
817
 */
818
int rand_drbg_enable_locking(RAND_DRBG *drbg)
819
1
{
820
1
    if (drbg->state != DRBG_UNINITIALISED) {
821
0
        RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
822
0
                RAND_R_DRBG_ALREADY_INITIALIZED);
823
0
        return 0;
824
0
    }
825
826
1
    if (drbg->lock == NULL) {
827
1
        if (drbg->parent != NULL && drbg->parent->lock == NULL) {
828
0
            RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
829
0
                    RAND_R_PARENT_LOCKING_NOT_ENABLED);
830
0
            return 0;
831
0
        }
832
833
1
        drbg->lock = CRYPTO_THREAD_lock_new();
834
1
        if (drbg->lock == NULL) {
835
0
            RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
836
0
                    RAND_R_FAILED_TO_CREATE_LOCK);
837
0
            return 0;
838
0
        }
839
1
    }
840
841
1
    return 1;
842
1
}
843
844
/*
845
 * Get and set the EXDATA
846
 */
847
int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
848
0
{
849
0
    return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
850
0
}
851
852
void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
853
0
{
854
0
    return CRYPTO_get_ex_data(&drbg->ex_data, idx);
855
0
}
856
857
858
/*
859
 * The following functions provide a RAND_METHOD that works on the
860
 * global DRBG.  They lock.
861
 */
862
863
/*
864
 * Allocates a new global DRBG on the secure heap (if enabled) and
865
 * initializes it with default settings.
866
 *
867
 * Returns a pointer to the new DRBG instance on success, NULL on failure.
868
 */
869
static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
870
3
{
871
3
    RAND_DRBG *drbg;
872
873
3
    drbg = RAND_DRBG_secure_new(rand_drbg_type, rand_drbg_flags, parent);
874
3
    if (drbg == NULL)
875
0
        return NULL;
876
877
    /* Only the master DRBG needs to have a lock */
878
3
    if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
879
0
        goto err;
880
881
    /* enable reseed propagation */
882
3
    drbg->enable_reseed_propagation = 1;
883
3
    drbg->reseed_counter = 1;
884
885
    /*
886
     * Ignore instantiation error to support just-in-time instantiation.
887
     *
888
     * The state of the drbg will be checked in RAND_DRBG_generate() and
889
     * an automatic recovery is attempted.
890
     */
891
3
    (void)RAND_DRBG_instantiate(drbg,
892
3
                                (const unsigned char *) ossl_pers_string,
893
3
                                sizeof(ossl_pers_string) - 1);
894
3
    return drbg;
895
896
0
err:
897
0
    RAND_DRBG_free(drbg);
898
0
    return NULL;
899
3
}
900
901
/*
902
 * Initialize the global DRBGs on first use.
903
 * Returns 1 on success, 0 on failure.
904
 */
905
DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
906
1
{
907
    /*
908
     * ensure that libcrypto is initialized, otherwise the
909
     * DRBG locks are not cleaned up properly
910
     */
911
1
    if (!OPENSSL_init_crypto(0, NULL))
912
0
        return 0;
913
914
1
    if (!CRYPTO_THREAD_init_local(&private_drbg, NULL))
915
0
        return 0;
916
917
1
    if (!CRYPTO_THREAD_init_local(&public_drbg, NULL))
918
0
        goto err1;
919
920
1
    master_drbg = drbg_setup(NULL);
921
1
    if (master_drbg == NULL)
922
0
        goto err2;
923
924
1
    return 1;
925
926
0
err2:
927
0
    CRYPTO_THREAD_cleanup_local(&public_drbg);
928
0
err1:
929
0
    CRYPTO_THREAD_cleanup_local(&private_drbg);
930
0
    return 0;
931
0
}
932
933
/* Clean up the global DRBGs before exit */
934
void rand_drbg_cleanup_int(void)
935
2
{
936
2
    if (master_drbg != NULL) {
937
1
        RAND_DRBG_free(master_drbg);
938
1
        master_drbg = NULL;
939
940
1
        CRYPTO_THREAD_cleanup_local(&private_drbg);
941
1
        CRYPTO_THREAD_cleanup_local(&public_drbg);
942
1
    }
943
2
}
944
945
void drbg_delete_thread_state(void)
946
1
{
947
1
    RAND_DRBG *drbg;
948
949
1
    drbg = CRYPTO_THREAD_get_local(&public_drbg);
950
1
    CRYPTO_THREAD_set_local(&public_drbg, NULL);
951
1
    RAND_DRBG_free(drbg);
952
953
1
    drbg = CRYPTO_THREAD_get_local(&private_drbg);
954
1
    CRYPTO_THREAD_set_local(&private_drbg, NULL);
955
1
    RAND_DRBG_free(drbg);
956
1
}
957
958
/* Implements the default OpenSSL RAND_bytes() method */
959
static int drbg_bytes(unsigned char *out, int count)
960
202k
{
961
202k
    int ret;
962
202k
    RAND_DRBG *drbg = RAND_DRBG_get0_public();
963
964
202k
    if (drbg == NULL)
965
0
        return 0;
966
967
202k
    ret = RAND_DRBG_bytes(drbg, out, count);
968
969
202k
    return ret;
970
202k
}
971
972
/*
973
 * Calculates the minimum length of a full entropy buffer
974
 * which is necessary to seed (i.e. instantiate) the DRBG
975
 * successfully.
976
 */
977
size_t rand_drbg_seedlen(RAND_DRBG *drbg)
978
0
{
979
    /*
980
     * If no os entropy source is available then RAND_seed(buffer, bufsize)
981
     * is expected to succeed if and only if the buffer length satisfies
982
     * the following requirements, which follow from the calculations
983
     * in RAND_DRBG_instantiate().
984
     */
985
0
    size_t min_entropy = drbg->strength;
986
0
    size_t min_entropylen = drbg->min_entropylen;
987
988
    /*
989
     * Extra entropy for the random nonce in the absence of a
990
     * get_nonce callback, see comment in RAND_DRBG_instantiate().
991
     */
992
0
    if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
993
0
        min_entropy += drbg->strength / 2;
994
0
        min_entropylen += drbg->min_noncelen;
995
0
    }
996
997
    /*
998
     * Convert entropy requirement from bits to bytes
999
     * (dividing by 8 without rounding upwards, because
1000
     * all entropy requirements are divisible by 8).
1001
     */
1002
0
    min_entropy >>= 3;
1003
1004
    /* Return a value that satisfies both requirements */
1005
0
    return min_entropy > min_entropylen ? min_entropy : min_entropylen;
1006
0
}
1007
1008
/* Implements the default OpenSSL RAND_add() method */
1009
static int drbg_add(const void *buf, int num, double randomness)
1010
0
{
1011
0
    int ret = 0;
1012
0
    RAND_DRBG *drbg = RAND_DRBG_get0_master();
1013
0
    size_t buflen;
1014
0
    size_t seedlen;
1015
1016
0
    if (drbg == NULL)
1017
0
        return 0;
1018
1019
0
    if (num < 0 || randomness < 0.0)
1020
0
        return 0;
1021
1022
0
    rand_drbg_lock(drbg);
1023
0
    seedlen = rand_drbg_seedlen(drbg);
1024
1025
0
    buflen = (size_t)num;
1026
1027
0
    if (buflen < seedlen || randomness < (double) seedlen) {
1028
#if defined(OPENSSL_RAND_SEED_NONE)
1029
        /*
1030
         * If no os entropy source is available, a reseeding will fail
1031
         * inevitably. So we use a trick to mix the buffer contents into
1032
         * the DRBG state without forcing a reseeding: we generate a
1033
         * dummy random byte, using the buffer content as additional data.
1034
         * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
1035
         */
1036
        unsigned char dummy[1];
1037
1038
        ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
1039
        rand_drbg_unlock(drbg);
1040
        return ret;
1041
#else
1042
        /*
1043
         * If an os entropy source is available then we declare the buffer content
1044
         * as additional data by setting randomness to zero and trigger a regular
1045
         * reseeding.
1046
         */
1047
0
        randomness = 0.0;
1048
0
#endif
1049
0
    }
1050
1051
1052
0
    if (randomness > (double)seedlen) {
1053
        /*
1054
         * The purpose of this check is to bound |randomness| by a
1055
         * relatively small value in order to prevent an integer
1056
         * overflow when multiplying by 8 in the rand_drbg_restart()
1057
         * call below. Note that randomness is measured in bytes,
1058
         * not bits, so this value corresponds to eight times the
1059
         * security strength.
1060
         */
1061
0
        randomness = (double)seedlen;
1062
0
    }
1063
1064
0
    ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
1065
0
    rand_drbg_unlock(drbg);
1066
1067
0
    return ret;
1068
0
}
1069
1070
/* Implements the default OpenSSL RAND_seed() method */
1071
static int drbg_seed(const void *buf, int num)
1072
0
{
1073
0
    return drbg_add(buf, num, num);
1074
0
}
1075
1076
/* Implements the default OpenSSL RAND_status() method */
1077
static int drbg_status(void)
1078
0
{
1079
0
    int ret;
1080
0
    RAND_DRBG *drbg = RAND_DRBG_get0_master();
1081
1082
0
    if (drbg == NULL)
1083
0
        return 0;
1084
1085
0
    rand_drbg_lock(drbg);
1086
0
    ret = drbg->state == DRBG_READY ? 1 : 0;
1087
0
    rand_drbg_unlock(drbg);
1088
0
    return ret;
1089
0
}
1090
1091
/*
1092
 * Get the master DRBG.
1093
 * Returns pointer to the DRBG on success, NULL on failure.
1094
 *
1095
 */
1096
RAND_DRBG *RAND_DRBG_get0_master(void)
1097
0
{
1098
0
    if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1099
0
        return NULL;
1100
1101
0
    return master_drbg;
1102
0
}
1103
1104
/*
1105
 * Get the public DRBG.
1106
 * Returns pointer to the DRBG on success, NULL on failure.
1107
 */
1108
RAND_DRBG *RAND_DRBG_get0_public(void)
1109
202k
{
1110
202k
    RAND_DRBG *drbg;
1111
1112
202k
    if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1113
0
        return NULL;
1114
1115
202k
    drbg = CRYPTO_THREAD_get_local(&public_drbg);
1116
202k
    if (drbg == NULL) {
1117
1
        if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1118
0
            return NULL;
1119
1
        drbg = drbg_setup(master_drbg);
1120
1
        CRYPTO_THREAD_set_local(&public_drbg, drbg);
1121
1
    }
1122
202k
    return drbg;
1123
202k
}
1124
1125
/*
1126
 * Get the private DRBG.
1127
 * Returns pointer to the DRBG on success, NULL on failure.
1128
 */
1129
RAND_DRBG *RAND_DRBG_get0_private(void)
1130
270k
{
1131
270k
    RAND_DRBG *drbg;
1132
1133
270k
    if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1134
0
        return NULL;
1135
1136
270k
    drbg = CRYPTO_THREAD_get_local(&private_drbg);
1137
270k
    if (drbg == NULL) {
1138
1
        if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1139
0
            return NULL;
1140
1
        drbg = drbg_setup(master_drbg);
1141
1
        CRYPTO_THREAD_set_local(&private_drbg, drbg);
1142
1
    }
1143
270k
    return drbg;
1144
270k
}
1145
1146
RAND_METHOD rand_meth = {
1147
    drbg_seed,
1148
    drbg_bytes,
1149
    NULL,
1150
    drbg_add,
1151
    drbg_bytes,
1152
    drbg_status
1153
};
1154
1155
RAND_METHOD *RAND_OpenSSL(void)
1156
270k
{
1157
270k
    return &rand_meth;
1158
270k
}