2 * Copyright 2008-2020 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>
27 DEFINE_STACK_OF(CMS_SignerInfo)
28 DEFINE_STACK_OF(GENERAL_NAME)
29 DEFINE_STACK_OF(GENERAL_NAMES)
30 DEFINE_STACK_OF_STRING()
32 static int save_certs(char *signerfile, STACK_OF(X509) *signers);
33 static int cms_cb(int ok, X509_STORE_CTX *ctx);
34 static void receipt_request_print(CMS_ContentInfo *cms);
35 static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING)
36 *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING)
38 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
39 STACK_OF(OPENSSL_STRING) *param);
41 # define SMIME_OP 0x10
42 # define SMIME_IP 0x20
43 # define SMIME_SIGNERS 0x40
44 # define SMIME_ENCRYPT (1 | SMIME_OP)
45 # define SMIME_DECRYPT (2 | SMIME_IP)
46 # define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS)
47 # define SMIME_VERIFY (4 | SMIME_IP)
48 # define SMIME_CMSOUT (5 | SMIME_IP | SMIME_OP)
49 # define SMIME_RESIGN (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
50 # define SMIME_DATAOUT (7 | SMIME_IP)
51 # define SMIME_DATA_CREATE (8 | SMIME_OP)
52 # define SMIME_DIGEST_VERIFY (9 | SMIME_IP)
53 # define SMIME_DIGEST_CREATE (10 | SMIME_OP)
54 # define SMIME_UNCOMPRESS (11 | SMIME_IP)
55 # define SMIME_COMPRESS (12 | SMIME_OP)
56 # define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP)
57 # define SMIME_ENCRYPTED_ENCRYPT (14 | SMIME_OP)
58 # define SMIME_SIGN_RECEIPT (15 | SMIME_IP | SMIME_OP)
59 # define SMIME_VERIFY_RECEIPT (16 | SMIME_IP)
61 static int verify_err = 0;
63 typedef struct cms_key_param_st cms_key_param;
65 struct cms_key_param_st {
67 STACK_OF(OPENSSL_STRING) *param;
71 typedef enum OPTION_choice {
72 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
73 OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENCRYPT,
74 OPT_DECRYPT, OPT_SIGN, OPT_CADES, OPT_SIGN_RECEIPT, OPT_RESIGN,
75 OPT_VERIFY, OPT_VERIFY_RETCODE, OPT_VERIFY_RECEIPT,
76 OPT_CMSOUT, OPT_DATA_OUT, OPT_DATA_CREATE, OPT_DIGEST_VERIFY,
77 OPT_DIGEST_CREATE, OPT_COMPRESS, OPT_UNCOMPRESS,
78 OPT_ED_DECRYPT, OPT_ED_ENCRYPT, OPT_DEBUG_DECRYPT, OPT_TEXT,
79 OPT_ASCIICRLF, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCERTS,
80 OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP, OPT_BINARY, OPT_KEYID,
81 OPT_NOSIGS, OPT_NO_CONTENT_VERIFY, OPT_NO_ATTR_VERIFY, OPT_INDEF,
82 OPT_NOINDEF, OPT_CRLFEOL, OPT_NOOUT, OPT_RR_PRINT,
83 OPT_RR_ALL, OPT_RR_FIRST, OPT_RCTFORM, OPT_CERTFILE, OPT_CAFILE,
84 OPT_CAPATH, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE,
85 OPT_CONTENT, OPT_PRINT,
86 OPT_SECRETKEY, OPT_SECRETKEYID, OPT_PWRI_PASSWORD, OPT_ECONTENT_TYPE,
87 OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP,
88 OPT_CERTSOUT, OPT_MD, OPT_INKEY, OPT_KEYFORM, OPT_KEYOPT, OPT_RR_FROM,
89 OPT_RR_TO, OPT_AES128_WRAP, OPT_AES192_WRAP, OPT_AES256_WRAP,
90 OPT_3DES_WRAP, OPT_WRAP, OPT_ENGINE,
98 const OPTIONS cms_options[] = {
99 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"},
101 OPT_SECTION("General"),
102 {"help", OPT_HELP, '-', "Display this summary"},
103 {"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"},
104 {"outform", OPT_OUTFORM, 'c',
105 "Output format SMIME (default), PEM or DER"},
106 {"in", OPT_IN, '<', "Input file"},
107 {"out", OPT_OUT, '>', "Output file"},
108 {"debug_decrypt", OPT_DEBUG_DECRYPT, '-',
109 "Disable MMA protection and return an error if no recipient found"
110 " (see documentation)"},
111 {"stream", OPT_INDEF, '-', "Enable CMS streaming"},
112 {"indef", OPT_INDEF, '-', "Same as -stream"},
113 {"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"},
114 {"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of CR only" },
115 {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
116 {"CApath", OPT_CAPATH, '/', "trusted certificates directory"},
117 {"CAstore", OPT_CASTORE, ':', "trusted certificates store URI"},
118 {"no-CAfile", OPT_NOCAFILE, '-',
119 "Do not load the default certificates file"},
120 {"no-CApath", OPT_NOCAPATH, '-',
121 "Do not load certificates from the default certificates directory"},
122 {"no-CAstore", OPT_NOCASTORE, '-',
123 "Do not load certificates from the default certificates store"},
124 # ifndef OPENSSL_NO_ENGINE
125 {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
128 OPT_SECTION("Action"),
129 {"encrypt", OPT_ENCRYPT, '-', "Encrypt message"},
130 {"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"},
131 {"sign", OPT_SIGN, '-', "Sign message"},
132 {"sign_receipt", OPT_SIGN_RECEIPT, '-', "Generate a signed receipt for the message"},
133 {"resign", OPT_RESIGN, '-', "Resign a signed message"},
134 {"cades", OPT_CADES, '-', "Include signer certificate digest"},
135 {"verify", OPT_VERIFY, '-', "Verify signed message"},
136 {"verify_retcode", OPT_VERIFY_RETCODE, '-',
137 "Exit non-zero on verification failure"},
138 {"verify_receipt", OPT_VERIFY_RECEIPT, '<',
139 "Verify receipts; exit if receipt signatures do not verify"},
140 {"digest_verify", OPT_DIGEST_VERIFY, '-',
141 "Verify a CMS \"DigestedData\" object and output it"},
142 {"digest_create", OPT_DIGEST_CREATE, '-',
143 "Create a CMS \"DigestedData\" object"},
144 {"compress", OPT_COMPRESS, '-', "Create a CMS \"CompressedData\" object"},
145 {"uncompress", OPT_UNCOMPRESS, '-',
146 "Uncompress a CMS \"CompressedData\" object"},
147 {"EncryptedData_decrypt", OPT_ED_DECRYPT, '-',
148 "Decrypt CMS \"EncryptedData\" object using symmetric key"},
149 {"EncryptedData_encrypt", OPT_ED_ENCRYPT, '-',
150 "Create CMS \"EncryptedData\" object using symmetric key"},
151 {"data_out", OPT_DATA_OUT, '-', "Copy CMS \"Data\" object to output"},
152 {"data_create", OPT_DATA_CREATE, '-', "Create a CMS \"Data\" object"},
153 {"cmsout", OPT_CMSOUT, '-', "Output CMS structure"},
154 {"no_content_verify", OPT_NO_CONTENT_VERIFY, '-',
155 "Do not verify signed content signatures"},
156 {"no_attr_verify", OPT_NO_ATTR_VERIFY, '-',
157 "Do not verify signed attribute signatures"},
158 {"nointern", OPT_NOINTERN, '-',
159 "Don't search certificates in message for signer"},
160 {"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"},
162 OPT_SECTION("Formatting"),
163 {"text", OPT_TEXT, '-', "Include or delete text MIME headers"},
164 {"asciicrlf", OPT_ASCIICRLF, '-',
165 "Perform CRLF canonicalisation when signing"},
166 {"nodetach", OPT_NODETACH, '-', "Use opaque signing"},
167 {"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"},
168 {"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"},
169 {"binary", OPT_BINARY, '-', "Don't translate message to text"},
170 {"keyid", OPT_KEYID, '-', "Use subject key identifier"},
171 {"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"},
172 {"nocerts", OPT_NOCERTS, '-',
173 "Don't include signers certificate when signing"},
174 {"noout", OPT_NOOUT, '-',
175 "For the -cmsout operation do not output the parsed CMS structure"},
176 {"receipt_request_print", OPT_RR_PRINT, '-', "Print CMS Receipt Request" },
177 {"receipt_request_all", OPT_RR_ALL, '-',
178 "When signing, create a receipt request for all recipients"},
179 {"receipt_request_first", OPT_RR_FIRST, '-',
180 "When signing, create a receipt request for first recipient"},
181 {"rctform", OPT_RCTFORM, 'F', "Receipt file format"},
182 {"certfile", OPT_CERTFILE, '<', "Other certificates file"},
183 {"content", OPT_CONTENT, '<',
184 "Supply or override content for detached signature"},
185 {"print", OPT_PRINT, '-',
186 "For the -cmsout operation print out all fields of the CMS structure"},
187 {"certsout", OPT_CERTSOUT, '>', "Certificate output file"},
189 OPT_SECTION("Keying"),
190 {"secretkey", OPT_SECRETKEY, 's',
191 "Use specified hex-encoded key to decrypt/encrypt recipients or content"},
192 {"secretkeyid", OPT_SECRETKEYID, 's',
193 "Identity of the -secretkey for CMS \"KEKRecipientInfo\" object"},
194 {"pwri_password", OPT_PWRI_PASSWORD, 's',
195 "Specific password for recipient"},
196 {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
197 {"inkey", OPT_INKEY, 's',
198 "Input private key (if not signer or recipient)"},
199 {"keyform", OPT_KEYFORM, 'f', "Input private key format (ENGINE, other values ignored)"},
200 {"keyopt", OPT_KEYOPT, 's', "Set public key parameters as n:v pairs"},
202 OPT_SECTION("Mail header"),
203 {"econtent_type", OPT_ECONTENT_TYPE, 's', "OID for external content"},
204 {"to", OPT_TO, 's', "To address"},
205 {"from", OPT_FROM, 's', "From address"},
206 {"subject", OPT_SUBJECT, 's', "Subject"},
207 {"signer", OPT_SIGNER, 's', "Signer certificate file"},
208 {"originator", OPT_ORIGINATOR, 's', "Originator certificate file"},
209 {"recip", OPT_RECIP, '<', "Recipient cert file for decryption"},
210 {"receipt_request_from", OPT_RR_FROM, 's',
211 "Create signed receipt request with specified email address"},
212 {"receipt_request_to", OPT_RR_TO, 's',
213 "Create signed receipt targeted to specified address"},
215 OPT_SECTION("Encryption"),
216 {"md", OPT_MD, 's', "Digest algorithm to use when signing or resigning"},
217 {"", OPT_CIPHER, '-', "Any supported cipher"},
219 OPT_SECTION("Key-wrapping"),
220 {"aes128-wrap", OPT_AES128_WRAP, '-', "Use AES128 to wrap key"},
221 {"aes192-wrap", OPT_AES192_WRAP, '-', "Use AES192 to wrap key"},
222 {"aes256-wrap", OPT_AES256_WRAP, '-', "Use AES256 to wrap key"},
223 # ifndef OPENSSL_NO_DES
224 {"des3-wrap", OPT_3DES_WRAP, '-', "Use 3DES-EDE to wrap key"},
226 {"wrap", OPT_WRAP, 's', "Any wrap cipher to wrap key"},
233 {"cert", 0, 0, "Recipient certs (optional; used only when encrypting)"},
237 int cms_main(int argc, char **argv)
239 ASN1_OBJECT *econtent_type = NULL;
240 BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
241 CMS_ContentInfo *cms = NULL, *rcms = NULL;
242 CMS_ReceiptRequest *rr = NULL;
244 EVP_PKEY *key = NULL;
245 const EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
246 const EVP_MD *sign_md = NULL;
247 STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
248 STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
249 STACK_OF(X509) *encerts = NULL, *other = NULL;
250 X509 *cert = NULL, *recip = NULL, *signer = NULL, *originator = NULL;
251 X509_STORE *store = NULL;
252 X509_VERIFY_PARAM *vpm = NULL;
253 char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
254 const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
255 char *certsoutfile = NULL;
256 int noCAfile = 0, noCApath = 0, noCAstore = 0;
257 char *infile = NULL, *outfile = NULL, *rctfile = NULL;
258 char *passinarg = NULL, *passin = NULL, *signerfile = NULL, *originatorfile = NULL, *recipfile = NULL;
259 char *to = NULL, *from = NULL, *subject = NULL, *prog;
260 cms_key_param *key_first = NULL, *key_param = NULL;
261 int flags = CMS_DETACHED, noout = 0, print = 0, keyidx = -1, vpmtouched = 0;
262 int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
263 int operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1;
264 int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_PEM;
265 size_t secret_keylen = 0, secret_keyidlen = 0;
266 unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
267 unsigned char *secret_key = NULL, *secret_keyid = NULL;
269 const char *mime_eol = "\n";
272 if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
275 prog = opt_init(argc, argv, cms_options);
276 while ((o = opt_next()) != OPT_EOF) {
281 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
284 opt_help(cms_options);
288 if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
292 if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
299 operation = SMIME_ENCRYPT;
302 operation = SMIME_DECRYPT;
305 operation = SMIME_SIGN;
307 case OPT_SIGN_RECEIPT:
308 operation = SMIME_SIGN_RECEIPT;
311 operation = SMIME_RESIGN;
314 operation = SMIME_VERIFY;
316 case OPT_VERIFY_RETCODE:
319 case OPT_VERIFY_RECEIPT:
320 operation = SMIME_VERIFY_RECEIPT;
324 operation = SMIME_CMSOUT;
327 operation = SMIME_DATAOUT;
329 case OPT_DATA_CREATE:
330 operation = SMIME_DATA_CREATE;
332 case OPT_DIGEST_VERIFY:
333 operation = SMIME_DIGEST_VERIFY;
335 case OPT_DIGEST_CREATE:
336 operation = SMIME_DIGEST_CREATE;
339 operation = SMIME_COMPRESS;
342 operation = SMIME_UNCOMPRESS;
345 operation = SMIME_ENCRYPTED_DECRYPT;
348 operation = SMIME_ENCRYPTED_ENCRYPT;
350 case OPT_DEBUG_DECRYPT:
351 flags |= CMS_DEBUG_DECRYPT;
357 flags |= CMS_ASCIICRLF;
360 flags |= CMS_NOINTERN;
363 flags |= CMS_NO_SIGNER_CERT_VERIFY;
366 flags |= CMS_NOCERTS;
372 flags &= ~CMS_DETACHED;
375 flags |= CMS_NOSMIMECAP;
384 flags |= CMS_USE_KEYID;
389 case OPT_NO_CONTENT_VERIFY:
390 flags |= CMS_NO_CONTENT_VERIFY;
392 case OPT_NO_ATTR_VERIFY:
393 flags |= CMS_NO_ATTR_VERIFY;
399 flags &= ~CMS_STREAM;
403 flags |= CMS_CRLFEOL;
418 if (rctformat == FORMAT_SMIME)
419 rcms = SMIME_read_CMS(rctin, NULL);
420 else if (rctformat == FORMAT_PEM)
421 rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL);
422 else if (rctformat == FORMAT_ASN1)
423 if (!opt_format(opt_arg(),
424 OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat))
428 certfile = opt_arg();
452 contfile = opt_arg();
456 && (rr_from = sk_OPENSSL_STRING_new_null()) == NULL)
458 sk_OPENSSL_STRING_push(rr_from, opt_arg());
462 && (rr_to = sk_OPENSSL_STRING_new_null()) == NULL)
464 sk_OPENSSL_STRING_push(rr_to, opt_arg());
470 if (secret_key != NULL) {
471 BIO_printf(bio_err, "Invalid key (supplied twice) %s\n",
475 secret_key = OPENSSL_hexstr2buf(opt_arg(), <mp);
476 if (secret_key == NULL) {
477 BIO_printf(bio_err, "Invalid key %s\n", opt_arg());
480 secret_keylen = (size_t)ltmp;
482 case OPT_SECRETKEYID:
483 if (secret_keyid != NULL) {
484 BIO_printf(bio_err, "Invalid id (supplied twice) %s\n",
488 secret_keyid = OPENSSL_hexstr2buf(opt_arg(), <mp);
489 if (secret_keyid == NULL) {
490 BIO_printf(bio_err, "Invalid id %s\n", opt_arg());
493 secret_keyidlen = (size_t)ltmp;
495 case OPT_PWRI_PASSWORD:
496 pwri_pass = (unsigned char *)opt_arg();
498 case OPT_ECONTENT_TYPE:
499 if (econtent_type != NULL) {
500 BIO_printf(bio_err, "Invalid OID (supplied twice) %s\n",
504 econtent_type = OBJ_txt2obj(opt_arg(), 0);
505 if (econtent_type == NULL) {
506 BIO_printf(bio_err, "Invalid OID %s\n", opt_arg());
511 e = setup_engine(opt_arg(), 0);
514 passinarg = opt_arg();
526 certsoutfile = opt_arg();
529 if (!opt_md(opt_arg(), &sign_md))
533 /* If previous -signer argument add signer to list */
534 if (signerfile != NULL) {
535 if (sksigners == NULL
536 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
538 sk_OPENSSL_STRING_push(sksigners, signerfile);
540 keyfile = signerfile;
542 && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
544 sk_OPENSSL_STRING_push(skkeys, keyfile);
547 signerfile = opt_arg();
550 originatorfile = opt_arg();
553 /* If previous -inkey argument add signer to list */
554 if (keyfile != NULL) {
555 if (signerfile == NULL) {
556 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
559 if (sksigners == NULL
560 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
562 sk_OPENSSL_STRING_push(sksigners, signerfile);
565 && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
567 sk_OPENSSL_STRING_push(skkeys, keyfile);
572 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
576 if (operation == SMIME_ENCRYPT) {
577 if (encerts == NULL && (encerts = sk_X509_new_null()) == NULL)
579 cert = load_cert(opt_arg(), FORMAT_UNDEF,
580 "recipient certificate file");
583 sk_X509_push(encerts, cert);
586 recipfile = opt_arg();
590 if (!opt_cipher(opt_unknown(), &cipher))
595 if (operation == SMIME_ENCRYPT) {
597 keyidx += sk_X509_num(encerts);
599 if (keyfile != NULL || signerfile != NULL)
602 keyidx += sk_OPENSSL_STRING_num(skkeys);
605 BIO_printf(bio_err, "No key specified\n");
608 if (key_param == NULL || key_param->idx != keyidx) {
609 cms_key_param *nparam;
610 nparam = app_malloc(sizeof(*nparam), "key param buffer");
611 nparam->idx = keyidx;
612 if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL)
615 if (key_first == NULL)
618 key_param->next = nparam;
621 sk_OPENSSL_STRING_push(key_param->param, opt_arg());
624 if (!opt_verify(o, vpm))
633 if (!opt_provider(o))
637 # ifndef OPENSSL_NO_DES
638 wrap_cipher = EVP_des_ede3_wrap();
641 case OPT_AES128_WRAP:
642 wrap_cipher = EVP_aes_128_wrap();
644 case OPT_AES192_WRAP:
645 wrap_cipher = EVP_aes_192_wrap();
647 case OPT_AES256_WRAP:
648 wrap_cipher = EVP_aes_256_wrap();
651 if (!opt_cipher(opt_unknown(), &wrap_cipher))
656 argc = opt_num_rest();
659 if ((rr_allorfirst != -1 || rr_from != NULL) && rr_to == NULL) {
660 BIO_puts(bio_err, "No Signed Receipts Recipients\n");
664 if (!(operation & SMIME_SIGNERS) && (rr_to != NULL || rr_from != NULL)) {
665 BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
668 if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) {
669 BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
673 if (flags & CMS_CADES) {
674 if (flags & CMS_NOATTR) {
675 BIO_puts(bio_err, "Incompatible options: "
676 "CAdES required signed attributes\n");
681 if (operation & SMIME_SIGNERS) {
682 if (keyfile != NULL && signerfile == NULL) {
683 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
686 /* Check to see if any final signer needs to be appended */
687 if (signerfile != NULL) {
688 if (sksigners == NULL
689 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
691 sk_OPENSSL_STRING_push(sksigners, signerfile);
692 if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
695 keyfile = signerfile;
696 sk_OPENSSL_STRING_push(skkeys, keyfile);
698 if (sksigners == NULL) {
699 BIO_printf(bio_err, "No signer certificate specified\n");
704 } else if (operation == SMIME_DECRYPT) {
705 if (recipfile == NULL && keyfile == NULL
706 && secret_key == NULL && pwri_pass == NULL) {
708 "No recipient certificate or key specified\n");
711 } else if (operation == SMIME_ENCRYPT) {
712 if (*argv == NULL && secret_key == NULL
713 && pwri_pass == NULL && encerts == NULL) {
714 BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
717 } else if (!operation) {
718 BIO_printf(bio_err, "No operation option (-encrypt|-decrypt|-sign|-verify|...) specified.\n");
722 if (!app_passwd(passinarg, NULL, &passin, NULL)) {
723 BIO_printf(bio_err, "Error getting password\n");
729 if (!(operation & SMIME_SIGNERS))
730 flags &= ~CMS_DETACHED;
732 if (!(operation & SMIME_OP))
733 if (flags & CMS_BINARY)
734 outformat = FORMAT_BINARY;
736 if (!(operation & SMIME_IP))
737 if (flags & CMS_BINARY)
738 informat = FORMAT_BINARY;
740 if (operation == SMIME_ENCRYPT) {
742 # ifndef OPENSSL_NO_DES
743 cipher = EVP_des_ede3_cbc();
745 BIO_printf(bio_err, "No cipher selected\n");
750 if (secret_key && !secret_keyid) {
751 BIO_printf(bio_err, "No secret key id\n");
755 if (*argv && encerts == NULL)
756 if ((encerts = sk_X509_new_null()) == NULL)
759 if ((cert = load_cert(*argv, FORMAT_UNDEF,
760 "recipient certificate file")) == NULL)
762 sk_X509_push(encerts, cert);
768 if (certfile != NULL) {
769 if (!load_certs(certfile, &other, FORMAT_PEM, NULL,
770 "certificate file")) {
771 ERR_print_errors(bio_err);
776 if (recipfile != NULL && (operation == SMIME_DECRYPT)) {
777 if ((recip = load_cert(recipfile, FORMAT_UNDEF,
778 "recipient certificate file")) == NULL) {
779 ERR_print_errors(bio_err);
784 if (originatorfile != NULL) {
785 if ((originator = load_cert(originatorfile, FORMAT_UNDEF,
786 "originator certificate file")) == NULL) {
787 ERR_print_errors(bio_err);
792 if (operation == SMIME_SIGN_RECEIPT) {
793 if ((signer = load_cert(signerfile, FORMAT_UNDEF,
794 "receipt signer certificate file")) == NULL) {
795 ERR_print_errors(bio_err);
800 if ((operation == SMIME_DECRYPT) || (operation == SMIME_ENCRYPT)) {
803 } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
805 keyfile = signerfile;
810 if (keyfile != NULL) {
811 key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
816 in = bio_open_default(infile, 'r', informat);
820 if (operation & SMIME_IP) {
821 if (informat == FORMAT_SMIME) {
822 cms = SMIME_read_CMS(in, &indata);
823 } else if (informat == FORMAT_PEM) {
824 cms = PEM_read_bio_CMS(in, NULL, NULL, NULL);
825 } else if (informat == FORMAT_ASN1) {
826 cms = d2i_CMS_bio(in, NULL);
828 BIO_printf(bio_err, "Bad input format for CMS file\n");
833 BIO_printf(bio_err, "Error reading S/MIME message\n");
836 if (contfile != NULL) {
838 if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
839 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
843 if (certsoutfile != NULL) {
844 STACK_OF(X509) *allcerts;
845 allcerts = CMS_get1_certs(cms);
846 if (!save_certs(certsoutfile, allcerts)) {
848 "Error writing certs to %s\n", certsoutfile);
852 sk_X509_pop_free(allcerts, X509_free);
856 if (rctfile != NULL) {
857 char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
858 if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) {
859 BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile);
863 if (rctformat == FORMAT_SMIME) {
864 rcms = SMIME_read_CMS(rctin, NULL);
865 } else if (rctformat == FORMAT_PEM) {
866 rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL);
867 } else if (rctformat == FORMAT_ASN1) {
868 rcms = d2i_CMS_bio(rctin, NULL);
870 BIO_printf(bio_err, "Bad input format for receipt\n");
875 BIO_printf(bio_err, "Error reading receipt\n");
880 out = bio_open_default(outfile, 'w', outformat);
884 if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) {
885 if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
886 CAstore, noCAstore)) == NULL)
888 X509_STORE_set_verify_cb(store, cms_cb);
890 X509_STORE_set1_param(store, vpm);
895 if (operation == SMIME_DATA_CREATE) {
896 cms = CMS_data_create(in, flags);
897 } else if (operation == SMIME_DIGEST_CREATE) {
898 cms = CMS_digest_create(in, sign_md, flags);
899 } else if (operation == SMIME_COMPRESS) {
900 cms = CMS_compress(in, -1, flags);
901 } else if (operation == SMIME_ENCRYPT) {
903 flags |= CMS_PARTIAL;
904 cms = CMS_encrypt(NULL, in, cipher, flags);
907 for (i = 0; i < sk_X509_num(encerts); i++) {
908 CMS_RecipientInfo *ri;
909 cms_key_param *kparam;
910 int tflags = flags | CMS_KEY_PARAM; /* This flag enforces allocating the EVP_PKEY_CTX for the recipient here */
912 X509 *x = sk_X509_value(encerts, i);
915 for (kparam = key_first; kparam; kparam = kparam->next) {
916 if (kparam->idx == i) {
920 ri = CMS_add1_recipient(cms, x, key, originator, tflags);
924 pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
925 if (kparam != NULL) {
926 if (!cms_set_pkey_param(pctx, kparam->param))
930 res = EVP_PKEY_CTX_ctrl(pctx, -1, -1,
931 EVP_PKEY_CTRL_CIPHER,
932 EVP_CIPHER_nid(cipher), NULL);
933 if (res <= 0 && res != -2)
936 if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE
938 EVP_CIPHER_CTX *wctx;
939 wctx = CMS_RecipientInfo_kari_get0_ctx(ri);
940 EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL);
944 if (secret_key != NULL) {
945 if (!CMS_add0_recipient_key(cms, NID_undef,
946 secret_key, secret_keylen,
947 secret_keyid, secret_keyidlen,
950 /* NULL these because call absorbs them */
954 if (pwri_pass != NULL) {
955 pwri_tmp = (unsigned char *)OPENSSL_strdup((char *)pwri_pass);
956 if (pwri_tmp == NULL)
958 if (CMS_add0_recipient_password(cms,
959 -1, NID_undef, NID_undef,
960 pwri_tmp, -1, NULL) == NULL)
964 if (!(flags & CMS_STREAM)) {
965 if (!CMS_final(cms, in, NULL, flags))
968 } else if (operation == SMIME_ENCRYPTED_ENCRYPT) {
969 cms = CMS_EncryptedData_encrypt(in, cipher,
970 secret_key, secret_keylen, flags);
972 } else if (operation == SMIME_SIGN_RECEIPT) {
973 CMS_ContentInfo *srcms = NULL;
974 STACK_OF(CMS_SignerInfo) *sis;
976 sis = CMS_get0_SignerInfos(cms);
979 si = sk_CMS_SignerInfo_value(sis, 0);
980 srcms = CMS_sign_receipt(si, signer, key, other, flags);
983 CMS_ContentInfo_free(cms);
985 } else if (operation & SMIME_SIGNERS) {
988 * If detached data content we enable streaming if S/MIME output
991 if (operation == SMIME_SIGN) {
993 if (flags & CMS_DETACHED) {
994 if (outformat == FORMAT_SMIME)
997 flags |= CMS_PARTIAL;
998 cms = CMS_sign(NULL, NULL, other, in, flags);
1001 if (econtent_type != NULL)
1002 CMS_set1_eContentType(cms, econtent_type);
1004 if (rr_to != NULL) {
1005 rr = make_receipt_request(rr_to, rr_allorfirst, rr_from);
1008 "Signed Receipt Request Creation Error\n");
1013 flags |= CMS_REUSE_DIGEST;
1015 for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
1017 cms_key_param *kparam;
1019 signerfile = sk_OPENSSL_STRING_value(sksigners, i);
1020 keyfile = sk_OPENSSL_STRING_value(skkeys, i);
1022 signer = load_cert(signerfile, FORMAT_UNDEF,
1023 "signer certificate");
1024 if (signer == NULL) {
1028 key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
1033 for (kparam = key_first; kparam; kparam = kparam->next) {
1034 if (kparam->idx == i) {
1035 tflags |= CMS_KEY_PARAM;
1039 si = CMS_add1_signer(cms, signer, key, sign_md, tflags);
1042 if (kparam != NULL) {
1044 pctx = CMS_SignerInfo_get0_pkey_ctx(si);
1045 if (!cms_set_pkey_param(pctx, kparam->param))
1048 if (rr != NULL && !CMS_add1_ReceiptRequest(si, rr))
1055 /* If not streaming or resigning finalize structure */
1056 if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
1057 if (!CMS_final(cms, in, NULL, flags))
1063 BIO_printf(bio_err, "Error creating CMS structure\n");
1068 if (operation == SMIME_DECRYPT) {
1069 if (flags & CMS_DEBUG_DECRYPT)
1070 CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);
1072 if (secret_key != NULL) {
1073 if (!CMS_decrypt_set1_key(cms,
1074 secret_key, secret_keylen,
1075 secret_keyid, secret_keyidlen)) {
1076 BIO_puts(bio_err, "Error decrypting CMS using secret key\n");
1082 if (!CMS_decrypt_set1_pkey_and_peer(cms, key, recip, originator)) {
1083 BIO_puts(bio_err, "Error decrypting CMS using private key\n");
1088 if (pwri_pass != NULL) {
1089 if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
1090 BIO_puts(bio_err, "Error decrypting CMS using password\n");
1095 if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
1096 BIO_printf(bio_err, "Error decrypting CMS structure\n");
1099 } else if (operation == SMIME_DATAOUT) {
1100 if (!CMS_data(cms, out, flags))
1102 } else if (operation == SMIME_UNCOMPRESS) {
1103 if (!CMS_uncompress(cms, indata, out, flags))
1105 } else if (operation == SMIME_DIGEST_VERIFY) {
1106 if (CMS_digest_verify(cms, indata, out, flags) > 0) {
1107 BIO_printf(bio_err, "Verification successful\n");
1109 BIO_printf(bio_err, "Verification failure\n");
1112 } else if (operation == SMIME_ENCRYPTED_DECRYPT) {
1113 if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
1114 indata, out, flags))
1116 } else if (operation == SMIME_VERIFY) {
1117 if (CMS_verify(cms, other, store, indata, out, flags) > 0) {
1118 BIO_printf(bio_err, "Verification successful\n");
1120 BIO_printf(bio_err, "Verification failure\n");
1122 ret = verify_err + 32;
1125 if (signerfile != NULL) {
1126 STACK_OF(X509) *signers;
1127 signers = CMS_get0_signers(cms);
1128 if (!save_certs(signerfile, signers)) {
1130 "Error writing signers to %s\n", signerfile);
1134 sk_X509_free(signers);
1137 receipt_request_print(cms);
1139 } else if (operation == SMIME_VERIFY_RECEIPT) {
1140 if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) {
1141 BIO_printf(bio_err, "Verification successful\n");
1143 BIO_printf(bio_err, "Verification failure\n");
1149 CMS_ContentInfo_print_ctx(out, cms, 0, NULL);
1150 } else if (outformat == FORMAT_SMIME) {
1152 BIO_printf(out, "To: %s%s", to, mime_eol);
1154 BIO_printf(out, "From: %s%s", from, mime_eol);
1156 BIO_printf(out, "Subject: %s%s", subject, mime_eol);
1157 if (operation == SMIME_RESIGN)
1158 ret = SMIME_write_CMS(out, cms, indata, flags);
1160 ret = SMIME_write_CMS(out, cms, in, flags);
1161 } else if (outformat == FORMAT_PEM) {
1162 ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
1163 } else if (outformat == FORMAT_ASN1) {
1164 ret = i2d_CMS_bio_stream(out, cms, in, flags);
1166 BIO_printf(bio_err, "Bad output format for CMS file\n");
1177 ERR_print_errors(bio_err);
1178 sk_X509_pop_free(encerts, X509_free);
1179 sk_X509_pop_free(other, X509_free);
1180 X509_VERIFY_PARAM_free(vpm);
1181 sk_OPENSSL_STRING_free(sksigners);
1182 sk_OPENSSL_STRING_free(skkeys);
1183 OPENSSL_free(secret_key);
1184 OPENSSL_free(secret_keyid);
1185 OPENSSL_free(pwri_tmp);
1186 ASN1_OBJECT_free(econtent_type);
1187 CMS_ReceiptRequest_free(rr);
1188 sk_OPENSSL_STRING_free(rr_to);
1189 sk_OPENSSL_STRING_free(rr_from);
1190 for (key_param = key_first; key_param;) {
1191 cms_key_param *tparam;
1192 sk_OPENSSL_STRING_free(key_param->param);
1193 tparam = key_param->next;
1194 OPENSSL_free(key_param);
1197 X509_STORE_free(store);
1202 CMS_ContentInfo_free(cms);
1203 CMS_ContentInfo_free(rcms);
1209 OPENSSL_free(passin);
1213 static int save_certs(char *signerfile, STACK_OF(X509) *signers)
1217 if (signerfile == NULL)
1219 tmp = BIO_new_file(signerfile, "w");
1222 for (i = 0; i < sk_X509_num(signers); i++)
1223 PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
1228 /* Minimal callback just to output policy info (if any) */
1230 static int cms_cb(int ok, X509_STORE_CTX *ctx)
1234 error = X509_STORE_CTX_get_error(ctx);
1238 if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
1239 && ((error != X509_V_OK) || (ok != 2)))
1242 policies_print(ctx);
1248 static void gnames_stack_print(STACK_OF(GENERAL_NAMES) *gns)
1250 STACK_OF(GENERAL_NAME) *gens;
1254 for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) {
1255 gens = sk_GENERAL_NAMES_value(gns, i);
1256 for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) {
1257 gen = sk_GENERAL_NAME_value(gens, j);
1258 BIO_puts(bio_err, " ");
1259 GENERAL_NAME_print(bio_err, gen);
1260 BIO_puts(bio_err, "\n");
1266 static void receipt_request_print(CMS_ContentInfo *cms)
1268 STACK_OF(CMS_SignerInfo) *sis;
1270 CMS_ReceiptRequest *rr;
1272 STACK_OF(GENERAL_NAMES) *rto, *rlist;
1275 sis = CMS_get0_SignerInfos(cms);
1276 for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) {
1277 si = sk_CMS_SignerInfo_value(sis, i);
1278 rv = CMS_get1_ReceiptRequest(si, &rr);
1279 BIO_printf(bio_err, "Signer %d:\n", i + 1);
1281 BIO_puts(bio_err, " No Receipt Request\n");
1282 } else if (rv < 0) {
1283 BIO_puts(bio_err, " Receipt Request Parse Error\n");
1284 ERR_print_errors(bio_err);
1288 CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst,
1290 BIO_puts(bio_err, " Signed Content ID:\n");
1291 idlen = ASN1_STRING_length(scid);
1292 id = (const char *)ASN1_STRING_get0_data(scid);
1293 BIO_dump_indent(bio_err, id, idlen, 4);
1294 BIO_puts(bio_err, " Receipts From");
1295 if (rlist != NULL) {
1296 BIO_puts(bio_err, " List:\n");
1297 gnames_stack_print(rlist);
1298 } else if (allorfirst == 1) {
1299 BIO_puts(bio_err, ": First Tier\n");
1300 } else if (allorfirst == 0) {
1301 BIO_puts(bio_err, ": All\n");
1303 BIO_printf(bio_err, " Unknown (%d)\n", allorfirst);
1305 BIO_puts(bio_err, " Receipts To:\n");
1306 gnames_stack_print(rto);
1308 CMS_ReceiptRequest_free(rr);
1312 static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns)
1315 STACK_OF(GENERAL_NAMES) *ret;
1316 GENERAL_NAMES *gens = NULL;
1317 GENERAL_NAME *gen = NULL;
1318 ret = sk_GENERAL_NAMES_new_null();
1321 for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) {
1322 char *str = sk_OPENSSL_STRING_value(ns, i);
1323 gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0);
1326 gens = GENERAL_NAMES_new();
1329 if (!sk_GENERAL_NAME_push(gens, gen))
1332 if (!sk_GENERAL_NAMES_push(ret, gens))
1340 sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free);
1341 GENERAL_NAMES_free(gens);
1342 GENERAL_NAME_free(gen);
1346 static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING)
1347 *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING)
1350 STACK_OF(GENERAL_NAMES) *rct_to = NULL, *rct_from = NULL;
1351 CMS_ReceiptRequest *rr;
1352 rct_to = make_names_stack(rr_to);
1355 if (rr_from != NULL) {
1356 rct_from = make_names_stack(rr_from);
1357 if (rct_from == NULL)
1362 rr = CMS_ReceiptRequest_create0(NULL, -1, rr_allorfirst, rct_from,
1366 sk_GENERAL_NAMES_pop_free(rct_to, GENERAL_NAMES_free);
1370 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
1371 STACK_OF(OPENSSL_STRING) *param)
1375 if (sk_OPENSSL_STRING_num(param) <= 0)
1377 for (i = 0; i < sk_OPENSSL_STRING_num(param); i++) {
1378 keyopt = sk_OPENSSL_STRING_value(param, i);
1379 if (pkey_ctrl_string(pctx, keyopt) <= 0) {
1380 BIO_printf(bio_err, "parameter error \"%s\"\n", keyopt);
1381 ERR_print_errors(bio_err);