Fix safestack issues in x509.h
[openssl.git] / apps / smime.c
1 /*
2  * Copyright 1999-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* S/MIME utility function */
11
12 #include <stdio.h>
13 #include <string.h>
14 #include "apps.h"
15 #include "progs.h"
16 #include <openssl/crypto.h>
17 #include <openssl/pem.h>
18 #include <openssl/err.h>
19 #include <openssl/x509_vfy.h>
20 #include <openssl/x509v3.h>
21
22 DEFINE_STACK_OF_STRING()
23
24 static int save_certs(char *signerfile, STACK_OF(X509) *signers);
25 static int smime_cb(int ok, X509_STORE_CTX *ctx);
26
27 #define SMIME_OP        0x10
28 #define SMIME_IP        0x20
29 #define SMIME_SIGNERS   0x40
30 #define SMIME_ENCRYPT   (1 | SMIME_OP)
31 #define SMIME_DECRYPT   (2 | SMIME_IP)
32 #define SMIME_SIGN      (3 | SMIME_OP | SMIME_SIGNERS)
33 #define SMIME_VERIFY    (4 | SMIME_IP)
34 #define SMIME_PK7OUT    (5 | SMIME_IP | SMIME_OP)
35 #define SMIME_RESIGN    (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
36
37 typedef enum OPTION_choice {
38     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
39     OPT_ENCRYPT, OPT_DECRYPT, OPT_SIGN, OPT_RESIGN, OPT_VERIFY,
40     OPT_PK7OUT, OPT_TEXT, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCHAIN,
41     OPT_NOCERTS, OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP,
42     OPT_BINARY, OPT_NOSIGS, OPT_STREAM, OPT_INDEF, OPT_NOINDEF,
43     OPT_CRLFEOL, OPT_ENGINE, OPT_PASSIN,
44     OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP, OPT_MD,
45     OPT_CIPHER, OPT_INKEY, OPT_KEYFORM, OPT_CERTFILE, OPT_CAFILE,
46     OPT_CAPATH, OPT_CASTORE, OPT_NOCAFILE, OPT_NOCAPATH, OPT_NOCASTORE,
47     OPT_R_ENUM, OPT_PROV_ENUM, OPT_CONFIG,
48     OPT_V_ENUM,
49     OPT_IN, OPT_INFORM, OPT_OUT,
50     OPT_OUTFORM, OPT_CONTENT
51 } OPTION_CHOICE;
52
53 const OPTIONS smime_options[] = {
54     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"},
55
56     OPT_SECTION("General"),
57     {"help", OPT_HELP, '-', "Display this summary"},
58     {"in", OPT_IN, '<', "Input file"},
59     {"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"},
60     {"out", OPT_OUT, '>', "Output file"},
61     {"outform", OPT_OUTFORM, 'c',
62      "Output format SMIME (default), PEM or DER"},
63     {"inkey", OPT_INKEY, 's',
64      "Input private key (if not signer or recipient)"},
65     {"keyform", OPT_KEYFORM, 'f', "Input private key format (ENGINE, other values ignored)"},
66 #ifndef OPENSSL_NO_ENGINE
67     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
68 #endif
69     {"stream", OPT_STREAM, '-', "Enable CMS streaming" },
70     {"indef", OPT_INDEF, '-', "Same as -stream" },
71     {"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"},
72     OPT_CONFIG_OPTION,
73
74     OPT_SECTION("Action"),
75     {"encrypt", OPT_ENCRYPT, '-', "Encrypt message"},
76     {"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"},
77     {"sign", OPT_SIGN, '-', "Sign message"},
78     {"resign", OPT_RESIGN, '-', "Resign a signed message"},
79     {"verify", OPT_VERIFY, '-', "Verify signed message"},
80
81     OPT_SECTION("Signing/Encryption"),
82     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
83     {"md", OPT_MD, 's', "Digest algorithm to use when signing or resigning"},
84     {"", OPT_CIPHER, '-', "Any supported cipher"},
85     {"pk7out", OPT_PK7OUT, '-', "Output PKCS#7 structure"},
86     {"nointern", OPT_NOINTERN, '-',
87      "Don't search certificates in message for signer"},
88     {"nodetach", OPT_NODETACH, '-', "Use opaque signing"},
89     {"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"},
90     {"binary", OPT_BINARY, '-', "Don't translate message to text"},
91     {"signer", OPT_SIGNER, 's', "Signer certificate file"},
92     {"content", OPT_CONTENT, '<',
93      "Supply or override content for detached signature"},
94     {"nocerts", OPT_NOCERTS, '-',
95      "Don't include signers certificate when signing"},
96
97     OPT_SECTION("Verification/Decryption"),
98     {"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"},
99     {"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"},
100
101     {"certfile", OPT_CERTFILE, '<', "Other certificates file"},
102     {"recip", OPT_RECIP, '<', "Recipient certificate file for decryption"},
103
104     OPT_SECTION("Email"),
105     {"to", OPT_TO, 's', "To address"},
106     {"from", OPT_FROM, 's', "From address"},
107     {"subject", OPT_SUBJECT, 's', "Subject"},
108     {"text", OPT_TEXT, '-', "Include or delete text MIME headers"},
109     {"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"},
110
111     OPT_SECTION("Certificate chain"),
112     {"CApath", OPT_CAPATH, '/', "Trusted certificates directory"},
113     {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
114     {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"},
115     {"no-CAfile", OPT_NOCAFILE, '-',
116      "Do not load the default certificates file"},
117     {"no-CApath", OPT_NOCAPATH, '-',
118      "Do not load certificates from the default certificates directory"},
119     {"no-CAstore", OPT_NOCASTORE, '-',
120      "Do not load certificates from the default certificates store"},
121     {"nochain", OPT_NOCHAIN, '-',
122      "set PKCS7_NOCHAIN so certificates contained in the message are not used as untrusted CAs" },
123     {"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of CR only"},
124
125     OPT_R_OPTIONS,
126     OPT_V_OPTIONS,
127     OPT_PROV_OPTIONS,
128
129     OPT_PARAMETERS(),
130     {"cert", 0, 0, "Recipient certs, used when encrypting"},
131     {NULL}
132 };
133
134 int smime_main(int argc, char **argv)
135 {
136     CONF *conf = NULL;
137     BIO *in = NULL, *out = NULL, *indata = NULL;
138     EVP_PKEY *key = NULL;
139     PKCS7 *p7 = NULL;
140     STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
141     STACK_OF(X509) *encerts = NULL, *other = NULL;
142     X509 *cert = NULL, *recip = NULL, *signer = NULL;
143     X509_STORE *store = NULL;
144     X509_VERIFY_PARAM *vpm = NULL;
145     const EVP_CIPHER *cipher = NULL;
146     const EVP_MD *sign_md = NULL;
147     const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL, *prog = NULL;
148     char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
149     char *infile = NULL, *outfile = NULL, *signerfile = NULL, *recipfile = NULL;
150     char *passinarg = NULL, *passin = NULL, *to = NULL, *from = NULL, *subject = NULL;
151     OPTION_CHOICE o;
152     int noCApath = 0, noCAfile = 0, noCAstore = 0;
153     int flags = PKCS7_DETACHED, operation = 0, ret = 0, indef = 0;
154     int informat = FORMAT_SMIME, outformat = FORMAT_SMIME, keyform =
155         FORMAT_PEM;
156     int vpmtouched = 0, rv = 0;
157     ENGINE *e = NULL;
158     const char *mime_eol = "\n";
159     OPENSSL_CTX *libctx = app_get0_libctx();
160     const char *propq = app_get0_propq();
161
162     if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
163         return 1;
164
165     prog = opt_init(argc, argv, smime_options);
166     while ((o = opt_next()) != OPT_EOF) {
167         switch (o) {
168         case OPT_EOF:
169         case OPT_ERR:
170  opthelp:
171             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
172             goto end;
173         case OPT_HELP:
174             opt_help(smime_options);
175             ret = 0;
176             goto end;
177         case OPT_INFORM:
178             if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
179                 goto opthelp;
180             break;
181         case OPT_IN:
182             infile = opt_arg();
183             break;
184         case OPT_OUTFORM:
185             if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
186                 goto opthelp;
187             break;
188         case OPT_OUT:
189             outfile = opt_arg();
190             break;
191         case OPT_ENCRYPT:
192             operation = SMIME_ENCRYPT;
193             break;
194         case OPT_DECRYPT:
195             operation = SMIME_DECRYPT;
196             break;
197         case OPT_SIGN:
198             operation = SMIME_SIGN;
199             break;
200         case OPT_RESIGN:
201             operation = SMIME_RESIGN;
202             break;
203         case OPT_VERIFY:
204             operation = SMIME_VERIFY;
205             break;
206         case OPT_PK7OUT:
207             operation = SMIME_PK7OUT;
208             break;
209         case OPT_TEXT:
210             flags |= PKCS7_TEXT;
211             break;
212         case OPT_NOINTERN:
213             flags |= PKCS7_NOINTERN;
214             break;
215         case OPT_NOVERIFY:
216             flags |= PKCS7_NOVERIFY;
217             break;
218         case OPT_NOCHAIN:
219             flags |= PKCS7_NOCHAIN;
220             break;
221         case OPT_NOCERTS:
222             flags |= PKCS7_NOCERTS;
223             break;
224         case OPT_NOATTR:
225             flags |= PKCS7_NOATTR;
226             break;
227         case OPT_NODETACH:
228             flags &= ~PKCS7_DETACHED;
229             break;
230         case OPT_NOSMIMECAP:
231             flags |= PKCS7_NOSMIMECAP;
232             break;
233         case OPT_BINARY:
234             flags |= PKCS7_BINARY;
235             break;
236         case OPT_NOSIGS:
237             flags |= PKCS7_NOSIGS;
238             break;
239         case OPT_STREAM:
240         case OPT_INDEF:
241             indef = 1;
242             break;
243         case OPT_NOINDEF:
244             indef = 0;
245             break;
246         case OPT_CRLFEOL:
247             flags |= PKCS7_CRLFEOL;
248             mime_eol = "\r\n";
249             break;
250         case OPT_R_CASES:
251             if (!opt_rand(o))
252                 goto end;
253             break;
254         case OPT_PROV_CASES:
255             if (!opt_provider(o))
256                 goto end;
257             break;
258         case OPT_CONFIG:
259             conf = app_load_config_modules(opt_arg());
260             if (conf == NULL)
261                 goto end;
262             break;
263         case OPT_ENGINE:
264             e = setup_engine(opt_arg(), 0);
265             break;
266         case OPT_PASSIN:
267             passinarg = opt_arg();
268             break;
269         case OPT_TO:
270             to = opt_arg();
271             break;
272         case OPT_FROM:
273             from = opt_arg();
274             break;
275         case OPT_SUBJECT:
276             subject = opt_arg();
277             break;
278         case OPT_SIGNER:
279             /* If previous -signer argument add signer to list */
280             if (signerfile != NULL) {
281                 if (sksigners == NULL
282                     && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
283                     goto end;
284                 sk_OPENSSL_STRING_push(sksigners, signerfile);
285                 if (keyfile == NULL)
286                     keyfile = signerfile;
287                 if (skkeys == NULL
288                     && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
289                     goto end;
290                 sk_OPENSSL_STRING_push(skkeys, keyfile);
291                 keyfile = NULL;
292             }
293             signerfile = opt_arg();
294             break;
295         case OPT_RECIP:
296             recipfile = opt_arg();
297             break;
298         case OPT_MD:
299             if (!opt_md(opt_arg(), &sign_md))
300                 goto opthelp;
301             break;
302         case OPT_CIPHER:
303             if (!opt_cipher(opt_unknown(), &cipher))
304                 goto opthelp;
305             break;
306         case OPT_INKEY:
307             /* If previous -inkey argument add signer to list */
308             if (keyfile != NULL) {
309                 if (signerfile == NULL) {
310                     BIO_printf(bio_err,
311                                "%s: Must have -signer before -inkey\n", prog);
312                     goto opthelp;
313                 }
314                 if (sksigners == NULL
315                     && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
316                     goto end;
317                 sk_OPENSSL_STRING_push(sksigners, signerfile);
318                 signerfile = NULL;
319                 if (skkeys == NULL
320                     && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
321                     goto end;
322                 sk_OPENSSL_STRING_push(skkeys, keyfile);
323             }
324             keyfile = opt_arg();
325             break;
326         case OPT_KEYFORM:
327             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
328                 goto opthelp;
329             break;
330         case OPT_CERTFILE:
331             certfile = opt_arg();
332             break;
333         case OPT_CAFILE:
334             CAfile = opt_arg();
335             break;
336         case OPT_CAPATH:
337             CApath = opt_arg();
338             break;
339         case OPT_CASTORE:
340             CAstore = opt_arg();
341             break;
342         case OPT_NOCAFILE:
343             noCAfile = 1;
344             break;
345         case OPT_NOCAPATH:
346             noCApath = 1;
347             break;
348         case OPT_NOCASTORE:
349             noCAstore = 1;
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 != NULL || sksigners != NULL)) {
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 != NULL) {
376             if (sksigners == NULL
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 == NULL) {
387             BIO_printf(bio_err, "No signer certificate specified\n");
388             goto opthelp;
389         }
390         signerfile = NULL;
391         keyfile = NULL;
392     } else if (operation == SMIME_DECRYPT) {
393         if (recipfile == NULL && keyfile == NULL) {
394             BIO_printf(bio_err,
395                        "No recipient certificate or key specified\n");
396             goto opthelp;
397         }
398     } else if (operation == SMIME_ENCRYPT) {
399         if (argc == 0) {
400             BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
401             goto opthelp;
402         }
403     } else if (!operation) {
404         goto opthelp;
405     }
406
407     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
408         BIO_printf(bio_err, "Error getting password\n");
409         goto end;
410     }
411
412     ret = 2;
413
414     if (!(operation & SMIME_SIGNERS))
415         flags &= ~PKCS7_DETACHED;
416
417     if (!(operation & SMIME_OP)) {
418         if (flags & PKCS7_BINARY)
419             outformat = FORMAT_BINARY;
420     }
421
422     if (!(operation & SMIME_IP)) {
423         if (flags & PKCS7_BINARY)
424             informat = FORMAT_BINARY;
425     }
426
427     if (operation == SMIME_ENCRYPT) {
428         if (cipher == NULL) {
429 #ifndef OPENSSL_NO_DES
430             cipher = EVP_des_ede3_cbc();
431 #else
432             BIO_printf(bio_err, "No cipher selected\n");
433             goto end;
434 #endif
435         }
436         encerts = sk_X509_new_null();
437         if (encerts == NULL)
438             goto end;
439         while (*argv != NULL) {
440             cert = load_cert(*argv, FORMAT_UNDEF,
441                              "recipient certificate file");
442             if (cert == NULL)
443                 goto end;
444             sk_X509_push(encerts, cert);
445             cert = NULL;
446             argv++;
447         }
448     }
449
450     if (certfile != NULL) {
451         if (!load_certs(certfile, &other, NULL, "certificates")) {
452             ERR_print_errors(bio_err);
453             goto end;
454         }
455     }
456
457     if (recipfile != NULL && (operation == SMIME_DECRYPT)) {
458         if ((recip = load_cert(recipfile, FORMAT_UNDEF,
459                                "recipient certificate file")) == NULL) {
460             ERR_print_errors(bio_err);
461             goto end;
462         }
463     }
464
465     if (operation == SMIME_DECRYPT) {
466         if (keyfile == NULL)
467             keyfile = recipfile;
468     } else if (operation == SMIME_SIGN) {
469         if (keyfile == NULL)
470             keyfile = signerfile;
471     } else {
472         keyfile = NULL;
473     }
474
475     if (keyfile != NULL) {
476         key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
477         if (key == NULL)
478             goto end;
479
480         /*
481          * TODO: Remove this when CMS has full support for provider-native
482          * EVP_PKEYs
483          */
484         if (EVP_PKEY_get0(key) == NULL)
485             goto end;
486
487     }
488
489     in = bio_open_default(infile, 'r', informat);
490     if (in == NULL)
491         goto end;
492
493     if (operation & SMIME_IP) {
494         PKCS7 *p7_in = NULL;
495
496         p7 = PKCS7_new_with_libctx(libctx, propq);
497         if (p7 == NULL) {
498             BIO_printf(bio_err, "Error allocating PKCS7 object\n");
499             goto end;
500         }
501         if (informat == FORMAT_SMIME) {
502             p7_in = SMIME_read_PKCS7_ex(in, &indata, &p7);
503         } else if (informat == FORMAT_PEM) {
504             p7_in = PEM_read_bio_PKCS7(in, &p7, NULL, NULL);
505         } else if (informat == FORMAT_ASN1) {
506             p7_in = d2i_PKCS7_bio(in, &p7);
507         } else {
508             BIO_printf(bio_err, "Bad input format for PKCS#7 file\n");
509             goto end;
510         }
511
512         if (p7_in == NULL) {
513             BIO_printf(bio_err, "Error reading S/MIME message\n");
514             goto end;
515         }
516         if (contfile != NULL) {
517             BIO_free(indata);
518             if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
519                 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
520                 goto end;
521             }
522         }
523     }
524
525     out = bio_open_default(outfile, 'w', outformat);
526     if (out == NULL)
527         goto end;
528
529     if (operation == SMIME_VERIFY) {
530         if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
531                                   CAstore, noCAstore)) == NULL)
532             goto end;
533         X509_STORE_set_verify_cb(store, smime_cb);
534         if (vpmtouched)
535             X509_STORE_set1_param(store, vpm);
536     }
537
538     ret = 3;
539
540     if (operation == SMIME_ENCRYPT) {
541         if (indef)
542             flags |= PKCS7_STREAM;
543         p7 = PKCS7_encrypt_with_libctx(encerts, in, cipher, flags, libctx, propq);
544     } else if (operation & SMIME_SIGNERS) {
545         int i;
546         /*
547          * If detached data content we only enable streaming if S/MIME output
548          * format.
549          */
550         if (operation == SMIME_SIGN) {
551             if (flags & PKCS7_DETACHED) {
552                 if (outformat == FORMAT_SMIME)
553                     flags |= PKCS7_STREAM;
554             } else if (indef) {
555                 flags |= PKCS7_STREAM;
556             }
557             flags |= PKCS7_PARTIAL;
558             p7 = PKCS7_sign_with_libctx(NULL, NULL, other, in, flags, libctx,
559                                         propq);
560             if (p7 == NULL)
561                 goto end;
562             if (flags & PKCS7_NOCERTS) {
563                 for (i = 0; i < sk_X509_num(other); i++) {
564                     X509 *x = sk_X509_value(other, i);
565                     PKCS7_add_certificate(p7, x);
566                 }
567             }
568         } else {
569             flags |= PKCS7_REUSE_DIGEST;
570         }
571         for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
572             signerfile = sk_OPENSSL_STRING_value(sksigners, i);
573             keyfile = sk_OPENSSL_STRING_value(skkeys, i);
574             signer = load_cert(signerfile, FORMAT_UNDEF,
575                                "signer certificate");
576             if (signer == NULL)
577                 goto end;
578             key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
579             if (key == NULL)
580                 goto end;
581
582             /*
583              * TODO: Remove this when CMS has full support for provider-native
584              * EVP_PKEYs
585              */
586             if (EVP_PKEY_get0(key) == NULL)
587                 goto end;
588
589             if (!PKCS7_sign_add_signer(p7, signer, key, sign_md, flags))
590                 goto end;
591             X509_free(signer);
592             signer = NULL;
593             EVP_PKEY_free(key);
594             key = NULL;
595         }
596         /* If not streaming or resigning finalize structure */
597         if ((operation == SMIME_SIGN) && !(flags & PKCS7_STREAM)) {
598             if (!PKCS7_final(p7, in, flags))
599                 goto end;
600         }
601     }
602
603     if (p7 == NULL) {
604         BIO_printf(bio_err, "Error creating PKCS#7 structure\n");
605         goto end;
606     }
607
608     ret = 4;
609     if (operation == SMIME_DECRYPT) {
610         if (!PKCS7_decrypt(p7, key, recip, out, flags)) {
611             BIO_printf(bio_err, "Error decrypting PKCS#7 structure\n");
612             goto end;
613         }
614     } else if (operation == SMIME_VERIFY) {
615         STACK_OF(X509) *signers;
616         if (PKCS7_verify(p7, other, store, indata, out, flags))
617             BIO_printf(bio_err, "Verification successful\n");
618         else {
619             BIO_printf(bio_err, "Verification failure\n");
620             goto end;
621         }
622         signers = PKCS7_get0_signers(p7, other, flags);
623         if (!save_certs(signerfile, signers)) {
624             BIO_printf(bio_err, "Error writing signers to %s\n", signerfile);
625             ret = 5;
626             goto end;
627         }
628         sk_X509_free(signers);
629     } else if (operation == SMIME_PK7OUT) {
630         PEM_write_bio_PKCS7(out, p7);
631     } else {
632         if (to)
633             BIO_printf(out, "To: %s%s", to, mime_eol);
634         if (from)
635             BIO_printf(out, "From: %s%s", from, mime_eol);
636         if (subject)
637             BIO_printf(out, "Subject: %s%s", subject, mime_eol);
638         if (outformat == FORMAT_SMIME) {
639             if (operation == SMIME_RESIGN)
640                 rv = SMIME_write_PKCS7(out, p7, indata, flags);
641             else
642                 rv = SMIME_write_PKCS7(out, p7, in, flags);
643         } else if (outformat == FORMAT_PEM) {
644             rv = PEM_write_bio_PKCS7_stream(out, p7, in, flags);
645         } else if (outformat == FORMAT_ASN1) {
646             rv = i2d_PKCS7_bio_stream(out, p7, in, flags);
647         } else {
648             BIO_printf(bio_err, "Bad output format for PKCS#7 file\n");
649             goto end;
650         }
651         if (rv == 0) {
652             BIO_printf(bio_err, "Error writing output\n");
653             ret = 3;
654             goto end;
655         }
656     }
657     ret = 0;
658  end:
659     if (ret)
660         ERR_print_errors(bio_err);
661     sk_X509_pop_free(encerts, X509_free);
662     sk_X509_pop_free(other, X509_free);
663     X509_VERIFY_PARAM_free(vpm);
664     sk_OPENSSL_STRING_free(sksigners);
665     sk_OPENSSL_STRING_free(skkeys);
666     X509_STORE_free(store);
667     X509_free(cert);
668     X509_free(recip);
669     X509_free(signer);
670     EVP_PKEY_free(key);
671     PKCS7_free(p7);
672     release_engine(e);
673     BIO_free(in);
674     BIO_free(indata);
675     BIO_free_all(out);
676     OPENSSL_free(passin);
677     NCONF_free(conf);
678     return ret;
679 }
680
681 static int save_certs(char *signerfile, STACK_OF(X509) *signers)
682 {
683     int i;
684     BIO *tmp;
685
686     if (signerfile == NULL)
687         return 1;
688     tmp = BIO_new_file(signerfile, "w");
689     if (tmp == NULL)
690         return 0;
691     for (i = 0; i < sk_X509_num(signers); i++)
692         PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
693     BIO_free(tmp);
694     return 1;
695 }
696
697 /* Minimal callback just to output policy info (if any) */
698
699 static int smime_cb(int ok, X509_STORE_CTX *ctx)
700 {
701     int error;
702
703     error = X509_STORE_CTX_get_error(ctx);
704
705     if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
706         && ((error != X509_V_OK) || (ok != 2)))
707         return ok;
708
709     policies_print(ctx);
710
711     return ok;
712 }