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