b10f61631da2a45a6a496299ad3418db12dc4d1f
[openssl.git] / apps / engine.c
1 /*
2  * Written by Richard Levitte <richard@levitte.org> for the OpenSSL project
3  * 2000.
4  */
5 /* ====================================================================
6  * Copyright (c) 2000 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include "apps.h"
63 #include <openssl/err.h>
64 #ifndef OPENSSL_NO_ENGINE
65 # include <openssl/engine.h>
66 # include <openssl/ssl.h>
67
68 typedef enum OPTION_choice {
69     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
70     OPT_C, OPT_T, OPT_TT, OPT_PRE, OPT_POST,
71     OPT_V = 100, OPT_VV, OPT_VVV, OPT_VVVV
72 } OPTION_CHOICE;
73
74 OPTIONS engine_options[] = {
75     {OPT_HELP_STR, 1, '-', "Usage: %s [options] engine...\n"},
76     {OPT_HELP_STR, 1, '-',
77         "  engine... Engines to load\n"},
78     {"help", OPT_HELP, '-', "Display this summary"},
79     {"v", OPT_V, '-', "List 'control commands' For each specified engine"},
80     {"vv", OPT_VV, '-', "Also display each command's description"},
81     {"vvv", OPT_VVV, '-', "Also add the input flags for each command"},
82     {"vvvv", OPT_VVVV, '-', "Also show internal input flags"},
83     {"c", OPT_C, '-', "List the capabilities of specified engine"},
84     {"t", OPT_T, '-', "Check that specified engine is available"},
85     {"tt", OPT_TT, '-', "Display error trace for unavailable engines"},
86     {"pre", OPT_PRE, 's', "Run command against the ENGINE before loading it"},
87     {"post", OPT_POST, 's', "Run command against the ENGINE after loading it"},
88     {OPT_MORE_STR, OPT_EOF, 1,
89      "Commands are like \"SO_PATH:/lib/libdriver.so\""},
90     {NULL}
91 };
92
93 static void identity(char *ptr)
94 {
95 }
96
97 static int append_buf(char **buf, int *size, const char *s)
98 {
99     if (*buf == NULL) {
100         *size = 256;
101         *buf = app_malloc(*size, "engine buffer");
102         **buf = '\0';
103     }
104
105     if (strlen(*buf) + strlen(s) >= (unsigned int)*size) {
106         *size += 256;
107         *buf = OPENSSL_realloc(*buf, *size);
108     }
109
110     if (*buf == NULL)
111         return 0;
112
113     if (**buf != '\0')
114         OPENSSL_strlcat(*buf, ", ", *size);
115     OPENSSL_strlcat(*buf, s, *size);
116
117     return 1;
118 }
119
120 static int util_flags(BIO *out, unsigned int flags, const char *indent)
121 {
122     int started = 0, err = 0;
123     /* Indent before displaying input flags */
124     BIO_printf(out, "%s%s(input flags): ", indent, indent);
125     if (flags == 0) {
126         BIO_printf(out, "<no flags>\n");
127         return 1;
128     }
129     /*
130      * If the object is internal, mark it in a way that shows instead of
131      * having it part of all the other flags, even if it really is.
132      */
133     if (flags & ENGINE_CMD_FLAG_INTERNAL) {
134         BIO_printf(out, "[Internal] ");
135     }
136
137     if (flags & ENGINE_CMD_FLAG_NUMERIC) {
138         BIO_printf(out, "NUMERIC");
139         started = 1;
140     }
141     /*
142      * Now we check that no combinations of the mutually exclusive NUMERIC,
143      * STRING, and NO_INPUT flags have been used. Future flags that can be
144      * OR'd together with these would need to added after these to preserve
145      * the testing logic.
146      */
147     if (flags & ENGINE_CMD_FLAG_STRING) {
148         if (started) {
149             BIO_printf(out, "|");
150             err = 1;
151         }
152         BIO_printf(out, "STRING");
153         started = 1;
154     }
155     if (flags & ENGINE_CMD_FLAG_NO_INPUT) {
156         if (started) {
157             BIO_printf(out, "|");
158             err = 1;
159         }
160         BIO_printf(out, "NO_INPUT");
161         started = 1;
162     }
163     /* Check for unknown flags */
164     flags = flags & ~ENGINE_CMD_FLAG_NUMERIC &
165         ~ENGINE_CMD_FLAG_STRING &
166         ~ENGINE_CMD_FLAG_NO_INPUT & ~ENGINE_CMD_FLAG_INTERNAL;
167     if (flags) {
168         if (started)
169             BIO_printf(out, "|");
170         BIO_printf(out, "<0x%04X>", flags);
171     }
172     if (err)
173         BIO_printf(out, "  <illegal flags!>");
174     BIO_printf(out, "\n");
175     return 1;
176 }
177
178 static int util_verbose(ENGINE *e, int verbose, BIO *out, const char *indent)
179 {
180     static const int line_wrap = 78;
181     int num;
182     int ret = 0;
183     char *name = NULL;
184     char *desc = NULL;
185     int flags;
186     int xpos = 0;
187     STACK_OF(OPENSSL_STRING) *cmds = NULL;
188     if (!ENGINE_ctrl(e, ENGINE_CTRL_HAS_CTRL_FUNCTION, 0, NULL, NULL) ||
189         ((num = ENGINE_ctrl(e, ENGINE_CTRL_GET_FIRST_CMD_TYPE,
190                             0, NULL, NULL)) <= 0)) {
191         return 1;
192     }
193
194     cmds = sk_OPENSSL_STRING_new_null();
195     if (!cmds)
196         goto err;
197
198     do {
199         int len;
200         /* Get the command input flags */
201         if ((flags = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FLAGS, num,
202                                  NULL, NULL)) < 0)
203             goto err;
204         if (!(flags & ENGINE_CMD_FLAG_INTERNAL) || verbose >= 4) {
205             /* Get the command name */
206             if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_LEN_FROM_CMD, num,
207                                    NULL, NULL)) <= 0)
208                 goto err;
209             name = app_malloc(len + 1, "name buffer");
210             if (ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_FROM_CMD, num, name,
211                             NULL) <= 0)
212                 goto err;
213             /* Get the command description */
214             if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_LEN_FROM_CMD, num,
215                                    NULL, NULL)) < 0)
216                 goto err;
217             if (len > 0) {
218                 desc = app_malloc(len + 1, "description buffer");
219                 if (ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_FROM_CMD, num, desc,
220                                 NULL) <= 0)
221                     goto err;
222             }
223             /* Now decide on the output */
224             if (xpos == 0)
225                 /* Do an indent */
226                 xpos = BIO_puts(out, indent);
227             else
228                 /* Otherwise prepend a ", " */
229                 xpos += BIO_printf(out, ", ");
230             if (verbose == 1) {
231                 /*
232                  * We're just listing names, comma-delimited
233                  */
234                 if ((xpos > (int)strlen(indent)) &&
235                     (xpos + (int)strlen(name) > line_wrap)) {
236                     BIO_printf(out, "\n");
237                     xpos = BIO_puts(out, indent);
238                 }
239                 xpos += BIO_printf(out, "%s", name);
240             } else {
241                 /* We're listing names plus descriptions */
242                 BIO_printf(out, "%s: %s\n", name,
243                            (desc == NULL) ? "<no description>" : desc);
244                 /* ... and sometimes input flags */
245                 if ((verbose >= 3) && !util_flags(out, flags, indent))
246                     goto err;
247                 xpos = 0;
248             }
249         }
250         OPENSSL_free(name);
251         name = NULL;
252         OPENSSL_free(desc);
253         desc = NULL;
254         /* Move to the next command */
255         num = ENGINE_ctrl(e, ENGINE_CTRL_GET_NEXT_CMD_TYPE, num, NULL, NULL);
256     } while (num > 0);
257     if (xpos > 0)
258         BIO_printf(out, "\n");
259     ret = 1;
260  err:
261     sk_OPENSSL_STRING_pop_free(cmds, identity);
262     OPENSSL_free(name);
263     OPENSSL_free(desc);
264     return ret;
265 }
266
267 static void util_do_cmds(ENGINE *e, STACK_OF(OPENSSL_STRING) *cmds,
268                          BIO *out, const char *indent)
269 {
270     int loop, res, num = sk_OPENSSL_STRING_num(cmds);
271
272     if (num < 0) {
273         BIO_printf(out, "[Error]: internal stack error\n");
274         return;
275     }
276     for (loop = 0; loop < num; loop++) {
277         char buf[256];
278         const char *cmd, *arg;
279         cmd = sk_OPENSSL_STRING_value(cmds, loop);
280         res = 1;                /* assume success */
281         /* Check if this command has no ":arg" */
282         if ((arg = strstr(cmd, ":")) == NULL) {
283             if (!ENGINE_ctrl_cmd_string(e, cmd, NULL, 0))
284                 res = 0;
285         } else {
286             if ((int)(arg - cmd) > 254) {
287                 BIO_printf(out, "[Error]: command name too long\n");
288                 return;
289             }
290             memcpy(buf, cmd, (int)(arg - cmd));
291             buf[arg - cmd] = '\0';
292             arg++;              /* Move past the ":" */
293             /* Call the command with the argument */
294             if (!ENGINE_ctrl_cmd_string(e, buf, arg, 0))
295                 res = 0;
296         }
297         if (res)
298             BIO_printf(out, "[Success]: %s\n", cmd);
299         else {
300             BIO_printf(out, "[Failure]: %s\n", cmd);
301             ERR_print_errors(out);
302         }
303     }
304 }
305
306 int engine_main(int argc, char **argv)
307 {
308     int ret = 1, i;
309     int verbose = 0, list_cap = 0, test_avail = 0, test_avail_noise = 0;
310     ENGINE *e;
311     STACK_OF(OPENSSL_STRING) *engines = sk_OPENSSL_STRING_new_null();
312     STACK_OF(OPENSSL_STRING) *pre_cmds = sk_OPENSSL_STRING_new_null();
313     STACK_OF(OPENSSL_STRING) *post_cmds = sk_OPENSSL_STRING_new_null();
314     BIO *out;
315     const char *indent = "     ";
316     OPTION_CHOICE o;
317     char *prog;
318     char *argv1;
319
320     out = dup_bio_out(FORMAT_TEXT);
321     if (engines == NULL || pre_cmds == NULL || post_cmds == NULL)
322         goto end;
323
324     /* Remember the original command name, parse/skip any leading engine
325      * names, and then setup to parse the rest of the line as flags. */
326     prog = argv[0];
327     while ((argv1 = argv[1]) != NULL && *argv1 != '-') {
328         sk_OPENSSL_STRING_push(engines, argv1);
329         argc--;
330         argv++;
331     }
332     argv[0] = prog;
333     opt_init(argc, argv, engine_options);
334
335     while ((o = opt_next()) != OPT_EOF) {
336         switch (o) {
337         case OPT_EOF:
338         case OPT_ERR:
339             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
340             goto end;
341         case OPT_HELP:
342             opt_help(engine_options);
343             ret = 0;
344             goto end;
345         case OPT_VVVV:
346         case OPT_VVV:
347         case OPT_VV:
348         case OPT_V:
349             /* Convert to an integer from one to four. */
350             i = (int)(o - OPT_V) + 1;
351             if (verbose < i)
352                 verbose = i;
353             break;
354         case OPT_C:
355             list_cap = 1;
356             break;
357         case OPT_TT:
358             test_avail_noise++;
359         case OPT_T:
360             test_avail++;
361             break;
362         case OPT_PRE:
363             sk_OPENSSL_STRING_push(pre_cmds, opt_arg());
364             break;
365         case OPT_POST:
366             sk_OPENSSL_STRING_push(post_cmds, opt_arg());
367             break;
368         }
369     }
370
371     /* Allow any trailing parameters as engine names. */
372     argc = opt_num_rest();
373     argv = opt_rest();
374     for ( ; *argv; argv++) {
375         if (**argv == '-') {
376             BIO_printf(bio_err, "%s: Cannot mix flags and engine names.\n",
377                        prog);
378             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
379             goto end;
380         }
381         sk_OPENSSL_STRING_push(engines, *argv);
382     }
383
384     if (sk_OPENSSL_STRING_num(engines) == 0) {
385         for (e = ENGINE_get_first(); e != NULL; e = ENGINE_get_next(e)) {
386             sk_OPENSSL_STRING_push(engines, (char *)ENGINE_get_id(e));
387         }
388     }
389
390     for (i = 0; i < sk_OPENSSL_STRING_num(engines); i++) {
391         const char *id = sk_OPENSSL_STRING_value(engines, i);
392         if ((e = ENGINE_by_id(id)) != NULL) {
393             const char *name = ENGINE_get_name(e);
394             /*
395              * Do "id" first, then "name". Easier to auto-parse.
396              */
397             BIO_printf(out, "(%s) %s\n", id, name);
398             util_do_cmds(e, pre_cmds, out, indent);
399             if (strcmp(ENGINE_get_id(e), id) != 0) {
400                 BIO_printf(out, "Loaded: (%s) %s\n",
401                            ENGINE_get_id(e), ENGINE_get_name(e));
402             }
403             if (list_cap) {
404                 int cap_size = 256;
405                 char *cap_buf = NULL;
406                 int k, n;
407                 const int *nids;
408                 ENGINE_CIPHERS_PTR fn_c;
409                 ENGINE_DIGESTS_PTR fn_d;
410                 ENGINE_PKEY_METHS_PTR fn_pk;
411
412                 if (ENGINE_get_RSA(e) != NULL
413                     && !append_buf(&cap_buf, &cap_size, "RSA"))
414                     goto end;
415                 if (ENGINE_get_DSA(e) != NULL
416                     && !append_buf(&cap_buf, &cap_size, "DSA"))
417                     goto end;
418                 if (ENGINE_get_DH(e) != NULL
419                     && !append_buf(&cap_buf, &cap_size, "DH"))
420                     goto end;
421                 if (ENGINE_get_RAND(e) != NULL
422                     && !append_buf(&cap_buf, &cap_size, "RAND"))
423                     goto end;
424
425                 fn_c = ENGINE_get_ciphers(e);
426                 if (!fn_c)
427                     goto skip_ciphers;
428                 n = fn_c(e, NULL, &nids, 0);
429                 for (k = 0; k < n; ++k)
430                     if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k])))
431                         goto end;
432
433  skip_ciphers:
434                 fn_d = ENGINE_get_digests(e);
435                 if (!fn_d)
436                     goto skip_digests;
437                 n = fn_d(e, NULL, &nids, 0);
438                 for (k = 0; k < n; ++k)
439                     if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k])))
440                         goto end;
441
442  skip_digests:
443                 fn_pk = ENGINE_get_pkey_meths(e);
444                 if (!fn_pk)
445                     goto skip_pmeths;
446                 n = fn_pk(e, NULL, &nids, 0);
447                 for (k = 0; k < n; ++k)
448                     if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k])))
449                         goto end;
450  skip_pmeths:
451                 if (cap_buf && (*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     }
475
476     ret = 0;
477  end:
478
479     ERR_print_errors(bio_err);
480     sk_OPENSSL_STRING_pop_free(engines, identity);
481     sk_OPENSSL_STRING_pop_free(pre_cmds, identity);
482     sk_OPENSSL_STRING_pop_free(post_cmds, identity);
483     BIO_free_all(out);
484     return (ret);
485 }
486 #else
487
488 # if PEDANTIC
489 static void *dummy = &dummy;
490 # endif
491
492 #endif