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