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