6c15dcfb6ea7e301ab250c3cdbe68b85147f21eb
[openssl.git] / apps / smime.c
1 /* smime.c */
2 /* Written by Dr Stephen N Henson (shenson@bigfoot.com) for the OpenSSL
3  * project 1999.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer. 
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58
59 /* S/MIME utility function */
60
61 #include <stdio.h>
62 #include <string.h>
63 #include "apps.h"
64 #include <openssl/pem.h>
65 #include <openssl/err.h>
66
67 #undef PROG
68 #define PROG smime_main
69 static X509 *load_cert(char *file);
70 static EVP_PKEY *load_key(char *file, char *pass);
71 static STACK_OF(X509) *load_certs(char *file);
72 static X509_STORE *setup_verify(char *CAfile, char *CApath);
73 static int save_certs(char *signerfile, STACK_OF(X509) *signers);
74
75 #define SMIME_OP        0x10
76 #define SMIME_ENCRYPT   (1 | SMIME_OP)
77 #define SMIME_DECRYPT   2
78 #define SMIME_SIGN      (3 | SMIME_OP)
79 #define SMIME_VERIFY    4
80 #define SMIME_PK7OUT    5
81
82 int MAIN(int argc, char **argv)
83 {
84         int operation = 0;
85         int ret = 0;
86         char **args;
87         char *inmode = "r", *outmode = "w";
88         char *infile = NULL, *outfile = NULL;
89         char *signerfile = NULL, *recipfile = NULL;
90         char *certfile = NULL, *keyfile = NULL;
91         EVP_CIPHER *cipher = NULL;
92         PKCS7 *p7 = NULL;
93         X509_STORE *store = NULL;
94         X509 *cert = NULL, *recip = NULL, *signer = NULL;
95         EVP_PKEY *key = NULL;
96         STACK_OF(X509) *encerts = NULL, *other = NULL;
97         BIO *in = NULL, *out = NULL, *indata = NULL;
98         int badarg = 0;
99         int flags = PKCS7_DETACHED;
100         char *to = NULL, *from = NULL, *subject = NULL;
101         char *CAfile = NULL, *CApath = NULL, *passin = NULL;
102
103         args = argv + 1;
104
105         ret = 1;
106
107         while (!badarg && *args && *args[0] == '-') {
108                 if (!strcmp (*args, "-encrypt")) operation = SMIME_ENCRYPT;
109                 else if (!strcmp (*args, "-decrypt")) operation = SMIME_DECRYPT;
110                 else if (!strcmp (*args, "-sign")) operation = SMIME_SIGN;
111                 else if (!strcmp (*args, "-verify")) operation = SMIME_VERIFY;
112                 else if (!strcmp (*args, "-pk7out")) operation = SMIME_PK7OUT;
113                 else if (!strcmp (*args, "-des3")) 
114                                 cipher = EVP_des_ede3_cbc();
115                 else if (!strcmp (*args, "-des")) 
116                                 cipher = EVP_des_cbc();
117                 else if (!strcmp (*args, "-rc2-40")) 
118                                 cipher = EVP_rc2_40_cbc();
119                 else if (!strcmp (*args, "-rc2-128")) 
120                                 cipher = EVP_rc2_cbc();
121                 else if (!strcmp (*args, "-rc2-64")) 
122                                 cipher = EVP_rc2_64_cbc();
123                 else if (!strcmp (*args, "-text")) 
124                                 flags |= PKCS7_TEXT;
125                 else if (!strcmp (*args, "-nointern")) 
126                                 flags |= PKCS7_NOINTERN;
127                 else if (!strcmp (*args, "-noverify")) 
128                                 flags |= PKCS7_NOVERIFY;
129                 else if (!strcmp (*args, "-nochain")) 
130                                 flags |= PKCS7_NOCHAIN;
131                 else if (!strcmp (*args, "-nocerts")) 
132                                 flags |= PKCS7_NOCERTS;
133                 else if (!strcmp (*args, "-noattr")) 
134                                 flags |= PKCS7_NOATTR;
135                 else if (!strcmp (*args, "-nodetach")) 
136                                 flags &= ~PKCS7_DETACHED;
137                 else if (!strcmp (*args, "-binary"))
138                                 flags |= PKCS7_BINARY;
139                 else if (!strcmp (*args, "-nosigs"))
140                                 flags |= PKCS7_NOSIGS;
141                 else if (!strcmp(*argv,"-passin")) {
142                         if (--argc < 1) badarg = 1;
143                         else passin= *(++argv);
144                 } else if (!strcmp(*argv,"-envpassin")) {
145                         if (--argc < 1) badarg = 1;
146                         else if(!(passin= getenv(*(++argv)))) {
147                                 BIO_printf(bio_err,
148                                  "Can't read environment variable %s\n",
149                                                                 *argv);
150                                 badarg = 1;
151                         }
152                 } else if (!strcmp (*args, "-to")) {
153                         if (args[1]) {
154                                 args++;
155                                 to = *args;
156                         } else badarg = 1;
157                 } else if (!strcmp (*args, "-from")) {
158                         if (args[1]) {
159                                 args++;
160                                 from = *args;
161                         } else badarg = 1;
162                 } else if (!strcmp (*args, "-subject")) {
163                         if (args[1]) {
164                                 args++;
165                                 subject = *args;
166                         } else badarg = 1;
167                 } else if (!strcmp (*args, "-signer")) {
168                         if (args[1]) {
169                                 args++;
170                                 signerfile = *args;
171                         } else badarg = 1;
172                 } else if (!strcmp (*args, "-recip")) {
173                         if (args[1]) {
174                                 args++;
175                                 recipfile = *args;
176                         } else badarg = 1;
177                 } else if (!strcmp (*args, "-inkey")) {
178                         if (args[1]) {
179                                 args++;
180                                 keyfile = *args;
181                         } else badarg = 1;
182                 } else if (!strcmp (*args, "-certfile")) {
183                         if (args[1]) {
184                                 args++;
185                                 certfile = *args;
186                         } else badarg = 1;
187                 } else if (!strcmp (*args, "-CAfile")) {
188                         if (args[1]) {
189                                 args++;
190                                 CAfile = *args;
191                         } else badarg = 1;
192                 } else if (!strcmp (*args, "-CApath")) {
193                         if (args[1]) {
194                                 args++;
195                                 CApath = *args;
196                         } else badarg = 1;
197                 } else if (!strcmp (*args, "-in")) {
198                         if (args[1]) {
199                                 args++;
200                                 infile = *args;
201                         } else badarg = 1;
202                 } else if (!strcmp (*args, "-out")) {
203                         if (args[1]) {
204                                 args++;
205                                 outfile = *args;
206                         } else badarg = 1;
207                 } else badarg = 1;
208                 args++;
209         }
210
211         if(operation == SMIME_SIGN) {
212                 if(!signerfile) {
213                         BIO_printf(bio_err, "No signer certificate specified\n");
214                         badarg = 1;
215                 }
216         } else if(operation == SMIME_DECRYPT) {
217                 if(!recipfile) {
218                         BIO_printf(bio_err, "No recipient certificate and key specified\n");
219                         badarg = 1;
220                 }
221         } else if(operation == SMIME_ENCRYPT) {
222                 if(!*args) {
223                         BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
224                         badarg = 1;
225                 }
226         } else if(!operation) badarg = 1;
227
228         if (badarg) {
229                 BIO_printf (bio_err, "Usage smime [options] cert.pem ...\n");
230                 BIO_printf (bio_err, "where options are\n");
231                 BIO_printf (bio_err, "-encrypt       encrypt message\n");
232                 BIO_printf (bio_err, "-decrypt       decrypt encrypted message\n");
233                 BIO_printf (bio_err, "-sign          sign message\n");
234                 BIO_printf (bio_err, "-verify        verify signed message\n");
235                 BIO_printf (bio_err, "-pk7out        output PKCS#7 structure\n");
236                 BIO_printf (bio_err, "-des3          encrypt with triple DES\n");
237                 BIO_printf (bio_err, "-rc2-40        encrypt with RC2-40\n");
238                 BIO_printf (bio_err, "-rc2-64        encrypt with RC2-64\n");
239                 BIO_printf (bio_err, "-rc2-128       encrypt with RC2-128\n");
240                 BIO_printf (bio_err, "-nointern      don't search certificates in message for signer\n");
241                 BIO_printf (bio_err, "-nosigs        don't verify message signature\n");
242                 BIO_printf (bio_err, "-noverify      don't verify signers certificate\n");
243                 BIO_printf (bio_err, "-nocerts       don't include signers certificate when signing\n");
244                 BIO_printf (bio_err, "-nodetach      use opaque signing\n");
245                 BIO_printf (bio_err, "-noattr        don't include any signed attributes\n");
246                 BIO_printf (bio_err, "-binary        don't translate message to text\n");
247                 BIO_printf (bio_err, "-in file       input file\n");
248                 BIO_printf (bio_err, "-certfile file other certificates file\n");
249                 BIO_printf (bio_err, "-signer file   signer certificate file\n");
250                 BIO_printf (bio_err, "-recip  file   recipient certificate file\n");
251                 BIO_printf (bio_err, "-in file       input file\n");
252                 BIO_printf (bio_err, "-inkey file    input private key (if not signer or recipient)\n");
253                 BIO_printf (bio_err, "-out file      output file\n");
254                 BIO_printf (bio_err, "-to addr       to address\n");
255                 BIO_printf (bio_err, "-from ad       from address\n");
256                 BIO_printf (bio_err, "-subject s     subject\n");
257                 BIO_printf (bio_err, "-text          include or delete text MIME headers\n");
258                 BIO_printf (bio_err, "-CApath dir    trusted certificates directory\n");
259                 BIO_printf (bio_err, "-CAfile file   trusted certificates file\n");
260                 BIO_printf (bio_err, "cert.pem       recipient certificate(s)\n");
261                 goto end;
262         }
263
264         ret = 2;
265
266         if(operation != SMIME_SIGN) flags &= ~PKCS7_DETACHED;
267
268         if(flags & PKCS7_BINARY) {
269                 if(operation & SMIME_OP) inmode = "rb";
270                 else outmode = "rb";
271         }
272
273         if(operation == SMIME_ENCRYPT) {
274                 if (!cipher) cipher = EVP_rc2_40_cbc();
275                 encerts = sk_X509_new_null();
276                 while (*args) {
277                         if(!(cert = load_cert(*args))) {
278                                 BIO_printf(bio_err, "Can't read recipent certificate file %s\n", *args);
279                                 goto end;
280                         }
281                         sk_X509_push(encerts, cert);
282                         cert = NULL;
283                         args++;
284                 }
285         }
286
287         if(signerfile && (operation == SMIME_SIGN)) {
288                 if(!(signer = load_cert(signerfile))) {
289                         BIO_printf(bio_err, "Can't read signer certificate file %s\n", signerfile);
290                         goto end;
291                 }
292         }
293
294         if(certfile) {
295                 if(!(other = load_certs(certfile))) {
296                         BIO_printf(bio_err, "Can't read certificate file %s\n", certfile);
297                         ERR_print_errors(bio_err);
298                         goto end;
299                 }
300         }
301
302         if(recipfile && (operation == SMIME_DECRYPT)) {
303                 if(!(recip = load_cert(recipfile))) {
304                         BIO_printf(bio_err, "Can't read recipient certificate file %s\n", recipfile);
305                         ERR_print_errors(bio_err);
306                         goto end;
307                 }
308         }
309
310         if(operation == SMIME_DECRYPT) {
311                 if(!keyfile) keyfile = recipfile;
312         } else if(operation == SMIME_SIGN) {
313                 if(!keyfile) keyfile = signerfile;
314         } else keyfile = NULL;
315
316         if(keyfile) {
317                 if(!(key = load_key(keyfile, passin))) {
318                         BIO_printf(bio_err, "Can't read recipient certificate file %s\n", keyfile);
319                         ERR_print_errors(bio_err);
320                         goto end;
321                 }
322         }
323
324         if (infile) {
325                 if (!(in = BIO_new_file(infile, inmode))) {
326                         BIO_printf (bio_err,
327                                  "Can't open input file %s\n", infile);
328                         goto end;
329                 }
330         } else in = BIO_new_fp(stdin, BIO_NOCLOSE);
331
332         if (outfile) {
333                 if (!(out = BIO_new_file(outfile, outmode))) {
334                         BIO_printf (bio_err,
335                                  "Can't open output file %s\n", outfile);
336                         goto end;
337                 }
338         } else out = BIO_new_fp(stdout, BIO_NOCLOSE);
339
340         if(operation == SMIME_VERIFY)
341                 if(!(store = setup_verify(CAfile, CApath))) goto end;
342
343         ret = 3;
344
345         if(operation == SMIME_ENCRYPT) {
346                 p7 = PKCS7_encrypt(encerts, in, cipher, flags);
347         } else if(operation == SMIME_SIGN) {
348                 p7 = PKCS7_sign(signer, key, other, in, flags);
349                 BIO_reset(in);
350         } else {
351                 if(!(p7 = SMIME_read_PKCS7(in, &indata))) {
352                         BIO_printf(bio_err, "Error reading S/MIME message\n");
353                         goto end;
354                 }
355         }
356
357         if(!p7) {
358                 BIO_printf(bio_err, "Error creating PKCS#7 structure\n");
359                 goto end;
360         }
361
362         ret = 4;
363         if(operation == SMIME_DECRYPT) {
364                 if(!PKCS7_decrypt(p7, key, recip, out, flags)) {
365                         BIO_printf(bio_err, "Error decrypting PKCS#7 structure\n");
366                         goto end;
367                 }
368         } else if(operation == SMIME_VERIFY) {
369                 STACK_OF(X509) *signers;
370                 if(PKCS7_verify(p7, other, store, indata, out, flags)) {
371                         BIO_printf(bio_err, "Verification Successful\n");
372                 } else {
373                         BIO_printf(bio_err, "Verification Failure\n");
374                         goto end;
375                 }
376                 signers = PKCS7_iget_signers(p7, other, flags);
377                 if(!save_certs(signerfile, signers)) {
378                         BIO_printf(bio_err, "Error writing signers to %s\n",
379                                                                 signerfile);
380                         ret = 5;
381                         goto end;
382                 }
383                 sk_X509_free(signers);
384         } else if(operation == SMIME_PK7OUT) {
385                 PEM_write_bio_PKCS7(out, p7);
386         } else {
387                 if(to) BIO_printf(out, "To: %s\n", to);
388                 if(from) BIO_printf(out, "From: %s\n", from);
389                 if(subject) BIO_printf(out, "Subject: %s\n", subject);
390                 SMIME_write_PKCS7(out, p7, in, flags);
391         }
392         ret = 0;
393 end:
394         if(ret) ERR_print_errors(bio_err);
395         sk_X509_pop_free(encerts, X509_free);
396         sk_X509_pop_free(other, X509_free);
397         X509_STORE_free(store);
398         X509_free(cert);
399         X509_free(recip);
400         X509_free(signer);
401         EVP_PKEY_free(key);
402         PKCS7_free(p7);
403         BIO_free(in);
404         BIO_free(indata);
405         BIO_free(out);
406         return (ret);
407 }
408
409 static X509 *load_cert(char *file)
410 {
411         BIO *in;
412         X509 *cert;
413         if(!(in = BIO_new_file(file, "r"))) return NULL;
414         cert = PEM_read_bio_X509(in, NULL, NULL,NULL);
415         BIO_free(in);
416         return cert;
417 }
418
419 static EVP_PKEY *load_key(char *file, char *pass)
420 {
421         BIO *in;
422         EVP_PKEY *key;
423         if(!(in = BIO_new_file(file, "r"))) return NULL;
424         key = PEM_read_bio_PrivateKey(in, NULL,PEM_cb,pass);
425         BIO_free(in);
426         return key;
427 }
428
429 static STACK_OF(X509) *load_certs(char *file)
430 {
431         BIO *in;
432         int i;
433         STACK_OF(X509) *othercerts;
434         STACK_OF(X509_INFO) *allcerts;
435         X509_INFO *xi;
436         if(!(in = BIO_new_file(file, "r"))) return NULL;
437         othercerts = sk_X509_new(NULL);
438         if(!othercerts) return NULL;
439         allcerts = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL);
440         for(i = 0; i < sk_X509_INFO_num(allcerts); i++) {
441                 xi = sk_X509_INFO_value (allcerts, i);
442                 if (xi->x509) {
443                         sk_X509_push(othercerts, xi->x509);
444                         xi->x509 = NULL;
445                 }
446         }
447         sk_X509_INFO_pop_free(allcerts, X509_INFO_free);
448         BIO_free(in);
449         return othercerts;
450 }
451
452 static X509_STORE *setup_verify(char *CAfile, char *CApath)
453 {
454         X509_STORE *store;
455         X509_LOOKUP *lookup;
456         if(!(store = X509_STORE_new())) goto end;
457         lookup=X509_STORE_add_lookup(store,X509_LOOKUP_file());
458         if (lookup == NULL) goto end;
459         if (CAfile) {
460                 if(!X509_LOOKUP_load_file(lookup,CAfile,X509_FILETYPE_PEM)) {
461                         BIO_printf(bio_err, "Error loading file %s\n", CAfile);
462                         goto end;
463                 }
464         } else X509_LOOKUP_load_file(lookup,NULL,X509_FILETYPE_DEFAULT);
465                 
466         lookup=X509_STORE_add_lookup(store,X509_LOOKUP_hash_dir());
467         if (lookup == NULL) goto end;
468         if (CApath) {
469                 if(!X509_LOOKUP_add_dir(lookup,CApath,X509_FILETYPE_PEM)) {
470                         BIO_printf(bio_err, "Error loading directory %s\n", CApath);
471                         goto end;
472                 }
473         } else X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT);
474
475         ERR_clear_error();
476         return store;
477         end:
478         X509_STORE_free(store);
479         return NULL;
480 }
481
482 int save_certs(char *signerfile, STACK_OF(X509) *signers)
483 {
484         int i;
485         BIO *tmp;
486         if(!signerfile) return 1;
487         tmp = BIO_new_file(signerfile, "w");
488         if(!tmp) return 0;
489         for(i = 0; i < sk_X509_num(signers); i++)
490                 PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
491         BIO_free(tmp);
492         return 1;
493 }
494