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