Coverage Report

Created: 2025-06-13 06:58

/src/openssl32/providers/implementations/rands/drbg.c
Line
Count
Source (jump to first uncovered line)
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
71.7k
{
56
71.7k
    return 1;
57
71.7k
}
58
59
/* Interpreted as a hint only and ignored as for ossl_drbg_lock() */
60
void ossl_drbg_unlock(void *vctx)
61
71.7k
{
62
71.7k
}
63
64
static int ossl_drbg_lock_parent(PROV_DRBG *drbg)
65
81.7k
{
66
81.7k
    void *parent = drbg->parent;
67
68
81.7k
    if (parent != NULL
69
81.7k
            && drbg->parent_lock != NULL
70
81.7k
            && !drbg->parent_lock(parent)) {
71
0
        ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
72
0
        return 0;
73
0
    }
74
81.7k
    return 1;
75
81.7k
}
76
77
static void ossl_drbg_unlock_parent(PROV_DRBG *drbg)
78
81.7k
{
79
81.7k
    void *parent = drbg->parent;
80
81
81.7k
    if (parent != NULL && drbg->parent_unlock != NULL)
82
81.7k
        drbg->parent_unlock(parent);
83
81.7k
}
84
85
static int get_parent_strength(PROV_DRBG *drbg, unsigned int *str)
86
44
{
87
44
    OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
88
44
    void *parent = drbg->parent;
89
44
    int res;
90
91
44
    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
44
    *params = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, str);
97
44
    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
44
    res = drbg->parent_get_ctx_params(parent, params);
102
44
    ossl_drbg_unlock_parent(drbg);
103
44
    if (!res) {
104
0
        ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_GET_PARENT_STRENGTH);
105
0
        return 0;
106
0
    }
107
44
    return 1;
