Coverage Report

Created: 2023-06-08 06:40

/src/openssl111/crypto/rand/drbg_lib.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2011-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 <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
0
{
105
0
    int ret = 1;
106
107
0
    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
0
    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
0
    drbg->state = DRBG_UNINITIALISED;
120
0
    drbg->flags = flags;
121
0
    drbg->type = type;
122
123
0
    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
0
    case NID_aes_256_ctr:
137
0
        ret = drbg_ctr_init(drbg);
138
0
        break;
139
0
    }
140
141
0
    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
0
    return ret;
146
0
}
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
0
{
191
0
    RAND_DRBG *drbg = secure ? OPENSSL_secure_zalloc(sizeof(*drbg))
192
0
                             : OPENSSL_zalloc(sizeof(*drbg));
193
194
0
    if (drbg == NULL) {
195
0
        RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
196
0
        return NULL;
197
0
    }
198
199
0
    drbg->secure = secure && CRYPTO_secure_allocated(drbg);
200
0
    drbg->fork_id = openssl_get_fork_id();
201
0
    drbg->parent = parent;
202
203
0
    if (parent == NULL) {
204
0
        drbg->get_entropy = rand_drbg_get_entropy;
205
0
        drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
206
0
#ifndef RAND_DRBG_GET_RANDOM_NONCE
207
0
        drbg->get_nonce = rand_drbg_get_nonce;
208
0
        drbg->cleanup_nonce = rand_drbg_cleanup_nonce;
209
0
#endif
210
211
0
        drbg->reseed_interval = master_reseed_interval;
212
0
        drbg->reseed_time_interval = master_reseed_time_interval;
213
0
    } else {
214
0
        drbg->get_entropy = rand_drbg_get_entropy;
215
0
        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
0
        drbg->reseed_interval = slave_reseed_interval;
222
0
        drbg->reseed_time_interval = slave_reseed_time_interval;
223
0
    }
224
225
0
    if (RAND_DRBG_set(drbg, type, flags) == 0)
226
0
        goto err;
227
228
0
    if (parent != NULL) {
229
0
        rand_drbg_lock(parent);
230
0
        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
0
        rand_drbg_unlock(parent);
240
0
    }
241
242
0
    return drbg;
243
244
0
 err:
245
0
    RAND_DRBG_free(drbg);
246
247
0
    return NULL;
248
0
}
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
0
{
257
0
    return rand_drbg_new(1, type, flags, parent);
258
0
}
259
260
/*
261
 * Uninstantiate |drbg| and free all memory.
262
 */
263
void RAND_DRBG_free(RAND_DRBG *drbg)
264
0
{
265
0
    if (drbg == NULL)
266
0
        return;
267
268
0
    if (drbg->meth != NULL)
269
0
        drbg->meth->uninstantiate(drbg);
270
0
    rand_pool_free(drbg->adin_pool);
271
0
    CRYPTO_THREAD_lock_free(drbg->lock);
272
0
    CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
273
274
0
    if (drbg->secure)
275
0
        OPENSSL_secure_clear_free(drbg, sizeof(*drbg));
276
0
    else
277
0
        OPENSSL_clear_free(drbg, sizeof(*drbg));
278
0
}
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
0
{
291
0
    unsigned char *nonce = NULL, *entropy = NULL;
292
0
    size_t noncelen = 0, entropylen = 0;
293
0
    size_t min_entropy = drbg->strength;
294
0
    size_t min_entropylen = drbg->min_entropylen;
295
0
    size_t max_entropylen = drbg->max_entropylen;
296
297
0
    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
0
    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
0
    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
0
    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
0
    if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
325
0
        min_entropy += drbg->strength / 2;
326
0
        min_entropylen += drbg->min_noncelen;
327
0
        max_entropylen += drbg->max_noncelen;
328
0
    }
329
330
0
    if (drbg->get_entropy != NULL)
331
0
        entropylen = drbg->get_entropy(drbg, &entropy, min_entropy,
332
0
                                       min_entropylen, max_entropylen, 0);
