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