xref: /openssl/crypto/rand/rand_lib.c (revision 3a01d5d6)
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 #if !defined(FIPS_MODULE) || !defined(OPENSSL_NO_FIPS_JITTER)
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     const char *propq;
542     char *name;
543     EVP_RAND_CTX *ctx = NULL;
544 # ifdef OPENSSL_NO_FIPS_JITTER
545     RAND_GLOBAL *dgbl = rand_get_global(libctx);
546     char *props = NULL;
547     size_t props_len;
548     OSSL_PROPERTY_LIST *pl1, *pl2, *pl3 = NULL;
549 
550     if (dgbl == NULL)
551         return NULL;
552     propq = dgbl->seed_propq;
553     if (dgbl->seed_name != NULL) {
554         name = dgbl->seed_name;
555     } else {
556         /*
557          * Default to our internal seed source.  This isn't part of the FIPS
558          * provider so we need to override any FIPS properties.
559          */
560         if (propq == NULL || *propq == '\0') {
561             propq = "-fips";
562         } else {
563             pl1 = ossl_parse_query(libctx, propq, 1);
564             if (pl1 == NULL) {
565                 ERR_raise(ERR_LIB_RAND, RAND_R_INVALID_PROPERTY_QUERY);
566                 return NULL;
567             }
568             pl2 = ossl_parse_query(libctx, "-fips", 1);
569             if (pl2 == NULL) {
570                 ossl_property_free(pl1);
571                 ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
572                 return NULL;
573             }
574             pl3 = ossl_property_merge(pl2, pl1);
575             ossl_property_free(pl1);
576             ossl_property_free(pl2);
577             if (pl3 == NULL) {
578                 ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
579                 return NULL;
580             }
581             props_len = ossl_property_list_to_string(libctx, pl3, NULL, 0);
582             if (props_len == 0) {
583                 /* Shouldn't happen since we added a query element */
584                 ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
585                 goto err;
586             } else {
587                 props = OPENSSL_malloc(props_len);
588                 if (props == NULL) {
589                     ERR_raise(ERR_LIB_RAND, ERR_R_MALLOC_FAILURE);
590                     goto err;
591                 }
592                 if (ossl_property_list_to_string(libctx, pl3,
593                                                  props, props_len) == 0) {
594                     ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
595                     goto err;
596                 }
597                 ossl_property_free(pl3);
598                 pl3 = NULL;
599                 propq = props;
600             }
601         }
602         name = OPENSSL_MSTR(OPENSSL_DEFAULT_SEED_SRC);
603     }
604 # else /* !OPENSSL_NO_FIPS_JITTER */
605     name = "JITTER";
606     propq = "-fips";  /* precautionary: shouldn't matter since it's internal */
607 # endif /* OPENSSL_NO_FIPS_JITTER */
608 
609     rand = EVP_RAND_fetch(libctx, name, propq);
610     if (rand == NULL) {
611         ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_FETCH_DRBG);
612         goto err;
613     }
614     ctx = EVP_RAND_CTX_new(rand, NULL);
615     EVP_RAND_free(rand);
616     if (ctx == NULL) {
617         ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_CREATE_DRBG);
618         goto err;
619     }
620     if (!EVP_RAND_instantiate(ctx, 0, 0, NULL, 0, NULL)) {
621         ERR_raise(ERR_LIB_RAND, RAND_R_ERROR_INSTANTIATING_DRBG);
622         goto err;
623     }
624 # ifdef OPENSSL_NO_FIPS_JITTER
625     OPENSSL_free(props);
626 # endif /* OPENSSL_NO_FIPS_JITTER */
627     return ctx;
628  err:
629     EVP_RAND_CTX_free(ctx);
630 # ifdef OPENSSL_NO_FIPS_JITTER
631     ossl_property_free(pl3);
632     OPENSSL_free(props);
633 # endif /* OPENSSL_NO_FIPS_JITTER */
634     return NULL;
635 }
636 #endif  /* !FIPS_MODULE || !OPENSSL_NO_FIPS_JITTER */
637 
638 #ifndef FIPS_MODULE
ossl_rand_get0_seed_noncreating(OSSL_LIB_CTX * ctx)639 EVP_RAND_CTX *ossl_rand_get0_seed_noncreating(OSSL_LIB_CTX *ctx)
640 {
641     RAND_GLOBAL *dgbl = rand_get_global(ctx);
642     EVP_RAND_CTX *ret;
643 
644     if (dgbl == NULL)
645         return NULL;
646 
647     if (!CRYPTO_THREAD_read_lock(dgbl->lock))
648         return NULL;
649     ret = dgbl->seed;
650     CRYPTO_THREAD_unlock(dgbl->lock);
651     return ret;
652 }
653 #endif  /* !FIPS_MODULE */
654 
rand_new_drbg(OSSL_LIB_CTX * libctx,EVP_RAND_CTX * parent,unsigned int reseed_interval,time_t reseed_time_interval)655 static EVP_RAND_CTX *rand_new_drbg(OSSL_LIB_CTX *libctx, EVP_RAND_CTX *parent,
656                                    unsigned int reseed_interval,
657                                    time_t reseed_time_interval)
658 {
659     EVP_RAND *rand;
660     RAND_GLOBAL *dgbl = rand_get_global(libctx);
661     EVP_RAND_CTX *ctx;
662     OSSL_PARAM params[8], *p = params;
663     const OSSL_PARAM *settables;
664     char *name, *cipher;
665     int use_df = 1;
666 
667     if (dgbl == NULL)
668         return NULL;
669     name = dgbl->rng_name != NULL ? dgbl->rng_name : "CTR-DRBG";
670     rand = EVP_RAND_fetch(libctx, name, dgbl->rng_propq);
671     if (rand == NULL) {
672         ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_FETCH_DRBG);
673         return NULL;
674     }
675     ctx = EVP_RAND_CTX_new(rand, parent);
676     EVP_RAND_free(rand);
677     if (ctx == NULL) {
678         ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_CREATE_DRBG);
679         return NULL;
680     }
681 
682     settables = EVP_RAND_CTX_settable_params(ctx);
683     if (OSSL_PARAM_locate_const(settables, OSSL_DRBG_PARAM_CIPHER)) {
684         cipher = dgbl->rng_cipher != NULL ? dgbl->rng_cipher : "AES-256-CTR";
685         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_CIPHER,
686                                                 cipher, 0);
687     }
688     if (dgbl->rng_digest != NULL
689             && OSSL_PARAM_locate_const(settables, OSSL_DRBG_PARAM_DIGEST))
690         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_DIGEST,
691                                                 dgbl->rng_digest, 0);
692     if (dgbl->rng_propq != NULL)
693         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_PROPERTIES,
694                                                 dgbl->rng_propq, 0);
695     if (OSSL_PARAM_locate_const(settables, OSSL_ALG_PARAM_MAC))
696         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_MAC, "HMAC", 0);
697     if (OSSL_PARAM_locate_const(settables, OSSL_DRBG_PARAM_USE_DF))
698         *p++ = OSSL_PARAM_construct_int(OSSL_DRBG_PARAM_USE_DF, &use_df);
699     *p++ = OSSL_PARAM_construct_uint(OSSL_DRBG_PARAM_RESEED_REQUESTS,
700                                      &reseed_interval);
701     *p++ = OSSL_PARAM_construct_time_t(OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL,
702                                        &reseed_time_interval);
703     *p = OSSL_PARAM_construct_end();
704     if (!EVP_RAND_instantiate(ctx, 0, 0, NULL, 0, params)) {
705         ERR_raise(ERR_LIB_RAND, RAND_R_ERROR_INSTANTIATING_DRBG);
706         EVP_RAND_CTX_free(ctx);
707         return NULL;
708     }
709     return ctx;
710 }
711 
712 #if defined(FIPS_MODULE)
rand_new_crngt(OSSL_LIB_CTX * libctx,EVP_RAND_CTX * parent)713 static EVP_RAND_CTX *rand_new_crngt(OSSL_LIB_CTX *libctx, EVP_RAND_CTX *parent)
714 {
715     EVP_RAND *rand;
716     EVP_RAND_CTX *ctx;
717 
718     rand = EVP_RAND_fetch(libctx, "CRNG-TEST", "-fips");
719     if (rand == NULL) {
720         ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_FETCH_DRBG);
721         return NULL;
722     }
723     ctx = EVP_RAND_CTX_new(rand, parent);
724     EVP_RAND_free(rand);
725     if (ctx == NULL) {
726         ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_CREATE_DRBG);
727         return NULL;
728     }
729 
730     if (!EVP_RAND_instantiate(ctx, 0, 0, NULL, 0, NULL)) {
731         ERR_raise(ERR_LIB_RAND, RAND_R_ERROR_INSTANTIATING_DRBG);
732         EVP_RAND_CTX_free(ctx);
733         return NULL;
734     }
735     return ctx;
736 }
737 #endif  /* FIPS_MODULE */
738 
739 /*
740  * Get the primary random generator.
741  * Returns pointer to its EVP_RAND_CTX on success, NULL on failure.
742  *
743  */
RAND_get0_primary(OSSL_LIB_CTX * ctx)744 EVP_RAND_CTX *RAND_get0_primary(OSSL_LIB_CTX *ctx)
745 {
746     RAND_GLOBAL *dgbl = rand_get_global(ctx);
747     EVP_RAND_CTX *ret;
748 
749     if (dgbl == NULL)
750         return NULL;
751 
752     if (!CRYPTO_THREAD_read_lock(dgbl->lock))
753         return NULL;
754 
755     ret = dgbl->primary;
756     CRYPTO_THREAD_unlock(dgbl->lock);
757 
758     if (ret != NULL)
759         return ret;
760 
761     if (!CRYPTO_THREAD_write_lock(dgbl->lock))
762         return NULL;
763 
764     ret = dgbl->primary;
765     if (ret != NULL) {
766         CRYPTO_THREAD_unlock(dgbl->lock);
767         return ret;
768     }
769 
770 #if !defined(FIPS_MODULE) || !defined(OPENSSL_NO_FIPS_JITTER)
771     /* Create a seed source for libcrypto or jitter enabled FIPS provider */
772     if (dgbl->seed == NULL) {
773         ERR_set_mark();
774         dgbl->seed = rand_new_seed(ctx);
775         ERR_pop_to_mark();
776     }
777 #endif  /* !FIPS_MODULE || !OPENSSL_NO_FIPS_JITTER */
778 
779 #if defined(FIPS_MODULE)
780     /* The FIPS provider has entropy health tests instead of the primary */
781     ret = rand_new_crngt(ctx, dgbl->seed);
782 #else   /* FIPS_MODULE */
783     ret = rand_new_drbg(ctx, dgbl->seed, PRIMARY_RESEED_INTERVAL,
784                         PRIMARY_RESEED_TIME_INTERVAL);
785 #endif  /* FIPS_MODULE */
786 
787     /*
788      * The primary DRBG may be shared between multiple threads so we must
789      * enable locking.
790      */
791     dgbl->primary = ret;
792     if (ret != NULL && !EVP_RAND_enable_locking(ret)) {
793         ERR_raise(ERR_LIB_EVP, EVP_R_UNABLE_TO_ENABLE_LOCKING);
794         EVP_RAND_CTX_free(ret);
795         ret = dgbl->primary = NULL;
796     }
797     CRYPTO_THREAD_unlock(dgbl->lock);
798 
799     return ret;
800 }
801 
802 /*
803  * Get the public random generator.
804  * Returns pointer to its EVP_RAND_CTX on success, NULL on failure.
805  */
RAND_get0_public(OSSL_LIB_CTX * ctx)806 EVP_RAND_CTX *RAND_get0_public(OSSL_LIB_CTX *ctx)
807 {
808     RAND_GLOBAL *dgbl = rand_get_global(ctx);
809     EVP_RAND_CTX *rand, *primary;
810 
811     if (dgbl == NULL)
812         return NULL;
813 
814     rand = CRYPTO_THREAD_get_local(&dgbl->public);
815     if (rand == NULL) {
816         primary = RAND_get0_primary(ctx);
817         if (primary == NULL)
818             return NULL;
819 
820         ctx = ossl_lib_ctx_get_concrete(ctx);
821         /*
822          * If the private is also NULL then this is the first time we've
823          * used this thread.
824          */
825         if (CRYPTO_THREAD_get_local(&dgbl->private) == NULL
826                 && !ossl_init_thread_start(NULL, ctx, rand_delete_thread_state))
827             return NULL;
828         rand = rand_new_drbg(ctx, primary, SECONDARY_RESEED_INTERVAL,
829                              SECONDARY_RESEED_TIME_INTERVAL);
830         CRYPTO_THREAD_set_local(&dgbl->public, rand);
831     }
832     return rand;
833 }
834 
835 /*
836  * Get the private random generator.
837  * Returns pointer to its EVP_RAND_CTX on success, NULL on failure.
838  */
RAND_get0_private(OSSL_LIB_CTX * ctx)839 EVP_RAND_CTX *RAND_get0_private(OSSL_LIB_CTX *ctx)
840 {
841     RAND_GLOBAL *dgbl = rand_get_global(ctx);
842     EVP_RAND_CTX *rand, *primary;
843 
844     if (dgbl == NULL)
845         return NULL;
846 
847     rand = CRYPTO_THREAD_get_local(&dgbl->private);
848     if (rand == NULL) {
849         primary = RAND_get0_primary(ctx);
850         if (primary == NULL)
851             return NULL;
852 
853         ctx = ossl_lib_ctx_get_concrete(ctx);
854         /*
855          * If the public is also NULL then this is the first time we've
856          * used this thread.
857          */
858         if (CRYPTO_THREAD_get_local(&dgbl->public) == NULL
859                 && !ossl_init_thread_start(NULL, ctx, rand_delete_thread_state))
860             return NULL;
861         rand = rand_new_drbg(ctx, primary, SECONDARY_RESEED_INTERVAL,
862                              SECONDARY_RESEED_TIME_INTERVAL);
863         CRYPTO_THREAD_set_local(&dgbl->private, rand);
864     }
865     return rand;
866 }
867 
868 #ifdef FIPS_MODULE
ossl_rand_get0_private_noncreating(OSSL_LIB_CTX * ctx)869 EVP_RAND_CTX *ossl_rand_get0_private_noncreating(OSSL_LIB_CTX *ctx)
870 {
871     RAND_GLOBAL *dgbl = rand_get_global(ctx);
872 
873     if (dgbl == NULL)
874         return NULL;
875 
876     return CRYPTO_THREAD_get_local(&dgbl->private);
877 }
878 #endif
879 
RAND_set0_public(OSSL_LIB_CTX * ctx,EVP_RAND_CTX * rand)880 int RAND_set0_public(OSSL_LIB_CTX *ctx, EVP_RAND_CTX *rand)
881 {
882     RAND_GLOBAL *dgbl = rand_get_global(ctx);
883     EVP_RAND_CTX *old;
884     int r;
885 
886     if (dgbl == NULL)
887         return 0;
888     old = CRYPTO_THREAD_get_local(&dgbl->public);
889     if ((r = CRYPTO_THREAD_set_local(&dgbl->public, rand)) > 0)
890         EVP_RAND_CTX_free(old);
891     return r;
892 }
893 
RAND_set0_private(OSSL_LIB_CTX * ctx,EVP_RAND_CTX * rand)894 int RAND_set0_private(OSSL_LIB_CTX *ctx, EVP_RAND_CTX *rand)
895 {
896     RAND_GLOBAL *dgbl = rand_get_global(ctx);
897     EVP_RAND_CTX *old;
898     int r;
899 
900     if (dgbl == NULL)
901         return 0;
902     old = CRYPTO_THREAD_get_local(&dgbl->private);
903     if ((r = CRYPTO_THREAD_set_local(&dgbl->private, rand)) > 0)
904         EVP_RAND_CTX_free(old);
905     return r;
906 }
907 
908 #ifndef FIPS_MODULE
random_set_string(char ** p,const char * s)909 static int random_set_string(char **p, const char *s)
910 {
911     char *d = NULL;
912 
913     if (s != NULL) {
914         d = OPENSSL_strdup(s);
915         if (d == NULL)
916             return 0;
917     }
918     OPENSSL_free(*p);
919     *p = d;
920     return 1;
921 }
922 
923 /*
924  * Load the DRBG definitions from a configuration file.
925  */
random_conf_init(CONF_IMODULE * md,const CONF * cnf)926 static int random_conf_init(CONF_IMODULE *md, const CONF *cnf)
927 {
928     STACK_OF(CONF_VALUE) *elist;
929     CONF_VALUE *cval;
930     RAND_GLOBAL *dgbl = rand_get_global(NCONF_get0_libctx((CONF *)cnf));
931     int i, r = 1;
932 
933     OSSL_TRACE1(CONF, "Loading random module: section %s\n",
934                 CONF_imodule_get_value(md));
935 
936     /* Value is a section containing RANDOM configuration */
937     elist = NCONF_get_section(cnf, CONF_imodule_get_value(md));
938     if (elist == NULL) {
939         ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_RANDOM_SECTION_ERROR);
940         return 0;
941     }
942 
943     if (dgbl == NULL)
944         return 0;
945 
946     for (i = 0; i < sk_CONF_VALUE_num(elist); i++) {
947         cval = sk_CONF_VALUE_value(elist, i);
948         if (OPENSSL_strcasecmp(cval->name, "random") == 0) {
949             if (!random_set_string(&dgbl->rng_name, cval->value))
950                 return 0;
951         } else if (OPENSSL_strcasecmp(cval->name, "cipher") == 0) {
952             if (!random_set_string(&dgbl->rng_cipher, cval->value))
953                 return 0;
954         } else if (OPENSSL_strcasecmp(cval->name, "digest") == 0) {
955             if (!random_set_string(&dgbl->rng_digest, cval->value))
956                 return 0;
957         } else if (OPENSSL_strcasecmp(cval->name, "properties") == 0) {
958             if (!random_set_string(&dgbl->rng_propq, cval->value))
959                 return 0;
960         } else if (OPENSSL_strcasecmp(cval->name, "seed") == 0) {
961             if (!random_set_string(&dgbl->seed_name, cval->value))
962                 return 0;
963         } else if (OPENSSL_strcasecmp(cval->name, "seed_properties") == 0) {
964             if (!random_set_string(&dgbl->seed_propq, cval->value))
965                 return 0;
966         } else {
967             ERR_raise_data(ERR_LIB_CRYPTO,
968                            CRYPTO_R_UNKNOWN_NAME_IN_RANDOM_SECTION,
969                            "name=%s, value=%s", cval->name, cval->value);
970             r = 0;
971         }
972     }
973     return r;
974 }
975 
976 
random_conf_deinit(CONF_IMODULE * md)977 static void random_conf_deinit(CONF_IMODULE *md)
978 {
979     OSSL_TRACE(CONF, "Cleaned up random\n");
980 }
981 
ossl_random_add_conf_module(void)982 void ossl_random_add_conf_module(void)
983 {
984     OSSL_TRACE(CONF, "Adding config module 'random'\n");
985     CONF_module_add("random", random_conf_init, random_conf_deinit);
986 }
987 
RAND_set_DRBG_type(OSSL_LIB_CTX * ctx,const char * drbg,const char * propq,const char * cipher,const char * digest)988 int RAND_set_DRBG_type(OSSL_LIB_CTX *ctx, const char *drbg, const char *propq,
989                        const char *cipher, const char *digest)
990 {
991     RAND_GLOBAL *dgbl = rand_get_global(ctx);
992 
993     if (dgbl == NULL)
994         return 0;
995     if (dgbl->primary != NULL) {
996         ERR_raise(ERR_LIB_CRYPTO, RAND_R_ALREADY_INSTANTIATED);
997         return 0;
998     }
999     return random_set_string(&dgbl->rng_name, drbg)
1000         && random_set_string(&dgbl->rng_propq, propq)
1001         && random_set_string(&dgbl->rng_cipher, cipher)
1002         && random_set_string(&dgbl->rng_digest, digest);
1003 }
1004 
RAND_set_seed_source_type(OSSL_LIB_CTX * ctx,const char * seed,const char * propq)1005 int RAND_set_seed_source_type(OSSL_LIB_CTX *ctx, const char *seed,
1006                               const char *propq)
1007 {
1008     RAND_GLOBAL *dgbl = rand_get_global(ctx);
1009 
1010     if (dgbl == NULL)
1011         return 0;
1012     if (dgbl->seed != NULL) {
1013         ERR_raise(ERR_LIB_CRYPTO, RAND_R_ALREADY_INSTANTIATED);
1014         return 0;
1015     }
1016     return random_set_string(&dgbl->seed_name, seed)
1017         && random_set_string(&dgbl->seed_propq, propq);
1018 }
1019 
1020 #endif
1021