Coverage Report

Created: 2025-07-11 06:57

/src/openssl/providers/implementations/rands/drbg.c
Line
Count
Source (jump to first uncovered line)
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
272
{
55
272
    return 1;
56
272
}
57
58
/* Interpreted as a hint only and ignored as for ossl_drbg_lock() */
59
void ossl_drbg_unlock(void *vctx)
60
272
{
61
272
}
62
63
static int ossl_drbg_lock_parent(PROV_DRBG *drbg)
64
384
{
65
384
    void *parent = drbg->parent;
66
67
384
    if (parent != NULL
68
384
            && drbg->parent_lock != NULL
69
384
            && !drbg->parent_lock(parent)) {
70
0
        ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
71
0
        return 0;
72
0
    }
73
384
    return 1;
74
384
}
75
76
static void ossl_drbg_unlock_parent(PROV_DRBG *drbg)
77
384
{
78
384
    void *parent = drbg->parent;
79
80
384
    if (parent != NULL && drbg->parent_unlock != NULL)
81
384
        drbg->parent_unlock(parent);
82
384
}
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
112
{
111
112
    OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
112
112
    void *parent = drbg->parent;
113
112
    unsigned int r = 0;
114
115
112
    *params = OSSL_PARAM_construct_uint(OSSL_DRBG_PARAM_RESEED_COUNTER, &r);
116
112
    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
112
    if (!drbg->parent_get_ctx_params(parent, params))
121
0
        r = 0;
122
112
    ossl_drbg_unlock_parent(drbg);
123
112
    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
112
}
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
32
{
149
32
    PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
150
32
    size_t bytes_needed;
151
32
    unsigned char *buffer;
152
153
    /* Figure out how many bytes we need */
154
32
    bytes_needed = entropy >= 0 ? (entropy + 7) / 8 : 0;
155
32
    if (bytes_needed < min_len)
156
0
        bytes_needed = min_len;
157
32
    if (bytes_needed > max_len)
158
0
        bytes_needed = max_len;
159
160
    /* Allocate storage */
161
32
    buffer = OPENSSL_secure_malloc(bytes_needed);
162
32
    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
32
    if (!ossl_prov_drbg_generate(drbg, buffer, bytes_needed,
175
32
                                 drbg->strength, prediction_resistance,
176
32
                                 (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
32
    *pout = buffer;
182
32
    return bytes_needed;
183
32
}
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
32
{
189
32
    OPENSSL_secure_clear_free(out, outlen);
190
32
}
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
80
{
196
80
    size_t bytes;
197
80
    unsigned int p_str;
198
199
80
    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
0
        return ossl_prov_get_entropy(drbg->provctx, pout, entropy, min_len,
205
0
                                     max_len);
206
207
80
    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
80
    if (!get_parent_strength(drbg, &p_str))
212
0
        return 0;
213
80
    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
80
    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
80
    bytes = drbg->parent_get_seed(drbg->parent, pout,
239
80
                                  entropy > 0 ? entropy : (int) drbg->strength,
240
80
                                  min_len, max_len, prediction_resistance,
241
80
                                  (unsigned char *)&drbg, sizeof(drbg));
242
80
    ossl_drbg_unlock_parent(drbg);
243
80
    return bytes;
244
80
}
245
246
static void cleanup_entropy(PROV_DRBG *drbg, unsigned char *out, size_t outlen)
247
80
{
248
80
    if (drbg->parent == NULL) {
249
0
        ossl_prov_cleanup_entropy(drbg->provctx, out, outlen);
250
80
    } else if (drbg->parent_clear_seed != NULL) {
251
80
        if (!ossl_drbg_lock_parent(drbg))
252
0
            return;
253
80
        drbg->parent_clear_seed(drbg->parent, out, outlen);
254
80
        ossl_drbg_unlock_parent(drbg);
255
80
    }
256
80
}
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
16
{
273
16
    PROV_DRBG_NONCE_GLOBAL *dngbl = OPENSSL_zalloc(sizeof(*dngbl));
274
275
16
    if (dngbl == NULL)
276
0
        return NULL;
277
278
16
    dngbl->rand_nonce_lock = CRYPTO_THREAD_lock_new();
279
16
    if (dngbl->rand_nonce_lock == NULL) {
280
0
        OPENSSL_free(dngbl);
281
0
        return NULL;
282
0
    }
283
284
16
    return dngbl;
285
16
}
286
287
void ossl_prov_drbg_nonce_ctx_free(void *vdngbl)
288
16
{
289
16
    PROV_DRBG_NONCE_GLOBAL *dngbl = vdngbl;
290
291
16
    if (dngbl == NULL)
292
0
        return;
293
294
16
    CRYPTO_THREAD_lock_free(dngbl->rand_nonce_lock);
295
296
16
    OPENSSL_free(dngbl);
297
16
}
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
0
{
303
0
    size_t ret = 0, n;
304
0
    unsigned char *buf = NULL;
305
0
    OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(drbg->provctx);
306
0
    PROV_DRBG_NONCE_GLOBAL *dngbl
307
0
        = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DRBG_NONCE_INDEX);
308
0
    struct {
309
0
        void *drbg;
310
0
        int count;
311
0
    } data;
312
313
0
    if (dngbl == NULL)
314
0
        return 0;
315
316
0
    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
0
    memset(&data, 0, sizeof(data));
332
0
    data.drbg = drbg;
333
0
    if (!CRYPTO_atomic_add(&dngbl->rand_nonce_count, 1, &data.count,
334
0
                           dngbl->rand_nonce_lock))
335
0
        return 0;
336
0
    return ossl_prov_get_nonce(drbg->provctx, pout, min_len, max_len,
337
0
                               &data, sizeof(data));
338
0
}
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
32
{
353
32
    unsigned char *nonce = NULL, *entropy = NULL;
354
32
    size_t noncelen = 0, entropylen = 0;
355
32
    unsigned int min_entropy;
356
32
    size_t min_entropylen, max_entropylen;
357
358
32
    if (strength > drbg->strength) {
359
0
        ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
360
0
        goto end;
361
0
    }
362
32
    min_entropy = drbg->strength;
363
32
    min_entropylen = drbg->min_entropylen;
364
32
    max_entropylen = drbg->max_entropylen;
365
366
32
    if (pers == NULL) {
367
32
        pers = (const unsigned char *)ossl_pers_string;
368
32
        perslen = sizeof(ossl_pers_string);
369
32
    }
370
32
    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
32
    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
32
    drbg->state = EVP_RAND_STATE_ERROR;
384
385
32
    if (drbg->min_noncelen > 0) {
386
32
        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
32
        } else if (drbg->parent != NULL) {
408
32
#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
32
            min_entropy += drbg->strength / 2;
417
32
            min_entropylen += drbg->min_noncelen;
418
32
            max_entropylen += drbg->max_noncelen;
419
32
        }
420
0
#ifndef PROV_RAND_GET_RANDOM_NONCE
421
0
        else { /* parent == NULL */
422
0
            noncelen = prov_drbg_get_nonce(drbg, &nonce, drbg->min_noncelen,
423
0
                                           drbg->max_noncelen);
424
0
            if (noncelen < drbg->min_noncelen
425
0
                    || noncelen > drbg->max_noncelen) {
426
0
                ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
427
0
                goto end;
428
0
            }
429
0
        }
430
32
#endif
431
32
    }
432
433
32
    drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
434
32
    if (drbg->reseed_next_counter) {
435
32
        drbg->reseed_next_counter++;
436
32
        if (!drbg->reseed_next_counter)
437
0
            drbg->reseed_next_counter = 1;
438
32
    }
439
440
32
    entropylen = get_entropy(drbg, &entropy, min_entropy,
441
32
                             min_entropylen, max_entropylen,
442
32
                             prediction_resistance);
443
32
    if (entropylen < min_entropylen
444
32
            || entropylen > max_entropylen) {
445
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
446
0
        goto end;
447
0
    }
448
449
32
    if (!drbg->instantiate(drbg, entropy, entropylen, nonce, noncelen,
450
32
                           pers, perslen)) {
451
0
        cleanup_entropy(drbg, entropy, entropylen);
452
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_INSTANTIATING_DRBG);
453
0
        goto end;
454
0
    }
455
32
    cleanup_entropy(drbg, entropy, entropylen);
456
457
32
    drbg->state = EVP_RAND_STATE_READY;
458
32
    drbg->generate_counter = 1;
459
32
    drbg->reseed_time = time(NULL);
460
32
    tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
461
462
32
 end:
463
32
    if (nonce != NULL)
464
0
        ossl_prov_cleanup_nonce(drbg->provctx, nonce, noncelen);
465
32
    if (drbg->state == EVP_RAND_STATE_READY)
466
32
        return 1;
467
0
    return 0;
468
32
}
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
48
{
490
48
    unsigned char *entropy = NULL;
491
48
    size_t entropylen = 0;
492
493
48
    if (!ossl_prov_is_running())
494
0
        return 0;
495
496
48
    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
48
    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
48
    if (adin == NULL) {
524
16
        adinlen = 0;
525
32
    } 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
48
    drbg->state = EVP_RAND_STATE_ERROR;
531
532
48
    drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
533
48
    if (drbg->reseed_next_counter) {
534
48
        drbg->reseed_next_counter++;
535
48
        if (!drbg->reseed_next_counter)
536
0
            drbg->reseed_next_counter = 1;
537
48
    }
538
539
48
    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
48
    entropylen = get_entropy(drbg, &entropy, drbg->strength,
565
48
                             drbg->min_entropylen, drbg->max_entropylen,
566
48
                             prediction_resistance);
567
48
    if (entropylen < drbg->min_entropylen
568
48
            || entropylen > drbg->max_entropylen) {
569
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
570
0
        goto end;
571
0
    }
572
573
48
    if (!drbg->reseed(drbg, entropy, entropylen, adin, adinlen))
574
0
        goto end;
575
576
48
    drbg->state = EVP_RAND_STATE_READY;
577
48
    drbg->generate_counter = 1;
578
48
    drbg->reseed_time = time(NULL);
579
48
    tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
580
48
    if (drbg->parent != NULL)
581
48
        drbg->parent_reseed_counter = get_parent_reseed_count(drbg);
582
583
48
 end:
584
48
    cleanup_entropy(drbg, entropy, entropylen);
585
48
    if (drbg->state == EVP_RAND_STATE_READY)
586
48
        return 1;
587
0
    return 0;
588
48
}
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
32
{
601
32
    int ret;
602
603
32
    if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
604
0
        return 0;
605
606
32
    ret = ossl_prov_drbg_reseed_unlocked(drbg, prediction_resistance, ent,
607
32
                                         ent_len, adin, adinlen);
608
609
32
    if (drbg->lock != NULL)
610
32
        CRYPTO_THREAD_unlock(drbg->lock);
611
612
32
    return ret;
613
32
}
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
64
{
629
64
    int fork_id;
630
64
    int reseed_required = 0;
631
64
    int ret = 0;
632
633
64
    if (!ossl_prov_is_running())
634
0
        return 0;
635
636
64
    if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
637
0
        return 0;
638
639
64
    if (drbg->state != EVP_RAND_STATE_READY) {
640
        /* try to recover from previous errors */
641
0
        rand_drbg_restart(drbg);
642
643
0
        if (drbg->state == EVP_RAND_STATE_ERROR) {
644
0
            ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
645
0
            goto err;
646
0
        }
647
0
        if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
648
0
            ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
649
0
            goto err;
650
0
        }
651
0
    }
