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