333
0
    if (entropylen < min_entropylen
334
0
            || entropylen > max_entropylen) {
335
0
        RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
336
0
        goto end;
337
0
    }
338
339
0
    if (drbg->min_noncelen > 0 && drbg->get_nonce != NULL) {
340
0
        noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
341
0
                                   drbg->min_noncelen, drbg->max_noncelen);
342
0
        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
0
    }
347
348
0
    if (!drbg->meth->instantiate(drbg, entropy, entropylen,
349
0
                         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
0
    drbg->state = DRBG_READY;
355
0
    drbg->generate_counter = 1;
356
0
    drbg->reseed_time = time(NULL);
357
0
    if (drbg->enable_reseed_propagation && drbg->parent == NULL)
358
0
        tsan_counter(&drbg->reseed_counter);
359
360
0
 end:
361
0
    if (entropy != NULL && drbg->cleanup_entropy != NULL)
362
0
        drbg->cleanup_entropy(drbg, entropy, entropylen);
363
0
    if (nonce != NULL && drbg->cleanup_nonce != NULL)
364
0
        drbg->cleanup_nonce(drbg, nonce, noncelen);
365
0
    if (drbg->state == DRBG_READY)
366
0
        return 1;
367
0
    return 0;
368
0
}
369
370
/*
371
 * Uninstantiate |drbg|. Must be instantiated before it can be used.
372
 *
373
 * Requires that drbg->lock is already locked for write, if non-null.
374
 *
375
 * Returns 1 on success, 0 on failure.
376
 */
377
int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
378
0
{
379
0
    if (drbg->meth == NULL) {
380
0
        drbg->state = DRBG_ERROR;
381
0
        RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
382
0
                RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
383
0
        return 0;
384
0
    }
385
386
    /* Clear the entire drbg->ctr struct, then reset some important
387
     * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
388
     * initial values.
389
     */
390
0
    drbg->meth->uninstantiate(drbg);
391
0
    return RAND_DRBG_set(drbg, drbg->type, drbg->flags);
392
0
}
393
394
/*
395
 * Reseed |drbg|, mixing in the specified data
396
 *
397
 * Requires that drbg->lock is already locked for write, if non-null.
398
 *
399
 * Returns 1 on success, 0 on failure.
400
 */
401
int RAND_DRBG_reseed(RAND_DRBG *drbg,
402
                     const unsigned char *adin, size_t adinlen,
403
                     int prediction_resistance)
404
0
{
405
0
    unsigned char *entropy = NULL;
406
0
    size_t entropylen = 0;
407
408
0
    if (drbg->state == DRBG_ERROR) {
409
0
        RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
410
0
        return 0;
411
0
    }
412
0
    if (drbg->state == DRBG_UNINITIALISED) {
413
0
        RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
414
0
        return 0;
415
0
    }
416
417
0
    if (adin == NULL) {
418
0
        adinlen = 0;
419
0
    } else if (adinlen > drbg->max_adinlen) {
420
0
        RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
421
0
        return 0;
422
0
    }
423
424
0
    drbg->state = DRBG_ERROR;
425
0
    if (drbg->get_entropy != NULL)
426
0
        entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
427
0
                                       drbg->min_entropylen,
428
0
                                       drbg->max_entropylen,
429
0
                                       prediction_resistance);
430
0
    if (entropylen < drbg->min_entropylen
431
0
            || entropylen > drbg->max_entropylen) {
432
0
        RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
433
0
        goto end;
434
0
    }
435
436
0
    if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
437
0
        goto end;
438
439
0
    drbg->state = DRBG_READY;
440
0
    drbg->generate_counter = 1;
441
0
    drbg->reseed_time = time(NULL);
442
0
    if (drbg->enable_reseed_propagation && drbg->parent == NULL)
443
0
        tsan_counter(&drbg->reseed_counter);
444
445
0
 end:
446
0
    if (entropy != NULL && drbg->cleanup_entropy != NULL)
447
0
        drbg->cleanup_entropy(drbg, entropy, entropylen);
448
0
    if (drbg->state == DRBG_READY)
449
0
        return 1;
450
0
    return 0;
451
0
}
452
453
/*
454
 * Restart |drbg|, using the specified entropy or additional input
455
 *
456
 * Tries its best to get the drbg instantiated by all means,
457
 * regardless of its current state.
458
 *
459
 * Optionally, a |buffer| of |len| random bytes can be passed,
460
 * which is assumed to contain at least |entropy| bits of entropy.
461
 *
462
 * If |entropy| > 0, the buffer content is used as entropy input.
463
 *
464
 * If |entropy| == 0, the buffer content is used as additional input
465
 *
466
 * Returns 1 on success, 0 on failure.
467
 *
468
 * This function is used internally only.
469
 */
