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