Coverage Report

Created: 2025-12-04 06:33

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