Coverage Report

Created: 2026-02-14 07:20

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
247k
{
55
247k
    return 1;
56
247k
}
57
58
/* Interpreted as a hint only and ignored as for ossl_drbg_lock() */
59
void ossl_drbg_unlock(void *vctx)
60
247k
{
61
247k
}
62
63
static int ossl_drbg_lock_parent(PROV_DRBG *drbg)
64
133k
{
65
133k
    void *parent = drbg->parent;
66
67
133k
    if (parent != NULL
68
133k
        && drbg->parent_lock != NULL
69
133k
        && !drbg->parent_lock(parent)) {
70
0
        ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
71
0
        return 0;
72
0
    }
73
133k
    return 1;
74
133k
}
75
76
static void ossl_drbg_unlock_parent(PROV_DRBG *drbg)
77
133k
{
78
133k
    void *parent = drbg->parent;
79
80
133k
    if (parent != NULL && drbg->parent_unlock != NULL)
81
133k
        drbg->parent_unlock(parent);
82
133k
}
83
84
static int get_parent_strength(PROV_DRBG *drbg, unsigned int *str)
85
117
{
86
117
    OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
87
117
    void *parent = drbg->parent;
88
117
    int res;
89
90
117
    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
117
    *params = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, str);
96
117
    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
117
    res = drbg->parent_get_ctx_params(parent, params);
101
117
    ossl_drbg_unlock_parent(drbg);
102
117
    if (!res) {
103
0
        ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_GET_PARENT_STRENGTH);
104
0
        return 0;
105
0
    }
106
117
    return 1;