652
64
    if (strength > drbg->strength) {
653
0
        ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
654
0
        goto err;
655
0
    }
656
657
64
    if (outlen > drbg->max_request) {
658
0
        ERR_raise(ERR_LIB_PROV, PROV_R_REQUEST_TOO_LARGE_FOR_DRBG);
659
0
        goto err;
660
0
    }
661
64
    if (adinlen > drbg->max_adinlen) {
662
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
663
0
        goto err;
664
0
    }
665
666
64
    fork_id = openssl_get_fork_id();
667
668
64
    if (drbg->fork_id != fork_id) {
669
0
        drbg->fork_id = fork_id;
670
0
        reseed_required = 1;
671
0
    }
672
673
64
    if (drbg->reseed_interval > 0) {
674
64
        if (drbg->generate_counter >= drbg->reseed_interval)
675
0
            reseed_required = 1;
676
64
    }
677
64
    if (drbg->reseed_time_interval > 0) {
678
64
        time_t now = time(NULL);
679
64
        if (now < drbg->reseed_time
680
64
            || now - drbg->reseed_time >= drbg->reseed_time_interval)
681
0
            reseed_required = 1;
682
64
    }
683
64
    if (drbg->parent != NULL
684
64
            && get_parent_reseed_count(drbg) != drbg->parent_reseed_counter)
