Coverage Report

Created: 2023-06-07 07:24

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