2 * Copyright 2008-2019 The OpenSSL Project Authors. All Rights Reserved.
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
10 /* CMS utility function */
17 #ifndef OPENSSL_NO_CMS
19 # include <openssl/crypto.h>
20 # include <openssl/pem.h>
21 # include <openssl/err.h>
22 # include <openssl/x509_vfy.h>
23 # include <openssl/x509v3.h>
24 # include <openssl/cms.h>
26 static int save_certs(char *signerfile, STACK_OF(X509) *signers);
27 static int cms_cb(int ok, X509_STORE_CTX *ctx);
28 static void receipt_request_print(CMS_ContentInfo *cms);
29 static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING)
30 *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING)
32 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
33 STACK_OF(OPENSSL_STRING) *param);
35 # define SMIME_OP 0x10
36 # define SMIME_IP 0x20
37 # define SMIME_SIGNERS 0x40
38 # define SMIME_ENCRYPT (1 | SMIME_OP)
39 # define SMIME_DECRYPT (2 | SMIME_IP)
40 # define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS)
41 # define SMIME_VERIFY (4 | SMIME_IP)
42 # define SMIME_CMSOUT (5 | SMIME_IP | SMIME_OP)
43 # define SMIME_RESIGN (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
44 # define SMIME_DATAOUT (7 | SMIME_IP)
45 # define SMIME_DATA_CREATE (8 | SMIME_OP)
46 # define SMIME_DIGEST_VERIFY (9 | SMIME_IP)
47 # define SMIME_DIGEST_CREATE (10 | SMIME_OP)
48 # define SMIME_UNCOMPRESS (11 | SMIME_IP)
49 # define SMIME_COMPRESS (12 | SMIME_OP)
50 # define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP)
51 # define SMIME_ENCRYPTED_ENCRYPT (14 | SMIME_OP)
52 # define SMIME_SIGN_RECEIPT (15 | SMIME_IP | SMIME_OP)
53 # define SMIME_VERIFY_RECEIPT (16 | SMIME_IP)
55 static int verify_err = 0;
57 typedef struct cms_key_param_st cms_key_param;
59 struct cms_key_param_st {
61 STACK_OF(OPENSSL_STRING) *param;
65 typedef enum OPTION_choice {
66 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
67 OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENCRYPT,
68 OPT_DECRYPT, OPT_SIGN, OPT_CADES, OPT_SIGN_RECEIPT, OPT_RESIGN,
69 OPT_VERIFY, OPT_VERIFY_RETCODE, OPT_VERIFY_RECEIPT,
70 OPT_CMSOUT, OPT_DATA_OUT, OPT_DATA_CREATE, OPT_DIGEST_VERIFY,
71 OPT_DIGEST_CREATE, OPT_COMPRESS, OPT_UNCOMPRESS,
72 OPT_ED_DECRYPT, OPT_ED_ENCRYPT, OPT_DEBUG_DECRYPT, OPT_TEXT,
73 OPT_ASCIICRLF, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCERTS,
74 OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP, OPT_BINARY, OPT_KEYID,
75 OPT_NOSIGS, OPT_NO_CONTENT_VERIFY, OPT_NO_ATTR_VERIFY, OPT_INDEF,
76 OPT_NOINDEF, OPT_CRLFEOL, OPT_NOOUT, OPT_RR_PRINT,
77 OPT_RR_ALL, OPT_RR_FIRST, OPT_RCTFORM, OPT_CERTFILE, OPT_CAFILE,
78 OPT_CAPATH, OPT_NOCAPATH, OPT_NOCAFILE,OPT_CONTENT, OPT_PRINT,
79 OPT_SECRETKEY, OPT_SECRETKEYID, OPT_PWRI_PASSWORD, OPT_ECONTENT_TYPE,
80 OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP,
81 OPT_CERTSOUT, OPT_MD, OPT_INKEY, OPT_KEYFORM, OPT_KEYOPT, OPT_RR_FROM,
82 OPT_RR_TO, OPT_AES128_WRAP, OPT_AES192_WRAP, OPT_AES256_WRAP,
83 OPT_3DES_WRAP, OPT_ENGINE,
89 const OPTIONS cms_options[] = {
90 {OPT_HELP_STR, 1, '-', "Usage: %s [options] cert.pem...\n"},
91 {OPT_HELP_STR, 1, '-',
92 " cert.pem... recipient certs for encryption\n"},
93 {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
94 {"help", OPT_HELP, '-', "Display this summary"},
95 {"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"},
96 {"outform", OPT_OUTFORM, 'c',
97 "Output format SMIME (default), PEM or DER"},
98 {"in", OPT_IN, '<', "Input file"},
99 {"out", OPT_OUT, '>', "Output file"},
100 {"encrypt", OPT_ENCRYPT, '-', "Encrypt message"},
101 {"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"},
102 {"sign", OPT_SIGN, '-', "Sign message"},
103 {"sign_receipt", OPT_SIGN_RECEIPT, '-', "Generate a signed receipt for the message"},
104 {"resign", OPT_RESIGN, '-', "Resign a signed message"},
105 {"cades", OPT_CADES, '-', "Include signer certificate digest"},
106 {"verify", OPT_VERIFY, '-', "Verify signed message"},
107 {"verify_retcode", OPT_VERIFY_RETCODE, '-',
108 "Exit non-zero on verification failure"},
109 {"verify_receipt", OPT_VERIFY_RECEIPT, '<',
110 "Verify receipts; exit if receipt signatures do not verify"},
111 {"cmsout", OPT_CMSOUT, '-', "Output CMS structure"},
112 {"data_out", OPT_DATA_OUT, '-', "Copy CMS \"Data\" object to output"},
113 {"data_create", OPT_DATA_CREATE, '-', "Create a CMS \"Data\" object"},
114 {"digest_verify", OPT_DIGEST_VERIFY, '-',
115 "Verify a CMS \"DigestedData\" object and output it"},
116 {"digest_create", OPT_DIGEST_CREATE, '-',
117 "Create a CMS \"DigestedData\" object"},
118 {"compress", OPT_COMPRESS, '-', "Create a CMS \"CompressedData\" object"},
119 {"uncompress", OPT_UNCOMPRESS, '-', "Uncompress a CMS \"CompressedData\" object"},
120 {"EncryptedData_decrypt", OPT_ED_DECRYPT, '-',
121 "Decrypt CMS \"EncryptedData\" object using symmetric key"},
122 {"EncryptedData_encrypt", OPT_ED_ENCRYPT, '-',
123 "Create CMS \"EncryptedData\" object using symmetric key"},
124 {"debug_decrypt", OPT_DEBUG_DECRYPT, '-',
125 "Disable MMA protection and return an error if no recipient found"
126 " (see documentation)"},
127 {"text", OPT_TEXT, '-', "Include or delete text MIME headers"},
128 {"asciicrlf", OPT_ASCIICRLF, '-',
129 "Perform CRLF canonicalisation when signing"},
130 {"nointern", OPT_NOINTERN, '-',
131 "Don't search certificates in message for signer"},
132 {"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"},
133 {"nocerts", OPT_NOCERTS, '-',
134 "Don't include signers certificate when signing"},
135 {"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"},
136 {"nodetach", OPT_NODETACH, '-', "Use opaque signing"},
137 {"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"},
138 {"binary", OPT_BINARY, '-', "Don't translate message to text"},
139 {"keyid", OPT_KEYID, '-', "Use subject key identifier"},
140 {"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"},
141 {"no_content_verify", OPT_NO_CONTENT_VERIFY, '-',
142 "Do not verify signed content signatures"},
143 {"no_attr_verify", OPT_NO_ATTR_VERIFY, '-',
144 "Do not verify signed attribute signatures"},
145 {"stream", OPT_INDEF, '-', "Enable CMS streaming"},
146 {"indef", OPT_INDEF, '-', "Same as -stream"},
147 {"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"},
148 {"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of CR only" },
149 {"noout", OPT_NOOUT, '-', "For the -cmsout operation do not output the parsed CMS structure"},
150 {"receipt_request_print", OPT_RR_PRINT, '-', "Print CMS Receipt Request" },
151 {"receipt_request_all", OPT_RR_ALL, '-',
152 "When signing, create a receipt request for all recipients"},
153 {"receipt_request_first", OPT_RR_FIRST, '-',
154 "When signing, create a receipt request for first recipient"},
155 {"rctform", OPT_RCTFORM, 'F', "Receipt file format"},
156 {"certfile", OPT_CERTFILE, '<', "Other certificates file"},
157 {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
158 {"CApath", OPT_CAPATH, '/', "trusted certificates directory"},
159 {"no-CAfile", OPT_NOCAFILE, '-',
160 "Do not load the default certificates file"},
161 {"no-CApath", OPT_NOCAPATH, '-',
162 "Do not load certificates from the default certificates directory"},
163 {"content", OPT_CONTENT, '<',
164 "Supply or override content for detached signature"},
165 {"print", OPT_PRINT, '-',
166 "For the -cmsout operation print out all fields of the CMS structure"},
167 {"secretkey", OPT_SECRETKEY, 's',
168 "Use specified hex-encoded key to decrypt/encrypt recipients or content"},
169 {"secretkeyid", OPT_SECRETKEYID, 's',
170 "Identity of the -secretkey for CMS \"KEKRecipientInfo\" object"},
171 {"pwri_password", OPT_PWRI_PASSWORD, 's',
172 "Specific password for recipient"},
173 {"econtent_type", OPT_ECONTENT_TYPE, 's', "OID for external content"},
174 {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
175 {"to", OPT_TO, 's', "To address"},
176 {"from", OPT_FROM, 's', "From address"},
177 {"subject", OPT_SUBJECT, 's', "Subject"},
178 {"signer", OPT_SIGNER, 's', "Signer certificate file"},
179 {"recip", OPT_RECIP, '<', "Recipient cert file for decryption"},
180 {"certsout", OPT_CERTSOUT, '>', "Certificate output file"},
181 {"md", OPT_MD, 's', "Digest algorithm to use when signing or resigning"},
182 {"inkey", OPT_INKEY, 's',
183 "Input private key (if not signer or recipient)"},
184 {"keyform", OPT_KEYFORM, 'f', "Input private key format (PEM or ENGINE)"},
185 {"keyopt", OPT_KEYOPT, 's', "Set public key parameters as n:v pairs"},
186 {"receipt_request_from", OPT_RR_FROM, 's',
187 "Create signed receipt request with specified email address"},
188 {"receipt_request_to", OPT_RR_TO, 's',
189 "Create signed receipt targeted to specified address"},
190 {"", OPT_CIPHER, '-', "Any supported cipher"},
193 {"aes128-wrap", OPT_AES128_WRAP, '-', "Use AES128 to wrap key"},
194 {"aes192-wrap", OPT_AES192_WRAP, '-', "Use AES192 to wrap key"},
195 {"aes256-wrap", OPT_AES256_WRAP, '-', "Use AES256 to wrap key"},
196 # ifndef OPENSSL_NO_DES
197 {"des3-wrap", OPT_3DES_WRAP, '-', "Use 3DES-EDE to wrap key"},
199 # ifndef OPENSSL_NO_ENGINE
200 {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
205 int cms_main(int argc, char **argv)
207 ASN1_OBJECT *econtent_type = NULL;
208 BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
209 CMS_ContentInfo *cms = NULL, *rcms = NULL;
210 CMS_ReceiptRequest *rr = NULL;
212 EVP_PKEY *key = NULL;
213 const EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
214 const EVP_MD *sign_md = NULL;
215 STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
216 STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
217 STACK_OF(X509) *encerts = NULL, *other = NULL;
218 X509 *cert = NULL, *recip = NULL, *signer = NULL;
219 X509_STORE *store = NULL;
220 X509_VERIFY_PARAM *vpm = NULL;
221 char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
222 const char *CAfile = NULL, *CApath = NULL;
223 char *certsoutfile = NULL;
224 int noCAfile = 0, noCApath = 0;
225 char *infile = NULL, *outfile = NULL, *rctfile = NULL;
226 char *passinarg = NULL, *passin = NULL, *signerfile = NULL, *recipfile = NULL;
227 char *to = NULL, *from = NULL, *subject = NULL, *prog;
228 cms_key_param *key_first = NULL, *key_param = NULL;
229 int flags = CMS_DETACHED, noout = 0, print = 0, keyidx = -1, vpmtouched = 0;
230 int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
231 int operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1;
232 int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_PEM;
233 size_t secret_keylen = 0, secret_keyidlen = 0;
234 unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
235 unsigned char *secret_key = NULL, *secret_keyid = NULL;
237 const char *mime_eol = "\n";
240 if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
243 prog = opt_init(argc, argv, cms_options);
244 while ((o = opt_next()) != OPT_EOF) {
249 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
252 opt_help(cms_options);
256 if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
260 if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
267 operation = SMIME_ENCRYPT;
270 operation = SMIME_DECRYPT;
273 operation = SMIME_SIGN;
275 case OPT_SIGN_RECEIPT:
276 operation = SMIME_SIGN_RECEIPT;
279 operation = SMIME_RESIGN;
282 operation = SMIME_VERIFY;
284 case OPT_VERIFY_RETCODE:
287 case OPT_VERIFY_RECEIPT:
288 operation = SMIME_VERIFY_RECEIPT;
292 operation = SMIME_CMSOUT;
295 operation = SMIME_DATAOUT;
297 case OPT_DATA_CREATE:
298 operation = SMIME_DATA_CREATE;
300 case OPT_DIGEST_VERIFY:
301 operation = SMIME_DIGEST_VERIFY;
303 case OPT_DIGEST_CREATE:
304 operation = SMIME_DIGEST_CREATE;
307 operation = SMIME_COMPRESS;
310 operation = SMIME_UNCOMPRESS;
313 operation = SMIME_ENCRYPTED_DECRYPT;
316 operation = SMIME_ENCRYPTED_ENCRYPT;
318 case OPT_DEBUG_DECRYPT:
319 flags |= CMS_DEBUG_DECRYPT;
325 flags |= CMS_ASCIICRLF;
328 flags |= CMS_NOINTERN;
331 flags |= CMS_NO_SIGNER_CERT_VERIFY;
334 flags |= CMS_NOCERTS;
340 flags &= ~CMS_DETACHED;
343 flags |= CMS_NOSMIMECAP;
352 flags |= CMS_USE_KEYID;
357 case OPT_NO_CONTENT_VERIFY:
358 flags |= CMS_NO_CONTENT_VERIFY;
360 case OPT_NO_ATTR_VERIFY:
361 flags |= CMS_NO_ATTR_VERIFY;
367 flags &= ~CMS_STREAM;
371 flags |= CMS_CRLFEOL;
386 if (rctformat == FORMAT_SMIME)
387 rcms = SMIME_read_CMS(rctin, NULL);
388 else if (rctformat == FORMAT_PEM)
389 rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL);
390 else if (rctformat == FORMAT_ASN1)
391 if (!opt_format(opt_arg(),
392 OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat))
396 certfile = opt_arg();
414 contfile = opt_arg();
418 && (rr_from = sk_OPENSSL_STRING_new_null()) == NULL)
420 sk_OPENSSL_STRING_push(rr_from, opt_arg());
424 && (rr_to = sk_OPENSSL_STRING_new_null()) == NULL)
426 sk_OPENSSL_STRING_push(rr_to, opt_arg());
432 if (secret_key != NULL) {
433 BIO_printf(bio_err, "Invalid key (supplied twice) %s\n",
437 secret_key = OPENSSL_hexstr2buf(opt_arg(), <mp);
438 if (secret_key == NULL) {
439 BIO_printf(bio_err, "Invalid key %s\n", opt_arg());
442 secret_keylen = (size_t)ltmp;
444 case OPT_SECRETKEYID:
445 if (secret_keyid != NULL) {
446 BIO_printf(bio_err, "Invalid id (supplied twice) %s\n",
450 secret_keyid = OPENSSL_hexstr2buf(opt_arg(), <mp);
451 if (secret_keyid == NULL) {
452 BIO_printf(bio_err, "Invalid id %s\n", opt_arg());
455 secret_keyidlen = (size_t)ltmp;
457 case OPT_PWRI_PASSWORD:
458 pwri_pass = (unsigned char *)opt_arg();
460 case OPT_ECONTENT_TYPE:
461 if (econtent_type != NULL) {
462 BIO_printf(bio_err, "Invalid OID (supplied twice) %s\n",
466 econtent_type = OBJ_txt2obj(opt_arg(), 0);
467 if (econtent_type == NULL) {
468 BIO_printf(bio_err, "Invalid OID %s\n", opt_arg());
473 e = setup_engine(opt_arg(), 0);
476 passinarg = opt_arg();
488 certsoutfile = opt_arg();
491 if (!opt_md(opt_arg(), &sign_md))
495 /* If previous -signer argument add signer to list */
496 if (signerfile != NULL) {
497 if (sksigners == NULL
498 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
500 sk_OPENSSL_STRING_push(sksigners, signerfile);
502 keyfile = signerfile;
504 && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
506 sk_OPENSSL_STRING_push(skkeys, keyfile);
509 signerfile = opt_arg();
512 /* If previous -inkey argument add signer to list */
513 if (keyfile != NULL) {
514 if (signerfile == NULL) {
515 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
518 if (sksigners == NULL
519 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
521 sk_OPENSSL_STRING_push(sksigners, signerfile);
524 && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
526 sk_OPENSSL_STRING_push(skkeys, keyfile);
531 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
535 if (operation == SMIME_ENCRYPT) {
536 if (encerts == NULL && (encerts = sk_X509_new_null()) == NULL)
538 cert = load_cert(opt_arg(), FORMAT_PEM,
539 "recipient certificate file");
542 sk_X509_push(encerts, cert);
545 recipfile = opt_arg();
549 if (!opt_cipher(opt_unknown(), &cipher))
554 if (operation == SMIME_ENCRYPT) {
556 keyidx += sk_X509_num(encerts);
558 if (keyfile != NULL || signerfile != NULL)
561 keyidx += sk_OPENSSL_STRING_num(skkeys);
564 BIO_printf(bio_err, "No key specified\n");
567 if (key_param == NULL || key_param->idx != keyidx) {
568 cms_key_param *nparam;
569 nparam = app_malloc(sizeof(*nparam), "key param buffer");
570 nparam->idx = keyidx;
571 if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL)
574 if (key_first == NULL)
577 key_param->next = nparam;
580 sk_OPENSSL_STRING_push(key_param->param, opt_arg());
583 if (!opt_verify(o, vpm))
592 # ifndef OPENSSL_NO_DES
593 wrap_cipher = EVP_des_ede3_wrap();
596 case OPT_AES128_WRAP:
597 wrap_cipher = EVP_aes_128_wrap();
599 case OPT_AES192_WRAP:
600 wrap_cipher = EVP_aes_192_wrap();
602 case OPT_AES256_WRAP:
603 wrap_cipher = EVP_aes_256_wrap();
607 argc = opt_num_rest();
610 if ((rr_allorfirst != -1 || rr_from != NULL) && rr_to == NULL) {
611 BIO_puts(bio_err, "No Signed Receipts Recipients\n");
615 if (!(operation & SMIME_SIGNERS) && (rr_to != NULL || rr_from != NULL)) {
616 BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
619 if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) {
620 BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
624 if (flags & CMS_CADES) {
625 if (flags & CMS_NOATTR) {
626 BIO_puts(bio_err, "Incompatible options: "
627 "CAdES required signed attributes\n");
632 if (operation & SMIME_SIGNERS) {
633 if (keyfile != NULL && signerfile == NULL) {
634 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
637 /* Check to see if any final signer needs to be appended */
638 if (signerfile != NULL) {
639 if (sksigners == NULL
640 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
642 sk_OPENSSL_STRING_push(sksigners, signerfile);
643 if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
646 keyfile = signerfile;
647 sk_OPENSSL_STRING_push(skkeys, keyfile);
649 if (sksigners == NULL) {
650 BIO_printf(bio_err, "No signer certificate specified\n");
655 } else if (operation == SMIME_DECRYPT) {
656 if (recipfile == NULL && keyfile == NULL
657 && secret_key == NULL && pwri_pass == NULL) {
659 "No recipient certificate or key specified\n");
662 } else if (operation == SMIME_ENCRYPT) {
663 if (*argv == NULL && secret_key == NULL
664 && pwri_pass == NULL && encerts == NULL) {
665 BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
668 } else if (!operation) {
669 BIO_printf(bio_err, "No operation option (-encrypt|-decrypt|-sign|-verify|...) specified.\n");
673 if (!app_passwd(passinarg, NULL, &passin, NULL)) {
674 BIO_printf(bio_err, "Error getting password\n");
680 if (!(operation & SMIME_SIGNERS))
681 flags &= ~CMS_DETACHED;
683 if (!(operation & SMIME_OP))
684 if (flags & CMS_BINARY)
685 outformat = FORMAT_BINARY;
687 if (!(operation & SMIME_IP))
688 if (flags & CMS_BINARY)
689 informat = FORMAT_BINARY;
691 if (operation == SMIME_ENCRYPT) {
693 # ifndef OPENSSL_NO_DES
694 cipher = EVP_des_ede3_cbc();
696 BIO_printf(bio_err, "No cipher selected\n");
701 if (secret_key && !secret_keyid) {
702 BIO_printf(bio_err, "No secret key id\n");
706 if (*argv && encerts == NULL)
707 if ((encerts = sk_X509_new_null()) == NULL)
710 if ((cert = load_cert(*argv, FORMAT_PEM,
711 "recipient certificate file")) == NULL)
713 sk_X509_push(encerts, cert);
719 if (certfile != NULL) {
720 if (!load_certs(certfile, &other, FORMAT_PEM, NULL,
721 "certificate file")) {
722 ERR_print_errors(bio_err);
727 if (recipfile != NULL && (operation == SMIME_DECRYPT)) {
728 if ((recip = load_cert(recipfile, FORMAT_PEM,
729 "recipient certificate file")) == NULL) {
730 ERR_print_errors(bio_err);
735 if (operation == SMIME_SIGN_RECEIPT) {
736 if ((signer = load_cert(signerfile, FORMAT_PEM,
737 "receipt signer certificate file")) == NULL) {
738 ERR_print_errors(bio_err);
743 if (operation == SMIME_DECRYPT) {
746 } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
748 keyfile = signerfile;
753 if (keyfile != NULL) {
754 key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
759 in = bio_open_default(infile, 'r', informat);
763 if (operation & SMIME_IP) {
764 if (informat == FORMAT_SMIME) {
765 cms = SMIME_read_CMS(in, &indata);
766 } else if (informat == FORMAT_PEM) {
767 cms = PEM_read_bio_CMS(in, NULL, NULL, NULL);
768 } else if (informat == FORMAT_ASN1) {
769 cms = d2i_CMS_bio(in, NULL);
771 BIO_printf(bio_err, "Bad input format for CMS file\n");
776 BIO_printf(bio_err, "Error reading S/MIME message\n");
779 if (contfile != NULL) {
781 if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
782 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
786 if (certsoutfile != NULL) {
787 STACK_OF(X509) *allcerts;
788 allcerts = CMS_get1_certs(cms);
789 if (!save_certs(certsoutfile, allcerts)) {
791 "Error writing certs to %s\n", certsoutfile);
795 sk_X509_pop_free(allcerts, X509_free);
799 if (rctfile != NULL) {
800 char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
801 if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) {
802 BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile);
806 if (rctformat == FORMAT_SMIME) {
807 rcms = SMIME_read_CMS(rctin, NULL);
808 } else if (rctformat == FORMAT_PEM) {
809 rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL);
810 } else if (rctformat == FORMAT_ASN1) {
811 rcms = d2i_CMS_bio(rctin, NULL);
813 BIO_printf(bio_err, "Bad input format for receipt\n");
818 BIO_printf(bio_err, "Error reading receipt\n");
823 out = bio_open_default(outfile, 'w', outformat);
827 if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) {
828 if ((store = setup_verify(CAfile, CApath, noCAfile, noCApath)) == NULL)
830 X509_STORE_set_verify_cb(store, cms_cb);
832 X509_STORE_set1_param(store, vpm);
837 if (operation == SMIME_DATA_CREATE) {
838 cms = CMS_data_create(in, flags);
839 } else if (operation == SMIME_DIGEST_CREATE) {
840 cms = CMS_digest_create(in, sign_md, flags);
841 } else if (operation == SMIME_COMPRESS) {
842 cms = CMS_compress(in, -1, flags);
843 } else if (operation == SMIME_ENCRYPT) {
845 flags |= CMS_PARTIAL;
846 cms = CMS_encrypt(NULL, in, cipher, flags);
849 for (i = 0; i < sk_X509_num(encerts); i++) {
850 CMS_RecipientInfo *ri;
851 cms_key_param *kparam;
853 X509 *x = sk_X509_value(encerts, i);
854 for (kparam = key_first; kparam; kparam = kparam->next) {
855 if (kparam->idx == i) {
856 tflags |= CMS_KEY_PARAM;
860 ri = CMS_add1_recipient_cert(cms, x, tflags);
863 if (kparam != NULL) {
865 pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
866 if (!cms_set_pkey_param(pctx, kparam->param))
869 if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE
871 EVP_CIPHER_CTX *wctx;
872 wctx = CMS_RecipientInfo_kari_get0_ctx(ri);
873 EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL);
877 if (secret_key != NULL) {
878 if (!CMS_add0_recipient_key(cms, NID_undef,
879 secret_key, secret_keylen,
880 secret_keyid, secret_keyidlen,
883 /* NULL these because call absorbs them */
887 if (pwri_pass != NULL) {
888 pwri_tmp = (unsigned char *)OPENSSL_strdup((char *)pwri_pass);
889 if (pwri_tmp == NULL)
891 if (CMS_add0_recipient_password(cms,
892 -1, NID_undef, NID_undef,
893 pwri_tmp, -1, NULL) == NULL)
897 if (!(flags & CMS_STREAM)) {
898 if (!CMS_final(cms, in, NULL, flags))
901 } else if (operation == SMIME_ENCRYPTED_ENCRYPT) {
902 cms = CMS_EncryptedData_encrypt(in, cipher,
903 secret_key, secret_keylen, flags);
905 } else if (operation == SMIME_SIGN_RECEIPT) {
906 CMS_ContentInfo *srcms = NULL;
907 STACK_OF(CMS_SignerInfo) *sis;
909 sis = CMS_get0_SignerInfos(cms);
912 si = sk_CMS_SignerInfo_value(sis, 0);
913 srcms = CMS_sign_receipt(si, signer, key, other, flags);
916 CMS_ContentInfo_free(cms);
918 } else if (operation & SMIME_SIGNERS) {
921 * If detached data content we enable streaming if S/MIME output
924 if (operation == SMIME_SIGN) {
926 if (flags & CMS_DETACHED) {
927 if (outformat == FORMAT_SMIME)
930 flags |= CMS_PARTIAL;
931 cms = CMS_sign(NULL, NULL, other, in, flags);
934 if (econtent_type != NULL)
935 CMS_set1_eContentType(cms, econtent_type);
938 rr = make_receipt_request(rr_to, rr_allorfirst, rr_from);
941 "Signed Receipt Request Creation Error\n");
946 flags |= CMS_REUSE_DIGEST;
948 for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
950 cms_key_param *kparam;
952 signerfile = sk_OPENSSL_STRING_value(sksigners, i);
953 keyfile = sk_OPENSSL_STRING_value(skkeys, i);
955 signer = load_cert(signerfile, FORMAT_PEM, "signer certificate");
956 if (signer == NULL) {
960 key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
965 for (kparam = key_first; kparam; kparam = kparam->next) {
966 if (kparam->idx == i) {
967 tflags |= CMS_KEY_PARAM;
971 si = CMS_add1_signer(cms, signer, key, sign_md, tflags);
974 if (kparam != NULL) {
976 pctx = CMS_SignerInfo_get0_pkey_ctx(si);
977 if (!cms_set_pkey_param(pctx, kparam->param))
980 if (rr != NULL && !CMS_add1_ReceiptRequest(si, rr))
987 /* If not streaming or resigning finalize structure */
988 if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
989 if (!CMS_final(cms, in, NULL, flags))
995 BIO_printf(bio_err, "Error creating CMS structure\n");
1000 if (operation == SMIME_DECRYPT) {
1001 if (flags & CMS_DEBUG_DECRYPT)
1002 CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);
1004 if (secret_key != NULL) {
1005 if (!CMS_decrypt_set1_key(cms,
1006 secret_key, secret_keylen,
1007 secret_keyid, secret_keyidlen)) {
1008 BIO_puts(bio_err, "Error decrypting CMS using secret key\n");
1014 if (!CMS_decrypt_set1_pkey(cms, key, recip)) {
1015 BIO_puts(bio_err, "Error decrypting CMS using private key\n");
1020 if (pwri_pass != NULL) {
1021 if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
1022 BIO_puts(bio_err, "Error decrypting CMS using password\n");
1027 if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
1028 BIO_printf(bio_err, "Error decrypting CMS structure\n");
1031 } else if (operation == SMIME_DATAOUT) {
1032 if (!CMS_data(cms, out, flags))
1034 } else if (operation == SMIME_UNCOMPRESS) {
1035 if (!CMS_uncompress(cms, indata, out, flags))
1037 } else if (operation == SMIME_DIGEST_VERIFY) {
1038 if (CMS_digest_verify(cms, indata, out, flags) > 0) {
1039 BIO_printf(bio_err, "Verification successful\n");
1041 BIO_printf(bio_err, "Verification failure\n");
1044 } else if (operation == SMIME_ENCRYPTED_DECRYPT) {
1045 if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
1046 indata, out, flags))
1048 } else if (operation == SMIME_VERIFY) {
1049 if (CMS_verify(cms, other, store, indata, out, flags) > 0) {
1050 BIO_printf(bio_err, "Verification successful\n");
1052 BIO_printf(bio_err, "Verification failure\n");
1054 ret = verify_err + 32;
1057 if (signerfile != NULL) {
1058 STACK_OF(X509) *signers;
1059 signers = CMS_get0_signers(cms);
1060 if (!save_certs(signerfile, signers)) {
1062 "Error writing signers to %s\n", signerfile);
1066 sk_X509_free(signers);
1069 receipt_request_print(cms);
1071 } else if (operation == SMIME_VERIFY_RECEIPT) {
1072 if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) {
1073 BIO_printf(bio_err, "Verification successful\n");
1075 BIO_printf(bio_err, "Verification failure\n");
1081 CMS_ContentInfo_print_ctx(out, cms, 0, NULL);
1082 } else if (outformat == FORMAT_SMIME) {
1084 BIO_printf(out, "To: %s%s", to, mime_eol);
1086 BIO_printf(out, "From: %s%s", from, mime_eol);
1088 BIO_printf(out, "Subject: %s%s", subject, mime_eol);
1089 if (operation == SMIME_RESIGN)
1090 ret = SMIME_write_CMS(out, cms, indata, flags);
1092 ret = SMIME_write_CMS(out, cms, in, flags);
1093 } else if (outformat == FORMAT_PEM) {
1094 ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
1095 } else if (outformat == FORMAT_ASN1) {
1096 ret = i2d_CMS_bio_stream(out, cms, in, flags);
1098 BIO_printf(bio_err, "Bad output format for CMS file\n");
1109 ERR_print_errors(bio_err);
1110 sk_X509_pop_free(encerts, X509_free);
1111 sk_X509_pop_free(other, X509_free);
1112 X509_VERIFY_PARAM_free(vpm);
1113 sk_OPENSSL_STRING_free(sksigners);
1114 sk_OPENSSL_STRING_free(skkeys);
1115 OPENSSL_free(secret_key);
1116 OPENSSL_free(secret_keyid);
1117 OPENSSL_free(pwri_tmp);
1118 ASN1_OBJECT_free(econtent_type);
1119 CMS_ReceiptRequest_free(rr);
1120 sk_OPENSSL_STRING_free(rr_to);
1121 sk_OPENSSL_STRING_free(rr_from);
1122 for (key_param = key_first; key_param;) {
1123 cms_key_param *tparam;
1124 sk_OPENSSL_STRING_free(key_param->param);
1125 tparam = key_param->next;
1126 OPENSSL_free(key_param);
1129 X509_STORE_free(store);
1134 CMS_ContentInfo_free(cms);
1135 CMS_ContentInfo_free(rcms);
1141 OPENSSL_free(passin);
1145 static int save_certs(char *signerfile, STACK_OF(X509) *signers)
1149 if (signerfile == NULL)
1151 tmp = BIO_new_file(signerfile, "w");
1154 for (i = 0; i < sk_X509_num(signers); i++)
1155 PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
1160 /* Minimal callback just to output policy info (if any) */
1162 static int cms_cb(int ok, X509_STORE_CTX *ctx)
1166 error = X509_STORE_CTX_get_error(ctx);
1170 if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
1171 && ((error != X509_V_OK) || (ok != 2)))
1174 policies_print(ctx);
1180 static void gnames_stack_print(STACK_OF(GENERAL_NAMES) *gns)
1182 STACK_OF(GENERAL_NAME) *gens;
1186 for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) {
1187 gens = sk_GENERAL_NAMES_value(gns, i);
1188 for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) {
1189 gen = sk_GENERAL_NAME_value(gens, j);
1190 BIO_puts(bio_err, " ");
1191 GENERAL_NAME_print(bio_err, gen);
1192 BIO_puts(bio_err, "\n");
1198 static void receipt_request_print(CMS_ContentInfo *cms)
1200 STACK_OF(CMS_SignerInfo) *sis;
1202 CMS_ReceiptRequest *rr;
1204 STACK_OF(GENERAL_NAMES) *rto, *rlist;
1207 sis = CMS_get0_SignerInfos(cms);
1208 for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) {
1209 si = sk_CMS_SignerInfo_value(sis, i);
1210 rv = CMS_get1_ReceiptRequest(si, &rr);
1211 BIO_printf(bio_err, "Signer %d:\n", i + 1);
1213 BIO_puts(bio_err, " No Receipt Request\n");
1214 } else if (rv < 0) {
1215 BIO_puts(bio_err, " Receipt Request Parse Error\n");
1216 ERR_print_errors(bio_err);
1220 CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst,
1222 BIO_puts(bio_err, " Signed Content ID:\n");
1223 idlen = ASN1_STRING_length(scid);
1224 id = (const char *)ASN1_STRING_get0_data(scid);
1225 BIO_dump_indent(bio_err, id, idlen, 4);
1226 BIO_puts(bio_err, " Receipts From");
1227 if (rlist != NULL) {
1228 BIO_puts(bio_err, " List:\n");
1229 gnames_stack_print(rlist);
1230 } else if (allorfirst == 1) {
1231 BIO_puts(bio_err, ": First Tier\n");
1232 } else if (allorfirst == 0) {
1233 BIO_puts(bio_err, ": All\n");
1235 BIO_printf(bio_err, " Unknown (%d)\n", allorfirst);
1237 BIO_puts(bio_err, " Receipts To:\n");
1238 gnames_stack_print(rto);
1240 CMS_ReceiptRequest_free(rr);
1244 static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns)
1247 STACK_OF(GENERAL_NAMES) *ret;
1248 GENERAL_NAMES *gens = NULL;
1249 GENERAL_NAME *gen = NULL;
1250 ret = sk_GENERAL_NAMES_new_null();
1253 for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) {
1254 char *str = sk_OPENSSL_STRING_value(ns, i);
1255 gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0);
1258 gens = GENERAL_NAMES_new();
1261 if (!sk_GENERAL_NAME_push(gens, gen))
1264 if (!sk_GENERAL_NAMES_push(ret, gens))
1272 sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free);
1273 GENERAL_NAMES_free(gens);
1274 GENERAL_NAME_free(gen);
1278 static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING)
1279 *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING)
1282 STACK_OF(GENERAL_NAMES) *rct_to = NULL, *rct_from = NULL;
1283 CMS_ReceiptRequest *rr;
1284 rct_to = make_names_stack(rr_to);
1287 if (rr_from != NULL) {
1288 rct_from = make_names_stack(rr_from);
1289 if (rct_from == NULL)
1294 rr = CMS_ReceiptRequest_create0(NULL, -1, rr_allorfirst, rct_from,
1298 sk_GENERAL_NAMES_pop_free(rct_to, GENERAL_NAMES_free);
1302 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
1303 STACK_OF(OPENSSL_STRING) *param)
1307 if (sk_OPENSSL_STRING_num(param) <= 0)
1309 for (i = 0; i < sk_OPENSSL_STRING_num(param); i++) {
1310 keyopt = sk_OPENSSL_STRING_value(param, i);
1311 if (pkey_ctrl_string(pctx, keyopt) <= 0) {
1312 BIO_printf(bio_err, "parameter error \"%s\"\n", keyopt);
1313 ERR_print_errors(bio_err);