470
int rand_drbg_restart(RAND_DRBG *drbg,
471
                      const unsigned char *buffer, size_t len, size_t entropy)
472
0
{
473
0
    int reseeded = 0;
474
0
    const unsigned char *adin = NULL;
475
0
    size_t adinlen = 0;
476
477
0
    if (drbg->seed_pool != NULL) {
478
0
        RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
479
0
        drbg->state = DRBG_ERROR;
480
0
        rand_pool_free(drbg->seed_pool);
481
0
        drbg->seed_pool = NULL;
482
0
        return 0;
483
0
    }
484
485
0
    if (buffer != NULL) {
486
0
        if (entropy > 0) {
487
0
            if (drbg->max_entropylen < len) {
488
0
                RANDerr(RAND_F_RAND_DRBG_RESTART,
489
0
                    RAND_R_ENTROPY_INPUT_TOO_LONG);
490
0
                drbg->state = DRBG_ERROR;
491
0
                return 0;
492
0
            }
493
494
0
            if (entropy > 8 * len) {
495
0
                RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
496
0
                drbg->state = DRBG_ERROR;
497
0
                return 0;
498
0
            }
499
500
            /* will be picked up by the rand_drbg_get_entropy() callback */
501
0
            drbg->seed_pool = rand_pool_attach(buffer, len, entropy);
502
0
            if (drbg->seed_pool == NULL)
503
0
                return 0;
504
0
        } else {
505
0
            if (drbg->max_adinlen < len) {
506
0
                RANDerr(RAND_F_RAND_DRBG_RESTART,
507
0
                        RAND_R_ADDITIONAL_INPUT_TOO_LONG);
508
0
                drbg->state = DRBG_ERROR;
509
0
                return 0;
510
0
            }
511
0
            adin = buffer;
512
0
            adinlen = len;
513
0
        }
514
0
    }
515
516
    /* repair error state */
517
0
    if (drbg->state == DRBG_ERROR)
518
0
        RAND_DRBG_uninstantiate(drbg);
519
520
    /* repair uninitialized state */
521
0
    if (drbg->state == DRBG_UNINITIALISED) {
522
        /* reinstantiate drbg */
523
0
        RAND_DRBG_instantiate(drbg,
524
0
                              (const unsigned char *) ossl_pers_string,
525
0
                              sizeof(ossl_pers_string) - 1);
526
        /* already reseeded. prevent second reseeding below */
527
0
        reseeded = (drbg->state == DRBG_READY);
528
0
    }
529
530
    /* refresh current state if entropy or additional input has been provided */
531
0
    if (drbg->state == DRBG_READY) {
532
0
        if (adin != NULL) {
533
            /*
534
             * mix in additional input without reseeding
535
             *
536
             * Similar to RAND_DRBG_reseed(), but the provided additional
537
             * data |adin| is mixed into the current state without pulling
538
             * entropy from the trusted entropy source using get_entropy().
539
             * This is not a reseeding in the strict sense of NIST SP 800-90A.
540
             */
541
0
            drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
542
0
        } else if (reseeded == 0) {
543
            /* do a full reseeding if it has not been done yet above */
544
0
            if (!RAND_DRBG_reseed(drbg, NULL, 0, 0)) {
545
0
                RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_RESEED_ERROR);
546
0
            }
547
0
        }
548
0
    }
549
550
0
    rand_pool_free(drbg->seed_pool);
551
0
    drbg->seed_pool = NULL;
