Coverage Report

Created: 2025-12-31 06:58

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