]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/rand/rand_lib.c
Rename OPENSSL_CTX prefix to OSSL_LIB_CTX
[thirdparty/openssl.git] / crypto / rand / rand_lib.c
1 /*
2 * Copyright 1995-2020 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 <stdio.h>
14 #include <time.h>
15 #include <limits.h>
16 #include <openssl/trace.h>
17 #include <openssl/err.h>
18 #include <openssl/conf.h>
19 #include "internal/cryptlib.h"
20 #include <openssl/opensslconf.h>
21 #include "crypto/rand.h"
22 #include "crypto/cryptlib.h"
23 #include <openssl/engine.h>
24 #include <openssl/core_names.h>
25 #include "internal/thread_once.h"
26 #include "rand_local.h"
27 #include "e_os.h"
28
29 #ifndef FIPS_MODULE
30 # include "prov/rand_pool.h"
31 # include "prov/seeding.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 static CRYPTO_RWLOCK *rand_meth_lock;
39 static const RAND_METHOD *default_RAND_meth;
40 static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
41
42 static int rand_inited = 0;
43
44 DEFINE_RUN_ONCE_STATIC(do_rand_init)
45 {
46 # ifndef OPENSSL_NO_ENGINE
47 rand_engine_lock = CRYPTO_THREAD_lock_new();
48 if (rand_engine_lock == NULL)
49 return 0;
50 # endif
51
52 rand_meth_lock = CRYPTO_THREAD_lock_new();
53 if (rand_meth_lock == NULL)
54 goto err;
55
56 if (!rand_pool_init())
57 goto err;
58
59 rand_inited = 1;
60 return 1;
61
62 err:
63 CRYPTO_THREAD_lock_free(rand_meth_lock);
64 rand_meth_lock = NULL;
65 # ifndef OPENSSL_NO_ENGINE
66 CRYPTO_THREAD_lock_free(rand_engine_lock);
67 rand_engine_lock = NULL;
68 # endif
69 return 0;
70 }
71
72 void rand_cleanup_int(void)
73 {
74 const RAND_METHOD *meth = default_RAND_meth;
75
76 if (!rand_inited)
77 return;
78
79 if (meth != NULL && meth->cleanup != NULL)
80 meth->cleanup();
81 RAND_set_rand_method(NULL);
82 rand_pool_cleanup();
83 # ifndef OPENSSL_NO_ENGINE
84 CRYPTO_THREAD_lock_free(rand_engine_lock);
85 rand_engine_lock = NULL;
86 # endif
87 CRYPTO_THREAD_lock_free(rand_meth_lock);
88 rand_meth_lock = NULL;
89 rand_inited = 0;
90 }
91
92 /*
93 * RAND_close_seed_files() ensures that any seed file descriptors are
94 * closed after use. This only applies to libcrypto/default provider,
95 * it does not apply to other providers.
96 */
97 void RAND_keep_random_devices_open(int keep)
98 {
99 if (RUN_ONCE(&rand_init, do_rand_init))
100 rand_pool_keep_random_devices_open(keep);
101 }
102
103 /*
104 * RAND_poll() reseeds the default RNG using random input
105 *
106 * The random input is obtained from polling various entropy
107 * sources which depend on the operating system and are
108 * configurable via the --with-rand-seed configure option.
109 */
110 int RAND_poll(void)
111 {
112 const RAND_METHOD *meth = RAND_get_rand_method();
113 int ret = meth == RAND_OpenSSL();
114
115 if (meth == NULL)
116 return 0;
117
118 #ifndef OPENSSL_NO_DEPRECATED_3_0
119 if (!ret) {
120 /* fill random pool and seed the current legacy RNG */
121 RAND_POOL *pool = rand_pool_new(RAND_DRBG_STRENGTH, 1,
122 (RAND_DRBG_STRENGTH + 7) / 8,
123 RAND_POOL_MAX_LENGTH);
124
125 if (pool == NULL)
126 return 0;
127
128 if (prov_pool_acquire_entropy(pool) == 0)
129 goto err;
130
131 if (meth->add == NULL
132 || meth->add(rand_pool_buffer(pool),
133 rand_pool_length(pool),
134 (rand_pool_entropy(pool) / 8.0)) == 0)
135 goto err;
136
137 ret = 1;
138 err:
139 rand_pool_free(pool);
140 }
141 #endif
142 return ret;
143 }
144
145 int RAND_set_rand_method(const RAND_METHOD *meth)
146 {
147 if (!RUN_ONCE(&rand_init, do_rand_init))
148 return 0;
149
150 CRYPTO_THREAD_write_lock(rand_meth_lock);
151 # ifndef OPENSSL_NO_ENGINE
152 ENGINE_finish(funct_ref);
153 funct_ref = NULL;
154 # endif
155 default_RAND_meth = meth;
156 CRYPTO_THREAD_unlock(rand_meth_lock);
157 return 1;
158 }
159
160 const RAND_METHOD *RAND_get_rand_method(void)
161 {
162 const RAND_METHOD *tmp_meth = NULL;
163
164 if (!RUN_ONCE(&rand_init, do_rand_init))
165 return NULL;
166
167 CRYPTO_THREAD_write_lock(rand_meth_lock);
168 if (default_RAND_meth == NULL) {
169 # ifndef OPENSSL_NO_ENGINE
170 ENGINE *e;
171
172 /* If we have an engine that can do RAND, use it. */
173 if ((e = ENGINE_get_default_RAND()) != NULL
174 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
175 funct_ref = e;
176 default_RAND_meth = tmp_meth;
177 } else {
178 ENGINE_finish(e);
179 default_RAND_meth = &rand_meth;
180 }
181 # else
182 default_RAND_meth = &rand_meth;
183 # endif
184 }
185 tmp_meth = default_RAND_meth;
186 CRYPTO_THREAD_unlock(rand_meth_lock);
187 return tmp_meth;
188 }
189
190 # if !defined(OPENSSL_NO_ENGINE)
191 int RAND_set_rand_engine(ENGINE *engine)
192 {
193 const RAND_METHOD *tmp_meth = NULL;
194
195 if (!RUN_ONCE(&rand_init, do_rand_init))
196 return 0;
197
198 if (engine != NULL) {
199 if (!ENGINE_init(engine))
200 return 0;
201 tmp_meth = ENGINE_get_RAND(engine);
202 if (tmp_meth == NULL) {
203 ENGINE_finish(engine);
204 return 0;
205 }
206 }
207 CRYPTO_THREAD_write_lock(rand_engine_lock);
208 /* This function releases any prior ENGINE so call it first */
209 RAND_set_rand_method(tmp_meth);
210 funct_ref = engine;
211 CRYPTO_THREAD_unlock(rand_engine_lock);
212 return 1;
213 }
214 # endif
215
216 void RAND_seed(const void *buf, int num)
217 {
218 const RAND_METHOD *meth = RAND_get_rand_method();
219
220 if (meth != NULL && meth->seed != NULL)
221 meth->seed(buf, num);
222 }
223
224 void RAND_add(const void *buf, int num, double randomness)
225 {
226 const RAND_METHOD *meth = RAND_get_rand_method();
227
228 if (meth != NULL && meth->add != NULL)
229 meth->add(buf, num, randomness);
230 }
231
232 # if !defined(OPENSSL_NO_DEPRECATED_1_1_0)
233 int RAND_pseudo_bytes(unsigned char *buf, int num)
234 {
235 const RAND_METHOD *meth = RAND_get_rand_method();
236
237 if (meth != NULL && meth->pseudorand != NULL)
238 return meth->pseudorand(buf, num);
239 RANDerr(RAND_F_RAND_PSEUDO_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
240 return -1;
241 }
242 # endif
243
244 int RAND_status(void)
245 {
246 EVP_RAND_CTX *rand;
247 const RAND_METHOD *meth = RAND_get_rand_method();
248
249 if (meth != NULL && meth != RAND_OpenSSL())
250 return meth->status != NULL ? meth->status() : 0;
251
252 if ((rand = RAND_get0_primary(NULL)) == NULL)
253 return 0;
254 return EVP_RAND_state(rand) == EVP_RAND_STATE_READY;
255 }
256 #else /* !FIPS_MODULE */
257
258 const RAND_METHOD *RAND_get_rand_method(void)
259 {
260 return NULL;
261 }
262 #endif /* !FIPS_MODULE */
263
264 /*
265 * This function is not part of RAND_METHOD, so if we're not using
266 * the default method, then just call RAND_bytes(). Otherwise make
267 * sure we're instantiated and use the private DRBG.
268 */
269 int RAND_priv_bytes_ex(OSSL_LIB_CTX *ctx, unsigned char *buf, int num)
270 {
271 EVP_RAND_CTX *rand;
272 const RAND_METHOD *meth = RAND_get_rand_method();
273
274 if (meth != NULL && meth != RAND_OpenSSL()) {
275 if (meth->bytes != NULL)
276 return meth->bytes(buf, num);
277 RANDerr(RAND_F_RAND_PRIV_BYTES_EX, RAND_R_FUNC_NOT_IMPLEMENTED);
278 return -1;
279 }
280
281 rand = RAND_get0_private(ctx);
282 if (rand != NULL)
283 return EVP_RAND_generate(rand, buf, num, 0, 0, NULL, 0);
284
285 return 0;
286 }
287
288 int RAND_priv_bytes(unsigned char *buf, int num)
289 {
290 return RAND_priv_bytes_ex(NULL, buf, num);
291 }
292
293 int RAND_bytes_ex(OSSL_LIB_CTX *ctx, unsigned char *buf, int num)
294 {
295 EVP_RAND_CTX *rand;
296 const RAND_METHOD *meth = RAND_get_rand_method();
297
298 if (meth != NULL && meth != RAND_OpenSSL()) {
299 if (meth->bytes != NULL)
300 return meth->bytes(buf, num);
301 RANDerr(RAND_F_RAND_BYTES_EX, RAND_R_FUNC_NOT_IMPLEMENTED);
302 return -1;
303 }
304
305 rand = RAND_get0_public(ctx);
306 if (rand != NULL)
307 return EVP_RAND_generate(rand, buf, num, 0, 0, NULL, 0);
308
309 return 0;
310 }
311
312 int RAND_bytes(unsigned char *buf, int num)
313 {
314 return RAND_bytes_ex(NULL, buf, num);
315 }
316
317 typedef struct rand_global_st {
318 /*
319 * The three shared DRBG instances
320 *
321 * There are three shared DRBG instances: <primary>, <public>, and
322 * <private>. The <public> and <private> DRBGs are secondary ones.
323 * These are used for non-secret (e.g. nonces) and secret
324 * (e.g. private keys) data respectively.
325 */
326 CRYPTO_RWLOCK *lock;
327
328 /*
329 * The <primary> DRBG
330 *
331 * Not used directly by the application, only for reseeding the two other
332 * DRBGs. It reseeds itself by pulling either randomness from os entropy
333 * sources or by consuming randomness which was added by RAND_add().
334 *
335 * The <primary> DRBG is a global instance which is accessed concurrently by
336 * all threads. The necessary locking is managed automatically by its child
337 * DRBG instances during reseeding.
338 */
339 EVP_RAND_CTX *primary;
340
341 /*
342 * The <public> DRBG
343 *
344 * Used by default for generating random bytes using RAND_bytes().
345 *
346 * The <public> secondary DRBG is thread-local, i.e., there is one instance
347 * per thread.
348 */
349 CRYPTO_THREAD_LOCAL public;
350
351 /*
352 * The <private> DRBG
353 *
354 * Used by default for generating private keys using RAND_priv_bytes()
355 *
356 * The <private> secondary DRBG is thread-local, i.e., there is one
357 * instance per thread.
358 */
359 CRYPTO_THREAD_LOCAL private;
360
361 /* Which RNG is being used by default and it's configuration settings */
362 char *rng_name;
363 char *rng_cipher;
364 char *rng_digest;
365 char *rng_propq;
366 } RAND_GLOBAL;
367
368 /*
369 * Initialize the OSSL_LIB_CTX global DRBGs on first use.
370 * Returns the allocated global data on success or NULL on failure.
371 */
372 static void *rand_ossl_ctx_new(OSSL_LIB_CTX *libctx)
373 {
374 RAND_GLOBAL *dgbl = OPENSSL_zalloc(sizeof(*dgbl));
375
376 if (dgbl == NULL)
377 return NULL;
378
379 #ifndef FIPS_MODULE
380 /*
381 * We need to ensure that base libcrypto thread handling has been
382 * initialised.
383 */
384 OPENSSL_init_crypto(0, NULL);
385 #endif
386
387 dgbl->lock = CRYPTO_THREAD_lock_new();
388 if (dgbl->lock == NULL)
389 goto err1;
390
391 if (!CRYPTO_THREAD_init_local(&dgbl->private, NULL))
392 goto err1;
393
394 if (!CRYPTO_THREAD_init_local(&dgbl->public, NULL))
395 goto err2;
396
397 return dgbl;
398
399 err2:
400 CRYPTO_THREAD_cleanup_local(&dgbl->private);
401 err1:
402 CRYPTO_THREAD_lock_free(dgbl->lock);
403 OPENSSL_free(dgbl);
404 return NULL;
405 }
406
407 static void rand_ossl_ctx_free(void *vdgbl)
408 {
409 RAND_GLOBAL *dgbl = vdgbl;
410
411 if (dgbl == NULL)
412 return;
413
414 CRYPTO_THREAD_lock_free(dgbl->lock);
415 EVP_RAND_CTX_free(dgbl->primary);
416 CRYPTO_THREAD_cleanup_local(&dgbl->private);
417 CRYPTO_THREAD_cleanup_local(&dgbl->public);
418 OPENSSL_free(dgbl->rng_name);
419 OPENSSL_free(dgbl->rng_cipher);
420 OPENSSL_free(dgbl->rng_digest);
421 OPENSSL_free(dgbl->rng_propq);
422
423 OPENSSL_free(dgbl);
424 }
425
426 static const OSSL_LIB_CTX_METHOD rand_drbg_ossl_ctx_method = {
427 rand_ossl_ctx_new,
428 rand_ossl_ctx_free,
429 };
430
431 static RAND_GLOBAL *rand_get_global(OSSL_LIB_CTX *libctx)
432 {
433 return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DRBG_INDEX,
434 &rand_drbg_ossl_ctx_method);
435 }
436
437 static void rand_delete_thread_state(void *arg)
438 {
439 OSSL_LIB_CTX *ctx = arg;
440 RAND_GLOBAL *dgbl = rand_get_global(ctx);
441 EVP_RAND_CTX *rand;
442
443 if (dgbl == NULL)
444 return;
445
446 rand = CRYPTO_THREAD_get_local(&dgbl->public);
447 CRYPTO_THREAD_set_local(&dgbl->public, NULL);
448 EVP_RAND_CTX_free(rand);
449
450 rand = CRYPTO_THREAD_get_local(&dgbl->private);
451 CRYPTO_THREAD_set_local(&dgbl->private, NULL);
452 EVP_RAND_CTX_free(rand);
453 }
454
455 static EVP_RAND_CTX *rand_new_drbg(OSSL_LIB_CTX *libctx, EVP_RAND_CTX *parent,
456 unsigned int reseed_interval,
457 time_t reseed_time_interval)
458 {
459 EVP_RAND *rand;
460 RAND_GLOBAL *dgbl = rand_get_global(libctx);
461 EVP_RAND_CTX *ctx;
462 OSSL_PARAM params[7], *p = params;
463 char *name, *cipher;
464
465 name = dgbl->rng_name != NULL ? dgbl->rng_name : "CTR-DRBG";
466 rand = EVP_RAND_fetch(libctx, name, dgbl->rng_propq);
467 if (rand == NULL) {
468 RANDerr(0, RAND_R_UNABLE_TO_FETCH_DRBG);
469 return NULL;
470 }
471 ctx = EVP_RAND_CTX_new(rand, parent);
472 EVP_RAND_free(rand);
473 if (ctx == NULL) {
474 RANDerr(0, RAND_R_UNABLE_TO_CREATE_DRBG);
475 return NULL;
476 }
477
478 /*
479 * Rather than trying to decode the DRBG settings, just pass them through
480 * and rely on the other end to ignore those it doesn't care about.
481 */
482 cipher = dgbl->rng_cipher != NULL ? dgbl->rng_cipher : "AES-256-CTR";
483 *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_CIPHER,
484 cipher, 0);
485 if (dgbl->rng_digest != NULL)
486 *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_DIGEST,
487 dgbl->rng_digest, 0);
488 if (dgbl->rng_propq != NULL)
489 *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_PROPERTIES,
490 dgbl->rng_propq, 0);
491 *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_MAC, "HMAC", 0);
492 *p++ = OSSL_PARAM_construct_uint(OSSL_DRBG_PARAM_RESEED_REQUESTS,
493 &reseed_interval);
494 *p++ = OSSL_PARAM_construct_time_t(OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL,
495 &reseed_time_interval);
496 *p = OSSL_PARAM_construct_end();
497 if (!EVP_RAND_set_ctx_params(ctx, params)) {
498 RANDerr(0, RAND_R_ERROR_INITIALISING_DRBG);
499 EVP_RAND_CTX_free(ctx);
500 return NULL;
501 }
502 if (!EVP_RAND_instantiate(ctx, 0, 0, NULL, 0)) {
503 RANDerr(0, RAND_R_ERROR_INSTANTIATING_DRBG);
504 EVP_RAND_CTX_free(ctx);
505 return NULL;
506 }
507 return ctx;
508 }
509
510 /*
511 * Get the primary random generator.
512 * Returns pointer to its EVP_RAND_CTX on success, NULL on failure.
513 *
514 */
515 EVP_RAND_CTX *RAND_get0_primary(OSSL_LIB_CTX *ctx)
516 {
517 RAND_GLOBAL *dgbl = rand_get_global(ctx);
518
519 if (dgbl == NULL)
520 return NULL;
521
522 if (dgbl->primary == NULL) {
523 if (!CRYPTO_THREAD_write_lock(dgbl->lock))
524 return NULL;
525 if (dgbl->primary == NULL)
526 dgbl->primary = rand_new_drbg(ctx, NULL, PRIMARY_RESEED_INTERVAL,
527 PRIMARY_RESEED_TIME_INTERVAL);
528 CRYPTO_THREAD_unlock(dgbl->lock);
529 }
530 return dgbl->primary;
531 }
532
533 /*
534 * Get the public random generator.
535 * Returns pointer to its EVP_RAND_CTX on success, NULL on failure.
536 */
537 EVP_RAND_CTX *RAND_get0_public(OSSL_LIB_CTX *ctx)
538 {
539 RAND_GLOBAL *dgbl = rand_get_global(ctx);
540 EVP_RAND_CTX *rand, *primary;
541
542 if (dgbl == NULL)
543 return NULL;
544
545 rand = CRYPTO_THREAD_get_local(&dgbl->public);
546 if (rand == NULL) {
547 primary = RAND_get0_primary(ctx);
548 if (primary == NULL)
549 return NULL;
550
551 ctx = ossl_lib_ctx_get_concrete(ctx);
552 /*
553 * If the private is also NULL then this is the first time we've
554 * used this thread.
555 */
556 if (CRYPTO_THREAD_get_local(&dgbl->private) == NULL
557 && !ossl_init_thread_start(NULL, ctx, rand_delete_thread_state))
558 return NULL;
559 rand = rand_new_drbg(ctx, primary, SECONDARY_RESEED_INTERVAL,
560 SECONDARY_RESEED_TIME_INTERVAL);
561 CRYPTO_THREAD_set_local(&dgbl->public, rand);
562 }
563 return rand;
564 }
565
566 /*
567 * Get the private random generator.
568 * Returns pointer to its EVP_RAND_CTX on success, NULL on failure.
569 */
570 EVP_RAND_CTX *RAND_get0_private(OSSL_LIB_CTX *ctx)
571 {
572 RAND_GLOBAL *dgbl = rand_get_global(ctx);
573 EVP_RAND_CTX *rand, *primary;
574
575 if (dgbl == NULL)
576 return NULL;
577
578 rand = CRYPTO_THREAD_get_local(&dgbl->private);
579 if (rand == NULL) {
580 primary = RAND_get0_primary(ctx);
581 if (primary == NULL)
582 return NULL;
583
584 ctx = ossl_lib_ctx_get_concrete(ctx);
585 /*
586 * If the public is also NULL then this is the first time we've
587 * used this thread.
588 */
589 if (CRYPTO_THREAD_get_local(&dgbl->public) == NULL
590 && !ossl_init_thread_start(NULL, ctx, rand_delete_thread_state))
591 return NULL;
592 rand = rand_new_drbg(ctx, primary, SECONDARY_RESEED_INTERVAL,
593 SECONDARY_RESEED_TIME_INTERVAL);
594 CRYPTO_THREAD_set_local(&dgbl->private, rand);
595 }
596 return rand;
597 }
598
599 #ifndef FIPS_MODULE
600 static int random_set_string(char **p, const char *s)
601 {
602 char *d = OPENSSL_strdup(s);
603
604 if (d == NULL) {
605 CRYPTOerr(0, ERR_R_MALLOC_FAILURE);
606 return 0;
607 }
608 OPENSSL_free(*p);
609 *p = d;
610 return 1;
611 }
612
613 /*
614 * Load the DRBG definitions from a configuration file.
615 */
616 static int random_conf_init(CONF_IMODULE *md, const CONF *cnf)
617 {
618 STACK_OF(CONF_VALUE) *elist;
619 CONF_VALUE *cval;
620 RAND_GLOBAL *dgbl = rand_get_global(cnf->libctx);
621 int i, r = 1;
622
623 OSSL_TRACE1(CONF, "Loading random module: section %s\n",
624 CONF_imodule_get_value(md));
625
626 /* Value is a section containing RANDOM configuration */
627 elist = NCONF_get_section(cnf, CONF_imodule_get_value(md));
628 if (elist == NULL) {
629 CRYPTOerr(0, CRYPTO_R_RANDOM_SECTION_ERROR);
630 return 0;
631 }
632
633 for (i = 0; i < sk_CONF_VALUE_num(elist); i++) {
634 cval = sk_CONF_VALUE_value(elist, i);
635 if (strcasecmp(cval->name, "random") == 0) {
636 if (!random_set_string(&dgbl->rng_name, cval->value))
637 return 0;
638 } else if (strcasecmp(cval->name, "cipher") == 0) {
639 if (!random_set_string(&dgbl->rng_cipher, cval->value))
640 return 0;
641 } else if (strcasecmp(cval->name, "digest") == 0) {
642 if (!random_set_string(&dgbl->rng_digest, cval->value))
643 return 0;
644 } else if (strcasecmp(cval->name, "properties") == 0) {
645 if (!random_set_string(&dgbl->rng_propq, cval->value))
646 return 0;
647 } else {
648 CRYPTOerr(0, CRYPTO_R_UNKNOWN_NAME_IN_RANDOM_SECTION);
649 ERR_add_error_data(4, "name=", cval->name, ", value=", cval->value);
650 r = 0;
651 }
652 }
653 return r;
654 }
655
656
657 static void random_conf_deinit(CONF_IMODULE *md)
658 {
659 OSSL_TRACE(CONF, "Cleaned up random\n");
660 }
661
662 void ossl_random_add_conf_module(void)
663 {
664 OSSL_TRACE(CONF, "Adding config module 'random'\n");
665 CONF_module_add("random", random_conf_init, random_conf_deinit);
666 }
667 #endif