107
117
}
108
109
static unsigned int get_parent_reseed_count(PROV_DRBG *drbg)
110
132k
{
111
132k
    OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
112
132k
    void *parent = drbg->parent;
113
132k
    unsigned int r = 0;
114
115
132k
    *params = OSSL_PARAM_construct_uint(OSSL_DRBG_PARAM_RESEED_COUNTER, &r);
116
132k
    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
132k
    if (!drbg->parent_get_ctx_params(parent, params))
121
0
        r = 0;
122
132k
    ossl_drbg_unlock_parent(drbg);
123
132k
    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
132k
}
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
54
{
149
54
    PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
150
54
    size_t bytes_needed;
151
54
    unsigned char *buffer;
152
153
    /* Figure out how many bytes we need */
154
54
    bytes_needed = entropy >= 0 ? (entropy + 7) / 8 : 0;
155
54
    if (bytes_needed < min_len)
156
5
        bytes_needed = min_len;
157
54
    if (bytes_needed > max_len)
158
0
        bytes_needed = max_len;
159
160
    /* Allocate storage */
161
54
    buffer = OPENSSL_secure_malloc(bytes_needed);
162
54
    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
54
    if (!ossl_prov_drbg_generate(drbg, buffer, bytes_needed,
175
54
            drbg->strength, prediction_resistance,
176
54
            (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
54
    *pout = buffer;
182
54
    return bytes_needed;
183
54
}
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
54
{
189
54
    OPENSSL_secure_clear_free(out, outlen);
190
54
}
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
260
{
196
260
    size_t bytes;
197
260
    unsigned int p_str;
198
199
260
    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
248
        return ossl_prov_get_entropy(drbg->provctx, pout, entropy, min_len,
205
248
            max_len);
206
207
12
    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
12
    if (!get_parent_strength(drbg, &p_str))
212
0
        return 0;
213
12
    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
12
    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
12
    bytes = drbg->parent_get_seed(drbg->parent, pout, drbg->strength,
239
12
        min_len, max_len, prediction_resistance,
240
12
        (unsigned char *)&drbg, sizeof(drbg));
241
12
    ossl_drbg_unlock_parent(drbg);
242
12
    return bytes;
243
12
}
244
245
static void cleanup_entropy(PROV_DRBG *drbg, unsigned char *out, size_t outlen)
246
1.14k
{
247
1.14k
    if (drbg->parent == NULL) {
248
1.07k
        ossl_prov_cleanup_entropy(drbg->provctx, out, outlen);
249
1.07k
    } else if (drbg->parent_clear_seed != NULL) {
250
72
        if (!ossl_drbg_lock_parent(drbg))
251
0
            return;
252
72
        drbg->parent_clear_seed(drbg->parent, out, outlen);
253
72
        ossl_drbg_unlock_parent(drbg);
254
72
    }
255
1.14k
}
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
380
{
272
380
    PROV_DRBG_NONCE_GLOBAL *dngbl = OPENSSL_zalloc(sizeof(*dngbl));
273
274
380
    if (dngbl == NULL)
275
0
        return NULL;
276
277
380
    dngbl->rand_nonce_lock = CRYPTO_THREAD_lock_new();
278
380
    if (dngbl->rand_nonce_lock == NULL) {
279
0
        OPENSSL_free(dngbl);
280
0
        return NULL;
281
0
    }
282
283
380
    return dngbl;
284
380
}
285
286
void ossl_prov_drbg_nonce_ctx_free(void *vdngbl)
287
196
{
288
196
    PROV_DRBG_NONCE_GLOBAL *dngbl = vdngbl;
289
290
196
    if (dngbl == NULL)
291
0
        return;
292
293
196
    CRYPTO_THREAD_lock_free(dngbl->rand_nonce_lock);
294
295
196
    OPENSSL_free(dngbl);
296
196
}
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
519
{
302
519
    size_t ret = 0, n;
303
519
    unsigned char *buf = NULL;
304
519
    OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(drbg->provctx);
305
519
    PROV_DRBG_NONCE_GLOBAL *dngbl
306
519
        = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DRBG_NONCE_INDEX);
307
519
    struct {
308
519
        void *drbg;
309
519
        int count;
310
519
    } data;
311
312
519
    if (dngbl == NULL)
313
0
        return 0;
314
315
519
    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
519
    memset(&data, 0, sizeof(data));
331
519
    data.drbg = drbg;
332
519
    if (!CRYPTO_atomic_add(&dngbl->rand_nonce_count, 1, &data.count,
333
519
            dngbl->rand_nonce_lock))
334
0
        return 0;
335
519
    return ossl_prov_get_nonce(drbg->provctx, pout, min_len, max_len,
336
519
        &data, sizeof(data));
337
519
}
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
564
{
352
564
    unsigned char *nonce = NULL, *entropy = NULL;
353
564
    size_t noncelen = 0, entropylen = 0;
354
564
    size_t min_entropy, min_entropylen, max_entropylen;
355
356
564
    if (strength > drbg->strength) {
357
0
        ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
358
0
        goto end;
359
0
    }
360
564
    min_entropy = drbg->strength;
361
564
    min_entropylen = drbg->min_entropylen;
362
564
    max_entropylen = drbg->max_entropylen;
363
364
564
    if (pers == NULL) {
365
564
        pers = (const unsigned char *)ossl_pers_string;
366
564
        perslen = sizeof(ossl_pers_string);
367
564
    }
368
564
    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
564
    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
564
    drbg->state = EVP_RAND_STATE_ERROR;
382
383
564
    if (drbg->min_noncelen > 0) {
384
563
        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
563
        } else if (drbg->parent != NULL) {
403
44
#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
44
            min_entropy += drbg->strength / 2;
412
44
            min_entropylen += drbg->min_noncelen;
413
44
            max_entropylen += drbg->max_noncelen;
414
44
        }
415
519
#ifndef PROV_RAND_GET_RANDOM_NONCE
416
519
        else { /* parent == NULL */
417
519
            noncelen = prov_drbg_get_nonce(drbg, &nonce, drbg->min_noncelen,
418
519
                drbg->max_noncelen);
419
519
            if (noncelen < drbg->min_noncelen
420
519
                || noncelen > drbg->max_noncelen) {
421
0
                ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
422
0
                goto end;
423
0
            }
424
519
        }
425
563
#endif
426
563
    }
427
428
564
    drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
429
564
    if (drbg->reseed_next_counter) {
430
564
        drbg->reseed_next_counter++;
431
564
        if (!drbg->reseed_next_counter)
432
0
            drbg->reseed_next_counter = 1;
433
564
    }
434
435
564
    entropylen = get_entropy(drbg, &entropy, min_entropy,
436
564
        min_entropylen, max_entropylen,
437
564
        prediction_resistance);
438
564
    if (entropylen < min_entropylen
439
564
        || entropylen > max_entropylen) {
440
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
441
0
        goto end;
442
0
    }
443
444
564
    if (!drbg->instantiate(drbg, entropy, entropylen, nonce, noncelen,
445
564
            pers, perslen)) {
446
20
        cleanup_entropy(drbg, entropy, entropylen);
447
20
        ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_INSTANTIATING_DRBG);
448
20
        goto end;
449
20
    }
450
544
    cleanup_entropy(drbg, entropy, entropylen);
451
452
544
    drbg->state = EVP_RAND_STATE_READY;
453
544
    drbg->generate_counter = 1;
454
544
    drbg->reseed_time = time(NULL);
455
544
    tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
456
457
564
end:
458
564
    if (nonce != NULL)
459
519
        ossl_prov_cleanup_nonce(drbg->provctx, nonce, noncelen);
460
564
    if (drbg->state == EVP_RAND_STATE_READY)
461
544
        return 1;
462
20
    return 0;
463
564
}
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
581
{
485
581
    unsigned char *entropy = NULL;
486
581
    size_t entropylen = 0;
487
488
581
    if (!ossl_prov_is_running())
489
0
        return 0;
490
491
581
    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
581
    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
581
    if (adin == NULL) {
519
581
        adinlen = 0;
520
581
    } 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
581
    drbg->state = EVP_RAND_STATE_ERROR;
526
527
581
    drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
528
581
    if (drbg->reseed_next_counter) {
529
581
        drbg->reseed_next_counter++;
530
581
        if (!drbg->reseed_next_counter)
531
0
            drbg->reseed_next_counter = 1;
532
581
    }
533
534
581
    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
581
    entropylen = get_entropy(drbg, &entropy, drbg->strength,
560
581
        drbg->min_entropylen, drbg->max_entropylen,
561
581
        prediction_resistance);
562
581
    if (entropylen < drbg->min_entropylen
563
581
        || entropylen > drbg->max_entropylen) {
564
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
565
0
        goto end;
566
0
    }
567
568
581
    if (!drbg->reseed(drbg, entropy, entropylen, adin, adinlen))
569
0
        goto end;
570
571
581
    drbg->state = EVP_RAND_STATE_READY;
572
581
    drbg->generate_counter = 1;
573
581
    drbg->reseed_time = time(NULL);
574
581
    tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
575
581
    if (drbg->parent != NULL)
576
26
        drbg->parent_reseed_counter = get_parent_reseed_count(drbg);
577
578
581
end:
579
581
    cleanup_entropy(drbg, entropy, entropylen);
580
581
    if (drbg->state == EVP_RAND_STATE_READY)
581
581
        return 1;
582
0
    return 0;
583
581
}
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
471
{
596
471
    int ret;
597
598
471
    if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
599
0
        return 0;
600
601
471
    ret = ossl_prov_drbg_reseed_unlocked(drbg, prediction_resistance, ent,
602
471
        ent_len, adin, adinlen);
603
604
471
    if (drbg->lock != NULL)
605
0
        CRYPTO_THREAD_unlock(drbg->lock);
606
607
471
    return ret;
608
471
}
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
79.8k
{
624
79.8k
    int fork_id;
625
79.8k
    int reseed_required = 0;
626
79.8k
    int ret = 0;
627
628
79.8k
    if (!ossl_prov_is_running())
629
0
        return 0;
630
631
79.8k
    if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
632
0
        return 0;
633
634
79.8k
    if (drbg->state != EVP_RAND_STATE_READY) {
635
        /* try to recover from previous errors */
636
224
        rand_drbg_restart(drbg);
637
638
224
        if (drbg->state == EVP_RAND_STATE_ERROR) {
639
10
            ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
640
10
            goto err;
641
10
        }
642
214
        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
214
    }
647
79.8k
    if (strength > drbg->strength) {
648
0
        ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
649
0
        goto err;
650
0
    }
651
652
79.8k
    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
79.8k
    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
79.8k
    fork_id = openssl_get_fork_id();
662
663
79.8k
    if (drbg->fork_id != fork_id) {
664
0
        drbg->fork_id = fork_id;
665
0
        reseed_required = 1;
666
0
    }
667
668
79.8k
    if (drbg->reseed_interval > 0) {
669
79.7k
        if (drbg->generate_counter >= drbg->reseed_interval)
670
48
            reseed_required = 1;
671
79.7k
    }
672
79.8k
    if (drbg->reseed_time_interval > 0) {
673
79.6k
        time_t now = time(NULL);
674
79.6k
        if (now < drbg->reseed_time
675
79.6k
            || now - drbg->reseed_time >= drbg->reseed_time_interval)
676
0
            reseed_required = 1;
677
79.6k
    }
678
79.8k
    if (drbg->parent != NULL
679
79.6k
        && get_parent_reseed_count(drbg) != drbg->parent_reseed_counter)
680
10
        reseed_required = 1;
681
682
79.8k
    if (reseed_required || prediction_resistance) {
683
58
        if (!ossl_prov_drbg_reseed_unlocked(drbg, prediction_resistance, NULL,
684
58
                0, adin, adinlen)) {
685
0
            ERR_raise(ERR_LIB_PROV, PROV_R_RESEED_ERROR);
686
0
            goto err;
687
0
        }
688
58
        adin = NULL;
689
58
        adinlen = 0;
690
58
    }
691
692
79.8k
    if (!drbg->generate(drbg, out, outlen, adin, adinlen)) {
693
20
        drbg->state = EVP_RAND_STATE_ERROR;
694
20
        ERR_raise(ERR_LIB_PROV, PROV_R_GENERATE_ERROR);
695
20
        goto err;
696
20
    }
697
698
79.8k
    drbg->generate_counter++;
699
700
79.8k
    ret = 1;
701
79.8k
err:
702
79.8k
    if (drbg->lock != NULL)
703
20
        CRYPTO_THREAD_unlock(drbg->lock);
704
705
79.8k
    return ret;
706
79.8k
}
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
519
{
727
    /* repair error state */
728
519
    if (drbg->state == EVP_RAND_STATE_ERROR)
729
0
        drbg->uninstantiate(drbg);
730
731
    /* repair uninitialized state */
732
519
    if (drbg->state == EVP_RAND_STATE_UNINITIALISED)
733
        /* reinstantiate drbg */
734
519
        ossl_prov_drbg_instantiate(drbg, drbg->strength, 0, NULL, 0);
735
736
519
    return drbg->state == EVP_RAND_STATE_READY;
737
519
}
738
739
/* Provider support from here down */
740
static const OSSL_DISPATCH *find_call(const OSSL_DISPATCH *dispatch,
741
    int function)
