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