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