685
16
        reseed_required = 1;
686
687
64
    if (reseed_required || prediction_resistance) {
688
16
        if (!ossl_prov_drbg_reseed_unlocked(drbg, prediction_resistance, NULL,
689
16
                                            0, adin, adinlen)) {
690
0
            ERR_raise(ERR_LIB_PROV, PROV_R_RESEED_ERROR);
691
0
            goto err;
692
0
        }
693
16
        adin = NULL;
694
16
        adinlen = 0;
695
16
    }
696
697
64
    if (!drbg->generate(drbg, out, outlen, adin, adinlen)) {
698
0
        drbg->state = EVP_RAND_STATE_ERROR;
699
0
        ERR_raise(ERR_LIB_PROV, PROV_R_GENERATE_ERROR);
700
0
        goto err;
701
0
    }
702
703
64
    drbg->generate_counter++;
704
705
64
    ret = 1;
706
64
 err:
707
64
    if (drbg->lock != NULL)
708
32
        CRYPTO_THREAD_unlock(drbg->lock);
709
710
64
    return ret;
711
64
}
712
713
/*
714
 * Restart |drbg|, using the specified entropy or additional input
715
 *
716
 * Tries its best to get the drbg instantiated by all means,
717
 * regardless of its current state.
718
 *
719
 * Optionally, a |buffer| of |len| random bytes can be passed,
720
 * which is assumed to contain at least |entropy| bits of entropy.
721
 *
722
 * If |entropy| > 0, the buffer content is used as entropy input.
723
 *
724
 * If |entropy| == 0, the buffer content is used as additional input
725
 *
726
 * Returns 1 on success, 0 on failure.
727
 *
728
 * This function is used internally only.
729
 */
