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