552
553
0
    return drbg->state == DRBG_READY;
554
0
}
555
556
/*
557
 * Generate |outlen| bytes into the buffer at |out|.  Reseed if we need
558
 * to or if |prediction_resistance| is set.  Additional input can be
559
 * sent in |adin| and |adinlen|.
560
 *
561
 * Requires that drbg->lock is already locked for write, if non-null.
562
 *
563
 * Returns 1 on success, 0 on failure.
564
 *
565
 */
566
int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
567
                       int prediction_resistance,
568
                       const unsigned char *adin, size_t adinlen)
569
0
{
570
0
    int fork_id;
571
0
    int reseed_required = 0;
572
573
0
    if (drbg->state != DRBG_READY) {
574
        /* try to recover from previous errors */
575
0
        rand_drbg_restart(drbg, NULL, 0, 0);
576
577
0
        if (drbg->state == DRBG_ERROR) {
578
0
            RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
579
0
            return 0;
580
0
        }
581
0
        if (drbg->state == DRBG_UNINITIALISED) {
582
0
            RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
583
0
            return 0;
584
0
        }
585
0
    }
586
587
0
    if (outlen > drbg->max_request) {
588
0
        RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
589
0
        return 0;
590
0
    }
591
0
    if (adinlen > drbg->max_adinlen) {
592
0
        RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
593
0
        return 0;
594
0
    }
595
596
0
    fork_id = openssl_get_fork_id();
597
598
0
    if (drbg->fork_id != fork_id) {
599
0
        drbg->fork_id = fork_id;
600
0
        reseed_required = 1;
601
0
    }
602
603
0
    if (drbg->reseed_interval > 0) {
604
0
        if (drbg->generate_counter >= drbg->reseed_interval)
605
0
            reseed_required = 1;
606
0
    }
607
0
    if (drbg->reseed_time_interval > 0) {
608
0
        time_t now = time(NULL);
609
0
        if (now < drbg->reseed_time
610
0
            || now - drbg->reseed_time >= drbg->reseed_time_interval)
611
0
            reseed_required = 1;
612
0
    }
613
0
    if (drbg->enable_reseed_propagation && drbg->parent != NULL) {
614
0
        if (drbg->reseed_counter != tsan_load(&drbg->parent->reseed_counter))
615
0
            reseed_required = 1;
616
0
    }
617
618
0
    if (reseed_required || prediction_resistance) {
619
0
        if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
620
0
            RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
621
0
            return 0;
622
0
        }
623
0
        adin = NULL;
624
0
        adinlen = 0;
625
0
    }
626
627
0
    if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
628
0
        drbg->state = DRBG_ERROR;
629
0
        RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
630
0
        return 0;
631
0
    }
632
633
0
    drbg->generate_counter++;
634
635
0
    return 1;
636
0
}
637
638
/*
639
 * Generates |outlen| random bytes and stores them in |out|. It will
640
 * using the given |drbg| to generate the bytes.
641
 *
642
 * Requires that drbg->lock is already locked for write, if non-null.
643
 *
644
 * Returns 1 on success 0 on failure.
645
 */
646
int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
647
0
{
648
0
    unsigned char *additional = NULL;
649
0
    size_t additional_len;
650
0
    size_t chunk;
651
0
    size_t ret = 0;
652
653
0
    if (drbg->adin_pool == NULL) {
654
0
        if (drbg->type == 0)
655
0
            goto err;
656
0
        drbg->adin_pool = rand_pool_new(0, 0, 0, drbg->max_adinlen);
657
0
        if (drbg->adin_pool == NULL)
658
0
            goto err;
659
0
    }
660
661
0
    additional_len = rand_drbg_get_additional_data(drbg->adin_pool,
662
0
                                                   &additional);
663
664
0
    for ( ; outlen > 0; outlen -= chunk, out += chunk) {
665
0
        chunk = outlen;
666
0
        if (chunk > drbg->max_request)
667
0
            chunk = drbg->max_request;
668
0
        ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
669
0
        if (!ret)
670
0
            goto err;
671
0
    }
672
0
    ret = 1;
673
674
0
 err:
675
0
    if (additional != NULL)
676
0
        rand_drbg_cleanup_additional_data(drbg->adin_pool, additional);
677
678
0
    return ret;
679
0
}
680
681
/*
682
 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
683
 *
684
 * Setting the callbacks is allowed only if the drbg has not been
685
 * initialized yet. Otherwise, the operation will fail.
686
 *
687
 * Returns 1 on success, 0 on failure.
688
 */