730
static int rand_drbg_restart(PROV_DRBG *drbg)
731
0
{
732
    /* repair error state */
733
0
    if (drbg->state == EVP_RAND_STATE_ERROR)
734
0
        drbg->uninstantiate(drbg);
735
736
    /* repair uninitialized state */
737
0
    if (drbg->state == EVP_RAND_STATE_UNINITIALISED)
738
        /* reinstantiate drbg */
739
0
        ossl_prov_drbg_instantiate(drbg, drbg->strength, 0, NULL, 0);
740
741
0
    return drbg->state == EVP_RAND_STATE_READY;
742
0
}
743
744
/* Provider support from here down */
745
static const OSSL_DISPATCH *find_call(const OSSL_DISPATCH *dispatch,
746
                                      int function)
747
224
{
748
224
    if (dispatch != NULL)
749
2.59k
        while (dispatch->function_id != 0) {
750
2.56k
            if (dispatch->function_id == function)
751
192
                return dispatch;
752
2.36k
            dispatch++;
753
2.36k
        }
754
32
    return NULL;
755
224
}
756
757
int ossl_drbg_enable_locking(void *vctx)
758
16
{
759
16
    PROV_DRBG *drbg = vctx;
760
761
16
    if (drbg != NULL && drbg->lock == NULL) {
762
16
        if (drbg->parent_enable_locking != NULL)
763
16
            if (!drbg->parent_enable_locking(drbg->parent)) {
764
0
                ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
765
0
                return 0;
766
0
            }
767
16
        drbg->lock = CRYPTO_THREAD_lock_new();
768
16
        if (drbg->lock == NULL) {
769
0
            ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_CREATE_LOCK);
770
0
            return 0;
771
0
        }
772
16
    }