108
44
}
109
110
static unsigned int get_parent_reseed_count(PROV_DRBG *drbg)
111
81.6k
{
112
81.6k
    OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
113
81.6k
    void *parent = drbg->parent;
114
81.6k
    unsigned int r = 0;
115
116
81.6k
    *params = OSSL_PARAM_construct_uint(OSSL_DRBG_PARAM_RESEED_COUNTER, &r);
117
81.6k
    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
81.6k
    if (!drbg->parent_get_ctx_params(parent, params))
122
0
        r = 0;
123
81.6k
    ossl_drbg_unlock_parent(drbg);
124
81.6k
    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
81.6k
}
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
20
{
150
20
    PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
151
20
    size_t bytes_needed;
152
20
    unsigned char *buffer;
153
154
    /* Figure out how many bytes we need */
155
20
    bytes_needed = entropy >= 0 ? (entropy + 7) / 8 : 0;
156
20
    if (bytes_needed < min_len)
157
4
        bytes_needed = min_len;
158
20
    if (bytes_needed > max_len)
159
0
        bytes_needed = max_len;
160
161
    /* Allocate storage */
162
20
    buffer = OPENSSL_secure_malloc(bytes_needed);
163
20
    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
20
    if (!ossl_prov_drbg_generate(drbg, buffer, bytes_needed,
176
20
                                 drbg->strength, prediction_resistance,
177
20
                                 (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
20
    *pout = buffer;
183
20
    return bytes_needed;
184
20
}
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
20
{
190
20
    OPENSSL_secure_clear_free(out, outlen);
191
20
}
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
9
{
197
9
    size_t bytes;
198
9
    unsigned int p_str;
199
200
9
    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
0
        return ossl_prov_get_entropy(drbg->provctx, pout, entropy, min_len,
211
0
                                     max_len);
212
9
#endif
213
214
9
    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
9
    if (!get_parent_strength(drbg, &p_str))
219
0
        return 0;
220
9
    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
9
    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
9
    bytes = drbg->parent_get_seed(drbg->parent, pout, drbg->strength,
246
9
                                  min_len, max_len, prediction_resistance,
247
9
                                  (unsigned char *)&drbg, sizeof(drbg));
248
9
    ossl_drbg_unlock_parent(drbg);
249
9
    return bytes;
250
9
}
251
252
static void cleanup_entropy(PROV_DRBG *drbg, unsigned char *out, size_t outlen)
253
235
{
254
235
    if (drbg->parent == NULL) {
255
#ifdef FIPS_MODULE
256
        ossl_crngt_cleanup_entropy(drbg, out, outlen);
257
#else
258
208
        ossl_prov_cleanup_entropy(drbg->provctx, out, outlen);
259
208
#endif
260
208
    } else if (drbg->parent_clear_seed != NULL) {
261
27
        if (!ossl_drbg_lock_parent(drbg))
262
0
            return;
263
27
        drbg->parent_clear_seed(drbg->parent, out, outlen);
264
27
        ossl_drbg_unlock_parent(drbg);
265
27
    }
266
235
}
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
151
{
283
151
    PROV_DRBG_NONCE_GLOBAL *dngbl = OPENSSL_zalloc(sizeof(*dngbl));
284
285
151
    if (dngbl == NULL)
286
0
        return NULL;
287
288
151
    dngbl->rand_nonce_lock = CRYPTO_THREAD_lock_new();
289
151
    if (dngbl->rand_nonce_lock == NULL) {
290
0
        OPENSSL_free(dngbl);
291
0
        return NULL;
292
0
    }
293
294
151
    return dngbl;
295
151
}
296
297
void ossl_prov_drbg_nonce_ctx_free(void *vdngbl)
298
99
{
299
99
    PROV_DRBG_NONCE_GLOBAL *dngbl = vdngbl;
300
301
99
    if (dngbl == NULL)
302
0
        return;
303
304
99
    CRYPTO_THREAD_lock_free(dngbl->rand_nonce_lock);
305
306
99
    OPENSSL_free(dngbl);
307
99
}
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
100
{
313
100
    size_t ret = 0, n;
314
100
    unsigned char *buf = NULL;
315
100
    OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(drbg->provctx);
316
100
    PROV_DRBG_NONCE_GLOBAL *dngbl
317
100
        = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DRBG_NONCE_INDEX);
318
100
    struct {
319
100
        void *drbg;
320
100
        int count;
321
100
    } data;
322
323
100
    if (dngbl == NULL)
324
0
        return 0;
325
326
100
    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
100
    memset(&data, 0, sizeof(data));
342
100
    data.drbg = drbg;
343
100
    if (!CRYPTO_atomic_add(&dngbl->rand_nonce_count, 1, &data.count,
344
100
                           dngbl->rand_nonce_lock))
345
0
        return 0;
346
100
    return ossl_prov_get_nonce(drbg->provctx, pout, min_len, max_len,
347
100
                               &data, sizeof(data));
348
100
}
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
117
{
363
117
    unsigned char *nonce = NULL, *entropy = NULL;
364
117
    size_t noncelen = 0, entropylen = 0;
365
117
    size_t min_entropy, min_entropylen, max_entropylen;
366
367
117
    if (strength > drbg->strength) {
368
0
        ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
369
0
        goto end;
370
0
    }
371
117
    min_entropy = drbg->strength;
372
117
    min_entropylen = drbg->min_entropylen;
373
117
    max_entropylen = drbg->max_entropylen;
374
375
117
    if (pers == NULL) {
376
117
        pers = (const unsigned char *)ossl_pers_string;
377
117
        perslen = sizeof(ossl_pers_string);
378
117
    }
379
117
    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
117
    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
117
    drbg->state = EVP_RAND_STATE_ERROR;
393
394
117
    if (drbg->min_noncelen > 0) {
395
116
        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,
409
0
                                               drbg->strength,
410
0
                                               drbg->min_noncelen,
411
0
                                               drbg->max_noncelen)) {
412
0
                ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
413
0
                goto end;
414
0
            }
415
0
#ifndef PROV_RAND_GET_RANDOM_NONCE
416
116
        } else if (drbg->parent != NULL) {
417
16
#endif
418
            /*
419
             * NIST SP800-90Ar1 section 9.1 says you can combine getting
420
             * the entropy and nonce in 1 call by increasing the entropy
421
             * with 50% and increasing the minimum length to accommodate
422
             * the length of the nonce. We do this in case a nonce is
423
             * required and there is no parental nonce capability.
424
             */
425
16
            min_entropy += drbg->strength / 2;
426
16
            min_entropylen += drbg->min_noncelen;
427
16
            max_entropylen += drbg->max_noncelen;
428
16
        }
429
100
#ifndef PROV_RAND_GET_RANDOM_NONCE
430
100
        else { /* parent == NULL */
431
100
            noncelen = prov_drbg_get_nonce(drbg, &nonce, drbg->min_noncelen, 
432
100
                                           drbg->max_noncelen);
433
100
            if (noncelen < drbg->min_noncelen
434
100
                    || noncelen > drbg->max_noncelen) {
435
0
                ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
436
0
                goto end;
437
0
            }
438
100
        }
439
116
#endif
440
116
    }