689
int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
690
                            RAND_DRBG_get_entropy_fn get_entropy,
691
                            RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
692
                            RAND_DRBG_get_nonce_fn get_nonce,
693
                            RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
694
0
{
695
0
    if (drbg->state != DRBG_UNINITIALISED)
696
0
        return 0;
697
0
    drbg->get_entropy = get_entropy;
698
0
    drbg->cleanup_entropy = cleanup_entropy;
699
0
    drbg->get_nonce = get_nonce;
700
0
    drbg->cleanup_nonce = cleanup_nonce;
701
0
    return 1;
702
0
}
703
704
/*
705
 * Set the reseed interval.
706
 *
707
 * The drbg will reseed automatically whenever the number of generate
708
 * requests exceeds the given reseed interval. If the reseed interval
709
 * is 0, then this feature is disabled.
710
 *
711
 * Returns 1 on success, 0 on failure.
712
 */
713
int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
714
0
{
715
0
    if (interval > MAX_RESEED_INTERVAL)
716
0
        return 0;
717
0
    drbg->reseed_interval = interval;
718
0
    return 1;
719
0
}
720
721
/*
722
 * Set the reseed time interval.
723
 *
724
 * The drbg will reseed automatically whenever the time elapsed since
725
 * the last reseeding exceeds the given reseed time interval. For safety,
726
 * a reseeding will also occur if the clock has been reset to a smaller
727
 * value.
728
 *
729
 * Returns 1 on success, 0 on failure.
730
 */
731
int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
732
0
{
733
0
    if (interval > MAX_RESEED_TIME_INTERVAL)
734
0
        return 0;
735
0
    drbg->reseed_time_interval = interval;
736
0
    return 1;
737
0
}
738
739
/*
740
 * Set the default values for reseed (time) intervals of new DRBG instances
741
 *
742
 * The default values can be set independently for master DRBG instances
743
 * (without a parent) and slave DRBG instances (with parent).
744
 *
745
 * Returns 1 on success, 0 on failure.
746
 */
747
748
int RAND_DRBG_set_reseed_defaults(
749
                                  unsigned int _master_reseed_interval,
750
                                  unsigned int _slave_reseed_interval,
751
                                  time_t _master_reseed_time_interval,
752
                                  time_t _slave_reseed_time_interval
753
                                  )
754
0
{
755
0
    if (_master_reseed_interval > MAX_RESEED_INTERVAL
756
0
        || _slave_reseed_interval > MAX_RESEED_INTERVAL)
757
0
        return 0;
758
759
0
    if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
760
0
        || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
761
0
        return 0;
762
763
0
    master_reseed_interval = _master_reseed_interval;
764
0
    slave_reseed_interval = _slave_reseed_interval;
765
766
0
    master_reseed_time_interval = _master_reseed_time_interval;
767
0
    slave_reseed_time_interval = _slave_reseed_time_interval;
768
769
0
    return 1;
770
0
}
771
772
/*
773
 * Locks the given drbg. Locking a drbg which does not have locking
774
 * enabled is considered a successful no-op.
775
 *
776
 * Returns 1 on success, 0 on failure.
777
 */
778
int rand_drbg_lock(RAND_DRBG *drbg)
779
0
{
780
0
    if (drbg->lock != NULL)
781
0
        return CRYPTO_THREAD_write_lock(drbg->lock);
782
783
0
    return 1;
784
0
}
785
786
/*
787
 * Unlocks the given drbg. Unlocking a drbg which does not have locking
788
 * enabled is considered a successful no-op.
789
 *
790
 * Returns 1 on success, 0 on failure.
791
 */
