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