Coverage Report

Created: 2023-09-25 06:45

/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
0
{
56
0
    return 1;
57
0
}
58
59
/* Interpreted as a hint only and ignored as for ossl_drbg_lock() */
60
void ossl_drbg_unlock(void *vctx)
61
0
{
62
0
}
63
64
static int ossl_drbg_lock_parent(PROV_DRBG *drbg)
65
0
{
66
0
    void *parent = drbg->parent;
67
68
0
    if (parent != NULL
69
0
            && drbg->parent_lock != NULL
70
0
            && !drbg->parent_lock(parent)) {
71
0
        ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
72
0
        return 0;
73
0
    }
74
0
    return 1;
75
0
}
76
77
static void ossl_drbg_unlock_parent(PROV_DRBG *drbg)
78
0
{
79
0
    void *parent = drbg->parent;
80
81
0
    if (parent != NULL && drbg->parent_unlock != NULL)
82
0
        drbg->parent_unlock(parent);
83
0
}
84
85
static int get_parent_strength(PROV_DRBG *drbg, unsigned int *str)
86
0
{
87
0
    OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
88
0
    void *parent = drbg->parent;
89
0
    int res;
90
91
0
    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
0
    *params = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, str);
97
0
    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
0
    res = drbg->parent_get_ctx_params(parent, params);
102
0
    ossl_drbg_unlock_parent(drbg);
103
0
    if (!res) {
104
0
        ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_GET_PARENT_STRENGTH);
105
0
        return 0;
106
0
    }
107
0
    return 1;
