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