prov: add extra params argument to KDF implementations
[openssl.git] / providers / implementations / rands / drbg.c
1 /*
2  * Copyright 2011-2021 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, 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     prov_drbg_nonce_ossl_ctx_new,
307     prov_drbg_nonce_ossl_ctx_free,
308 };
309
310 /* Get a nonce from the operating system */
311 static size_t prov_drbg_get_nonce(PROV_DRBG *drbg, unsigned char **pout,
312                                   size_t min_len, size_t max_len)
313 {
314     size_t ret = 0, n;
315     unsigned char *buf = NULL;
316     OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(drbg->provctx);
317     PROV_DRBG_NONCE_GLOBAL *dngbl
318         = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DRBG_NONCE_INDEX,
319                                 &drbg_nonce_ossl_ctx_method);
320     struct {
321         void *drbg;
322         int count;
323     } data;
324
325     if (dngbl == NULL)
326         return 0;
327
328     if (drbg->parent != NULL && drbg->parent_nonce != NULL) {
329         n = drbg->parent_nonce(drbg->parent, NULL, 0, drbg->min_noncelen,
330                                drbg->max_noncelen);
331         if (n > 0 && (buf = OPENSSL_malloc(n)) != NULL) {
332             ret = drbg->parent_nonce(drbg->parent, buf, 0,
333                                      drbg->min_noncelen, drbg->max_noncelen);
334             if (ret == n) {
335                 *pout = buf;
336                 return ret;
337             }
338             OPENSSL_free(buf);
339         }
340     }
341
342     /* Use the built in nonce source plus some of our specifics */
343     memset(&data, 0, sizeof(data));
344     data.drbg = drbg;
345     CRYPTO_atomic_add(&dngbl->rand_nonce_count, 1, &data.count,
346                       dngbl->rand_nonce_lock);
347     return ossl_prov_get_nonce(drbg->provctx, pout, min_len, max_len,
348                                &data, sizeof(data));
349 }
350 #endif /* PROV_RAND_GET_RANDOM_NONCE */
351
352 /*
353  * Instantiate |drbg|, after it has been initialized.  Use |pers| and
354  * |perslen| as prediction-resistance input.
355  *
356  * Requires that drbg->lock is already locked for write, if non-null.
357  *
358  * Returns 1 on success, 0 on failure.
359  */
360 int ossl_prov_drbg_instantiate(PROV_DRBG *drbg, unsigned int strength,
361                                int prediction_resistance,
362                                const unsigned char *pers, size_t perslen)
363 {
364     unsigned char *nonce = NULL, *entropy = NULL;
365     size_t noncelen = 0, entropylen = 0;
366     size_t min_entropy, min_entropylen, max_entropylen;
367
368     if (!ossl_prov_is_running())
369         return 0;
370
371     if (strength > drbg->strength) {
372         ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
373         goto end;
374     }
375     min_entropy = drbg->strength;
376     min_entropylen = drbg->min_entropylen;
377     max_entropylen = drbg->max_entropylen;
378
379     if (pers == NULL) {
380         pers = (const unsigned char *)ossl_pers_string;
381         perslen = sizeof(ossl_pers_string);
382     }
383     if (perslen > drbg->max_perslen) {
384         ERR_raise(ERR_LIB_PROV, PROV_R_PERSONALISATION_STRING_TOO_LONG);
385         goto end;
386     }
387
388     if (drbg->state != EVP_RAND_STATE_UNINITIALISED) {
389         if (drbg->state == EVP_RAND_STATE_ERROR)
390             ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
391         else
392             ERR_raise(ERR_LIB_PROV, PROV_R_ALREADY_INSTANTIATED);
393         goto end;
394     }
395
396     drbg->state = EVP_RAND_STATE_ERROR;
397
398     if (drbg->min_noncelen > 0) {
399         if (drbg->parent_nonce != NULL) {
400             noncelen = drbg->parent_nonce(drbg->parent, NULL, drbg->strength,
401                                           drbg->min_noncelen,
402                                           drbg->max_noncelen);
403             if (noncelen == 0) {
404                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
405                 goto end;
406             }
407             nonce = OPENSSL_malloc(noncelen);
408             if (nonce == NULL) {
409                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
410                 goto end;
411             }
412             if (noncelen != drbg->parent_nonce(drbg->parent, nonce,
413                                                drbg->strength,
414                                                drbg->min_noncelen,
415                                                drbg->max_noncelen)) {
416                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
417                 goto end;
418             }
419 #ifndef PROV_RAND_GET_RANDOM_NONCE
420         } else if (drbg->parent != NULL) {
421 #endif
422             /*
423              * NIST SP800-90Ar1 section 9.1 says you can combine getting
424              * the entropy and nonce in 1 call by increasing the entropy
425              * with 50% and increasing the minimum length to accommodate
426              * the length of the nonce. We do this in case a nonce is
427              * required and there is no parental nonce capability.
428              */
429             min_entropy += drbg->strength / 2;
430             min_entropylen += drbg->min_noncelen;
431             max_entropylen += drbg->max_noncelen;
432         }
433 #ifndef PROV_RAND_GET_RANDOM_NONCE
434         else { /* parent == NULL */
435             noncelen = prov_drbg_get_nonce(drbg, &nonce, drbg->min_noncelen, 
436                                            drbg->max_noncelen);
437             if (noncelen < drbg->min_noncelen
438                     || noncelen > drbg->max_noncelen) {
439                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
440                 goto end;
441             }
442         }
443 #endif
444     }
445
446     drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
447     if (drbg->reseed_next_counter) {
448         drbg->reseed_next_counter++;
449         if (!drbg->reseed_next_counter)
450             drbg->reseed_next_counter = 1;
451     }
452
453     entropylen = get_entropy(drbg, &entropy, min_entropy,
454                              min_entropylen, max_entropylen,
455                              prediction_resistance);
456     if (entropylen < min_entropylen
457             || entropylen > max_entropylen) {
458         ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
459         goto end;
460     }
461
462     if (!drbg->instantiate(drbg, entropy, entropylen, nonce, noncelen,
463                            pers, perslen)) {
464         ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_INSTANTIATING_DRBG);
465         goto end;
466     }
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 (entropy != NULL)
475         cleanup_entropy(drbg, entropy, entropylen);
476     if (nonce != NULL)
477         ossl_prov_cleanup_nonce(drbg->provctx, nonce, noncelen);
478     if (drbg->state == EVP_RAND_STATE_READY)
479         return 1;
480     return 0;
481 }
482
483 /*
484  * Uninstantiate |drbg|. Must be instantiated before it can be used.
485  *
486  * Requires that drbg->lock is already locked for write, if non-null.
487  *
488  * Returns 1 on success, 0 on failure.
489  */
490 int ossl_prov_drbg_uninstantiate(PROV_DRBG *drbg)
491 {
492     drbg->state = EVP_RAND_STATE_UNINITIALISED;
493     return 1;
494 }
495
496 /*
497  * Reseed |drbg|, mixing in the specified data
498  *
499  * Requires that drbg->lock is already locked for write, if non-null.
500  *
501  * Returns 1 on success, 0 on failure.
502  */
503 int ossl_prov_drbg_reseed(PROV_DRBG *drbg, int prediction_resistance,
504                           const unsigned char *ent, size_t ent_len,
505                           const unsigned char *adin, size_t adinlen)
506 {
507     unsigned char *entropy = NULL;
508     size_t entropylen = 0;
509
510     if (!ossl_prov_is_running())
511         return 0;
512
513     if (drbg->state != EVP_RAND_STATE_READY) {
514         /* try to recover from previous errors */
515         rand_drbg_restart(drbg);
516
517         if (drbg->state == EVP_RAND_STATE_ERROR) {
518             ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
519             return 0;
520         }
521         if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
522             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
523             return 0;
524         }
525     }
526
527     if (ent != NULL) {
528         if (ent_len < drbg->min_entropylen) {
529             ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_OUT_OF_RANGE);
530             drbg->state = EVP_RAND_STATE_ERROR;
531             return 0;
532         }
533         if (ent_len > drbg->max_entropylen) {
534             ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_INPUT_TOO_LONG);
535             drbg->state = EVP_RAND_STATE_ERROR;
536             return 0;
537         }
538     }
539
540     if (adin == NULL) {
541         adinlen = 0;
542     } else if (adinlen > drbg->max_adinlen) {
543         ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
544         return 0;
545     }
546
547     drbg->state = EVP_RAND_STATE_ERROR;
548
549     drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
550     if (drbg->reseed_next_counter) {
551         drbg->reseed_next_counter++;
552         if (!drbg->reseed_next_counter)
553             drbg->reseed_next_counter = 1;
554     }
555
556     if (ent != NULL) {
557 #ifdef FIPS_MODULE
558         /*
559          * NIST SP-800-90A mandates that entropy *shall not* be provided
560          * by the consuming application. Instead the data is added as additional
561          * input.
562          *
563          * (NIST SP-800-90Ar1, Sections 9.1 and 9.2)
564          */
565         if (!drbg->reseed(drbg, NULL, 0, ent, ent_len)) {
566             ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_RESEED);
567             return 0;
568         }
569 #else
570         if (!drbg->reseed(drbg, ent, ent_len, adin, adinlen)) {
571             ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_RESEED);
572             return 0;
573         }
574         /* There isn't much point adding the same additional input twice */
575         adin = NULL;
576         adinlen = 0;
577 #endif
578     }
579
580     /* Reseed using our sources in addition */
581     entropylen = get_entropy(drbg, &entropy, drbg->strength,
582                              drbg->min_entropylen, drbg->max_entropylen,
583                              prediction_resistance);
584     if (entropylen < drbg->min_entropylen
585             || entropylen > drbg->max_entropylen) {
586         ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
587         goto end;
588     }
589
590     if (!drbg->reseed(drbg, entropy, entropylen, adin, adinlen))
591         goto end;
592
593     drbg->state = EVP_RAND_STATE_READY;
594     drbg->generate_counter = 1;
595     drbg->reseed_time = time(NULL);
596     tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
597     if (drbg->parent != NULL)
598         drbg->parent_reseed_counter = get_parent_reseed_count(drbg);
599
600  end:
601     cleanup_entropy(drbg, entropy, entropylen);
602     if (drbg->state == EVP_RAND_STATE_READY)
603         return 1;
604     return 0;
605 }
606
607 /*
608  * Generate |outlen| bytes into the buffer at |out|.  Reseed if we need
609  * to or if |prediction_resistance| is set.  Additional input can be
610  * sent in |adin| and |adinlen|.
611  *
612  * Requires that drbg->lock is already locked for write, if non-null.
613  *
614  * Returns 1 on success, 0 on failure.
615  *
616  */
617 int ossl_prov_drbg_generate(PROV_DRBG *drbg, unsigned char *out, size_t outlen,
618                             unsigned int strength, int prediction_resistance,
619                             const unsigned char *adin, size_t adinlen)
620 {
621     int fork_id;
622     int reseed_required = 0;
623
624     if (!ossl_prov_is_running())
625         return 0;
626
627     if (drbg->state != EVP_RAND_STATE_READY) {
628         /* try to recover from previous errors */
629         rand_drbg_restart(drbg);
630
631         if (drbg->state == EVP_RAND_STATE_ERROR) {
632             ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
633             return 0;
634         }
635         if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
636             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
637             return 0;
638         }
639     }
640     if (strength > drbg->strength) {
641         ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
642         return 0;
643     }
644
645     if (outlen > drbg->max_request) {
646         ERR_raise(ERR_LIB_PROV, PROV_R_REQUEST_TOO_LARGE_FOR_DRBG);
647         return 0;
648     }
649     if (adinlen > drbg->max_adinlen) {
650         ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
651         return 0;
652     }
653
654     fork_id = openssl_get_fork_id();
655
656     if (drbg->fork_id != fork_id) {
657         drbg->fork_id = fork_id;
658         reseed_required = 1;
659     }
660
661     if (drbg->reseed_interval > 0) {
662         if (drbg->generate_counter >= drbg->reseed_interval)
663             reseed_required = 1;
664     }
665     if (drbg->reseed_time_interval > 0) {
666         time_t now = time(NULL);
667         if (now < drbg->reseed_time
668             || now - drbg->reseed_time >= drbg->reseed_time_interval)
669             reseed_required = 1;
670     }
671     if (drbg->parent != NULL
672             && get_parent_reseed_count(drbg) != drbg->parent_reseed_counter)
673         reseed_required = 1;
674
675     if (reseed_required || prediction_resistance) {
676         if (!ossl_prov_drbg_reseed(drbg, prediction_resistance, NULL, 0,
677                                    adin, adinlen)) {
678             ERR_raise(ERR_LIB_PROV, PROV_R_RESEED_ERROR);
679             return 0;
680         }
681         adin = NULL;
682         adinlen = 0;
683     }
684
685     if (!drbg->generate(drbg, out, outlen, adin, adinlen)) {
686         drbg->state = EVP_RAND_STATE_ERROR;
687         ERR_raise(ERR_LIB_PROV, PROV_R_GENERATE_ERROR);
688         return 0;
689     }
690
691     drbg->generate_counter++;
692
693     return 1;
694 }
695
696 /*
697  * Restart |drbg|, using the specified entropy or additional input
698  *
699  * Tries its best to get the drbg instantiated by all means,
700  * regardless of its current state.
701  *
702  * Optionally, a |buffer| of |len| random bytes can be passed,
703  * which is assumed to contain at least |entropy| bits of entropy.
704  *
705  * If |entropy| > 0, the buffer content is used as entropy input.
706  *
707  * If |entropy| == 0, the buffer content is used as additional input
708  *
709  * Returns 1 on success, 0 on failure.
710  *
711  * This function is used internally only.
712  */
713 static int rand_drbg_restart(PROV_DRBG *drbg)
714 {
715     /* repair error state */
716     if (drbg->state == EVP_RAND_STATE_ERROR)
717         drbg->uninstantiate(drbg);
718
719     /* repair uninitialized state */
720     if (drbg->state == EVP_RAND_STATE_UNINITIALISED)
721         /* reinstantiate drbg */
722         ossl_prov_drbg_instantiate(drbg, drbg->strength, 0, NULL, 0);
723
724     return drbg->state == EVP_RAND_STATE_READY;
725 }
726
727 /* Provider support from here down */
728 static const OSSL_DISPATCH *find_call(const OSSL_DISPATCH *dispatch,
729                                       int function)
730 {
731     if (dispatch != NULL)
732         while (dispatch->function_id != 0) {
733             if (dispatch->function_id == function)
734                 return dispatch;
735             dispatch++;
736         }
737     return NULL;
738 }
739
740 int ossl_drbg_enable_locking(void *vctx)
741 {
742     PROV_DRBG *drbg = vctx;
743
744     if (drbg != NULL && drbg->lock == NULL) {
745         if (drbg->parent_enable_locking != NULL)
746             if (!drbg->parent_enable_locking(drbg->parent)) {
747                 ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
748                 return 0;
749             }
750         drbg->lock = CRYPTO_THREAD_lock_new();
751         if (drbg->lock == NULL) {
752             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_CREATE_LOCK);
753             return 0;
754         }
755     }
756     return 1;
757 }
758
759 /*
760  * Allocate memory and initialize a new DRBG. The DRBG is allocated on
761  * the secure heap if |secure| is nonzero and the secure heap is enabled.
762  * The |parent|, if not NULL, will be used as random source for reseeding.
763  * This also requires the parent's provider context and the parent's lock.
764  *
765  * Returns a pointer to the new DRBG instance on success, NULL on failure.
766  */
767 PROV_DRBG *ossl_rand_drbg_new
768     (void *provctx, void *parent, const OSSL_DISPATCH *p_dispatch,
769      int (*dnew)(PROV_DRBG *ctx),
770      int (*instantiate)(PROV_DRBG *drbg,
771                         const unsigned char *entropy, size_t entropylen,
772                         const unsigned char *nonce, size_t noncelen,
773                         const unsigned char *pers, size_t perslen),
774      int (*uninstantiate)(PROV_DRBG *ctx),
775      int (*reseed)(PROV_DRBG *drbg, const unsigned char *ent, size_t ent_len,
776                    const unsigned char *adin, size_t adin_len),
777      int (*generate)(PROV_DRBG *, unsigned char *out, size_t outlen,
778                      const unsigned char *adin, size_t adin_len))
779 {
780     PROV_DRBG *drbg;
781     unsigned int p_str;
782     const OSSL_DISPATCH *pfunc;
783
784     if (!ossl_prov_is_running())
785         return NULL;
786
787     drbg = OPENSSL_zalloc(sizeof(*drbg));
788     if (drbg == NULL) {
789         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
790         return NULL;
791     }
792
793     drbg->provctx = provctx;
794     drbg->instantiate = instantiate;
795     drbg->uninstantiate = uninstantiate;
796     drbg->reseed = reseed;
797     drbg->generate = generate;
798     drbg->fork_id = openssl_get_fork_id();
799
800     /* Extract parent's functions */
801     drbg->parent = parent;
802     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_ENABLE_LOCKING)) != NULL)
803         drbg->parent_enable_locking = OSSL_FUNC_rand_enable_locking(pfunc);
804     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_LOCK)) != NULL)
805         drbg->parent_lock = OSSL_FUNC_rand_lock(pfunc);
806     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_UNLOCK)) != NULL)
807         drbg->parent_unlock = OSSL_FUNC_rand_unlock(pfunc);
808     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_CTX_PARAMS)) != NULL)
809         drbg->parent_get_ctx_params = OSSL_FUNC_rand_get_ctx_params(pfunc);
810     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_NONCE)) != NULL)
811         drbg->parent_nonce = OSSL_FUNC_rand_nonce(pfunc);
812     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_SEED)) != NULL)
813         drbg->parent_get_seed = OSSL_FUNC_rand_get_seed(pfunc);
814     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_CLEAR_SEED)) != NULL)
815         drbg->parent_clear_seed = OSSL_FUNC_rand_clear_seed(pfunc);
816
817     /* Set some default maximums up */
818     drbg->max_entropylen = DRBG_MAX_LENGTH;
819     drbg->max_noncelen = DRBG_MAX_LENGTH;
820     drbg->max_perslen = DRBG_MAX_LENGTH;
821     drbg->max_adinlen = DRBG_MAX_LENGTH;
822     drbg->generate_counter = 1;
823     drbg->reseed_counter = 1;
824     drbg->reseed_interval = RESEED_INTERVAL;
825     drbg->reseed_time_interval = TIME_INTERVAL;
826
827     if (!dnew(drbg))
828         goto err;
829
830     if (parent != NULL) {
831         if (!get_parent_strength(drbg, &p_str))
832             goto err;
833         if (drbg->strength > p_str) {
834             /*
835              * We currently don't support the algorithm from NIST SP 800-90C
836              * 10.1.2 to use a weaker DRBG as source
837              */
838             ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_STRENGTH_TOO_WEAK);
839             goto err;
840         }
841     }
842     return drbg;
843
844  err:
845     ossl_rand_drbg_free(drbg);
846     return NULL;
847 }
848
849 void ossl_rand_drbg_free(PROV_DRBG *drbg)
850 {
851     if (drbg == NULL)
852         return;
853
854     CRYPTO_THREAD_lock_free(drbg->lock);
855     OPENSSL_free(drbg);
856 }
857
858 int ossl_drbg_get_ctx_params(PROV_DRBG *drbg, OSSL_PARAM params[])
859 {
860     OSSL_PARAM *p;
861
862     p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STATE);
863     if (p != NULL && !OSSL_PARAM_set_int(p, drbg->state))
864         return 0;
865
866     p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STRENGTH);
867     if (p != NULL && !OSSL_PARAM_set_int(p, drbg->strength))
868         return 0;
869
870     p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_MAX_REQUEST);
871     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_request))
872         return 0;
873
874     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_ENTROPYLEN);
875     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_entropylen))
876         return 0;
877
878     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ENTROPYLEN);
879     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_entropylen))
880         return 0;
881
882     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_NONCELEN);
883     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_noncelen))
884         return 0;
885
886     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_NONCELEN);
887     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_noncelen))
888         return 0;
889
890     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_PERSLEN);
891     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_perslen))
892         return 0;
893
894     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ADINLEN);
895     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_adinlen))
896         return 0;
897
898     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
899     if (p != NULL && !OSSL_PARAM_set_uint(p, drbg->reseed_interval))
900         return 0;
901
902     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME);
903     if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time))
904         return 0;
905
906     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
907     if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time_interval))
908         return 0;
909
910     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_COUNTER);
911     if (p != NULL
912             && !OSSL_PARAM_set_uint(p, tsan_load(&drbg->reseed_counter)))
913         return 0;
914     return 1;
915 }
916
917 int ossl_drbg_set_ctx_params(PROV_DRBG *drbg, const OSSL_PARAM params[])
918 {
919     const OSSL_PARAM *p;
920
921     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
922     if (p != NULL && !OSSL_PARAM_get_uint(p, &drbg->reseed_interval))
923         return 0;
924
925     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
926     if (p != NULL && !OSSL_PARAM_get_time_t(p, &drbg->reseed_time_interval))
927         return 0;
928     return 1;
929 }