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