441
442
117
    drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
443
117
    if (drbg->reseed_next_counter) {
444
117
        drbg->reseed_next_counter++;
445
117
        if (!drbg->reseed_next_counter)
446
0
            drbg->reseed_next_counter = 1;
447
117
    }
448
449
117
    entropylen = get_entropy(drbg, &entropy, min_entropy,
450
117
                             min_entropylen, max_entropylen,
451
117
                             prediction_resistance);
452
117
    if (entropylen < min_entropylen
453
117
            || entropylen > max_entropylen) {
454
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
455
0
        goto end;
456
0
    }
457
458
117
    if (!drbg->instantiate(drbg, entropy, entropylen, nonce, noncelen,
459
117
                           pers, perslen)) {
460
4
        cleanup_entropy(drbg, entropy, entropylen);
461
4
        ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_INSTANTIATING_DRBG);
462
4
        goto end;
463
4
    }
464
113
    cleanup_entropy(drbg, entropy, entropylen);
465
466
113
    drbg->state = EVP_RAND_STATE_READY;
467
113
    drbg->generate_counter = 1;
468
113
    drbg->reseed_time = time(NULL);
469
113
    tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
470
471
117
 end:
472
117
    if (nonce != NULL)
473
100
        ossl_prov_cleanup_nonce(drbg->provctx, nonce, noncelen);
474
117
    if (drbg->state == EVP_RAND_STATE_READY)
475
113
        return 1;
476
4
    return 0;
477
117
}
478
479
/*
480
 * Uninstantiate |drbg|. Must be instantiated before it can be used.
481
 *
482
 * Requires that drbg->lock is already locked for write, if non-null.
483
 *
484
 * Returns 1 on success, 0 on failure.
485
 */
486
int ossl_prov_drbg_uninstantiate(PROV_DRBG *drbg)
487
0
{
488
0
    drbg->state = EVP_RAND_STATE_UNINITIALISED;
489
0
    return 1;
490
0
}
491
492
static int ossl_prov_drbg_reseed_unlocked(PROV_DRBG *drbg,
493
                                          int prediction_resistance,
494
                                          const unsigned char *ent,
495
                                          size_t ent_len,
496
                                          const unsigned char *adin,
497
                                          size_t adinlen)
498
116
{
499
116
    unsigned char *entropy = NULL;
500
116
    size_t entropylen = 0;
501
502
116
    if (!ossl_prov_is_running())
503
0
        return 0;
504
505
116
    if (drbg->state != EVP_RAND_STATE_READY) {
506
        /* try to recover from previous errors */
507
0
        rand_drbg_restart(drbg);
508
509
0
        if (drbg->state == EVP_RAND_STATE_ERROR) {
510
0
            ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
511
0
            return 0;
512
0
        }
513
0
        if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
514
0
            ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
515
0
            return 0;
516
0
        }
517
0
    }
518
519
116
    if (ent != NULL) {
520
0
        if (ent_len < drbg->min_entropylen) {
521
0
            ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_OUT_OF_RANGE);
522
0
            drbg->state = EVP_RAND_STATE_ERROR;
523
0
            return 0;
524
0
        }
