Coverage Report

Created: 2026-04-01 06:39

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl33/providers/implementations/rands/drbg.c
Line
Count
Source
1
/*
2
 * Copyright 2011-2024 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (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 <openssl/evp.h>
15
#include "crypto/rand.h"
16
#include <openssl/proverr.h>
17
#include "drbg_local.h"
18
#include "internal/thread_once.h"
19
#include "crypto/cryptlib.h"
20
#include "prov/seeding.h"
21
#include "crypto/rand_pool.h"
22
#include "prov/provider_ctx.h"
23
#include "prov/providercommon.h"
24
#include "prov/fipscommon.h"
25
#include "crypto/context.h"
26
27
/*
28
 * Support framework for NIST SP 800-90A DRBG
29
 *
30
 * See manual page PROV_DRBG(7) for a general overview.
31
 *
32
 * The OpenSSL model is to have new and free functions, and that new
33
 * does all initialization.  That is not the NIST model, which has
34
 * instantiation and un-instantiate, and re-use within a new/free
35
 * lifecycle.  (No doubt this comes from the desire to support hardware
36
 * DRBG, where allocation of resources on something like an HSM is
37
 * a much bigger deal than just re-setting an allocated resource.)
38
 */
39
40
/* NIST SP 800-90A DRBG recommends the use of a personalization string. */
41
static const char ossl_pers_string[] = DRBG_DEFAULT_PERS_STRING;
42
43
static const OSSL_DISPATCH *find_call(const OSSL_DISPATCH *dispatch,
44
    int function);
45
46
static int rand_drbg_restart(PROV_DRBG *drbg);
47
48
/*
49
 * We interpret a call to this function as a hint only and ignore it. This
50
 * occurs when the EVP layer thinks we should do some locking. In practice
51
 * however we manage for ourselves when we take a lock or not on the basis
52
 * of whether drbg->lock is present or not.
53
 */
54
int ossl_drbg_lock(void *vctx)
55
301k
{
56
301k
    return 1;
57
301k
}
58
59
/* Interpreted as a hint only and ignored as for ossl_drbg_lock() */
60
void ossl_drbg_unlock(void *vctx)
61
301k
{
62
301k
}
63
64
static int ossl_drbg_lock_parent(PROV_DRBG *drbg)
65
163k
{
66
163k
    void *parent = drbg->parent;
67
68
163k
    if (parent != NULL
69
163k
        && drbg->parent_lock != NULL
70
163k
        && !drbg->parent_lock(parent)) {
71
0
        ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
72
0
        return 0;
73
0
    }
74
163k
    return 1;
75
163k
}
76
77
static void ossl_drbg_unlock_parent(PROV_DRBG *drbg)
78
163k
{
79
163k
    void *parent = drbg->parent;
80
81
163k
    if (parent != NULL && drbg->parent_unlock != NULL)
82
163k
        drbg->parent_unlock(parent);
83
163k
}
84
85
static int get_parent_strength(PROV_DRBG *drbg, unsigned int *str)
86
117
{
87
117
    OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
88
117
    void *parent = drbg->parent;
89
117
    int res;
90
91
117
    if (drbg->parent_get_ctx_params == NULL) {
92
0
        ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_GET_PARENT_STRENGTH);
93
0
        return 0;
94
0
    }
95
96
117
    *params = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, str);
97
117
    if (!ossl_drbg_lock_parent(drbg)) {
98
0
        ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_LOCK_PARENT);
99
0
        return 0;
100
0
    }
101
117
    res = drbg->parent_get_ctx_params(parent, params);
102
117
    ossl_drbg_unlock_parent(drbg);
103
117
    if (!res) {
104
0
        ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_GET_PARENT_STRENGTH);
105
0
        return 0;
106
0
    }
107
117
    return 1;
108
117
}
109
110
static unsigned int get_parent_reseed_count(PROV_DRBG *drbg)
111
163k
{
112
163k
    OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
113
163k
    void *parent = drbg->parent;
114
163k
    unsigned int r = 0;
115
116
163k
    *params = OSSL_PARAM_construct_uint(OSSL_DRBG_PARAM_RESEED_COUNTER, &r);
117
163k
    if (!ossl_drbg_lock_parent(drbg)) {
118
0
        ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_LOCK_PARENT);
119
0
        goto err;
120
0
    }
121
163k
    if (!drbg->parent_get_ctx_params(parent, params))
122
0
        r = 0;
123
163k
    ossl_drbg_unlock_parent(drbg);
124
163k
    return r;
125
126
0
err:
127
0
    r = tsan_load(&drbg->reseed_counter) - 2;
128
0
    if (r == 0)
129
0
        r = UINT_MAX;
130
0
    return r;
131
163k
}
132
133
/*
134
 * Implements the get_entropy() callback
135
 *
136
 * If the DRBG has a parent, then the required amount of entropy input
137
 * is fetched using the parent's ossl_prov_drbg_generate().
138
 *
139
 * Otherwise, the entropy is polled from the system entropy sources
140
 * using ossl_pool_acquire_entropy().
141
 *
142
 * If a random pool has been added to the DRBG using RAND_add(), then
143
 * its entropy will be used up first.
144
 */
