Check the return from OPENSSL_buf2hexstr()
[openssl.git] / apps / openssl.c
1 /*
2  * Copyright 1995-2019 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 #include <internal/cryptlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdlib.h>
14 #include <openssl/bio.h>
15 #include <openssl/crypto.h>
16 #include <openssl/trace.h>
17 #include <openssl/lhash.h>
18 #include <openssl/conf.h>
19 #include <openssl/x509.h>
20 #include <openssl/pem.h>
21 #include <openssl/ssl.h>
22 #ifndef OPENSSL_NO_ENGINE
23 # include <openssl/engine.h>
24 #endif
25 #include <openssl/err.h>
26 /* Needed to get the other O_xxx flags. */
27 #ifdef OPENSSL_SYS_VMS
28 # include <unixio.h>
29 #endif
30 #include "apps.h"
31 #include "progs.h"
32
33 /* Special sentinel to exit the program. */
34 #define EXIT_THE_PROGRAM (-1)
35
36 /*
37  * The LHASH callbacks ("hash" & "cmp") have been replaced by functions with
38  * the base prototypes (we cast each variable inside the function to the
39  * required type of "FUNCTION*"). This removes the necessity for
40  * macro-generated wrapper functions.
41  */
42 static LHASH_OF(FUNCTION) *prog_init(void);
43 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]);
44 char *default_config_file = NULL;
45
46 BIO *bio_in = NULL;
47 BIO *bio_out = NULL;
48 BIO *bio_err = NULL;
49
50 static int apps_startup(void)
51 {
52 #ifdef SIGPIPE
53     signal(SIGPIPE, SIG_IGN);
54 #endif
55
56     /* Set non-default library initialisation settings */
57     if (!OPENSSL_init_ssl(OPENSSL_INIT_ENGINE_ALL_BUILTIN
58                           | OPENSSL_INIT_LOAD_CONFIG, NULL))
59         return 0;
60
61     setup_ui_method();
62
63     return 1;
64 }
65
66 static void apps_shutdown(void)
67 {
68     destroy_ui_method();
69 }
70
71 static char *make_config_name(void)
72 {
73     const char *t;
74     size_t len;
75     char *p;
76
77     if ((t = getenv("OPENSSL_CONF")) != NULL)
78         return OPENSSL_strdup(t);
79
80     t = X509_get_default_cert_area();
81     len = strlen(t) + 1 + strlen(OPENSSL_CONF) + 1;
82     p = app_malloc(len, "config filename buffer");
83     strcpy(p, t);
84 #ifndef OPENSSL_SYS_VMS
85     strcat(p, "/");
86 #endif
87     strcat(p, OPENSSL_CONF);
88
89     return p;
90 }
91
92
93 #ifndef OPENSSL_NO_TRACE
94 typedef struct tracedata_st {
95     BIO *bio;
96     unsigned int ingroup:1;
97 } tracedata;
98
99 static size_t internal_trace_cb(const char *buf, size_t cnt,
100                                 int category, int cmd, void *vdata)
101 {
102     int ret = 0;
103     tracedata *trace_data = vdata;
104     char buffer[256], *hex;
105     CRYPTO_THREAD_ID tid;
106
107     switch (cmd) {
108     case OSSL_TRACE_CTRL_BEGIN:
109         if (!ossl_assert(!trace_data->ingroup))
110             return 0;
111         trace_data->ingroup = 1;
112
113         tid = CRYPTO_THREAD_get_current_id();
114         hex = OPENSSL_buf2hexstr((const unsigned char *)&tid, sizeof(tid));
115         BIO_snprintf(buffer, sizeof(buffer), "TRACE[%s]:%s: ",
116                      hex == NULL ? "<null>" : hex,
117                      OSSL_trace_get_category_name(category));
118         OPENSSL_free(hex);
119         BIO_ctrl(trace_data->bio, PREFIX_CTRL_SET_PREFIX,
120                  strlen(buffer), buffer);
121         break;
122     case OSSL_TRACE_CTRL_WRITE:
123         if (!ossl_assert(trace_data->ingroup))
124             return 0;
125
126         ret = BIO_write(trace_data->bio, buf, cnt);
127         break;
128     case OSSL_TRACE_CTRL_END:
129         if (!ossl_assert(trace_data->ingroup))
130             return 0;
131         trace_data->ingroup = 0;
132
133         BIO_ctrl(trace_data->bio, PREFIX_CTRL_SET_PREFIX, 0, NULL);
134
135         break;
136     }
137
138     return ret < 0 ? 0 : ret;
139 }
140
141 DEFINE_STACK_OF(tracedata)
142 static STACK_OF(tracedata) *trace_data_stack;
143
144 static void tracedata_free(tracedata *data)
145 {
146     BIO_free_all(data->bio);
147     OPENSSL_free(data);
148 }
149
150 static STACK_OF(tracedata) *trace_data_stack;
151
152 static void cleanup_trace(void)
153 {
154     sk_tracedata_pop_free(trace_data_stack, tracedata_free);
155 }
156
157 static void setup_trace_category(int category)
158 {
159     BIO *channel;
160     tracedata *trace_data;
161
162     if (OSSL_trace_enabled(category))
163         return;
164
165     channel = BIO_push(BIO_new(apps_bf_prefix()),
166                        dup_bio_err(FORMAT_TEXT));
167     trace_data = OPENSSL_zalloc(sizeof(*trace_data));
168
169     if (trace_data == NULL
170         || (trace_data->bio = channel) == NULL
171         || OSSL_trace_set_callback(category, internal_trace_cb,
172                                    trace_data) == 0
173         || sk_tracedata_push(trace_data_stack, trace_data) == 0) {
174
175         fprintf(stderr,
176                 "warning: unable to setup trace callback for category '%s'.\n",
177                 OSSL_trace_get_category_name(category));
178
179         OSSL_trace_set_callback(category, NULL, NULL);
180         BIO_free_all(channel);
181     }
182 }
183
184 static void setup_trace(const char *str)
185 {
186     char *val;
187
188     /*
189      * We add this handler as early as possible to ensure it's executed
190      * as late as possible, i.e. after the TRACE code has done its cleanup
191      * (which happens last in OPENSSL_cleanup).
192      */
193     atexit(cleanup_trace);
194
195     trace_data_stack = sk_tracedata_new_null();
196     val = OPENSSL_strdup(str);
197
198     if (val != NULL) {
199         char *valp = val;
200         char *item;
201
202         for (valp = val; (item = strtok(valp, ",")) != NULL; valp = NULL) {
203             int category = OSSL_trace_get_category_num(item);
204
205             if (category == OSSL_TRACE_CATEGORY_ALL) {
206                 while (++category < OSSL_TRACE_CATEGORY_NUM)
207                     setup_trace_category(category);
208                 break;
209             } else if (category > 0) {
210                 setup_trace_category(category);
211             } else {
212                 fprintf(stderr,
213                         "warning: unknown trace category: '%s'.\n", item);
214             }
215         }
216     }
217
218     OPENSSL_free(val);
219 }
220 #endif /* OPENSSL_NO_TRACE */
221
222 int main(int argc, char *argv[])
223 {
224     FUNCTION f, *fp;
225     LHASH_OF(FUNCTION) *prog = NULL;
226     char *p, *pname;
227     char buf[1024];
228     const char *prompt;
229     ARGS arg;
230     int first, n, i, ret = 0;
231
232     arg.argv = NULL;
233     arg.size = 0;
234
235     /* Set up some of the environment. */
236     default_config_file = make_config_name();
237     bio_in = dup_bio_in(FORMAT_TEXT);
238     bio_out = dup_bio_out(FORMAT_TEXT);
239     bio_err = dup_bio_err(FORMAT_TEXT);
240
241 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
242     argv = copy_argv(&argc, argv);
243 #elif defined(_WIN32)
244     /*
245      * Replace argv[] with UTF-8 encoded strings.
246      */
247     win32_utf8argv(&argc, &argv);
248 #endif
249
250     /*
251      * We use the prefix method to get the trace output we want.  Since some
252      * trace outputs happen with OPENSSL_cleanup(), which is run automatically
253      * after exit(), we need to destroy the prefix method as late as possible.
254      */
255     atexit(destroy_prefix_method);
256
257 #ifndef OPENSSL_NO_TRACE
258     setup_trace(getenv("OPENSSL_TRACE"));
259 #endif
260
261     p = getenv("OPENSSL_DEBUG_MEMORY");
262     if (p != NULL && strcmp(p, "on") == 0)
263         CRYPTO_set_mem_debug(1);
264     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
265
266     if (getenv("OPENSSL_FIPS")) {
267         BIO_printf(bio_err, "FIPS mode not supported.\n");
268         return 1;
269     }
270
271     if (!apps_startup()) {
272         BIO_printf(bio_err,
273                    "FATAL: Startup failure (dev note: apps_startup() failed)\n");
274         ERR_print_errors(bio_err);
275         ret = 1;
276         goto end;
277     }
278
279     prog = prog_init();
280     if (prog == NULL) {
281         BIO_printf(bio_err,
282                    "FATAL: Startup failure (dev note: prog_init() failed)\n");
283         ERR_print_errors(bio_err);
284         ret = 1;
285         goto end;
286     }
287     pname = opt_progname(argv[0]);
288
289     /* first check the program name */
290     f.name = pname;
291     fp = lh_FUNCTION_retrieve(prog, &f);
292     if (fp != NULL) {
293         argv[0] = pname;
294         ret = fp->func(argc, argv);
295         goto end;
296     }
297
298     /* If there is stuff on the command line, run with that. */
299     if (argc != 1) {
300         argc--;
301         argv++;
302         ret = do_cmd(prog, argc, argv);
303         if (ret < 0)
304             ret = 0;
305         goto end;
306     }
307
308     /* ok, lets enter interactive mode */
309     for (;;) {
310         ret = 0;
311         /* Read a line, continue reading if line ends with \ */
312         for (p = buf, n = sizeof(buf), i = 0, first = 1; n > 0; first = 0) {
313             prompt = first ? "OpenSSL> " : "> ";
314             p[0] = '\0';
315 #ifndef READLINE
316             fputs(prompt, stdout);
317             fflush(stdout);
318             if (!fgets(p, n, stdin))
319                 goto end;
320             if (p[0] == '\0')
321                 goto end;
322             i = strlen(p);
323             if (i <= 1)
324                 break;
325             if (p[i - 2] != '\\')
326                 break;
327             i -= 2;
328             p += i;
329             n -= i;
330 #else
331             {
332                 extern char *readline(const char *);
333                 extern void add_history(const char *cp);
334                 char *text;
335
336                 text = readline(prompt);
337                 if (text == NULL)
338                     goto end;
339                 i = strlen(text);
340                 if (i == 0 || i > n)
341                     break;
342                 if (text[i - 1] != '\\') {
343                     p += strlen(strcpy(p, text));
344                     free(text);
345                     add_history(buf);
346                     break;
347                 }
348
349                 text[i - 1] = '\0';
350                 p += strlen(strcpy(p, text));
351                 free(text);
352                 n -= i;
353             }
354 #endif
355         }
356
357         if (!chopup_args(&arg, buf)) {
358             BIO_printf(bio_err, "Can't parse (no memory?)\n");
359             break;
360         }
361
362         ret = do_cmd(prog, arg.argc, arg.argv);
363         if (ret == EXIT_THE_PROGRAM) {
364             ret = 0;
365             goto end;
366         }
367         if (ret != 0)
368             BIO_printf(bio_err, "error in %s\n", arg.argv[0]);
369         (void)BIO_flush(bio_out);
370         (void)BIO_flush(bio_err);
371     }
372     ret = 1;
373  end:
374     OPENSSL_free(default_config_file);
375     lh_FUNCTION_free(prog);
376     OPENSSL_free(arg.argv);
377     app_RAND_write();
378
379     BIO_free(bio_in);
380     BIO_free_all(bio_out);
381     apps_shutdown();
382 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
383     if (CRYPTO_mem_leaks(bio_err) <= 0)
384         ret = 1;
385 #endif
386     BIO_free(bio_err);
387     EXIT(ret);
388 }
389
390 typedef enum HELP_CHOICE {
391     OPT_hERR = -1, OPT_hEOF = 0, OPT_hHELP
392 } HELP_CHOICE;
393
394 const OPTIONS help_options[] = {
395     {OPT_HELP_STR, 1, '-', "Usage: help [options] [command]\n"},
396
397     OPT_SECTION("General"),
398     {"help", OPT_hHELP, '-', "Display this summary"},
399
400     OPT_PARAMETERS(),
401     {"command", 0, 0, "Name of command to display help (optional)"},
402     {NULL}
403 };
404
405
406 int help_main(int argc, char **argv)
407 {
408     FUNCTION *fp;
409     int i, nl;
410     FUNC_TYPE tp;
411     char *prog;
412     HELP_CHOICE o;
413     DISPLAY_COLUMNS dc;
414
415     prog = opt_init(argc, argv, help_options);
416     while ((o = opt_next()) != OPT_hEOF) {
417         switch (o) {
418         case OPT_hERR:
419         case OPT_hEOF:
420             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
421             return 1;
422         case OPT_hHELP:
423             opt_help(help_options);
424             return 0;
425         }
426     }
427
428     if (opt_num_rest() == 1) {
429         char *new_argv[3];
430
431         new_argv[0] = opt_rest()[0];
432         new_argv[1] = "--help";
433         new_argv[2] = NULL;
434         return do_cmd(prog_init(), 2, new_argv);
435     }
436     if (opt_num_rest() != 0) {
437         BIO_printf(bio_err, "Usage: %s\n", prog);
438         return 1;
439     }
440
441     calculate_columns(functions, &dc);
442     BIO_printf(bio_err, "Standard commands");
443     i = 0;
444     tp = FT_none;
445     for (fp = functions; fp->name != NULL; fp++) {
446         nl = 0;
447         if (i++ % dc.columns == 0) {
448             BIO_printf(bio_err, "\n");
449             nl = 1;
450         }
451         if (fp->type != tp) {
452             tp = fp->type;
453             if (!nl)
454                 BIO_printf(bio_err, "\n");
455             if (tp == FT_md) {
456                 i = 1;
457                 BIO_printf(bio_err,
458                            "\nMessage Digest commands (see the `dgst' command for more details)\n");
459             } else if (tp == FT_cipher) {
460                 i = 1;
461                 BIO_printf(bio_err,
462                            "\nCipher commands (see the `enc' command for more details)\n");
463             }
464         }
465         BIO_printf(bio_err, "%-*s", dc.width, fp->name);
466     }
467     BIO_printf(bio_err, "\n\n");
468     return 0;
469 }
470
471 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[])
472 {
473     FUNCTION f, *fp;
474
475     if (argc <= 0 || argv[0] == NULL)
476         return 0;
477     f.name = argv[0];
478     fp = lh_FUNCTION_retrieve(prog, &f);
479     if (fp == NULL) {
480         if (EVP_get_digestbyname(argv[0])) {
481             f.type = FT_md;
482             f.func = dgst_main;
483             fp = &f;
484         } else if (EVP_get_cipherbyname(argv[0])) {
485             f.type = FT_cipher;
486             f.func = enc_main;
487             fp = &f;
488         }
489     }
490     if (fp != NULL) {
491         return fp->func(argc, argv);
492     }
493     if ((strncmp(argv[0], "no-", 3)) == 0) {
494         /*
495          * User is asking if foo is unsupported, by trying to "run" the
496          * no-foo command.  Strange.
497          */
498         f.name = argv[0] + 3;
499         if (lh_FUNCTION_retrieve(prog, &f) == NULL) {
500             BIO_printf(bio_out, "%s\n", argv[0]);
501             return 0;
502         }
503         BIO_printf(bio_out, "%s\n", argv[0] + 3);
504         return 1;
505     }
506     if (strcmp(argv[0], "quit") == 0 || strcmp(argv[0], "q") == 0 ||
507         strcmp(argv[0], "exit") == 0 || strcmp(argv[0], "bye") == 0)
508         /* Special value to mean "exit the program. */
509         return EXIT_THE_PROGRAM;
510
511     BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n",
512                argv[0]);
513     return 1;
514 }
515
516 static int function_cmp(const FUNCTION * a, const FUNCTION * b)
517 {
518     return strncmp(a->name, b->name, 8);
519 }
520
521 static unsigned long function_hash(const FUNCTION * a)
522 {
523     return OPENSSL_LH_strhash(a->name);
524 }
525
526 static int SortFnByName(const void *_f1, const void *_f2)
527 {
528     const FUNCTION *f1 = _f1;
529     const FUNCTION *f2 = _f2;
530
531     if (f1->type != f2->type)
532         return f1->type - f2->type;
533     return strcmp(f1->name, f2->name);
534 }
535
536 static LHASH_OF(FUNCTION) *prog_init(void)
537 {
538     static LHASH_OF(FUNCTION) *ret = NULL;
539     static int prog_inited = 0;
540     FUNCTION *f;
541     size_t i;
542
543     if (prog_inited)
544         return ret;
545
546     prog_inited = 1;
547
548     /* Sort alphabetically within category. For nicer help displays. */
549     for (i = 0, f = functions; f->name != NULL; ++f, ++i)
550         ;
551     qsort(functions, i, sizeof(*functions), SortFnByName);
552
553     if ((ret = lh_FUNCTION_new(function_hash, function_cmp)) == NULL)
554         return NULL;
555
556     for (f = functions; f->name != NULL; f++)
557         (void)lh_FUNCTION_insert(ret, f);
558     return ret;
559 }