307303b25700ede67a0aa81f7d54810f3d778f77
[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 <stdio.h>
11 #include <string.h>
12 #include <stdlib.h>
13 #include <openssl/bio.h>
14 #include <openssl/crypto.h>
15 #include <openssl/trace.h>
16 #include <openssl/lhash.h>
17 #include <openssl/conf.h>
18 #include <openssl/x509.h>
19 #include <openssl/pem.h>
20 #include <openssl/ssl.h>
21 #ifndef OPENSSL_NO_ENGINE
22 # include <openssl/engine.h>
23 #endif
24 #include <openssl/err.h>
25 /* Needed to get the other O_xxx flags. */
26 #ifdef OPENSSL_SYS_VMS
27 # include <unixio.h>
28 #endif
29 #include "apps.h"
30 #include "progs.h"
31
32 /*
33  * The LHASH callbacks ("hash" & "cmp") have been replaced by functions with
34  * the base prototypes (we cast each variable inside the function to the
35  * required type of "FUNCTION*"). This removes the necessity for
36  * macro-generated wrapper functions.
37  */
38 static LHASH_OF(FUNCTION) *prog_init(void);
39 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]);
40 char *default_config_file = NULL;
41
42 BIO *bio_in = NULL;
43 BIO *bio_out = NULL;
44 BIO *bio_err = NULL;
45
46 static void warn_deprecated(const FUNCTION *fp)
47 {
48     if (fp->deprecated_version != NULL)
49         BIO_printf(bio_err, "The command %s was deprecated in version %s.",
50                    fp->name, fp->deprecated_version);
51     else
52         BIO_printf(bio_err, "The command %s is deprecated.", fp->name);
53     if (strcmp(fp->deprecated_alternative, DEPRECATED_NO_ALTERNATIVE) != 0)
54         BIO_printf(bio_err, " Use '%s' instead.", fp->deprecated_alternative);
55     BIO_printf(bio_err, "\n");
56 }
57
58 static int apps_startup(void)
59 {
60     const char *use_libctx = NULL;
61 #ifdef SIGPIPE
62     signal(SIGPIPE, SIG_IGN);
63 #endif
64
65     /* Set non-default library initialisation settings */
66     if (!OPENSSL_init_ssl(OPENSSL_INIT_ENGINE_ALL_BUILTIN
67                           | OPENSSL_INIT_LOAD_CONFIG, NULL))
68         return 0;
69
70     (void)setup_ui_method();
71
72     /*
73      * NOTE: This is an undocumented feature required for testing only.
74      * There are no guarantees that it will exist in future builds.
75      */
76     use_libctx = getenv("OPENSSL_TEST_LIBCTX");
77     if (use_libctx != NULL) {
78         /* Set this to "1" to create a global libctx */
79         if (strcmp(use_libctx, "1") == 0) {
80             if (app_create_libctx() == NULL)
81                 return 0;
82         }
83     }
84
85     return 1;
86 }
87
88 static void apps_shutdown(void)
89 {
90     app_providers_cleanup();
91     OSSL_LIB_CTX_free(app_get0_libctx());
92     destroy_ui_method();
93 }
94
95
96 #ifndef OPENSSL_NO_TRACE
97 typedef struct tracedata_st {
98     BIO *bio;
99     unsigned int ingroup:1;
100 } tracedata;
101
102 static size_t internal_trace_cb(const char *buf, size_t cnt,
103                                 int category, int cmd, void *vdata)
104 {
105     int ret = 0;
106     tracedata *trace_data = vdata;
107     char buffer[256], *hex;
108     CRYPTO_THREAD_ID tid;
109
110     switch (cmd) {
111     case OSSL_TRACE_CTRL_BEGIN:
112         if (trace_data->ingroup) {
113             BIO_printf(bio_err, "ERROR: tracing already started\n");
114             return 0;
115         }
116         trace_data->ingroup = 1;
117
118         tid = CRYPTO_THREAD_get_current_id();
119         hex = OPENSSL_buf2hexstr((const unsigned char *)&tid, sizeof(tid));
120         BIO_snprintf(buffer, sizeof(buffer), "TRACE[%s]:%s: ",
121                      hex == NULL ? "<null>" : hex,
122                      OSSL_trace_get_category_name(category));
123         OPENSSL_free(hex);
124         BIO_set_prefix(trace_data->bio, buffer);
125         break;
126     case OSSL_TRACE_CTRL_WRITE:
127         if (!trace_data->ingroup) {
128             BIO_printf(bio_err, "ERROR: writing when tracing not started\n");
129             return 0;
130         }
131
132         ret = BIO_write(trace_data->bio, buf, cnt);
133         break;
134     case OSSL_TRACE_CTRL_END:
135         if (!trace_data->ingroup) {
136             BIO_printf(bio_err, "ERROR: finishing when tracing not started\n");
137             return 0;
138         }
139         trace_data->ingroup = 0;
140
141         BIO_set_prefix(trace_data->bio, NULL);
142
143         break;
144     }
145
146     return ret < 0 ? 0 : ret;
147 }
148
149 DEFINE_STACK_OF(tracedata)
150 static STACK_OF(tracedata) *trace_data_stack;
151
152 static void tracedata_free(tracedata *data)
153 {
154     BIO_free_all(data->bio);
155     OPENSSL_free(data);
156 }
157
158 static STACK_OF(tracedata) *trace_data_stack;
159
160 static void cleanup_trace(void)
161 {
162     sk_tracedata_pop_free(trace_data_stack, tracedata_free);
163 }
164
165 static void setup_trace_category(int category)
166 {
167     BIO *channel;
168     tracedata *trace_data;
169
170     if (OSSL_trace_enabled(category))
171         return;
172
173     channel = BIO_push(BIO_new(BIO_f_prefix()), dup_bio_err(FORMAT_TEXT));
174     trace_data = OPENSSL_zalloc(sizeof(*trace_data));
175
176     if (trace_data == NULL
177         || (trace_data->bio = channel) == NULL
178         || OSSL_trace_set_callback(category, internal_trace_cb,
179                                    trace_data) == 0
180         || sk_tracedata_push(trace_data_stack, trace_data) == 0) {
181
182         fprintf(stderr,
183                 "warning: unable to setup trace callback for category '%s'.\n",
184                 OSSL_trace_get_category_name(category));
185
186         OSSL_trace_set_callback(category, NULL, NULL);
187         BIO_free_all(channel);
188     }
189 }
190
191 static void setup_trace(const char *str)
192 {
193     char *val;
194
195     /*
196      * We add this handler as early as possible to ensure it's executed
197      * as late as possible, i.e. after the TRACE code has done its cleanup
198      * (which happens last in OPENSSL_cleanup).
199      */
200     atexit(cleanup_trace);
201
202     trace_data_stack = sk_tracedata_new_null();
203     val = OPENSSL_strdup(str);
204
205     if (val != NULL) {
206         char *valp = val;
207         char *item;
208
209         for (valp = val; (item = strtok(valp, ",")) != NULL; valp = NULL) {
210             int category = OSSL_trace_get_category_num(item);
211
212             if (category == OSSL_TRACE_CATEGORY_ALL) {
213                 while (++category < OSSL_TRACE_CATEGORY_NUM)
214                     setup_trace_category(category);
215                 break;
216             } else if (category > 0) {
217                 setup_trace_category(category);
218             } else {
219                 fprintf(stderr,
220                         "warning: unknown trace category: '%s'.\n", item);
221             }
222         }
223     }
224
225     OPENSSL_free(val);
226 }
227 #endif /* OPENSSL_NO_TRACE */
228
229 static char *help_argv[] = { "help", NULL };
230
231 int main(int argc, char *argv[])
232 {
233     FUNCTION f, *fp;
234     LHASH_OF(FUNCTION) *prog = NULL;
235     char *pname;
236     ARGS arg;
237     int ret = 0;
238
239     arg.argv = NULL;
240     arg.size = 0;
241
242     /* Set up some of the environment. */
243     bio_in = dup_bio_in(FORMAT_TEXT);
244     bio_out = dup_bio_out(FORMAT_TEXT);
245     bio_err = dup_bio_err(FORMAT_TEXT);
246
247 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
248     argv = copy_argv(&argc, argv);
249 #elif defined(_WIN32)
250     /*
251      * Replace argv[] with UTF-8 encoded strings.
252      */
253     win32_utf8argv(&argc, &argv);
254 #endif
255
256 #ifndef OPENSSL_NO_TRACE
257     setup_trace(getenv("OPENSSL_TRACE"));
258 #endif
259
260     if (!apps_startup()) {
261         BIO_printf(bio_err,
262                    "FATAL: Startup failure (dev note: apps_startup() failed)\n");
263         ERR_print_errors(bio_err);
264         ret = 1;
265         goto end;
266     }
267
268     prog = prog_init();
269     if (prog == NULL) {
270         BIO_printf(bio_err,
271                    "FATAL: Startup failure (dev note: prog_init() failed)\n");
272         ERR_print_errors(bio_err);
273         ret = 1;
274         goto end;
275     }
276     pname = opt_progname(argv[0]);
277
278     default_config_file = CONF_get1_default_config_file();
279     if (default_config_file == NULL)
280         app_bail_out("%s: could not get default config file\n", pname);
281
282     /* first check the program name */
283     f.name = pname;
284     fp = lh_FUNCTION_retrieve(prog, &f);
285     if (fp == NULL) {
286         /* We assume we've been called as 'openssl cmd' */
287         argc--;
288         argv++;
289     }
290
291     /* If there's a command, run with that, otherwise "help". */
292     ret = argc > 0
293         ? do_cmd(prog, argc, argv)
294         : do_cmd(prog, 1, help_argv);
295
296  end:
297     OPENSSL_free(default_config_file);
298     lh_FUNCTION_free(prog);
299     OPENSSL_free(arg.argv);
300     app_RAND_write();
301
302     BIO_free(bio_in);
303     BIO_free_all(bio_out);
304     apps_shutdown();
305     BIO_free(bio_err);
306     EXIT(ret);
307 }
308
309 typedef enum HELP_CHOICE {
310     OPT_hERR = -1, OPT_hEOF = 0, OPT_hHELP
311 } HELP_CHOICE;
312
313 const OPTIONS help_options[] = {
314     {OPT_HELP_STR, 1, '-', "Usage: help [options] [command]\n"},
315
316     OPT_SECTION("General"),
317     {"help", OPT_hHELP, '-', "Display this summary"},
318
319     OPT_PARAMETERS(),
320     {"command", 0, 0, "Name of command to display help (optional)"},
321     {NULL}
322 };
323
324
325 int help_main(int argc, char **argv)
326 {
327     FUNCTION *fp;
328     int i, nl;
329     FUNC_TYPE tp;
330     char *prog;
331     HELP_CHOICE o;
332     DISPLAY_COLUMNS dc;
333     char *new_argv[3];
334
335     prog = opt_init(argc, argv, help_options);
336     while ((o = opt_next()) != OPT_hEOF) {
337         switch (o) {
338         case OPT_hERR:
339         case OPT_hEOF:
340             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
341             return 1;
342         case OPT_hHELP:
343             opt_help(help_options);
344             return 0;
345         }
346     }
347
348     if (opt_num_rest() == 1) {
349         new_argv[0] = opt_rest()[0];
350         new_argv[1] = "--help";
351         new_argv[2] = NULL;
352         return do_cmd(prog_init(), 2, new_argv);
353     }
354     if (opt_num_rest() != 0) {
355         BIO_printf(bio_err, "Usage: %s\n", prog);
356         return 1;
357     }
358
359     calculate_columns(functions, &dc);
360     BIO_printf(bio_err, "Standard commands");
361     i = 0;
362     tp = FT_none;
363     for (fp = functions; fp->name != NULL; fp++) {
364         nl = 0;
365         if (i++ % dc.columns == 0) {
366             BIO_printf(bio_err, "\n");
367             nl = 1;
368         }
369         if (fp->type != tp) {
370             tp = fp->type;
371             if (!nl)
372                 BIO_printf(bio_err, "\n");
373             if (tp == FT_md) {
374                 i = 1;
375                 BIO_printf(bio_err,
376                            "\nMessage Digest commands (see the `dgst' command for more details)\n");
377             } else if (tp == FT_cipher) {
378                 i = 1;
379                 BIO_printf(bio_err,
380                            "\nCipher commands (see the `enc' command for more details)\n");
381             }
382         }
383         BIO_printf(bio_err, "%-*s", dc.width, fp->name);
384     }
385     BIO_printf(bio_err, "\n\n");
386     return 0;
387 }
388
389 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[])
390 {
391     FUNCTION f, *fp;
392
393     if (argc <= 0 || argv[0] == NULL)
394         return 0;
395     f.name = argv[0];
396     fp = lh_FUNCTION_retrieve(prog, &f);
397     if (fp == NULL) {
398         if (EVP_get_digestbyname(argv[0])) {
399             f.type = FT_md;
400             f.func = dgst_main;
401             fp = &f;
402         } else if (EVP_get_cipherbyname(argv[0])) {
403             f.type = FT_cipher;
404             f.func = enc_main;
405             fp = &f;
406         }
407     }
408     if (fp != NULL) {
409         if (fp->deprecated_alternative != NULL)
410             warn_deprecated(fp);
411         return fp->func(argc, argv);
412     }
413     if ((strncmp(argv[0], "no-", 3)) == 0) {
414         /*
415          * User is asking if foo is unsupported, by trying to "run" the
416          * no-foo command.  Strange.
417          */
418         f.name = argv[0] + 3;
419         if (lh_FUNCTION_retrieve(prog, &f) == NULL) {
420             BIO_printf(bio_out, "%s\n", argv[0]);
421             return 0;
422         }
423         BIO_printf(bio_out, "%s\n", argv[0] + 3);
424         return 1;
425     }
426
427     BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n",
428                argv[0]);
429     return 1;
430 }
431
432 static int function_cmp(const FUNCTION * a, const FUNCTION * b)
433 {
434     return strncmp(a->name, b->name, 8);
435 }
436
437 static unsigned long function_hash(const FUNCTION * a)
438 {
439     return OPENSSL_LH_strhash(a->name);
440 }
441
442 static int SortFnByName(const void *_f1, const void *_f2)
443 {
444     const FUNCTION *f1 = _f1;
445     const FUNCTION *f2 = _f2;
446
447     if (f1->type != f2->type)
448         return f1->type - f2->type;
449     return strcmp(f1->name, f2->name);
450 }
451
452 static LHASH_OF(FUNCTION) *prog_init(void)
453 {
454     static LHASH_OF(FUNCTION) *ret = NULL;
455     static int prog_inited = 0;
456     FUNCTION *f;
457     size_t i;
458
459     if (prog_inited)
460         return ret;
461
462     prog_inited = 1;
463
464     /* Sort alphabetically within category. For nicer help displays. */
465     for (i = 0, f = functions; f->name != NULL; ++f, ++i)
466         ;
467     qsort(functions, i, sizeof(*functions), SortFnByName);
468
469     if ((ret = lh_FUNCTION_new(function_hash, function_cmp)) == NULL)
470         return NULL;
471
472     for (f = functions; f->name != NULL; f++)
473         (void)lh_FUNCTION_insert(ret, f);
474     return ret;
475 }