7a184a7d67e8f207b35243ea1de3bf86d95b74ad
[openssl.git] / crypto / provider_core.c
1 /*
2  * Copyright 2019 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 #include <openssl/core.h>
11 #include <openssl/core_numbers.h>
12 #include <openssl/opensslv.h>
13 #include "internal/cryptlib.h"
14 #include "internal/nelem.h"
15 #include "internal/thread_once.h"
16 #include "internal/provider.h"
17 #include "internal/refcount.h"
18 #include "provider_local.h"
19
20 static OSSL_PROVIDER *provider_new(const char *name,
21                                    OSSL_provider_init_fn *init_function);
22
23 /*-
24  * Provider Object structure
25  * =========================
26  */
27
28 struct provider_store_st;        /* Forward declaration */
29
30 struct ossl_provider_st {
31     /* Flag bits */
32     unsigned int flag_initialized:1;
33     unsigned int flag_fallback:1;
34
35     /* OpenSSL library side data */
36     CRYPTO_REF_COUNT refcnt;
37     CRYPTO_RWLOCK *refcnt_lock;  /* For the ref counter */
38     char *name;
39     DSO *module;
40     OSSL_provider_init_fn *init_function;
41     struct provider_store_st *store; /* The store this instance belongs to */
42
43     /* Provider side functions */
44     OSSL_provider_teardown_fn *teardown;
45     OSSL_provider_get_param_types_fn *get_param_types;
46     OSSL_provider_get_params_fn *get_params;
47     OSSL_provider_query_operation_fn *query_operation;
48 };
49 DEFINE_STACK_OF(OSSL_PROVIDER)
50
51 static int ossl_provider_cmp(const OSSL_PROVIDER * const *a,
52                              const OSSL_PROVIDER * const *b)
53 {
54     return strcmp((*a)->name, (*b)->name);
55 }
56
57 /*-
58  * Provider Object store
59  * =====================
60  *
61  * The Provider Object store is a library context object, and therefore needs
62  * an index.
63  */
64
65 struct provider_store_st {
66     STACK_OF(OSSL_PROVIDER) *providers;
67     CRYPTO_RWLOCK *lock;
68     unsigned int use_fallbacks:1;
69 };
70 static int provider_store_index = -1;
71
72 static void provider_store_free(void *vstore)
73 {
74     struct provider_store_st *store = vstore;
75
76     if (store == NULL)
77         return;
78     sk_OSSL_PROVIDER_pop_free(store->providers, ossl_provider_free);
79     CRYPTO_THREAD_lock_free(store->lock);
80     OPENSSL_free(store);
81 }
82
83 static void *provider_store_new(void)
84 {
85     struct provider_store_st *store = OPENSSL_zalloc(sizeof(*store));
86     const struct predefined_providers_st *p = NULL;
87
88     if (store == NULL
89         || (store->providers = sk_OSSL_PROVIDER_new(ossl_provider_cmp)) == NULL
90         || (store->lock = CRYPTO_THREAD_lock_new()) == NULL) {
91         provider_store_free(store);
92         return NULL;
93     }
94     store->use_fallbacks = 1;
95
96     for (p = predefined_providers; p->name != NULL; p++) {
97         OSSL_PROVIDER *prov = NULL;
98
99         /*
100          * We use the internal constructor directly here,
101          * otherwise we get a call loop
102          */
103         prov = provider_new(p->name, p->init);
104
105         if (prov == NULL
106             || sk_OSSL_PROVIDER_push(store->providers, prov) == 0) {
107             ossl_provider_free(prov);
108             provider_store_free(store);
109             CRYPTOerr(CRYPTO_F_PROVIDER_STORE_NEW, ERR_R_INTERNAL_ERROR);
110             return NULL;
111         }
112         prov->store = store;
113         if(p->is_fallback)
114             ossl_provider_set_fallback(prov);
115     }
116
117     return store;
118 }
119
120 static const OPENSSL_CTX_METHOD provider_store_method = {
121     provider_store_new,
122     provider_store_free,
123 };
124
125 static CRYPTO_ONCE provider_store_init_flag = CRYPTO_ONCE_STATIC_INIT;
126 DEFINE_RUN_ONCE_STATIC(do_provider_store_init)
127 {
128     return OPENSSL_init_crypto(0, NULL)
129         && (provider_store_index =
130             openssl_ctx_new_index(&provider_store_method)) != -1;
131 }
132
133
134 static struct provider_store_st *get_provider_store(OPENSSL_CTX *libctx)
135 {
136     struct provider_store_st *store = NULL;
137
138     if (!RUN_ONCE(&provider_store_init_flag, do_provider_store_init))
139         return NULL;
140
141     store = openssl_ctx_get_data(libctx, provider_store_index);
142     if (store == NULL)
143         CRYPTOerr(CRYPTO_F_GET_PROVIDER_STORE, ERR_R_INTERNAL_ERROR);
144     return store;
145 }
146
147 OSSL_PROVIDER *ossl_provider_find(OPENSSL_CTX *libctx, const char *name)
148 {
149     struct provider_store_st *store = NULL;
150     OSSL_PROVIDER *prov = NULL;
151
152     if ((store = get_provider_store(libctx)) != NULL) {
153         OSSL_PROVIDER tmpl = { 0, };
154         int i;
155
156         tmpl.name = (char *)name;
157         CRYPTO_THREAD_write_lock(store->lock);
158         if ((i = sk_OSSL_PROVIDER_find(store->providers, &tmpl)) == -1
159             || (prov = sk_OSSL_PROVIDER_value(store->providers, i)) == NULL
160             || !ossl_provider_upref(prov))
161             prov = NULL;
162         CRYPTO_THREAD_unlock(store->lock);
163     }
164
165     return prov;
166 }
167
168 /*-
169  * Provider Object methods
170  * =======================
171  */
172
173 static OSSL_PROVIDER *provider_new(const char *name,
174                                    OSSL_provider_init_fn *init_function)
175 {
176     OSSL_PROVIDER *prov = NULL;
177
178     if ((prov = OPENSSL_zalloc(sizeof(*prov))) == NULL
179 #ifndef HAVE_ATOMICS
180         || (prov->refcnt_lock = CRYPTO_THREAD_lock_new()) == NULL
181 #endif
182         || !ossl_provider_upref(prov) /* +1 One reference to be returned */
183         || (prov->name = OPENSSL_strdup(name)) == NULL) {
184         ossl_provider_free(prov);
185         CRYPTOerr(CRYPTO_F_PROVIDER_NEW, ERR_R_MALLOC_FAILURE);
186         return NULL;
187     }
188
189     prov->init_function = init_function;
190     return prov;
191 }
192
193 int ossl_provider_upref(OSSL_PROVIDER *prov)
194 {
195     int ref = 0;
196
197     CRYPTO_UP_REF(&prov->refcnt, &ref, prov->refcnt_lock);
198     return ref;
199 }
200
201 OSSL_PROVIDER *ossl_provider_new(OPENSSL_CTX *libctx, const char *name,
202                                  OSSL_provider_init_fn *init_function)
203 {
204     struct provider_store_st *store = NULL;
205     OSSL_PROVIDER *prov = NULL;
206
207     if ((store = get_provider_store(libctx)) == NULL)
208         return NULL;
209
210     if ((prov = ossl_provider_find(libctx, name)) != NULL) { /* refcount +1 */
211         ossl_provider_free(prov); /* refcount -1 */
212         CRYPTOerr(CRYPTO_F_OSSL_PROVIDER_NEW,
213                   CRYPTO_R_PROVIDER_ALREADY_EXISTS);
214         ERR_add_error_data(2, "name=", name);
215         return NULL;
216     }
217
218     /* provider_new() generates an error, so no need here */
219     if ((prov = provider_new(name, init_function)) == NULL)
220         return NULL;
221
222     CRYPTO_THREAD_write_lock(store->lock);
223     if (!ossl_provider_upref(prov)) { /* +1 One reference for the store */
224         ossl_provider_free(prov); /* -1 Reference that was to be returned */
225         prov = NULL;
226     } else if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0) {
227         ossl_provider_free(prov); /* -1 Store reference */
228         ossl_provider_free(prov); /* -1 Reference that was to be returned */
229         prov = NULL;
230     } else {
231         prov->store = store;
232     }
233     CRYPTO_THREAD_unlock(store->lock);
234
235     if (prov == NULL)
236         CRYPTOerr(CRYPTO_F_OSSL_PROVIDER_NEW, ERR_R_MALLOC_FAILURE);
237
238     /*
239      * At this point, the provider is only partially "loaded".  To be
240      * fully "loaded", ossl_provider_activate() must also be called.
241      */
242
243     return prov;
244 }
245
246 void ossl_provider_free(OSSL_PROVIDER *prov)
247 {
248     if (prov != NULL) {
249         int ref = 0;
250
251         CRYPTO_DOWN_REF(&prov->refcnt, &ref, prov->refcnt_lock);
252
253         /*
254          * When the refcount drops below two, the store is the only
255          * possible reference, or it has already been taken away from
256          * the store (this may happen if a provider was activated
257          * because it's a fallback, but isn't currently used)
258          * When that happens, the provider is inactivated.
259          */
260         if (ref < 2 && prov->flag_initialized) {
261             if (prov->teardown != NULL)
262                 prov->teardown();
263             prov->flag_initialized = 0;
264         }
265
266         /*
267          * When the refcount drops to zero, it has been taken out of
268          * the store.  All we have to do here is clean it out.
269          */
270         if (ref == 0) {
271             DSO_free(prov->module);
272             OPENSSL_free(prov->name);
273 #ifndef HAVE_ATOMICS
274             CRYPTO_THREAD_lock_free(prov->refcnt_lock);
275 #endif
276             OPENSSL_free(prov);
277         }
278     }
279 }
280
281 /*
282  * Provider activation.
283  *
284  * What "activation" means depends on the provider form; for built in
285  * providers (in the library or the application alike), the provider
286  * can already be considered to be loaded, all that's needed is to
287  * initialize it.  However, for dynamically loadable provider modules,
288  * we must first load that module.
289  *
290  * Built in modules are distinguished from dynamically loaded modules
291  * with an already assigned init function.
292  */
293 static const OSSL_DISPATCH *core_dispatch; /* Define further down */
294
295 /*
296  * Internal version that doesn't affect the store flags, and thereby avoid
297  * locking.  Direct callers must remember to set the store flags when
298  * appropriate
299  */
300 static int provider_activate(OSSL_PROVIDER *prov)
301 {
302     const OSSL_DISPATCH *provider_dispatch = NULL;
303
304     if (prov->flag_initialized)
305         return 1;
306
307     /*
308      * If the init function isn't set, it indicates that this provider is
309      * a loadable module.
310      */
311     if (prov->init_function == NULL) {
312         if (prov->module == NULL) {
313             char *platform_module_name = NULL;
314             char *module_path = NULL;
315             const char *load_dir = ossl_safe_getenv("OPENSSL_MODULES");
316
317             if ((prov->module = DSO_new()) == NULL) {
318                 /* DSO_new() generates an error already */
319                 return 0;
320             }
321
322             if (load_dir == NULL)
323                 load_dir = MODULESDIR;
324
325             DSO_ctrl(prov->module, DSO_CTRL_SET_FLAGS,
326                      DSO_FLAG_NAME_TRANSLATION_EXT_ONLY, NULL);
327             if ((platform_module_name =
328                  DSO_convert_filename(prov->module, prov->name)) == NULL
329                 || (module_path =
330                     DSO_merge(prov->module, platform_module_name,
331                               load_dir)) == NULL
332                 || DSO_load(prov->module, module_path, NULL,
333                             DSO_FLAG_NAME_TRANSLATION_EXT_ONLY) == NULL) {
334                 DSO_free(prov->module);
335                 prov->module = NULL;
336             }
337
338             OPENSSL_free(platform_module_name);
339             OPENSSL_free(module_path);
340         }
341
342         if (prov->module != NULL)
343             prov->init_function = (OSSL_provider_init_fn *)
344                 DSO_bind_func(prov->module, "OSSL_provider_init");
345     }
346
347     if (prov->init_function == NULL
348         || !prov->init_function(prov, core_dispatch, &provider_dispatch)) {
349         CRYPTOerr(CRYPTO_F_PROVIDER_ACTIVATE, ERR_R_INIT_FAIL);
350         ERR_add_error_data(2, "name=", prov->name);
351         DSO_free(prov->module);
352         prov->module = NULL;
353         return 0;
354     }
355
356     for (; provider_dispatch->function_id != 0; provider_dispatch++) {
357         switch (provider_dispatch->function_id) {
358         case OSSL_FUNC_PROVIDER_TEARDOWN:
359             prov->teardown =
360                 OSSL_get_provider_teardown(provider_dispatch);
361             break;
362         case OSSL_FUNC_PROVIDER_GET_PARAM_TYPES:
363             prov->get_param_types =
364                 OSSL_get_provider_get_param_types(provider_dispatch);
365             break;
366         case OSSL_FUNC_PROVIDER_GET_PARAMS:
367             prov->get_params =
368                 OSSL_get_provider_get_params(provider_dispatch);
369             break;
370         case OSSL_FUNC_PROVIDER_QUERY_OPERATION:
371             prov->query_operation =
372                 OSSL_get_provider_query_operation(provider_dispatch);
373             break;
374         }
375     }
376
377     /* With this flag set, this provider has become fully "loaded". */
378     prov->flag_initialized = 1;
379
380     return 1;
381 }
382
383 int ossl_provider_activate(OSSL_PROVIDER *prov)
384 {
385     if (provider_activate(prov)) {
386         CRYPTO_THREAD_write_lock(prov->store->lock);
387         prov->store->use_fallbacks = 0;
388         CRYPTO_THREAD_unlock(prov->store->lock);
389         return 1;
390     }
391
392     return 0;
393 }
394
395
396 static int provider_forall_loaded(struct provider_store_st *store,
397                                   int *found_activated,
398                                   int (*cb)(OSSL_PROVIDER *provider,
399                                             void *cbdata),
400                                   void *cbdata)
401 {
402     int i;
403     int ret = 1;
404     int num_provs = sk_OSSL_PROVIDER_num(store->providers);
405
406     if (found_activated != NULL)
407         *found_activated = 0;
408     for (i = 0; i < num_provs; i++) {
409         OSSL_PROVIDER *prov =
410             sk_OSSL_PROVIDER_value(store->providers, i);
411
412         if (prov->flag_initialized) {
413             if (found_activated != NULL)
414                 *found_activated = 1;
415             if (!(ret = cb(prov, cbdata)))
416                 break;
417         }
418     }
419
420     return ret;
421 }
422
423 int ossl_provider_forall_loaded(OPENSSL_CTX *ctx,
424                                 int (*cb)(OSSL_PROVIDER *provider,
425                                           void *cbdata),
426                                 void *cbdata)
427 {
428     int ret = 1;
429     int i;
430     struct provider_store_st *store = get_provider_store(ctx);
431
432     if (store != NULL) {
433         int found_activated = 0;
434
435         CRYPTO_THREAD_read_lock(store->lock);
436         ret = provider_forall_loaded(store, &found_activated, cb, cbdata);
437
438         /*
439          * If there's nothing activated ever in this store, try to activate
440          * all fallbacks.
441          */
442         if (!found_activated && store->use_fallbacks) {
443             int num_provs = sk_OSSL_PROVIDER_num(store->providers);
444             int activated_fallback_count = 0;
445
446             for (i = 0; i < num_provs; i++) {
447                 OSSL_PROVIDER *prov =
448                     sk_OSSL_PROVIDER_value(store->providers, i);
449
450                 /*
451                  * Note that we don't care if the activation succeeds or
452                  * not.  If it doesn't succeed, then the next loop will
453                  * fail anyway.
454                  */
455                 if (prov->flag_fallback) {
456                     activated_fallback_count++;
457                     provider_activate(prov);
458                 }
459             }
460
461             if (activated_fallback_count > 0) {
462                 /*
463                  * We assume that all fallbacks have been added to the store
464                  * before any fallback is activated.
465                  * TODO: We may have to reconsider this, IF we find ourselves
466                  * adding fallbacks after any previous fallback has been
467                  * activated.
468                  */
469                 store->use_fallbacks = 0;
470
471                 /*
472                  * Now that we've activated available fallbacks, try a
473                  * second sweep
474                  */
475                 ret = provider_forall_loaded(store, NULL, cb, cbdata);
476             }
477         }
478         CRYPTO_THREAD_unlock(store->lock);
479     }
480
481     return ret;
482 }
483
484 /* Setters of Provider Object data */
485 int ossl_provider_set_fallback(OSSL_PROVIDER *prov)
486 {
487     if (prov == NULL)
488         return 0;
489
490     prov->flag_fallback = 1;
491     return 1;
492 }
493
494 /* Getters of Provider Object data */
495 const char *ossl_provider_name(OSSL_PROVIDER *prov)
496 {
497     return prov->name;
498 }
499
500 const DSO *ossl_provider_dso(OSSL_PROVIDER *prov)
501 {
502     return prov->module;
503 }
504
505 const char *ossl_provider_module_name(OSSL_PROVIDER *prov)
506 {
507     return DSO_get_filename(prov->module);
508 }
509
510 const char *ossl_provider_module_path(OSSL_PROVIDER *prov)
511 {
512     /* FIXME: Ensure it's a full path */
513     return DSO_get_filename(prov->module);
514 }
515
516 /* Wrappers around calls to the provider */
517 void ossl_provider_teardown(const OSSL_PROVIDER *prov)
518 {
519     if (prov->teardown != NULL)
520         prov->teardown();
521 }
522
523 const OSSL_ITEM *ossl_provider_get_param_types(const OSSL_PROVIDER *prov)
524 {
525     return prov->get_param_types == NULL ? NULL : prov->get_param_types(prov);
526 }
527
528 int ossl_provider_get_params(const OSSL_PROVIDER *prov,
529                              const OSSL_PARAM params[])
530 {
531     return prov->get_params == NULL ? 0 : prov->get_params(prov, params);
532 }
533
534
535 const OSSL_ALGORITHM *ossl_provider_query_operation(const OSSL_PROVIDER *prov,
536                                                     int operation_id,
537                                                     int *no_cache)
538 {
539     return prov->query_operation(prov, operation_id, no_cache);
540 }
541
542 /*-
543  * Core functions for the provider
544  * ===============================
545  *
546  * This is the set of functions that the core makes available to the provider
547  */
548
549 /*
550  * This returns a list of Provider Object parameters with their types, for
551  * discovery.  We do not expect that many providers will use this, but one
552  * never knows.
553  */
554 static const OSSL_ITEM param_types[] = {
555     { OSSL_PARAM_UTF8_PTR, "openssl-version" },
556     { OSSL_PARAM_UTF8_PTR, "provider-name" },
557     { 0, NULL }
558 };
559
560 static const OSSL_ITEM *core_get_param_types(const OSSL_PROVIDER *prov)
561 {
562     return param_types;
563 }
564
565 static int core_get_params(const OSSL_PROVIDER *prov, const OSSL_PARAM params[])
566 {
567     int i;
568
569     for (i = 0; params[i].key != NULL; i++) {
570         if (strcmp(params[i].key, "openssl-version") == 0) {
571             *(void **)params[i].data = OPENSSL_VERSION_STR;
572             if (params[i].return_size)
573                 *params[i].return_size = sizeof(OPENSSL_VERSION_STR);
574         } else if (strcmp(params[i].key, "provider-name") == 0) {
575             *(void **)params[i].data = prov->name;
576             if (params[i].return_size)
577                 *params[i].return_size = strlen(prov->name) + 1;
578         }
579     }
580
581     return 1;
582 }
583
584 static const OSSL_DISPATCH core_dispatch_[] = {
585     { OSSL_FUNC_CORE_GET_PARAM_TYPES, (void (*)(void))core_get_param_types },
586     { OSSL_FUNC_CORE_GET_PARAMS, (void (*)(void))core_get_params },
587     { 0, NULL }
588 };
589 static const OSSL_DISPATCH *core_dispatch = core_dispatch_;