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