742
6.24k
{
743
6.24k
    if (dispatch != NULL)
744
3.68k
        while (dispatch->function_id != 0) {
745
3.63k
            if (dispatch->function_id == function)
746
270
                return dispatch;
747
3.36k
            dispatch++;
748
3.36k
        }
749
5.97k
    return NULL;
750
6.24k
}
751
752
int ossl_drbg_enable_locking(void *vctx)
753
18
{
754
18
    PROV_DRBG *drbg = vctx;
755
756
18
    if (drbg != NULL && drbg->lock == NULL) {
757
18
        if (drbg->parent_enable_locking != NULL)
758
18
            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
18
        drbg->lock = CRYPTO_THREAD_lock_new();
763
18
        if (drbg->lock == NULL) {
764
0
            ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_CREATE_LOCK);
765
0
            return 0;
766
0
        }
767
18
    }
768
18
    return 1;
769
18
}
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
892
{
792
892
    PROV_DRBG *drbg;
793
892
    unsigned int p_str;
794
892
    const OSSL_DISPATCH *pfunc;
795
796
892
    if (!ossl_prov_is_running())
797
0
        return NULL;
798
799
892
    drbg = OPENSSL_zalloc(sizeof(*drbg));
800
892
    if (drbg == NULL)
801
0
        return NULL;
802
803
892
    drbg->provctx = provctx;
804
892
    drbg->instantiate = instantiate;
805
892
    drbg->uninstantiate = uninstantiate;
806
892
    drbg->reseed = reseed;
807
892
    drbg->generate = generate;
808
892
    drbg->fork_id = openssl_get_fork_id();
809
810
    /* Extract parent's functions */
811
892
    drbg->parent = parent;
812
892
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_ENABLE_LOCKING)) != NULL)
813
45
        drbg->parent_enable_locking = OSSL_FUNC_rand_enable_locking(pfunc);
