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