145
size_t ossl_drbg_get_seed(void *vdrbg, unsigned char **pout,
146
    int entropy, size_t min_len,
147
    size_t max_len, int prediction_resistance,
148
    const unsigned char *adin, size_t adin_len)
149
54
{
150
54
    PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
151
54
    size_t bytes_needed;
152
54
    unsigned char *buffer;
153
154
    /* Figure out how many bytes we need */
155
54
    bytes_needed = entropy >= 0 ? (entropy + 7) / 8 : 0;
156
54
    if (bytes_needed < min_len)
157
5
        bytes_needed = min_len;
158
54
    if (bytes_needed > max_len)
159
0
        bytes_needed = max_len;
160
161
    /* Allocate storage */
162
54
    buffer = OPENSSL_secure_malloc(bytes_needed);
163
54
    if (buffer == NULL)
164
0
        return 0;
165
166
    /*
167
     * Get random data.  Include our DRBG address as
168
     * additional input, in order to provide a distinction between
169
     * different DRBG child instances.
170
     *
171
     * Note: using the sizeof() operator on a pointer triggers
172
     *       a warning in some static code analyzers, but it's
173
     *       intentional and correct here.
174
     */
175
54
    if (!ossl_prov_drbg_generate(drbg, buffer, bytes_needed,
176
54
            drbg->strength, prediction_resistance,
177
54
            (unsigned char *)&drbg, sizeof(drbg))) {
178
0
        OPENSSL_secure_clear_free(buffer, bytes_needed);
179
0
        ERR_raise(ERR_LIB_PROV, PROV_R_GENERATE_ERROR);
180
0
        return 0;
181
0
    }
182
54
    *pout = buffer;
183
54
    return bytes_needed;
184
54
}
185
186
/* Implements the cleanup_entropy() callback */
187
void ossl_drbg_clear_seed(ossl_unused void *vdrbg,
188
    unsigned char *out, size_t outlen)
189
54
{
190
54
    OPENSSL_secure_clear_free(out, outlen);
191
54
}
192
193
static size_t get_entropy(PROV_DRBG *drbg, unsigned char **pout, int entropy,
194
    size_t min_len, size_t max_len,
195
    int prediction_resistance)
196
250
{
197
250
    size_t bytes;
198
250
    unsigned int p_str;
199
200
250
    if (drbg->parent == NULL)
201
#ifdef FIPS_MODULE
202
        return ossl_crngt_get_entropy(drbg, pout, entropy, min_len, max_len,
203
            prediction_resistance);
204
#else
205
        /*
206
         * In normal use (i.e. OpenSSL's own uses), this is never called.
207
         * Outside of the FIPS provider, OpenSSL sets its DRBGs up so that
208
         * they always have a parent.  This remains purely for legacy reasons.
209
         */
210
238
        return ossl_prov_get_entropy(drbg->provctx, pout, entropy, min_len,
211
238
            max_len);
212
12
#endif
213
214
12
    if (drbg->parent_get_seed == NULL) {
215
0
        ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_CANNOT_SUPPLY_ENTROPY_SEED);
216
0
        return 0;
217
0
    }
218
12
    if (!get_parent_strength(drbg, &p_str))
219
0
        return 0;
220
12
    if (drbg->strength > p_str) {
221
        /*
222
         * We currently don't support the algorithm from NIST SP 800-90C
223
         * 10.1.2 to use a weaker DRBG as source
224
         */
225
0
        ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_STRENGTH_TOO_WEAK);
226
0
        return 0;
227
0
    }
228
229
    /*
230
     * Our lock is already held, but we need to lock our parent before
231
     * generating bits from it.  Note: taking the lock will be a no-op
232
     * if locking is not required (while drbg->parent->lock == NULL).
233
     */
234
12
    if (!ossl_drbg_lock_parent(drbg))
235
0
        return 0;
236
    /*
237
     * Get random data from parent.  Include our DRBG address as
238
     * additional input, in order to provide a distinction between
239
     * different DRBG child instances.
240
     *
241
     * Note: using the sizeof() operator on a pointer triggers
242
     *       a warning in some static code analyzers, but it's
243
     *       intentional and correct here.
244
     */
245
12
    bytes = drbg->parent_get_seed(drbg->parent, pout, drbg->strength,
246
12
        min_len, max_len, prediction_resistance,
247
12
        (unsigned char *)&drbg, sizeof(drbg));
248
12
    ossl_drbg_unlock_parent(drbg);
249
12
    return bytes;
