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