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