250
12
}
251
252
static void cleanup_entropy(PROV_DRBG *drbg, unsigned char *out, size_t outlen)
253
1.24k
{
254
1.24k
    if (drbg->parent == NULL) {
255
#ifdef FIPS_MODULE
256
        ossl_crngt_cleanup_entropy(drbg, out, outlen);
257
#else
258
1.17k
        ossl_prov_cleanup_entropy(drbg->provctx, out, outlen);
259
1.17k
#endif
260
1.17k
    } else if (drbg->parent_clear_seed != NULL) {
261
72
        if (!ossl_drbg_lock_parent(drbg))
262
0
            return;
263
72
        drbg->parent_clear_seed(drbg->parent, out, outlen);
264
72
        ossl_drbg_unlock_parent(drbg);
265
72
    }
266
1.24k
}
267
268
#ifndef PROV_RAND_GET_RANDOM_NONCE
269
typedef struct prov_drbg_nonce_global_st {
270
    CRYPTO_RWLOCK *rand_nonce_lock;
271
    int rand_nonce_count;
272
} PROV_DRBG_NONCE_GLOBAL;
273
274
/*
275
 * drbg_ossl_ctx_new() calls drgb_setup() which calls rand_drbg_get_nonce()
276
 * which needs to get the rand_nonce_lock out of the OSSL_LIB_CTX...but since
277
 * drbg_ossl_ctx_new() hasn't finished running yet we need the rand_nonce_lock
278
 * to be in a different global data object. Otherwise we will go into an
279
 * infinite recursion loop.
280
 */
281
void *ossl_prov_drbg_nonce_ctx_new(OSSL_LIB_CTX *libctx)
282
380
{
283
380
    PROV_DRBG_NONCE_GLOBAL *dngbl = OPENSSL_zalloc(sizeof(*dngbl));
284
285
380
    if (dngbl == NULL)
286
0
        return NULL;
287
288
380
    dngbl->rand_nonce_lock = CRYPTO_THREAD_lock_new();
289
380
    if (dngbl->rand_nonce_lock == NULL) {
290
0
        OPENSSL_free(dngbl);
291
0
        return NULL;
292
0
    }
293
294
380
    return dngbl;
295
380
}
296
297
void ossl_prov_drbg_nonce_ctx_free(void *vdngbl)
298
196
{
299
196
    PROV_DRBG_NONCE_GLOBAL *dngbl = vdngbl;
300
301
196
    if (dngbl == NULL)
302
0
        return;
303
304
196
    CRYPTO_THREAD_lock_free(dngbl->rand_nonce_lock);
305
306
196
    OPENSSL_free(dngbl);
307
196
}
308
309
/* Get a nonce from the operating system */
310
static size_t prov_drbg_get_nonce(PROV_DRBG *drbg, unsigned char **pout,
311
    size_t min_len, size_t max_len)
312
569
{
313
569
    size_t ret = 0, n;
314
569
    unsigned char *buf = NULL;
315
569
    OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(drbg->provctx);
316
569
    PROV_DRBG_NONCE_GLOBAL *dngbl
317
569
        = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DRBG_NONCE_INDEX);
318
569
    struct {
319
569
        void *drbg;
320
569
        int count;
321
569
    } data;
322
323
569
    if (dngbl == NULL)
324
0
        return 0;
325
326
569
    if (drbg->parent != NULL && drbg->parent_nonce != NULL) {
327
0
        n = drbg->parent_nonce(drbg->parent, NULL, 0, drbg->min_noncelen,
328
0
            drbg->max_noncelen);
329
0
        if (n > 0 && (buf = OPENSSL_malloc(n)) != NULL) {
330
0
            ret = drbg->parent_nonce(drbg->parent, buf, 0,
331
0
                drbg->min_noncelen, drbg->max_noncelen);
332
0
            if (ret == n) {
333
0
                *pout = buf;
334
0
                return ret;
335
0
            }
336
0
            OPENSSL_free(buf);
337
0
        }
338
0
    }
339
340
    /* Use the built in nonce source plus some of our specifics */
341
569
    memset(&data, 0, sizeof(data));
342
569
    data.drbg = drbg;
343
569
    if (!CRYPTO_atomic_add(&dngbl->rand_nonce_count, 1, &data.count,
344
569
            dngbl->rand_nonce_lock))
345
0
        return 0;
346
569
    return ossl_prov_get_nonce(drbg->provctx, pout, min_len, max_len,
347
569
        &data, sizeof(data));
348
569
}
349
#endif /* PROV_RAND_GET_RANDOM_NONCE */
350
351
/*
352
 * Instantiate |drbg|, after it has been initialized.  Use |pers| and
353
 * |perslen| as prediction-resistance input.
354
 *
355
 * Requires that drbg->lock is already locked for write, if non-null.
356
 *
357
 * Returns 1 on success, 0 on failure.
358
 */
359
int ossl_prov_drbg_instantiate(PROV_DRBG *drbg, unsigned int strength,
360
    int prediction_resistance,
361
    const unsigned char *pers, size_t perslen)