773
16
    return 1;
774
16
}
775
776
/*
777
 * Allocate memory and initialize a new DRBG. The DRBG is allocated on
778
 * the secure heap if |secure| is nonzero and the secure heap is enabled.
779
 * The |parent|, if not NULL, will be used as random source for reseeding.
780
 * This also requires the parent's provider context and the parent's lock.
781
 *
782
 * Returns a pointer to the new DRBG instance on success, NULL on failure.
783
 */
784
PROV_DRBG *ossl_rand_drbg_new
785
    (void *provctx, void *parent, const OSSL_DISPATCH *p_dispatch,
786
     int (*dnew)(PROV_DRBG *ctx),
787
     void (*dfree)(void *vctx),
788
     int (*instantiate)(PROV_DRBG *drbg,
789
                        const unsigned char *entropy, size_t entropylen,
790
                        const unsigned char *nonce, size_t noncelen,
791
                        const unsigned char *pers, size_t perslen),
792
     int (*uninstantiate)(PROV_DRBG *ctx),
793
     int (*reseed)(PROV_DRBG *drbg, const unsigned char *ent, size_t ent_len,
794
                   const unsigned char *adin, size_t adin_len),
795
     int (*generate)(PROV_DRBG *, unsigned char *out, size_t outlen,
796
                     const unsigned char *adin, size_t adin_len))
797
32
{
798
32
    PROV_DRBG *drbg;
799
32
    unsigned int p_str;
800
32
    const OSSL_DISPATCH *pfunc;
801
802
32
    if (!ossl_prov_is_running())
803
0
        return NULL;
804
805
32
    drbg = OPENSSL_zalloc(sizeof(*drbg));
806
32
    if (drbg == NULL)
807
0
        return NULL;
808
809
32
    drbg->provctx = provctx;
810
32
    drbg->instantiate = instantiate;
811
32
    drbg->uninstantiate = uninstantiate;
812
32
    drbg->reseed = reseed;
813
32
    drbg->generate = generate;
814
32
    drbg->fork_id = openssl_get_fork_id();
815
816
    /* Extract parent's functions */
817
32
    drbg->parent = parent;
818
32
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_ENABLE_LOCKING)) != NULL)
819
32
        drbg->parent_enable_locking = OSSL_FUNC_rand_enable_locking(pfunc);
820
32
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_LOCK)) != NULL)
821
32
        drbg->parent_lock = OSSL_FUNC_rand_lock(pfunc);
822
32
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_UNLOCK)) != NULL)
823
32
        drbg->parent_unlock = OSSL_FUNC_rand_unlock(pfunc);
824
32
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_CTX_PARAMS)) != NULL)
825
32
        drbg->parent_get_ctx_params = OSSL_FUNC_rand_get_ctx_params(pfunc);
826
32
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_NONCE)) != NULL)
827
0
        drbg->parent_nonce = OSSL_FUNC_rand_nonce(pfunc);
