apps/x509.c: Fix mem leaks in processing of -next_serial in print loop
[openssl.git] / providers / implementations / rands / drbg.c
1 /*
2  * Copyright 2011-2020 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 "drbg_local.h"
17 #include "internal/thread_once.h"
18 #include "crypto/cryptlib.h"
19 #include "prov/seeding.h"
20 #include "crypto/rand_pool.h"
21 #include "prov/provider_ctx.h"
22 #include "prov/providercommonerr.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 static size_t prov_drbg_get_entropy(PROV_DRBG *drbg, unsigned char **pout,
145                                     int entropy, size_t min_len,
146                                     size_t max_len, int prediction_resistance)
147 {
148     unsigned int p_str;
149     size_t r, bytes_needed;
150     unsigned char *buffer;
151
152     if (!get_parent_strength(drbg, &p_str))
153         return 0;
154     if (drbg->strength > p_str) {
155         /*
156          * We currently don't support the algorithm from NIST SP 800-90C
157          * 10.1.2 to use a weaker DRBG as source
158          */
159         ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_STRENGTH_TOO_WEAK);
160         return 0;
161     }
162
163     if (drbg->parent_generate == NULL) {
164         ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_CANNOT_GENERATE_RANDOM_NUMBERS);
165         return 0;
166     }
167
168     /* Figure out how many bytes we need */
169     bytes_needed = entropy >= 0 ? (entropy + 7) / 8 : 0;
170     if (bytes_needed < min_len)
171         bytes_needed = min_len;
172     if (bytes_needed > max_len)
173         bytes_needed = max_len;
174
175     /* Allocate storage */
176     buffer = OPENSSL_secure_malloc(bytes_needed);
177     if (buffer == NULL) {
178         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
179         return 0;
180     }
181
182     /*
183      * Our lock is already held, but we need to lock our parent before
184      * generating bits from it.  Note: taking the lock will be a no-op
185      * if locking is not required (while drbg->parent->lock == NULL).
186      */
187     ossl_drbg_lock_parent(drbg);
188     /*
189      * Get random data from parent.  Include our DRBG address as
190      * additional input, in order to provide a distinction between
191      * different DRBG child instances.
192      *
193      * Note: using the sizeof() operator on a pointer triggers
194      *       a warning in some static code analyzers, but it's
195      *       intentional and correct here.
196      */
197     r = drbg->parent_generate(drbg->parent, buffer, bytes_needed,
198                               drbg->strength, prediction_resistance,
199                               (unsigned char *)&drbg,
200                               sizeof(drbg));
201     ossl_drbg_unlock_parent(drbg);
202     if (r == 0) {
203         OPENSSL_secure_clear_free(buffer, bytes_needed);
204         ERR_raise(ERR_LIB_PROV, PROV_R_GENERATE_ERROR);
205         return 0;
206     }
207     *pout = buffer;
208     return bytes_needed;
209 }
210
211 /*
212  * Implements the cleanup_entropy() callback
213  *
214  */
215 static void prov_drbg_cleanup_entropy(ossl_unused PROV_DRBG *drbg,
216                                       unsigned char *out, size_t outlen)
217 {
218     OPENSSL_secure_clear_free(out, outlen);
219 }
220
221 static size_t get_entropy(PROV_DRBG *drbg, unsigned char **pout, int entropy,
222                           size_t min_len, size_t max_len,
223                           int prediction_resistance)
224 {
225     if (drbg->parent == NULL)
226 #ifdef FIPS_MODULE
227         return ossl_crngt_get_entropy(drbg, pout, entropy, min_len, max_len,
228                                       prediction_resistance);
229 #else
230         return ossl_prov_get_entropy(drbg->provctx, pout, entropy, min_len,
231                                      max_len);
232 #endif
233
234     return prov_drbg_get_entropy(drbg, pout, entropy, min_len, max_len,
235                                  prediction_resistance);
236 }
237
238 static void cleanup_entropy(PROV_DRBG *drbg, unsigned char *out, size_t outlen)
239 {
240     if (drbg->parent == NULL) {
241 #ifdef FIPS_MODULE
242         ossl_crngt_cleanup_entropy(drbg, out, outlen);
243 #else
244         ossl_prov_cleanup_entropy(drbg->provctx, out, outlen);
245 #endif
246     } else {
247         prov_drbg_cleanup_entropy(drbg, out, outlen);
248     }
249 }
250
251 #ifndef PROV_RAND_GET_RANDOM_NONCE
252 typedef struct prov_drbg_nonce_global_st {
253     CRYPTO_RWLOCK *rand_nonce_lock;
254     int rand_nonce_count;
255 } PROV_DRBG_NONCE_GLOBAL;
256
257 /*
258  * drbg_ossl_ctx_new() calls drgb_setup() which calls rand_drbg_get_nonce()
259  * which needs to get the rand_nonce_lock out of the OSSL_LIB_CTX...but since
260  * drbg_ossl_ctx_new() hasn't finished running yet we need the rand_nonce_lock
261  * to be in a different global data object. Otherwise we will go into an
262  * infinite recursion loop.
263  */
264 static void *prov_drbg_nonce_ossl_ctx_new(OSSL_LIB_CTX *libctx)
265 {
266     PROV_DRBG_NONCE_GLOBAL *dngbl = OPENSSL_zalloc(sizeof(*dngbl));
267
268     if (dngbl == NULL)
269         return NULL;
270
271     dngbl->rand_nonce_lock = CRYPTO_THREAD_lock_new();
272     if (dngbl->rand_nonce_lock == NULL) {
273         OPENSSL_free(dngbl);
274         return NULL;
275     }
276
277     return dngbl;
278 }
279
280 static void prov_drbg_nonce_ossl_ctx_free(void *vdngbl)
281 {
282     PROV_DRBG_NONCE_GLOBAL *dngbl = vdngbl;
283
284     if (dngbl == NULL)
285         return;
286
287     CRYPTO_THREAD_lock_free(dngbl->rand_nonce_lock);
288
289     OPENSSL_free(dngbl);
290 }
291
292 static const OSSL_LIB_CTX_METHOD drbg_nonce_ossl_ctx_method = {
293     prov_drbg_nonce_ossl_ctx_new,
294     prov_drbg_nonce_ossl_ctx_free,
295 };
296
297 /* Get a nonce from the operating system */
298 static size_t prov_drbg_get_nonce(PROV_DRBG *drbg, unsigned char **pout,
299                                   size_t min_len, size_t max_len)
300 {
301     size_t ret = 0, n;
302     unsigned char *buf = NULL;
303     OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(drbg->provctx);
304     PROV_DRBG_NONCE_GLOBAL *dngbl
305         = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DRBG_NONCE_INDEX,
306                                 &drbg_nonce_ossl_ctx_method);
307     struct {
308         void *drbg;
309         int count;
310     } data;
311
312     if (dngbl == NULL)
313         return 0;
314
315     if (drbg->parent != NULL && drbg->parent_nonce != NULL) {
316         n = drbg->parent_nonce(drbg->parent, NULL, 0, drbg->min_noncelen,
317                                drbg->max_noncelen);
318         if (n > 0 && (buf = OPENSSL_malloc(n)) != NULL) {
319             ret = drbg->parent_nonce(drbg->parent, buf, 0,
320                                      drbg->min_noncelen, drbg->max_noncelen);
321             if (ret == n) {
322                 *pout = buf;
323                 return ret;
324             }
325             OPENSSL_free(buf);
326         }
327     }
328
329     /* Use the built in nonce source plus some of our specifics */
330     memset(&data, 0, sizeof(data));
331     data.drbg = drbg;
332     CRYPTO_atomic_add(&dngbl->rand_nonce_count, 1, &data.count,
333                       dngbl->rand_nonce_lock);
334     return ossl_prov_get_nonce(drbg->provctx, pout, min_len, max_len,
335                                &data, sizeof(data));
336 }
337 #endif /* PROV_RAND_GET_RANDOM_NONCE */
338
339 /*
340  * Instantiate |drbg|, after it has been initialized.  Use |pers| and
341  * |perslen| as prediction-resistance input.
342  *
343  * Requires that drbg->lock is already locked for write, if non-null.
344  *
345  * Returns 1 on success, 0 on failure.
346  */
347 int ossl_prov_drbg_instantiate(PROV_DRBG *drbg, unsigned int strength,
348                                int prediction_resistance,
349                                const unsigned char *pers, size_t perslen)
350 {
351     unsigned char *nonce = NULL, *entropy = NULL;
352     size_t noncelen = 0, entropylen = 0;
353     size_t min_entropy, min_entropylen, max_entropylen;
354
355     if (!ossl_prov_is_running())
356         return 0;
357
358     if (strength > drbg->strength) {
359         ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
360         goto end;
361     }
362     min_entropy = drbg->strength;
363     min_entropylen = drbg->min_entropylen;
364     max_entropylen = drbg->max_entropylen;
365
366     if (pers == NULL) {
367         pers = (const unsigned char *)ossl_pers_string;
368         perslen = sizeof(ossl_pers_string);
369     }
370     if (perslen > drbg->max_perslen) {
371         ERR_raise(ERR_LIB_PROV, PROV_R_PERSONALISATION_STRING_TOO_LONG);
372         goto end;
373     }
374
375     if (drbg->state != EVP_RAND_STATE_UNINITIALISED) {
376         if (drbg->state == EVP_RAND_STATE_ERROR)
377             ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
378         else
379             ERR_raise(ERR_LIB_PROV, PROV_R_ALREADY_INSTANTIATED);
380         goto end;
381     }
382
383     drbg->state = EVP_RAND_STATE_ERROR;
384
385     if (drbg->min_noncelen > 0) {
386         if (drbg->parent_nonce != NULL) {
387             noncelen = drbg->parent_nonce(drbg->parent, NULL, drbg->strength,
388                                           drbg->min_noncelen,
389                                           drbg->max_noncelen);
390             if (noncelen == 0) {
391                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
392                 goto end;
393             }
394             nonce = OPENSSL_malloc(noncelen);
395             if (nonce == NULL) {
396                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
397                 goto end;
398             }
399             if (noncelen != drbg->parent_nonce(drbg->parent, nonce,
400                                                drbg->strength,
401                                                drbg->min_noncelen,
402                                                drbg->max_noncelen)) {
403                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
404                 goto end;
405             }
406 #ifndef PROV_RAND_GET_RANDOM_NONCE
407         } else if (drbg->parent != NULL) {
408 #endif
409             /*
410              * NIST SP800-90Ar1 section 9.1 says you can combine getting
411              * the entropy and nonce in 1 call by increasing the entropy
412              * with 50% and increasing the minimum length to accommodate
413              * the length of the nonce. We do this in case a nonce is
414              * required and there is no parental nonce capability.
415              */
416             min_entropy += drbg->strength / 2;
417             min_entropylen += drbg->min_noncelen;
418             max_entropylen += drbg->max_noncelen;
419         }
420 #ifndef PROV_RAND_GET_RANDOM_NONCE
421         else { /* parent == NULL */
422             noncelen = prov_drbg_get_nonce(drbg, &nonce, drbg->min_noncelen, 
423                                            drbg->max_noncelen);
424             if (noncelen < drbg->min_noncelen
425                     || noncelen > drbg->max_noncelen) {
426                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
427                 goto end;
428             }
429         }
430 #endif
431     }
432
433     drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
434     if (drbg->reseed_next_counter) {
435         drbg->reseed_next_counter++;
436         if (!drbg->reseed_next_counter)
437             drbg->reseed_next_counter = 1;
438     }
439
440     entropylen = get_entropy(drbg, &entropy, min_entropy,
441                              min_entropylen, max_entropylen,
442                              prediction_resistance);
443     if (entropylen < min_entropylen
444             || entropylen > max_entropylen) {
445         ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
446         goto end;
447     }
448
449     if (!drbg->instantiate(drbg, entropy, entropylen, nonce, noncelen,
450                            pers, perslen)) {
451         ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_INSTANTIATING_DRBG);
452         goto end;
453     }
454
455     drbg->state = EVP_RAND_STATE_READY;
456     drbg->generate_counter = 1;
457     drbg->reseed_time = time(NULL);
458     tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
459
460  end:
461     if (entropy != NULL)
462         cleanup_entropy(drbg, entropy, entropylen);
463     if (nonce != NULL)
464         ossl_prov_cleanup_nonce(drbg->provctx, nonce, noncelen);
465     if (drbg->state == EVP_RAND_STATE_READY)
466         return 1;
467     return 0;
468 }
469
470 /*
471  * Uninstantiate |drbg|. Must be instantiated before it can be used.
472  *
473  * Requires that drbg->lock is already locked for write, if non-null.
474  *
475  * Returns 1 on success, 0 on failure.
476  */
477 int ossl_prov_drbg_uninstantiate(PROV_DRBG *drbg)
478 {
479     drbg->state = EVP_RAND_STATE_UNINITIALISED;
480     return 1;
481 }
482
483 /*
484  * Reseed |drbg|, mixing in the specified data
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_reseed(PROV_DRBG *drbg, int prediction_resistance,
491                           const unsigned char *ent, size_t ent_len,
492                           const unsigned char *adin, size_t adinlen)
493 {
494     unsigned char *entropy = NULL;
495     size_t entropylen = 0;
496
497     if (!ossl_prov_is_running())
498         return 0;
499
500     if (drbg->state != EVP_RAND_STATE_READY) {
501         /* try to recover from previous errors */
502         rand_drbg_restart(drbg);
503
504         if (drbg->state == EVP_RAND_STATE_ERROR) {
505             ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
506             return 0;
507         }
508         if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
509             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
510             return 0;
511         }
512     }
513
514     if (ent != NULL) {
515         if (ent_len < drbg->min_entropylen) {
516             ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_OUT_OF_RANGE);
517             drbg->state = EVP_RAND_STATE_ERROR;
518             return 0;
519         }
520         if (ent_len > drbg->max_entropylen) {
521             ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_INPUT_TOO_LONG);
522             drbg->state = EVP_RAND_STATE_ERROR;
523             return 0;
524         }
525     }
526
527     if (adin == NULL) {
528         adinlen = 0;
529     } else if (adinlen > drbg->max_adinlen) {
530         ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
531         return 0;
532     }
533
534     drbg->state = EVP_RAND_STATE_ERROR;
535
536     drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
537     if (drbg->reseed_next_counter) {
538         drbg->reseed_next_counter++;
539         if (!drbg->reseed_next_counter)
540             drbg->reseed_next_counter = 1;
541     }
542
543     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         if (!drbg->reseed(drbg, ent, ent_len, adin, adinlen)) {
558             ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_RESEED);
559             return 0;
560         }
561         /* There isn't much point adding the same additional input twice */
562         adin = NULL;
563         adinlen = 0;
564 #endif
565     }
566
567     /* Reseed using our sources in addition */
568     entropylen = get_entropy(drbg, &entropy, drbg->strength,
569                              drbg->min_entropylen, drbg->max_entropylen,
570                              prediction_resistance);
571     if (entropylen < drbg->min_entropylen
572             || entropylen > drbg->max_entropylen) {
573         ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
574         goto end;
575     }
576
577     if (!drbg->reseed(drbg, entropy, entropylen, adin, adinlen))
578         goto end;
579
580     drbg->state = EVP_RAND_STATE_READY;
581     drbg->generate_counter = 1;
582     drbg->reseed_time = time(NULL);
583     tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
584     if (drbg->parent != NULL)
585         drbg->parent_reseed_counter = get_parent_reseed_count(drbg);
586
587  end:
588     cleanup_entropy(drbg, entropy, entropylen);
589     if (drbg->state == EVP_RAND_STATE_READY)
590         return 1;
591     return 0;
592 }
593
594 /*
595  * Generate |outlen| bytes into the buffer at |out|.  Reseed if we need
596  * to or if |prediction_resistance| is set.  Additional input can be
597  * sent in |adin| and |adinlen|.
598  *
599  * Requires that drbg->lock is already locked for write, if non-null.
600  *
601  * Returns 1 on success, 0 on failure.
602  *
603  */
604 int ossl_prov_drbg_generate(PROV_DRBG *drbg, unsigned char *out, size_t outlen,
605                             unsigned int strength, int prediction_resistance,
606                             const unsigned char *adin, size_t adinlen)
607 {
608     int fork_id;
609     int reseed_required = 0;
610
611     if (!ossl_prov_is_running())
612         return 0;
613
614     if (drbg->state != EVP_RAND_STATE_READY) {
615         /* try to recover from previous errors */
616         rand_drbg_restart(drbg);
617
618         if (drbg->state == EVP_RAND_STATE_ERROR) {
619             ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
620             return 0;
621         }
622         if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
623             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
624             return 0;
625         }
626     }
627     if (strength > drbg->strength) {
628         ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
629         return 0;
630     }
631
632     if (outlen > drbg->max_request) {
633         ERR_raise(ERR_LIB_PROV, PROV_R_REQUEST_TOO_LARGE_FOR_DRBG);
634         return 0;
635     }
636     if (adinlen > drbg->max_adinlen) {
637         ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
638         return 0;
639     }
640
641     fork_id = openssl_get_fork_id();
642
643     if (drbg->fork_id != fork_id) {
644         drbg->fork_id = fork_id;
645         reseed_required = 1;
646     }
647
648     if (drbg->reseed_interval > 0) {
649         if (drbg->generate_counter >= drbg->reseed_interval)
650             reseed_required = 1;
651     }
652     if (drbg->reseed_time_interval > 0) {
653         time_t now = time(NULL);
654         if (now < drbg->reseed_time
655             || now - drbg->reseed_time >= drbg->reseed_time_interval)
656             reseed_required = 1;
657     }
658     if (drbg->parent != NULL
659             && get_parent_reseed_count(drbg) != drbg->parent_reseed_counter)
660         reseed_required = 1;
661
662     if (reseed_required || prediction_resistance) {
663         if (!ossl_prov_drbg_reseed(drbg, prediction_resistance, NULL, 0,
664                                    adin, adinlen)) {
665             ERR_raise(ERR_LIB_PROV, PROV_R_RESEED_ERROR);
666             return 0;
667         }
668         adin = NULL;
669         adinlen = 0;
670     }
671
672     if (!drbg->generate(drbg, out, outlen, adin, adinlen)) {
673         drbg->state = EVP_RAND_STATE_ERROR;
674         ERR_raise(ERR_LIB_PROV, PROV_R_GENERATE_ERROR);
675         return 0;
676     }
677
678     drbg->generate_counter++;
679
680     return 1;
681 }
682
683 /*
684  * Restart |drbg|, using the specified entropy or additional input
685  *
686  * Tries its best to get the drbg instantiated by all means,
687  * regardless of its current state.
688  *
689  * Optionally, a |buffer| of |len| random bytes can be passed,
690  * which is assumed to contain at least |entropy| bits of entropy.
691  *
692  * If |entropy| > 0, the buffer content is used as entropy input.
693  *
694  * If |entropy| == 0, the buffer content is used as additional input
695  *
696  * Returns 1 on success, 0 on failure.
697  *
698  * This function is used internally only.
699  */
700 static int rand_drbg_restart(PROV_DRBG *drbg)
701 {
702     /* repair error state */
703     if (drbg->state == EVP_RAND_STATE_ERROR)
704         drbg->uninstantiate(drbg);
705
706     /* repair uninitialized state */
707     if (drbg->state == EVP_RAND_STATE_UNINITIALISED)
708         /* reinstantiate drbg */
709         ossl_prov_drbg_instantiate(drbg, drbg->strength, 0, NULL, 0);
710
711     return drbg->state == EVP_RAND_STATE_READY;
712 }
713
714 /* Provider support from here down */
715 static const OSSL_DISPATCH *find_call(const OSSL_DISPATCH *dispatch,
716                                       int function)
717 {
718     if (dispatch != NULL)
719         while (dispatch->function_id != 0) {
720             if (dispatch->function_id == function)
721                 return dispatch;
722             dispatch++;
723         }
724     return NULL;
725 }
726
727 int ossl_drbg_enable_locking(void *vctx)
728 {
729     PROV_DRBG *drbg = vctx;
730
731     if (drbg != NULL && drbg->lock == NULL) {
732         if (drbg->parent_enable_locking != NULL)
733             if (!drbg->parent_enable_locking(drbg->parent)) {
734                 ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
735                 return 0;
736             }
737         drbg->lock = CRYPTO_THREAD_lock_new();
738         if (drbg->lock == NULL) {
739             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_CREATE_LOCK);
740             return 0;
741         }
742     }
743     return 1;
744 }
745
746 /*
747  * Allocate memory and initialize a new DRBG. The DRBG is allocated on
748  * the secure heap if |secure| is nonzero and the secure heap is enabled.
749  * The |parent|, if not NULL, will be used as random source for reseeding.
750  * This also requires the parent's provider context and the parent's lock.
751  *
752  * Returns a pointer to the new DRBG instance on success, NULL on failure.
753  */
754 PROV_DRBG *ossl_rand_drbg_new
755     (void *provctx, void *parent, const OSSL_DISPATCH *p_dispatch,
756      int (*dnew)(PROV_DRBG *ctx),
757      int (*instantiate)(PROV_DRBG *drbg,
758                         const unsigned char *entropy, size_t entropylen,
759                         const unsigned char *nonce, size_t noncelen,
760                         const unsigned char *pers, size_t perslen),
761      int (*uninstantiate)(PROV_DRBG *ctx),
762      int (*reseed)(PROV_DRBG *drbg, const unsigned char *ent, size_t ent_len,
763                    const unsigned char *adin, size_t adin_len),
764      int (*generate)(PROV_DRBG *, unsigned char *out, size_t outlen,
765                      const unsigned char *adin, size_t adin_len))
766 {
767     PROV_DRBG *drbg;
768     unsigned int p_str;
769     const OSSL_DISPATCH *pfunc;
770
771     if (!ossl_prov_is_running())
772         return NULL;
773
774     drbg = OPENSSL_zalloc(sizeof(*drbg));
775     if (drbg == NULL) {
776         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
777         return NULL;
778     }
779
780     drbg->provctx = provctx;
781     drbg->instantiate = instantiate;
782     drbg->uninstantiate = uninstantiate;
783     drbg->reseed = reseed;
784     drbg->generate = generate;
785     drbg->fork_id = openssl_get_fork_id();
786
787     /* Extract parent's functions */
788     drbg->parent = parent;
789     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_ENABLE_LOCKING)) != NULL)
790         drbg->parent_enable_locking = OSSL_FUNC_rand_enable_locking(pfunc);
791     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_LOCK)) != NULL)
792         drbg->parent_lock = OSSL_FUNC_rand_lock(pfunc);
793     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_UNLOCK)) != NULL)
794         drbg->parent_unlock = OSSL_FUNC_rand_unlock(pfunc);
795     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_CTX_PARAMS)) != NULL)
796         drbg->parent_get_ctx_params = OSSL_FUNC_rand_get_ctx_params(pfunc);
797     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GENERATE)) != NULL)
798         drbg->parent_generate = OSSL_FUNC_rand_generate(pfunc);
799     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_NONCE)) != NULL)
800         drbg->parent_nonce = OSSL_FUNC_rand_nonce(pfunc);
801
802     /* Set some default maximums up */
803     drbg->max_entropylen = DRBG_MAX_LENGTH;
804     drbg->max_noncelen = DRBG_MAX_LENGTH;
805     drbg->max_perslen = DRBG_MAX_LENGTH;
806     drbg->max_adinlen = DRBG_MAX_LENGTH;
807     drbg->generate_counter = 1;
808     drbg->reseed_counter = 1;
809     drbg->reseed_interval = RESEED_INTERVAL;
810     drbg->reseed_time_interval = TIME_INTERVAL;
811
812     if (!dnew(drbg))
813         goto err;
814
815     if (parent != NULL) {
816         if (!get_parent_strength(drbg, &p_str))
817             goto err;
818         if (drbg->strength > p_str) {
819             /*
820              * We currently don't support the algorithm from NIST SP 800-90C
821              * 10.1.2 to use a weaker DRBG as source
822              */
823             ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_STRENGTH_TOO_WEAK);
824             goto err;
825         }
826     }
827     return drbg;
828
829  err:
830     ossl_rand_drbg_free(drbg);
831     return NULL;
832 }
833
834 void ossl_rand_drbg_free(PROV_DRBG *drbg)
835 {
836     if (drbg == NULL)
837         return;
838
839     CRYPTO_THREAD_lock_free(drbg->lock);
840     OPENSSL_free(drbg);
841 }
842
843 int ossl_drbg_get_ctx_params(PROV_DRBG *drbg, OSSL_PARAM params[])
844 {
845     OSSL_PARAM *p;
846
847     p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STATE);
848     if (p != NULL && !OSSL_PARAM_set_int(p, drbg->state))
849         return 0;
850
851     p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STRENGTH);
852     if (p != NULL && !OSSL_PARAM_set_int(p, drbg->strength))
853         return 0;
854
855     p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_MAX_REQUEST);
856     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_request))
857         return 0;
858
859     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_ENTROPYLEN);
860     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_entropylen))
861         return 0;
862
863     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ENTROPYLEN);
864     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_entropylen))
865         return 0;
866
867     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_NONCELEN);
868     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_noncelen))
869         return 0;
870
871     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_NONCELEN);
872     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_noncelen))
873         return 0;
874
875     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_PERSLEN);
876     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_perslen))
877         return 0;
878
879     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ADINLEN);
880     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_adinlen))
881         return 0;
882
883     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
884     if (p != NULL && !OSSL_PARAM_set_uint(p, drbg->reseed_interval))
885         return 0;
886
887     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME);
888     if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time))
889         return 0;
890
891     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
892     if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time_interval))
893         return 0;
894
895     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_COUNTER);
896     if (p != NULL
897             && !OSSL_PARAM_set_uint(p, tsan_load(&drbg->reseed_counter)))
898         return 0;
899     return 1;
900 }
901
902 int ossl_drbg_set_ctx_params(PROV_DRBG *drbg, const OSSL_PARAM params[])
903 {
904     const OSSL_PARAM *p;
905
906     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
907     if (p != NULL && !OSSL_PARAM_get_uint(p, &drbg->reseed_interval))
908         return 0;
909
910     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
911     if (p != NULL && !OSSL_PARAM_get_time_t(p, &drbg->reseed_time_interval))
912         return 0;
913     return 1;
914 }