362
614
{
363
614
    unsigned char *nonce = NULL, *entropy = NULL;
364
614
    size_t noncelen = 0, entropylen = 0;
365
614
    size_t min_entropy, min_entropylen, max_entropylen;
366
367
614
    if (strength > drbg->strength) {
368
0
        ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
369
0
        goto end;
370
0
    }
371
614
    min_entropy = drbg->strength;
372
614
    min_entropylen = drbg->min_entropylen;
373
614
    max_entropylen = drbg->max_entropylen;
374
375
614
    if (pers == NULL) {
376
614
        pers = (const unsigned char *)ossl_pers_string;
377
614
        perslen = sizeof(ossl_pers_string);
378
614
    }
379
614
    if (perslen > drbg->max_perslen) {
380
0
        ERR_raise(ERR_LIB_PROV, PROV_R_PERSONALISATION_STRING_TOO_LONG);
381
0
        goto end;
382
0
    }
383
384
614
    if (drbg->state != EVP_RAND_STATE_UNINITIALISED) {
385
0
        if (drbg->state == EVP_RAND_STATE_ERROR)
386
0
            ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
387
0
        else
388
0
            ERR_raise(ERR_LIB_PROV, PROV_R_ALREADY_INSTANTIATED);
389
0
        goto end;
390
0
    }
391
392
614
    drbg->state = EVP_RAND_STATE_ERROR;
393
394
614
    if (drbg->min_noncelen > 0) {
395
613
        if (drbg->parent_nonce != NULL) {
396
0
            noncelen = drbg->parent_nonce(drbg->parent, NULL, drbg->strength,
397
0
                drbg->min_noncelen,
398
0
                drbg->max_noncelen);
399
0
            if (noncelen == 0) {
400
0
                ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
401
0
                goto end;
402
0
            }
403
0
            nonce = OPENSSL_malloc(noncelen);
404
0
            if (nonce == NULL) {
405
0
                ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
406
0
                goto end;
407
0
            }
408
0
            if (noncelen != drbg->parent_nonce(drbg->parent, nonce, drbg->strength, drbg->min_noncelen, drbg->max_noncelen)) {
409
0
                ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
410
0
                goto end;
411
0
            }
412
0
#ifndef PROV_RAND_GET_RANDOM_NONCE
413
613
        } else if (drbg->parent != NULL) {
414
44
#endif
415
            /*
416
             * NIST SP800-90Ar1 section 9.1 says you can combine getting
417
             * the entropy and nonce in 1 call by increasing the entropy
418
             * with 50% and increasing the minimum length to accommodate
419
             * the length of the nonce. We do this in case a nonce is
420
             * required and there is no parental nonce capability.
421
             */
422
44
            min_entropy += drbg->strength / 2;
423
44
            min_entropylen += drbg->min_noncelen;
424
44
            max_entropylen += drbg->max_noncelen;
425
44
        }
426
569
#ifndef PROV_RAND_GET_RANDOM_NONCE
427
569
        else { /* parent == NULL */
428
569
            noncelen = prov_drbg_get_nonce(drbg, &nonce, drbg->min_noncelen,
429
569
                drbg->max_noncelen);
430
569
            if (noncelen < drbg->min_noncelen
431
569
                || noncelen > drbg->max_noncelen) {
432
0
                ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
433
0
                goto end;
434
0
            }
435
569
        }
436
613
#endif
437
613
    }
438
439
614
    drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
440
614
    if (drbg->reseed_next_counter) {
441
614
        drbg->reseed_next_counter++;
442
614
        if (!drbg->reseed_next_counter)
443
0
            drbg->reseed_next_counter = 1;
444
614
    }
445
446
614
    entropylen = get_entropy(drbg, &entropy, min_entropy,
447
614
        min_entropylen, max_entropylen,
448
614
        prediction_resistance);
449
614
    if (entropylen < min_entropylen
450
614
        || entropylen > max_entropylen) {
451
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
452
0
        goto end;
453
0
    }
454
455
614
    if (!drbg->instantiate(drbg, entropy, entropylen, nonce, noncelen,
456
614
            pers, perslen)) {
457
24
        cleanup_entropy(drbg, entropy, entropylen);
458
24
        ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_INSTANTIATING_DRBG);
459
24
        goto end;
460
24
    }
461
590
    cleanup_entropy(drbg, entropy, entropylen);
462
463
590
    drbg->state = EVP_RAND_STATE_READY;
464
590
    drbg->generate_counter = 1;
465
590
    drbg->reseed_time = time(NULL);
466
590
    tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
467
468
614
end:
469
614
    if (nonce != NULL)
470
569
        ossl_prov_cleanup_nonce(drbg->provctx, nonce, noncelen);
471
614
    if (drbg->state == EVP_RAND_STATE_READY)
472
590
        return 1;
473
24
    return 0;
474
614
}
475
476
/*
477
 * Uninstantiate |drbg|. Must be instantiated before it can be used.
478
 *
479
 * Requires that drbg->lock is already locked for write, if non-null.
480
 *
481
 * Returns 1 on success, 0 on failure.
482
 */
483
int ossl_prov_drbg_uninstantiate(PROV_DRBG *drbg)
484
0
{
485
0
    drbg->state = EVP_RAND_STATE_UNINITIALISED;
486
0
    return 1;
487
0
}
488
489
static int ossl_prov_drbg_reseed_unlocked(PROV_DRBG *drbg,
490
    int prediction_resistance,
491
    const unsigned char *ent,
492
    size_t ent_len,
493
    const unsigned char *adin,
494
    size_t adinlen)