814
892
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_LOCK)) != NULL)
815
45
        drbg->parent_lock = OSSL_FUNC_rand_lock(pfunc);
816
892
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_UNLOCK)) != NULL)
817
45
        drbg->parent_unlock = OSSL_FUNC_rand_unlock(pfunc);
818
892
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_CTX_PARAMS)) != NULL)
819
45
        drbg->parent_get_ctx_params = OSSL_FUNC_rand_get_ctx_params(pfunc);
820
892
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_NONCE)) != NULL)
821
0
        drbg->parent_nonce = OSSL_FUNC_rand_nonce(pfunc);
822
892
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_SEED)) != NULL)
823
45
        drbg->parent_get_seed = OSSL_FUNC_rand_get_seed(pfunc);
824
892
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_CLEAR_SEED)) != NULL)
825
45
        drbg->parent_clear_seed = OSSL_FUNC_rand_clear_seed(pfunc);
826
827
    /* Set some default maximums up */
828
892
    drbg->max_entropylen = DRBG_MAX_LENGTH;
829
892
    drbg->max_noncelen = DRBG_MAX_LENGTH;
830
892
    drbg->max_perslen = DRBG_MAX_LENGTH;
831
892
    drbg->max_adinlen = DRBG_MAX_LENGTH;
832
892
    drbg->generate_counter = 1;
