Coverage Report

Created: 2025-06-13 06:56

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