Coverage Report

Created: 2024-05-21 06:52

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