108
0
}
109
110
static unsigned int get_parent_reseed_count(PROV_DRBG *drbg)
111
0
{
112
0
    OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
113
0
    void *parent = drbg->parent;
114
0
    unsigned int r = 0;
115
116
0
    *params = OSSL_PARAM_construct_uint(OSSL_DRBG_PARAM_RESEED_COUNTER, &r);
117
0
    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
0
    if (!drbg->parent_get_ctx_params(parent, params))
122
0
        r = 0;
123
0
    ossl_drbg_unlock_parent(drbg);
124
0
    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
0
}
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
0
{
150
0
    PROV_DRBG *drbg = (PROV_DRBG *)vdrbg;
151
0
    size_t bytes_needed;
152
0
    unsigned char *buffer;
153
154
    /* Figure out how many bytes we need */
155
0
    bytes_needed = entropy >= 0 ? (entropy + 7) / 8 : 0;
156
0
    if (bytes_needed < min_len)
157
0
        bytes_needed = min_len;
158
0
    if (bytes_needed > max_len)
159
0
        bytes_needed = max_len;
160
161
    /* Allocate storage */
162
0
    buffer = OPENSSL_secure_malloc(bytes_needed);
163
0
    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
0
    if (!ossl_prov_drbg_generate(drbg, buffer, bytes_needed,
176
0
                                 drbg->strength, prediction_resistance,
177
0
                                 (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
0
    *pout = buffer;
183
0
    return bytes_needed;
184
0
}
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
0
{
190
0
    OPENSSL_secure_clear_free(out, outlen);
191
0
}
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
0
{
197
0
    size_t bytes;
198
0
    unsigned int p_str;
199
200
0
    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
0
#endif
208
209
0
    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
0
    if (!get_parent_strength(drbg, &p_str))
214
0
        return 0;
215
0
    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
0
    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
0
    bytes = drbg->parent_get_seed(drbg->parent, pout, drbg->strength,
241
0
                                  min_len, max_len, prediction_resistance,
242
0
                                  (unsigned char *)&drbg, sizeof(drbg));
243
0
    ossl_drbg_unlock_parent(drbg);
244
0
    return bytes;
245
0
}
246
247
static void cleanup_entropy(PROV_DRBG *drbg, unsigned char *out, size_t outlen)
248
0
{
249
0
    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
0
    } else if (drbg->parent_clear_seed != NULL) {
256
0
        if (!ossl_drbg_lock_parent(drbg))
257
0
            return;
258
0
        drbg->parent_clear_seed(drbg->parent, out, outlen);
259
0
        ossl_drbg_unlock_parent(drbg);
260
0
    }
261
0
}
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
4
{
278
4
    PROV_DRBG_NONCE_GLOBAL *dngbl = OPENSSL_zalloc(sizeof(*dngbl));
279
280
4
    if (dngbl == NULL)
281
0
        return NULL;
282
283
4
    dngbl->rand_nonce_lock = CRYPTO_THREAD_lock_new();
284
4
    if (dngbl->rand_nonce_lock == NULL) {
285
0
        OPENSSL_free(dngbl);
286
0
        return NULL;
287
0
    }
288
289
4
    return dngbl;
290
4
}
291
292
void ossl_prov_drbg_nonce_ctx_free(void *vdngbl)
293
2
{
294
2
    PROV_DRBG_NONCE_GLOBAL *dngbl = vdngbl;
295
296
2
    if (dngbl == NULL)
297
0
        return;
298
299
2
    CRYPTO_THREAD_lock_free(dngbl->rand_nonce_lock);
300
301
2
    OPENSSL_free(dngbl);
302
2
}
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
0
{
358
0
    unsigned char *nonce = NULL, *entropy = NULL;
359
0
    size_t noncelen = 0, entropylen = 0;
360
0
    size_t min_entropy, min_entropylen, max_entropylen;
361
362
0
    if (strength > drbg->strength) {
363
0
        ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
364
0
        goto end;
365
0
    }
366
0
    min_entropy = drbg->strength;
367
0
    min_entropylen = drbg->min_entropylen;
368
0
    max_entropylen = drbg->max_entropylen;
369
370
0
    if (pers == NULL) {
371
0
        pers = (const unsigned char *)ossl_pers_string;
372
0
        perslen = sizeof(ossl_pers_string);
373
0
    }
374
0
    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
0
    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
0
    drbg->state = EVP_RAND_STATE_ERROR;
388
389
0
    if (drbg->min_noncelen > 0) {
390
0
        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
0
        } else if (drbg->parent != NULL) {
412
0
#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
0
            min_entropy += drbg->strength / 2;
421
0
            min_entropylen += drbg->min_noncelen;
422
0
            max_entropylen += drbg->max_noncelen;
423
0
        }
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
0
#endif
435
0
    }
436
437
0
    drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
438
0
    if (drbg->reseed_next_counter) {
439
0
        drbg->reseed_next_counter++;
440
0
        if (!drbg->reseed_next_counter)
441
0
            drbg->reseed_next_counter = 1;
442
0
    }
443
444
0
    entropylen = get_entropy(drbg, &entropy, min_entropy,
445
0
                             min_entropylen, max_entropylen,
446
0
                             prediction_resistance);
447
0
    if (entropylen < min_entropylen
448
0
            || entropylen > max_entropylen) {
449
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
450
0
        goto end;
451
0
    }
452
453
0
    if (!drbg->instantiate(drbg, entropy, entropylen, nonce, noncelen,
454
0
                           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
0
    cleanup_entropy(drbg, entropy, entropylen);
460
461
0
    drbg->state = EVP_RAND_STATE_READY;
462
0
    drbg->generate_counter = 1;
463
0
    drbg->reseed_time = time(NULL);
464
0
    tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
465
466
0
 end:
467
0
    if (nonce != NULL)
468
0
        ossl_prov_cleanup_nonce(drbg->provctx, nonce, noncelen);
469
0
    if (drbg->state == EVP_RAND_STATE_READY)
470
0
        return 1;
471
0
    return 0;
472
0
}
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
0
{
494
0
    unsigned char *entropy = NULL;
495
0
    size_t entropylen = 0;
496
497
0
    if (!ossl_prov_is_running())
498
0
        return 0;
499
500
0
    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
0
    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
0
    if (adin == NULL) {
528
0
        adinlen = 0;
529
0
    } 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
0
    drbg->state = EVP_RAND_STATE_ERROR;
535
536
0
    drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
537
0
    if (drbg->reseed_next_counter) {
538
0
        drbg->reseed_next_counter++;
539
0
        if (!drbg->reseed_next_counter)
540
0
            drbg->reseed_next_counter = 1;
541
0
    }
542
543
0
    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
0
    entropylen = get_entropy(drbg, &entropy, drbg->strength,
569
0
                             drbg->min_entropylen, drbg->max_entropylen,
570
0
                             prediction_resistance);
571
0
    if (entropylen < drbg->min_entropylen
572
0
            || entropylen > drbg->max_entropylen) {
573
0
        ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
574
0
        goto end;
575
0
    }
576
577
0
    if (!drbg->reseed(drbg, entropy, entropylen, adin, adinlen))
578
0
        goto end;
579
580
0
    drbg->state = EVP_RAND_STATE_READY;
581
0
    drbg->generate_counter = 1;
582
0
    drbg->reseed_time = time(NULL);
583
0
    tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
584
0
    if (drbg->parent != NULL)
585
0
        drbg->parent_reseed_counter = get_parent_reseed_count(drbg);
586
587
0
 end:
588
0
    cleanup_entropy(drbg, entropy, entropylen);
589
0
    if (drbg->state == EVP_RAND_STATE_READY)
590
0
        return 1;
591
0
    return 0;
592
0
}
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
0
{
633
0
    int fork_id;
634
0
    int reseed_required = 0;
635
0
    int ret = 0;
636
637
0
    if (!ossl_prov_is_running())
638
0
        return 0;
639
640
0
    if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
641
0
        return 0;
642
643
0
    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
0
    if (strength > drbg->strength) {
657
0
        ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
658
0
        goto err;
659
0
    }
660
661
0
    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
0
    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
0
    fork_id = openssl_get_fork_id();
671
672
0
    if (drbg->fork_id != fork_id) {
673
0
        drbg->fork_id = fork_id;
674
0
        reseed_required = 1;
675
0
    }
676
677
0
    if (drbg->reseed_interval > 0) {
678
0
        if (drbg->generate_counter >= drbg->reseed_interval)
679
0
            reseed_required = 1;
680
0
    }
681
0
    if (drbg->reseed_time_interval > 0) {
682
0
        time_t now = time(NULL);
683
0
        if (now < drbg->reseed_time
684
0
            || now - drbg->reseed_time >= drbg->reseed_time_interval)
685
0
            reseed_required = 1;
686
0
    }
687
0
    if (drbg->parent != NULL
688
0
            && get_parent_reseed_count(drbg) != drbg->parent_reseed_counter)
689
0
        reseed_required = 1;
690
691
0
    if (reseed_required || prediction_resistance) {
692
0
        if (!ossl_prov_drbg_reseed_unlocked(drbg, prediction_resistance, NULL,
693
0
                                            0, adin, adinlen)) {
694
0
            ERR_raise(ERR_LIB_PROV, PROV_R_RESEED_ERROR);
695
0
            goto err;
696
0
        }
697
0
        adin = NULL;
698
0
        adinlen = 0;
699
0
    }
700
701
0
    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
0
    drbg->generate_counter++;
708
709
0
    ret = 1;
710
0
 err:
711
0
    if (drbg->lock != NULL)
712
0
        CRYPTO_THREAD_unlock(drbg->lock);
713
714
0
    return ret;
715
0
}
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
0
{
752
0
    if (dispatch != NULL)
753
0
        while (dispatch->function_id != 0) {
754
0
            if (dispatch->function_id == function)
755
0
                return dispatch;
756
0
            dispatch++;
757
0
        }
758
0
    return NULL;
759
0
}
760
761
int ossl_drbg_enable_locking(void *vctx)
762
0
{
763
0
    PROV_DRBG *drbg = vctx;
764
765
0
    if (drbg != NULL && drbg->lock == NULL) {
766
0
        if (drbg->parent_enable_locking != NULL)
767
0
            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
0
        drbg->lock = CRYPTO_THREAD_lock_new();
772
0
        if (drbg->lock == NULL) {
773
0
            ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_CREATE_LOCK);
774
0
            return 0;
775
0
        }
776
0
    }
777
0
    return 1;
778
0
}
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
0
{
801
0
    PROV_DRBG *drbg;
802
0
    unsigned int p_str;
803
0
    const OSSL_DISPATCH *pfunc;
804
805
0
    if (!ossl_prov_is_running())
806
0
        return NULL;
807
808
0
    drbg = OPENSSL_zalloc(sizeof(*drbg));
809
0
    if (drbg == NULL)
810
0
        return NULL;
811
812
0
    drbg->provctx = provctx;
813
0
    drbg->instantiate = instantiate;
814
0
    drbg->uninstantiate = uninstantiate;
815
0
    drbg->reseed = reseed;
816
0
    drbg->generate = generate;
817
0
    drbg->fork_id = openssl_get_fork_id();
818
819
    /* Extract parent's functions */
820
0
    drbg->parent = parent;
821
0
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_ENABLE_LOCKING)) != NULL)
822
0
        drbg->parent_enable_locking = OSSL_FUNC_rand_enable_locking(pfunc);
