Big apps cleanup (option-parsing, etc)
[openssl.git] / apps / dgst.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57
58 #include <stdio.h>
59 #include <string.h>
60 #include <stdlib.h>
61 #include "apps.h"
62 #include <openssl/bio.h>
63 #include <openssl/err.h>
64 #include <openssl/evp.h>
65 #include <openssl/objects.h>
66 #include <openssl/x509.h>
67 #include <openssl/pem.h>
68 #include <openssl/hmac.h>
69
70 #undef BUFSIZE
71 #define BUFSIZE 1024*8
72
73 int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout,
74           EVP_PKEY *key, unsigned char *sigin, int siglen,
75           const char *sig_name, const char *md_name,
76           const char *file, BIO *bmd);
77
78 typedef enum OPTION_choice {
79     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
80     OPT_C, OPT_R, OPT_RAND, OPT_OUT, OPT_SIGN, OPT_PASSIN, OPT_VERIFY,
81     OPT_PRVERIFY, OPT_SIGNATURE, OPT_KEYFORM, OPT_ENGINE, OPT_ENGINE_IMPL,
82     OPT_HEX, OPT_BINARY, OPT_DEBUG, OPT_FIPS_FINGERPRINT,
83     OPT_NON_FIPS_ALLOW, OPT_HMAC, OPT_MAC, OPT_SIGOPT, OPT_MACOPT,
84     OPT_DIGEST
85 } OPTION_CHOICE;
86
87 OPTIONS dgst_options[] = {
88     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [file...]\n"},
89     {OPT_HELP_STR, 1, '-',
90         "  file... files to digest (default is stdin)\n"},
91     {"help", OPT_HELP, '-', "Display this summary"},
92     {"c", OPT_C, '-', "Print the digest with separating colons"},
93     {"r", OPT_R, '-', "Print the digest in coreutils format"},
94     {"rand", OPT_RAND, 's'},
95     {"out", OPT_OUT, '>', "Output to filename rather than stdout"},
96     {"passin", OPT_PASSIN, 's'},
97     {"sign", OPT_SIGN, '<', "Sign digest using private key in file"},
98     {"verify", OPT_VERIFY, '<',
99      "Verify a signature using public key in file"},
100     {"prverify", OPT_PRVERIFY, '<',
101      "Verify a signature using private key in file"},
102     {"signature", OPT_SIGNATURE, '<', "File with signature to verify"},
103     {"keyform", OPT_KEYFORM, 'f', "Key file format (PEM or ENGINE)"},
104 #ifndef OPENSSL_NO_ENGINE
105     {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
106 #endif
107     {"engine_impl", OPT_ENGINE_IMPL, '-'},
108     {"hex", OPT_HEX, '-', "Print as hex dump"},
109     {"binary", OPT_BINARY, '-', "Print in binary form"},
110     {"d", OPT_DEBUG, '-', "Print debug info"},
111     {"debug", OPT_DEBUG, '-'},
112     {"fips-fingerprint", OPT_FIPS_FINGERPRINT, '-'},
113     {"non-fips-allow", OPT_NON_FIPS_ALLOW, '-'},
114     {"hmac", OPT_HMAC, 's', "Create hashed MAC with key"},
115     {"mac", OPT_MAC, 's', "Create MAC (not neccessarily HMAC)"},
116     {"sigop", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
117     {"macop", OPT_MACOPT, 's', "MAC algorithm parameters in n:v form or key"},
118     {"", OPT_DIGEST, '-', "Any supported digest"},
119     {NULL}
120 };
121
122 int dgst_main(int argc, char **argv)
123 {
124     BIO *in = NULL, *inp, *bmd = NULL, *out = NULL;
125     ENGINE *e = NULL, *impl = NULL;
126     EVP_PKEY *sigkey = NULL;
127     STACK_OF(OPENSSL_STRING) *sigopts = NULL, *macopts = NULL;
128     char *hmac_key = NULL;
129     char *mac_name = NULL;
130     char *passinarg = NULL, *passin = NULL;
131     const EVP_MD *md = NULL, *m;
132     const char *outfile = NULL, *keyfile = NULL, *prog = NULL;
133     const char *sigfile = NULL, *randfile = NULL;
134     OPTION_CHOICE o;
135     int separator = 0, debug = 0, keyform = FORMAT_PEM, siglen = 0;
136     int i, ret = 1, out_bin = -1, want_pub = 0, do_verify =
137         0, non_fips_allow = 0;
138     unsigned char *buf = NULL, *sigbuf = NULL;
139 #ifndef OPENSSL_NO_ENGINE
140     char *engine = NULL;
141     int engine_impl = 0;
142 #endif
143
144     prog = opt_progname(argv[0]);
145     if ((buf = (unsigned char *)OPENSSL_malloc(BUFSIZE)) == NULL) {
146         BIO_printf(bio_err, "%s: out of memory\n", prog);
147         goto end;
148     }
149     md = EVP_get_digestbyname(prog);
150
151     prog = opt_init(argc, argv, dgst_options);
152     while ((o = opt_next()) != OPT_EOF) {
153         switch (o) {
154         case OPT_EOF:
155         case OPT_ERR:
156  opthelp:
157             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
158             goto end;
159         case OPT_HELP:
160             opt_help(dgst_options);
161             ret = 0;
162             goto end;
163         case OPT_C:
164             separator = 1;
165             break;
166         case OPT_R:
167             separator = 2;
168             break;
169         case OPT_RAND:
170             randfile = opt_arg();
171             break;
172         case OPT_OUT:
173             outfile = opt_arg();
174             break;
175         case OPT_SIGN:
176             keyfile = opt_arg();
177             break;
178         case OPT_PASSIN:
179             passinarg = opt_arg();
180             break;
181         case OPT_VERIFY:
182             keyfile = opt_arg();
183             want_pub = do_verify = 1;
184             break;
185         case OPT_PRVERIFY:
186             keyfile = opt_arg();
187             do_verify = 1;
188             break;
189         case OPT_SIGNATURE:
190             sigfile = opt_arg();
191             break;
192         case OPT_KEYFORM:
193             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
194                 goto opthelp;
195             break;
196 #ifndef OPENSSL_NO_ENGINE
197         case OPT_ENGINE:
198             engine = opt_arg();
199             e = setup_engine(engine, 0);
200             break;
201         case OPT_ENGINE_IMPL:
202             engine_impl = 1;
203             break;
204 #endif
205         case OPT_HEX:
206             out_bin = 0;
207             break;
208         case OPT_BINARY:
209             out_bin = 1;
210             break;
211         case OPT_DEBUG:
212             debug = 1;
213             break;
214         case OPT_FIPS_FINGERPRINT:
215             hmac_key = "etaonrishdlcupfm";
216             break;
217         case OPT_NON_FIPS_ALLOW:
218             non_fips_allow = 1;
219             break;
220         case OPT_HMAC:
221             hmac_key = opt_arg();
222             break;
223         case OPT_MAC:
224             mac_name = opt_arg();
225             break;
226         case OPT_SIGOPT:
227             if (!sigopts)
228                 sigopts = sk_OPENSSL_STRING_new_null();
229             if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
230                 goto opthelp;
231             break;
232         case OPT_MACOPT:
233             if (!macopts)
234                 macopts = sk_OPENSSL_STRING_new_null();
235             if (!macopts || !sk_OPENSSL_STRING_push(macopts, opt_arg()))
236                 goto opthelp;
237             break;
238         case OPT_DIGEST:
239             if (!opt_md(opt_unknown(), &m))
240                 goto opthelp;
241             md = m;
242             break;
243         }
244     }
245     argc = opt_num_rest();
246     argv = opt_rest();
247
248     if (do_verify && !sigfile) {
249         BIO_printf(bio_err,
250                    "No signature to verify: use the -signature option\n");
251         goto end;
252     }
253 #ifndef OPENSSL_NO_ENGINE
254     if (engine_impl)
255         impl = e;
256 #endif
257
258     in = BIO_new(BIO_s_file());
259     bmd = BIO_new(BIO_f_md());
260     if ((in == NULL) || (bmd == NULL)) {
261         ERR_print_errors(bio_err);
262         goto end;
263     }
264
265     if (debug) {
266         BIO_set_callback(in, BIO_debug_callback);
267         /* needed for windows 3.1 */
268         BIO_set_callback_arg(in, (char *)bio_err);
269     }
270
271     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
272         BIO_printf(bio_err, "Error getting password\n");
273         goto end;
274     }
275
276     if (out_bin == -1) {
277         if (keyfile)
278             out_bin = 1;
279         else
280             out_bin = 0;
281     }
282
283     if (randfile)
284         app_RAND_load_file(randfile, 0);
285
286     out = bio_open_default(outfile, out_bin ? "wb" : "w");
287     if (out == NULL)
288         goto end;
289
290     if ((! !mac_name + ! !keyfile + ! !hmac_key) > 1) {
291         BIO_printf(bio_err, "MAC and Signing key cannot both be specified\n");
292         goto end;
293     }
294
295     if (keyfile) {
296         if (want_pub)
297             sigkey = load_pubkey(keyfile, keyform, 0, NULL, e, "key file");
298         else
299             sigkey = load_key(keyfile, keyform, 0, passin, e, "key file");
300         if (!sigkey) {
301             /*
302              * load_[pub]key() has already printed an appropriate message
303              */
304             goto end;
305         }
306     }
307
308     if (mac_name) {
309         EVP_PKEY_CTX *mac_ctx = NULL;
310         int r = 0;
311         if (!init_gen_str(&mac_ctx, mac_name, impl, 0))
312             goto mac_end;
313         if (macopts) {
314             char *macopt;
315             for (i = 0; i < sk_OPENSSL_STRING_num(macopts); i++) {
316                 macopt = sk_OPENSSL_STRING_value(macopts, i);
317                 if (pkey_ctrl_string(mac_ctx, macopt) <= 0) {
318                     BIO_printf(bio_err,
319                                "MAC parameter error \"%s\"\n", macopt);
320                     ERR_print_errors(bio_err);
321                     goto mac_end;
322                 }
323             }
324         }
325         if (EVP_PKEY_keygen(mac_ctx, &sigkey) <= 0) {
326             BIO_puts(bio_err, "Error generating key\n");
327             ERR_print_errors(bio_err);
328             goto mac_end;
329         }
330         r = 1;
331  mac_end:
332         EVP_PKEY_CTX_free(mac_ctx);
333         if (r == 0)
334             goto end;
335     }
336
337     if (non_fips_allow) {
338         EVP_MD_CTX *md_ctx;
339         BIO_get_md_ctx(bmd, &md_ctx);
340         EVP_MD_CTX_set_flags(md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
341     }
342
343     if (hmac_key) {
344         sigkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, impl,
345                                       (unsigned char *)hmac_key, -1);
346         if (!sigkey)
347             goto end;
348     }
349
350     if (sigkey) {
351         EVP_MD_CTX *mctx = NULL;
352         EVP_PKEY_CTX *pctx = NULL;
353         int r;
354         if (!BIO_get_md_ctx(bmd, &mctx)) {
355             BIO_printf(bio_err, "Error getting context\n");
356             ERR_print_errors(bio_err);
357             goto end;
358         }
359         if (do_verify)
360             r = EVP_DigestVerifyInit(mctx, &pctx, md, impl, sigkey);
361         else
362             r = EVP_DigestSignInit(mctx, &pctx, md, impl, sigkey);
363         if (!r) {
364             BIO_printf(bio_err, "Error setting context\n");
365             ERR_print_errors(bio_err);
366             goto end;
367         }
368         if (sigopts) {
369             char *sigopt;
370             for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
371                 sigopt = sk_OPENSSL_STRING_value(sigopts, i);
372                 if (pkey_ctrl_string(pctx, sigopt) <= 0) {
373                     BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
374                     ERR_print_errors(bio_err);
375                     goto end;
376                 }
377             }
378         }
379     }
380     /* we use md as a filter, reading from 'in' */
381     else {
382         EVP_MD_CTX *mctx = NULL;
383         if (!BIO_get_md_ctx(bmd, &mctx)) {
384             BIO_printf(bio_err, "Error getting context\n");
385             ERR_print_errors(bio_err);
386             goto end;
387         }
388         if (md == NULL)
389             md = EVP_md5();
390         if (!EVP_DigestInit_ex(mctx, md, impl)) {
391             BIO_printf(bio_err, "Error setting digest\n");
392             ERR_print_errors(bio_err);
393             goto end;
394         }
395     }
396
397     if (sigfile && sigkey) {
398         BIO *sigbio = BIO_new_file(sigfile, "rb");
399         if (!sigbio) {
400             BIO_printf(bio_err, "Error opening signature file %s\n", sigfile);
401             ERR_print_errors(bio_err);
402             goto end;
403         }
404         siglen = EVP_PKEY_size(sigkey);
405         sigbuf = OPENSSL_malloc(siglen);
406         if (!sigbuf) {
407             BIO_printf(bio_err, "Out of memory\n");
408             goto end;
409         }
410         siglen = BIO_read(sigbio, sigbuf, siglen);
411         BIO_free(sigbio);
412         if (siglen <= 0) {
413             BIO_printf(bio_err, "Error reading signature file %s\n", sigfile);
414             ERR_print_errors(bio_err);
415             goto end;
416         }
417     }
418     inp = BIO_push(bmd, in);
419
420     if (md == NULL) {
421         EVP_MD_CTX *tctx;
422         BIO_get_md_ctx(bmd, &tctx);
423         md = EVP_MD_CTX_md(tctx);
424     }
425
426     if (argc == 0) {
427         BIO_set_fp(in, stdin, BIO_NOCLOSE);
428         ret = do_fp(out, buf, inp, separator, out_bin, sigkey, sigbuf,
429                     siglen, NULL, NULL, "stdin", bmd);
430     } else {
431         const char *md_name = NULL, *sig_name = NULL;
432         if (!out_bin) {
433             if (sigkey) {
434                 const EVP_PKEY_ASN1_METHOD *ameth;
435                 ameth = EVP_PKEY_get0_asn1(sigkey);
436                 if (ameth)
437                     EVP_PKEY_asn1_get0_info(NULL, NULL,
438                                             NULL, NULL, &sig_name, ameth);
439             }
440             if (md)
441                 md_name = EVP_MD_name(md);
442         }
443         ret = 0;
444         for (i = 0; i < argc; i++) {
445             int r;
446             if (BIO_read_filename(in, argv[i]) <= 0) {
447                 perror(argv[i]);
448                 ret++;
449                 continue;
450             } else
451                 r = do_fp(out, buf, inp, separator, out_bin, sigkey, sigbuf,
452                           siglen, sig_name, md_name, argv[i], bmd);
453             if (r)
454                 ret = r;
455             (void)BIO_reset(bmd);
456         }
457     }
458  end:
459     if (buf != NULL) {
460         OPENSSL_cleanse(buf, BUFSIZE);
461         OPENSSL_free(buf);
462     }
463     BIO_free(in);
464     if (passin)
465         OPENSSL_free(passin);
466     BIO_free_all(out);
467     EVP_PKEY_free(sigkey);
468     if (sigopts)
469         sk_OPENSSL_STRING_free(sigopts);
470     if (macopts)
471         sk_OPENSSL_STRING_free(macopts);
472     if (sigbuf)
473         OPENSSL_free(sigbuf);
474     BIO_free(bmd);
475     return (ret);
476 }
477
478 int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout,
479           EVP_PKEY *key, unsigned char *sigin, int siglen,
480           const char *sig_name, const char *md_name,
481           const char *file, BIO *bmd)
482 {
483     size_t len;
484     int i;
485
486     for (;;) {
487         i = BIO_read(bp, (char *)buf, BUFSIZE);
488         if (i < 0) {
489             BIO_printf(bio_err, "Read Error in %s\n", file);
490             ERR_print_errors(bio_err);
491             return 1;
492         }
493         if (i == 0)
494             break;
495     }
496     if (sigin) {
497         EVP_MD_CTX *ctx;
498         BIO_get_md_ctx(bp, &ctx);
499         i = EVP_DigestVerifyFinal(ctx, sigin, (unsigned int)siglen);
500         if (i > 0)
501             BIO_printf(out, "Verified OK\n");
502         else if (i == 0) {
503             BIO_printf(out, "Verification Failure\n");
504             return 1;
505         } else {
506             BIO_printf(bio_err, "Error Verifying Data\n");
507             ERR_print_errors(bio_err);
508             return 1;
509         }
510         return 0;
511     }
512     if (key) {
513         EVP_MD_CTX *ctx;
514         BIO_get_md_ctx(bp, &ctx);
515         len = BUFSIZE;
516         if (!EVP_DigestSignFinal(ctx, buf, &len)) {
517             BIO_printf(bio_err, "Error Signing Data\n");
518             ERR_print_errors(bio_err);
519             return 1;
520         }
521     } else {
522         len = BIO_gets(bp, (char *)buf, BUFSIZE);
523         if ((int)len < 0) {
524             ERR_print_errors(bio_err);
525             return 1;
526         }
527     }
528
529     if (binout)
530         BIO_write(out, buf, len);
531     else if (sep == 2) {
532         for (i = 0; i < (int)len; i++)
533             BIO_printf(out, "%02x", buf[i]);
534         BIO_printf(out, " *%s\n", file);
535     } else {
536         if (sig_name) {
537             BIO_puts(out, sig_name);
538             if (md_name)
539                 BIO_printf(out, "-%s", md_name);
540             BIO_printf(out, "(%s)= ", file);
541         } else if (md_name)
542             BIO_printf(out, "%s(%s)= ", md_name, file);
543         else
544             BIO_printf(out, "(%s)= ", file);
545         for (i = 0; i < (int)len; i++) {
546             if (sep && (i != 0))
547                 BIO_printf(out, ":");
548             BIO_printf(out, "%02x", buf[i]);
549         }
550         BIO_printf(out, "\n");
551     }
552     return 0;
553 }