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