deprecate engines in libcrypto
[openssl.git] / crypto / engine / eng_dyn.c
1 /*
2  * Copyright 2001-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 "eng_local.h"
14 #include "internal/dso.h"
15 #include <openssl/crypto.h>
16
17 /*
18  * Shared libraries implementing ENGINEs for use by the "dynamic" ENGINE
19  * loader should implement the hook-up functions with the following
20  * prototypes.
21  */
22
23 DEFINE_STACK_OF_STRING()
24
25 /* Our ENGINE handlers */
26 static int dynamic_init(ENGINE *e);
27 static int dynamic_finish(ENGINE *e);
28 static int dynamic_ctrl(ENGINE *e, int cmd, long i, void *p,
29                         void (*f) (void));
30 /* Predeclare our context type */
31 typedef struct st_dynamic_data_ctx dynamic_data_ctx;
32 /* The implementation for the important control command */
33 static int dynamic_load(ENGINE *e, dynamic_data_ctx *ctx);
34
35 #define DYNAMIC_CMD_SO_PATH             ENGINE_CMD_BASE
36 #define DYNAMIC_CMD_NO_VCHECK           (ENGINE_CMD_BASE + 1)
37 #define DYNAMIC_CMD_ID                  (ENGINE_CMD_BASE + 2)
38 #define DYNAMIC_CMD_LIST_ADD            (ENGINE_CMD_BASE + 3)
39 #define DYNAMIC_CMD_DIR_LOAD            (ENGINE_CMD_BASE + 4)
40 #define DYNAMIC_CMD_DIR_ADD             (ENGINE_CMD_BASE + 5)
41 #define DYNAMIC_CMD_LOAD                (ENGINE_CMD_BASE + 6)
42
43 /* The constants used when creating the ENGINE */
44 static const char *engine_dynamic_id = "dynamic";
45 static const char *engine_dynamic_name = "Dynamic engine loading support";
46 static const ENGINE_CMD_DEFN dynamic_cmd_defns[] = {
47     {DYNAMIC_CMD_SO_PATH,
48      "SO_PATH",
49      "Specifies the path to the new ENGINE shared library",
50      ENGINE_CMD_FLAG_STRING},
51     {DYNAMIC_CMD_NO_VCHECK,
52      "NO_VCHECK",
53      "Specifies to continue even if version checking fails (boolean)",
54      ENGINE_CMD_FLAG_NUMERIC},
55     {DYNAMIC_CMD_ID,
56      "ID",
57      "Specifies an ENGINE id name for loading",
58      ENGINE_CMD_FLAG_STRING},
59     {DYNAMIC_CMD_LIST_ADD,
60      "LIST_ADD",
61      "Whether to add a loaded ENGINE to the internal list (0=no,1=yes,2=mandatory)",
62      ENGINE_CMD_FLAG_NUMERIC},
63     {DYNAMIC_CMD_DIR_LOAD,
64      "DIR_LOAD",
65      "Specifies whether to load from 'DIR_ADD' directories (0=no,1=yes,2=mandatory)",
66      ENGINE_CMD_FLAG_NUMERIC},
67     {DYNAMIC_CMD_DIR_ADD,
68      "DIR_ADD",
69      "Adds a directory from which ENGINEs can be loaded",
70      ENGINE_CMD_FLAG_STRING},
71     {DYNAMIC_CMD_LOAD,
72      "LOAD",
73      "Load up the ENGINE specified by other settings",
74      ENGINE_CMD_FLAG_NO_INPUT},
75     {0, NULL, NULL, 0}
76 };
77
78 /*
79  * Loading code stores state inside the ENGINE structure via the "ex_data"
80  * element. We load all our state into a single structure and use that as a
81  * single context in the "ex_data" stack.
82  */
83 struct st_dynamic_data_ctx {
84     /* The DSO object we load that supplies the ENGINE code */
85     DSO *dynamic_dso;
86     /*
87      * The function pointer to the version checking shared library function
88      */
89     dynamic_v_check_fn v_check;
90     /*
91      * The function pointer to the engine-binding shared library function
92      */
93     dynamic_bind_engine bind_engine;
94     /* The default name/path for loading the shared library */
95     char *DYNAMIC_LIBNAME;
96     /* Whether to continue loading on a version check failure */
97     int no_vcheck;
98     /* If non-NULL, stipulates the 'id' of the ENGINE to be loaded */
99     char *engine_id;
100     /*
101      * If non-zero, a successfully loaded ENGINE should be added to the
102      * internal ENGINE list. If 2, the add must succeed or the entire load
103      * should fail.
104      */
105     int list_add_value;
106     /* The symbol name for the version checking function */
107     const char *DYNAMIC_F1;
108     /* The symbol name for the "initialise ENGINE structure" function */
109     const char *DYNAMIC_F2;
110     /*
111      * Whether to never use 'dirs', use 'dirs' as a fallback, or only use
112      * 'dirs' for loading. Default is to use 'dirs' as a fallback.
113      */
114     int dir_load;
115     /* A stack of directories from which ENGINEs could be loaded */
116     STACK_OF(OPENSSL_STRING) *dirs;
117 };
118
119 /*
120  * This is the "ex_data" index we obtain and reserve for use with our context
121  * structure.
122  */
123 static int dynamic_ex_data_idx = -1;
124
125 static void int_free_str(char *s)
126 {
127     OPENSSL_free(s);
128 }
129
130 /*
131  * Because our ex_data element may or may not get allocated depending on
132  * whether a "first-use" occurs before the ENGINE is freed, we have a memory
133  * leak problem to solve. We can't declare a "new" handler for the ex_data as
134  * we don't want a dynamic_data_ctx in *all* ENGINE structures of all types
135  * (this is a bug in the design of CRYPTO_EX_DATA). As such, we just declare
136  * a "free" handler and that will get called if an ENGINE is being destroyed
137  * and there was an ex_data element corresponding to our context type.
138  */
139 static void dynamic_data_ctx_free_func(void *parent, void *ptr,
140                                        CRYPTO_EX_DATA *ad, int idx, long argl,
141                                        void *argp)
142 {
143     if (ptr) {
144         dynamic_data_ctx *ctx = (dynamic_data_ctx *)ptr;
145         DSO_free(ctx->dynamic_dso);
146         OPENSSL_free(ctx->DYNAMIC_LIBNAME);
147         OPENSSL_free(ctx->engine_id);
148         sk_OPENSSL_STRING_pop_free(ctx->dirs, int_free_str);
149         OPENSSL_free(ctx);
150     }
151 }
152
153 /*
154  * Construct the per-ENGINE context. We create it blindly and then use a lock
155  * to check for a race - if so, all but one of the threads "racing" will have
156  * wasted their time. The alternative involves creating everything inside the
157  * lock which is far worse.
158  */
159 static int dynamic_set_data_ctx(ENGINE *e, dynamic_data_ctx **ctx)
160 {
161     dynamic_data_ctx *c = OPENSSL_zalloc(sizeof(*c));
162     int ret = 1;
163
164     if (c == NULL) {
165         ENGINEerr(ENGINE_F_DYNAMIC_SET_DATA_CTX, ERR_R_MALLOC_FAILURE);
166         return 0;
167     }
168     c->dirs = sk_OPENSSL_STRING_new_null();
169     if (c->dirs == NULL) {
170         ENGINEerr(ENGINE_F_DYNAMIC_SET_DATA_CTX, ERR_R_MALLOC_FAILURE);
171         OPENSSL_free(c);
172         return 0;
173     }
174     c->DYNAMIC_F1 = "v_check";
175     c->DYNAMIC_F2 = "bind_engine";
176     c->dir_load = 1;
177     CRYPTO_THREAD_write_lock(global_engine_lock);
178     if ((*ctx = (dynamic_data_ctx *)ENGINE_get_ex_data(e,
179                                                        dynamic_ex_data_idx))
180         == NULL) {
181         /* Good, we're the first */
182         ret = ENGINE_set_ex_data(e, dynamic_ex_data_idx, c);
183         if (ret) {
184             *ctx = c;
185             c = NULL;
186         }
187     }
188     CRYPTO_THREAD_unlock(global_engine_lock);
189     /*
190      * If we lost the race to set the context, c is non-NULL and *ctx is the
191      * context of the thread that won.
192      */
193     if (c)
194         sk_OPENSSL_STRING_free(c->dirs);
195     OPENSSL_free(c);
196     return ret;
197 }
198
199 /*
200  * This function retrieves the context structure from an ENGINE's "ex_data",
201  * or if it doesn't exist yet, sets it up.
202  */
203 static dynamic_data_ctx *dynamic_get_data_ctx(ENGINE *e)
204 {
205     dynamic_data_ctx *ctx;
206     if (dynamic_ex_data_idx < 0) {
207         /*
208          * Create and register the ENGINE ex_data, and associate our "free"
209          * function with it to ensure any allocated contexts get freed when
210          * an ENGINE goes underground.
211          */
212         int new_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL,
213                                               dynamic_data_ctx_free_func);
214         if (new_idx == -1) {
215             ENGINEerr(ENGINE_F_DYNAMIC_GET_DATA_CTX, ENGINE_R_NO_INDEX);
216             return NULL;
217         }
218         CRYPTO_THREAD_write_lock(global_engine_lock);
219         /* Avoid a race by checking again inside this lock */
220         if (dynamic_ex_data_idx < 0) {
221             /* Good, someone didn't beat us to it */
222             dynamic_ex_data_idx = new_idx;
223             new_idx = -1;
224         }
225         CRYPTO_THREAD_unlock(global_engine_lock);
226         /*
227          * In theory we could "give back" the index here if (new_idx>-1), but
228          * it's not possible and wouldn't gain us much if it were.
229          */
230     }
231     ctx = (dynamic_data_ctx *)ENGINE_get_ex_data(e, dynamic_ex_data_idx);
232     /* Check if the context needs to be created */
233     if ((ctx == NULL) && !dynamic_set_data_ctx(e, &ctx))
234         /* "set_data" will set errors if necessary */
235         return NULL;
236     return ctx;
237 }
238
239 static ENGINE *engine_dynamic(void)
240 {
241     ENGINE *ret = ENGINE_new();
242     if (ret == NULL)
243         return NULL;
244     if (!ENGINE_set_id(ret, engine_dynamic_id) ||
245         !ENGINE_set_name(ret, engine_dynamic_name) ||
246         !ENGINE_set_init_function(ret, dynamic_init) ||
247         !ENGINE_set_finish_function(ret, dynamic_finish) ||
248         !ENGINE_set_ctrl_function(ret, dynamic_ctrl) ||
249         !ENGINE_set_flags(ret, ENGINE_FLAGS_BY_ID_COPY) ||
250         !ENGINE_set_cmd_defns(ret, dynamic_cmd_defns)) {
251         ENGINE_free(ret);
252         return NULL;
253     }
254     return ret;
255 }
256
257 void engine_load_dynamic_int(void)
258 {
259     ENGINE *toadd = engine_dynamic();
260     if (!toadd)
261         return;
262     ENGINE_add(toadd);
263     /*
264      * If the "add" worked, it gets a structural reference. So either way, we
265      * release our just-created reference.
266      */
267     ENGINE_free(toadd);
268     /*
269      * If the "add" didn't work, it was probably a conflict because it was
270      * already added (eg. someone calling ENGINE_load_blah then calling
271      * ENGINE_load_builtin_engines() perhaps).
272      */
273     ERR_clear_error();
274 }
275
276 static int dynamic_init(ENGINE *e)
277 {
278     /*
279      * We always return failure - the "dynamic" engine itself can't be used
280      * for anything.
281      */
282     return 0;
283 }
284
285 static int dynamic_finish(ENGINE *e)
286 {
287     /*
288      * This should never be called on account of "dynamic_init" always
289      * failing.
290      */
291     return 0;
292 }
293
294 static int dynamic_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
295 {
296     dynamic_data_ctx *ctx = dynamic_get_data_ctx(e);
297     int initialised;
298
299     if (!ctx) {
300         ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ENGINE_R_NOT_LOADED);
301         return 0;
302     }
303     initialised = ((ctx->dynamic_dso == NULL) ? 0 : 1);
304     /* All our control commands require the ENGINE to be uninitialised */
305     if (initialised) {
306         ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ENGINE_R_ALREADY_LOADED);
307         return 0;
308     }
309     switch (cmd) {
310     case DYNAMIC_CMD_SO_PATH:
311         /* a NULL 'p' or a string of zero-length is the same thing */
312         if (p && (strlen((const char *)p) < 1))
313             p = NULL;
314         OPENSSL_free(ctx->DYNAMIC_LIBNAME);
315         if (p)
316             ctx->DYNAMIC_LIBNAME = OPENSSL_strdup(p);
317         else
318             ctx->DYNAMIC_LIBNAME = NULL;
319         return (ctx->DYNAMIC_LIBNAME ? 1 : 0);
320     case DYNAMIC_CMD_NO_VCHECK:
321         ctx->no_vcheck = ((i == 0) ? 0 : 1);
322         return 1;
323     case DYNAMIC_CMD_ID:
324         /* a NULL 'p' or a string of zero-length is the same thing */
325         if (p && (strlen((const char *)p) < 1))
326             p = NULL;
327         OPENSSL_free(ctx->engine_id);
328         if (p)
329             ctx->engine_id = OPENSSL_strdup(p);
330         else
331             ctx->engine_id = NULL;
332         return (ctx->engine_id ? 1 : 0);
333     case DYNAMIC_CMD_LIST_ADD:
334         if ((i < 0) || (i > 2)) {
335             ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ENGINE_R_INVALID_ARGUMENT);
336             return 0;
337         }
338         ctx->list_add_value = (int)i;
339         return 1;
340     case DYNAMIC_CMD_LOAD:
341         return dynamic_load(e, ctx);
342     case DYNAMIC_CMD_DIR_LOAD:
343         if ((i < 0) || (i > 2)) {
344             ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ENGINE_R_INVALID_ARGUMENT);
345             return 0;
346         }
347         ctx->dir_load = (int)i;
348         return 1;
349     case DYNAMIC_CMD_DIR_ADD:
350         /* a NULL 'p' or a string of zero-length is the same thing */
351         if (p == NULL || (strlen((const char *)p) < 1)) {
352             ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ENGINE_R_INVALID_ARGUMENT);
353             return 0;
354         }
355         {
356             char *tmp_str = OPENSSL_strdup(p);
357             if (tmp_str == NULL) {
358                 ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ERR_R_MALLOC_FAILURE);
359                 return 0;
360             }
361             if (!sk_OPENSSL_STRING_push(ctx->dirs, tmp_str)) {
362                 OPENSSL_free(tmp_str);
363                 ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ERR_R_MALLOC_FAILURE);
364                 return 0;
365             }
366         }
367         return 1;
368     default:
369         break;
370     }
371     ENGINEerr(ENGINE_F_DYNAMIC_CTRL, ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED);
372     return 0;
373 }
374
375 static int int_load(dynamic_data_ctx *ctx)
376 {
377     int num, loop;
378     /* Unless told not to, try a direct load */
379     if ((ctx->dir_load != 2) && (DSO_load(ctx->dynamic_dso,
380                                           ctx->DYNAMIC_LIBNAME, NULL,
381                                           0)) != NULL)
382         return 1;
383     /* If we're not allowed to use 'dirs' or we have none, fail */
384     if (!ctx->dir_load || (num = sk_OPENSSL_STRING_num(ctx->dirs)) < 1)
385         return 0;
386     for (loop = 0; loop < num; loop++) {
387         const char *s = sk_OPENSSL_STRING_value(ctx->dirs, loop);
388         char *merge = DSO_merge(ctx->dynamic_dso, ctx->DYNAMIC_LIBNAME, s);
389         if (!merge)
390             return 0;
391         if (DSO_load(ctx->dynamic_dso, merge, NULL, 0)) {
392             /* Found what we're looking for */
393             OPENSSL_free(merge);
394             return 1;
395         }
396         OPENSSL_free(merge);
397     }
398     return 0;
399 }
400
401 static int dynamic_load(ENGINE *e, dynamic_data_ctx *ctx)
402 {
403     ENGINE cpy;
404     dynamic_fns fns;
405
406     if (ctx->dynamic_dso == NULL)
407         ctx->dynamic_dso = DSO_new();
408     if (ctx->dynamic_dso == NULL)
409         return 0;
410     if (!ctx->DYNAMIC_LIBNAME) {
411         if (!ctx->engine_id)
412             return 0;
413         DSO_ctrl(ctx->dynamic_dso, DSO_CTRL_SET_FLAGS,
414                  DSO_FLAG_NAME_TRANSLATION_EXT_ONLY, NULL);
415         ctx->DYNAMIC_LIBNAME =
416             DSO_convert_filename(ctx->dynamic_dso, ctx->engine_id);
417     }
418     if (!int_load(ctx)) {
419         ENGINEerr(ENGINE_F_DYNAMIC_LOAD, ENGINE_R_DSO_NOT_FOUND);
420         DSO_free(ctx->dynamic_dso);
421         ctx->dynamic_dso = NULL;
422         return 0;
423     }
424     /* We have to find a bind function otherwise it'll always end badly */
425     if (!
426         (ctx->bind_engine =
427          (dynamic_bind_engine) DSO_bind_func(ctx->dynamic_dso,
428                                              ctx->DYNAMIC_F2))) {
429         ctx->bind_engine = NULL;
430         DSO_free(ctx->dynamic_dso);
431         ctx->dynamic_dso = NULL;
432         ENGINEerr(ENGINE_F_DYNAMIC_LOAD, ENGINE_R_DSO_FAILURE);
433         return 0;
434     }
435     /* Do we perform version checking? */
436     if (!ctx->no_vcheck) {
437         unsigned long vcheck_res = 0;
438         /*
439          * Now we try to find a version checking function and decide how to
440          * cope with failure if/when it fails.
441          */
442         ctx->v_check =
443             (dynamic_v_check_fn) DSO_bind_func(ctx->dynamic_dso,
444                                                ctx->DYNAMIC_F1);
445         if (ctx->v_check)
446             vcheck_res = ctx->v_check(OSSL_DYNAMIC_VERSION);
447         /*
448          * We fail if the version checker veto'd the load *or* if it is
449          * deferring to us (by returning its version) and we think it is too
450          * old.
451          */
452         if (vcheck_res < OSSL_DYNAMIC_OLDEST) {
453             /* Fail */
454             ctx->bind_engine = NULL;
455             ctx->v_check = NULL;
456             DSO_free(ctx->dynamic_dso);
457             ctx->dynamic_dso = NULL;
458             ENGINEerr(ENGINE_F_DYNAMIC_LOAD,
459                       ENGINE_R_VERSION_INCOMPATIBILITY);
460             return 0;
461         }
462     }
463     /*
464      * First binary copy the ENGINE structure so that we can roll back if the
465      * hand-over fails
466      */
467     memcpy(&cpy, e, sizeof(ENGINE));
468     /*
469      * Provide the ERR, "ex_data", memory, and locking callbacks so the
470      * loaded library uses our state rather than its own. FIXME: As noted in
471      * engine.h, much of this would be simplified if each area of code
472      * provided its own "summary" structure of all related callbacks. It
473      * would also increase opaqueness.
474      */
475     fns.static_state = ENGINE_get_static_state();
476     CRYPTO_get_mem_functions(&fns.mem_fns.malloc_fn, &fns.mem_fns.realloc_fn,
477                              &fns.mem_fns.free_fn);
478     /*
479      * Now that we've loaded the dynamic engine, make sure no "dynamic"
480      * ENGINE elements will show through.
481      */
482     engine_set_all_null(e);
483
484     /* Try to bind the ENGINE onto our own ENGINE structure */
485     if (!ctx->bind_engine(e, ctx->engine_id, &fns)) {
486         ctx->bind_engine = NULL;
487         ctx->v_check = NULL;
488         DSO_free(ctx->dynamic_dso);
489         ctx->dynamic_dso = NULL;
490         ENGINEerr(ENGINE_F_DYNAMIC_LOAD, ENGINE_R_INIT_FAILED);
491         /* Copy the original ENGINE structure back */
492         memcpy(e, &cpy, sizeof(ENGINE));
493         return 0;
494     }
495     /* Do we try to add this ENGINE to the internal list too? */
496     if (ctx->list_add_value > 0) {
497         if (!ENGINE_add(e)) {
498             /* Do we tolerate this or fail? */
499             if (ctx->list_add_value > 1) {
500                 /*
501                  * Fail - NB: By this time, it's too late to rollback, and
502                  * trying to do so allows the bind_engine() code to have
503                  * created leaks. We just have to fail where we are, after
504                  * the ENGINE has changed.
505                  */
506                 ENGINEerr(ENGINE_F_DYNAMIC_LOAD,
507                           ENGINE_R_CONFLICTING_ENGINE_ID);
508                 return 0;
509             }
510             /* Tolerate */
511             ERR_clear_error();
512         }
513     }
514     return 1;
515 }