7724084255fa3f9219b8d8a205b45d77b7e40094
[openssl.git] / apps / engine.c
1 /*
2  * Copyright 2000-2017 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 <openssl/opensslconf.h>
11 #ifdef OPENSSL_NO_ENGINE
12 NON_EMPTY_TRANSLATION_UNIT
13 #else
14
15 # include "apps.h"
16 # include <stdio.h>
17 # include <stdlib.h>
18 # include <string.h>
19 # include <openssl/err.h>
20 # include <openssl/engine.h>
21 # include <openssl/ssl.h>
22 # include <openssl/store.h>
23
24 typedef enum OPTION_choice {
25     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
26     OPT_C, OPT_T, OPT_TT, OPT_PRE, OPT_POST,
27     OPT_V = 100, OPT_VV, OPT_VVV, OPT_VVVV
28 } OPTION_CHOICE;
29
30 const OPTIONS engine_options[] = {
31     {OPT_HELP_STR, 1, '-', "Usage: %s [options] engine...\n"},
32     {OPT_HELP_STR, 1, '-',
33         "  engine... Engines to load\n"},
34     {"help", OPT_HELP, '-', "Display this summary"},
35     {"v", OPT_V, '-', "List 'control commands' For each specified engine"},
36     {"vv", OPT_VV, '-', "Also display each command's description"},
37     {"vvv", OPT_VVV, '-', "Also add the input flags for each command"},
38     {"vvvv", OPT_VVVV, '-', "Also show internal input flags"},
39     {"c", OPT_C, '-', "List the capabilities of specified engine"},
40     {"t", OPT_T, '-', "Check that specified engine is available"},
41     {"tt", OPT_TT, '-', "Display error trace for unavailable engines"},
42     {"pre", OPT_PRE, 's', "Run command against the ENGINE before loading it"},
43     {"post", OPT_POST, 's', "Run command against the ENGINE after loading it"},
44     {OPT_MORE_STR, OPT_EOF, 1,
45      "Commands are like \"SO_PATH:/lib/libdriver.so\""},
46     {NULL}
47 };
48
49 static int append_buf(char **buf, int *size, const char *s)
50 {
51     if (*buf == NULL) {
52         *size = 256;
53         *buf = app_malloc(*size, "engine buffer");
54         **buf = '\0';
55     }
56
57     if (strlen(*buf) + strlen(s) >= (unsigned int)*size) {
58         char *tmp;
59         *size += 256;
60         tmp = OPENSSL_realloc(*buf, *size);
61         if (tmp == NULL) {
62             OPENSSL_free(*buf);
63             *buf = NULL;
64             return 0;
65         }
66         *buf = tmp;
67     }
68
69     if (**buf != '\0')
70         OPENSSL_strlcat(*buf, ", ", *size);
71     OPENSSL_strlcat(*buf, s, *size);
72
73     return 1;
74 }
75
76 static int util_flags(BIO *out, unsigned int flags, const char *indent)
77 {
78     int started = 0, err = 0;
79     /* Indent before displaying input flags */
80     BIO_printf(out, "%s%s(input flags): ", indent, indent);
81     if (flags == 0) {
82         BIO_printf(out, "<no flags>\n");
83         return 1;
84     }
85     /*
86      * If the object is internal, mark it in a way that shows instead of
87      * having it part of all the other flags, even if it really is.
88      */
89     if (flags & ENGINE_CMD_FLAG_INTERNAL) {
90         BIO_printf(out, "[Internal] ");
91     }
92
93     if (flags & ENGINE_CMD_FLAG_NUMERIC) {
94         BIO_printf(out, "NUMERIC");
95         started = 1;
96     }
97     /*
98      * Now we check that no combinations of the mutually exclusive NUMERIC,
99      * STRING, and NO_INPUT flags have been used. Future flags that can be
100      * OR'd together with these would need to added after these to preserve
101      * the testing logic.
102      */
103     if (flags & ENGINE_CMD_FLAG_STRING) {
104         if (started) {
105             BIO_printf(out, "|");
106             err = 1;
107         }
108         BIO_printf(out, "STRING");
109         started = 1;
110     }
111     if (flags & ENGINE_CMD_FLAG_NO_INPUT) {
112         if (started) {
113             BIO_printf(out, "|");
114             err = 1;
115         }
116         BIO_printf(out, "NO_INPUT");
117         started = 1;
118     }
119     /* Check for unknown flags */
120     flags = flags & ~ENGINE_CMD_FLAG_NUMERIC &
121         ~ENGINE_CMD_FLAG_STRING &
122         ~ENGINE_CMD_FLAG_NO_INPUT & ~ENGINE_CMD_FLAG_INTERNAL;
123     if (flags) {
124         if (started)
125             BIO_printf(out, "|");
126         BIO_printf(out, "<0x%04X>", flags);
127     }
128     if (err)
129         BIO_printf(out, "  <illegal flags!>");
130     BIO_printf(out, "\n");
131     return 1;
132 }
133
134 static int util_verbose(ENGINE *e, int verbose, BIO *out, const char *indent)
135 {
136     static const int line_wrap = 78;
137     int num;
138     int ret = 0;
139     char *name = NULL;
140     char *desc = NULL;
141     int flags;
142     int xpos = 0;
143     STACK_OF(OPENSSL_STRING) *cmds = NULL;
144     if (!ENGINE_ctrl(e, ENGINE_CTRL_HAS_CTRL_FUNCTION, 0, NULL, NULL) ||
145         ((num = ENGINE_ctrl(e, ENGINE_CTRL_GET_FIRST_CMD_TYPE,
146                             0, NULL, NULL)) <= 0)) {
147         return 1;
148     }
149
150     cmds = sk_OPENSSL_STRING_new_null();
151     if (cmds == NULL)
152         goto err;
153
154     do {
155         int len;
156         /* Get the command input flags */
157         if ((flags = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FLAGS, num,
158                                  NULL, NULL)) < 0)
159             goto err;
160         if (!(flags & ENGINE_CMD_FLAG_INTERNAL) || verbose >= 4) {
161             /* Get the command name */
162             if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_LEN_FROM_CMD, num,
163                                    NULL, NULL)) <= 0)
164                 goto err;
165             name = app_malloc(len + 1, "name buffer");
166             if (ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_FROM_CMD, num, name,
167                             NULL) <= 0)
168                 goto err;
169             /* Get the command description */
170             if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_LEN_FROM_CMD, num,
171                                    NULL, NULL)) < 0)
172                 goto err;
173             if (len > 0) {
174                 desc = app_malloc(len + 1, "description buffer");
175                 if (ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_FROM_CMD, num, desc,
176                                 NULL) <= 0)
177                     goto err;
178             }
179             /* Now decide on the output */
180             if (xpos == 0)
181                 /* Do an indent */
182                 xpos = BIO_puts(out, indent);
183             else
184                 /* Otherwise prepend a ", " */
185                 xpos += BIO_printf(out, ", ");
186             if (verbose == 1) {
187                 /*
188                  * We're just listing names, comma-delimited
189                  */
190                 if ((xpos > (int)strlen(indent)) &&
191                     (xpos + (int)strlen(name) > line_wrap)) {
192                     BIO_printf(out, "\n");
193                     xpos = BIO_puts(out, indent);
194                 }
195                 xpos += BIO_printf(out, "%s", name);
196             } else {
197                 /* We're listing names plus descriptions */
198                 BIO_printf(out, "%s: %s\n", name,
199                            (desc == NULL) ? "<no description>" : desc);
200                 /* ... and sometimes input flags */
201                 if ((verbose >= 3) && !util_flags(out, flags, indent))
202                     goto err;
203                 xpos = 0;
204             }
205         }
206         OPENSSL_free(name);
207         name = NULL;
208         OPENSSL_free(desc);
209         desc = NULL;
210         /* Move to the next command */
211         num = ENGINE_ctrl(e, ENGINE_CTRL_GET_NEXT_CMD_TYPE, num, NULL, NULL);
212     } while (num > 0);
213     if (xpos > 0)
214         BIO_printf(out, "\n");
215     ret = 1;
216  err:
217     sk_OPENSSL_STRING_free(cmds);
218     OPENSSL_free(name);
219     OPENSSL_free(desc);
220     return ret;
221 }
222
223 static void util_do_cmds(ENGINE *e, STACK_OF(OPENSSL_STRING) *cmds,
224                          BIO *out, const char *indent)
225 {
226     int loop, res, num = sk_OPENSSL_STRING_num(cmds);
227
228     if (num < 0) {
229         BIO_printf(out, "[Error]: internal stack error\n");
230         return;
231     }
232     for (loop = 0; loop < num; loop++) {
233         char buf[256];
234         const char *cmd, *arg;
235         cmd = sk_OPENSSL_STRING_value(cmds, loop);
236         res = 1;                /* assume success */
237         /* Check if this command has no ":arg" */
238         if ((arg = strstr(cmd, ":")) == NULL) {
239             if (!ENGINE_ctrl_cmd_string(e, cmd, NULL, 0))
240                 res = 0;
241         } else {
242             if ((int)(arg - cmd) > 254) {
243                 BIO_printf(out, "[Error]: command name too long\n");
244                 return;
245             }
246             memcpy(buf, cmd, (int)(arg - cmd));
247             buf[arg - cmd] = '\0';
248             arg++;              /* Move past the ":" */
249             /* Call the command with the argument */
250             if (!ENGINE_ctrl_cmd_string(e, buf, arg, 0))
251                 res = 0;
252         }
253         if (res) {
254             BIO_printf(out, "[Success]: %s\n", cmd);
255         } else {
256             BIO_printf(out, "[Failure]: %s\n", cmd);
257             ERR_print_errors(out);
258         }
259     }
260 }
261
262 struct util_store_cap_data {
263     ENGINE *engine;
264     char **cap_buf;
265     int *cap_size;
266     int ok;
267 };
268 static void util_store_cap(const OSSL_STORE_LOADER *loader, void *arg)
269 {
270     struct util_store_cap_data *ctx = arg;
271
272     if (OSSL_STORE_LOADER_get0_engine(loader) == ctx->engine) {
273         char buf[256];
274         BIO_snprintf(buf, sizeof(buf), "STORE(%s)",
275                      OSSL_STORE_LOADER_get0_scheme(loader));
276         if (!append_buf(ctx->cap_buf, ctx->cap_size, buf))
277             ctx->ok = 0;
278     }
279 }
280
281 int engine_main(int argc, char **argv)
282 {
283     int ret = 1, i;
284     int verbose = 0, list_cap = 0, test_avail = 0, test_avail_noise = 0;
285     ENGINE *e;
286     STACK_OF(OPENSSL_CSTRING) *engines = sk_OPENSSL_CSTRING_new_null();
287     STACK_OF(OPENSSL_STRING) *pre_cmds = sk_OPENSSL_STRING_new_null();
288     STACK_OF(OPENSSL_STRING) *post_cmds = sk_OPENSSL_STRING_new_null();
289     BIO *out;
290     const char *indent = "     ";
291     OPTION_CHOICE o;
292     char *prog;
293     char *argv1;
294
295     out = dup_bio_out(FORMAT_TEXT);
296     if (engines == NULL || pre_cmds == NULL || post_cmds == NULL)
297         goto end;
298
299     /* Remember the original command name, parse/skip any leading engine
300      * names, and then setup to parse the rest of the line as flags. */
301     prog = argv[0];
302     while ((argv1 = argv[1]) != NULL && *argv1 != '-') {
303         sk_OPENSSL_CSTRING_push(engines, argv1);
304         argc--;
305         argv++;
306     }
307     argv[0] = prog;
308     opt_init(argc, argv, engine_options);
309
310     while ((o = opt_next()) != OPT_EOF) {
311         switch (o) {
312         case OPT_EOF:
313         case OPT_ERR:
314             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
315             goto end;
316         case OPT_HELP:
317             opt_help(engine_options);
318             ret = 0;
319             goto end;
320         case OPT_VVVV:
321         case OPT_VVV:
322         case OPT_VV:
323         case OPT_V:
324             /* Convert to an integer from one to four. */
325             i = (int)(o - OPT_V) + 1;
326             if (verbose < i)
327                 verbose = i;
328             break;
329         case OPT_C:
330             list_cap = 1;
331             break;
332         case OPT_TT:
333             test_avail_noise++;
334             /* fall thru */
335         case OPT_T:
336             test_avail++;
337             break;
338         case OPT_PRE:
339             sk_OPENSSL_STRING_push(pre_cmds, opt_arg());
340             break;
341         case OPT_POST:
342             sk_OPENSSL_STRING_push(post_cmds, opt_arg());
343             break;
344         }
345     }
346
347     /* Allow any trailing parameters as engine names. */
348     argc = opt_num_rest();
349     argv = opt_rest();
350     for ( ; *argv; argv++) {
351         if (**argv == '-') {
352             BIO_printf(bio_err, "%s: Cannot mix flags and engine names.\n",
353                        prog);
354             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
355             goto end;
356         }
357         sk_OPENSSL_CSTRING_push(engines, *argv);
358     }
359
360     if (sk_OPENSSL_CSTRING_num(engines) == 0) {
361         for (e = ENGINE_get_first(); e != NULL; e = ENGINE_get_next(e)) {
362             sk_OPENSSL_CSTRING_push(engines, ENGINE_get_id(e));
363         }
364     }
365
366     ret = 0;
367     for (i = 0; i < sk_OPENSSL_CSTRING_num(engines); i++) {
368         const char *id = sk_OPENSSL_CSTRING_value(engines, i);
369         if ((e = ENGINE_by_id(id)) != NULL) {
370             const char *name = ENGINE_get_name(e);
371             /*
372              * Do "id" first, then "name". Easier to auto-parse.
373              */
374             BIO_printf(out, "(%s) %s\n", id, name);
375             util_do_cmds(e, pre_cmds, out, indent);
376             if (strcmp(ENGINE_get_id(e), id) != 0) {
377                 BIO_printf(out, "Loaded: (%s) %s\n",
378                            ENGINE_get_id(e), ENGINE_get_name(e));
379             }
380             if (list_cap) {
381                 int cap_size = 256;
382                 char *cap_buf = NULL;
383                 int k, n;
384                 const int *nids;
385                 ENGINE_CIPHERS_PTR fn_c;
386                 ENGINE_DIGESTS_PTR fn_d;
387                 ENGINE_PKEY_METHS_PTR fn_pk;
388
389                 if (ENGINE_get_RSA(e) != NULL
390                     && !append_buf(&cap_buf, &cap_size, "RSA"))
391                     goto end;
392                 if (ENGINE_get_DSA(e) != NULL
393                     && !append_buf(&cap_buf, &cap_size, "DSA"))
394                     goto end;
395                 if (ENGINE_get_DH(e) != NULL
396                     && !append_buf(&cap_buf, &cap_size, "DH"))
397                     goto end;
398                 if (ENGINE_get_RAND(e) != NULL
399                     && !append_buf(&cap_buf, &cap_size, "RAND"))
400                     goto end;
401
402                 fn_c = ENGINE_get_ciphers(e);
403                 if (fn_c == NULL)
404                     goto skip_ciphers;
405                 n = fn_c(e, NULL, &nids, 0);
406                 for (k = 0; k < n; ++k)
407                     if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k])))
408                         goto end;
409
410  skip_ciphers:
411                 fn_d = ENGINE_get_digests(e);
412                 if (fn_d == NULL)
413                     goto skip_digests;
414                 n = fn_d(e, NULL, &nids, 0);
415                 for (k = 0; k < n; ++k)
416                     if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k])))
417                         goto end;
418
419  skip_digests:
420                 fn_pk = ENGINE_get_pkey_meths(e);
421                 if (fn_pk == NULL)
422                     goto skip_pmeths;
423                 n = fn_pk(e, NULL, &nids, 0);
424                 for (k = 0; k < n; ++k)
425                     if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k])))
426                         goto end;
427  skip_pmeths:
428                 {
429                     struct util_store_cap_data store_ctx;
430
431                     store_ctx.engine = e;
432                     store_ctx.cap_buf = &cap_buf;
433                     store_ctx.cap_size = &cap_size;
434                     store_ctx.ok = 1;
435
436                     OSSL_STORE_do_all_loaders(util_store_cap, &store_ctx);
437                     if (!store_ctx.ok)
438                         goto end;
439                 }
440                 if (cap_buf != NULL && (*cap_buf != '\0'))
441                     BIO_printf(out, " [%s]\n", cap_buf);
442
443                 OPENSSL_free(cap_buf);
444             }
445             if (test_avail) {
446                 BIO_printf(out, "%s", indent);
447                 if (ENGINE_init(e)) {
448                     BIO_printf(out, "[ available ]\n");
449                     util_do_cmds(e, post_cmds, out, indent);
450                     ENGINE_finish(e);
451                 } else {
452                     BIO_printf(out, "[ unavailable ]\n");
453                     if (test_avail_noise)
454                         ERR_print_errors_fp(stdout);
455                     ERR_clear_error();
456                 }
457             }
458             if ((verbose > 0) && !util_verbose(e, verbose, out, indent))
459                 goto end;
460             ENGINE_free(e);
461         } else {
462             ERR_print_errors(bio_err);
463             /* because exit codes above 127 have special meaning on Unix */
464             if (++ret > 127)
465                 ret = 127;
466         }
467     }
468
469  end:
470
471     ERR_print_errors(bio_err);
472     sk_OPENSSL_CSTRING_free(engines);
473     sk_OPENSSL_STRING_free(pre_cmds);
474     sk_OPENSSL_STRING_free(post_cmds);
475     BIO_free_all(out);
476     return (ret);
477 }
478 #endif