792
int rand_drbg_unlock(RAND_DRBG *drbg)
793
0
{
794
0
    if (drbg->lock != NULL)
795
0
        return CRYPTO_THREAD_unlock(drbg->lock);
796
797
0
    return 1;
798
0
}
799
800
/*
801
 * Enables locking for the given drbg
802
 *
803
 * Locking can only be enabled if the random generator
804
 * is in the uninitialized state.
805
 *
806
 * Returns 1 on success, 0 on failure.
807
 */
808
int rand_drbg_enable_locking(RAND_DRBG *drbg)
809
0
{
810
0
    if (drbg->state != DRBG_UNINITIALISED) {
811
0
        RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
812
0
                RAND_R_DRBG_ALREADY_INITIALIZED);
813
0
        return 0;
814
0
    }
815
816
0
    if (drbg->lock == NULL) {
817
0
        if (drbg->parent != NULL && drbg->parent->lock == NULL) {
818
0
            RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
819
0
                    RAND_R_PARENT_LOCKING_NOT_ENABLED);
820
0
            return 0;
821
0
        }
822
823
0
        drbg->lock = CRYPTO_THREAD_lock_new();
824
0
        if (drbg->lock == NULL) {
825
0
            RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
826
0
                    RAND_R_FAILED_TO_CREATE_LOCK);
827
0
            return 0;
828
0
        }
829
0
    }
830
831
0
    return 1;
832
0
}
833
834
/*
835
 * Get and set the EXDATA
836
 */
837
int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
838
0
{
839
0
    return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
840
0
}
841
842
void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
843
0
{
844
0
    return CRYPTO_get_ex_data(&drbg->ex_data, idx);
845
0
}
846
847
848
/*
849
 * The following functions provide a RAND_METHOD that works on the
850
 * global DRBG.  They lock.
851
 */
852
853
/*
854
 * Allocates a new global DRBG on the secure heap (if enabled) and
855
 * initializes it with default settings.
856
 *
857
 * Returns a pointer to the new DRBG instance on success, NULL on failure.
858
 */
859
static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
860
0
{
861
0
    RAND_DRBG *drbg;
862
863
0
    drbg = RAND_DRBG_secure_new(rand_drbg_type, rand_drbg_flags, parent);
864
0
    if (drbg == NULL)
865
0
        return NULL;
866
867
    /* Only the master DRBG needs to have a lock */
868
0
    if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
869
0
        goto err;
870
871
    /* enable reseed propagation */
872
0
    drbg->enable_reseed_propagation = 1;
873
0
    drbg->reseed_counter = 1;
874
875
    /*
876
     * Ignore instantiation error to support just-in-time instantiation.
877
     *
878
     * The state of the drbg will be checked in RAND_DRBG_generate() and
879
     * an automatic recovery is attempted.
880
     */
881
0
    (void)RAND_DRBG_instantiate(drbg,
882
0
                                (const unsigned char *) ossl_pers_string,
883
0
                                sizeof(ossl_pers_string) - 1);
884
0
    return drbg;
885
886
0
err:
887
0
    RAND_DRBG_free(drbg);
888
0
    return NULL;
889
0
}
890
891
/*
892
 * Initialize the global DRBGs on first use.
893
 * Returns 1 on success, 0 on failure.
894
 */