495
630
{
496
630
    unsigned char *entropy = NULL;
497
630
    size_t entropylen = 0;
498
499
630
    if (!ossl_prov_is_running())
500
0
        return 0;
501
502
630
    if (drbg->state != EVP_RAND_STATE_READY) {
503
        /* try to recover from previous errors */
504
0
        rand_drbg_restart(drbg);
505
506
0
        if (drbg->state == EVP_RAND_STATE_ERROR) {
507
0
            ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
508
0
            return 0;
509
0
        }
510
0
        if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
511
0
            ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
512
0
            return 0;
513
0
        }
514
0
    }
515
516
630
    if (ent != NULL) {
517
0
        if (ent_len < drbg->min_entropylen) {
518
0
            ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_OUT_OF_RANGE);
519
0
            drbg->state = EVP_RAND_STATE_ERROR;
520
0
            return 0;
521
0
        }
522
0
        if (ent_len > drbg->max_entropylen) {
523
0
            ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_INPUT_TOO_LONG);
524
0
            drbg->state = EVP_RAND_STATE_ERROR;
525
0
            return 0;
526
0
        }
527
0
    }
528
529
630
    if (adin == NULL) {
530
630
        adinlen = 0;
531
630
    } else if (adinlen > drbg->max_adinlen) {
532
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
533
0
        return 0;
534
0
    }
535
536
630
    drbg->state = EVP_RAND_STATE_ERROR;
537
538
630
    drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
539
630
    if (drbg->reseed_next_counter) {
540
630
        drbg->reseed_next_counter++;
541
630
        if (!drbg->reseed_next_counter)
542
0
            drbg->reseed_next_counter = 1;
543
630
    }
544
545
630
    if (ent != NULL) {
546
#ifdef FIPS_MODULE
547
        /*
548
         * NIST SP-800-90A mandates that entropy *shall not* be provided
549
         * by the consuming application. Instead the data is added as additional
550
         * input.
551
         *
552
         * (NIST SP-800-90Ar1, Sections 9.1 and 9.2)
553
         */
554
        if (!drbg->reseed(drbg, NULL, 0, ent, ent_len)) {
555
            ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_RESEED);
556
            return 0;
557
        }
558
#else
559
0
        if (!drbg->reseed(drbg, ent, ent_len, adin, adinlen)) {
560
0
            ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_RESEED);
561
0
            return 0;
562
0
        }
563
        /* There isn't much point adding the same additional input twice */
564
0
        adin = NULL;
565
0
        adinlen = 0;
566
0
#endif
567
0
    }
568
569
    /* Reseed using our sources in addition */
570
630
    entropylen = get_entropy(drbg, &entropy, drbg->strength,
571
630
        drbg->min_entropylen, drbg->max_entropylen,
572
630
        prediction_resistance);
573
630
    if (entropylen < drbg->min_entropylen
574
630
        || entropylen > drbg->max_entropylen) {
575
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
576
0
        goto end;
577
0
    }
578
579
630
    if (!drbg->reseed(drbg, entropy, entropylen, adin, adinlen))
580
0
        goto end;
581
582
630
    drbg->state = EVP_RAND_STATE_READY;
583
630
    drbg->generate_counter = 1;
584
630
    drbg->reseed_time = time(NULL);
585
630
    tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
586
630
    if (drbg->parent != NULL)
587
26
        drbg->parent_reseed_counter = get_parent_reseed_count(drbg);
588
589
630
end:
590
630
    cleanup_entropy(drbg, entropy, entropylen);
591
630
    if (drbg->state == EVP_RAND_STATE_READY)
592
630
        return 1;
593
0
    return 0;
594
630
}
595
596
/*
597
 * Reseed |drbg|, mixing in the specified data
598
 *
599
 * Acquires the drbg->lock for writing, if non-null.
600
 *
601
 * Returns 1 on success, 0 on failure.
602
 */
603
int ossl_prov_drbg_reseed(PROV_DRBG *drbg, int prediction_resistance,
604
    const unsigned char *ent, size_t ent_len,
605
    const unsigned char *adin, size_t adinlen)
606
515
{
607
515
    int ret;
608
609
515
    if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
610
0
        return 0;
611
612
515
    ret = ossl_prov_drbg_reseed_unlocked(drbg, prediction_resistance, ent,
613
515
        ent_len, adin, adinlen);
614
615
515
    if (drbg->lock != NULL)
616
0
        CRYPTO_THREAD_unlock(drbg->lock);
617
618
515
    return ret;
619
515
}
620
621
/*
622
 * Generate |outlen| bytes into the buffer at |out|.  Reseed if we need
623
 * to or if |prediction_resistance| is set.  Additional input can be
624
 * sent in |adin| and |adinlen|.
625
 *
626
 * Acquires the drbg->lock for writing if available
627
 *
628
 * Returns 1 on success, 0 on failure.
629
 *
630
 */
631
int ossl_prov_drbg_generate(PROV_DRBG *drbg, unsigned char *out, size_t outlen,
632
    unsigned int strength, int prediction_resistance,
633
    const unsigned char *adin, size_t adinlen)
