Coverage Report

Created: 2026-09-12 06:55

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