833
892
    drbg->reseed_counter = 1;
834
892
    drbg->reseed_interval = RESEED_INTERVAL;
835
892
    drbg->reseed_time_interval = TIME_INTERVAL;
836
837
892
    if (!dnew(drbg))
838
0
        goto err;
839
840
892
    if (parent != NULL) {
841
45
        if (!get_parent_strength(drbg, &p_str))
842
0
            goto err;
843
45
        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
45
    }
852
#ifdef TSAN_REQUIRES_LOCKING
853
    if (!ossl_drbg_enable_locking(drbg))
854
        goto err;
855
#endif
856
892
    return drbg;
857
858
0
err:
859
0
    dfree(drbg);
860
0
    return NULL;
861
892
}
862
863
void ossl_rand_drbg_free(PROV_DRBG *drbg)
864
876
{
865
876
    if (drbg == NULL)
866
0
        return;
867
868
876
    CRYPTO_THREAD_lock_free(drbg->lock);
869
876
    OPENSSL_free(drbg);
870
876
}
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
75
{
878
75
    OSSL_PARAM *p;
879
880
75
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STATE);
881
75
    if (p != NULL && !OSSL_PARAM_set_int(p, drbg->state))
882
0
        return 0;
883
884
75
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STRENGTH);
885
75
    if (p != NULL && !OSSL_PARAM_set_int(p, drbg->strength))
886
0
        return 0;
887
888
75
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_ENTROPYLEN);
889
75
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_entropylen))
890
0
        return 0;
891
892
75
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ENTROPYLEN);
893
75
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_entropylen))
894
0
        return 0;
895
896
75
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_NONCELEN);
897
75
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_noncelen))
898
0
        return 0;
899
900
75
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_NONCELEN);
901
75
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_noncelen))
902
0
        return 0;
903
904
75
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_PERSLEN);
905
75
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_perslen))
906
0
        return 0;
907
908
75
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ADINLEN);
909
75
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_adinlen))
910
0
        return 0;
911
912
75
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
913
75
    if (p != NULL && !OSSL_PARAM_set_uint(p, drbg->reseed_interval))
914
0
        return 0;
915
916
75
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME);
917
75
    if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time))
918
0
        return 0;
919
920
75
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
921
75
    if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time_interval))
922
0
        return 0;
923
75
    if (!OSSL_FIPS_IND_GET_CTX_PARAM(drbg, params))
924
0
        return 0;
925
75
    return 1;
926
75
}
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
246k
{
935
246k
    size_t cnt = 0;
936
246k
    OSSL_PARAM *p;
937
938
    /* This value never changes once set */
939
246k
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_MAX_REQUEST);
940
246k
    if (p != NULL) {
941
123k
        if (!OSSL_PARAM_set_size_t(p, drbg->max_request))
942
0
            return 0;
943
123k
        cnt++;
944
123k
    }
945
946
    /*
947
     * Can be changed by multiple threads, but we tolerate inaccuracies in this
948
     * value.
949
     */
950
246k
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_COUNTER);
951
246k
    if (p != NULL) {
952
122k
        if (!OSSL_PARAM_set_uint(p, tsan_load(&drbg->reseed_counter)))
953
0
            return 0;
954
122k
        cnt++;
955
122k
    }
956
957
246k
    if (params[cnt].key == NULL)
958
246k
        *complete = 1;
959
78
    else
960
78
        *complete = 0;
961
962
246k
    return 1;
963
246k
}
964
965
int ossl_drbg_set_ctx_params(PROV_DRBG *drbg, const OSSL_PARAM params[])
966
127
{
967
127
    const OSSL_PARAM *p;
968
969
127
    if (params == NULL)
970
0
        return 1;
971
972
127
    p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
973
127
    if (p != NULL && !OSSL_PARAM_get_uint(p, &drbg->reseed_interval))
974
0
        return 0;
975
976
127
    p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
977
127
    if (p != NULL && !OSSL_PARAM_get_time_t(p, &drbg->reseed_time_interval))
978
0
        return 0;
979
980
127
    return 1;
981
127
}
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
568
{
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
568
    if (EVP_MD_xof(md)) {
1022
22
        ERR_raise(ERR_LIB_PROV, PROV_R_XOF_DIGESTS_NOT_ALLOWED);
1023
22
        return 0;
1024
22
    }
1025
546
#endif /* FIPS_MODULE */
1026
546
    return 1;
1027
568
}