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