634
84.2k
{
635
84.2k
    int fork_id;
636
84.2k
    int reseed_required = 0;
637
84.2k
    int ret = 0;
638
639
84.2k
    if (!ossl_prov_is_running())
640
0
        return 0;
641
642
84.2k
    if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
643
0
        return 0;
644
645
84.2k
    if (drbg->state != EVP_RAND_STATE_READY) {
646
        /* try to recover from previous errors */
647
218
        rand_drbg_restart(drbg);
648
649
218
        if (drbg->state == EVP_RAND_STATE_ERROR) {
650
10
            ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
651
10
            goto err;
652
10
        }
653
208
        if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
654
0
            ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
655
0
            goto err;
656
0
        }
657
208
    }
658
84.2k
    if (strength > drbg->strength) {
659
0
        ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
660
0
        goto err;
661
0
    }
662
663
84.2k
    if (outlen > drbg->max_request) {
664
0
        ERR_raise(ERR_LIB_PROV, PROV_R_REQUEST_TOO_LARGE_FOR_DRBG);
665
0
        goto err;
666
0
    }
667
84.2k
    if (adinlen > drbg->max_adinlen) {
668
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
669
0
        goto err;
670
0
    }
671
672
84.2k
    fork_id = openssl_get_fork_id();
673
674
84.2k
    if (drbg->fork_id != fork_id) {
675
0
        drbg->fork_id = fork_id;
676
0
        reseed_required = 1;
677
0
    }
678
679
84.2k
    if (drbg->reseed_interval > 0) {
680
84.1k
        if (drbg->generate_counter >= drbg->reseed_interval)
681
49
            reseed_required = 1;
682
84.1k
    }
683
84.2k
    if (drbg->reseed_time_interval > 0) {
684
84.0k
        time_t now = time(NULL);
685
84.0k
        if (now < drbg->reseed_time
686
84.0k
            || now - drbg->reseed_time >= drbg->reseed_time_interval)
687
0
            reseed_required = 1;
688
84.0k
    }
689
84.2k
    if (drbg->parent != NULL
690
84.0k
        && get_parent_reseed_count(drbg) != drbg->parent_reseed_counter)
691
10
        reseed_required = 1;
692
693
84.2k
    if (reseed_required || prediction_resistance) {
694
59
        if (!ossl_prov_drbg_reseed_unlocked(drbg, prediction_resistance, NULL,
695
59
                0, adin, adinlen)) {
696
0
            ERR_raise(ERR_LIB_PROV, PROV_R_RESEED_ERROR);
697
0
            goto err;
698
0
        }
699
59
        adin = NULL;
700
59
        adinlen = 0;
701
59
    }
702
703
84.2k
    if (!drbg->generate(drbg, out, outlen, adin, adinlen)) {
704
20
        drbg->state = EVP_RAND_STATE_ERROR;
705
20
        ERR_raise(ERR_LIB_PROV, PROV_R_GENERATE_ERROR);
706
20
        goto err;
707
20
    }
708
709
84.2k
    drbg->generate_counter++;
710
711
84.2k
    ret = 1;
712
84.2k
err:
713
84.2k
    if (drbg->lock != NULL)
714
20
        CRYPTO_THREAD_unlock(drbg->lock);
715
716
84.2k
    return ret;
717
84.2k
}
718
719
/*
720
 * Restart |drbg|, using the specified entropy or additional input
721
 *
722
 * Tries its best to get the drbg instantiated by all means,
723
 * regardless of its current state.
724
 *
725
 * Optionally, a |buffer| of |len| random bytes can be passed,
726
 * which is assumed to contain at least |entropy| bits of entropy.
727
 *
728
 * If |entropy| > 0, the buffer content is used as entropy input.
729
 *
730
 * If |entropy| == 0, the buffer content is used as additional input
731
 *
732
 * Returns 1 on success, 0 on failure.
733
 *
734
 * This function is used internally only.
735
 */
736
static int rand_drbg_restart(PROV_DRBG *drbg)
737
569
{
738
    /* repair error state */
739
569
    if (drbg->state == EVP_RAND_STATE_ERROR)
740
0
        drbg->uninstantiate(drbg);
741
742
    /* repair uninitialized state */
743
569
    if (drbg->state == EVP_RAND_STATE_UNINITIALISED)
744
        /* reinstantiate drbg */
745
569
        ossl_prov_drbg_instantiate(drbg, drbg->strength, 0, NULL, 0);
746
747
569
    return drbg->state == EVP_RAND_STATE_READY;
748
569
}
749
750
/* Provider support from here down */
751
static const OSSL_DISPATCH *find_call(const OSSL_DISPATCH *dispatch,
752
    int function)
753
6.60k
{
754
6.60k
    if (dispatch != NULL)
755
3.68k
        while (dispatch->function_id != 0) {
756
3.63k
            if (dispatch->function_id == function)
757
270
                return dispatch;
758
3.36k
            dispatch++;
759
3.36k
        }
760
6.33k
    return NULL;
761
6.60k
}
762
763
int ossl_drbg_enable_locking(void *vctx)
764
18
{
765
18
    PROV_DRBG *drbg = vctx;
766
767
18
    if (drbg != NULL && drbg->lock == NULL) {
768
18
        if (drbg->parent_enable_locking != NULL)
769
18
            if (!drbg->parent_enable_locking(drbg->parent)) {
770
0
                ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
771
0
                return 0;
772
0
            }
773
18
        drbg->lock = CRYPTO_THREAD_lock_new();
774
18
        if (drbg->lock == NULL) {
775
0
            ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_CREATE_LOCK);
776
0
            return 0;
777
0
        }
778
18
    }
