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