Revert "TEST: separate out NIST ECC tests from non-NIST"
[openssl.git] / apps / cms.c
1 /*
2  * Copyright 2008-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 /* CMS utility function */
11
12 #include <stdio.h>
13 #include <string.h>
14 #include "apps.h"
15 #include "progs.h"
16
17 #ifndef OPENSSL_NO_CMS
18
19 # include <openssl/crypto.h>
20 # include <openssl/pem.h>
21 # include <openssl/err.h>
22 # include <openssl/x509_vfy.h>
23 # include <openssl/x509v3.h>
24 # include <openssl/cms.h>
25
26 DEFINE_STACK_OF(X509)
27 DEFINE_STACK_OF(CMS_SignerInfo)
28 DEFINE_STACK_OF(GENERAL_NAME)
29 DEFINE_STACK_OF(GENERAL_NAMES)
30 DEFINE_STACK_OF_STRING()
31
32 static int save_certs(char *signerfile, STACK_OF(X509) *signers);
33 static int cms_cb(int ok, X509_STORE_CTX *ctx);
34 static void receipt_request_print(CMS_ContentInfo *cms);
35 static CMS_ReceiptRequest *make_receipt_request(
36     STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst,
37     STACK_OF(OPENSSL_STRING) *rr_from, OPENSSL_CTX *libctx, const char *propq);
38 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
39                               STACK_OF(OPENSSL_STRING) *param);
40
41 # define SMIME_OP        0x10
42 # define SMIME_IP        0x20
43 # define SMIME_SIGNERS   0x40
44 # define SMIME_ENCRYPT           (1 | SMIME_OP)
45 # define SMIME_DECRYPT           (2 | SMIME_IP)
46 # define SMIME_SIGN              (3 | SMIME_OP | SMIME_SIGNERS)
47 # define SMIME_VERIFY            (4 | SMIME_IP)
48 # define SMIME_CMSOUT            (5 | SMIME_IP | SMIME_OP)
49 # define SMIME_RESIGN            (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
50 # define SMIME_DATAOUT           (7 | SMIME_IP)
51 # define SMIME_DATA_CREATE       (8 | SMIME_OP)
52 # define SMIME_DIGEST_VERIFY     (9 | SMIME_IP)
53 # define SMIME_DIGEST_CREATE     (10 | SMIME_OP)
54 # define SMIME_UNCOMPRESS        (11 | SMIME_IP)
55 # define SMIME_COMPRESS          (12 | SMIME_OP)
56 # define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP)
57 # define SMIME_ENCRYPTED_ENCRYPT (14 | SMIME_OP)
58 # define SMIME_SIGN_RECEIPT      (15 | SMIME_IP | SMIME_OP)
59 # define SMIME_VERIFY_RECEIPT    (16 | SMIME_IP)
60
61 static int verify_err = 0;
62
63 typedef struct cms_key_param_st cms_key_param;
64
65 struct cms_key_param_st {
66     int idx;
67     STACK_OF(OPENSSL_STRING) *param;
68     cms_key_param *next;
69 };
70
71 typedef enum OPTION_choice {
72     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
73     OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENCRYPT,
74     OPT_DECRYPT, OPT_SIGN, OPT_CADES, OPT_SIGN_RECEIPT, OPT_RESIGN,
75     OPT_VERIFY, OPT_VERIFY_RETCODE, OPT_VERIFY_RECEIPT,
76     OPT_CMSOUT, OPT_DATA_OUT, OPT_DATA_CREATE, OPT_DIGEST_VERIFY,
77     OPT_DIGEST_CREATE, OPT_COMPRESS, OPT_UNCOMPRESS,
78     OPT_ED_DECRYPT, OPT_ED_ENCRYPT, OPT_DEBUG_DECRYPT, OPT_TEXT,
79     OPT_ASCIICRLF, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCERTS,
80     OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP, OPT_BINARY, OPT_KEYID,
81     OPT_NOSIGS, OPT_NO_CONTENT_VERIFY, OPT_NO_ATTR_VERIFY, OPT_INDEF,
82     OPT_NOINDEF, OPT_CRLFEOL, OPT_NOOUT, OPT_RR_PRINT,
83     OPT_RR_ALL, OPT_RR_FIRST, OPT_RCTFORM, OPT_CERTFILE, OPT_CAFILE,
84     OPT_CAPATH, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE,
85     OPT_CONTENT, OPT_PRINT, OPT_NAMEOPT,
86     OPT_SECRETKEY, OPT_SECRETKEYID, OPT_PWRI_PASSWORD, OPT_ECONTENT_TYPE,
87     OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP,
88     OPT_CERTSOUT, OPT_MD, OPT_INKEY, OPT_KEYFORM, OPT_KEYOPT, OPT_RR_FROM,
89     OPT_RR_TO, OPT_AES128_WRAP, OPT_AES192_WRAP, OPT_AES256_WRAP,
90     OPT_3DES_WRAP, OPT_WRAP, OPT_ENGINE,
91     OPT_R_ENUM,
92     OPT_PROV_ENUM, OPT_CONFIG,
93     OPT_V_ENUM,
94     OPT_CIPHER,
95     OPT_ORIGINATOR
96 } OPTION_CHOICE;
97
98 const OPTIONS cms_options[] = {
99     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"},
100
101     OPT_SECTION("General"),
102     {"help", OPT_HELP, '-', "Display this summary"},
103     {"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"},
104     {"outform", OPT_OUTFORM, 'c',
105      "Output format SMIME (default), PEM or DER"},
106     {"in", OPT_IN, '<', "Input file"},
107     {"out", OPT_OUT, '>', "Output file"},
108     {"debug_decrypt", OPT_DEBUG_DECRYPT, '-',
109         "Disable MMA protection and return an error if no recipient found"
110         " (see documentation)"},
111     {"stream", OPT_INDEF, '-', "Enable CMS streaming"},
112     {"indef", OPT_INDEF, '-', "Same as -stream"},
113     {"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"},
114     {"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of CR only" },
115     {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
116     {"CApath", OPT_CAPATH, '/', "trusted certificates directory"},
117     {"CAstore", OPT_CASTORE, ':', "trusted certificates store URI"},
118     {"no-CAfile", OPT_NOCAFILE, '-',
119      "Do not load the default certificates file"},
120     {"no-CApath", OPT_NOCAPATH, '-',
121      "Do not load certificates from the default certificates directory"},
122     {"no-CAstore", OPT_NOCASTORE, '-',
123      "Do not load certificates from the default certificates store"},
124 # ifndef OPENSSL_NO_ENGINE
125     {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
126 # endif
127     OPT_CONFIG_OPTION,
128
129     OPT_SECTION("Action"),
130     {"encrypt", OPT_ENCRYPT, '-', "Encrypt message"},
131     {"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"},
132     {"sign", OPT_SIGN, '-', "Sign message"},
133     {"sign_receipt", OPT_SIGN_RECEIPT, '-', "Generate a signed receipt for the message"},
134     {"resign", OPT_RESIGN, '-', "Resign a signed message"},
135     {"cades", OPT_CADES, '-', "Include signer certificate digest"},
136     {"verify", OPT_VERIFY, '-', "Verify signed message"},
137     {"verify_retcode", OPT_VERIFY_RETCODE, '-',
138         "Exit non-zero on verification failure"},
139     {"verify_receipt", OPT_VERIFY_RECEIPT, '<',
140         "Verify receipts; exit if receipt signatures do not verify"},
141     {"digest_verify", OPT_DIGEST_VERIFY, '-',
142         "Verify a CMS \"DigestedData\" object and output it"},
143     {"digest_create", OPT_DIGEST_CREATE, '-',
144         "Create a CMS \"DigestedData\" object"},
145     {"compress", OPT_COMPRESS, '-', "Create a CMS \"CompressedData\" object"},
146     {"uncompress", OPT_UNCOMPRESS, '-',
147         "Uncompress a CMS \"CompressedData\" object"},
148     {"EncryptedData_decrypt", OPT_ED_DECRYPT, '-',
149         "Decrypt CMS \"EncryptedData\" object using symmetric key"},
150     {"EncryptedData_encrypt", OPT_ED_ENCRYPT, '-',
151         "Create CMS \"EncryptedData\" object using symmetric key"},
152     {"data_out", OPT_DATA_OUT, '-', "Copy CMS \"Data\" object to output"},
153     {"data_create", OPT_DATA_CREATE, '-', "Create a CMS \"Data\" object"},
154     {"cmsout", OPT_CMSOUT, '-', "Output CMS structure"},
155     {"no_content_verify", OPT_NO_CONTENT_VERIFY, '-',
156         "Do not verify signed content signatures"},
157     {"no_attr_verify", OPT_NO_ATTR_VERIFY, '-',
158         "Do not verify signed attribute signatures"},
159     {"nointern", OPT_NOINTERN, '-',
160         "Don't search certificates in message for signer"},
161     {"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"},
162
163     OPT_SECTION("Formatting"),
164     {"text", OPT_TEXT, '-', "Include or delete text MIME headers"},
165     {"asciicrlf", OPT_ASCIICRLF, '-',
166         "Perform CRLF canonicalisation when signing"},
167     {"nodetach", OPT_NODETACH, '-', "Use opaque signing"},
168     {"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"},
169     {"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"},
170     {"binary", OPT_BINARY, '-', "Don't translate message to text"},
171     {"keyid", OPT_KEYID, '-', "Use subject key identifier"},
172     {"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"},
173     {"nocerts", OPT_NOCERTS, '-',
174      "Don't include signers certificate when signing"},
175     {"noout", OPT_NOOUT, '-',
176         "For the -cmsout operation do not output the parsed CMS structure"},
177     {"receipt_request_print", OPT_RR_PRINT, '-', "Print CMS Receipt Request" },
178     {"receipt_request_all", OPT_RR_ALL, '-',
179         "When signing, create a receipt request for all recipients"},
180     {"receipt_request_first", OPT_RR_FIRST, '-',
181         "When signing, create a receipt request for first recipient"},
182     {"rctform", OPT_RCTFORM, 'F', "Receipt file format"},
183     {"certfile", OPT_CERTFILE, '<', "Other certificates file"},
184     {"content", OPT_CONTENT, '<',
185      "Supply or override content for detached signature"},
186     {"print", OPT_PRINT, '-',
187      "For the -cmsout operation print out all fields of the CMS structure"},
188     {"nameopt", OPT_NAMEOPT, 's',
189      "For the -print option specifies various strings printing options"},
190     {"certsout", OPT_CERTSOUT, '>', "Certificate output file"},
191
192     OPT_SECTION("Keying"),
193     {"secretkey", OPT_SECRETKEY, 's',
194         "Use specified hex-encoded key to decrypt/encrypt recipients or content"},
195     {"secretkeyid", OPT_SECRETKEYID, 's',
196         "Identity of the -secretkey for CMS \"KEKRecipientInfo\" object"},
197     {"pwri_password", OPT_PWRI_PASSWORD, 's',
198         "Specific password for recipient"},
199     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
200     {"inkey", OPT_INKEY, 's',
201      "Input private key (if not signer or recipient)"},
202     {"keyform", OPT_KEYFORM, 'f', "Input private key format (ENGINE, other values ignored)"},
203     {"keyopt", OPT_KEYOPT, 's', "Set public key parameters as n:v pairs"},
204
205     OPT_SECTION("Mail header"),
206     {"econtent_type", OPT_ECONTENT_TYPE, 's', "OID for external content"},
207     {"to", OPT_TO, 's', "To address"},
208     {"from", OPT_FROM, 's', "From address"},
209     {"subject", OPT_SUBJECT, 's', "Subject"},
210     {"signer", OPT_SIGNER, 's', "Signer certificate file"},
211     {"originator", OPT_ORIGINATOR, 's', "Originator certificate file"},
212     {"recip", OPT_RECIP, '<', "Recipient cert file for decryption"},
213     {"receipt_request_from", OPT_RR_FROM, 's',
214         "Create signed receipt request with specified email address"},
215     {"receipt_request_to", OPT_RR_TO, 's',
216         "Create signed receipt targeted to specified address"},
217
218     OPT_SECTION("Encryption"),
219     {"md", OPT_MD, 's', "Digest algorithm to use when signing or resigning"},
220     {"", OPT_CIPHER, '-', "Any supported cipher"},
221
222     OPT_SECTION("Key-wrapping"),
223     {"aes128-wrap", OPT_AES128_WRAP, '-', "Use AES128 to wrap key"},
224     {"aes192-wrap", OPT_AES192_WRAP, '-', "Use AES192 to wrap key"},
225     {"aes256-wrap", OPT_AES256_WRAP, '-', "Use AES256 to wrap key"},
226 # ifndef OPENSSL_NO_DES
227     {"des3-wrap", OPT_3DES_WRAP, '-', "Use 3DES-EDE to wrap key"},
228 # endif
229     {"wrap", OPT_WRAP, 's', "Any wrap cipher to wrap key"},
230
231     OPT_R_OPTIONS,
232     OPT_V_OPTIONS,
233     OPT_PROV_OPTIONS,
234
235     OPT_PARAMETERS(),
236     {"cert", 0, 0, "Recipient certs (optional; used only when encrypting)"},
237     {NULL}
238 };
239
240 static CMS_ContentInfo *load_content_info(int informat, BIO *in, BIO **indata,
241                                           const char *name,
242                                           OPENSSL_CTX *libctx, const char *propq)
243 {
244     CMS_ContentInfo *ret, *ci;
245
246     ret = CMS_ContentInfo_new_with_libctx(libctx, propq);
247     if (ret == NULL) {
248         BIO_printf(bio_err, "Error allocating CMS_contentinfo\n");
249         return NULL;
250     }
251     switch (informat) {
252     case FORMAT_SMIME:
253         ci = SMIME_read_CMS_ex(in, indata, &ret);
254         break;
255     case FORMAT_PEM:
256         ci = PEM_read_bio_CMS(in, &ret, NULL, NULL);
257         break;
258     case FORMAT_ASN1:
259         ci = d2i_CMS_bio(in, &ret);
260         break;
261     default:
262         BIO_printf(bio_err, "Bad input format for %s\n", name);
263         goto err;
264     }
265     if (ci == NULL) {
266         BIO_printf(bio_err, "Error reading %s Content Info\n", name);
267         goto err;
268     }
269     return ret;
270 err:
271     CMS_ContentInfo_free(ret);
272     return NULL;
273 }
274
275 int cms_main(int argc, char **argv)
276 {
277     CONF *conf = NULL;
278     ASN1_OBJECT *econtent_type = NULL;
279     BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
280     CMS_ContentInfo *cms = NULL, *rcms = NULL;
281     CMS_ReceiptRequest *rr = NULL;
282     ENGINE *e = NULL;
283     EVP_PKEY *key = NULL;
284     const EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
285     const EVP_MD *sign_md = NULL;
286     STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
287     STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
288     STACK_OF(X509) *encerts = NULL, *other = NULL;
289     X509 *cert = NULL, *recip = NULL, *signer = NULL, *originator = NULL;
290     X509_STORE *store = NULL;
291     X509_VERIFY_PARAM *vpm = NULL;
292     char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
293     const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
294     char *certsoutfile = NULL;
295     int noCAfile = 0, noCApath = 0, noCAstore = 0;
296     char *infile = NULL, *outfile = NULL, *rctfile = NULL;
297     char *passinarg = NULL, *passin = NULL, *signerfile = NULL, *originatorfile = NULL, *recipfile = NULL;
298     char *to = NULL, *from = NULL, *subject = NULL, *prog;
299     cms_key_param *key_first = NULL, *key_param = NULL;
300     int flags = CMS_DETACHED, noout = 0, print = 0, keyidx = -1, vpmtouched = 0;
301     int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
302     int operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1;
303     int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_PEM;
304     size_t secret_keylen = 0, secret_keyidlen = 0;
305     unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
306     unsigned char *secret_key = NULL, *secret_keyid = NULL;
307     long ltmp;
308     const char *mime_eol = "\n";
309     OPTION_CHOICE o;
310     OPENSSL_CTX *libctx = app_get0_libctx();
311     const char *propq = app_get0_propq();
312
313     if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
314         return 1;
315
316     prog = opt_init(argc, argv, cms_options);
317     while ((o = opt_next()) != OPT_EOF) {
318         switch (o) {
319         case OPT_EOF:
320         case OPT_ERR:
321  opthelp:
322             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
323             goto end;
324         case OPT_HELP:
325             opt_help(cms_options);
326             ret = 0;
327             goto end;
328         case OPT_INFORM:
329             if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
330                 goto opthelp;
331             break;
332         case OPT_OUTFORM:
333             if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
334                 goto opthelp;
335             break;
336         case OPT_OUT:
337             outfile = opt_arg();
338             break;
339         case OPT_ENCRYPT:
340             operation = SMIME_ENCRYPT;
341             break;
342         case OPT_DECRYPT:
343             operation = SMIME_DECRYPT;
344             break;
345         case OPT_SIGN:
346             operation = SMIME_SIGN;
347             break;
348         case OPT_SIGN_RECEIPT:
349             operation = SMIME_SIGN_RECEIPT;
350             break;
351         case OPT_RESIGN:
352             operation = SMIME_RESIGN;
353             break;
354         case OPT_VERIFY:
355             operation = SMIME_VERIFY;
356             break;
357         case OPT_VERIFY_RETCODE:
358             verify_retcode = 1;
359             break;
360         case OPT_VERIFY_RECEIPT:
361             operation = SMIME_VERIFY_RECEIPT;
362             rctfile = opt_arg();
363             break;
364         case OPT_CMSOUT:
365             operation = SMIME_CMSOUT;
366             break;
367         case OPT_DATA_OUT:
368             operation = SMIME_DATAOUT;
369             break;
370         case OPT_DATA_CREATE:
371             operation = SMIME_DATA_CREATE;
372             break;
373         case OPT_DIGEST_VERIFY:
374             operation = SMIME_DIGEST_VERIFY;
375             break;
376         case OPT_DIGEST_CREATE:
377             operation = SMIME_DIGEST_CREATE;
378             break;
379         case OPT_COMPRESS:
380             operation = SMIME_COMPRESS;
381             break;
382         case OPT_UNCOMPRESS:
383             operation = SMIME_UNCOMPRESS;
384             break;
385         case OPT_ED_DECRYPT:
386             operation = SMIME_ENCRYPTED_DECRYPT;
387             break;
388         case OPT_ED_ENCRYPT:
389             operation = SMIME_ENCRYPTED_ENCRYPT;
390             break;
391         case OPT_DEBUG_DECRYPT:
392             flags |= CMS_DEBUG_DECRYPT;
393             break;
394         case OPT_TEXT:
395             flags |= CMS_TEXT;
396             break;
397         case OPT_ASCIICRLF:
398             flags |= CMS_ASCIICRLF;
399             break;
400         case OPT_NOINTERN:
401             flags |= CMS_NOINTERN;
402             break;
403         case OPT_NOVERIFY:
404             flags |= CMS_NO_SIGNER_CERT_VERIFY;
405             break;
406         case OPT_NOCERTS:
407             flags |= CMS_NOCERTS;
408             break;
409         case OPT_NOATTR:
410             flags |= CMS_NOATTR;
411             break;
412         case OPT_NODETACH:
413             flags &= ~CMS_DETACHED;
414             break;
415         case OPT_NOSMIMECAP:
416             flags |= CMS_NOSMIMECAP;
417             break;
418         case OPT_BINARY:
419             flags |= CMS_BINARY;
420             break;
421         case OPT_CADES:
422             flags |= CMS_CADES;
423             break;
424         case OPT_KEYID:
425             flags |= CMS_USE_KEYID;
426             break;
427         case OPT_NOSIGS:
428             flags |= CMS_NOSIGS;
429             break;
430         case OPT_NO_CONTENT_VERIFY:
431             flags |= CMS_NO_CONTENT_VERIFY;
432             break;
433         case OPT_NO_ATTR_VERIFY:
434             flags |= CMS_NO_ATTR_VERIFY;
435             break;
436         case OPT_INDEF:
437             flags |= CMS_STREAM;
438             break;
439         case OPT_NOINDEF:
440             flags &= ~CMS_STREAM;
441             break;
442         case OPT_CRLFEOL:
443             mime_eol = "\r\n";
444             flags |= CMS_CRLFEOL;
445             break;
446         case OPT_NOOUT:
447             noout = 1;
448             break;
449         case OPT_RR_PRINT:
450             rr_print = 1;
451             break;
452         case OPT_RR_ALL:
453             rr_allorfirst = 0;
454             break;
455         case OPT_RR_FIRST:
456             rr_allorfirst = 1;
457             break;
458         case OPT_RCTFORM:
459             if (rctformat == FORMAT_ASN1) {
460                 if (!opt_format(opt_arg(),
461                                 OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat))
462                     goto opthelp;
463             } else {
464                 rcms = load_content_info(rctformat, rctin, NULL, "recipient",
465                                          libctx, propq);
466             }
467             break;
468         case OPT_CERTFILE:
469             certfile = opt_arg();
470             break;
471         case OPT_CAFILE:
472             CAfile = opt_arg();
473             break;
474         case OPT_CAPATH:
475             CApath = opt_arg();
476             break;
477         case OPT_CASTORE:
478             CAstore = opt_arg();
479             break;
480         case OPT_NOCAFILE:
481             noCAfile = 1;
482             break;
483         case OPT_NOCAPATH:
484             noCApath = 1;
485             break;
486         case OPT_NOCASTORE:
487             noCAstore = 1;
488             break;
489         case OPT_IN:
490             infile = opt_arg();
491             break;
492         case OPT_CONTENT:
493             contfile = opt_arg();
494             break;
495         case OPT_RR_FROM:
496             if (rr_from == NULL
497                 && (rr_from = sk_OPENSSL_STRING_new_null()) == NULL)
498                 goto end;
499             sk_OPENSSL_STRING_push(rr_from, opt_arg());
500             break;
501         case OPT_RR_TO:
502             if (rr_to == NULL
503                 && (rr_to = sk_OPENSSL_STRING_new_null()) == NULL)
504                 goto end;
505             sk_OPENSSL_STRING_push(rr_to, opt_arg());
506             break;
507         case OPT_PRINT:
508             noout = print = 1;
509             break;
510         case OPT_NAMEOPT:
511             if (!set_nameopt(opt_arg()))
512                 goto opthelp;
513             break;
514         case OPT_SECRETKEY:
515             if (secret_key != NULL) {
516                 BIO_printf(bio_err, "Invalid key (supplied twice) %s\n",
517                            opt_arg());
518                 goto opthelp;
519             }
520             secret_key = OPENSSL_hexstr2buf(opt_arg(), &ltmp);
521             if (secret_key == NULL) {
522                 BIO_printf(bio_err, "Invalid key %s\n", opt_arg());
523                 goto end;
524             }
525             secret_keylen = (size_t)ltmp;
526             break;
527         case OPT_SECRETKEYID:
528             if (secret_keyid != NULL) {
529                 BIO_printf(bio_err, "Invalid id (supplied twice) %s\n",
530                            opt_arg());
531                 goto opthelp;
532             }
533             secret_keyid = OPENSSL_hexstr2buf(opt_arg(), &ltmp);
534             if (secret_keyid == NULL) {
535                 BIO_printf(bio_err, "Invalid id %s\n", opt_arg());
536                 goto opthelp;
537             }
538             secret_keyidlen = (size_t)ltmp;
539             break;
540         case OPT_PWRI_PASSWORD:
541             pwri_pass = (unsigned char *)opt_arg();
542             break;
543         case OPT_ECONTENT_TYPE:
544             if (econtent_type != NULL) {
545                 BIO_printf(bio_err, "Invalid OID (supplied twice) %s\n",
546                            opt_arg());
547                 goto opthelp;
548             }
549             econtent_type = OBJ_txt2obj(opt_arg(), 0);
550             if (econtent_type == NULL) {
551                 BIO_printf(bio_err, "Invalid OID %s\n", opt_arg());
552                 goto opthelp;
553             }
554             break;
555         case OPT_ENGINE:
556             e = setup_engine(opt_arg(), 0);
557             break;
558         case OPT_PASSIN:
559             passinarg = opt_arg();
560             break;
561         case OPT_TO:
562             to = opt_arg();
563             break;
564         case OPT_FROM:
565             from = opt_arg();
566             break;
567         case OPT_SUBJECT:
568             subject = opt_arg();
569             break;
570         case OPT_CERTSOUT:
571             certsoutfile = opt_arg();
572             break;
573         case OPT_MD:
574             if (!opt_md(opt_arg(), &sign_md))
575                 goto end;
576             break;
577         case OPT_SIGNER:
578             /* If previous -signer argument add signer to list */
579             if (signerfile != NULL) {
580                 if (sksigners == NULL
581                     && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
582                     goto end;
583                 sk_OPENSSL_STRING_push(sksigners, signerfile);
584                 if (keyfile == NULL)
585                     keyfile = signerfile;
586                 if (skkeys == NULL
587                     && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
588                     goto end;
589                 sk_OPENSSL_STRING_push(skkeys, keyfile);
590                 keyfile = NULL;
591             }
592             signerfile = opt_arg();
593             break;
594         case OPT_ORIGINATOR:
595              originatorfile = opt_arg();
596              break;
597         case OPT_INKEY:
598             /* If previous -inkey argument add signer to list */
599             if (keyfile != NULL) {
600                 if (signerfile == NULL) {
601                     BIO_puts(bio_err, "Illegal -inkey without -signer\n");
602                     goto end;
603                 }
604                 if (sksigners == NULL
605                     && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
606                     goto end;
607                 sk_OPENSSL_STRING_push(sksigners, signerfile);
608                 signerfile = NULL;
609                 if (skkeys == NULL
610                     && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
611                     goto end;
612                 sk_OPENSSL_STRING_push(skkeys, keyfile);
613             }
614             keyfile = opt_arg();
615             break;
616         case OPT_KEYFORM:
617             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
618                 goto opthelp;
619             break;
620         case OPT_RECIP:
621             if (operation == SMIME_ENCRYPT) {
622                 if (encerts == NULL && (encerts = sk_X509_new_null()) == NULL)
623                     goto end;
624                 cert = load_cert(opt_arg(), FORMAT_UNDEF,
625                                  "recipient certificate file");
626                 if (cert == NULL)
627                     goto end;
628                 sk_X509_push(encerts, cert);
629                 cert = NULL;
630             } else {
631                 recipfile = opt_arg();
632             }
633             break;
634         case OPT_CIPHER:
635             if (!opt_cipher(opt_unknown(), &cipher))
636                 goto end;
637             break;
638         case OPT_KEYOPT:
639             keyidx = -1;
640             if (operation == SMIME_ENCRYPT) {
641                 if (encerts != NULL)
642                     keyidx += sk_X509_num(encerts);
643             } else {
644                 if (keyfile != NULL || signerfile != NULL)
645                     keyidx++;
646                 if (skkeys != NULL)
647                     keyidx += sk_OPENSSL_STRING_num(skkeys);
648             }
649             if (keyidx < 0) {
650                 BIO_printf(bio_err, "No key specified\n");
651                 goto opthelp;
652             }
653             if (key_param == NULL || key_param->idx != keyidx) {
654                 cms_key_param *nparam;
655                 nparam = app_malloc(sizeof(*nparam), "key param buffer");
656                 nparam->idx = keyidx;
657                 if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL)
658                     goto end;
659                 nparam->next = NULL;
660                 if (key_first == NULL)
661                     key_first = nparam;
662                 else
663                     key_param->next = nparam;
664                 key_param = nparam;
665             }
666             sk_OPENSSL_STRING_push(key_param->param, opt_arg());
667             break;
668         case OPT_V_CASES:
669             if (!opt_verify(o, vpm))
670                 goto end;
671             vpmtouched++;
672             break;
673         case OPT_R_CASES:
674             if (!opt_rand(o))
675                 goto end;
676             break;
677         case OPT_PROV_CASES:
678             if (!opt_provider(o))
679                 goto end;
680             break;
681         case OPT_CONFIG:
682             conf = app_load_config_modules(opt_arg());
683             if (conf == NULL)
684                 goto end;
685             break;
686         case OPT_3DES_WRAP:
687 # ifndef OPENSSL_NO_DES
688             wrap_cipher = EVP_des_ede3_wrap();
689 # endif
690             break;
691         case OPT_AES128_WRAP:
692             wrap_cipher = EVP_aes_128_wrap();
693             break;
694         case OPT_AES192_WRAP:
695             wrap_cipher = EVP_aes_192_wrap();
696             break;
697         case OPT_AES256_WRAP:
698             wrap_cipher = EVP_aes_256_wrap();
699             break;
700         case OPT_WRAP:
701             if (!opt_cipher(opt_unknown(), &wrap_cipher))
702                 goto end;
703             break;
704         }
705     }
706     argc = opt_num_rest();
707     argv = opt_rest();
708
709     if ((rr_allorfirst != -1 || rr_from != NULL) && rr_to == NULL) {
710         BIO_puts(bio_err, "No Signed Receipts Recipients\n");
711         goto opthelp;
712     }
713
714     if (!(operation & SMIME_SIGNERS) && (rr_to != NULL || rr_from != NULL)) {
715         BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
716         goto opthelp;
717     }
718     if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) {
719         BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
720         goto opthelp;
721     }
722
723     if ((flags & CMS_CADES) != 0) {
724         if ((flags & CMS_NOATTR) != 0) {
725             BIO_puts(bio_err, "Incompatible options: "
726                      "CAdES required signed attributes\n");
727             goto opthelp;
728         }
729         if (operation == SMIME_VERIFY
730                 && (flags & (CMS_NO_SIGNER_CERT_VERIFY | CMS_NO_ATTR_VERIFY)) != 0) {
731             BIO_puts(bio_err, "Incompatible options: CAdES validation require"
732                      " certs and signed attributes validations\n");
733             goto opthelp;
734         }
735     }
736
737     if (operation & SMIME_SIGNERS) {
738         if (keyfile != NULL && signerfile == NULL) {
739             BIO_puts(bio_err, "Illegal -inkey without -signer\n");
740             goto opthelp;
741         }
742         /* Check to see if any final signer needs to be appended */
743         if (signerfile != NULL) {
744             if (sksigners == NULL
745                 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
746                 goto end;
747             sk_OPENSSL_STRING_push(sksigners, signerfile);
748             if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
749                 goto end;
750             if (keyfile == NULL)
751                 keyfile = signerfile;
752             sk_OPENSSL_STRING_push(skkeys, keyfile);
753         }
754         if (sksigners == NULL) {
755             BIO_printf(bio_err, "No signer certificate specified\n");
756             goto opthelp;
757         }
758         signerfile = NULL;
759         keyfile = NULL;
760     } else if (operation == SMIME_DECRYPT) {
761         if (recipfile == NULL && keyfile == NULL
762             && secret_key == NULL && pwri_pass == NULL) {
763             BIO_printf(bio_err,
764                        "No recipient certificate or key specified\n");
765             goto opthelp;
766         }
767     } else if (operation == SMIME_ENCRYPT) {
768         if (*argv == NULL && secret_key == NULL
769             && pwri_pass == NULL && encerts == NULL) {
770             BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
771             goto opthelp;
772         }
773     } else if (!operation) {
774         BIO_printf(bio_err, "No operation option (-encrypt|-decrypt|-sign|-verify|...) specified.\n");
775         goto opthelp;
776     }
777
778     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
779         BIO_printf(bio_err, "Error getting password\n");
780         goto end;
781     }
782
783     ret = 2;
784
785     if (!(operation & SMIME_SIGNERS))
786         flags &= ~CMS_DETACHED;
787
788     if (!(operation & SMIME_OP))
789         if (flags & CMS_BINARY)
790             outformat = FORMAT_BINARY;
791
792     if (!(operation & SMIME_IP))
793         if (flags & CMS_BINARY)
794             informat = FORMAT_BINARY;
795
796     if (operation == SMIME_ENCRYPT) {
797         if (!cipher) {
798 # ifndef OPENSSL_NO_DES
799             cipher = EVP_des_ede3_cbc();
800 # else
801             BIO_printf(bio_err, "No cipher selected\n");
802             goto end;
803 # endif
804         }
805
806         if (secret_key && !secret_keyid) {
807             BIO_printf(bio_err, "No secret key id\n");
808             goto end;
809         }
810
811         if (*argv && encerts == NULL)
812             if ((encerts = sk_X509_new_null()) == NULL)
813                 goto end;
814         while (*argv) {
815             if ((cert = load_cert(*argv, FORMAT_UNDEF,
816                                   "recipient certificate file")) == NULL)
817                 goto end;
818             sk_X509_push(encerts, cert);
819             cert = NULL;
820             argv++;
821         }
822     }
823
824     if (certfile != NULL) {
825         if (!load_certs(certfile, &other, NULL, "certificate file")) {
826             ERR_print_errors(bio_err);
827             goto end;
828         }
829     }
830
831     if (recipfile != NULL && (operation == SMIME_DECRYPT)) {
832         if ((recip = load_cert(recipfile, FORMAT_UNDEF,
833                                "recipient certificate file")) == NULL) {
834             ERR_print_errors(bio_err);
835             goto end;
836         }
837     }
838
839     if (originatorfile != NULL) {
840         if ((originator = load_cert(originatorfile, FORMAT_UNDEF,
841                                     "originator certificate file")) == NULL) {
842              ERR_print_errors(bio_err);
843              goto end;
844         }
845     }
846
847     if (operation == SMIME_SIGN_RECEIPT) {
848         if ((signer = load_cert(signerfile, FORMAT_UNDEF,
849                                 "receipt signer certificate file")) == NULL) {
850             ERR_print_errors(bio_err);
851             goto end;
852         }
853     }
854
855     if ((operation == SMIME_DECRYPT) || (operation == SMIME_ENCRYPT)) {
856         if (keyfile == NULL)
857             keyfile = recipfile;
858     } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
859         if (keyfile == NULL)
860             keyfile = signerfile;
861     } else {
862         keyfile = NULL;
863     }
864
865     if (keyfile != NULL) {
866         key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
867         if (key == NULL)
868             goto end;
869
870         /*
871          * TODO: Remove this when CMS has full support for provider-native
872          * EVP_PKEYs
873          */
874         if (EVP_PKEY_get0(key) == NULL)
875             goto end;
876     }
877
878     in = bio_open_default(infile, 'r', informat);
879     if (in == NULL)
880         goto end;
881
882     if (operation & SMIME_IP) {
883         cms = load_content_info(informat, in, &indata, "SMIME", libctx, propq);
884         if (cms == NULL)
885             goto end;
886         if (contfile != NULL) {
887             BIO_free(indata);
888             if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
889                 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
890                 goto end;
891             }
892         }
893         if (certsoutfile != NULL) {
894             STACK_OF(X509) *allcerts;
895             allcerts = CMS_get1_certs(cms);
896             if (!save_certs(certsoutfile, allcerts)) {
897                 BIO_printf(bio_err,
898                            "Error writing certs to %s\n", certsoutfile);
899                 ret = 5;
900                 goto end;
901             }
902             sk_X509_pop_free(allcerts, X509_free);
903         }
904     }
905
906     if (rctfile != NULL) {
907         char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
908         if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) {
909             BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile);
910             goto end;
911         }
912
913         rcms = load_content_info(rctformat, rctin, NULL, "recipient", libctx,
914                                  propq);
915         if (rcms == NULL)
916             goto end;
917     }
918
919     out = bio_open_default(outfile, 'w', outformat);
920     if (out == NULL)
921         goto end;
922
923     if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) {
924         if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
925                                   CAstore, noCAstore)) == NULL)
926             goto end;
927         X509_STORE_set_verify_cb(store, cms_cb);
928         if (vpmtouched)
929             X509_STORE_set1_param(store, vpm);
930     }
931
932     ret = 3;
933
934     if (operation == SMIME_DATA_CREATE) {
935         cms = CMS_data_create_with_libctx(in, flags, libctx, propq);
936     } else if (operation == SMIME_DIGEST_CREATE) {
937         cms = CMS_digest_create_with_libctx(in, sign_md, flags, libctx, propq);
938     } else if (operation == SMIME_COMPRESS) {
939         cms = CMS_compress(in, -1, flags);
940     } else if (operation == SMIME_ENCRYPT) {
941         int i;
942         flags |= CMS_PARTIAL;
943         cms = CMS_encrypt_with_libctx(NULL, in, cipher, flags, libctx, propq);
944         if (cms == NULL)
945             goto end;
946         for (i = 0; i < sk_X509_num(encerts); i++) {
947             CMS_RecipientInfo *ri;
948             cms_key_param *kparam;
949             int tflags = flags | CMS_KEY_PARAM; /* This flag enforces allocating the EVP_PKEY_CTX for the recipient here */
950             EVP_PKEY_CTX *pctx;
951             X509 *x = sk_X509_value(encerts, i);
952             int res;
953
954             for (kparam = key_first; kparam; kparam = kparam->next) {
955                 if (kparam->idx == i) {
956                     break;
957                 }
958             }
959             ri = CMS_add1_recipient(cms, x, key, originator, tflags);
960             if (ri == NULL)
961                 goto end;
962
963             pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
964             if (kparam != NULL) {
965                 if (!cms_set_pkey_param(pctx, kparam->param))
966                     goto end;
967             }
968
969             res = EVP_PKEY_CTX_ctrl(pctx, -1, -1,
970                                     EVP_PKEY_CTRL_CIPHER,
971                                     EVP_CIPHER_nid(cipher), NULL);
972             if (res <= 0 && res != -2)
973                 goto end;
974
975             if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE
976                 && wrap_cipher) {
977                 EVP_CIPHER_CTX *wctx;
978                 wctx = CMS_RecipientInfo_kari_get0_ctx(ri);
979                 EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL);
980             }
981         }
982
983         if (secret_key != NULL) {
984             if (!CMS_add0_recipient_key(cms, NID_undef,
985                                         secret_key, secret_keylen,
986                                         secret_keyid, secret_keyidlen,
987                                         NULL, NULL, NULL))
988                 goto end;
989             /* NULL these because call absorbs them */
990             secret_key = NULL;
991             secret_keyid = NULL;
992         }
993         if (pwri_pass != NULL) {
994             pwri_tmp = (unsigned char *)OPENSSL_strdup((char *)pwri_pass);
995             if (pwri_tmp == NULL)
996                 goto end;
997             if (CMS_add0_recipient_password(cms,
998                                             -1, NID_undef, NID_undef,
999                                             pwri_tmp, -1, NULL) == NULL)
1000                 goto end;
1001             pwri_tmp = NULL;
1002         }
1003         if (!(flags & CMS_STREAM)) {
1004             if (!CMS_final(cms, in, NULL, flags))
1005                 goto end;
1006         }
1007     } else if (operation == SMIME_ENCRYPTED_ENCRYPT) {
1008         cms = CMS_EncryptedData_encrypt_with_libctx(in, cipher, secret_key,
1009                                                     secret_keylen, flags,
1010                                                     libctx, propq);
1011
1012     } else if (operation == SMIME_SIGN_RECEIPT) {
1013         CMS_ContentInfo *srcms = NULL;
1014         STACK_OF(CMS_SignerInfo) *sis;
1015         CMS_SignerInfo *si;
1016         sis = CMS_get0_SignerInfos(cms);
1017         if (sis == NULL)
1018             goto end;
1019         si = sk_CMS_SignerInfo_value(sis, 0);
1020         srcms = CMS_sign_receipt(si, signer, key, other, flags);
1021         if (srcms == NULL)
1022             goto end;
1023         CMS_ContentInfo_free(cms);
1024         cms = srcms;
1025     } else if (operation & SMIME_SIGNERS) {
1026         int i;
1027         /*
1028          * If detached data content we enable streaming if S/MIME output
1029          * format.
1030          */
1031         if (operation == SMIME_SIGN) {
1032
1033             if (flags & CMS_DETACHED) {
1034                 if (outformat == FORMAT_SMIME)
1035                     flags |= CMS_STREAM;
1036             }
1037             flags |= CMS_PARTIAL;
1038             cms = CMS_sign_with_libctx(NULL, NULL, other, in, flags, libctx, propq);
1039             if (cms == NULL)
1040                 goto end;
1041             if (econtent_type != NULL)
1042                 CMS_set1_eContentType(cms, econtent_type);
1043
1044             if (rr_to != NULL) {
1045                 rr = make_receipt_request(rr_to, rr_allorfirst, rr_from, libctx,
1046                                           propq);
1047                 if (rr == NULL) {
1048                     BIO_puts(bio_err,
1049                              "Signed Receipt Request Creation Error\n");
1050                     goto end;
1051                 }
1052             }
1053         } else {
1054             flags |= CMS_REUSE_DIGEST;
1055         }
1056         for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
1057             CMS_SignerInfo *si;
1058             cms_key_param *kparam;
1059             int tflags = flags;
1060             signerfile = sk_OPENSSL_STRING_value(sksigners, i);
1061             keyfile = sk_OPENSSL_STRING_value(skkeys, i);
1062
1063             signer = load_cert(signerfile, FORMAT_UNDEF,
1064                                "signer certificate");
1065             if (signer == NULL) {
1066                 ret = 2;
1067                 goto end;
1068             }
1069             key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
1070             if (key == NULL) {
1071                 ret = 2;
1072                 goto end;
1073             }
1074
1075             /*
1076              * TODO: Remove this when CMS has full support for provider-native
1077              * EVP_PKEYs
1078              */
1079             if (EVP_PKEY_get0(key) == NULL)
1080                 goto end;
1081
1082             for (kparam = key_first; kparam; kparam = kparam->next) {
1083                 if (kparam->idx == i) {
1084                     tflags |= CMS_KEY_PARAM;
1085                     break;
1086                 }
1087             }
1088             si = CMS_add1_signer(cms, signer, key, sign_md, tflags);
1089             if (si == NULL)
1090                 goto end;
1091             if (kparam != NULL) {
1092                 EVP_PKEY_CTX *pctx;
1093                 pctx = CMS_SignerInfo_get0_pkey_ctx(si);
1094                 if (!cms_set_pkey_param(pctx, kparam->param))
1095                     goto end;
1096             }
1097             if (rr != NULL && !CMS_add1_ReceiptRequest(si, rr))
1098                 goto end;
1099             X509_free(signer);
1100             signer = NULL;
1101             EVP_PKEY_free(key);
1102             key = NULL;
1103         }
1104         /* If not streaming or resigning finalize structure */
1105         if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
1106             if (!CMS_final(cms, in, NULL, flags))
1107                 goto end;
1108         }
1109     }
1110
1111     if (cms == NULL) {
1112         BIO_printf(bio_err, "Error creating CMS structure\n");
1113         goto end;
1114     }
1115
1116     ret = 4;
1117     if (operation == SMIME_DECRYPT) {
1118         if (flags & CMS_DEBUG_DECRYPT)
1119             CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);
1120
1121         if (secret_key != NULL) {
1122             if (!CMS_decrypt_set1_key(cms,
1123                                       secret_key, secret_keylen,
1124                                       secret_keyid, secret_keyidlen)) {
1125                 BIO_puts(bio_err, "Error decrypting CMS using secret key\n");
1126                 goto end;
1127             }
1128         }
1129
1130         if (key != NULL) {
1131             if (!CMS_decrypt_set1_pkey_and_peer(cms, key, recip, originator)) {
1132                 BIO_puts(bio_err, "Error decrypting CMS using private key\n");
1133                 goto end;
1134             }
1135         }
1136
1137         if (pwri_pass != NULL) {
1138             if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
1139                 BIO_puts(bio_err, "Error decrypting CMS using password\n");
1140                 goto end;
1141             }
1142         }
1143
1144         if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
1145             BIO_printf(bio_err, "Error decrypting CMS structure\n");
1146             goto end;
1147         }
1148     } else if (operation == SMIME_DATAOUT) {
1149         if (!CMS_data(cms, out, flags))
1150             goto end;
1151     } else if (operation == SMIME_UNCOMPRESS) {
1152         if (!CMS_uncompress(cms, indata, out, flags))
1153             goto end;
1154     } else if (operation == SMIME_DIGEST_VERIFY) {
1155         if (CMS_digest_verify(cms, indata, out, flags) > 0) {
1156             BIO_printf(bio_err, "Verification successful\n");
1157         } else {
1158             BIO_printf(bio_err, "Verification failure\n");
1159             goto end;
1160         }
1161     } else if (operation == SMIME_ENCRYPTED_DECRYPT) {
1162         if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
1163                                        indata, out, flags))
1164             goto end;
1165     } else if (operation == SMIME_VERIFY) {
1166         if (CMS_verify(cms, other, store, indata, out, flags) > 0) {
1167             BIO_printf(bio_err, "%s Verification successful\n",
1168                        (flags & CMS_CADES) ? "CAdES" : "CMS");
1169         } else {
1170             BIO_printf(bio_err, "Verification failure\n");
1171             if (verify_retcode)
1172                 ret = verify_err + 32;
1173             goto end;
1174         }
1175         if (signerfile != NULL) {
1176             STACK_OF(X509) *signers;
1177             signers = CMS_get0_signers(cms);
1178             if (!save_certs(signerfile, signers)) {
1179                 BIO_printf(bio_err,
1180                            "Error writing signers to %s\n", signerfile);
1181                 ret = 5;
1182                 goto end;
1183             }
1184             sk_X509_free(signers);
1185         }
1186         if (rr_print)
1187             receipt_request_print(cms);
1188
1189     } else if (operation == SMIME_VERIFY_RECEIPT) {
1190         if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) {
1191             BIO_printf(bio_err, "Verification successful\n");
1192         } else {
1193             BIO_printf(bio_err, "Verification failure\n");
1194             goto end;
1195         }
1196     } else {
1197         if (noout) {
1198             if (print) {
1199                 ASN1_PCTX *pctx = NULL;
1200                 if (get_nameopt() != XN_FLAG_ONELINE) {
1201                     pctx = ASN1_PCTX_new();
1202                     if (pctx != NULL) { /* Print anyway if malloc failed */
1203                         ASN1_PCTX_set_flags(pctx, ASN1_PCTX_FLAGS_SHOW_ABSENT);
1204                         ASN1_PCTX_set_str_flags(pctx, get_nameopt());
1205                         ASN1_PCTX_set_nm_flags(pctx, get_nameopt());
1206                     }
1207                 }
1208                 CMS_ContentInfo_print_ctx(out, cms, 0, pctx);
1209                 ASN1_PCTX_free(pctx);
1210             }
1211         } else if (outformat == FORMAT_SMIME) {
1212             if (to)
1213                 BIO_printf(out, "To: %s%s", to, mime_eol);
1214             if (from)
1215                 BIO_printf(out, "From: %s%s", from, mime_eol);
1216             if (subject)
1217                 BIO_printf(out, "Subject: %s%s", subject, mime_eol);
1218             if (operation == SMIME_RESIGN)
1219                 ret = SMIME_write_CMS(out, cms, indata, flags);
1220             else
1221                 ret = SMIME_write_CMS(out, cms, in, flags);
1222         } else if (outformat == FORMAT_PEM) {
1223             ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
1224         } else if (outformat == FORMAT_ASN1) {
1225             ret = i2d_CMS_bio_stream(out, cms, in, flags);
1226         } else {
1227             BIO_printf(bio_err, "Bad output format for CMS file\n");
1228             goto end;
1229         }
1230         if (ret <= 0) {
1231             ret = 6;
1232             goto end;
1233         }
1234     }
1235     ret = 0;
1236  end:
1237     if (ret)
1238         ERR_print_errors(bio_err);
1239     sk_X509_pop_free(encerts, X509_free);
1240     sk_X509_pop_free(other, X509_free);
1241     X509_VERIFY_PARAM_free(vpm);
1242     sk_OPENSSL_STRING_free(sksigners);
1243     sk_OPENSSL_STRING_free(skkeys);
1244     OPENSSL_free(secret_key);
1245     OPENSSL_free(secret_keyid);
1246     OPENSSL_free(pwri_tmp);
1247     ASN1_OBJECT_free(econtent_type);
1248     CMS_ReceiptRequest_free(rr);
1249     sk_OPENSSL_STRING_free(rr_to);
1250     sk_OPENSSL_STRING_free(rr_from);
1251     for (key_param = key_first; key_param;) {
1252         cms_key_param *tparam;
1253         sk_OPENSSL_STRING_free(key_param->param);
1254         tparam = key_param->next;
1255         OPENSSL_free(key_param);
1256         key_param = tparam;
1257     }
1258     X509_STORE_free(store);
1259     X509_free(cert);
1260     X509_free(recip);
1261     X509_free(signer);
1262     EVP_PKEY_free(key);
1263     CMS_ContentInfo_free(cms);
1264     CMS_ContentInfo_free(rcms);
1265     release_engine(e);
1266     BIO_free(rctin);
1267     BIO_free(in);
1268     BIO_free(indata);
1269     BIO_free_all(out);
1270     OPENSSL_free(passin);
1271     NCONF_free(conf);
1272     return ret;
1273 }
1274
1275 static int save_certs(char *signerfile, STACK_OF(X509) *signers)
1276 {
1277     int i;
1278     BIO *tmp;
1279     if (signerfile == NULL)
1280         return 1;
1281     tmp = BIO_new_file(signerfile, "w");
1282     if (tmp == NULL)
1283         return 0;
1284     for (i = 0; i < sk_X509_num(signers); i++)
1285         PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
1286     BIO_free(tmp);
1287     return 1;
1288 }
1289
1290 /* Minimal callback just to output policy info (if any) */
1291
1292 static int cms_cb(int ok, X509_STORE_CTX *ctx)
1293 {
1294     int error;
1295
1296     error = X509_STORE_CTX_get_error(ctx);
1297
1298     verify_err = error;
1299
1300     if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
1301         && ((error != X509_V_OK) || (ok != 2)))
1302         return ok;
1303
1304     policies_print(ctx);
1305
1306     return ok;
1307
1308 }
1309
1310 static void gnames_stack_print(STACK_OF(GENERAL_NAMES) *gns)
1311 {
1312     STACK_OF(GENERAL_NAME) *gens;
1313     GENERAL_NAME *gen;
1314     int i, j;
1315
1316     for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) {
1317         gens = sk_GENERAL_NAMES_value(gns, i);
1318         for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) {
1319             gen = sk_GENERAL_NAME_value(gens, j);
1320             BIO_puts(bio_err, "    ");
1321             GENERAL_NAME_print(bio_err, gen);
1322             BIO_puts(bio_err, "\n");
1323         }
1324     }
1325     return;
1326 }
1327
1328 static void receipt_request_print(CMS_ContentInfo *cms)
1329 {
1330     STACK_OF(CMS_SignerInfo) *sis;
1331     CMS_SignerInfo *si;
1332     CMS_ReceiptRequest *rr;
1333     int allorfirst;
1334     STACK_OF(GENERAL_NAMES) *rto, *rlist;
1335     ASN1_STRING *scid;
1336     int i, rv;
1337     sis = CMS_get0_SignerInfos(cms);
1338     for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) {
1339         si = sk_CMS_SignerInfo_value(sis, i);
1340         rv = CMS_get1_ReceiptRequest(si, &rr);
1341         BIO_printf(bio_err, "Signer %d:\n", i + 1);
1342         if (rv == 0) {
1343             BIO_puts(bio_err, "  No Receipt Request\n");
1344         } else if (rv < 0) {
1345             BIO_puts(bio_err, "  Receipt Request Parse Error\n");
1346             ERR_print_errors(bio_err);
1347         } else {
1348             const char *id;
1349             int idlen;
1350             CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst,
1351                                            &rlist, &rto);
1352             BIO_puts(bio_err, "  Signed Content ID:\n");
1353             idlen = ASN1_STRING_length(scid);
1354             id = (const char *)ASN1_STRING_get0_data(scid);
1355             BIO_dump_indent(bio_err, id, idlen, 4);
1356             BIO_puts(bio_err, "  Receipts From");
1357             if (rlist != NULL) {
1358                 BIO_puts(bio_err, " List:\n");
1359                 gnames_stack_print(rlist);
1360             } else if (allorfirst == 1) {
1361                 BIO_puts(bio_err, ": First Tier\n");
1362             } else if (allorfirst == 0) {
1363                 BIO_puts(bio_err, ": All\n");
1364             } else {
1365                 BIO_printf(bio_err, " Unknown (%d)\n", allorfirst);
1366             }
1367             BIO_puts(bio_err, "  Receipts To:\n");
1368             gnames_stack_print(rto);
1369         }
1370         CMS_ReceiptRequest_free(rr);
1371     }
1372 }
1373
1374 static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns)
1375 {
1376     int i;
1377     STACK_OF(GENERAL_NAMES) *ret;
1378     GENERAL_NAMES *gens = NULL;
1379     GENERAL_NAME *gen = NULL;
1380     ret = sk_GENERAL_NAMES_new_null();
1381     if (ret == NULL)
1382         goto err;
1383     for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) {
1384         char *str = sk_OPENSSL_STRING_value(ns, i);
1385         gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0);
1386         if (gen == NULL)
1387             goto err;
1388         gens = GENERAL_NAMES_new();
1389         if (gens == NULL)
1390             goto err;
1391         if (!sk_GENERAL_NAME_push(gens, gen))
1392             goto err;
1393         gen = NULL;
1394         if (!sk_GENERAL_NAMES_push(ret, gens))
1395             goto err;
1396         gens = NULL;
1397     }
1398
1399     return ret;
1400
1401  err:
1402     sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free);
1403     GENERAL_NAMES_free(gens);
1404     GENERAL_NAME_free(gen);
1405     return NULL;
1406 }
1407
1408 static CMS_ReceiptRequest *make_receipt_request(
1409    STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst,
1410    STACK_OF(OPENSSL_STRING) *rr_from,
1411    OPENSSL_CTX *libctx, const char *propq)
1412 {
1413     STACK_OF(GENERAL_NAMES) *rct_to = NULL, *rct_from = NULL;
1414     CMS_ReceiptRequest *rr;
1415     rct_to = make_names_stack(rr_to);
1416     if (rct_to == NULL)
1417         goto err;
1418     if (rr_from != NULL) {
1419         rct_from = make_names_stack(rr_from);
1420         if (rct_from == NULL)
1421             goto err;
1422     } else {
1423         rct_from = NULL;
1424     }
1425     rr = CMS_ReceiptRequest_create0_with_libctx(NULL, -1, rr_allorfirst,
1426                                                 rct_from, rct_to, libctx, propq);
1427     return rr;
1428  err:
1429     sk_GENERAL_NAMES_pop_free(rct_to, GENERAL_NAMES_free);
1430     return NULL;
1431 }
1432
1433 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
1434                               STACK_OF(OPENSSL_STRING) *param)
1435 {
1436     char *keyopt;
1437     int i;
1438     if (sk_OPENSSL_STRING_num(param) <= 0)
1439         return 1;
1440     for (i = 0; i < sk_OPENSSL_STRING_num(param); i++) {
1441         keyopt = sk_OPENSSL_STRING_value(param, i);
1442         if (pkey_ctrl_string(pctx, keyopt) <= 0) {
1443             BIO_printf(bio_err, "parameter error \"%s\"\n", keyopt);
1444             ERR_print_errors(bio_err);
1445             return 0;
1446         }
1447     }
1448     return 1;
1449 }
1450
1451 #endif