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