779
18
    return 1;
780
18
}
781
782
/*
783
 * Allocate memory and initialize a new DRBG. The DRBG is allocated on
784
 * the secure heap if |secure| is nonzero and the secure heap is enabled.
785
 * The |parent|, if not NULL, will be used as random source for reseeding.
786
 * This also requires the parent's provider context and the parent's lock.
787
 *
788
 * Returns a pointer to the new DRBG instance on success, NULL on failure.
789
 */
790
PROV_DRBG *ossl_rand_drbg_new(void *provctx, void *parent, const OSSL_DISPATCH *p_dispatch,
791
    int (*dnew)(PROV_DRBG *ctx),
792
    void (*dfree)(void *vctx),
793
    int (*instantiate)(PROV_DRBG *drbg,
794
        const unsigned char *entropy, size_t entropylen,
795
        const unsigned char *nonce, size_t noncelen,
796
        const unsigned char *pers, size_t perslen),
797
    int (*uninstantiate)(PROV_DRBG *ctx),
798
    int (*reseed)(PROV_DRBG *drbg, const unsigned char *ent, size_t ent_len,
799
        const unsigned char *adin, size_t adin_len),
800
    int (*generate)(PROV_DRBG *, unsigned char *out, size_t outlen,
801
        const unsigned char *adin, size_t adin_len))
802
943
{
803
943
    PROV_DRBG *drbg;
804
943
    unsigned int p_str;
805
943
    const OSSL_DISPATCH *pfunc;
806
807
943
    if (!ossl_prov_is_running())
808
0
        return NULL;
809
810
943
    drbg = OPENSSL_zalloc(sizeof(*drbg));
811
943
    if (drbg == NULL)
812
0
        return NULL;
813
814
943
    drbg->provctx = provctx;
815
943
    drbg->instantiate = instantiate;
816
943
    drbg->uninstantiate = uninstantiate;
817
943
    drbg->reseed = reseed;
818
943
    drbg->generate = generate;
819
943
    drbg->fork_id = openssl_get_fork_id();
820
821
    /* Extract parent's functions */
822
943
    drbg->parent = parent;
823
943
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_ENABLE_LOCKING)) != NULL)
824
45
        drbg->parent_enable_locking = OSSL_FUNC_rand_enable_locking(pfunc);
825
943
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_LOCK)) != NULL)
826
45
        drbg->parent_lock = OSSL_FUNC_rand_lock(pfunc);
827
943
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_UNLOCK)) != NULL)
828
45
        drbg->parent_unlock = OSSL_FUNC_rand_unlock(pfunc);
829
943
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_CTX_PARAMS)) != NULL)
830
45
        drbg->parent_get_ctx_params = OSSL_FUNC_rand_get_ctx_params(pfunc);
831
943
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_NONCE)) != NULL)
832
0
        drbg->parent_nonce = OSSL_FUNC_rand_nonce(pfunc);
833
943
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_SEED)) != NULL)
834
45
        drbg->parent_get_seed = OSSL_FUNC_rand_get_seed(pfunc);
835
943
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_CLEAR_SEED)) != NULL)
836
45
        drbg->parent_clear_seed = OSSL_FUNC_rand_clear_seed(pfunc);
837
838
    /* Set some default maximums up */
839
943
    drbg->max_entropylen = DRBG_MAX_LENGTH;
840
943
    drbg->max_noncelen = DRBG_MAX_LENGTH;
841
943
    drbg->max_perslen = DRBG_MAX_LENGTH;
842
943
    drbg->max_adinlen = DRBG_MAX_LENGTH;
843
943
    drbg->generate_counter = 1;
844
943
    drbg->reseed_counter = 1;
845
943
    drbg->reseed_interval = RESEED_INTERVAL;
846
943
    drbg->reseed_time_interval = TIME_INTERVAL;
847
848
943
    if (!dnew(drbg))
849
0
        goto err;
850
851
943
    if (parent != NULL) {
852
45
        if (!get_parent_strength(drbg, &p_str))
853
0
            goto err;
854
45
        if (drbg->strength > p_str) {
855
            /*
856
             * We currently don't support the algorithm from NIST SP 800-90C
857
             * 10.1.2 to use a weaker DRBG as source
858
             */
859
0
            ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_STRENGTH_TOO_WEAK);
860
0
            goto err;
861
0
        }
862
45
    }
863
#ifdef TSAN_REQUIRES_LOCKING
864
    if (!ossl_drbg_enable_locking(drbg))
865
        goto err;
866
#endif
867
943
    return drbg;
868
869
0
err:
870
0
    dfree(drbg);
871
0
    return NULL;
