Remove getenv(OPENSSL_FIPS) in openssl command
[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 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 (!apps_startup()) {
265         BIO_printf(bio_err,
266                    "FATAL: Startup failure (dev note: apps_startup() failed)\n");
267         ERR_print_errors(bio_err);
268         ret = 1;
269         goto end;
270     }
271
272     prog = prog_init();
273     if (prog == NULL) {
274         BIO_printf(bio_err,
275                    "FATAL: Startup failure (dev note: prog_init() failed)\n");
276         ERR_print_errors(bio_err);
277         ret = 1;
278         goto end;
279     }
280     pname = opt_progname(argv[0]);
281
282     /* first check the program name */
283     f.name = pname;
284     fp = lh_FUNCTION_retrieve(prog, &f);
285     if (fp != NULL) {
286         argv[0] = pname;
287         if (fp->deprecated_alternative != NULL)
288             warn_deprecated(fp);
289         ret = fp->func(argc, argv);
290         goto end;
291     }
292
293     /* If there is stuff on the command line, run with that. */
294     if (argc != 1) {
295         argc--;
296         argv++;
297         ret = do_cmd(prog, argc, argv);
298         if (ret < 0)
299             ret = 0;
300         goto end;
301     }
302
303     /* ok, lets enter interactive mode */
304     for (;;) {
305         ret = 0;
306         /* Read a line, continue reading if line ends with \ */
307         for (p = buf, n = sizeof(buf), i = 0, first = 1; n > 0; first = 0) {
308             prompt = first ? "OpenSSL> " : "> ";
309             p[0] = '\0';
310 #ifndef READLINE
311             fputs(prompt, stdout);
312             fflush(stdout);
313             if (!fgets(p, n, stdin))
314                 goto end;
315             if (p[0] == '\0')
316                 goto end;
317             i = strlen(p);
318             if (i <= 1)
319                 break;
320             if (p[i - 2] != '\\')
321                 break;
322             i -= 2;
323             p += i;
324             n -= i;
325 #else
326             {
327                 extern char *readline(const char *);
328                 extern void add_history(const char *cp);
329                 char *text;
330
331                 text = readline(prompt);
332                 if (text == NULL)
333                     goto end;
334                 i = strlen(text);
335                 if (i == 0 || i > n)
336                     break;
337                 if (text[i - 1] != '\\') {
338                     p += strlen(strcpy(p, text));
339                     free(text);
340                     add_history(buf);
341                     break;
342                 }
343
344                 text[i - 1] = '\0';
345                 p += strlen(strcpy(p, text));
346                 free(text);
347                 n -= i;
348             }
349 #endif
350         }
351
352         if (!chopup_args(&arg, buf)) {
353             BIO_printf(bio_err, "Can't parse (no memory?)\n");
354             break;
355         }
356
357         ret = do_cmd(prog, arg.argc, arg.argv);
358         if (ret == EXIT_THE_PROGRAM) {
359             ret = 0;
360             goto end;
361         }
362         if (ret != 0)
363             BIO_printf(bio_err, "error in %s\n", arg.argv[0]);
364         (void)BIO_flush(bio_out);
365         (void)BIO_flush(bio_err);
366     }
367     ret = 1;
368  end:
369     app_providers_cleanup();
370     OPENSSL_free(default_config_file);
371     lh_FUNCTION_free(prog);
372     OPENSSL_free(arg.argv);
373     app_RAND_write();
374
375     BIO_free(bio_in);
376     BIO_free_all(bio_out);
377     apps_shutdown();
378     BIO_free(bio_err);
379     EXIT(ret);
380 }
381
382 typedef enum HELP_CHOICE {
383     OPT_hERR = -1, OPT_hEOF = 0, OPT_hHELP
384 } HELP_CHOICE;
385
386 const OPTIONS help_options[] = {
387     {OPT_HELP_STR, 1, '-', "Usage: help [options] [command]\n"},
388
389     OPT_SECTION("General"),
390     {"help", OPT_hHELP, '-', "Display this summary"},
391
392     OPT_PARAMETERS(),
393     {"command", 0, 0, "Name of command to display help (optional)"},
394     {NULL}
395 };
396
397
398 int help_main(int argc, char **argv)
399 {
400     FUNCTION *fp;
401     int i, nl;
402     FUNC_TYPE tp;
403     char *prog;
404     HELP_CHOICE o;
405     DISPLAY_COLUMNS dc;
406
407     prog = opt_init(argc, argv, help_options);
408     while ((o = opt_next()) != OPT_hEOF) {
409         switch (o) {
410         case OPT_hERR:
411         case OPT_hEOF:
412             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
413             return 1;
414         case OPT_hHELP:
415             opt_help(help_options);
416             return 0;
417         }
418     }
419
420     if (opt_num_rest() == 1) {
421         char *new_argv[3];
422
423         new_argv[0] = opt_rest()[0];
424         new_argv[1] = "--help";
425         new_argv[2] = NULL;
426         return do_cmd(prog_init(), 2, new_argv);
427     }
428     if (opt_num_rest() != 0) {
429         BIO_printf(bio_err, "Usage: %s\n", prog);
430         return 1;
431     }
432
433     calculate_columns(functions, &dc);
434     BIO_printf(bio_err, "Standard commands");
435     i = 0;
436     tp = FT_none;
437     for (fp = functions; fp->name != NULL; fp++) {
438         nl = 0;
439         if (i++ % dc.columns == 0) {
440             BIO_printf(bio_err, "\n");
441             nl = 1;
442         }
443         if (fp->type != tp) {
444             tp = fp->type;
445             if (!nl)
446                 BIO_printf(bio_err, "\n");
447             if (tp == FT_md) {
448                 i = 1;
449                 BIO_printf(bio_err,
450                            "\nMessage Digest commands (see the `dgst' command for more details)\n");
451             } else if (tp == FT_cipher) {
452                 i = 1;
453                 BIO_printf(bio_err,
454                            "\nCipher commands (see the `enc' command for more details)\n");
455             }
456         }
457         BIO_printf(bio_err, "%-*s", dc.width, fp->name);
458     }
459     BIO_printf(bio_err, "\n\n");
460     return 0;
461 }
462
463 static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[])
464 {
465     FUNCTION f, *fp;
466
467     if (argc <= 0 || argv[0] == NULL)
468         return 0;
469     f.name = argv[0];
470     fp = lh_FUNCTION_retrieve(prog, &f);
471     if (fp == NULL) {
472         if (EVP_get_digestbyname(argv[0])) {
473             f.type = FT_md;
474             f.func = dgst_main;
475             fp = &f;
476         } else if (EVP_get_cipherbyname(argv[0])) {
477             f.type = FT_cipher;
478             f.func = enc_main;
479             fp = &f;
480         }
481     }
482     if (fp != NULL) {
483         if (fp->deprecated_alternative != NULL)
484             warn_deprecated(fp);
485         return fp->func(argc, argv);
486     }
487     if ((strncmp(argv[0], "no-", 3)) == 0) {
488         /*
489          * User is asking if foo is unsupported, by trying to "run" the
490          * no-foo command.  Strange.
491          */
492         f.name = argv[0] + 3;
493         if (lh_FUNCTION_retrieve(prog, &f) == NULL) {
494             BIO_printf(bio_out, "%s\n", argv[0]);
495             return 0;
496         }
497         BIO_printf(bio_out, "%s\n", argv[0] + 3);
498         return 1;
499     }
500     if (strcmp(argv[0], "quit") == 0 || strcmp(argv[0], "q") == 0 ||
501         strcmp(argv[0], "exit") == 0 || strcmp(argv[0], "bye") == 0)
502         /* Special value to mean "exit the program. */
503         return EXIT_THE_PROGRAM;
504
505     BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n",
506                argv[0]);
507     return 1;
508 }
509
510 static int function_cmp(const FUNCTION * a, const FUNCTION * b)
511 {
512     return strncmp(a->name, b->name, 8);
513 }
514
515 static unsigned long function_hash(const FUNCTION * a)
516 {
517     return OPENSSL_LH_strhash(a->name);
518 }
519
520 static int SortFnByName(const void *_f1, const void *_f2)
521 {
522     const FUNCTION *f1 = _f1;
523     const FUNCTION *f2 = _f2;
524
525     if (f1->type != f2->type)
526         return f1->type - f2->type;
527     return strcmp(f1->name, f2->name);
528 }
529
530 static LHASH_OF(FUNCTION) *prog_init(void)
531 {
532     static LHASH_OF(FUNCTION) *ret = NULL;
533     static int prog_inited = 0;
534     FUNCTION *f;
535     size_t i;
536
537     if (prog_inited)
538         return ret;
539
540     prog_inited = 1;
541
542     /* Sort alphabetically within category. For nicer help displays. */
543     for (i = 0, f = functions; f->name != NULL; ++f, ++i)
544         ;
545     qsort(functions, i, sizeof(*functions), SortFnByName);
546
547     if ((ret = lh_FUNCTION_new(function_hash, function_cmp)) == NULL)
548         return NULL;
549
550     for (f = functions; f->name != NULL; f++)
551         (void)lh_FUNCTION_insert(ret, f);
552     return ret;
553 }