895
DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
896
0
{
897
    /*
898
     * ensure that libcrypto is initialized, otherwise the
899
     * DRBG locks are not cleaned up properly
900
     */
901
0
    if (!OPENSSL_init_crypto(0, NULL))
902
0
        return 0;
903
904
0
    if (!CRYPTO_THREAD_init_local(&private_drbg, NULL))
905
0
        return 0;
906
907
0
    if (!CRYPTO_THREAD_init_local(&public_drbg, NULL))
908
0
        goto err1;
909
910
0
    master_drbg = drbg_setup(NULL);
911
0
    if (master_drbg == NULL)
912
0
        goto err2;
913
914
0
    return 1;
915
916
0
err2:
917
0
    CRYPTO_THREAD_cleanup_local(&public_drbg);
918
0
err1:
919
0
    CRYPTO_THREAD_cleanup_local(&private_drbg);
920
0
    return 0;
921
0
}
922
923
/* Clean up the global DRBGs before exit */
924
void rand_drbg_cleanup_int(void)
925
2
{
926
2
    if (master_drbg != NULL) {
927
0
        RAND_DRBG_free(master_drbg);
928
0
        master_drbg = NULL;
929
930
0
        CRYPTO_THREAD_cleanup_local(&private_drbg);
931
0
        CRYPTO_THREAD_cleanup_local(&public_drbg);
932
0
    }
933
2
}
934
935
void drbg_delete_thread_state(void)
936
0
{
937
0
    RAND_DRBG *drbg;
938
939
0
    drbg = CRYPTO_THREAD_get_local(&public_drbg);
940
0
    CRYPTO_THREAD_set_local(&public_drbg, NULL);
941
0
    RAND_DRBG_free(drbg);
942
943
0
    drbg = CRYPTO_THREAD_get_local(&private_drbg);
944
0
    CRYPTO_THREAD_set_local(&private_drbg, NULL);
945
0
    RAND_DRBG_free(drbg);
946
0
}
947
948
/* Implements the default OpenSSL RAND_bytes() method */
949
static int drbg_bytes(unsigned char *out, int count)
950
0
{
951
0
    int ret;
952
0
    RAND_DRBG *drbg = RAND_DRBG_get0_public();
953
954
0
    if (drbg == NULL)
955
0
        return 0;
956
957
0
    ret = RAND_DRBG_bytes(drbg, out, count);
958
959
0
    return ret;
960
0
}
961
962
/*
963
 * Calculates the minimum length of a full entropy buffer
964
 * which is necessary to seed (i.e. instantiate) the DRBG
965
 * successfully.
966
 */
967
size_t rand_drbg_seedlen(RAND_DRBG *drbg)
968
0
{
969
    /*
970
     * If no os entropy source is available then RAND_seed(buffer, bufsize)
971
     * is expected to succeed if and only if the buffer length satisfies
972
     * the following requirements, which follow from the calculations
973
     * in RAND_DRBG_instantiate().
974
     */
975
0
    size_t min_entropy = drbg->strength;
976
0
    size_t min_entropylen = drbg->min_entropylen;
977
978
    /*
979
     * Extra entropy for the random nonce in the absence of a
980
     * get_nonce callback, see comment in RAND_DRBG_instantiate().
981
     */
982
0
    if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
983
0
        min_entropy += drbg->strength / 2;
984
0
        min_entropylen += drbg->min_noncelen;
985
0
    }
986
987
    /*
988
     * Convert entropy requirement from bits to bytes
989
     * (dividing by 8 without rounding upwards, because
990
     * all entropy requirements are divisible by 8).
991
     */
992
0
    min_entropy >>= 3;
993
994
    /* Return a value that satisfies both requirements */
995
0
    return min_entropy > min_entropylen ? min_entropy : min_entropylen;
