Add support for -no-CApath and -no-CAfile options
[openssl.git] / apps / smime.c
1 /*
2  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3  * project.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999-2004 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 #include <openssl/x509_vfy.h>
68 #include <openssl/x509v3.h>
69
70 static int save_certs(char *signerfile, STACK_OF(X509) *signers);
71 static int smime_cb(int ok, X509_STORE_CTX *ctx);
72
73 #define SMIME_OP        0x10
74 #define SMIME_IP        0x20
75 #define SMIME_SIGNERS   0x40
76 #define SMIME_ENCRYPT   (1 | SMIME_OP)
77 #define SMIME_DECRYPT   (2 | SMIME_IP)
78 #define SMIME_SIGN      (3 | SMIME_OP | SMIME_SIGNERS)
79 #define SMIME_VERIFY    (4 | SMIME_IP)
80 #define SMIME_PK7OUT    (5 | SMIME_IP | SMIME_OP)
81 #define SMIME_RESIGN    (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
82
83 typedef enum OPTION_choice {
84     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
85     OPT_ENCRYPT, OPT_DECRYPT, OPT_SIGN, OPT_RESIGN, OPT_VERIFY,
86     OPT_PK7OUT, OPT_TEXT, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCHAIN,
87     OPT_NOCERTS, OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP,
88     OPT_BINARY, OPT_NOSIGS, OPT_STREAM, OPT_INDEF, OPT_NOINDEF,
89     OPT_NOOLDMIME, OPT_CRLFEOL, OPT_RAND, OPT_ENGINE, OPT_PASSIN,
90     OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP, OPT_MD,
91     OPT_CIPHER, OPT_INKEY, OPT_KEYFORM, OPT_CERTFILE, OPT_CAFILE,
92     OPT_V_ENUM,
93     OPT_CAPATH, OPT_NOCAFILE, OPT_NOCAPATH, OPT_IN, OPT_INFORM, OPT_OUT,
94     OPT_OUTFORM, OPT_CONTENT
95 } OPTION_CHOICE;
96
97 OPTIONS smime_options[] = {
98     {OPT_HELP_STR, 1, '-', "Usage: %s [options] cert.pem...\n"},
99     {OPT_HELP_STR, 1, '-',
100         "  cert.pem... recipient certs for encryption\n"},
101     {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
102     {"help", OPT_HELP, '-', "Display this summary"},
103     {"encrypt", OPT_ENCRYPT, '-', "Encrypt message"},
104     {"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"},
105     {"sign", OPT_SIGN, '-', "Sign message"},
106     {"verify", OPT_VERIFY, '-', "Verify signed message"},
107     {"pk7out", OPT_PK7OUT, '-', "Output PKCS#7 structure"},
108     {"nointern", OPT_NOINTERN, '-',
109      "Don't search certificates in message for signer"},
110     {"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"},
111     {"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"},
112     {"nocerts", OPT_NOCERTS, '-',
113      "Don't include signers certificate when signing"},
114     {"nodetach", OPT_NODETACH, '-', "Use opaque signing"},
115     {"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"},
116     {"binary", OPT_BINARY, '-', "Don't translate message to text"},
117     {"certfile", OPT_CERTFILE, '<', "Other certificates file"},
118     {"signer", OPT_SIGNER, '<', "Signer certificate file"},
119     {"recip", OPT_RECIP, '<', "Recipient certificate file for decryption"},
120     {"in", OPT_IN, '<', "Input file"},
121     {"inform", OPT_INFORM, 'F', "Input format SMIME (default), PEM or DER"},
122     {"inkey", OPT_INKEY, '<',
123      "Input private key (if not signer or recipient)"},
124     {"keyform", OPT_KEYFORM, 'f', "Input private key format (PEM or ENGINE)"},
125     {"out", OPT_OUT, '>', "Output file"},
126     {"outform", OPT_OUTFORM, 'F',
127      "Output format SMIME (default), PEM or DER"},
128     {"content", OPT_CONTENT, '<',
129      "Supply or override content for detached signature"},
130     {"to", OPT_TO, 's', "To address"},
131     {"from", OPT_FROM, 's', "From address"},
132     {"subject", OPT_SUBJECT, 's', "Subject"},
133     {"text", OPT_TEXT, '-', "Include or delete text MIME headers"},
134     {"CApath", OPT_CAPATH, '/', "Trusted certificates directory"},
135     {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
136     {"no-CAfile", OPT_NOCAFILE, '-',
137      "Do not load the default certificates file"},
138     {"no-CApath", OPT_NOCAPATH, '-',
139      "Do not load certificates from the default certificates directory"},
140     {"resign", OPT_RESIGN, '-'},
141     {"nochain", OPT_NOCHAIN, '-'},
142     {"nosmimecap", OPT_NOSMIMECAP, '-'},
143     {"stream", OPT_STREAM, '-'},
144     {"indef", OPT_INDEF, '-'},
145     {"noindef", OPT_NOINDEF, '-'},
146     {"nooldmime", OPT_NOOLDMIME, '-'},
147     {"crlfeol", OPT_CRLFEOL, '-'},
148     {"rand", OPT_RAND, 's',
149      "Load the file(s) into the random number generator"},
150     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
151     {"md", OPT_MD, 's'},
152     {"", OPT_CIPHER, '-', "Any supported cipher"},
153     OPT_V_OPTIONS,
154 #ifndef OPENSSL_NO_ENGINE
155     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
156 #endif
157     {NULL}
158 };
159
160 int smime_main(int argc, char **argv)
161 {
162     BIO *in = NULL, *out = NULL, *indata = NULL;
163     EVP_PKEY *key = NULL;
164     PKCS7 *p7 = NULL;
165     STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
166     STACK_OF(X509) *encerts = NULL, *other = NULL;
167     X509 *cert = NULL, *recip = NULL, *signer = NULL;
168     X509_STORE *store = NULL;
169     X509_VERIFY_PARAM *vpm = NULL;
170     const EVP_CIPHER *cipher = NULL;
171     const EVP_MD *sign_md = NULL;
172     char *CAfile = NULL, *CApath = NULL, *inrand = NULL;
173     char *certfile = NULL, *keyfile = NULL, *contfile = NULL, *prog;
174     char *infile = NULL, *outfile = NULL, *signerfile = NULL, *recipfile =
175         NULL;
176     char *passinarg = NULL, *passin = NULL, *to = NULL, *from =
177         NULL, *subject = NULL;
178     OPTION_CHOICE o;
179     int noCApath = 0, noCAfile = 0;
180     int flags = PKCS7_DETACHED, operation = 0, ret = 0, need_rand = 0, indef =
181         0;
182     int informat = FORMAT_SMIME, outformat = FORMAT_SMIME, keyform =
183         FORMAT_PEM;
184     int vpmtouched = 0, rv = 0;
185     ENGINE *e = NULL;
186
187     if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
188         return 1;
189
190     prog = opt_init(argc, argv, smime_options);
191     while ((o = opt_next()) != OPT_EOF) {
192         switch (o) {
193         case OPT_EOF:
194         case OPT_ERR:
195  opthelp:
196             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
197             goto end;
198         case OPT_HELP:
199             opt_help(smime_options);
200             ret = 0;
201             goto end;
202         case OPT_INFORM:
203             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
204                 goto opthelp;
205             break;
206         case OPT_IN:
207             infile = opt_arg();
208             break;
209         case OPT_OUTFORM:
210             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
211                 goto opthelp;
212             break;
213         case OPT_OUT:
214             outfile = opt_arg();
215             break;
216         case OPT_ENCRYPT:
217             operation = SMIME_ENCRYPT;
218             break;
219         case OPT_DECRYPT:
220             operation = SMIME_DECRYPT;
221             break;
222         case OPT_SIGN:
223             operation = SMIME_SIGN;
224             break;
225         case OPT_RESIGN:
226             operation = SMIME_RESIGN;
227             break;
228         case OPT_VERIFY:
229             operation = SMIME_VERIFY;
230             break;
231         case OPT_PK7OUT:
232             operation = SMIME_PK7OUT;
233             break;
234         case OPT_TEXT:
235             flags |= PKCS7_TEXT;
236             break;
237         case OPT_NOINTERN:
238             flags |= PKCS7_NOINTERN;
239             break;
240         case OPT_NOVERIFY:
241             flags |= PKCS7_NOVERIFY;
242             break;
243         case OPT_NOCHAIN:
244             flags |= PKCS7_NOCHAIN;
245             break;
246         case OPT_NOCERTS:
247             flags |= PKCS7_NOCERTS;
248             break;
249         case OPT_NOATTR:
250             flags |= PKCS7_NOATTR;
251             break;
252         case OPT_NODETACH:
253             flags &= ~PKCS7_DETACHED;
254             break;
255         case OPT_NOSMIMECAP:
256             flags |= PKCS7_NOSMIMECAP;
257             break;
258         case OPT_BINARY:
259             flags |= PKCS7_BINARY;
260             break;
261         case OPT_NOSIGS:
262             flags |= PKCS7_NOSIGS;
263             break;
264         case OPT_STREAM:
265         case OPT_INDEF:
266             indef = 1;
267             break;
268         case OPT_NOINDEF:
269             indef = 0;
270             break;
271         case OPT_NOOLDMIME:
272             flags |= PKCS7_NOOLDMIMETYPE;
273             break;
274         case OPT_CRLFEOL:
275             flags |= PKCS7_CRLFEOL;
276             break;
277         case OPT_RAND:
278             inrand = opt_arg();
279             need_rand = 1;
280             break;
281         case OPT_ENGINE:
282             e = setup_engine(opt_arg(), 0);
283             break;
284         case OPT_PASSIN:
285             passinarg = opt_arg();
286             break;
287         case OPT_TO:
288             to = opt_arg();
289             break;
290         case OPT_FROM:
291             from = opt_arg();
292             break;
293         case OPT_SUBJECT:
294             subject = opt_arg();
295             break;
296         case OPT_SIGNER:
297             /* If previous -signer argument add signer to list */
298             if (signerfile) {
299                 if (sksigners == NULL
300                     && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
301                     goto end;
302                 sk_OPENSSL_STRING_push(sksigners, signerfile);
303                 if (keyfile == NULL)
304                     keyfile = signerfile;
305                 if (skkeys == NULL
306                     && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
307                     goto end;
308                 sk_OPENSSL_STRING_push(skkeys, keyfile);
309                 keyfile = NULL;
310             }
311             signerfile = opt_arg();
312             break;
313         case OPT_RECIP:
314             recipfile = opt_arg();
315             break;
316         case OPT_MD:
317             if (!opt_md(opt_arg(), &sign_md))
318                 goto opthelp;
319             break;
320         case OPT_CIPHER:
321             if (!opt_cipher(opt_unknown(), &cipher))
322                 goto opthelp;
323             break;
324         case OPT_INKEY:
325             /* If previous -inkey arument add signer to list */
326             if (keyfile) {
327                 if (signerfile == NULL) {
328                     BIO_printf(bio_err,
329                                "%s: Must have -signer before -inkey\n", prog);
330                     goto opthelp;
331                 }
332                 if (sksigners == NULL
333                     && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
334                     goto end;
335                 sk_OPENSSL_STRING_push(sksigners, signerfile);
336                 signerfile = NULL;
337                 if (skkeys == NULL
338                     && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
339                     goto end;
340                 sk_OPENSSL_STRING_push(skkeys, keyfile);
341             }
342             keyfile = opt_arg();
343             break;
344         case OPT_KEYFORM:
345             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
346                 goto opthelp;
347             break;
348         case OPT_CERTFILE:
349             certfile = opt_arg();
350             break;
351         case OPT_CAFILE:
352             CAfile = opt_arg();
353             break;
354         case OPT_CAPATH:
355             CApath = opt_arg();
356             break;
357         case OPT_NOCAFILE:
358             noCAfile = 1;
359             break;
360         case OPT_NOCAPATH:
361             noCApath = 1;
362             break;
363         case OPT_CONTENT:
364             contfile = opt_arg();
365             break;
366         case OPT_V_CASES:
367             if (!opt_verify(o, vpm))
368                 goto opthelp;
369             vpmtouched++;
370             break;
371         }
372     }
373     argc = opt_num_rest();
374     argv = opt_rest();
375
376     if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) {
377         BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
378         goto opthelp;
379     }
380
381     if (operation & SMIME_SIGNERS) {
382         /* Check to see if any final signer needs to be appended */
383         if (keyfile && !signerfile) {
384             BIO_puts(bio_err, "Illegal -inkey without -signer\n");
385             goto opthelp;
386         }
387         if (signerfile) {
388             if (!sksigners
389                 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
390                 goto end;
391             sk_OPENSSL_STRING_push(sksigners, signerfile);
392             if (!skkeys && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
393                 goto end;
394             if (!keyfile)
395                 keyfile = signerfile;
396             sk_OPENSSL_STRING_push(skkeys, keyfile);
397         }
398         if (!sksigners) {
399             BIO_printf(bio_err, "No signer certificate specified\n");
400             goto opthelp;
401         }
402         signerfile = NULL;
403         keyfile = NULL;
404         need_rand = 1;
405     } else if (operation == SMIME_DECRYPT) {
406         if (!recipfile && !keyfile) {
407             BIO_printf(bio_err,
408                        "No recipient certificate or key specified\n");
409             goto opthelp;
410         }
411     } else if (operation == SMIME_ENCRYPT) {
412         if (argc == 0) {
413             BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
414             goto opthelp;
415         }
416         need_rand = 1;
417     } else if (!operation)
418         goto opthelp;
419
420     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
421         BIO_printf(bio_err, "Error getting password\n");
422         goto end;
423     }
424
425     if (!app_load_modules(NULL))
426         goto end;
427
428     if (need_rand) {
429         app_RAND_load_file(NULL, (inrand != NULL));
430         if (inrand != NULL)
431             BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
432                        app_RAND_load_files(inrand));
433     }
434
435     ret = 2;
436
437     if (!(operation & SMIME_SIGNERS))
438         flags &= ~PKCS7_DETACHED;
439
440     if (!(operation & SMIME_OP)) {
441         if (flags & PKCS7_BINARY)
442             outformat = FORMAT_BINARY;
443     }
444
445     if (!(operation & SMIME_IP)) {
446         if (flags & PKCS7_BINARY)
447             informat = FORMAT_BINARY;
448     }
449
450     if (operation == SMIME_ENCRYPT) {
451         if (!cipher) {
452 #ifndef OPENSSL_NO_DES
453             cipher = EVP_des_ede3_cbc();
454 #else
455             BIO_printf(bio_err, "No cipher selected\n");
456             goto end;
457 #endif
458         }
459         encerts = sk_X509_new_null();
460         if (!encerts)
461             goto end;
462         while (*argv) {
463             cert = load_cert(*argv, FORMAT_PEM,
464                              NULL, e, "recipient certificate file");
465             if (cert == NULL)
466                 goto end;
467             sk_X509_push(encerts, cert);
468             cert = NULL;
469             argv++;
470         }
471     }
472
473     if (certfile) {
474         if ((other = load_certs(certfile, FORMAT_PEM, NULL,
475                                  e, "certificate file")) == NULL) {
476             ERR_print_errors(bio_err);
477             goto end;
478         }
479     }
480
481     if (recipfile && (operation == SMIME_DECRYPT)) {
482         if ((recip = load_cert(recipfile, FORMAT_PEM, NULL,
483                                 e, "recipient certificate file")) == NULL) {
484             ERR_print_errors(bio_err);
485             goto end;
486         }
487     }
488
489     if (operation == SMIME_DECRYPT) {
490         if (!keyfile)
491             keyfile = recipfile;
492     } else if (operation == SMIME_SIGN) {
493         if (!keyfile)
494             keyfile = signerfile;
495     } else
496         keyfile = NULL;
497
498     if (keyfile) {
499         key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
500         if (!key)
501             goto end;
502     }
503
504     in = bio_open_default(infile, 'r', informat);
505     if (in == NULL)
506         goto end;
507
508     if (operation & SMIME_IP) {
509         if (informat == FORMAT_SMIME)
510             p7 = SMIME_read_PKCS7(in, &indata);
511         else if (informat == FORMAT_PEM)
512             p7 = PEM_read_bio_PKCS7(in, NULL, NULL, NULL);
513         else if (informat == FORMAT_ASN1)
514             p7 = d2i_PKCS7_bio(in, NULL);
515         else {
516             BIO_printf(bio_err, "Bad input format for PKCS#7 file\n");
517             goto end;
518         }
519
520         if (!p7) {
521             BIO_printf(bio_err, "Error reading S/MIME message\n");
522             goto end;
523         }
524         if (contfile) {
525             BIO_free(indata);
526             if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
527                 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
528                 goto end;
529             }
530         }
531     }
532
533     out = bio_open_default(outfile, 'w', outformat);
534     if (out == NULL)
535         goto end;
536
537     if (operation == SMIME_VERIFY) {
538         if ((store = setup_verify(CAfile, CApath, noCAfile, noCApath)) == NULL)
539             goto end;
540         X509_STORE_set_verify_cb(store, smime_cb);
541         if (vpmtouched)
542             X509_STORE_set1_param(store, vpm);
543     }
544
545     ret = 3;
546
547     if (operation == SMIME_ENCRYPT) {
548         if (indef)
549             flags |= PKCS7_STREAM;
550         p7 = PKCS7_encrypt(encerts, in, cipher, flags);
551     } else if (operation & SMIME_SIGNERS) {
552         int i;
553         /*
554          * If detached data content we only enable streaming if S/MIME output
555          * format.
556          */
557         if (operation == SMIME_SIGN) {
558             if (flags & PKCS7_DETACHED) {
559                 if (outformat == FORMAT_SMIME)
560                     flags |= PKCS7_STREAM;
561             } else if (indef)
562                 flags |= PKCS7_STREAM;
563             flags |= PKCS7_PARTIAL;
564             p7 = PKCS7_sign(NULL, NULL, other, in, flags);
565             if (!p7)
566                 goto end;
567             if (flags & PKCS7_NOCERTS) {
568                 for (i = 0; i < sk_X509_num(other); i++) {
569                     X509 *x = sk_X509_value(other, i);
570                     PKCS7_add_certificate(p7, x);
571                 }
572             }
573         } else
574             flags |= PKCS7_REUSE_DIGEST;
575         for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
576             signerfile = sk_OPENSSL_STRING_value(sksigners, i);
577             keyfile = sk_OPENSSL_STRING_value(skkeys, i);
578             signer = load_cert(signerfile, FORMAT_PEM, NULL,
579                                e, "signer certificate");
580             if (!signer)
581                 goto end;
582             key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
583             if (!key)
584                 goto end;
585             if (!PKCS7_sign_add_signer(p7, signer, key, sign_md, flags))
586                 goto end;
587             X509_free(signer);
588             signer = NULL;
589             EVP_PKEY_free(key);
590             key = NULL;
591         }
592         /* If not streaming or resigning finalize structure */
593         if ((operation == SMIME_SIGN) && !(flags & PKCS7_STREAM)) {
594             if (!PKCS7_final(p7, in, flags))
595                 goto end;
596         }
597     }
598
599     if (!p7) {
600         BIO_printf(bio_err, "Error creating PKCS#7 structure\n");
601         goto end;
602     }
603
604     ret = 4;
605     if (operation == SMIME_DECRYPT) {
606         if (!PKCS7_decrypt(p7, key, recip, out, flags)) {
607             BIO_printf(bio_err, "Error decrypting PKCS#7 structure\n");
608             goto end;
609         }
610     } else if (operation == SMIME_VERIFY) {
611         STACK_OF(X509) *signers;
612         if (PKCS7_verify(p7, other, store, indata, out, flags))
613             BIO_printf(bio_err, "Verification successful\n");
614         else {
615             BIO_printf(bio_err, "Verification failure\n");
616             goto end;
617         }
618         signers = PKCS7_get0_signers(p7, other, flags);
619         if (!save_certs(signerfile, signers)) {
620             BIO_printf(bio_err, "Error writing signers to %s\n", signerfile);
621             ret = 5;
622             goto end;
623         }
624         sk_X509_free(signers);
625     } else if (operation == SMIME_PK7OUT)
626         PEM_write_bio_PKCS7(out, p7);
627     else {
628         if (to)
629             BIO_printf(out, "To: %s\n", to);
630         if (from)
631             BIO_printf(out, "From: %s\n", from);
632         if (subject)
633             BIO_printf(out, "Subject: %s\n", subject);
634         if (outformat == FORMAT_SMIME) {
635             if (operation == SMIME_RESIGN)
636                 rv = SMIME_write_PKCS7(out, p7, indata, flags);
637             else
638                 rv = SMIME_write_PKCS7(out, p7, in, flags);
639         } else if (outformat == FORMAT_PEM)
640             rv = PEM_write_bio_PKCS7_stream(out, p7, in, flags);
641         else if (outformat == FORMAT_ASN1)
642             rv = i2d_PKCS7_bio_stream(out, p7, in, flags);
643         else {
644             BIO_printf(bio_err, "Bad output format for PKCS#7 file\n");
645             goto end;
646         }
647         if (rv == 0) {
648             BIO_printf(bio_err, "Error writing output\n");
649             ret = 3;
650             goto end;
651         }
652     }
653     ret = 0;
654  end:
655     if (need_rand)
656         app_RAND_write_file(NULL);
657     if (ret)
658         ERR_print_errors(bio_err);
659     sk_X509_pop_free(encerts, X509_free);
660     sk_X509_pop_free(other, X509_free);
661     X509_VERIFY_PARAM_free(vpm);
662     sk_OPENSSL_STRING_free(sksigners);
663     sk_OPENSSL_STRING_free(skkeys);
664     X509_STORE_free(store);
665     X509_free(cert);
666     X509_free(recip);
667     X509_free(signer);
668     EVP_PKEY_free(key);
669     PKCS7_free(p7);
670     BIO_free(in);
671     BIO_free(indata);
672     BIO_free_all(out);
673     OPENSSL_free(passin);
674     return (ret);
675 }
676
677 static int save_certs(char *signerfile, STACK_OF(X509) *signers)
678 {
679     int i;
680     BIO *tmp;
681     if (!signerfile)
682         return 1;
683     tmp = BIO_new_file(signerfile, "w");
684     if (!tmp)
685         return 0;
686     for (i = 0; i < sk_X509_num(signers); i++)
687         PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
688     BIO_free(tmp);
689     return 1;
690 }
691
692 /* Minimal callback just to output policy info (if any) */
693
694 static int smime_cb(int ok, X509_STORE_CTX *ctx)
695 {
696     int error;
697
698     error = X509_STORE_CTX_get_error(ctx);
699
700     if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
701         && ((error != X509_V_OK) || (ok != 2)))
702         return ok;
703
704     policies_print(ctx);
705
706     return ok;
707
708 }