828
32
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_SEED)) != NULL)
829
32
        drbg->parent_get_seed = OSSL_FUNC_rand_get_seed(pfunc);
830
32
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_CLEAR_SEED)) != NULL)
831
32
        drbg->parent_clear_seed = OSSL_FUNC_rand_clear_seed(pfunc);
832
833
    /* Set some default maximums up */
834
32
    drbg->max_entropylen = DRBG_MAX_LENGTH;
835
32
    drbg->max_noncelen = DRBG_MAX_LENGTH;
836
32
    drbg->max_perslen = DRBG_MAX_LENGTH;
837
32
    drbg->max_adinlen = DRBG_MAX_LENGTH;
838
32
    drbg->generate_counter = 1;
839
32
    drbg->reseed_counter = 1;
840
32
    drbg->reseed_interval = RESEED_INTERVAL;
841
32
    drbg->reseed_time_interval = TIME_INTERVAL;
842
843
32
    if (!dnew(drbg))
844
0
        goto err;
845
846
32
    if (parent != NULL) {
847
32
        if (!get_parent_strength(drbg, &p_str))
848
0
            goto err;
849
32
        if (drbg->strength > p_str) {
850
            /*
851
             * We currently don't support the algorithm from NIST SP 800-90C
852
             * 10.1.2 to use a weaker DRBG as source
853
             */
854
0
            ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_STRENGTH_TOO_WEAK);
855
0
            goto err;
856
0
        }
857
32
    }
858
#ifdef TSAN_REQUIRES_LOCKING
859
    if (!ossl_drbg_enable_locking(drbg))
860
        goto err;
861
#endif
862
32
    return drbg;
863
864
0
 err:
865
0
    dfree(drbg);
866
0
    return NULL;
867
32
}
868
869
void ossl_rand_drbg_free(PROV_DRBG *drbg)
870
32
{
871
32
    if (drbg == NULL)
872
0
        return;
873
874
32
    CRYPTO_THREAD_lock_free(drbg->lock);
875
32
    OPENSSL_free(drbg);
876
32
}
877
878
/*
879
 * Helper function called by internal DRBG implementations. Assumes that at
880
 * least a read lock has been taken on drbg->lock
881
 */
882
int ossl_drbg_get_ctx_params(PROV_DRBG *drbg, OSSL_PARAM params[])
883
64
{
884
64
    OSSL_PARAM *p;
885
886
64
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STATE);
887
64
    if (p != NULL && !OSSL_PARAM_set_int(p, drbg->state))
888
0
        return 0;
889
890
64
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STRENGTH);
891
64
    if (p != NULL && !OSSL_PARAM_set_int(p, drbg->strength))
892
0
        return 0;
893
894
64
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_ENTROPYLEN);
895
64
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_entropylen))
896
0
        return 0;
897
898
64
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ENTROPYLEN);
899
64
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_entropylen))
900
0
        return 0;
901
902
64
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_NONCELEN);
903
64
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_noncelen))
904
0
        return 0;
905
906
64
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_NONCELEN);
907
64
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_noncelen))
908
0
        return 0;
909
910
64
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_PERSLEN);
911
64
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_perslen))
912
0
        return 0;
913
914
64
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ADINLEN);
915
64
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_adinlen))
916
0
        return 0;
917
918
64
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
919
64
    if (p != NULL && !OSSL_PARAM_set_uint(p, drbg->reseed_interval))
920
0
        return 0;
921
922
64
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME);
923
64
    if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time))
924
0
        return 0;
925
926
64
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
927
64
    if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time_interval))
928
0
        return 0;
929
64
    if (!OSSL_FIPS_IND_GET_CTX_PARAM(drbg, params))
930
0
        return 0;
931
64
    return 1;
932
64
}
933
934
/*
935
 * Helper function to get certain params that require no lock to obtain. Sets
936
 * *complete to 1 if all the params were processed, or 0 otherwise
937
 */
