apps/cms.c: Correct -sign output and -verify input with -binary
[openssl.git] / apps / dgst.c
1 /*
2  * Copyright 1995-2021 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 "apps.h"
14 #include "progs.h"
15 #include <openssl/bio.h>
16 #include <openssl/err.h>
17 #include <openssl/evp.h>
18 #include <openssl/objects.h>
19 #include <openssl/x509.h>
20 #include <openssl/pem.h>
21 #include <openssl/hmac.h>
22 #include <ctype.h>
23
24 #undef BUFSIZE
25 #define BUFSIZE 1024*8
26
27 int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout, int xoflen,
28           EVP_PKEY *key, unsigned char *sigin, int siglen,
29           const char *sig_name, const char *md_name,
30           const char *file);
31 static void show_digests(const OBJ_NAME *name, void *bio_);
32
33 struct doall_dgst_digests {
34     BIO *bio;
35     int n;
36 };
37
38 typedef enum OPTION_choice {
39     OPT_COMMON,
40     OPT_LIST,
41     OPT_C, OPT_R, OPT_OUT, OPT_SIGN, OPT_PASSIN, OPT_VERIFY,
42     OPT_PRVERIFY, OPT_SIGNATURE, OPT_KEYFORM, OPT_ENGINE, OPT_ENGINE_IMPL,
43     OPT_HEX, OPT_BINARY, OPT_DEBUG, OPT_FIPS_FINGERPRINT,
44     OPT_HMAC, OPT_MAC, OPT_SIGOPT, OPT_MACOPT, OPT_XOFLEN,
45     OPT_DIGEST,
46     OPT_R_ENUM, OPT_PROV_ENUM
47 } OPTION_CHOICE;
48
49 const OPTIONS dgst_options[] = {
50     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [file...]\n"},
51
52     OPT_SECTION("General"),
53     {"help", OPT_HELP, '-', "Display this summary"},
54     {"list", OPT_LIST, '-', "List digests"},
55 #ifndef OPENSSL_NO_ENGINE
56     {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
57     {"engine_impl", OPT_ENGINE_IMPL, '-',
58      "Also use engine given by -engine for digest operations"},
59 #endif
60     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
61
62     OPT_SECTION("Output"),
63     {"c", OPT_C, '-', "Print the digest with separating colons"},
64     {"r", OPT_R, '-', "Print the digest in coreutils format"},
65     {"out", OPT_OUT, '>', "Output to filename rather than stdout"},
66     {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"},
67     {"hex", OPT_HEX, '-', "Print as hex dump"},
68     {"binary", OPT_BINARY, '-', "Print in binary form"},
69     {"xoflen", OPT_XOFLEN, 'p', "Output length for XOF algorithms"},
70     {"d", OPT_DEBUG, '-', "Print debug info"},
71     {"debug", OPT_DEBUG, '-', "Print debug info"},
72
73     OPT_SECTION("Signing"),
74     {"sign", OPT_SIGN, 's', "Sign digest using private key"},
75     {"verify", OPT_VERIFY, 's', "Verify a signature using public key"},
76     {"prverify", OPT_PRVERIFY, 's', "Verify a signature using private key"},
77     {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
78     {"signature", OPT_SIGNATURE, '<', "File with signature to verify"},
79     {"hmac", OPT_HMAC, 's', "Create hashed MAC with key"},
80     {"mac", OPT_MAC, 's', "Create MAC (not necessarily HMAC)"},
81     {"macopt", OPT_MACOPT, 's', "MAC algorithm parameters in n:v form or key"},
82     {"", OPT_DIGEST, '-', "Any supported digest"},
83     {"fips-fingerprint", OPT_FIPS_FINGERPRINT, '-',
84      "Compute HMAC with the key used in OpenSSL-FIPS fingerprint"},
85
86     OPT_R_OPTIONS,
87     OPT_PROV_OPTIONS,
88
89     OPT_PARAMETERS(),
90     {"file", 0, 0, "Files to digest (optional; default is stdin)"},
91     {NULL}
92 };
93
94 int dgst_main(int argc, char **argv)
95 {
96     BIO *in = NULL, *inp, *bmd = NULL, *out = NULL;
97     ENGINE *e = NULL, *impl = NULL;
98     EVP_PKEY *sigkey = NULL;
99     STACK_OF(OPENSSL_STRING) *sigopts = NULL, *macopts = NULL;
100     char *hmac_key = NULL;
101     char *mac_name = NULL, *digestname = NULL;
102     char *passinarg = NULL, *passin = NULL;
103     EVP_MD *md = NULL;
104     const char *outfile = NULL, *keyfile = NULL, *prog = NULL;
105     const char *sigfile = NULL;
106     const char *md_name = NULL;
107     OPTION_CHOICE o;
108     int separator = 0, debug = 0, keyform = FORMAT_UNDEF, siglen = 0;
109     int i, ret = 1, out_bin = -1, want_pub = 0, do_verify = 0;
110     int xoflen = 0;
111     unsigned char *buf = NULL, *sigbuf = NULL;
112     int engine_impl = 0;
113     struct doall_dgst_digests dec;
114
115     buf = app_malloc(BUFSIZE, "I/O buffer");
116     md = (EVP_MD *)EVP_get_digestbyname(argv[0]);
117
118     prog = opt_init(argc, argv, dgst_options);
119     while ((o = opt_next()) != OPT_EOF) {
120         switch (o) {
121         case OPT_EOF:
122         case OPT_ERR:
123  opthelp:
124             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
125             goto end;
126         case OPT_HELP:
127             opt_help(dgst_options);
128             ret = 0;
129             goto end;
130         case OPT_LIST:
131             BIO_printf(bio_out, "Supported digests:\n");
132             dec.bio = bio_out;
133             dec.n = 0;
134             OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH,
135                                    show_digests, &dec);
136             BIO_printf(bio_out, "\n");
137             ret = 0;
138             goto end;
139         case OPT_C:
140             separator = 1;
141             break;
142         case OPT_R:
143             separator = 2;
144             break;
145         case OPT_R_CASES:
146             if (!opt_rand(o))
147                 goto end;
148             break;
149         case OPT_OUT:
150             outfile = opt_arg();
151             break;
152         case OPT_SIGN:
153             keyfile = opt_arg();
154             break;
155         case OPT_PASSIN:
156             passinarg = opt_arg();
157             break;
158         case OPT_VERIFY:
159             keyfile = opt_arg();
160             want_pub = do_verify = 1;
161             break;
162         case OPT_PRVERIFY:
163             keyfile = opt_arg();
164             do_verify = 1;
165             break;
166         case OPT_SIGNATURE:
167             sigfile = opt_arg();
168             break;
169         case OPT_KEYFORM:
170             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
171                 goto opthelp;
172             break;
173         case OPT_ENGINE:
174             e = setup_engine(opt_arg(), 0);
175             break;
176         case OPT_ENGINE_IMPL:
177             engine_impl = 1;
178             break;
179         case OPT_HEX:
180             out_bin = 0;
181             break;
182         case OPT_BINARY:
183             out_bin = 1;
184             break;
185         case OPT_XOFLEN:
186             xoflen = atoi(opt_arg());
187             break;
188         case OPT_DEBUG:
189             debug = 1;
190             break;
191         case OPT_FIPS_FINGERPRINT:
192             hmac_key = "etaonrishdlcupfm";
193             break;
194         case OPT_HMAC:
195             hmac_key = opt_arg();
196             break;
197         case OPT_MAC:
198             mac_name = opt_arg();
199             break;
200         case OPT_SIGOPT:
201             if (!sigopts)
202                 sigopts = sk_OPENSSL_STRING_new_null();
203             if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
204                 goto opthelp;
205             break;
206         case OPT_MACOPT:
207             if (!macopts)
208                 macopts = sk_OPENSSL_STRING_new_null();
209             if (!macopts || !sk_OPENSSL_STRING_push(macopts, opt_arg()))
210                 goto opthelp;
211             break;
212         case OPT_DIGEST:
213             digestname = opt_unknown();
214             break;
215         case OPT_PROV_CASES:
216             if (!opt_provider(o))
217                 goto end;
218             break;
219         }
220     }
221
222     /* Remaining args are files to digest. */
223     argc = opt_num_rest();
224     argv = opt_rest();
225     if (keyfile != NULL && argc > 1) {
226         BIO_printf(bio_err, "%s: Can only sign or verify one file.\n", prog);
227         goto end;
228     }
229     if (!app_RAND_load())
230         goto end;
231
232     if (digestname != NULL) {
233         if (!opt_md(digestname, &md))
234             goto opthelp;
235     }
236
237     if (do_verify && sigfile == NULL) {
238         BIO_printf(bio_err,
239                    "No signature to verify: use the -signature option\n");
240         goto end;
241     }
242     if (engine_impl)
243         impl = e;
244
245     in = BIO_new(BIO_s_file());
246     bmd = BIO_new(BIO_f_md());
247     if ((in == NULL) || (bmd == NULL)) {
248         ERR_print_errors(bio_err);
249         goto end;
250     }
251
252     if (debug) {
253         BIO_set_callback(in, BIO_debug_callback);
254         /* needed for windows 3.1 */
255         BIO_set_callback_arg(in, (char *)bio_err);
256     }
257
258     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
259         BIO_printf(bio_err, "Error getting password\n");
260         goto end;
261     }
262
263     if (out_bin == -1) {
264         if (keyfile != NULL)
265             out_bin = 1;
266         else
267             out_bin = 0;
268     }
269
270     out = bio_open_default(outfile, 'w', out_bin ? FORMAT_BINARY : FORMAT_TEXT);
271     if (out == NULL)
272         goto end;
273
274     if ((!(mac_name == NULL) + !(keyfile == NULL) + !(hmac_key == NULL)) > 1) {
275         BIO_printf(bio_err, "MAC and Signing key cannot both be specified\n");
276         goto end;
277     }
278
279     if (keyfile != NULL) {
280         int type;
281
282         if (want_pub)
283             sigkey = load_pubkey(keyfile, keyform, 0, NULL, e, "public key");
284         else
285             sigkey = load_key(keyfile, keyform, 0, passin, e, "private key");
286         if (sigkey == NULL) {
287             /*
288              * load_[pub]key() has already printed an appropriate message
289              */
290             goto end;
291         }
292         type = EVP_PKEY_id(sigkey);
293         if (type == EVP_PKEY_ED25519 || type == EVP_PKEY_ED448) {
294             /*
295              * We implement PureEdDSA for these which doesn't have a separate
296              * digest, and only supports one shot.
297              */
298             BIO_printf(bio_err, "Key type not supported for this operation\n");
299             goto end;
300         }
301     }
302
303     if (mac_name != NULL) {
304         EVP_PKEY_CTX *mac_ctx = NULL;
305         int r = 0;
306         if (!init_gen_str(&mac_ctx, mac_name, impl, 0, NULL, NULL))
307             goto mac_end;
308         if (macopts != NULL) {
309             char *macopt;
310             for (i = 0; i < sk_OPENSSL_STRING_num(macopts); i++) {
311                 macopt = sk_OPENSSL_STRING_value(macopts, i);
312                 if (pkey_ctrl_string(mac_ctx, macopt) <= 0) {
313                     BIO_printf(bio_err,
314                                "MAC parameter error \"%s\"\n", macopt);
315                     ERR_print_errors(bio_err);
316                     goto mac_end;
317                 }
318             }
319         }
320         if (EVP_PKEY_keygen(mac_ctx, &sigkey) <= 0) {
321             BIO_puts(bio_err, "Error generating key\n");
322             ERR_print_errors(bio_err);
323             goto mac_end;
324         }
325         r = 1;
326  mac_end:
327         EVP_PKEY_CTX_free(mac_ctx);
328         if (r == 0)
329             goto end;
330     }
331
332     if (hmac_key != NULL) {
333         if (md == NULL)
334             md = (EVP_MD *)EVP_sha256();
335         sigkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, impl,
336                                               (unsigned char *)hmac_key,
337                                               strlen(hmac_key));
338         if (sigkey == NULL)
339             goto end;
340     }
341
342     if (sigkey != NULL) {
343         EVP_MD_CTX *mctx = NULL;
344         EVP_PKEY_CTX *pctx = NULL;
345         int r;
346         if (!BIO_get_md_ctx(bmd, &mctx)) {
347             BIO_printf(bio_err, "Error getting context\n");
348             ERR_print_errors(bio_err);
349             goto end;
350         }
351         if (do_verify)
352             r = EVP_DigestVerifyInit(mctx, &pctx, md, impl, sigkey);
353         else
354             r = EVP_DigestSignInit(mctx, &pctx, md, impl, sigkey);
355         if (!r) {
356             BIO_printf(bio_err, "Error setting context\n");
357             ERR_print_errors(bio_err);
358             goto end;
359         }
360         if (sigopts != NULL) {
361             char *sigopt;
362             for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
363                 sigopt = sk_OPENSSL_STRING_value(sigopts, i);
364                 if (pkey_ctrl_string(pctx, sigopt) <= 0) {
365                     BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
366                     ERR_print_errors(bio_err);
367                     goto end;
368                 }
369             }
370         }
371     }
372     /* we use md as a filter, reading from 'in' */
373     else {
374         EVP_MD_CTX *mctx = NULL;
375         if (!BIO_get_md_ctx(bmd, &mctx)) {
376             BIO_printf(bio_err, "Error getting context\n");
377             ERR_print_errors(bio_err);
378             goto end;
379         }
380         if (md == NULL)
381             md = (EVP_MD *)EVP_sha256();
382         if (!EVP_DigestInit_ex(mctx, md, impl)) {
383             BIO_printf(bio_err, "Error setting digest\n");
384             ERR_print_errors(bio_err);
385             goto end;
386         }
387     }
388
389     if (sigfile != NULL && sigkey != NULL) {
390         BIO *sigbio = BIO_new_file(sigfile, "rb");
391         if (sigbio == NULL) {
392             BIO_printf(bio_err, "Error opening signature file %s\n", sigfile);
393             ERR_print_errors(bio_err);
394             goto end;
395         }
396         siglen = EVP_PKEY_size(sigkey);
397         sigbuf = app_malloc(siglen, "signature buffer");
398         siglen = BIO_read(sigbio, sigbuf, siglen);
399         BIO_free(sigbio);
400         if (siglen <= 0) {
401             BIO_printf(bio_err, "Error reading signature file %s\n", sigfile);
402             ERR_print_errors(bio_err);
403             goto end;
404         }
405     }
406     inp = BIO_push(bmd, in);
407
408     if (md == NULL) {
409         EVP_MD_CTX *tctx;
410
411         BIO_get_md_ctx(bmd, &tctx);
412         md = EVP_MD_CTX_get1_md(tctx);
413     }
414     if (md != NULL)
415         md_name = EVP_MD_name(md);
416
417     if (xoflen > 0) {
418         if (!(EVP_MD_flags(md) & EVP_MD_FLAG_XOF)) {
419             BIO_printf(bio_err, "Length can only be specified for XOF\n");
420             goto end;
421         }
422         if (sigkey != NULL) {
423             BIO_printf(bio_err, "Signing key cannot be specified for XOF\n");
424             goto end;
425         }
426     }
427
428     if (argc == 0) {
429         BIO_set_fp(in, stdin, BIO_NOCLOSE);
430         ret = do_fp(out, buf, inp, separator, out_bin, xoflen, sigkey, sigbuf,
431                     siglen, NULL, md_name, "stdin");
432     } else {
433         const char *sig_name = NULL;
434         if (!out_bin) {
435             if (sigkey != NULL)
436                 sig_name = EVP_PKEY_get0_type_name(sigkey);
437         }
438         ret = 0;
439         for (i = 0; i < argc; i++) {
440             int r;
441             if (BIO_read_filename(in, argv[i]) <= 0) {
442                 perror(argv[i]);
443                 ret++;
444                 continue;
445             } else {
446                 r = do_fp(out, buf, inp, separator, out_bin, xoflen,
447                           sigkey, sigbuf, siglen, sig_name, md_name, argv[i]);
448             }
449             if (r)
450                 ret = r;
451             (void)BIO_reset(bmd);
452         }
453     }
454  end:
455     OPENSSL_clear_free(buf, BUFSIZE);
456     BIO_free(in);
457     OPENSSL_free(passin);
458     BIO_free_all(out);
459     EVP_MD_free(md);
460     EVP_PKEY_free(sigkey);
461     sk_OPENSSL_STRING_free(sigopts);
462     sk_OPENSSL_STRING_free(macopts);
463     OPENSSL_free(sigbuf);
464     BIO_free(bmd);
465     release_engine(e);
466     return ret;
467 }
468
469 static void show_digests(const OBJ_NAME *name, void *arg)
470 {
471     struct doall_dgst_digests *dec = (struct doall_dgst_digests *)arg;
472     const EVP_MD *md = NULL;
473
474     /* Filter out signed digests (a.k.a signature algorithms) */
475     if (strstr(name->name, "rsa") != NULL || strstr(name->name, "RSA") != NULL)
476         return;
477
478     if (!islower((unsigned char)*name->name))
479         return;
480
481     /* Filter out message digests that we cannot use */
482     md = EVP_get_digestbyname(name->name);
483     if (md == NULL)
484         return;
485
486     BIO_printf(dec->bio, "-%-25s", name->name);
487     if (++dec->n == 3) {
488         BIO_printf(dec->bio, "\n");
489         dec->n = 0;
490     } else {
491         BIO_printf(dec->bio, " ");
492     }
493 }
494
495 /*
496  * The newline_escape_filename function performs newline escaping for any
497  * filename that contains a newline.  This function also takes a pointer
498  * to backslash. The backslash pointer is a flag to indicating whether a newline
499  * is present in the filename.  If a newline is present, the backslash flag is
500  * set and the output format will contain a backslash at the beginning of the
501  * digest output. This output format is to replicate the output format found
502  * in the '*sum' checksum programs. This aims to preserve backward
503  * compatibility.
504  */
505 static const char *newline_escape_filename(const char *file, int * backslash)
506 {
507     size_t i, e = 0, length = strlen(file), newline_count = 0, mem_len = 0;
508     char *file_cpy = NULL;
509
510     for (i = 0; i < length; i++)
511         if (file[i] == '\n')
512             newline_count++;
513
514     mem_len = length + newline_count + 1;
515     file_cpy = app_malloc(mem_len, file);
516     i = 0;
517
518     while(e < length) {
519         const char c = file[e];
520         if (c == '\n') {
521             file_cpy[i++] = '\\';
522             file_cpy[i++] = 'n';
523             *backslash = 1;
524         } else {
525             file_cpy[i++] = c;
526         }
527         e++;
528     }
529     file_cpy[i] = '\0';
530     return (const char*)file_cpy;
531 }
532
533
534 int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout, int xoflen,
535           EVP_PKEY *key, unsigned char *sigin, int siglen,
536           const char *sig_name, const char *md_name,
537           const char *file)
538 {
539     size_t len = BUFSIZE;
540     int i, backslash = 0, ret = 1;
541     unsigned char *allocated_buf = NULL;
542
543     while (BIO_pending(bp) || !BIO_eof(bp)) {
544         i = BIO_read(bp, (char *)buf, BUFSIZE);
545         if (i < 0) {
546             BIO_printf(bio_err, "Read Error in %s\n", file);
547             ERR_print_errors(bio_err);
548             goto end;
549         }
550         if (i == 0)
551             break;
552     }
553     if (sigin != NULL) {
554         EVP_MD_CTX *ctx;
555         BIO_get_md_ctx(bp, &ctx);
556         i = EVP_DigestVerifyFinal(ctx, sigin, (unsigned int)siglen);
557         if (i > 0) {
558             BIO_printf(out, "Verified OK\n");
559         } else if (i == 0) {
560             BIO_printf(out, "Verification Failure\n");
561             goto end;
562         } else {
563             BIO_printf(bio_err, "Error Verifying Data\n");
564             ERR_print_errors(bio_err);
565             goto end;
566         }
567         ret = 0;
568         goto end;
569     }
570     if (key != NULL) {
571         EVP_MD_CTX *ctx;
572         size_t tmplen;
573
574         BIO_get_md_ctx(bp, &ctx);
575         if (!EVP_DigestSignFinal(ctx, NULL, &tmplen)) {
576             BIO_printf(bio_err, "Error Signing Data\n");
577             ERR_print_errors(bio_err);
578             goto end;
579         }
580         if (tmplen > BUFSIZE) {
581             len = tmplen;
582             allocated_buf = app_malloc(len, "Signature buffer");
583             buf = allocated_buf;
584         }
585         if (!EVP_DigestSignFinal(ctx, buf, &len)) {
586             BIO_printf(bio_err, "Error Signing Data\n");
587             ERR_print_errors(bio_err);
588             goto end;
589         }
590     } else if (xoflen > 0) {
591         EVP_MD_CTX *ctx;
592
593         len = xoflen;
594         if (len > BUFSIZE) {
595             allocated_buf = app_malloc(len, "Digest buffer");
596             buf = allocated_buf;
597         }
598
599         BIO_get_md_ctx(bp, &ctx);
600
601         if (!EVP_DigestFinalXOF(ctx, buf, len)) {
602             BIO_printf(bio_err, "Error Digesting Data\n");
603             ERR_print_errors(bio_err);
604             goto end;
605         }
606     } else {
607         len = BIO_gets(bp, (char *)buf, BUFSIZE);
608         if ((int)len < 0) {
609             ERR_print_errors(bio_err);
610             goto end;
611         }
612     }
613
614     if (binout) {
615         BIO_write(out, buf, len);
616     } else if (sep == 2) {
617         file = newline_escape_filename(file, &backslash);
618
619         if (backslash == 1)
620             BIO_puts(out, "\\");
621
622         for (i = 0; i < (int)len; i++)
623             BIO_printf(out, "%02x", buf[i]);
624
625         BIO_printf(out, " *%s\n", file);
626         OPENSSL_free((char *)file);
627     } else {
628         if (sig_name != NULL) {
629             BIO_puts(out, sig_name);
630             if (md_name != NULL)
631                 BIO_printf(out, "-%s", md_name);
632             BIO_printf(out, "(%s)= ", file);
633         } else if (md_name != NULL) {
634             BIO_printf(out, "%s(%s)= ", md_name, file);
635         } else {
636             BIO_printf(out, "(%s)= ", file);
637         }
638         for (i = 0; i < (int)len; i++) {
639             if (sep && (i != 0))
640                 BIO_printf(out, ":");
641             BIO_printf(out, "%02x", buf[i]);
642         }
643         BIO_printf(out, "\n");
644     }
645
646     ret = 0;
647  end:
648     if (allocated_buf != NULL)
649         OPENSSL_clear_free(allocated_buf, len);
650
651     return ret;
652 }