Coverage Report

Created: 2025-12-31 06:58

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