872
943
}
873
874
void ossl_rand_drbg_free(PROV_DRBG *drbg)
875
927
{
876
927
    if (drbg == NULL)
877
0
        return;
878
879
927
    CRYPTO_THREAD_lock_free(drbg->lock);
880
927
    OPENSSL_free(drbg);
881
927
}
882
883
/*
884
 * Helper function called by internal DRBG implementations. Assumes that at
885
 * least a read lock has been taken on drbg->lock
886
 */
887
int ossl_drbg_get_ctx_params(PROV_DRBG *drbg, OSSL_PARAM params[])
888
3
{
889
3
    OSSL_PARAM *p;
890
891
3
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STATE);
892
3
    if (p != NULL && !OSSL_PARAM_set_int(p, drbg->state))
893
0
        return 0;
894
895
3
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STRENGTH);
896
3
    if (p != NULL && !OSSL_PARAM_set_int(p, drbg->strength))
897
0
        return 0;
898
899
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_ENTROPYLEN);
900
3
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_entropylen))
901
0
        return 0;
902
903
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ENTROPYLEN);
904
3
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_entropylen))
905
0
        return 0;
906
907
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_NONCELEN);
908
3
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_noncelen))
909
0
        return 0;
910
911
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_NONCELEN);
912
3
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_noncelen))
913
0
        return 0;
914
915
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_PERSLEN);
916
3
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_perslen))
917
0
        return 0;
918
919
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ADINLEN);
920
3
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_adinlen))
921
0
        return 0;
922
923
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
924
3
    if (p != NULL && !OSSL_PARAM_set_uint(p, drbg->reseed_interval))
925
0
        return 0;
926
927
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME);
928
3
    if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time))
929
0
        return 0;
930
931
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
932
3
    if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time_interval))
933
0
        return 0;
934
935
3
    return 1;
936
3
}
937
938
/*
939
 * Helper function to get certain params that require no lock to obtain. Sets
940
 * *complete to 1 if all the params were processed, or 0 otherwise
941
 */
942
int ossl_drbg_get_ctx_params_no_lock(PROV_DRBG *drbg, OSSL_PARAM params[],
943
    int *complete)
944
300k
{
945
300k
    size_t cnt = 0;
946
300k
    OSSL_PARAM *p;
947
948
    /* This value never changes once set */
949
300k
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_MAX_REQUEST);
950
300k
    if (p != NULL) {
951
150k
        if (!OSSL_PARAM_set_size_t(p, drbg->max_request))
952
0
            return 0;
953
150k
        cnt++;
954
150k
    }
955
956
    /*
957
     * Can be changed by multiple threads, but we tolerate inaccuracies in this
958
     * value.
959
     */
960
300k
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_COUNTER);
961
300k
    if (p != NULL) {
962
149k
        if (!OSSL_PARAM_set_uint(p, tsan_load(&drbg->reseed_counter)))
963
0
            return 0;
964
149k
        cnt++;
965
149k
    }
966
967
300k
    if (params[cnt].key == NULL)
968
300k
        *complete = 1;
969
78
    else
970
78
        *complete = 0;
971
972
300k
    return 1;
973
300k
}
974
975
int ossl_drbg_set_ctx_params(PROV_DRBG *drbg, const OSSL_PARAM params[])
976
122
{
977
122
    const OSSL_PARAM *p;
978
979
122
    if (params == NULL)
980
0
        return 1;
981
982
122
    p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
983
122
    if (p != NULL && !OSSL_PARAM_get_uint(p, &drbg->reseed_interval))
984
0
        return 0;
985
986
122
    p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
987
122
    if (p != NULL && !OSSL_PARAM_get_time_t(p, &drbg->reseed_time_interval))
988
0
        return 0;
989
122
    return 1;
990
122
}
991
992
/* Confirm digest is allowed to be used with a DRBG */
993
int ossl_drbg_verify_digest(ossl_unused OSSL_LIB_CTX *libctx, const EVP_MD *md)
994
{
995
#ifdef FIPS_MODULE
996
    /* FIPS 140-3 IG D.R limited DRBG digests to a specific set */
997
    static const char *const allowed_digests[] = {
998
        "SHA1", /* SHA 1 allowed */
999
        "SHA2-256",
1000
        "SHA2-512", /* non-truncated SHA2 allowed */
1001
        "SHA3-256",
1002
        "SHA3-512", /* non-truncated SHA3 allowed */
1003
    };
1004
    size_t i;
1005
1006
    if (FIPS_restricted_drbg_digests_enabled(libctx)) {
1007
        for (i = 0; i < OSSL_NELEM(allowed_digests); i++)
1008
            if (EVP_MD_is_a(md, allowed_digests[i]))
1009
                return 1;
1010
        ERR_raise(ERR_LIB_PROV, PROV_R_DIGEST_NOT_ALLOWED);
1011
        return 0;
1012
    }
1013
#endif
1014
    /* Outside of FIPS, any digests that are not XOF are allowed */
1015
    if ((EVP_MD_get_flags(md) & EVP_MD_FLAG_XOF) != 0) {
1016
        ERR_raise(ERR_LIB_PROV, PROV_R_XOF_DIGESTS_NOT_ALLOWED);
1017
        return 0;
1018
    }
1019
    return 1;
1020
}