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