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