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