823
0
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_LOCK)) != NULL)
824
0
        drbg->parent_lock = OSSL_FUNC_rand_lock(pfunc);
825
0
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_UNLOCK)) != NULL)
826
0
        drbg->parent_unlock = OSSL_FUNC_rand_unlock(pfunc);
827
0
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_CTX_PARAMS)) != NULL)
828
0
        drbg->parent_get_ctx_params = OSSL_FUNC_rand_get_ctx_params(pfunc);
829
0
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_NONCE)) != NULL)
830
0
        drbg->parent_nonce = OSSL_FUNC_rand_nonce(pfunc);
831
0
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_SEED)) != NULL)
832
0
        drbg->parent_get_seed = OSSL_FUNC_rand_get_seed(pfunc);
833
0
    if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_CLEAR_SEED)) != NULL)
834
0
        drbg->parent_clear_seed = OSSL_FUNC_rand_clear_seed(pfunc);
835
836
    /* Set some default maximums up */
837
0
    drbg->max_entropylen = DRBG_MAX_LENGTH;
838
0
    drbg->max_noncelen = DRBG_MAX_LENGTH;
839
0
    drbg->max_perslen = DRBG_MAX_LENGTH;
840
0
    drbg->max_adinlen = DRBG_MAX_LENGTH;
841
0
    drbg->generate_counter = 1;
