Raise an error on syscall failure in tls_retry_write_records
[openssl.git] / crypto / rand / rand_lib.c
1 /*
2  * Copyright 1995-2023 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 /* We need to use some engine deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
12
13 #include <openssl/err.h>
14 #include <openssl/opensslconf.h>
15 #include <openssl/core_names.h>
16 #include "internal/cryptlib.h"
17 #include "internal/thread_once.h"
18 #include "crypto/rand.h"
19 #include "crypto/cryptlib.h"
20 #include "rand_local.h"
21 #include "crypto/context.h"
22
23 #ifndef FIPS_MODULE
24 # include <stdio.h>
25 # include <time.h>
26 # include <limits.h>
27 # include <openssl/conf.h>
28 # include <openssl/trace.h>
29 # include <openssl/engine.h>
30 # include "crypto/rand_pool.h"
31 # include "prov/seeding.h"
32 # include "internal/e_os.h"
33 # include "internal/property.h"
34
35 # ifndef OPENSSL_NO_ENGINE
36 /* non-NULL if default_RAND_meth is ENGINE-provided */
37 static ENGINE *funct_ref;
38 static CRYPTO_RWLOCK *rand_engine_lock;
39 # endif
40 # ifndef OPENSSL_NO_DEPRECATED_3_0
41 static CRYPTO_RWLOCK *rand_meth_lock;
42 static const RAND_METHOD *default_RAND_meth;
43 # endif
44 static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
45
46 static int rand_inited = 0;
47
48 DEFINE_RUN_ONCE_STATIC(do_rand_init)
49 {
50 # ifndef OPENSSL_NO_ENGINE
51     rand_engine_lock = CRYPTO_THREAD_lock_new();
52     if (rand_engine_lock == NULL)
53         return 0;
54 # endif
55
56 # ifndef OPENSSL_NO_DEPRECATED_3_0
57     rand_meth_lock = CRYPTO_THREAD_lock_new();
58     if (rand_meth_lock == NULL)
59         goto err;
60 # endif
61
62     if (!ossl_rand_pool_init())
63         goto err;
64
65     rand_inited = 1;
66     return 1;
67
68  err:
69 # ifndef OPENSSL_NO_DEPRECATED_3_0
70     CRYPTO_THREAD_lock_free(rand_meth_lock);
71     rand_meth_lock = NULL;
72 # endif
73 # ifndef OPENSSL_NO_ENGINE
74     CRYPTO_THREAD_lock_free(rand_engine_lock);
75     rand_engine_lock = NULL;
76 # endif
77     return 0;
78 }
79
80 void ossl_rand_cleanup_int(void)
81 {
82 # ifndef OPENSSL_NO_DEPRECATED_3_0
83     const RAND_METHOD *meth = default_RAND_meth;
84
85     if (!rand_inited)
86         return;
87
88     if (meth != NULL && meth->cleanup != NULL)
89         meth->cleanup();
90     RAND_set_rand_method(NULL);
91 # endif
92     ossl_rand_pool_cleanup();
93 # ifndef OPENSSL_NO_ENGINE
94     CRYPTO_THREAD_lock_free(rand_engine_lock);
95     rand_engine_lock = NULL;
96 # endif
97 # ifndef OPENSSL_NO_DEPRECATED_3_0
98     CRYPTO_THREAD_lock_free(rand_meth_lock);
99     rand_meth_lock = NULL;
100 # endif
101     ossl_release_default_drbg_ctx();
102     rand_inited = 0;
103 }
104
105 /*
106  * RAND_close_seed_files() ensures that any seed file descriptors are
107  * closed after use.  This only applies to libcrypto/default provider,
108  * it does not apply to other providers.
109  */
110 void RAND_keep_random_devices_open(int keep)
111 {
112     if (RUN_ONCE(&rand_init, do_rand_init))
113         ossl_rand_pool_keep_random_devices_open(keep);
114 }
115
116 /*
117  * RAND_poll() reseeds the default RNG using random input
118  *
119  * The random input is obtained from polling various entropy
120  * sources which depend on the operating system and are
121  * configurable via the --with-rand-seed configure option.
122  */
123 int RAND_poll(void)
124 {
125     static const char salt[] = "polling";
126
127 # ifndef OPENSSL_NO_DEPRECATED_3_0
128     const RAND_METHOD *meth = RAND_get_rand_method();
129     int ret = meth == RAND_OpenSSL();
130
131     if (meth == NULL)
132         return 0;
133
134     if (!ret) {
135         /* fill random pool and seed the current legacy RNG */
136         RAND_POOL *pool = ossl_rand_pool_new(RAND_DRBG_STRENGTH, 1,
137                                              (RAND_DRBG_STRENGTH + 7) / 8,
138                                              RAND_POOL_MAX_LENGTH);
139
140         if (pool == NULL)
141             return 0;
142
143         if (ossl_pool_acquire_entropy(pool) == 0)
144             goto err;
145
146         if (meth->add == NULL
147             || meth->add(ossl_rand_pool_buffer(pool),
148                          ossl_rand_pool_length(pool),
149                          (ossl_rand_pool_entropy(pool) / 8.0)) == 0)
150             goto err;
151
152         ret = 1;
153      err:
154         ossl_rand_pool_free(pool);
155         return ret;
156     }
157 # endif
158
159     RAND_seed(salt, sizeof(salt));
160     return 1;
161 }
162
163 # ifndef OPENSSL_NO_DEPRECATED_3_0
164 static int rand_set_rand_method_internal(const RAND_METHOD *meth,
165                                          ossl_unused ENGINE *e)
166 {
167     if (!RUN_ONCE(&rand_init, do_rand_init))
168         return 0;
169
170     if (!CRYPTO_THREAD_write_lock(rand_meth_lock))
171         return 0;
172 #  ifndef OPENSSL_NO_ENGINE
173     ENGINE_finish(funct_ref);
174     funct_ref = e;
175 #  endif
176     default_RAND_meth = meth;
177     CRYPTO_THREAD_unlock(rand_meth_lock);
178     return 1;
179 }
180
181 int RAND_set_rand_method(const RAND_METHOD *meth)
182 {
183     return rand_set_rand_method_internal(meth, NULL);
184 }
185
186 const RAND_METHOD *RAND_get_rand_method(void)
187 {
188     const RAND_METHOD *tmp_meth = NULL;
189
190     if (!RUN_ONCE(&rand_init, do_rand_init))
191         return NULL;
192
193     if (!CRYPTO_THREAD_read_lock(rand_meth_lock))
194         return NULL;
195     tmp_meth = default_RAND_meth;
196     CRYPTO_THREAD_unlock(rand_meth_lock);
197     if (tmp_meth != NULL)
198         return tmp_meth;
199
200     if (!CRYPTO_THREAD_write_lock(rand_meth_lock))
201         return NULL;
202     if (default_RAND_meth == NULL) {
203 #  ifndef OPENSSL_NO_ENGINE
204         ENGINE *e;
205
206         /* If we have an engine that can do RAND, use it. */
207         if ((e = ENGINE_get_default_RAND()) != NULL
208                 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
209             funct_ref = e;
210             default_RAND_meth = tmp_meth;
211         } else {
212             ENGINE_finish(e);
213             default_RAND_meth = &ossl_rand_meth;
214         }
215 #  else
216         default_RAND_meth = &ossl_rand_meth;
217 #  endif
218     }
219     tmp_meth = default_RAND_meth;
220     CRYPTO_THREAD_unlock(rand_meth_lock);
221     return tmp_meth;
222 }
223
224 #  if !defined(OPENSSL_NO_ENGINE)
225 int RAND_set_rand_engine(ENGINE *engine)
226 {
227     const RAND_METHOD *tmp_meth = NULL;
228
229     if (!RUN_ONCE(&rand_init, do_rand_init))
230         return 0;
231
232     if (engine != NULL) {
233         if (!ENGINE_init(engine))
234             return 0;
235         tmp_meth = ENGINE_get_RAND(engine);
236         if (tmp_meth == NULL) {
237             ENGINE_finish(engine);
238             return 0;
239         }
240     }
241     if (!CRYPTO_THREAD_write_lock(rand_engine_lock)) {
242         ENGINE_finish(engine);
243         return 0;
244     }
245
246     /* This function releases any prior ENGINE so call it first */
247     rand_set_rand_method_internal(tmp_meth, engine);
248     CRYPTO_THREAD_unlock(rand_engine_lock);
249     return 1;
250 }
251 #  endif
252 # endif /* OPENSSL_NO_DEPRECATED_3_0 */
253
254 void RAND_seed(const void *buf, int num)
255 {
256     EVP_RAND_CTX *drbg;
257 # ifndef OPENSSL_NO_DEPRECATED_3_0
258     const RAND_METHOD *meth = RAND_get_rand_method();
259
260     if (meth != NULL && meth->seed != NULL) {
261         meth->seed(buf, num);
262         return;
263     }
264 # endif
265
266     drbg = RAND_get0_primary(NULL);
267     if (drbg != NULL && num > 0)
268         EVP_RAND_reseed(drbg, 0, NULL, 0, buf, num);
269 }
270
271 void RAND_add(const void *buf, int num, double randomness)
272 {
273     EVP_RAND_CTX *drbg;
274 # ifndef OPENSSL_NO_DEPRECATED_3_0
275     const RAND_METHOD *meth = RAND_get_rand_method();
276
277     if (meth != NULL && meth->add != NULL) {
278         meth->add(buf, num, randomness);
279         return;
280     }
281 # endif
282     drbg = RAND_get0_primary(NULL);
283     if (drbg != NULL && num > 0)
284 # ifdef OPENSSL_RAND_SEED_NONE
285         /* Without an entropy source, we have to rely on the user */
286         EVP_RAND_reseed(drbg, 0, buf, num, NULL, 0);
287 # else
288         /* With an entropy source, we downgrade this to additional input */
289         EVP_RAND_reseed(drbg, 0, NULL, 0, buf, num);
290 # endif
291 }
292
293 # if !defined(OPENSSL_NO_DEPRECATED_1_1_0)
294 int RAND_pseudo_bytes(unsigned char *buf, int num)
295 {
296     const RAND_METHOD *meth = RAND_get_rand_method();
297
298     if (meth != NULL && meth->pseudorand != NULL)
299         return meth->pseudorand(buf, num);
300     ERR_raise(ERR_LIB_RAND, RAND_R_FUNC_NOT_IMPLEMENTED);
301     return -1;
302 }
303 # endif
304
305 int RAND_status(void)
306 {
307     EVP_RAND_CTX *rand;
308 # ifndef OPENSSL_NO_DEPRECATED_3_0
309     const RAND_METHOD *meth = RAND_get_rand_method();
310
311     if (meth != NULL && meth != RAND_OpenSSL())
312         return meth->status != NULL ? meth->status() : 0;
313 # endif
314
315     if ((rand = RAND_get0_primary(NULL)) == NULL)
316         return 0;
317     return EVP_RAND_get_state(rand) == EVP_RAND_STATE_READY;
318 }
319 # else  /* !FIPS_MODULE */
320
321 # ifndef OPENSSL_NO_DEPRECATED_3_0
322 const RAND_METHOD *RAND_get_rand_method(void)
323 {
324     return NULL;
325 }
326 # endif
327 #endif /* !FIPS_MODULE */
328
329 /*
330  * This function is not part of RAND_METHOD, so if we're not using
331  * the default method, then just call RAND_bytes().  Otherwise make
332  * sure we're instantiated and use the private DRBG.
333  */
334 int RAND_priv_bytes_ex(OSSL_LIB_CTX *ctx, unsigned char *buf, size_t num,
335                        unsigned int strength)
336 {
337     EVP_RAND_CTX *rand;
338 #if !defined(OPENSSL_NO_DEPRECATED_3_0) && !defined(FIPS_MODULE)
339     const RAND_METHOD *meth = RAND_get_rand_method();
340
341     if (meth != NULL && meth != RAND_OpenSSL()) {
342         if (meth->bytes != NULL)
343             return meth->bytes(buf, num);
344         ERR_raise(ERR_LIB_RAND, RAND_R_FUNC_NOT_IMPLEMENTED);
345         return -1;
346     }
347 #endif
348
349     rand = RAND_get0_private(ctx);
350     if (rand != NULL)
351         return EVP_RAND_generate(rand, buf, num, strength, 0, NULL, 0);
352
353     return 0;
354 }
355
356 int RAND_priv_bytes(unsigned char *buf, int num)
357 {
358     if (num < 0)
359         return 0;
360     return RAND_priv_bytes_ex(NULL, buf, (size_t)num, 0);
361 }
362
363 int RAND_bytes_ex(OSSL_LIB_CTX *ctx, unsigned char *buf, size_t num,
364                   unsigned int strength)
365 {
366     EVP_RAND_CTX *rand;
367 #if !defined(OPENSSL_NO_DEPRECATED_3_0) && !defined(FIPS_MODULE)
368     const RAND_METHOD *meth = RAND_get_rand_method();
369
370     if (meth != NULL && meth != RAND_OpenSSL()) {
371         if (meth->bytes != NULL)
372             return meth->bytes(buf, num);
373         ERR_raise(ERR_LIB_RAND, RAND_R_FUNC_NOT_IMPLEMENTED);
374         return -1;
375     }
376 #endif
377
378     rand = RAND_get0_public(ctx);
379     if (rand != NULL)
380         return EVP_RAND_generate(rand, buf, num, strength, 0, NULL, 0);
381
382     return 0;
383 }
384
385 int RAND_bytes(unsigned char *buf, int num)
386 {
387     if (num < 0)
388         return 0;
389     return RAND_bytes_ex(NULL, buf, (size_t)num, 0);
390 }
391
392 typedef struct rand_global_st {
393     /*
394      * The three shared DRBG instances
395      *
396      * There are three shared DRBG instances: <primary>, <public>, and
397      * <private>.  The <public> and <private> DRBGs are secondary ones.
398      * These are used for non-secret (e.g. nonces) and secret
399      * (e.g. private keys) data respectively.
400      */
401     CRYPTO_RWLOCK *lock;
402
403     EVP_RAND_CTX *seed;
404
405     /*
406      * The <primary> DRBG
407      *
408      * Not used directly by the application, only for reseeding the two other
409      * DRBGs. It reseeds itself by pulling either randomness from os entropy
410      * sources or by consuming randomness which was added by RAND_add().
411      *
412      * The <primary> DRBG is a global instance which is accessed concurrently by
413      * all threads. The necessary locking is managed automatically by its child
414      * DRBG instances during reseeding.
415      */
416     EVP_RAND_CTX *primary;
417
418     /*
419      * The <public> DRBG
420      *
421      * Used by default for generating random bytes using RAND_bytes().
422      *
423      * The <public> secondary DRBG is thread-local, i.e., there is one instance
424      * per thread.
425      */
426     CRYPTO_THREAD_LOCAL public;
427
428     /*
429      * The <private> DRBG
430      *
431      * Used by default for generating private keys using RAND_priv_bytes()
432      *
433      * The <private> secondary DRBG is thread-local, i.e., there is one
434      * instance per thread.
435      */
436     CRYPTO_THREAD_LOCAL private;
437
438     /* Which RNG is being used by default and it's configuration settings */
439     char *rng_name;
440     char *rng_cipher;
441     char *rng_digest;
442     char *rng_propq;
443
444     /* Allow the randomness source to be changed */
445     char *seed_name;
446     char *seed_propq;
447 } RAND_GLOBAL;
448
449 /*
450  * Initialize the OSSL_LIB_CTX global DRBGs on first use.
451  * Returns the allocated global data on success or NULL on failure.
452  */
453 void *ossl_rand_ctx_new(OSSL_LIB_CTX *libctx)
454 {
455     RAND_GLOBAL *dgbl = OPENSSL_zalloc(sizeof(*dgbl));
456
457     if (dgbl == NULL)
458         return NULL;
459
460 #ifndef FIPS_MODULE
461     /*
462      * We need to ensure that base libcrypto thread handling has been
463      * initialised.
464      */
465      OPENSSL_init_crypto(OPENSSL_INIT_BASE_ONLY, NULL);
466 #endif
467
468     dgbl->lock = CRYPTO_THREAD_lock_new();
469     if (dgbl->lock == NULL)
470         goto err1;
471
472     if (!CRYPTO_THREAD_init_local(&dgbl->private, NULL))
473         goto err1;
474
475     if (!CRYPTO_THREAD_init_local(&dgbl->public, NULL))
476         goto err2;
477
478     return dgbl;
479
480  err2:
481     CRYPTO_THREAD_cleanup_local(&dgbl->private);
482  err1:
483     CRYPTO_THREAD_lock_free(dgbl->lock);
484     OPENSSL_free(dgbl);
485     return NULL;
486 }
487
488 void ossl_rand_ctx_free(void *vdgbl)
489 {
490     RAND_GLOBAL *dgbl = vdgbl;
491
492     if (dgbl == NULL)
493         return;
494
495     CRYPTO_THREAD_lock_free(dgbl->lock);
496     CRYPTO_THREAD_cleanup_local(&dgbl->private);
497     CRYPTO_THREAD_cleanup_local(&dgbl->public);
498     EVP_RAND_CTX_free(dgbl->primary);
499     EVP_RAND_CTX_free(dgbl->seed);
500     OPENSSL_free(dgbl->rng_name);
501     OPENSSL_free(dgbl->rng_cipher);
502     OPENSSL_free(dgbl->rng_digest);
503     OPENSSL_free(dgbl->rng_propq);
504     OPENSSL_free(dgbl->seed_name);
505     OPENSSL_free(dgbl->seed_propq);
506
507     OPENSSL_free(dgbl);
508 }
509
510 static RAND_GLOBAL *rand_get_global(OSSL_LIB_CTX *libctx)
511 {
512     return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DRBG_INDEX);
513 }
514
515 static void rand_delete_thread_state(void *arg)
516 {
517     OSSL_LIB_CTX *ctx = arg;
518     RAND_GLOBAL *dgbl = rand_get_global(ctx);
519     EVP_RAND_CTX *rand;
520
521     if (dgbl == NULL)
522         return;
523
524     rand = CRYPTO_THREAD_get_local(&dgbl->public);
525     CRYPTO_THREAD_set_local(&dgbl->public, NULL);
526     EVP_RAND_CTX_free(rand);
527
528     rand = CRYPTO_THREAD_get_local(&dgbl->private);
529     CRYPTO_THREAD_set_local(&dgbl->private, NULL);
530     EVP_RAND_CTX_free(rand);
531 }
532
533 #ifndef FIPS_MODULE
534 static EVP_RAND_CTX *rand_new_seed(OSSL_LIB_CTX *libctx)
535 {
536     EVP_RAND *rand;
537     RAND_GLOBAL *dgbl = rand_get_global(libctx);
538     EVP_RAND_CTX *ctx = NULL;
539     const char *propq;
540     char *name, *props = NULL;
541     size_t props_len;
542     OSSL_PROPERTY_LIST *pl1, *pl2, *pl3 = NULL;
543
544     if (dgbl == NULL)
545         return NULL;
546     propq = dgbl->seed_propq;
547     if (dgbl->seed_name != NULL) {
548         name = dgbl->seed_name;
549     } else {
550         /*
551          * Default to our internal seed source.  This isn't part of the FIPS
552          * provider so we need to override any FIPS properties.
553          */
554         if (propq == NULL || *propq == '\0') {
555             propq = "-fips";
556         } else {
557             pl1 = ossl_parse_query(libctx, propq, 1);
558             if (pl1 == NULL) {
559                 ERR_raise(ERR_LIB_RAND, RAND_R_INVALID_PROPERTY_QUERY);
560                 return NULL;
561             }
562             pl2 = ossl_parse_query(libctx, "-fips", 1);
563             if (pl2 == NULL) {
564                 ossl_property_free(pl1);
565                 ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
566                 return NULL;
567             }
568             pl3 = ossl_property_merge(pl2, pl1);
569             ossl_property_free(pl1);
570             ossl_property_free(pl2);
571             if (pl3 == NULL) {
572                 ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
573                 return NULL;
574             }
575             props_len = ossl_property_list_to_string(libctx, pl3, NULL, 0);
576             if (props_len == 0) {
577                 /* Shouldn't happen since we added a query element */
578                 ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
579                 goto err;
580             } else {
581                 props = OPENSSL_malloc(props_len);
582                 if (props == NULL) {
583                     ERR_raise(ERR_LIB_RAND, ERR_R_MALLOC_FAILURE);
584                     goto err;
585                 }
586                 if (ossl_property_list_to_string(libctx, pl3,
587                                                  props, props_len) == 0) {
588                     ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
589                     goto err;
590                 }
591                 ossl_property_free(pl3);
592                 pl3 = NULL;
593                 propq = props;
594             }
595         }
596         name = "SEED-SRC";
597     }
598
599     rand = EVP_RAND_fetch(libctx, name, propq);
600     if (rand == NULL) {
601         ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_FETCH_DRBG);
602         goto err;
603     }
604     ctx = EVP_RAND_CTX_new(rand, NULL);
605     EVP_RAND_free(rand);
606     if (ctx == NULL) {
607         ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_CREATE_DRBG);
608         goto err;
609     }
610     if (!EVP_RAND_instantiate(ctx, 0, 0, NULL, 0, NULL)) {
611         ERR_raise(ERR_LIB_RAND, RAND_R_ERROR_INSTANTIATING_DRBG);
612         goto err;
613     }
614     OPENSSL_free(props);
615     return ctx;
616  err:
617     EVP_RAND_CTX_free(ctx);
618     ossl_property_free(pl3);
619     OPENSSL_free(props);
620     return NULL;
621 }
622
623 EVP_RAND_CTX *ossl_rand_get0_seed_noncreating(OSSL_LIB_CTX *ctx)
624 {
625     RAND_GLOBAL *dgbl = rand_get_global(ctx);
626     EVP_RAND_CTX *ret;
627
628     if (dgbl == NULL)
629         return NULL;
630
631     if (!CRYPTO_THREAD_read_lock(dgbl->lock))
632         return NULL;
633     ret = dgbl->seed;
634     CRYPTO_THREAD_unlock(dgbl->lock);
635     return ret;
636 }
637 #endif
638
639 static EVP_RAND_CTX *rand_new_drbg(OSSL_LIB_CTX *libctx, EVP_RAND_CTX *parent,
640                                    unsigned int reseed_interval,
641                                    time_t reseed_time_interval, int use_df)
642 {
643     EVP_RAND *rand;
644     RAND_GLOBAL *dgbl = rand_get_global(libctx);
645     EVP_RAND_CTX *ctx;
646     OSSL_PARAM params[8], *p = params;
647     const OSSL_PARAM *settables;
648     char *name, *cipher;
649
650     if (dgbl == NULL)
651         return NULL;
652     name = dgbl->rng_name != NULL ? dgbl->rng_name : "CTR-DRBG";
653     rand = EVP_RAND_fetch(libctx, name, dgbl->rng_propq);
654     if (rand == NULL) {
655         ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_FETCH_DRBG);
656         return NULL;
657     }
658     ctx = EVP_RAND_CTX_new(rand, parent);
659     EVP_RAND_free(rand);
660     if (ctx == NULL) {
661         ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_CREATE_DRBG);
662         return NULL;
663     }
664
665     settables = EVP_RAND_CTX_settable_params(ctx);
666     if (OSSL_PARAM_locate_const(settables, OSSL_DRBG_PARAM_CIPHER)) {
667         cipher = dgbl->rng_cipher != NULL ? dgbl->rng_cipher : "AES-256-CTR";
668         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_CIPHER,
669                                                 cipher, 0);
670     }
671     if (dgbl->rng_digest != NULL
672             && OSSL_PARAM_locate_const(settables, OSSL_DRBG_PARAM_DIGEST))
673         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_DIGEST,
674                                                 dgbl->rng_digest, 0);
675     if (dgbl->rng_propq != NULL)
676         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_PROPERTIES,
677                                                 dgbl->rng_propq, 0);
678     if (OSSL_PARAM_locate_const(settables, OSSL_ALG_PARAM_MAC))
679         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_MAC, "HMAC", 0);
680     if (OSSL_PARAM_locate_const(settables, OSSL_DRBG_PARAM_USE_DF))
681         *p++ = OSSL_PARAM_construct_int(OSSL_DRBG_PARAM_USE_DF, &use_df);
682     *p++ = OSSL_PARAM_construct_uint(OSSL_DRBG_PARAM_RESEED_REQUESTS,
683                                      &reseed_interval);
684     *p++ = OSSL_PARAM_construct_time_t(OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL,
685                                        &reseed_time_interval);
686     *p = OSSL_PARAM_construct_end();
687     if (!EVP_RAND_instantiate(ctx, 0, 0, NULL, 0, params)) {
688         ERR_raise(ERR_LIB_RAND, RAND_R_ERROR_INSTANTIATING_DRBG);
689         EVP_RAND_CTX_free(ctx);
690         return NULL;
691     }
692     return ctx;
693 }
694
695 /*
696  * Get the primary random generator.
697  * Returns pointer to its EVP_RAND_CTX on success, NULL on failure.
698  *
699  */
700 EVP_RAND_CTX *RAND_get0_primary(OSSL_LIB_CTX *ctx)
701 {
702     RAND_GLOBAL *dgbl = rand_get_global(ctx);
703     EVP_RAND_CTX *ret;
704
705     if (dgbl == NULL)
706         return NULL;
707
708     if (!CRYPTO_THREAD_read_lock(dgbl->lock))
709         return NULL;
710
711     ret = dgbl->primary;
712     CRYPTO_THREAD_unlock(dgbl->lock);
713
714     if (ret != NULL)
715         return ret;
716
717     if (!CRYPTO_THREAD_write_lock(dgbl->lock))
718         return NULL;
719
720     ret = dgbl->primary;
721     if (ret != NULL) {
722         CRYPTO_THREAD_unlock(dgbl->lock);
723         return ret;
724     }
725
726 #ifndef FIPS_MODULE
727     if (dgbl->seed == NULL) {
728         ERR_set_mark();
729         dgbl->seed = rand_new_seed(ctx);
730         ERR_pop_to_mark();
731     }
732 #endif
733
734     ret = dgbl->primary = rand_new_drbg(ctx, dgbl->seed,
735                                         PRIMARY_RESEED_INTERVAL,
736                                         PRIMARY_RESEED_TIME_INTERVAL, 1);
737     /*
738     * The primary DRBG may be shared between multiple threads so we must
739     * enable locking.
740     */
741     if (ret != NULL && !EVP_RAND_enable_locking(ret)) {
742         ERR_raise(ERR_LIB_EVP, EVP_R_UNABLE_TO_ENABLE_LOCKING);
743         EVP_RAND_CTX_free(ret);
744         ret = dgbl->primary = NULL;
745     }
746     CRYPTO_THREAD_unlock(dgbl->lock);
747
748     return ret;
749 }
750
751 /*
752  * Get the public random generator.
753  * Returns pointer to its EVP_RAND_CTX on success, NULL on failure.
754  */
755 EVP_RAND_CTX *RAND_get0_public(OSSL_LIB_CTX *ctx)
756 {
757     RAND_GLOBAL *dgbl = rand_get_global(ctx);
758     EVP_RAND_CTX *rand, *primary;
759
760     if (dgbl == NULL)
761         return NULL;
762
763     rand = CRYPTO_THREAD_get_local(&dgbl->public);
764     if (rand == NULL) {
765         primary = RAND_get0_primary(ctx);
766         if (primary == NULL)
767             return NULL;
768
769         ctx = ossl_lib_ctx_get_concrete(ctx);
770         /*
771          * If the private is also NULL then this is the first time we've
772          * used this thread.
773          */
774         if (CRYPTO_THREAD_get_local(&dgbl->private) == NULL
775                 && !ossl_init_thread_start(NULL, ctx, rand_delete_thread_state))
776             return NULL;
777         rand = rand_new_drbg(ctx, primary, SECONDARY_RESEED_INTERVAL,
778                              SECONDARY_RESEED_TIME_INTERVAL, 0);
779         CRYPTO_THREAD_set_local(&dgbl->public, rand);
780     }
781     return rand;
782 }
783
784 /*
785  * Get the private random generator.
786  * Returns pointer to its EVP_RAND_CTX on success, NULL on failure.
787  */
788 EVP_RAND_CTX *RAND_get0_private(OSSL_LIB_CTX *ctx)
789 {
790     RAND_GLOBAL *dgbl = rand_get_global(ctx);
791     EVP_RAND_CTX *rand, *primary;
792
793     if (dgbl == NULL)
794         return NULL;
795
796     rand = CRYPTO_THREAD_get_local(&dgbl->private);
797     if (rand == NULL) {
798         primary = RAND_get0_primary(ctx);
799         if (primary == NULL)
800             return NULL;
801
802         ctx = ossl_lib_ctx_get_concrete(ctx);
803         /*
804          * If the public is also NULL then this is the first time we've
805          * used this thread.
806          */
807         if (CRYPTO_THREAD_get_local(&dgbl->public) == NULL
808                 && !ossl_init_thread_start(NULL, ctx, rand_delete_thread_state))
809             return NULL;
810         rand = rand_new_drbg(ctx, primary, SECONDARY_RESEED_INTERVAL,
811                              SECONDARY_RESEED_TIME_INTERVAL, 0);
812         CRYPTO_THREAD_set_local(&dgbl->private, rand);
813     }
814     return rand;
815 }
816
817 #ifdef FIPS_MODULE
818 EVP_RAND_CTX *ossl_rand_get0_private_noncreating(OSSL_LIB_CTX *ctx)
819 {
820     RAND_GLOBAL *dgbl = rand_get_global(ctx);
821
822     if (dgbl == NULL)
823         return NULL;
824
825     return CRYPTO_THREAD_get_local(&dgbl->private);
826 }
827 #endif
828
829 int RAND_set0_public(OSSL_LIB_CTX *ctx, EVP_RAND_CTX *rand)
830 {
831     RAND_GLOBAL *dgbl = rand_get_global(ctx);
832     EVP_RAND_CTX *old;
833     int r;
834
835     if (dgbl == NULL)
836         return 0;
837     old = CRYPTO_THREAD_get_local(&dgbl->public);
838     if ((r = CRYPTO_THREAD_set_local(&dgbl->public, rand)) > 0)
839         EVP_RAND_CTX_free(old);
840     return r;
841 }
842
843 int RAND_set0_private(OSSL_LIB_CTX *ctx, EVP_RAND_CTX *rand)
844 {
845     RAND_GLOBAL *dgbl = rand_get_global(ctx);
846     EVP_RAND_CTX *old;
847     int r;
848
849     if (dgbl == NULL)
850         return 0;
851     old = CRYPTO_THREAD_get_local(&dgbl->private);
852     if ((r = CRYPTO_THREAD_set_local(&dgbl->private, rand)) > 0)
853         EVP_RAND_CTX_free(old);
854     return r;
855 }
856
857 #ifndef FIPS_MODULE
858 static int random_set_string(char **p, const char *s)
859 {
860     char *d = NULL;
861
862     if (s != NULL) {
863         d = OPENSSL_strdup(s);
864         if (d == NULL)
865             return 0;
866     }
867     OPENSSL_free(*p);
868     *p = d;
869     return 1;
870 }
871
872 /*
873  * Load the DRBG definitions from a configuration file.
874  */
875 static int random_conf_init(CONF_IMODULE *md, const CONF *cnf)
876 {
877     STACK_OF(CONF_VALUE) *elist;
878     CONF_VALUE *cval;
879     RAND_GLOBAL *dgbl = rand_get_global(NCONF_get0_libctx((CONF *)cnf));
880     int i, r = 1;
881
882     OSSL_TRACE1(CONF, "Loading random module: section %s\n",
883                 CONF_imodule_get_value(md));
884
885     /* Value is a section containing RANDOM configuration */
886     elist = NCONF_get_section(cnf, CONF_imodule_get_value(md));
887     if (elist == NULL) {
888         ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_RANDOM_SECTION_ERROR);
889         return 0;
890     }
891
892     if (dgbl == NULL)
893         return 0;
894
895     for (i = 0; i < sk_CONF_VALUE_num(elist); i++) {
896         cval = sk_CONF_VALUE_value(elist, i);
897         if (OPENSSL_strcasecmp(cval->name, "random") == 0) {
898             if (!random_set_string(&dgbl->rng_name, cval->value))
899                 return 0;
900         } else if (OPENSSL_strcasecmp(cval->name, "cipher") == 0) {
901             if (!random_set_string(&dgbl->rng_cipher, cval->value))
902                 return 0;
903         } else if (OPENSSL_strcasecmp(cval->name, "digest") == 0) {
904             if (!random_set_string(&dgbl->rng_digest, cval->value))
905                 return 0;
906         } else if (OPENSSL_strcasecmp(cval->name, "properties") == 0) {
907             if (!random_set_string(&dgbl->rng_propq, cval->value))
908                 return 0;
909         } else if (OPENSSL_strcasecmp(cval->name, "seed") == 0) {
910             if (!random_set_string(&dgbl->seed_name, cval->value))
911                 return 0;
912         } else if (OPENSSL_strcasecmp(cval->name, "seed_properties") == 0) {
913             if (!random_set_string(&dgbl->seed_propq, cval->value))
914                 return 0;
915         } else {
916             ERR_raise_data(ERR_LIB_CRYPTO,
917                            CRYPTO_R_UNKNOWN_NAME_IN_RANDOM_SECTION,
918                            "name=%s, value=%s", cval->name, cval->value);
919             r = 0;
920         }
921     }
922     return r;
923 }
924
925
926 static void random_conf_deinit(CONF_IMODULE *md)
927 {
928     OSSL_TRACE(CONF, "Cleaned up random\n");
929 }
930
931 void ossl_random_add_conf_module(void)
932 {
933     OSSL_TRACE(CONF, "Adding config module 'random'\n");
934     CONF_module_add("random", random_conf_init, random_conf_deinit);
935 }
936
937 int RAND_set_DRBG_type(OSSL_LIB_CTX *ctx, const char *drbg, const char *propq,
938                        const char *cipher, const char *digest)
939 {
940     RAND_GLOBAL *dgbl = rand_get_global(ctx);
941
942     if (dgbl == NULL)
943         return 0;
944     if (dgbl->primary != NULL) {
945         ERR_raise(ERR_LIB_CRYPTO, RAND_R_ALREADY_INSTANTIATED);
946         return 0;
947     }
948     return random_set_string(&dgbl->rng_name, drbg)
949         && random_set_string(&dgbl->rng_propq, propq)
950         && random_set_string(&dgbl->rng_cipher, cipher)
951         && random_set_string(&dgbl->rng_digest, digest);
952 }
953
954 int RAND_set_seed_source_type(OSSL_LIB_CTX *ctx, const char *seed,
955                               const char *propq)
956 {
957     RAND_GLOBAL *dgbl = rand_get_global(ctx);
958
959     if (dgbl == NULL)
960         return 0;
961     if (dgbl->seed != NULL) {
962         ERR_raise(ERR_LIB_CRYPTO, RAND_R_ALREADY_INSTANTIATED);
963         return 0;
964     }
965     return random_set_string(&dgbl->seed_name, seed)
966         && random_set_string(&dgbl->seed_propq, propq);
967 }
968
969 #endif