525
0
        if (ent_len > drbg->max_entropylen) {
526
0
            ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_INPUT_TOO_LONG);
527
0
            drbg->state = EVP_RAND_STATE_ERROR;
528
0
            return 0;
529
0
        }
530
0
    }
531
532
116
    if (adin == NULL) {
533
116
        adinlen = 0;
534
116
    } else if (adinlen > drbg->max_adinlen) {
535
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
536
0
        return 0;
537
0
    }
538
539
116
    drbg->state = EVP_RAND_STATE_ERROR;
540
541
116
    drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
542
116
    if (drbg->reseed_next_counter) {
543
116
        drbg->reseed_next_counter++;
544
116
        if (!drbg->reseed_next_counter)
545
0
            drbg->reseed_next_counter = 1;
546
116
    }
547
548
116
    if (ent != NULL) {
549
#ifdef FIPS_MODULE
550
        /*
551
         * NIST SP-800-90A mandates that entropy *shall not* be provided
552
         * by the consuming application. Instead the data is added as additional
553
         * input.
554
         *
555
         * (NIST SP-800-90Ar1, Sections 9.1 and 9.2)
556
         */
557
        if (!drbg->reseed(drbg, NULL, 0, ent, ent_len)) {
558
            ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_RESEED);
559
            return 0;
560
        }
561
#else
562
0
        if (!drbg->reseed(drbg, ent, ent_len, adin, adinlen)) {
563
0
            ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_RESEED);
564
0
            return 0;
565
0
        }
566
        /* There isn't much point adding the same additional input twice */
567
0
        adin = NULL;
568
0
        adinlen = 0;
569
0
#endif
570
0
    }
571
572
    /* Reseed using our sources in addition */
573
116
    entropylen = get_entropy(drbg, &entropy, drbg->strength,
574
116
                             drbg->min_entropylen, drbg->max_entropylen,
575
116
                             prediction_resistance);
576
116
    if (entropylen < drbg->min_entropylen
577
116
            || entropylen > drbg->max_entropylen) {
578
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
579
0
        goto end;
580
0
    }
581
582
116
    if (!drbg->reseed(drbg, entropy, entropylen, adin, adinlen))
583
0
        goto end;
584
585
116
    drbg->state = EVP_RAND_STATE_READY;
586
116
    drbg->generate_counter = 1;
587
116
    drbg->reseed_time = time(NULL);
588
116
    tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
589
116
    if (drbg->parent != NULL)
590
8
        drbg->parent_reseed_counter = get_parent_reseed_count(drbg);
591
592
116
 end:
593
116
    cleanup_entropy(drbg, entropy, entropylen);
594
116
    if (drbg->state == EVP_RAND_STATE_READY)
595
116
        return 1;
596
0
    return 0;
597
116
}
598
599
/*
600
 * Reseed |drbg|, mixing in the specified data
601
 *
602
 * Acquires the drbg->lock for writing, if non-null.
603
 *
604
 * Returns 1 on success, 0 on failure.
605
 */
606
int ossl_prov_drbg_reseed(PROV_DRBG *drbg, int prediction_resistance,
607
                          const unsigned char *ent, size_t ent_len,
608
                          const unsigned char *adin, size_t adinlen)
609
89
{
610
89
    int ret;
611
612
89
    if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
613
0
        return 0;
614
615
89
    ret = ossl_prov_drbg_reseed_unlocked(drbg, prediction_resistance, ent,
616
89
                                         ent_len, adin, adinlen);
617
618
89
    if (drbg->lock != NULL)
619
0
        CRYPTO_THREAD_unlock(drbg->lock);
620
621
89
    return ret;
622
89
}
623
624
/*
625
 * Generate |outlen| bytes into the buffer at |out|.  Reseed if we need
626
 * to or if |prediction_resistance| is set.  Additional input can be
627
 * sent in |adin| and |adinlen|.
628
 *
629
 * Acquires the drbg->lock for writing if available
630
 *
631
 * Returns 1 on success, 0 on failure.
632
 *
633
 */
