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