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