634
int ossl_prov_drbg_generate(PROV_DRBG *drbg, unsigned char *out, size_t outlen,
635
                            unsigned int strength, int prediction_resistance,
636
                            const unsigned char *adin, size_t adinlen)
637
35.8k
{
638
35.8k
    int fork_id;
639
35.8k
    int reseed_required = 0;
640
35.8k
    int ret = 0;
641
642
35.8k
    if (!ossl_prov_is_running())
643
0
        return 0;
644
645
35.8k
    if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
646
0
        return 0;
647
648
35.8k
    if (drbg->state != EVP_RAND_STATE_READY) {
649
        /* try to recover from previous errors */
650
100
        rand_drbg_restart(drbg);
651
652
100
        if (drbg->state == EVP_RAND_STATE_ERROR) {
653
4
            ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
654
4
            goto err;
655
4
        }
656
96
        if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
657
0
            ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
658
0
            goto err;
659
0
        }
660
96
    }
661
35.7k
    if (strength > drbg->strength) {
662
0
        ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
663
0
        goto err;
664
0
    }
665
666
35.7k
    if (outlen > drbg->max_request) {
667
0
        ERR_raise(ERR_LIB_PROV, PROV_R_REQUEST_TOO_LARGE_FOR_DRBG);
668
0
        goto err;
669
0
    }
670
35.7k
    if (adinlen > drbg->max_adinlen) {
671
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
672
0
        goto err;
673
0
    }
674
675
35.7k
    fork_id = openssl_get_fork_id();
676
677
35.7k
    if (drbg->fork_id != fork_id) {
678
0
        drbg->fork_id = fork_id;
679
0
        reseed_required = 1;
680
0
    }
681
682
35.7k
    if (drbg->reseed_interval > 0) {
683
35.7k
        if (drbg->generate_counter >= drbg->reseed_interval)
684
19
            reseed_required = 1;
685
35.7k
    }
686
35.7k
    if (drbg->reseed_time_interval > 0) {
687
35.7k
        time_t now = time(NULL);
688
35.7k
        if (now < drbg->reseed_time
689
35.7k
            || now - drbg->reseed_time >= drbg->reseed_time_interval)
690
0
            reseed_required = 1;
691
35.7k
    }
692
35.7k
    if (drbg->parent != NULL
693
35.7k
            && get_parent_reseed_count(drbg) != drbg->parent_reseed_counter)
694
8
        reseed_required = 1;
695
696
35.7k
    if (reseed_required || prediction_resistance) {
697
27
        if (!ossl_prov_drbg_reseed_unlocked(drbg, prediction_resistance, NULL,
698
27
                                            0, adin, adinlen)) {
699
0
            ERR_raise(ERR_LIB_PROV, PROV_R_RESEED_ERROR);
700
0
            goto err;
701
0
        }
702
27
        adin = NULL;
703
27
        adinlen = 0;
704
27
    }
705
706
35.7k
    if (!drbg->generate(drbg, out, outlen, adin, adinlen)) {
707
7
        drbg->state = EVP_RAND_STATE_ERROR;
708
7
        ERR_raise(ERR_LIB_PROV, PROV_R_GENERATE_ERROR);
709
7
        goto err;
710
7
    }
711
712
35.7k
    drbg->generate_counter++;
713
714
35.7k
    ret = 1;
715
35.8k
 err:
716
35.8k
    if (drbg->lock != NULL)
717
16
        CRYPTO_THREAD_unlock(drbg->lock);
718
719
35.8k
    return ret;
720
35.7k
}
721
722
/*
723
 * Restart |drbg|, using the specified entropy or additional input
724
 *
725
 * Tries its best to get the drbg instantiated by all means,
726
 * regardless of its current state.
727
 *
728
 * Optionally, a |buffer| of |len| random bytes can be passed,
729
 * which is assumed to contain at least |entropy| bits of entropy.
730
 *
731
 * If |entropy| > 0, the buffer content is used as entropy input.
732
 *
733
 * If |entropy| == 0, the buffer content is used as additional input
734
 *
735
 * Returns 1 on success, 0 on failure.
736
 *
737
 * This function is used internally only.
738
 */
