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