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