842
0
    drbg->reseed_counter = 1;
843
0
    drbg->reseed_interval = RESEED_INTERVAL;
844
0
    drbg->reseed_time_interval = TIME_INTERVAL;
845
846
0
    if (!dnew(drbg))
847
0
        goto err;
848
849
0
    if (parent != NULL) {
850
0
        if (!get_parent_strength(drbg, &p_str))
851
0
            goto err;
852
0
        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
0
    }
861
#ifdef TSAN_REQUIRES_LOCKING
862
    if (!ossl_drbg_enable_locking(drbg))
863
        goto err;
864
#endif
865
0
    return drbg;
866
867
0
 err:
868
0
    ossl_rand_drbg_free(drbg);
869
0
    return NULL;
870
0
}
871
872
void ossl_rand_drbg_free(PROV_DRBG *drbg)
873
0
{
874
0
    if (drbg == NULL)
875
0
        return;
876
877
0
    CRYPTO_THREAD_lock_free(drbg->lock);
878
0
    OPENSSL_free(drbg);
879
0
}
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
0
{
887
0
    OSSL_PARAM *p;
888
889
0
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STATE);
890
0
    if (p != NULL && !OSSL_PARAM_set_int(p, drbg->state))
891
0
        return 0;
892
893
0
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STRENGTH);
894
0
    if (p != NULL && !OSSL_PARAM_set_int(p, drbg->strength))
895
0
        return 0;
896
897
0
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_ENTROPYLEN);
898
0
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_entropylen))
899
0
        return 0;
900
901
0
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ENTROPYLEN);
902
0
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_entropylen))
903
0
        return 0;
904
905
0
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_NONCELEN);
906
0
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_noncelen))
907
0
        return 0;
908
909
0
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_NONCELEN);
910
0
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_noncelen))
911
0
        return 0;
912
913
0
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_PERSLEN);
914
0
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_perslen))
915
0
        return 0;
916
917
0
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ADINLEN);
918
0
    if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_adinlen))
919
0
        return 0;
920
921
0
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
922
0
    if (p != NULL && !OSSL_PARAM_set_uint(p, drbg->reseed_interval))
923
0
        return 0;
924
925
0
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME);
926
0
    if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time))
927
0
        return 0;
928
929
0
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
930
0
    if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time_interval))
931
0
        return 0;
932
933
0
    return 1;
934
0
}
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
0
{
943
0
    size_t cnt = 0;
944
0
    OSSL_PARAM *p;
945
946
    /* This value never changes once set */
947
0
    p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_MAX_REQUEST);
948
0
    if (p != NULL) {
949
0
        if (!OSSL_PARAM_set_size_t(p, drbg->max_request))
950
0
            return 0;
951
0
        cnt++;
952
0
    }
953
954
    /*
955
     * Can be changed by multiple threads, but we tolerate inaccuracies in this
956
     * value.
957
     */
958
0
    p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_COUNTER);
959
0
    if (p != NULL) {
960
0
        if (!OSSL_PARAM_set_uint(p, tsan_load(&drbg->reseed_counter)))
961
0
            return 0;
962
0
        cnt++;
963
0
    }
964
965
0
    if (params[cnt].key == NULL)
966
0
        *complete = 1;
967
0
    else
968
0
        *complete = 0;
969
970
0
    return 1;
971
0
}
972
973
int ossl_drbg_set_ctx_params(PROV_DRBG *drbg, const OSSL_PARAM params[])
974
0
{
975
0
    const OSSL_PARAM *p;
976
977
0
    if (params == NULL)
978
0
        return 1;
979
980
0
    p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
981
0
    if (p != NULL && !OSSL_PARAM_get_uint(p, &drbg->reseed_interval))
982
0
        return 0;
983
984
0
    p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
985
0
    if (p != NULL && !OSSL_PARAM_get_time_t(p, &drbg->reseed_time_interval))
986
0
        return 0;
987
0
    return 1;
988
0
}
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
}