996
0
}
997
998
/* Implements the default OpenSSL RAND_add() method */
999
static int drbg_add(const void *buf, int num, double randomness)
1000
0
{
1001
0
    int ret = 0;
1002
0
    RAND_DRBG *drbg = RAND_DRBG_get0_master();
1003
0
    size_t buflen;
1004
0
    size_t seedlen;
1005
1006
0
    if (drbg == NULL)
1007
0
        return 0;
1008
1009
0
    if (num < 0 || randomness < 0.0)
1010
0
        return 0;
1011
1012
0
    rand_drbg_lock(drbg);
1013
0
    seedlen = rand_drbg_seedlen(drbg);
1014
1015
0
    buflen = (size_t)num;
1016
1017
0
    if (buflen < seedlen || randomness < (double) seedlen) {
1018
#if defined(OPENSSL_RAND_SEED_NONE)
1019
        /*
1020
         * If no os entropy source is available, a reseeding will fail
1021
         * inevitably. So we use a trick to mix the buffer contents into
1022
         * the DRBG state without forcing a reseeding: we generate a
1023
         * dummy random byte, using the buffer content as additional data.
1024
         * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
1025
         */
1026
        unsigned char dummy[1];
1027
1028
        ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
1029
        rand_drbg_unlock(drbg);
1030
        return ret;
1031
#else
1032
        /*
1033
         * If an os entropy source is available then we declare the buffer content
1034
         * as additional data by setting randomness to zero and trigger a regular
1035
         * reseeding.
1036
         */
1037
0
        randomness = 0.0;
1038
0
#endif
1039
0
    }
1040
1041
1042
0
    if (randomness > (double)seedlen) {
1043
        /*
1044
         * The purpose of this check is to bound |randomness| by a
1045
         * relatively small value in order to prevent an integer
1046
         * overflow when multiplying by 8 in the rand_drbg_restart()
1047
         * call below. Note that randomness is measured in bytes,
1048
         * not bits, so this value corresponds to eight times the
1049
         * security strength.
1050
         */
1051
0
        randomness = (double)seedlen;
1052
0
    }
1053
1054
0
    ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
1055
0
    rand_drbg_unlock(drbg);
1056
1057
0
    return ret;
1058
0
}
1059
1060
/* Implements the default OpenSSL RAND_seed() method */
1061
static int drbg_seed(const void *buf, int num)
1062
0
{
1063
0
    return drbg_add(buf, num, num);
1064
0
}
1065
1066
/* Implements the default OpenSSL RAND_status() method */
1067
static int drbg_status(void)
1068
0
{
1069
0
    int ret;
1070
0
    RAND_DRBG *drbg = RAND_DRBG_get0_master();
1071
1072
0
    if (drbg == NULL)
1073
0
        return 0;
1074
1075
0
    rand_drbg_lock(drbg);
1076
0
    ret = drbg->state == DRBG_READY ? 1 : 0;
1077
0
    rand_drbg_unlock(drbg);
1078
0
    return ret;
1079
0
}
1080
1081
/*
1082
 * Get the master DRBG.
1083
 * Returns pointer to the DRBG on success, NULL on failure.
1084
 *
1085
 */
1086
RAND_DRBG *RAND_DRBG_get0_master(void)
1087
0
{
1088
0
    if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1089
0
        return NULL;
1090
1091
0
    return master_drbg;
1092
0
}
1093
1094
/*
1095
 * Get the public DRBG.
1096
 * Returns pointer to the DRBG on success, NULL on failure.
1097
 */
1098
RAND_DRBG *RAND_DRBG_get0_public(void)
1099
0
{
1100
0
    RAND_DRBG *drbg;
1101
1102
0
    if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1103
0
        return NULL;
1104
1105
0
    drbg = CRYPTO_THREAD_get_local(&public_drbg);
1106
0
    if (drbg == NULL) {
1107
0
        if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1108
0
            return NULL;
1109
0
        drbg = drbg_setup(master_drbg);
1110
0
        CRYPTO_THREAD_set_local(&public_drbg, drbg);
1111
0
    }
1112
0
    return drbg;
1113
0
}
1114
1115
/*
1116
 * Get the private DRBG.
1117
 * Returns pointer to the DRBG on success, NULL on failure.
1118
 */
1119
RAND_DRBG *RAND_DRBG_get0_private(void)
1120
0
{
1121
0
    RAND_DRBG *drbg;
1122
1123
0
    if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1124
0
        return NULL;
1125
1126
0
    drbg = CRYPTO_THREAD_get_local(&private_drbg);
1127
0
    if (drbg == NULL) {
1128
0
        if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1129
0
            return NULL;
1130
0
        drbg = drbg_setup(master_drbg);
1131
0
        CRYPTO_THREAD_set_local(&private_drbg, drbg);
1132
0
    }
1133
0
    return drbg;
1134
0
}
1135
1136
RAND_METHOD rand_meth = {
1137
    drbg_seed,
1138
    drbg_bytes,
1139
    NULL,
1140
    drbg_add,
1141
    drbg_bytes,
1142
    drbg_status
1143
};
1144
1145
RAND_METHOD *RAND_OpenSSL(void)
1146
0
{
1147
0
    return &rand_meth;
1148
0
}