3b809837e5476e34ad0bc55f71d62c2e2c68fdbf
[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 #ifndef NO_DES
114                 else if (!strcmp (*args, "-des3")) 
115                                 cipher = EVP_des_ede3_cbc();
116                 else if (!strcmp (*args, "-des")) 
117                                 cipher = EVP_des_cbc();
118 #endif
119 #ifndef NO_RC2
120                 else if (!strcmp (*args, "-rc2-40")) 
121                                 cipher = EVP_rc2_40_cbc();
122                 else if (!strcmp (*args, "-rc2-128")) 
123                                 cipher = EVP_rc2_cbc();
124                 else if (!strcmp (*args, "-rc2-64")) 
125                                 cipher = EVP_rc2_64_cbc();
126 #endif
127                 else if (!strcmp (*args, "-text")) 
128                                 flags |= PKCS7_TEXT;
129                 else if (!strcmp (*args, "-nointern")) 
130                                 flags |= PKCS7_NOINTERN;
131                 else if (!strcmp (*args, "-noverify")) 
132                                 flags |= PKCS7_NOVERIFY;
133                 else if (!strcmp (*args, "-nochain")) 
134                                 flags |= PKCS7_NOCHAIN;
135                 else if (!strcmp (*args, "-nocerts")) 
136                                 flags |= PKCS7_NOCERTS;
137                 else if (!strcmp (*args, "-noattr")) 
138                                 flags |= PKCS7_NOATTR;
139                 else if (!strcmp (*args, "-nodetach")) 
140                                 flags &= ~PKCS7_DETACHED;
141                 else if (!strcmp (*args, "-binary"))
142                                 flags |= PKCS7_BINARY;
143                 else if (!strcmp (*args, "-nosigs"))
144                                 flags |= PKCS7_NOSIGS;
145                 else if (!strcmp(*argv,"-passin")) {
146                         if (--argc < 1) badarg = 1;
147                         else passin= *(++argv);
148                 } else if (!strcmp(*argv,"-envpassin")) {
149                         if (--argc < 1) badarg = 1;
150                         else if(!(passin= getenv(*(++argv)))) {
151                                 BIO_printf(bio_err,
152                                  "Can't read environment variable %s\n",
153                                                                 *argv);
154                                 badarg = 1;
155                         }
156                 } else if (!strcmp (*args, "-to")) {
157                         if (args[1]) {
158                                 args++;
159                                 to = *args;
160                         } else badarg = 1;
161                 } else if (!strcmp (*args, "-from")) {
162                         if (args[1]) {
163                                 args++;
164                                 from = *args;
165                         } else badarg = 1;
166                 } else if (!strcmp (*args, "-subject")) {
167                         if (args[1]) {
168                                 args++;
169                                 subject = *args;
170                         } else badarg = 1;
171                 } else if (!strcmp (*args, "-signer")) {
172                         if (args[1]) {
173                                 args++;
174                                 signerfile = *args;
175                         } else badarg = 1;
176                 } else if (!strcmp (*args, "-recip")) {
177                         if (args[1]) {
178                                 args++;
179                                 recipfile = *args;
180                         } else badarg = 1;
181                 } else if (!strcmp (*args, "-inkey")) {
182                         if (args[1]) {
183                                 args++;
184                                 keyfile = *args;
185                         } else badarg = 1;
186                 } else if (!strcmp (*args, "-certfile")) {
187                         if (args[1]) {
188                                 args++;
189                                 certfile = *args;
190                         } else badarg = 1;
191                 } else if (!strcmp (*args, "-CAfile")) {
192                         if (args[1]) {
193                                 args++;
194                                 CAfile = *args;
195                         } else badarg = 1;
196                 } else if (!strcmp (*args, "-CApath")) {
197                         if (args[1]) {
198                                 args++;
199                                 CApath = *args;
200                         } else badarg = 1;
201                 } else if (!strcmp (*args, "-in")) {
202                         if (args[1]) {
203                                 args++;
204                                 infile = *args;
205                         } else badarg = 1;
206                 } else if (!strcmp (*args, "-out")) {
207                         if (args[1]) {
208                                 args++;
209                                 outfile = *args;
210                         } else badarg = 1;
211                 } else badarg = 1;
212                 args++;
213         }
214
215         if(operation == SMIME_SIGN) {
216                 if(!signerfile) {
217                         BIO_printf(bio_err, "No signer certificate specified\n");
218                         badarg = 1;
219                 }
220         } else if(operation == SMIME_DECRYPT) {
221                 if(!recipfile) {
222                         BIO_printf(bio_err, "No recipient certificate and key specified\n");
223                         badarg = 1;
224                 }
225         } else if(operation == SMIME_ENCRYPT) {
226                 if(!*args) {
227                         BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
228                         badarg = 1;
229                 }
230         } else if(!operation) badarg = 1;
231
232         if (badarg) {
233                 BIO_printf (bio_err, "Usage smime [options] cert.pem ...\n");
234                 BIO_printf (bio_err, "where options are\n");
235                 BIO_printf (bio_err, "-encrypt       encrypt message\n");
236                 BIO_printf (bio_err, "-decrypt       decrypt encrypted message\n");
237                 BIO_printf (bio_err, "-sign          sign message\n");
238                 BIO_printf (bio_err, "-verify        verify signed message\n");
239                 BIO_printf (bio_err, "-pk7out        output PKCS#7 structure\n");
240 #ifndef NO_DES
241                 BIO_printf (bio_err, "-des3          encrypt with triple DES\n");
242                 BIO_printf (bio_err, "-des           encrypt with DES\n");
243 #endif
244 #ifndef NO_RC2
245                 BIO_printf (bio_err, "-rc2-40        encrypt with RC2-40 (default)\n");
246                 BIO_printf (bio_err, "-rc2-64        encrypt with RC2-64\n");
247                 BIO_printf (bio_err, "-rc2-128       encrypt with RC2-128\n");
248 #endif
249                 BIO_printf (bio_err, "-nointern      don't search certificates in message for signer\n");
250                 BIO_printf (bio_err, "-nosigs        don't verify message signature\n");
251                 BIO_printf (bio_err, "-noverify      don't verify signers certificate\n");
252                 BIO_printf (bio_err, "-nocerts       don't include signers certificate when signing\n");
253                 BIO_printf (bio_err, "-nodetach      use opaque signing\n");
254                 BIO_printf (bio_err, "-noattr        don't include any signed attributes\n");
255                 BIO_printf (bio_err, "-binary        don't translate message to text\n");
256                 BIO_printf (bio_err, "-certfile file other certificates file\n");
257                 BIO_printf (bio_err, "-signer file   signer certificate file\n");
258                 BIO_printf (bio_err, "-recip  file   recipient certificate file for decryption\n");
259                 BIO_printf (bio_err, "-in file       input file\n");
260                 BIO_printf (bio_err, "-inkey file    input private key (if not signer or recipient)\n");
261                 BIO_printf (bio_err, "-out file      output file\n");
262                 BIO_printf (bio_err, "-to addr       to address\n");
263                 BIO_printf (bio_err, "-from ad       from address\n");
264                 BIO_printf (bio_err, "-subject s     subject\n");
265                 BIO_printf (bio_err, "-text          include or delete text MIME headers\n");
266                 BIO_printf (bio_err, "-CApath dir    trusted certificates directory\n");
267                 BIO_printf (bio_err, "-CAfile file   trusted certificates file\n");
268                 BIO_printf (bio_err, "cert.pem       recipient certificate(s) for encryption\n");
269                 goto end;
270         }
271
272         ret = 2;
273
274         if(operation != SMIME_SIGN) flags &= ~PKCS7_DETACHED;
275
276         if(flags & PKCS7_BINARY) {
277                 if(operation & SMIME_OP) inmode = "rb";
278                 else outmode = "rb";
279         }
280
281         if(operation == SMIME_ENCRYPT) {
282                 if (!cipher) {
283 #ifndef NO_RC2                  
284                         cipher = EVP_rc2_40_cbc();
285 #else
286                         BIO_printf(bio_err, "No cipher selected\n");
287                         goto end;
288 #endif
289                 }
290                 encerts = sk_X509_new_null();
291                 while (*args) {
292                         if(!(cert = load_cert(*args))) {
293                                 BIO_printf(bio_err, "Can't read recipent certificate file %s\n", *args);
294                                 goto end;
295                         }
296                         sk_X509_push(encerts, cert);
297                         cert = NULL;
298                         args++;
299                 }
300         }
301
302         if(signerfile && (operation == SMIME_SIGN)) {
303                 if(!(signer = load_cert(signerfile))) {
304                         BIO_printf(bio_err, "Can't read signer certificate file %s\n", signerfile);
305                         goto end;
306                 }
307         }
308
309         if(certfile) {
310                 if(!(other = load_certs(certfile))) {
311                         BIO_printf(bio_err, "Can't read certificate file %s\n", certfile);
312                         ERR_print_errors(bio_err);
313                         goto end;
314                 }
315         }
316
317         if(recipfile && (operation == SMIME_DECRYPT)) {
318                 if(!(recip = load_cert(recipfile))) {
319                         BIO_printf(bio_err, "Can't read recipient certificate file %s\n", recipfile);
320                         ERR_print_errors(bio_err);
321                         goto end;
322                 }
323         }
324
325         if(operation == SMIME_DECRYPT) {
326                 if(!keyfile) keyfile = recipfile;
327         } else if(operation == SMIME_SIGN) {
328                 if(!keyfile) keyfile = signerfile;
329         } else keyfile = NULL;
330
331         if(keyfile) {
332                 if(!(key = load_key(keyfile, passin))) {
333                         BIO_printf(bio_err, "Can't read recipient certificate file %s\n", keyfile);
334                         ERR_print_errors(bio_err);
335                         goto end;
336                 }
337         }
338
339         if (infile) {
340                 if (!(in = BIO_new_file(infile, inmode))) {
341                         BIO_printf (bio_err,
342                                  "Can't open input file %s\n", infile);
343                         goto end;
344                 }
345         } else in = BIO_new_fp(stdin, BIO_NOCLOSE);
346
347         if (outfile) {
348                 if (!(out = BIO_new_file(outfile, outmode))) {
349                         BIO_printf (bio_err,
350                                  "Can't open output file %s\n", outfile);
351                         goto end;
352                 }
353         } else out = BIO_new_fp(stdout, BIO_NOCLOSE);
354
355         if(operation == SMIME_VERIFY)
356                 if(!(store = setup_verify(CAfile, CApath))) goto end;
357
358         ret = 3;
359
360         if(operation == SMIME_ENCRYPT) {
361                 p7 = PKCS7_encrypt(encerts, in, cipher, flags);
362         } else if(operation == SMIME_SIGN) {
363                 p7 = PKCS7_sign(signer, key, other, in, flags);
364                 BIO_reset(in);
365         } else {
366                 if(!(p7 = SMIME_read_PKCS7(in, &indata))) {
367                         BIO_printf(bio_err, "Error reading S/MIME message\n");
368                         goto end;
369                 }
370         }
371
372         if(!p7) {
373                 BIO_printf(bio_err, "Error creating PKCS#7 structure\n");
374                 goto end;
375         }
376
377         ret = 4;
378         if(operation == SMIME_DECRYPT) {
379                 if(!PKCS7_decrypt(p7, key, recip, out, flags)) {
380                         BIO_printf(bio_err, "Error decrypting PKCS#7 structure\n");
381                         goto end;
382                 }
383         } else if(operation == SMIME_VERIFY) {
384                 STACK_OF(X509) *signers;
385                 if(PKCS7_verify(p7, other, store, indata, out, flags)) {
386                         BIO_printf(bio_err, "Verification Successful\n");
387                 } else {
388                         BIO_printf(bio_err, "Verification Failure\n");
389                         goto end;
390                 }
391                 signers = PKCS7_iget_signers(p7, other, flags);
392                 if(!save_certs(signerfile, signers)) {
393                         BIO_printf(bio_err, "Error writing signers to %s\n",
394                                                                 signerfile);
395                         ret = 5;
396                         goto end;
397                 }
398                 sk_X509_free(signers);
399         } else if(operation == SMIME_PK7OUT) {
400                 PEM_write_bio_PKCS7(out, p7);
401         } else {
402                 if(to) BIO_printf(out, "To: %s\n", to);
403                 if(from) BIO_printf(out, "From: %s\n", from);
404                 if(subject) BIO_printf(out, "Subject: %s\n", subject);
405                 SMIME_write_PKCS7(out, p7, in, flags);
406         }
407         ret = 0;
408 end:
409         if(ret) ERR_print_errors(bio_err);
410         sk_X509_pop_free(encerts, X509_free);
411         sk_X509_pop_free(other, X509_free);
412         X509_STORE_free(store);
413         X509_free(cert);
414         X509_free(recip);
415         X509_free(signer);
416         EVP_PKEY_free(key);
417         PKCS7_free(p7);
418         BIO_free(in);
419         BIO_free(indata);
420         BIO_free(out);
421         return (ret);
422 }
423
424 static X509 *load_cert(char *file)
425 {
426         BIO *in;
427         X509 *cert;
428         if(!(in = BIO_new_file(file, "r"))) return NULL;
429         cert = PEM_read_bio_X509(in, NULL, NULL,NULL);
430         BIO_free(in);
431         return cert;
432 }
433
434 static EVP_PKEY *load_key(char *file, char *pass)
435 {
436         BIO *in;
437         EVP_PKEY *key;
438         if(!(in = BIO_new_file(file, "r"))) return NULL;
439         key = PEM_read_bio_PrivateKey(in, NULL,PEM_cb,pass);
440         BIO_free(in);
441         return key;
442 }
443
444 static STACK_OF(X509) *load_certs(char *file)
445 {
446         BIO *in;
447         int i;
448         STACK_OF(X509) *othercerts;
449         STACK_OF(X509_INFO) *allcerts;
450         X509_INFO *xi;
451         if(!(in = BIO_new_file(file, "r"))) return NULL;
452         othercerts = sk_X509_new(NULL);
453         if(!othercerts) return NULL;
454         allcerts = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL);
455         for(i = 0; i < sk_X509_INFO_num(allcerts); i++) {
456                 xi = sk_X509_INFO_value (allcerts, i);
457                 if (xi->x509) {
458                         sk_X509_push(othercerts, xi->x509);
459                         xi->x509 = NULL;
460                 }
461         }
462         sk_X509_INFO_pop_free(allcerts, X509_INFO_free);
463         BIO_free(in);
464         return othercerts;
465 }
466
467 static X509_STORE *setup_verify(char *CAfile, char *CApath)
468 {
469         X509_STORE *store;
470         X509_LOOKUP *lookup;
471         if(!(store = X509_STORE_new())) goto end;
472         lookup=X509_STORE_add_lookup(store,X509_LOOKUP_file());
473         if (lookup == NULL) goto end;
474         if (CAfile) {
475                 if(!X509_LOOKUP_load_file(lookup,CAfile,X509_FILETYPE_PEM)) {
476                         BIO_printf(bio_err, "Error loading file %s\n", CAfile);
477                         goto end;
478                 }
479         } else X509_LOOKUP_load_file(lookup,NULL,X509_FILETYPE_DEFAULT);
480                 
481         lookup=X509_STORE_add_lookup(store,X509_LOOKUP_hash_dir());
482         if (lookup == NULL) goto end;
483         if (CApath) {
484                 if(!X509_LOOKUP_add_dir(lookup,CApath,X509_FILETYPE_PEM)) {
485                         BIO_printf(bio_err, "Error loading directory %s\n", CApath);
486                         goto end;
487                 }
488         } else X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT);
489
490         ERR_clear_error();
491         return store;
492         end:
493         X509_STORE_free(store);
494         return NULL;
495 }
496
497 int save_certs(char *signerfile, STACK_OF(X509) *signers)
498 {
499         int i;
500         BIO *tmp;
501         if(!signerfile) return 1;
502         tmp = BIO_new_file(signerfile, "w");
503         if(!tmp) return 0;
504         for(i = 0; i < sk_X509_num(signers); i++)
505                 PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
506         BIO_free(tmp);
507         return 1;
508 }
509