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