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