c22027e3b198cc7108737a7e46e242a2465e649a
[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 static void warn_binary(const char *file)
276 {
277     BIO *bio;
278     unsigned char linebuf[1024], *cur, *end;
279     int len;
280
281     if (file == NULL)
282         return; /* cannot give a warning for stdin input */
283     if ((bio = bio_open_default(file, 'r', FORMAT_BINARY)) == NULL)
284         return; /* cannot give a proper warning since there is an error */
285     while ((len = BIO_read(bio, linebuf, sizeof(linebuf))) > 0) {
286         end = linebuf + len;
287         for (cur = linebuf; cur < end; cur++) {
288             if (*cur == '\0' || *cur >= 0x80) {
289                 BIO_printf(bio_err, "Warning: input file '%s' contains %s"
290                            " character; better use -binary option\n",
291                            file, *cur == '\0' ? "NUL" : "8-bit");
292                 goto end;
293             }
294         }
295     }
296  end:
297     BIO_free(bio);
298 }
299
300 int cms_main(int argc, char **argv)
301 {
302     CONF *conf = NULL;
303     ASN1_OBJECT *econtent_type = NULL;
304     BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
305     CMS_ContentInfo *cms = NULL, *rcms = NULL;
306     CMS_ReceiptRequest *rr = NULL;
307     ENGINE *e = NULL;
308     EVP_PKEY *key = NULL;
309     EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
310     EVP_MD *sign_md = NULL;
311     STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
312     STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
313     STACK_OF(X509) *encerts = sk_X509_new_null(), *other = NULL;
314     X509 *cert = NULL, *recip = NULL, *signer = NULL, *originator = NULL;
315     X509_STORE *store = NULL;
316     X509_VERIFY_PARAM *vpm = X509_VERIFY_PARAM_new();
317     char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
318     const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
319     char *certsoutfile = NULL, *digestname = NULL, *wrapname = NULL;
320     int noCAfile = 0, noCApath = 0, noCAstore = 0;
321     char *infile = NULL, *outfile = NULL, *rctfile = NULL;
322     char *passinarg = NULL, *passin = NULL, *signerfile = NULL;
323     char *originatorfile = NULL, *recipfile = NULL, *ciphername = NULL;
324     char *to = NULL, *from = NULL, *subject = NULL, *prog;
325     cms_key_param *key_first = NULL, *key_param = NULL;
326     int flags = CMS_DETACHED, binary_files = 0;
327     int noout = 0, print = 0, keyidx = -1, vpmtouched = 0;
328     int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
329     int operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1;
330     int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_UNDEF;
331     size_t secret_keylen = 0, secret_keyidlen = 0;
332     unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
333     unsigned char *secret_key = NULL, *secret_keyid = NULL;
334     long ltmp;
335     const char *mime_eol = "\n";
336     OPTION_CHOICE o;
337     OSSL_LIB_CTX *libctx = app_get0_libctx();
338
339     if (encerts == NULL || vpm == NULL)
340         goto end;
341
342     prog = opt_init(argc, argv, cms_options);
343     while ((o = opt_next()) != OPT_EOF) {
344         switch (o) {
345         case OPT_EOF:
346         case OPT_ERR:
347  opthelp:
348             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
349             goto end;
350         case OPT_HELP:
351             opt_help(cms_options);
352             ret = 0;
353             goto end;
354         case OPT_INFORM:
355             if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
356                 goto opthelp;
357             break;
358         case OPT_OUTFORM:
359             if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
360                 goto opthelp;
361             break;
362         case OPT_OUT:
363             outfile = opt_arg();
364             break;
365
366         case OPT_ENCRYPT:
367             operation = SMIME_ENCRYPT;
368             break;
369         case OPT_DECRYPT:
370             operation = SMIME_DECRYPT;
371             break;
372         case OPT_SIGN:
373             operation = SMIME_SIGN;
374             break;
375         case OPT_VERIFY:
376             operation = SMIME_VERIFY;
377             break;
378         case OPT_RESIGN:
379             operation = SMIME_RESIGN;
380             break;
381         case OPT_SIGN_RECEIPT:
382             operation = SMIME_SIGN_RECEIPT;
383             break;
384         case OPT_VERIFY_RECEIPT:
385             operation = SMIME_VERIFY_RECEIPT;
386             rctfile = opt_arg();
387             break;
388         case OPT_VERIFY_RETCODE:
389             verify_retcode = 1;
390             break;
391         case OPT_DIGEST_CREATE:
392             operation = SMIME_DIGEST_CREATE;
393             break;
394         case OPT_DIGEST_VERIFY:
395             operation = SMIME_DIGEST_VERIFY;
396             break;
397         case OPT_COMPRESS:
398             operation = SMIME_COMPRESS;
399             break;
400         case OPT_UNCOMPRESS:
401             operation = SMIME_UNCOMPRESS;
402             break;
403         case OPT_ED_ENCRYPT:
404             operation = SMIME_ENCRYPTED_ENCRYPT;
405             break;
406         case OPT_ED_DECRYPT:
407             operation = SMIME_ENCRYPTED_DECRYPT;
408             break;
409         case OPT_DATA_CREATE:
410             operation = SMIME_DATA_CREATE;
411             break;
412         case OPT_DATA_OUT:
413             operation = SMIME_DATA_OUT;
414             break;
415         case OPT_CMSOUT:
416             operation = SMIME_CMSOUT;
417             break;
418
419         case OPT_DEBUG_DECRYPT:
420             flags |= CMS_DEBUG_DECRYPT;
421             break;
422         case OPT_TEXT:
423             flags |= CMS_TEXT;
424             break;
425         case OPT_ASCIICRLF:
426             flags |= CMS_ASCIICRLF;
427             break;
428         case OPT_NOINTERN:
429             flags |= CMS_NOINTERN;
430             break;
431         case OPT_NOVERIFY:
432             flags |= CMS_NO_SIGNER_CERT_VERIFY;
433             break;
434         case OPT_NOCERTS:
435             flags |= CMS_NOCERTS;
436             break;
437         case OPT_NOATTR:
438             flags |= CMS_NOATTR;
439             break;
440         case OPT_NODETACH:
441             flags &= ~CMS_DETACHED;
442             break;
443         case OPT_NOSMIMECAP:
444             flags |= CMS_NOSMIMECAP;
445             break;
446         case OPT_BINARY:
447             flags |= CMS_BINARY;
448             break;
449         case OPT_CADES:
450             flags |= CMS_CADES;
451             break;
452         case OPT_KEYID:
453             flags |= CMS_USE_KEYID;
454             break;
455         case OPT_NOSIGS:
456             flags |= CMS_NOSIGS;
457             break;
458         case OPT_NO_CONTENT_VERIFY:
459             flags |= CMS_NO_CONTENT_VERIFY;
460             break;
461         case OPT_NO_ATTR_VERIFY:
462             flags |= CMS_NO_ATTR_VERIFY;
463             break;
464         case OPT_INDEF:
465             flags |= CMS_STREAM;
466             break;
467         case OPT_NOINDEF:
468             flags &= ~CMS_STREAM;
469             break;
470         case OPT_CRLFEOL:
471             mime_eol = "\r\n";
472             flags |= CMS_CRLFEOL;
473             break;
474         case OPT_NOOUT:
475             noout = 1;
476             break;
477         case OPT_RR_PRINT:
478             rr_print = 1;
479             break;
480         case OPT_RR_ALL:
481             rr_allorfirst = 0;
482             break;
483         case OPT_RR_FIRST:
484             rr_allorfirst = 1;
485             break;
486         case OPT_RCTFORM:
487             if (!opt_format(opt_arg(),
488                             OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat))
489                 goto opthelp;
490             break;
491         case OPT_CERTFILE:
492             certfile = opt_arg();
493             break;
494         case OPT_CAFILE:
495             CAfile = opt_arg();
496             break;
497         case OPT_CAPATH:
498             CApath = opt_arg();
499             break;
500         case OPT_CASTORE:
501             CAstore = opt_arg();
502             break;
503         case OPT_NOCAFILE:
504             noCAfile = 1;
505             break;
506         case OPT_NOCAPATH:
507             noCApath = 1;
508             break;
509         case OPT_NOCASTORE:
510             noCAstore = 1;
511             break;
512         case OPT_IN:
513             infile = opt_arg();
514             break;
515         case OPT_CONTENT:
516             contfile = opt_arg();
517             break;
518         case OPT_RR_FROM:
519             if (rr_from == NULL
520                 && (rr_from = sk_OPENSSL_STRING_new_null()) == NULL)
521                 goto end;
522             sk_OPENSSL_STRING_push(rr_from, opt_arg());
523             break;
524         case OPT_RR_TO:
525             if (rr_to == NULL
526                 && (rr_to = sk_OPENSSL_STRING_new_null()) == NULL)
527                 goto end;
528             sk_OPENSSL_STRING_push(rr_to, opt_arg());
529             break;
530         case OPT_PRINT:
531             noout = print = 1;
532             break;
533         case OPT_NAMEOPT:
534             if (!set_nameopt(opt_arg()))
535                 goto opthelp;
536             break;
537         case OPT_SECRETKEY:
538             if (secret_key != NULL) {
539                 BIO_printf(bio_err, "Invalid key (supplied twice) %s\n",
540                            opt_arg());
541                 goto opthelp;
542             }
543             secret_key = OPENSSL_hexstr2buf(opt_arg(), &ltmp);
544             if (secret_key == NULL) {
545                 BIO_printf(bio_err, "Invalid key %s\n", opt_arg());
546                 goto end;
547             }
548             secret_keylen = (size_t)ltmp;
549             break;
550         case OPT_SECRETKEYID:
551             if (secret_keyid != NULL) {
552                 BIO_printf(bio_err, "Invalid id (supplied twice) %s\n",
553                            opt_arg());
554                 goto opthelp;
555             }
556             secret_keyid = OPENSSL_hexstr2buf(opt_arg(), &ltmp);
557             if (secret_keyid == NULL) {
558                 BIO_printf(bio_err, "Invalid id %s\n", opt_arg());
559                 goto opthelp;
560             }
561             secret_keyidlen = (size_t)ltmp;
562             break;
563         case OPT_PWRI_PASSWORD:
564             pwri_pass = (unsigned char *)opt_arg();
565             break;
566         case OPT_ECONTENT_TYPE:
567             if (econtent_type != NULL) {
568                 BIO_printf(bio_err, "Invalid OID (supplied twice) %s\n",
569                            opt_arg());
570                 goto opthelp;
571             }
572             econtent_type = OBJ_txt2obj(opt_arg(), 0);
573             if (econtent_type == NULL) {
574                 BIO_printf(bio_err, "Invalid OID %s\n", opt_arg());
575                 goto opthelp;
576             }
577             break;
578         case OPT_ENGINE:
579             e = setup_engine(opt_arg(), 0);
580             break;
581         case OPT_PASSIN:
582             passinarg = opt_arg();
583             break;
584         case OPT_TO:
585             to = opt_arg();
586             break;
587         case OPT_FROM:
588             from = opt_arg();
589             break;
590         case OPT_SUBJECT:
591             subject = opt_arg();
592             break;
593         case OPT_CERTSOUT:
594             certsoutfile = opt_arg();
595             break;
596         case OPT_MD:
597             digestname = opt_arg();
598             break;
599         case OPT_SIGNER:
600             /* If previous -signer argument add signer to list */
601             if (signerfile != NULL) {
602                 if (sksigners == NULL
603                     && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
604                     goto end;
605                 sk_OPENSSL_STRING_push(sksigners, signerfile);
606                 if (keyfile == NULL)
607                     keyfile = signerfile;
608                 if (skkeys == NULL
609                     && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
610                     goto end;
611                 sk_OPENSSL_STRING_push(skkeys, keyfile);
612                 keyfile = NULL;
613             }
614             signerfile = opt_arg();
615             break;
616         case OPT_ORIGINATOR:
617             originatorfile = opt_arg();
618             break;
619         case OPT_INKEY:
620             /* If previous -inkey argument add signer to list */
621             if (keyfile != NULL) {
622                 if (signerfile == NULL) {
623                     BIO_puts(bio_err, "Illegal -inkey without -signer\n");
624                     goto end;
625                 }
626                 if (sksigners == NULL
627                     && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
628                     goto end;
629                 sk_OPENSSL_STRING_push(sksigners, signerfile);
630                 signerfile = NULL;
631                 if (skkeys == NULL
632                     && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
633                     goto end;
634                 sk_OPENSSL_STRING_push(skkeys, keyfile);
635             }
636             keyfile = opt_arg();
637             break;
638         case OPT_KEYFORM:
639             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
640                 goto opthelp;
641             break;
642         case OPT_RECIP:
643             if (operation == SMIME_ENCRYPT) {
644                 cert = load_cert(opt_arg(), FORMAT_UNDEF,
645                                  "recipient certificate file");
646                 if (cert == NULL)
647                     goto end;
648                 sk_X509_push(encerts, cert);
649                 cert = NULL;
650             } else {
651                 recipfile = opt_arg();
652             }
653             break;
654         case OPT_CIPHER:
655             ciphername = opt_unknown();
656             break;
657         case OPT_KEYOPT:
658             keyidx = -1;
659             if (operation == SMIME_ENCRYPT) {
660                 if (sk_X509_num(encerts) > 0)
661                     keyidx += sk_X509_num(encerts);
662             } else {
663                 if (keyfile != NULL || signerfile != NULL)
664                     keyidx++;
665                 if (skkeys != NULL)
666                     keyidx += sk_OPENSSL_STRING_num(skkeys);
667             }
668             if (keyidx < 0) {
669                 BIO_printf(bio_err, "No key specified\n");
670                 goto opthelp;
671             }
672             if (key_param == NULL || key_param->idx != keyidx) {
673                 cms_key_param *nparam;
674                 nparam = app_malloc(sizeof(*nparam), "key param buffer");
675                 if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL) {
676                     OPENSSL_free(nparam);
677                     goto end;
678                 }
679                 nparam->idx = keyidx;
680                 nparam->next = NULL;
681                 if (key_first == NULL)
682                     key_first = nparam;
683                 else
684                     key_param->next = nparam;
685                 key_param = nparam;
686             }
687             sk_OPENSSL_STRING_push(key_param->param, opt_arg());
688             break;
689         case OPT_V_CASES:
690             if (!opt_verify(o, vpm))
691                 goto end;
692             vpmtouched++;
693             break;
694         case OPT_R_CASES:
695             if (!opt_rand(o))
696                 goto end;
697             break;
698         case OPT_PROV_CASES:
699             if (!opt_provider(o))
700                 goto end;
701             break;
702         case OPT_CONFIG:
703             conf = app_load_config_modules(opt_arg());
704             if (conf == NULL)
705                 goto end;
706             break;
707         case OPT_WRAP:
708             wrapname = opt_unknown();
709             break;
710         case OPT_AES128_WRAP:
711         case OPT_AES192_WRAP:
712         case OPT_AES256_WRAP:
713         case OPT_3DES_WRAP:
714             wrapname = opt_flag() + 1;
715             break;
716         }
717     }
718     if (!app_RAND_load())
719         goto end;
720
721     if (digestname != NULL) {
722         if (!opt_md(digestname, &sign_md))
723             goto end;
724     }
725     if (ciphername != NULL) {
726         if (!opt_cipher_any(ciphername, &cipher))
727             goto end;
728     }
729     if (wrapname != NULL) {
730         if (!opt_cipher_any(wrapname, &wrap_cipher))
731             goto end;
732     }
733
734     /* Remaining args are files to process. */
735     argc = opt_num_rest();
736     argv = opt_rest();
737
738     if ((rr_allorfirst != -1 || rr_from != NULL) && rr_to == NULL) {
739         BIO_puts(bio_err, "No Signed Receipts Recipients\n");
740         goto opthelp;
741     }
742
743     if (!(operation & SMIME_SIGNERS) && (rr_to != NULL || rr_from != NULL)) {
744         BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
745         goto opthelp;
746     }
747     if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) {
748         BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
749         goto opthelp;
750     }
751
752     if ((flags & CMS_CADES) != 0) {
753         if ((flags & CMS_NOATTR) != 0) {
754             BIO_puts(bio_err, "Incompatible options: "
755                      "CAdES requires signed attributes\n");
756             goto opthelp;
757         }
758         if (operation == SMIME_VERIFY
759                 && (flags & (CMS_NO_SIGNER_CERT_VERIFY | CMS_NO_ATTR_VERIFY)) != 0) {
760             BIO_puts(bio_err, "Incompatible options: CAdES validation requires"
761                      " certs and signed attributes validations\n");
762             goto opthelp;
763         }
764     }
765
766     if (operation & SMIME_SIGNERS) {
767         if (keyfile != NULL && signerfile == NULL) {
768             BIO_puts(bio_err, "Illegal -inkey without -signer\n");
769             goto opthelp;
770         }
771         /* Check to see if any final signer needs to be appended */
772         if (signerfile != NULL) {
773             if (sksigners == NULL
774                 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
775                 goto end;
776             sk_OPENSSL_STRING_push(sksigners, signerfile);
777             if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
778                 goto end;
779             if (keyfile == NULL)
780                 keyfile = signerfile;
781             sk_OPENSSL_STRING_push(skkeys, keyfile);
782         }
783         if (sksigners == NULL) {
784             BIO_printf(bio_err, "No signer certificate specified\n");
785             goto opthelp;
786         }
787         signerfile = NULL;
788         keyfile = NULL;
789     } else if (operation == SMIME_DECRYPT) {
790         if (recipfile == NULL && keyfile == NULL
791             && secret_key == NULL && pwri_pass == NULL) {
792             BIO_printf(bio_err,
793                        "No recipient certificate or key specified\n");
794             goto opthelp;
795         }
796     } else if (operation == SMIME_ENCRYPT) {
797         if (*argv == NULL && secret_key == NULL
798             && pwri_pass == NULL && sk_X509_num(encerts) <= 0) {
799             BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
800             goto opthelp;
801         }
802     } else if (!operation) {
803         BIO_printf(bio_err, "No operation option (-encrypt|-decrypt|-sign|-verify|...) specified.\n");
804         goto opthelp;
805     }
806
807     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
808         BIO_printf(bio_err, "Error getting password\n");
809         goto end;
810     }
811
812     ret = 2;
813
814     if ((operation & SMIME_SIGNERS) == 0) {
815         if ((flags & CMS_DETACHED) == 0)
816             BIO_printf(bio_err,
817                        "Warning: -nodetach option is ignored for non-signing operation\n");
818
819         flags &= ~CMS_DETACHED;
820     }
821     if ((operation & SMIME_IP) == 0 && contfile != NULL)
822         BIO_printf(bio_err,
823                    "Warning: -contfile option is ignored for the given operation\n");
824
825     if ((flags & CMS_BINARY) != 0) {
826         if (!(operation & SMIME_OP))
827             outformat = FORMAT_BINARY;
828         if (!(operation & SMIME_IP))
829             informat = FORMAT_BINARY;
830         if ((operation & SMIME_SIGNERS) != 0 && (flags & CMS_DETACHED) != 0)
831             binary_files = 1;
832         if ((operation & SMIME_IP) != 0 && contfile == NULL)
833             binary_files = 1;
834     }
835
836     if (operation == SMIME_ENCRYPT) {
837         if (!cipher) {
838 #ifndef OPENSSL_NO_DES
839             cipher = (EVP_CIPHER *)EVP_des_ede3_cbc();
840 #else
841             BIO_printf(bio_err, "No cipher selected\n");
842             goto end;
843 #endif
844         }
845
846         if (secret_key && !secret_keyid) {
847             BIO_printf(bio_err, "No secret key id\n");
848             goto end;
849         }
850
851         if (*argv != NULL) {
852             if (operation == SMIME_ENCRYPT) {
853                 for (; *argv != NULL; argv++) {
854                     cert = load_cert(*argv, FORMAT_UNDEF,
855                                      "recipient certificate file");
856                     if (cert == NULL)
857                         goto end;
858                     sk_X509_push(encerts, cert);
859                     cert = NULL;
860                 }
861             } else {
862                 BIO_printf(bio_err, "Warning: recipient certificate file parameters ignored for operation other than -encrypt\n");
863             }
864         }
865     }
866
867     if (certfile != NULL) {
868         if (!load_certs(certfile, 0, &other, NULL, "certificate file")) {
869             ERR_print_errors(bio_err);
870             goto end;
871         }
872     }
873
874     if (recipfile != NULL && (operation == SMIME_DECRYPT)) {
875         if ((recip = load_cert(recipfile, FORMAT_UNDEF,
876                                "recipient certificate file")) == NULL) {
877             ERR_print_errors(bio_err);
878             goto end;
879         }
880     }
881
882     if (originatorfile != NULL) {
883         if ((originator = load_cert(originatorfile, FORMAT_UNDEF,
884                                     "originator certificate file")) == NULL) {
885             ERR_print_errors(bio_err);
886             goto end;
887         }
888     }
889
890     if (operation == SMIME_SIGN_RECEIPT) {
891         if ((signer = load_cert(signerfile, FORMAT_UNDEF,
892                                 "receipt signer certificate file")) == NULL) {
893             ERR_print_errors(bio_err);
894             goto end;
895         }
896     }
897
898     if ((operation == SMIME_DECRYPT) || (operation == SMIME_ENCRYPT)) {
899         if (keyfile == NULL)
900             keyfile = recipfile;
901     } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
902         if (keyfile == NULL)
903             keyfile = signerfile;
904     } else {
905         keyfile = NULL;
906     }
907
908     if (keyfile != NULL) {
909         key = load_key(keyfile, keyform, 0, passin, e, "signing key");
910         if (key == NULL)
911             goto end;
912     }
913
914     if ((flags & CMS_BINARY) == 0)
915         warn_binary(infile);
916     in = bio_open_default(infile, 'r',
917                           binary_files ? FORMAT_BINARY : informat);
918     if (in == NULL)
919         goto end;
920
921     if (operation & SMIME_IP) {
922         cms = load_content_info(informat, in, flags, &indata, "SMIME");
923         if (cms == NULL)
924             goto end;
925         if (contfile != NULL) {
926             BIO_free(indata);
927             if ((flags & CMS_BINARY) == 0)
928                 warn_binary(contfile);
929             if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
930                 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
931                 goto end;
932             }
933         }
934         if (certsoutfile != NULL) {
935             STACK_OF(X509) *allcerts;
936             allcerts = CMS_get1_certs(cms);
937             if (!save_certs(certsoutfile, allcerts)) {
938                 BIO_printf(bio_err,
939                            "Error writing certs to %s\n", certsoutfile);
940                 ret = 5;
941                 goto end;
942             }
943             sk_X509_pop_free(allcerts, X509_free);
944         }
945     }
946
947     if (rctfile != NULL) {
948         char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
949
950         if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) {
951             BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile);
952             goto end;
953         }
954
955         rcms = load_content_info(rctformat, rctin, 0, NULL, "receipt");
956         if (rcms == NULL)
957             goto end;
958     }
959
960     out = bio_open_default(outfile, 'w',
961                            binary_files ? FORMAT_BINARY : outformat);
962     if (out == NULL)
963         goto end;
964
965     if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) {
966         if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
967                                   CAstore, noCAstore)) == NULL)
968             goto end;
969         X509_STORE_set_verify_cb(store, cms_cb);
970         if (vpmtouched)
971             X509_STORE_set1_param(store, vpm);
972     }
973
974     ret = 3;
975
976     if (operation == SMIME_DATA_CREATE) {
977         cms = CMS_data_create_ex(in, flags, libctx, app_get0_propq());
978     } else if (operation == SMIME_DIGEST_CREATE) {
979         cms = CMS_digest_create_ex(in, sign_md, flags, libctx, app_get0_propq());
980     } else if (operation == SMIME_COMPRESS) {
981         cms = CMS_compress(in, -1, flags);
982     } else if (operation == SMIME_ENCRYPT) {
983         int i;
984         flags |= CMS_PARTIAL;
985         cms = CMS_encrypt_ex(NULL, in, cipher, flags, libctx, app_get0_propq());
986         if (cms == NULL)
987             goto end;
988         for (i = 0; i < sk_X509_num(encerts); i++) {
989             CMS_RecipientInfo *ri;
990             cms_key_param *kparam;
991             int tflags = flags | CMS_KEY_PARAM;
992             /* This flag enforces allocating the EVP_PKEY_CTX for the recipient here */
993             EVP_PKEY_CTX *pctx;
994             X509 *x = sk_X509_value(encerts, i);
995             int res;
996
997             for (kparam = key_first; kparam; kparam = kparam->next) {
998                 if (kparam->idx == i) {
999                     break;
1000                 }
1001             }
1002             ri = CMS_add1_recipient(cms, x, key, originator, tflags);
1003             if (ri == NULL)
1004                 goto end;
1005
1006             pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
1007             if (kparam != NULL) {
1008                 if (!cms_set_pkey_param(pctx, kparam->param))
1009                     goto end;
1010             }
1011
1012             res = EVP_PKEY_CTX_ctrl(pctx, -1, -1,
1013                                     EVP_PKEY_CTRL_CIPHER,
1014                                     EVP_CIPHER_get_nid(cipher), NULL);
1015             if (res <= 0 && res != -2)
1016                 goto end;
1017
1018             if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE
1019                     && wrap_cipher != NULL) {
1020                 EVP_CIPHER_CTX *wctx;
1021                 wctx = CMS_RecipientInfo_kari_get0_ctx(ri);
1022                 EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL);
1023             }
1024         }
1025
1026         if (secret_key != NULL) {
1027             if (!CMS_add0_recipient_key(cms, NID_undef,
1028                                         secret_key, secret_keylen,
1029                                         secret_keyid, secret_keyidlen,
1030                                         NULL, NULL, NULL))
1031                 goto end;
1032             /* NULL these because call absorbs them */
1033             secret_key = NULL;
1034             secret_keyid = NULL;
1035         }
1036         if (pwri_pass != NULL) {
1037             pwri_tmp = (unsigned char *)OPENSSL_strdup((char *)pwri_pass);
1038             if (pwri_tmp == NULL)
1039                 goto end;
1040             if (CMS_add0_recipient_password(cms,
1041                                             -1, NID_undef, NID_undef,
1042                                             pwri_tmp, -1, NULL) == NULL)
1043                 goto end;
1044             pwri_tmp = NULL;
1045         }
1046         if (!(flags & CMS_STREAM)) {
1047             if (!CMS_final(cms, in, NULL, flags))
1048                 goto end;
1049         }
1050     } else if (operation == SMIME_ENCRYPTED_ENCRYPT) {
1051         cms = CMS_EncryptedData_encrypt_ex(in, cipher, secret_key,
1052                                            secret_keylen, flags, libctx, app_get0_propq());
1053
1054     } else if (operation == SMIME_SIGN_RECEIPT) {
1055         CMS_ContentInfo *srcms = NULL;
1056         STACK_OF(CMS_SignerInfo) *sis;
1057         CMS_SignerInfo *si;
1058         sis = CMS_get0_SignerInfos(cms);
1059         if (sis == NULL)
1060             goto end;
1061         si = sk_CMS_SignerInfo_value(sis, 0);
1062         srcms = CMS_sign_receipt(si, signer, key, other, flags);
1063         if (srcms == NULL)
1064             goto end;
1065         CMS_ContentInfo_free(cms);
1066         cms = srcms;
1067     } else if (operation & SMIME_SIGNERS) {
1068         int i;
1069         /*
1070          * If detached data content we enable streaming if S/MIME output
1071          * format.
1072          */
1073         if (operation == SMIME_SIGN) {
1074
1075             if (flags & CMS_DETACHED) {
1076                 if (outformat == FORMAT_SMIME)
1077                     flags |= CMS_STREAM;
1078             }
1079             flags |= CMS_PARTIAL;
1080             cms = CMS_sign_ex(NULL, NULL, other, in, flags, libctx, app_get0_propq());
1081             if (cms == NULL)
1082                 goto end;
1083             if (econtent_type != NULL)
1084                 CMS_set1_eContentType(cms, econtent_type);
1085
1086             if (rr_to != NULL
1087                 && ((rr = make_receipt_request(rr_to, rr_allorfirst, rr_from))
1088                     == NULL)) {
1089                 BIO_puts(bio_err, "Signed Receipt Request Creation Error\n");
1090                 goto end;
1091             }
1092         } else {
1093             flags |= CMS_REUSE_DIGEST;
1094         }
1095         for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
1096             CMS_SignerInfo *si;
1097             cms_key_param *kparam;
1098             int tflags = flags;
1099             signerfile = sk_OPENSSL_STRING_value(sksigners, i);
1100             keyfile = sk_OPENSSL_STRING_value(skkeys, i);
1101
1102             signer = load_cert(signerfile, FORMAT_UNDEF, "signer certificate");
1103             if (signer == NULL) {
1104                 ret = 2;
1105                 goto end;
1106             }
1107             key = load_key(keyfile, keyform, 0, passin, e, "signing key");
1108             if (key == NULL) {
1109                 ret = 2;
1110                 goto end;
1111             }
1112
1113             for (kparam = key_first; kparam; kparam = kparam->next) {
1114                 if (kparam->idx == i) {
1115                     tflags |= CMS_KEY_PARAM;
1116                     break;
1117                 }
1118             }
1119             si = CMS_add1_signer(cms, signer, key, sign_md, tflags);
1120             if (si == NULL)
1121                 goto end;
1122             if (kparam != NULL) {
1123                 EVP_PKEY_CTX *pctx;
1124                 pctx = CMS_SignerInfo_get0_pkey_ctx(si);
1125                 if (!cms_set_pkey_param(pctx, kparam->param))
1126                     goto end;
1127             }
1128             if (rr != NULL && !CMS_add1_ReceiptRequest(si, rr))
1129                 goto end;
1130             X509_free(signer);
1131             signer = NULL;
1132             EVP_PKEY_free(key);
1133             key = NULL;
1134         }
1135         /* If not streaming or resigning finalize structure */
1136         if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
1137             if (!CMS_final(cms, in, NULL, flags))
1138                 goto end;
1139         }
1140     }
1141
1142     if (cms == NULL) {
1143         BIO_printf(bio_err, "Error creating CMS structure\n");
1144         goto end;
1145     }
1146
1147     ret = 4;
1148     if (operation == SMIME_DECRYPT) {
1149         if (flags & CMS_DEBUG_DECRYPT)
1150             CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);
1151
1152         if (secret_key != NULL) {
1153             if (!CMS_decrypt_set1_key(cms,
1154                                       secret_key, secret_keylen,
1155                                       secret_keyid, secret_keyidlen)) {
1156                 BIO_puts(bio_err, "Error decrypting CMS using secret key\n");
1157                 goto end;
1158             }
1159         }
1160
1161         if (key != NULL) {
1162             if (!CMS_decrypt_set1_pkey_and_peer(cms, key, recip, originator)) {
1163                 BIO_puts(bio_err, "Error decrypting CMS using private key\n");
1164                 goto end;
1165             }
1166         }
1167
1168         if (pwri_pass != NULL) {
1169             if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
1170                 BIO_puts(bio_err, "Error decrypting CMS using password\n");
1171                 goto end;
1172             }
1173         }
1174
1175         if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
1176             BIO_printf(bio_err, "Error decrypting CMS structure\n");
1177             goto end;
1178         }
1179     } else if (operation == SMIME_DATA_OUT) {
1180         if (!CMS_data(cms, out, flags))
1181             goto end;
1182     } else if (operation == SMIME_UNCOMPRESS) {
1183         if (!CMS_uncompress(cms, indata, out, flags))
1184             goto end;
1185     } else if (operation == SMIME_DIGEST_VERIFY) {
1186         if (CMS_digest_verify(cms, indata, out, flags) > 0) {
1187             BIO_printf(bio_err, "Verification successful\n");
1188         } else {
1189             BIO_printf(bio_err, "Verification failure\n");
1190             goto end;
1191         }
1192     } else if (operation == SMIME_ENCRYPTED_DECRYPT) {
1193         if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
1194                                        indata, out, flags))
1195             goto end;
1196     } else if (operation == SMIME_VERIFY) {
1197         if (CMS_verify(cms, other, store, indata, out, flags) > 0) {
1198             BIO_printf(bio_err, "%s Verification successful\n",
1199                        (flags & CMS_CADES) != 0 ? "CAdES" : "CMS");
1200         } else {
1201             BIO_printf(bio_err, "%s Verification failure\n",
1202                        (flags & CMS_CADES) != 0 ? "CAdES" : "CMS");
1203             if (verify_retcode)
1204                 ret = verify_err + 32;
1205             goto end;
1206         }
1207         if (signerfile != NULL) {
1208             STACK_OF(X509) *signers = CMS_get0_signers(cms);
1209
1210             if (!save_certs(signerfile, signers)) {
1211                 BIO_printf(bio_err,
1212                            "Error writing signers to %s\n", signerfile);
1213                 ret = 5;
1214                 goto end;
1215             }
1216             sk_X509_free(signers);
1217         }
1218         if (rr_print)
1219             receipt_request_print(cms);
1220
1221     } else if (operation == SMIME_VERIFY_RECEIPT) {
1222         if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) {
1223             BIO_printf(bio_err, "Verification successful\n");
1224         } else {
1225             BIO_printf(bio_err, "Verification failure\n");
1226             goto end;
1227         }
1228     } else {
1229         if (noout) {
1230             if (print) {
1231                 ASN1_PCTX *pctx = NULL;
1232                 if (get_nameopt() != XN_FLAG_ONELINE) {
1233                     pctx = ASN1_PCTX_new();
1234                     if (pctx != NULL) { /* Print anyway if malloc failed */
1235                         ASN1_PCTX_set_flags(pctx, ASN1_PCTX_FLAGS_SHOW_ABSENT);
1236                         ASN1_PCTX_set_str_flags(pctx, get_nameopt());
1237                         ASN1_PCTX_set_nm_flags(pctx, get_nameopt());
1238                     }
1239                 }
1240                 CMS_ContentInfo_print_ctx(out, cms, 0, pctx);
1241                 ASN1_PCTX_free(pctx);
1242             }
1243         } else if (outformat == FORMAT_SMIME) {
1244             if (to)
1245                 BIO_printf(out, "To: %s%s", to, mime_eol);
1246             if (from)
1247                 BIO_printf(out, "From: %s%s", from, mime_eol);
1248             if (subject)
1249                 BIO_printf(out, "Subject: %s%s", subject, mime_eol);
1250             if (operation == SMIME_RESIGN)
1251                 ret = SMIME_write_CMS(out, cms, indata, flags);
1252             else
1253                 ret = SMIME_write_CMS(out, cms, in, flags);
1254         } else if (outformat == FORMAT_PEM) {
1255             ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
1256         } else if (outformat == FORMAT_ASN1) {
1257             ret = i2d_CMS_bio_stream(out, cms, in, flags);
1258         } else {
1259             BIO_printf(bio_err, "Bad output format for CMS file\n");
1260             goto end;
1261         }
1262         if (ret <= 0) {
1263             ret = 6;
1264             goto end;
1265         }
1266     }
1267     ret = 0;
1268  end:
1269     if (ret)
1270         ERR_print_errors(bio_err);
1271     sk_X509_pop_free(encerts, X509_free);
1272     sk_X509_pop_free(other, X509_free);
1273     X509_VERIFY_PARAM_free(vpm);
1274     sk_OPENSSL_STRING_free(sksigners);
1275     sk_OPENSSL_STRING_free(skkeys);
1276     OPENSSL_free(secret_key);
1277     OPENSSL_free(secret_keyid);
1278     OPENSSL_free(pwri_tmp);
1279     ASN1_OBJECT_free(econtent_type);
1280     CMS_ReceiptRequest_free(rr);
1281     sk_OPENSSL_STRING_free(rr_to);
1282     sk_OPENSSL_STRING_free(rr_from);
1283     for (key_param = key_first; key_param;) {
1284         cms_key_param *tparam;
1285         sk_OPENSSL_STRING_free(key_param->param);
1286         tparam = key_param->next;
1287         OPENSSL_free(key_param);
1288         key_param = tparam;
1289     }
1290     X509_STORE_free(store);
1291     X509_free(cert);
1292     X509_free(recip);
1293     X509_free(signer);
1294     EVP_PKEY_free(key);
1295     EVP_CIPHER_free(cipher);
1296     EVP_CIPHER_free(wrap_cipher);
1297     EVP_MD_free(sign_md);
1298     CMS_ContentInfo_free(cms);
1299     CMS_ContentInfo_free(rcms);
1300     release_engine(e);
1301     BIO_free(rctin);
1302     BIO_free(in);
1303     BIO_free(indata);
1304     BIO_free_all(out);
1305     OPENSSL_free(passin);
1306     NCONF_free(conf);
1307     return ret;
1308 }
1309
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
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
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
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
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
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
1449     rct_to = make_names_stack(rr_to);
1450     if (rct_to == NULL)
1451         goto err;
1452     if (rr_from != NULL) {
1453         rct_from = make_names_stack(rr_from);
1454         if (rct_from == NULL)
1455             goto err;
1456     } else {
1457         rct_from = NULL;
1458     }
1459     return CMS_ReceiptRequest_create0_ex(NULL, -1, rr_allorfirst, rct_from,
1460                                          rct_to, app_get0_libctx());
1461  err:
1462     sk_GENERAL_NAMES_pop_free(rct_to, GENERAL_NAMES_free);
1463     return NULL;
1464 }
1465
1466 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
1467                               STACK_OF(OPENSSL_STRING) *param)
1468 {
1469     char *keyopt;
1470     int i;
1471     if (sk_OPENSSL_STRING_num(param) <= 0)
1472         return 1;
1473     for (i = 0; i < sk_OPENSSL_STRING_num(param); i++) {
1474         keyopt = sk_OPENSSL_STRING_value(param, i);
1475         if (pkey_ctrl_string(pctx, keyopt) <= 0) {
1476             BIO_printf(bio_err, "parameter error \"%s\"\n", keyopt);
1477             ERR_print_errors(bio_err);
1478             return 0;
1479         }
1480     }
1481     return 1;
1482 }