739
static int rand_drbg_restart(PROV_DRBG *drbg)
740
100
{
741
    /* repair error state */
742
100
    if (drbg->state == EVP_RAND_STATE_ERROR)
743
0
        drbg->uninstantiate(drbg);
744
745
    /* repair uninitialized state */
746
100
    if (drbg->state == EVP_RAND_STATE_UNINITIALISED)
747
        /* reinstantiate drbg */
748
100
        ossl_prov_drbg_instantiate(drbg, drbg->strength, 0, NULL, 0);
749
750
100
    return drbg->state == EVP_RAND_STATE_READY;
751
100
}
752
753
/* Provider support from here down */
754
static const OSSL_DISPATCH *find_call(const OSSL_DISPATCH *dispatch,
755
                                      int function)
756
1.19k
{
757
1.19k
    if (dispatch != NULL)
758
1.38k
        while (dispatch->function_id != 0) {
759
1.37k
            if (dispatch->function_id == function)
760
102
                return dispatch;
761
1.27k
            dispatch++;
762
1.27k
        }
763
1.08k
    return NULL;
764
1.19k
}
765
766
int ossl_drbg_enable_locking(void *vctx)
767
7
{
768
7
    PROV_DRBG *drbg = vctx;
769
770
7
    if (drbg != NULL && drbg->lock == NULL) {
771
7
        if (drbg->parent_enable_locking != NULL)
772
7
            if (!drbg->parent_enable_locking(drbg->parent)) {
773
0
                ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
774
0
                return 0;
775
0
            }
776
7
        drbg->lock = CRYPTO_THREAD_lock_new();
777
7
        if (drbg->lock == NULL) {
778
0
            ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_CREATE_LOCK);
779
0
            return 0;
780
0
        }
781
7
    }
782
7
    return 1;
783
7
}
784
785
/*
786
 * Allocate memory and initialize a new DRBG. The DRBG is allocated on
787
 * the secure heap if |secure| is nonzero and the secure heap is enabled.
788
 * The |parent|, if not NULL, will be used as random source for reseeding.
789
 * This also requires the parent's provider context and the parent's lock.
790
 *
791
 * Returns a pointer to the new DRBG instance on success, NULL on failure.
792
 */
793
PROV_DRBG *ossl_rand_drbg_new
794
    (void *provctx, void *parent, const OSSL_DISPATCH *p_dispatch,
795
     int (*dnew)(PROV_DRBG *ctx),
796
     void (*dfree)(void *vctx),
797
     int (*instantiate)(PROV_DRBG *drbg,
798
                        const unsigned char *entropy, size_t entropylen,
799
                        const unsigned char *nonce, size_t noncelen,
800
                        const unsigned char *pers, size_t perslen),
801
     int (*uninstantiate)(PROV_DRBG *ctx),
802
     int (*reseed)(PROV_DRBG *drbg, const unsigned char *ent, size_t ent_len,
803
                   const unsigned char *adin, size_t adin_len),
804
     int (*generate)(PROV_DRBG *, unsigned char *out, size_t outlen,
805
                     const unsigned char *adin, size_t adin_len))
806
170
{
807
170
    PROV_DRBG *drbg;
808
170
    unsigned int p_str;
809
170
    const OSSL_DISPATCH *pfunc;
810
811
170
    if (!ossl_prov_is_running())
812
0
        return NULL;
813
814
170
    drbg = OPENSSL_zalloc(sizeof(*drbg));
815
170
    if (drbg == NULL)
816
0
        return NULL;
817
818
170
    drbg->provctx = provctx;
819
170
    drbg->instantiate = instantiate;
820
170
    drbg->uninstantiate = uninstantiate;
821
170
    drbg->reseed = reseed;
822
170
    drbg->generate = generate;
823
170
    drbg->fork_id = openssl_get_fork_id();
824
825
    /* Extract parent's functions */
826
170
    drbg->parent = parent;
827
170
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_ENABLE_LOCKING)) != NULL)
828
17
        drbg->parent_enable_locking = OSSL_FUNC_rand_enable_locking(pfunc);
