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