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 #include "crypto/context.h"
25 
26 /*
27  * Support framework for NIST SP 800-90A DRBG
28  *
29  * See manual page PROV_DRBG(7) for a general overview.
30  *
31  * The OpenSSL model is to have new and free functions, and that new
32  * does all initialization.  That is not the NIST model, which has
33  * instantiation and un-instantiate, and reuse within a new/free
34  * lifecycle.  (No doubt this comes from the desire to support hardware
35  * DRBG, where allocation of resources on something like an HSM is
36  * a much bigger deal than just re-setting an allocated resource.)
37  */
38 
39 /* NIST SP 800-90A DRBG recommends the use of a personalization string. */
40 static const char ossl_pers_string[] = DRBG_DEFAULT_PERS_STRING;
41 
42 static const OSSL_DISPATCH *find_call(const OSSL_DISPATCH *dispatch,
43                                       int function);
44 
45 static int rand_drbg_restart(PROV_DRBG *drbg);
46 
47 /*
48  * We interpret a call to this function as a hint only and ignore it. This
49  * occurs when the EVP layer thinks we should do some locking. In practice
50  * however we manage for ourselves when we take a lock or not on the basis
51  * of whether drbg->lock is present or not.
52  */
ossl_drbg_lock(void * vctx)53 int ossl_drbg_lock(void *vctx)
54 {
55     return 1;
56 }
57 
58 /* Interpreted as a hint only and ignored as for ossl_drbg_lock() */
ossl_drbg_unlock(void * vctx)59 void ossl_drbg_unlock(void *vctx)
60 {
61 }
62 
ossl_drbg_lock_parent(PROV_DRBG * drbg)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 
ossl_drbg_unlock_parent(PROV_DRBG * drbg)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 
get_parent_strength(PROV_DRBG * drbg,unsigned int * str)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 
get_parent_reseed_count(PROV_DRBG * drbg)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  */
ossl_drbg_get_seed(void * vdrbg,unsigned char ** pout,int entropy,size_t min_len,size_t max_len,int prediction_resistance,const unsigned char * adin,size_t adin_len)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         return 0;
164 
165     /*
166      * Get random data.  Include our DRBG address as
167      * additional input, in order to provide a distinction between
168      * different DRBG child instances.
169      *
170      * Note: using the sizeof() operator on a pointer triggers
171      *       a warning in some static code analyzers, but it's
172      *       intentional and correct here.
173      */
174     if (!ossl_prov_drbg_generate(drbg, buffer, bytes_needed,
175                                  drbg->strength, prediction_resistance,
176                                  (unsigned char *)&drbg, sizeof(drbg))) {
177         OPENSSL_secure_clear_free(buffer, bytes_needed);
178         ERR_raise(ERR_LIB_PROV, PROV_R_GENERATE_ERROR);
179         return 0;
180     }
181     *pout = buffer;
182     return bytes_needed;
183 }
184 
185 /* Implements the cleanup_entropy() callback */
ossl_drbg_clear_seed(ossl_unused void * vdrbg,unsigned char * out,size_t outlen)186 void ossl_drbg_clear_seed(ossl_unused void *vdrbg,
187                           unsigned char *out, size_t outlen)
188 {
189     OPENSSL_secure_clear_free(out, outlen);
190 }
191 
get_entropy(PROV_DRBG * drbg,unsigned char ** pout,int entropy,size_t min_len,size_t max_len,int prediction_resistance)192 static size_t get_entropy(PROV_DRBG *drbg, unsigned char **pout, int entropy,
193                           size_t min_len, size_t max_len,
194                           int prediction_resistance)
195 {
196     size_t bytes;
197     unsigned int p_str;
198 
199     if (drbg->parent == NULL)
200         /*
201          * In normal use (i.e. OpenSSL's own uses), this is never called.
202          * This remains purely for legacy reasons.
203          */
204         return ossl_prov_get_entropy(drbg->provctx, pout, entropy, min_len,
205                                      max_len);
206 
207     if (drbg->parent_get_seed == NULL) {
208         ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_CANNOT_SUPPLY_ENTROPY_SEED);
209         return 0;
210     }
211     if (!get_parent_strength(drbg, &p_str))
212         return 0;
213     if (drbg->strength > p_str) {
214         /*
215          * We currently don't support the algorithm from NIST SP 800-90C
216          * 10.1.2 to use a weaker DRBG as source
217          */
218         ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_STRENGTH_TOO_WEAK);
219         return 0;
220     }
221 
222     /*
223      * Our lock is already held, but we need to lock our parent before
224      * generating bits from it.  Note: taking the lock will be a no-op
225      * if locking is not required (while drbg->parent->lock == NULL).
226      */
227     if (!ossl_drbg_lock_parent(drbg))
228         return 0;
229     /*
230      * Get random data from parent.  Include our DRBG address as
231      * additional input, in order to provide a distinction between
232      * different DRBG child instances.
233      *
234      * Note: using the sizeof() operator on a pointer triggers
235      *       a warning in some static code analyzers, but it's
236      *       intentional and correct here.
237      */
238     bytes = drbg->parent_get_seed(drbg->parent, pout, drbg->strength,
239                                   min_len, max_len, prediction_resistance,
240                                   (unsigned char *)&drbg, sizeof(drbg));
241     ossl_drbg_unlock_parent(drbg);
242     return bytes;
243 }
244 
cleanup_entropy(PROV_DRBG * drbg,unsigned char * out,size_t outlen)245 static void cleanup_entropy(PROV_DRBG *drbg, unsigned char *out, size_t outlen)
246 {
247     if (drbg->parent == NULL) {
248         ossl_prov_cleanup_entropy(drbg->provctx, out, outlen);
249     } else if (drbg->parent_clear_seed != NULL) {
250         if (!ossl_drbg_lock_parent(drbg))
251             return;
252         drbg->parent_clear_seed(drbg->parent, out, outlen);
253         ossl_drbg_unlock_parent(drbg);
254     }
255 }
256 
257 #ifndef PROV_RAND_GET_RANDOM_NONCE
258 typedef struct prov_drbg_nonce_global_st {
259     CRYPTO_RWLOCK *rand_nonce_lock;
260     int rand_nonce_count;
261 } PROV_DRBG_NONCE_GLOBAL;
262 
263 /*
264  * drbg_ossl_ctx_new() calls drgb_setup() which calls rand_drbg_get_nonce()
265  * which needs to get the rand_nonce_lock out of the OSSL_LIB_CTX...but since
266  * drbg_ossl_ctx_new() hasn't finished running yet we need the rand_nonce_lock
267  * to be in a different global data object. Otherwise we will go into an
268  * infinite recursion loop.
269  */
ossl_prov_drbg_nonce_ctx_new(OSSL_LIB_CTX * libctx)270 void *ossl_prov_drbg_nonce_ctx_new(OSSL_LIB_CTX *libctx)
271 {
272     PROV_DRBG_NONCE_GLOBAL *dngbl = OPENSSL_zalloc(sizeof(*dngbl));
273 
274     if (dngbl == NULL)
275         return NULL;
276 
277     dngbl->rand_nonce_lock = CRYPTO_THREAD_lock_new();
278     if (dngbl->rand_nonce_lock == NULL) {
279         OPENSSL_free(dngbl);
280         return NULL;
281     }
282 
283     return dngbl;
284 }
285 
ossl_prov_drbg_nonce_ctx_free(void * vdngbl)286 void ossl_prov_drbg_nonce_ctx_free(void *vdngbl)
287 {
288     PROV_DRBG_NONCE_GLOBAL *dngbl = vdngbl;
289 
290     if (dngbl == NULL)
291         return;
292 
293     CRYPTO_THREAD_lock_free(dngbl->rand_nonce_lock);
294 
295     OPENSSL_free(dngbl);
296 }
297 
298 /* Get a nonce from the operating system */
prov_drbg_get_nonce(PROV_DRBG * drbg,unsigned char ** pout,size_t min_len,size_t max_len)299 static size_t prov_drbg_get_nonce(PROV_DRBG *drbg, unsigned char **pout,
300                                   size_t min_len, size_t max_len)
301 {
302     size_t ret = 0, n;
303     unsigned char *buf = NULL;
304     OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(drbg->provctx);
305     PROV_DRBG_NONCE_GLOBAL *dngbl
306         = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DRBG_NONCE_INDEX);
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     if (!CRYPTO_atomic_add(&dngbl->rand_nonce_count, 1, &data.count,
333                            dngbl->rand_nonce_lock))
334         return 0;
335     return ossl_prov_get_nonce(drbg->provctx, pout, min_len, max_len,
336                                &data, sizeof(data));
337 }
338 #endif /* PROV_RAND_GET_RANDOM_NONCE */
339 
340 /*
341  * Instantiate |drbg|, after it has been initialized.  Use |pers| and
342  * |perslen| as prediction-resistance input.
343  *
344  * Requires that drbg->lock is already locked for write, if non-null.
345  *
346  * Returns 1 on success, 0 on failure.
347  */
ossl_prov_drbg_instantiate(PROV_DRBG * drbg,unsigned int strength,int prediction_resistance,const unsigned char * pers,size_t perslen)348 int ossl_prov_drbg_instantiate(PROV_DRBG *drbg, unsigned int strength,
349                                int prediction_resistance,
350                                const unsigned char *pers, size_t perslen)
351 {
352     unsigned char *nonce = NULL, *entropy = NULL;
353     size_t noncelen = 0, entropylen = 0;
354     size_t min_entropy, min_entropylen, max_entropylen;
355 
356     if (strength > drbg->strength) {
357         ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
358         goto end;
359     }
360     min_entropy = drbg->strength;
361     min_entropylen = drbg->min_entropylen;
362     max_entropylen = drbg->max_entropylen;
363 
364     if (pers == NULL) {
365         pers = (const unsigned char *)ossl_pers_string;
366         perslen = sizeof(ossl_pers_string);
367     }
368     if (perslen > drbg->max_perslen) {
369         ERR_raise(ERR_LIB_PROV, PROV_R_PERSONALISATION_STRING_TOO_LONG);
370         goto end;
371     }
372 
373     if (drbg->state != EVP_RAND_STATE_UNINITIALISED) {
374         if (drbg->state == EVP_RAND_STATE_ERROR)
375             ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
376         else
377             ERR_raise(ERR_LIB_PROV, PROV_R_ALREADY_INSTANTIATED);
378         goto end;
379     }
380 
381     drbg->state = EVP_RAND_STATE_ERROR;
382 
383     if (drbg->min_noncelen > 0) {
384         if (drbg->parent_nonce != NULL) {
385             noncelen = drbg->parent_nonce(drbg->parent, NULL, drbg->strength,
386                                           drbg->min_noncelen,
387                                           drbg->max_noncelen);
388             if (noncelen == 0) {
389                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
390                 goto end;
391             }
392             nonce = OPENSSL_malloc(noncelen);
393             if (nonce == NULL) {
394                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
395                 goto end;
396             }
397             if (noncelen != drbg->parent_nonce(drbg->parent, nonce,
398                                                drbg->strength,
399                                                drbg->min_noncelen,
400                                                drbg->max_noncelen)) {
401                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
402                 goto end;
403             }
404 #ifndef PROV_RAND_GET_RANDOM_NONCE
405         } else if (drbg->parent != NULL) {
406 #endif
407             /*
408              * NIST SP800-90Ar1 section 9.1 says you can combine getting
409              * the entropy and nonce in 1 call by increasing the entropy
410              * with 50% and increasing the minimum length to accommodate
411              * the length of the nonce. We do this in case a nonce is
412              * required and there is no parental nonce capability.
413              */
414             min_entropy += drbg->strength / 2;
415             min_entropylen += drbg->min_noncelen;
416             max_entropylen += drbg->max_noncelen;
417         }
418 #ifndef PROV_RAND_GET_RANDOM_NONCE
419         else { /* parent == NULL */
420             noncelen = prov_drbg_get_nonce(drbg, &nonce, drbg->min_noncelen,
421                                            drbg->max_noncelen);
422             if (noncelen < drbg->min_noncelen
423                     || noncelen > drbg->max_noncelen) {
424                 ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_NONCE);
425                 goto end;
426             }
427         }
428 #endif
429     }
430 
431     drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
432     if (drbg->reseed_next_counter) {
433         drbg->reseed_next_counter++;
434         if (!drbg->reseed_next_counter)
435             drbg->reseed_next_counter = 1;
436     }
437 
438     entropylen = get_entropy(drbg, &entropy, min_entropy,
439                              min_entropylen, max_entropylen,
440                              prediction_resistance);
441     if (entropylen < min_entropylen
442             || entropylen > max_entropylen) {
443         ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
444         goto end;
445     }
446 
447     if (!drbg->instantiate(drbg, entropy, entropylen, nonce, noncelen,
448                            pers, perslen)) {
449         cleanup_entropy(drbg, entropy, entropylen);
450         ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_INSTANTIATING_DRBG);
451         goto end;
452     }
453     cleanup_entropy(drbg, entropy, entropylen);
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 (nonce != NULL)
462         ossl_prov_cleanup_nonce(drbg->provctx, nonce, noncelen);
463     if (drbg->state == EVP_RAND_STATE_READY)
464         return 1;
465     return 0;
466 }
467 
468 /*
469  * Uninstantiate |drbg|. Must be instantiated before it can be used.
470  *
471  * Requires that drbg->lock is already locked for write, if non-null.
472  *
473  * Returns 1 on success, 0 on failure.
474  */
ossl_prov_drbg_uninstantiate(PROV_DRBG * drbg)475 int ossl_prov_drbg_uninstantiate(PROV_DRBG *drbg)
476 {
477     drbg->state = EVP_RAND_STATE_UNINITIALISED;
478     return 1;
479 }
480 
ossl_prov_drbg_reseed_unlocked(PROV_DRBG * drbg,int prediction_resistance,const unsigned char * ent,size_t ent_len,const unsigned char * adin,size_t adinlen)481 static int ossl_prov_drbg_reseed_unlocked(PROV_DRBG *drbg,
482                                           int prediction_resistance,
483                                           const unsigned char *ent,
484                                           size_t ent_len,
485                                           const unsigned char *adin,
486                                           size_t adinlen)
487 {
488     unsigned char *entropy = NULL;
489     size_t entropylen = 0;
490 
491     if (!ossl_prov_is_running())
492         return 0;
493 
494     if (drbg->state != EVP_RAND_STATE_READY) {
495         /* try to recover from previous errors */
496         rand_drbg_restart(drbg);
497 
498         if (drbg->state == EVP_RAND_STATE_ERROR) {
499             ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
500             return 0;
501         }
502         if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
503             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
504             return 0;
505         }
506     }
507 
508     if (ent != NULL) {
509         if (ent_len < drbg->min_entropylen) {
510             ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_OUT_OF_RANGE);
511             drbg->state = EVP_RAND_STATE_ERROR;
512             return 0;
513         }
514         if (ent_len > drbg->max_entropylen) {
515             ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_INPUT_TOO_LONG);
516             drbg->state = EVP_RAND_STATE_ERROR;
517             return 0;
518         }
519     }
520 
521     if (adin == NULL) {
522         adinlen = 0;
523     } else if (adinlen > drbg->max_adinlen) {
524         ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
525         return 0;
526     }
527 
528     drbg->state = EVP_RAND_STATE_ERROR;
529 
530     drbg->reseed_next_counter = tsan_load(&drbg->reseed_counter);
531     if (drbg->reseed_next_counter) {
532         drbg->reseed_next_counter++;
533         if (!drbg->reseed_next_counter)
534             drbg->reseed_next_counter = 1;
535     }
536 
537     if (ent != NULL) {
538 #ifdef FIPS_MODULE
539         /*
540          * NIST SP-800-90A mandates that entropy *shall not* be provided
541          * by the consuming application. Instead the data is added as additional
542          * input.
543          *
544          * (NIST SP-800-90Ar1, Sections 9.1 and 9.2)
545          */
546         if (!drbg->reseed(drbg, NULL, 0, ent, ent_len)) {
547             ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_RESEED);
548             return 0;
549         }
550 #else
551         if (!drbg->reseed(drbg, ent, ent_len, adin, adinlen)) {
552             ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_RESEED);
553             return 0;
554         }
555         /* There isn't much point adding the same additional input twice */
556         adin = NULL;
557         adinlen = 0;
558 #endif
559     }
560 
561     /* Reseed using our sources in addition */
562     entropylen = get_entropy(drbg, &entropy, drbg->strength,
563                              drbg->min_entropylen, drbg->max_entropylen,
564                              prediction_resistance);
565     if (entropylen < drbg->min_entropylen
566             || entropylen > drbg->max_entropylen) {
567         ERR_raise(ERR_LIB_PROV, PROV_R_ERROR_RETRIEVING_ENTROPY);
568         goto end;
569     }
570 
571     if (!drbg->reseed(drbg, entropy, entropylen, adin, adinlen))
572         goto end;
573 
574     drbg->state = EVP_RAND_STATE_READY;
575     drbg->generate_counter = 1;
576     drbg->reseed_time = time(NULL);
577     tsan_store(&drbg->reseed_counter, drbg->reseed_next_counter);
578     if (drbg->parent != NULL)
579         drbg->parent_reseed_counter = get_parent_reseed_count(drbg);
580 
581  end:
582     cleanup_entropy(drbg, entropy, entropylen);
583     if (drbg->state == EVP_RAND_STATE_READY)
584         return 1;
585     return 0;
586 }
587 
588 /*
589  * Reseed |drbg|, mixing in the specified data
590  *
591  * Acquires the drbg->lock for writing, if non-null.
592  *
593  * Returns 1 on success, 0 on failure.
594  */
ossl_prov_drbg_reseed(PROV_DRBG * drbg,int prediction_resistance,const unsigned char * ent,size_t ent_len,const unsigned char * adin,size_t adinlen)595 int ossl_prov_drbg_reseed(PROV_DRBG *drbg, int prediction_resistance,
596                           const unsigned char *ent, size_t ent_len,
597                           const unsigned char *adin, size_t adinlen)
598 {
599     int ret;
600 
601     if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
602         return 0;
603 
604     ret = ossl_prov_drbg_reseed_unlocked(drbg, prediction_resistance, ent,
605                                          ent_len, adin, adinlen);
606 
607     if (drbg->lock != NULL)
608         CRYPTO_THREAD_unlock(drbg->lock);
609 
610     return ret;
611 }
612 
613 /*
614  * Generate |outlen| bytes into the buffer at |out|.  Reseed if we need
615  * to or if |prediction_resistance| is set.  Additional input can be
616  * sent in |adin| and |adinlen|.
617  *
618  * Acquires the drbg->lock for writing if available
619  *
620  * Returns 1 on success, 0 on failure.
621  *
622  */
ossl_prov_drbg_generate(PROV_DRBG * drbg,unsigned char * out,size_t outlen,unsigned int strength,int prediction_resistance,const unsigned char * adin,size_t adinlen)623 int ossl_prov_drbg_generate(PROV_DRBG *drbg, unsigned char *out, size_t outlen,
624                             unsigned int strength, int prediction_resistance,
625                             const unsigned char *adin, size_t adinlen)
626 {
627     int fork_id;
628     int reseed_required = 0;
629     int ret = 0;
630 
631     if (!ossl_prov_is_running())
632         return 0;
633 
634     if (drbg->lock != NULL && !CRYPTO_THREAD_write_lock(drbg->lock))
635         return 0;
636 
637     if (drbg->state != EVP_RAND_STATE_READY) {
638         /* try to recover from previous errors */
639         rand_drbg_restart(drbg);
640 
641         if (drbg->state == EVP_RAND_STATE_ERROR) {
642             ERR_raise(ERR_LIB_PROV, PROV_R_IN_ERROR_STATE);
643             goto err;
644         }
645         if (drbg->state == EVP_RAND_STATE_UNINITIALISED) {
646             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_INSTANTIATED);
647             goto err;
648         }
649     }
650     if (strength > drbg->strength) {
651         ERR_raise(ERR_LIB_PROV, PROV_R_INSUFFICIENT_DRBG_STRENGTH);
652         goto err;
653     }
654 
655     if (outlen > drbg->max_request) {
656         ERR_raise(ERR_LIB_PROV, PROV_R_REQUEST_TOO_LARGE_FOR_DRBG);
657         goto err;
658     }
659     if (adinlen > drbg->max_adinlen) {
660         ERR_raise(ERR_LIB_PROV, PROV_R_ADDITIONAL_INPUT_TOO_LONG);
661         goto err;
662     }
663 
664     fork_id = openssl_get_fork_id();
665 
666     if (drbg->fork_id != fork_id) {
667         drbg->fork_id = fork_id;
668         reseed_required = 1;
669     }
670 
671     if (drbg->reseed_interval > 0) {
672         if (drbg->generate_counter >= drbg->reseed_interval)
673             reseed_required = 1;
674     }
675     if (drbg->reseed_time_interval > 0) {
676         time_t now = time(NULL);
677         if (now < drbg->reseed_time
678             || now - drbg->reseed_time >= drbg->reseed_time_interval)
679             reseed_required = 1;
680     }
681     if (drbg->parent != NULL
682             && get_parent_reseed_count(drbg) != drbg->parent_reseed_counter)
683         reseed_required = 1;
684 
685     if (reseed_required || prediction_resistance) {
686         if (!ossl_prov_drbg_reseed_unlocked(drbg, prediction_resistance, NULL,
687                                             0, adin, adinlen)) {
688             ERR_raise(ERR_LIB_PROV, PROV_R_RESEED_ERROR);
689             goto err;
690         }
691         adin = NULL;
692         adinlen = 0;
693     }
694 
695     if (!drbg->generate(drbg, out, outlen, adin, adinlen)) {
696         drbg->state = EVP_RAND_STATE_ERROR;
697         ERR_raise(ERR_LIB_PROV, PROV_R_GENERATE_ERROR);
698         goto err;
699     }
700 
701     drbg->generate_counter++;
702 
703     ret = 1;
704  err:
705     if (drbg->lock != NULL)
706         CRYPTO_THREAD_unlock(drbg->lock);
707 
708     return ret;
709 }
710 
711 /*
712  * Restart |drbg|, using the specified entropy or additional input
713  *
714  * Tries its best to get the drbg instantiated by all means,
715  * regardless of its current state.
716  *
717  * Optionally, a |buffer| of |len| random bytes can be passed,
718  * which is assumed to contain at least |entropy| bits of entropy.
719  *
720  * If |entropy| > 0, the buffer content is used as entropy input.
721  *
722  * If |entropy| == 0, the buffer content is used as additional input
723  *
724  * Returns 1 on success, 0 on failure.
725  *
726  * This function is used internally only.
727  */
rand_drbg_restart(PROV_DRBG * drbg)728 static int rand_drbg_restart(PROV_DRBG *drbg)
729 {
730     /* repair error state */
731     if (drbg->state == EVP_RAND_STATE_ERROR)
732         drbg->uninstantiate(drbg);
733 
734     /* repair uninitialized state */
735     if (drbg->state == EVP_RAND_STATE_UNINITIALISED)
736         /* reinstantiate drbg */
737         ossl_prov_drbg_instantiate(drbg, drbg->strength, 0, NULL, 0);
738 
739     return drbg->state == EVP_RAND_STATE_READY;
740 }
741 
742 /* Provider support from here down */
find_call(const OSSL_DISPATCH * dispatch,int function)743 static const OSSL_DISPATCH *find_call(const OSSL_DISPATCH *dispatch,
744                                       int function)
745 {
746     if (dispatch != NULL)
747         while (dispatch->function_id != 0) {
748             if (dispatch->function_id == function)
749                 return dispatch;
750             dispatch++;
751         }
752     return NULL;
753 }
754 
ossl_drbg_enable_locking(void * vctx)755 int ossl_drbg_enable_locking(void *vctx)
756 {
757     PROV_DRBG *drbg = vctx;
758 
759     if (drbg != NULL && drbg->lock == NULL) {
760         if (drbg->parent_enable_locking != NULL)
761             if (!drbg->parent_enable_locking(drbg->parent)) {
762                 ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_LOCKING_NOT_ENABLED);
763                 return 0;
764             }
765         drbg->lock = CRYPTO_THREAD_lock_new();
766         if (drbg->lock == NULL) {
767             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_CREATE_LOCK);
768             return 0;
769         }
770     }
771     return 1;
772 }
773 
774 /*
775  * Allocate memory and initialize a new DRBG. The DRBG is allocated on
776  * the secure heap if |secure| is nonzero and the secure heap is enabled.
777  * The |parent|, if not NULL, will be used as random source for reseeding.
778  * This also requires the parent's provider context and the parent's lock.
779  *
780  * Returns a pointer to the new DRBG instance on success, NULL on failure.
781  */
ossl_rand_drbg_new(void * provctx,void * parent,const OSSL_DISPATCH * p_dispatch,int (* dnew)(PROV_DRBG * ctx),void (* dfree)(void * vctx),int (* instantiate)(PROV_DRBG * drbg,const unsigned char * entropy,size_t entropylen,const unsigned char * nonce,size_t noncelen,const unsigned char * pers,size_t perslen),int (* uninstantiate)(PROV_DRBG * ctx),int (* reseed)(PROV_DRBG * drbg,const unsigned char * ent,size_t ent_len,const unsigned char * adin,size_t adin_len),int (* generate)(PROV_DRBG *,unsigned char * out,size_t outlen,const unsigned char * adin,size_t adin_len))782 PROV_DRBG *ossl_rand_drbg_new
783     (void *provctx, void *parent, const OSSL_DISPATCH *p_dispatch,
784      int (*dnew)(PROV_DRBG *ctx),
785      void (*dfree)(void *vctx),
786      int (*instantiate)(PROV_DRBG *drbg,
787                         const unsigned char *entropy, size_t entropylen,
788                         const unsigned char *nonce, size_t noncelen,
789                         const unsigned char *pers, size_t perslen),
790      int (*uninstantiate)(PROV_DRBG *ctx),
791      int (*reseed)(PROV_DRBG *drbg, const unsigned char *ent, size_t ent_len,
792                    const unsigned char *adin, size_t adin_len),
793      int (*generate)(PROV_DRBG *, unsigned char *out, size_t outlen,
794                      const unsigned char *adin, size_t adin_len))
795 {
796     PROV_DRBG *drbg;
797     unsigned int p_str;
798     const OSSL_DISPATCH *pfunc;
799 
800     if (!ossl_prov_is_running())
801         return NULL;
802 
803     drbg = OPENSSL_zalloc(sizeof(*drbg));
804     if (drbg == NULL)
805         return NULL;
806 
807     drbg->provctx = provctx;
808     drbg->instantiate = instantiate;
809     drbg->uninstantiate = uninstantiate;
810     drbg->reseed = reseed;
811     drbg->generate = generate;
812     drbg->fork_id = openssl_get_fork_id();
813 
814     /* Extract parent's functions */
815     drbg->parent = parent;
816     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_ENABLE_LOCKING)) != NULL)
817         drbg->parent_enable_locking = OSSL_FUNC_rand_enable_locking(pfunc);
818     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_LOCK)) != NULL)
819         drbg->parent_lock = OSSL_FUNC_rand_lock(pfunc);
820     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_UNLOCK)) != NULL)
821         drbg->parent_unlock = OSSL_FUNC_rand_unlock(pfunc);
822     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_CTX_PARAMS)) != NULL)
823         drbg->parent_get_ctx_params = OSSL_FUNC_rand_get_ctx_params(pfunc);
824     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_NONCE)) != NULL)
825         drbg->parent_nonce = OSSL_FUNC_rand_nonce(pfunc);
826     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_GET_SEED)) != NULL)
827         drbg->parent_get_seed = OSSL_FUNC_rand_get_seed(pfunc);
828     if ((pfunc = find_call(p_dispatch, OSSL_FUNC_RAND_CLEAR_SEED)) != NULL)
829         drbg->parent_clear_seed = OSSL_FUNC_rand_clear_seed(pfunc);
830 
831     /* Set some default maximums up */
832     drbg->max_entropylen = DRBG_MAX_LENGTH;
833     drbg->max_noncelen = DRBG_MAX_LENGTH;
834     drbg->max_perslen = DRBG_MAX_LENGTH;
835     drbg->max_adinlen = DRBG_MAX_LENGTH;
836     drbg->generate_counter = 1;
837     drbg->reseed_counter = 1;
838     drbg->reseed_interval = RESEED_INTERVAL;
839     drbg->reseed_time_interval = TIME_INTERVAL;
840 
841     if (!dnew(drbg))
842         goto err;
843 
844     if (parent != NULL) {
845         if (!get_parent_strength(drbg, &p_str))
846             goto err;
847         if (drbg->strength > p_str) {
848             /*
849              * We currently don't support the algorithm from NIST SP 800-90C
850              * 10.1.2 to use a weaker DRBG as source
851              */
852             ERR_raise(ERR_LIB_PROV, PROV_R_PARENT_STRENGTH_TOO_WEAK);
853             goto err;
854         }
855     }
856 #ifdef TSAN_REQUIRES_LOCKING
857     if (!ossl_drbg_enable_locking(drbg))
858         goto err;
859 #endif
860     return drbg;
861 
862  err:
863     dfree(drbg);
864     return NULL;
865 }
866 
ossl_rand_drbg_free(PROV_DRBG * drbg)867 void ossl_rand_drbg_free(PROV_DRBG *drbg)
868 {
869     if (drbg == NULL)
870         return;
871 
872     CRYPTO_THREAD_lock_free(drbg->lock);
873     OPENSSL_free(drbg);
874 }
875 
876 /*
877  * Helper function called by internal DRBG implementations. Assumes that at
878  * least a read lock has been taken on drbg->lock
879  */
ossl_drbg_get_ctx_params(PROV_DRBG * drbg,OSSL_PARAM params[])880 int ossl_drbg_get_ctx_params(PROV_DRBG *drbg, OSSL_PARAM params[])
881 {
882     OSSL_PARAM *p;
883 
884     p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STATE);
885     if (p != NULL && !OSSL_PARAM_set_int(p, drbg->state))
886         return 0;
887 
888     p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STRENGTH);
889     if (p != NULL && !OSSL_PARAM_set_int(p, drbg->strength))
890         return 0;
891 
892     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_ENTROPYLEN);
893     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_entropylen))
894         return 0;
895 
896     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ENTROPYLEN);
897     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_entropylen))
898         return 0;
899 
900     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MIN_NONCELEN);
901     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->min_noncelen))
902         return 0;
903 
904     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_NONCELEN);
905     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_noncelen))
906         return 0;
907 
908     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_PERSLEN);
909     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_perslen))
910         return 0;
911 
912     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_MAX_ADINLEN);
913     if (p != NULL && !OSSL_PARAM_set_size_t(p, drbg->max_adinlen))
914         return 0;
915 
916     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
917     if (p != NULL && !OSSL_PARAM_set_uint(p, drbg->reseed_interval))
918         return 0;
919 
920     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME);
921     if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time))
922         return 0;
923 
924     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
925     if (p != NULL && !OSSL_PARAM_set_time_t(p, drbg->reseed_time_interval))
926         return 0;
927     if (!OSSL_FIPS_IND_GET_CTX_PARAM(drbg, params))
928         return 0;
929     return 1;
930 }
931 
932 /*
933  * Helper function to get certain params that require no lock to obtain. Sets
934  * *complete to 1 if all the params were processed, or 0 otherwise
935  */
ossl_drbg_get_ctx_params_no_lock(PROV_DRBG * drbg,OSSL_PARAM params[],int * complete)936 int ossl_drbg_get_ctx_params_no_lock(PROV_DRBG *drbg, OSSL_PARAM params[],
937                                      int *complete)
938 {
939     size_t cnt = 0;
940     OSSL_PARAM *p;
941 
942     /* This value never changes once set */
943     p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_MAX_REQUEST);
944     if (p != NULL) {
945         if (!OSSL_PARAM_set_size_t(p, drbg->max_request))
946             return 0;
947         cnt++;
948     }
949 
950     /*
951      * Can be changed by multiple threads, but we tolerate inaccuracies in this
952      * value.
953      */
954     p = OSSL_PARAM_locate(params, OSSL_DRBG_PARAM_RESEED_COUNTER);
955     if (p != NULL) {
956         if (!OSSL_PARAM_set_uint(p, tsan_load(&drbg->reseed_counter)))
957             return 0;
958         cnt++;
959     }
960 
961     if (params[cnt].key == NULL)
962         *complete = 1;
963     else
964         *complete = 0;
965 
966     return 1;
967 }
968 
ossl_drbg_set_ctx_params(PROV_DRBG * drbg,const OSSL_PARAM params[])969 int ossl_drbg_set_ctx_params(PROV_DRBG *drbg, const OSSL_PARAM params[])
970 {
971     const OSSL_PARAM *p;
972 
973     if (ossl_param_is_empty(params))
974         return 1;
975 
976     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_REQUESTS);
977     if (p != NULL && !OSSL_PARAM_get_uint(p, &drbg->reseed_interval))
978         return 0;
979 
980     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL);
981     if (p != NULL && !OSSL_PARAM_get_time_t(p, &drbg->reseed_time_interval))
982         return 0;
983 
984     return 1;
985 }
986 
987 #ifdef FIPS_MODULE
digest_allowed(const EVP_MD * md)988 static int digest_allowed(const EVP_MD *md)
989 {
990     /* FIPS 140-3 IG D.R limited DRBG digests to a specific set */
991     static const char *const allowed_digests[] = {
992         "SHA1",                     /* SHA 1 allowed */
993         "SHA2-256", "SHA2-512",     /* non-truncated SHA2 allowed */
994         "SHA3-256", "SHA3-512",     /* non-truncated SHA3 allowed */
995     };
996     size_t i;
997 
998     for (i = 0; i < OSSL_NELEM(allowed_digests); i++) {
999         if (EVP_MD_is_a(md, allowed_digests[i]))
1000             return 1;
1001     }
1002     return 0;
1003 }
1004 #endif
1005 
1006 /* Confirm digest is allowed to be used with a DRBG */
ossl_drbg_verify_digest(PROV_DRBG * drbg,OSSL_LIB_CTX * libctx,const EVP_MD * md)1007 int ossl_drbg_verify_digest(PROV_DRBG *drbg, OSSL_LIB_CTX *libctx,
1008                             const EVP_MD *md)
1009 {
1010 #ifdef FIPS_MODULE
1011     int approved = digest_allowed(md);
1012 
1013     if (!approved) {
1014         if (!OSSL_FIPS_IND_ON_UNAPPROVED(drbg, OSSL_FIPS_IND_SETTABLE0,
1015                                          libctx, "DRBG", "Digest",
1016                                          ossl_fips_config_restricted_drbg_digests)) {
1017             ERR_raise(ERR_LIB_PROV, PROV_R_DIGEST_NOT_ALLOWED);
1018             return 0;
1019         }
1020     }
1021 #else   /* FIPS_MODULE */
1022     /* Outside of FIPS, any digests that are not XOF are allowed */
1023     if (EVP_MD_xof(md)) {
1024         ERR_raise(ERR_LIB_PROV, PROV_R_XOF_DIGESTS_NOT_ALLOWED);
1025         return 0;
1026     }
1027 #endif  /* FIPS_MODULE */
1028     return 1;
1029 }
1030