829
170
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_LOCK)) != NULL)
830
17
        drbg->parent_lock = OSSL_FUNC_rand_lock(pfunc);
831
170
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_UNLOCK)) != NULL)
832
17
        drbg->parent_unlock = OSSL_FUNC_rand_unlock(pfunc);
833
170
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_CTX_PARAMS)) != NULL)
834
17
        drbg->parent_get_ctx_params = OSSL_FUNC_rand_get_ctx_params(pfunc);
835
170
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_NONCE)) != NULL)
836
0
        drbg->parent_nonce = OSSL_FUNC_rand_nonce(pfunc);
837
170
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_SEED)) != NULL)
838
17
        drbg->parent_get_seed = OSSL_FUNC_rand_get_seed(pfunc);
839
170
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_CLEAR_SEED)) != NULL)
840
17
        drbg->parent_clear_seed = OSSL_FUNC_rand_clear_seed(pfunc);
841
842
    /* Set some default maximums up */
843
170
    drbg->max_entropylen = DRBG_MAX_LENGTH;
844
170
    drbg->max_noncelen = DRBG_MAX_LENGTH;
845
170
    drbg->max_perslen = DRBG_MAX_LENGTH;
846
170
    drbg->max_adinlen = DRBG_MAX_LENGTH;
847
170
    drbg->generate_counter = 1;
848
170
    drbg->reseed_counter = 1;
849
170
    drbg->reseed_interval = RESEED_INTERVAL;
850
170
    drbg->reseed_time_interval = TIME_INTERVAL;
851
852
170
    if (!dnew(drbg))
853
0
        goto err;
854
855
170
    if (parent != NULL) {
856
17
        if (!get_parent_strength(drbg, &p_str))
857
0
            goto err;
858
17
        if (drbg->strength > p_str) {
859
            /*
860
             * We currently don't support the algorithm from NIST SP 800-90C
861
             * 10.1.2 to use a weaker DRBG as source
862
             */
863
0
            ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_STRENGTH_TOO_WEAK);
864
0
            goto err;
865
0
        }
866
17
    }
867
#ifdef TSAN_REQUIRES_LOCKING
868
    if (!ossl_drbg_enable_locking(drbg))
869
        goto err;
870
#endif
871
170
    return drbg;
872
873
0
 err:
874
0
    dfree(drbg);
875
0
    return NULL;
876
170
}
877
878
void ossl_rand_drbg_free(PROV_DRBG *drbg)
879
170
{
880
170
    if (drbg == NULL)
881
0
        return;
882
883
170
    CRYPTO_THREAD_lock_free(drbg->lock);
884
170
    OPENSSL_free(drbg);
885
170
}
886
887
/*
888
 * Helper function called by internal DRBG implementations. Assumes that at
889
 * least a read lock has been taken on drbg->lock
890
 */
891
int ossl_drbg_get_ctx_params(PROV_DRBG *drbg, OSSL_PARAM params[])
892
3
{
893
3
    OSSL_PARAM *p;
894
895
3
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STATE);
896
3
    if (p != NULL && !OSSL_PARAM_set_int(p, drbg->state))
897
0
        return 0;
898
899
3
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STRENGTH);
900
3
    if (p != NULL && !OSSL_PARAM_set_int(p, drbg->strength))
901
0
        return 0;
902
903
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_ENTROPYLEN);
904
3
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_entropylen))
905
0
        return 0;
906
907
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ENTROPYLEN);
908
3
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_entropylen))
909
0
        return 0;
910
911
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_NONCELEN);
912
3
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_noncelen))
913
0
        return 0;
914
915
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_NONCELEN);
916
3
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_noncelen))
917
0
        return 0;
918
919
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_PERSLEN);
920
3
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_perslen))
921
0
        return 0;
