e3197daab92ff0c7c5af3bec0cd9c35ed9f3f9b2
[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 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 static char *make_config_name(void)
84 {
85     const char *t;
86     size_t len;
87     char *p;
88
89     if ((t = getenv("OPENSSL_CONF")) != NULL)
90         return OPENSSL_strdup(t);
91
92     t = X509_get_default_cert_area();
93     len = strlen(t) + 1 + strlen(OPENSSL_CONF) + 1;
94     p = app_malloc(len, "config filename buffer");
95     strcpy(p, t);
96 #ifndef OPENSSL_SYS_VMS
97     strcat(p, "/");
98 #endif
99     strcat(p, OPENSSL_CONF);
100
101     return p;
102 }
103
104
105 #ifndef OPENSSL_NO_TRACE
106 typedef struct tracedata_st {
107     BIO *bio;
108     unsigned int ingroup:1;
109 } tracedata;
110
111 static size_t internal_trace_cb(const char *buf, size_t cnt,
112                                 int category, int cmd, void *vdata)
113 {
114     int ret = 0;
115     tracedata *trace_data = vdata;
116     char buffer[256], *hex;
117     CRYPTO_THREAD_ID tid;
118
119     switch (cmd) {
120     case OSSL_TRACE_CTRL_BEGIN:
121         if (!ossl_assert(!trace_data->ingroup))
122             return 0;
123         trace_data->ingroup = 1;
124
125         tid = CRYPTO_THREAD_get_current_id();
126         hex = OPENSSL_buf2hexstr((const unsigned char *)&tid, sizeof(tid));
127         BIO_snprintf(buffer, sizeof(buffer), "TRACE[%s]:%s: ",
128                      hex == NULL ? "<null>" : hex,
129                      OSSL_trace_get_category_name(category));
130         OPENSSL_free(hex);
131         BIO_set_prefix(trace_data->bio, buffer);
132         break;
133     case OSSL_TRACE_CTRL_WRITE:
134         if (!ossl_assert(trace_data->ingroup))
135             return 0;
136
137         ret = BIO_write(trace_data->bio, buf, cnt);
138         break;
139     case OSSL_TRACE_CTRL_END:
140         if (!ossl_assert(trace_data->ingroup))
141             return 0;
142         trace_data->ingroup = 0;
143
144         BIO_set_prefix(trace_data->bio, NULL);
145
146         break;
147     }
148
149     return ret < 0 ? 0 : ret;
150 }
151
152 DEFINE_STACK_OF(tracedata)
153 static STACK_OF(tracedata) *trace_data_stack;
154
155 static void tracedata_free(tracedata *data)
156 {
157     BIO_free_all(data->bio);
158     OPENSSL_free(data);
159 }
160
161 static STACK_OF(tracedata) *trace_data_stack;
162
163 static void cleanup_trace(void)
164 {
165     sk_tracedata_pop_free(trace_data_stack, tracedata_free);
166 }
167
168 static void setup_trace_category(int category)
169 {
170     BIO *channel;
171     tracedata *trace_data;
172
173     if (OSSL_trace_enabled(category))
174         return;
175
176     channel = BIO_push(BIO_new(BIO_f_prefix()), dup_bio_err(FORMAT_TEXT));
177     trace_data = OPENSSL_zalloc(sizeof(*trace_data));
178
179     if (trace_data == NULL
180         || (trace_data->bio = channel) == NULL
181         || OSSL_trace_set_callback(category, internal_trace_cb,
182                                    trace_data) == 0
183         || sk_tracedata_push(trace_data_stack, trace_data) == 0) {
184
185         fprintf(stderr,
186                 "warning: unable to setup trace callback for category '%s'.\n",
187                 OSSL_trace_get_category_name(category));
188
189         OSSL_trace_set_callback(category, NULL, NULL);
190         BIO_free_all(channel);
191     }
192 }
193
194 static void setup_trace(const char *str)
195 {
196     char *val;
197
198     /*
199      * We add this handler as early as possible to ensure it's executed
200      * as late as possible, i.e. after the TRACE code has done its cleanup
201      * (which happens last in OPENSSL_cleanup).
202      */
203     atexit(cleanup_trace);
204
205     trace_data_stack = sk_tracedata_new_null();
206     val = OPENSSL_strdup(str);
207
208     if (val != NULL) {
209         char *valp = val;
210         char *item;
211
212         for (valp = val; (item = strtok(valp, ",")) != NULL; valp = NULL) {
213             int category = OSSL_trace_get_category_num(item);
214
215             if (category == OSSL_TRACE_CATEGORY_ALL) {
216                 while (++category < OSSL_TRACE_CATEGORY_NUM)
217                     setup_trace_category(category);
218                 break;
219             } else if (category > 0) {
220                 setup_trace_category(category);
221             } else {
222                 fprintf(stderr,
223                         "warning: unknown trace category: '%s'.\n", item);
224             }
225         }
226     }
227
228     OPENSSL_free(val);
229 }
230 #endif /* OPENSSL_NO_TRACE */
231
232 int main(int argc, char *argv[])
233 {
234     FUNCTION f, *fp;
235     LHASH_OF(FUNCTION) *prog = NULL;
236     char *p, *pname;
237     char buf[1024];
238     const char *prompt;
239     ARGS arg;
240     int first, n, i, ret = 0;
241
242     arg.argv = NULL;
243     arg.size = 0;
244
245     /* Set up some of the environment. */
246     default_config_file = make_config_name();
247     bio_in = dup_bio_in(FORMAT_TEXT);
248     bio_out = dup_bio_out(FORMAT_TEXT);
249     bio_err = dup_bio_err(FORMAT_TEXT);
250
251 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
252     argv = copy_argv(&argc, argv);
253 #elif defined(_WIN32)
254     /*
255      * Replace argv[] with UTF-8 encoded strings.
256      */
257     win32_utf8argv(&argc, &argv);
258 #endif
259
260 #ifndef OPENSSL_NO_TRACE
261     setup_trace(getenv("OPENSSL_TRACE"));
262 #endif
263
264     if (getenv("OPENSSL_FIPS")) {
265         BIO_printf(bio_err, "FIPS mode not supported.\n");
266         return 1;
267     }
268
269     if (!apps_startup()) {
270         BIO_printf(bio_err,
271                    "FATAL: Startup failure (dev note: apps_startup() failed)\n");
272         ERR_print_errors(bio_err);
273         ret = 1;
274         goto end;
275     }
276
277     prog = prog_init();
278     if (prog == NULL) {
279         BIO_printf(bio_err,
280                    "FATAL: Startup failure (dev note: prog_init() failed)\n");
281         ERR_print_errors(bio_err);
282         ret = 1;
283         goto end;
284     }
285     pname = opt_progname(argv[0]);
286
287     /* first check the program name */
288     f.name = pname;
289     fp = lh_FUNCTION_retrieve(prog, &f);
290     if (fp != NULL) {
291         argv[0] = pname;
292         if (fp->deprecated_alternative != NULL)
293             warn_deprecated(fp);
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     app_providers_cleanup();
375     OPENSSL_free(default_config_file);
376     lh_FUNCTION_free(prog);
377     OPENSSL_free(arg.argv);
378     app_RAND_write();
379
380     BIO_free(bio_in);
381     BIO_free_all(bio_out);
382     apps_shutdown();
383     BIO_free(bio_err);
384     EXIT(ret);
385 }
386
387 typedef enum HELP_CHOICE {
388     OPT_hERR = -1, OPT_hEOF = 0, OPT_hHELP
389 } HELP_CHOICE;
390
391 const OPTIONS help_options[] = {
392     {OPT_HELP_STR, 1, '-', "Usage: help [options] [command]\n"},
393
394     OPT_SECTION("General"),
395     {"help", OPT_hHELP, '-', "Display this summary"},
396
397     OPT_PARAMETERS(),
398     {"command", 0, 0, "Name of command to display help (optional)"},
399     {NULL}
400 };
401
402
403 int help_main(int argc, char **argv)
404 {
405     FUNCTION *fp;
406     int i, nl;
407     FUNC_TYPE tp;
408     char *prog;
409     HELP_CHOICE o;
410     DISPLAY_COLUMNS dc;
411
412     prog = opt_init(argc, argv, help_options);
413     while ((o = opt_next()) != OPT_hEOF) {
414         switch (o) {
415         case OPT_hERR:
416         case OPT_hEOF:
417             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
418             return 1;
419         case OPT_hHELP:
420             opt_help(help_options);
421             return 0;
422         }
423     }
424
425     if (opt_num_rest() == 1) {
426         char *new_argv[3];
427
428         new_argv[0] = opt_rest()[0];
429         new_argv[1] = "--help";
430         new_argv[2] = NULL;
431         return do_cmd(prog_init(), 2, new_argv);
432     }
433     if (opt_num_rest() != 0) {
434         BIO_printf(bio_err, "Usage: %s\n", prog);
435         return 1;
436     }
437
438     calculate_columns(functions, &dc);
439     BIO_printf(bio_err, "Standard commands");
440     i = 0;
441     tp = FT_none;
442     for (fp = functions; fp->name != NULL; fp++) {
443         nl = 0;
444         if (i++ % dc.columns == 0) {
445             BIO_printf(bio_err, "\n");
446             nl = 1;
447         }
448         if (fp->type != tp) {
449             tp = fp->type;
450             if (!nl)
451                 BIO_printf(bio_err, "\n");
452             if (tp == FT_md) {
453                 i = 1;
454                 BIO_printf(bio_err,
455                            "\nMessage Digest commands (see the `dgst' command for more details)\n");
456             } else if (tp == FT_cipher) {
457                 i = 1;
458                 BIO_printf(bio_err,
459                            "\nCipher commands (see the `enc' command for more details)\n");
460             }
461         }
462         BIO_printf(bio_err, "%-*s", dc.width, fp->name);
463     }
464     BIO_printf(bio_err, "\n\n");
465     return 0;
466 }
467
468 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[])
469 {
470     FUNCTION f, *fp;
471
472     if (argc <= 0 || argv[0] == NULL)
473         return 0;
474     f.name = argv[0];
475     fp = lh_FUNCTION_retrieve(prog, &f);
476     if (fp == NULL) {
477         if (EVP_get_digestbyname(argv[0])) {
478             f.type = FT_md;
479             f.func = dgst_main;
480             fp = &f;
481         } else if (EVP_get_cipherbyname(argv[0])) {
482             f.type = FT_cipher;
483             f.func = enc_main;
484             fp = &f;
485         }
486     }
487     if (fp != NULL) {
488         if (fp->deprecated_alternative != NULL)
489             warn_deprecated(fp);
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 }