938
int ossl_drbg_get_ctx_params_no_lock(PROV_DRBG *drbg, OSSL_PARAM params[],
939
                                     int *complete)
940
144
{
941
144
    size_t cnt = 0;
942
144
    OSSL_PARAM *p;
943
944
    /* This value never changes once set */
945
144
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_MAX_REQUEST);
946
144
    if (p != NULL) {
947
32
        if (!OSSL_PARAM_set_size_t(p, drbg->max_request))
948
0
            return 0;
949
32
        cnt++;
950
32
    }
951
952
    /*
953
     * Can be changed by multiple threads, but we tolerate inaccuracies in this
954
     * value.
955
     */
956
144
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_COUNTER);
957
144
    if (p != NULL) {
958
48
        if (!OSSL_PARAM_set_uint(p, tsan_load(&drbg->reseed_counter)))
959
0
            return 0;
960
48
        cnt++;
961
48
    }
962
963
144
    if (params[cnt].key == NULL)
964
80
        *complete = 1;
965
64
    else
966
64
        *complete = 0;
967
968
144
    return 1;
969
144
}
970
971
int ossl_drbg_set_ctx_params(PROV_DRBG *drbg, const OSSL_PARAM params[])
972
32
{
973
32
    const OSSL_PARAM *p;
974
975
32
    if (ossl_param_is_empty(params))
976
0
        return 1;
977
978
32
    p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
979
32
    if (p != NULL && !OSSL_PARAM_get_uint(p, &drbg->reseed_interval))
980
0
        return 0;
981
982
32
    p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
983
32
    if (p != NULL && !OSSL_PARAM_get_time_t(p, &drbg->reseed_time_interval))
984
0
        return 0;
985
986
32
    return 1;
987
32
}
988
989
#ifdef FIPS_MODULE
990
static int digest_allowed(const EVP_MD *md)
991
{
992
    /* FIPS 140-3 IG D.R limited DRBG digests to a specific set */
993
    static const char *const allowed_digests[] = {
994
        "SHA1",                     /* SHA 1 allowed */
995
        "SHA2-256", "SHA2-512",     /* non-truncated SHA2 allowed */
996
        "SHA3-256", "SHA3-512",     /* non-truncated SHA3 allowed */
997
    };
998
    size_t i;
999
1000
    for (i = 0; i < OSSL_NELEM(allowed_digests); i++) {
1001
        if (EVP_MD_is_a(md, allowed_digests[i]))
1002
            return 1;
1003
    }
1004
    return 0;
1005
}
1006
#endif
1007
1008
/* Confirm digest is allowed to be used with a DRBG */
1009
int ossl_drbg_verify_digest(PROV_DRBG *drbg, OSSL_LIB_CTX *libctx,
1010
                            const EVP_MD *md)
1011
0
{
1012
#ifdef FIPS_MODULE
1013
    int approved = digest_allowed(md);
1014
1015
    if (!approved) {
1016
        if (!OSSL_FIPS_IND_ON_UNAPPROVED(drbg, OSSL_FIPS_IND_SETTABLE0,
1017
                                         libctx, "DRBG", "Digest",
1018
                                         ossl_fips_config_restricted_drbg_digests)) {
1019
            ERR_raise(ERR_LIB_PROV, PROV_R_DIGEST_NOT_ALLOWED);
1020
            return 0;
1021
        }
1022
    }
1023
#else   /* FIPS_MODULE */
1024
    /* Outside of FIPS, any digests that are not XOF are allowed */
1025
0
    if (EVP_MD_xof(md)) {
1026
0
        ERR_raise(ERR_LIB_PROV, PROV_R_XOF_DIGESTS_NOT_ALLOWED);
1027
0
        return 0;
1028
0
    }
1029
0
#endif  /* FIPS_MODULE */
1030
0
    return 1;
1031
0
}