922
923
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ADINLEN);
924
3
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_adinlen))
925
0
        return 0;
926
927
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
928
3
    if (p != NULL && !OSSL_PARAM_set_uint(p, drbg->reseed_interval))
929
0
        return 0;
930
931
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME);
932
3
    if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time))
933
0
        return 0;
934
935
3
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
936
3
    if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time_interval))
937
0
        return 0;
938
939
3
    return 1;
940
3
}
941
942
/*
943
 * Helper function to get certain params that require no lock to obtain. Sets
944
 * *complete to 1 if all the params were processed, or 0 otherwise
945
 */
946
int ossl_drbg_get_ctx_params_no_lock(PROV_DRBG *drbg, OSSL_PARAM params[],
947
                                     int *complete)
948
71.5k
{
949
71.5k
    size_t cnt = 0;
950
71.5k
    OSSL_PARAM *p;
951
952
    /* This value never changes once set */
953
71.5k
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_MAX_REQUEST);
954
71.5k
    if (p != NULL) {
955
35.7k
        if (!OSSL_PARAM_set_size_t(p, drbg->max_request))
956
0
            return 0;
957
35.7k
        cnt++;
958
35.7k
    }
959
960
    /*
961
     * Can be changed by multiple threads, but we tolerate inaccuracies in this
962
     * value.
963
     */
964
71.5k
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_COUNTER);
965
71.5k
    if (p != NULL) {
966
35.6k
        if (!OSSL_PARAM_set_uint(p, tsan_load(&drbg->reseed_counter)))
967
0
            return 0;
968
35.6k
        cnt++;
969
35.6k
    }
970
971
71.5k
    if (params[cnt].key == NULL)
972
71.4k
        *complete = 1;
973
24
    else
974
24
        *complete = 0;
975
976
71.5k
    return 1;
977
71.5k
}
978
979
int ossl_drbg_set_ctx_params(PROV_DRBG *drbg, const OSSL_PARAM params[])
980
6
{
981
6
    const OSSL_PARAM *p;
982
983
6
    if (params == NULL)
984
0
        return 1;
985
986
6
    p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
987
6
    if (p != NULL && !OSSL_PARAM_get_uint(p, &drbg->reseed_interval))
988
0
        return 0;
989
990
6
    p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
991
6
    if (p != NULL && !OSSL_PARAM_get_time_t(p, &drbg->reseed_time_interval))
992
0
        return 0;
993
6
    return 1;
994
6
}
995
996
/* Confirm digest is allowed to be used with a DRBG */
997
int ossl_drbg_verify_digest(ossl_unused OSSL_LIB_CTX *libctx, const EVP_MD *md)
998
{
999
#ifdef FIPS_MODULE
1000
    /* FIPS 140-3 IG D.R limited DRBG digests to a specific set */
1001
    static const char *const allowed_digests[] = {
1002
        "SHA1",                     /* SHA 1 allowed */
1003
        "SHA2-256", "SHA2-512",     /* non-truncated SHA2 allowed */
1004
        "SHA3-256", "SHA3-512",     /* non-truncated SHA3 allowed */
1005
    };
1006
    size_t i;
1007
1008
    if (FIPS_restricted_drbg_digests_enabled(libctx)) {
1009
        for (i = 0; i < OSSL_NELEM(allowed_digests); i++)
1010
            if (EVP_MD_is_a(md, allowed_digests[i]))
1011
                return 1;
1012
        ERR_raise(ERR_LIB_PROV, PROV_R_DIGEST_NOT_ALLOWED);
1013
        return 0;
1014
    }
1015
#endif
1016
    /* Outside of FIPS, any digests that are not XOF are allowed */
1017
    if ((EVP_MD_get_flags(md) & EVP_MD_FLAG_XOF) != 0) {
1018
        ERR_raise(ERR_LIB_PROV, PROV_R_XOF_DIGESTS_NOT_ALLOWED);
1019
        return 0;
1020
    }
1021
    return 1;
1022
}