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