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>
26 DEFINE_STACK_OF(CMS_SignerInfo)
27 DEFINE_STACK_OF(GENERAL_NAME)
28 DEFINE_STACK_OF(GENERAL_NAMES)
29 DEFINE_STACK_OF_STRING()
31 static int save_certs(char *signerfile, STACK_OF(X509) *signers);
32 static int cms_cb(int ok, X509_STORE_CTX *ctx);
33 static void receipt_request_print(CMS_ContentInfo *cms);
34 static CMS_ReceiptRequest *make_receipt_request(
35 STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst,
36 STACK_OF(OPENSSL_STRING) *rr_from, OPENSSL_CTX *libctx, const char *propq);
37 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
38 STACK_OF(OPENSSL_STRING) *param);
40 # define SMIME_OP 0x10
41 # define SMIME_IP 0x20
42 # define SMIME_SIGNERS 0x40
43 # define SMIME_ENCRYPT (1 | SMIME_OP)
44 # define SMIME_DECRYPT (2 | SMIME_IP)
45 # define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS)
46 # define SMIME_VERIFY (4 | SMIME_IP)
47 # define SMIME_CMSOUT (5 | SMIME_IP | SMIME_OP)
48 # define SMIME_RESIGN (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
49 # define SMIME_DATAOUT (7 | SMIME_IP)
50 # define SMIME_DATA_CREATE (8 | SMIME_OP)
51 # define SMIME_DIGEST_VERIFY (9 | SMIME_IP)
52 # define SMIME_DIGEST_CREATE (10 | SMIME_OP)
53 # define SMIME_UNCOMPRESS (11 | SMIME_IP)
54 # define SMIME_COMPRESS (12 | SMIME_OP)
55 # define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP)
56 # define SMIME_ENCRYPTED_ENCRYPT (14 | SMIME_OP)
57 # define SMIME_SIGN_RECEIPT (15 | SMIME_IP | SMIME_OP)
58 # define SMIME_VERIFY_RECEIPT (16 | SMIME_IP)
60 static int verify_err = 0;
62 typedef struct cms_key_param_st cms_key_param;
64 struct cms_key_param_st {
66 STACK_OF(OPENSSL_STRING) *param;
70 typedef enum OPTION_choice {
71 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
72 OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENCRYPT,
73 OPT_DECRYPT, OPT_SIGN, OPT_CADES, OPT_SIGN_RECEIPT, OPT_RESIGN,
74 OPT_VERIFY, OPT_VERIFY_RETCODE, OPT_VERIFY_RECEIPT,
75 OPT_CMSOUT, OPT_DATA_OUT, OPT_DATA_CREATE, OPT_DIGEST_VERIFY,
76 OPT_DIGEST_CREATE, OPT_COMPRESS, OPT_UNCOMPRESS,
77 OPT_ED_DECRYPT, OPT_ED_ENCRYPT, OPT_DEBUG_DECRYPT, OPT_TEXT,
78 OPT_ASCIICRLF, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCERTS,
79 OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP, OPT_BINARY, OPT_KEYID,
80 OPT_NOSIGS, OPT_NO_CONTENT_VERIFY, OPT_NO_ATTR_VERIFY, OPT_INDEF,
81 OPT_NOINDEF, OPT_CRLFEOL, OPT_NOOUT, OPT_RR_PRINT,
82 OPT_RR_ALL, OPT_RR_FIRST, OPT_RCTFORM, OPT_CERTFILE, OPT_CAFILE,
83 OPT_CAPATH, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE,
84 OPT_CONTENT, OPT_PRINT, OPT_NAMEOPT,
85 OPT_SECRETKEY, OPT_SECRETKEYID, OPT_PWRI_PASSWORD, OPT_ECONTENT_TYPE,
86 OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP,
87 OPT_CERTSOUT, OPT_MD, OPT_INKEY, OPT_KEYFORM, OPT_KEYOPT, OPT_RR_FROM,
88 OPT_RR_TO, OPT_AES128_WRAP, OPT_AES192_WRAP, OPT_AES256_WRAP,
89 OPT_3DES_WRAP, OPT_WRAP, OPT_ENGINE,
91 OPT_PROV_ENUM, OPT_CONFIG,
97 const OPTIONS cms_options[] = {
98 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"},
100 OPT_SECTION("General"),
101 {"help", OPT_HELP, '-', "Display this summary"},
102 {"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"},
103 {"outform", OPT_OUTFORM, 'c',
104 "Output format SMIME (default), PEM or DER"},
105 {"in", OPT_IN, '<', "Input file"},
106 {"out", OPT_OUT, '>', "Output file"},
107 {"debug_decrypt", OPT_DEBUG_DECRYPT, '-',
108 "Disable MMA protection and return an error if no recipient found"
109 " (see documentation)"},
110 {"stream", OPT_INDEF, '-', "Enable CMS streaming"},
111 {"indef", OPT_INDEF, '-', "Same as -stream"},
112 {"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"},
113 {"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of CR only" },
114 {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
115 {"CApath", OPT_CAPATH, '/', "trusted certificates directory"},
116 {"CAstore", OPT_CASTORE, ':', "trusted certificates store URI"},
117 {"no-CAfile", OPT_NOCAFILE, '-',
118 "Do not load the default certificates file"},
119 {"no-CApath", OPT_NOCAPATH, '-',
120 "Do not load certificates from the default certificates directory"},
121 {"no-CAstore", OPT_NOCASTORE, '-',
122 "Do not load certificates from the default certificates store"},
123 # ifndef OPENSSL_NO_ENGINE
124 {"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 {"nameopt", OPT_NAMEOPT, 's',
188 "For the -print option specifies various strings printing options"},
189 {"certsout", OPT_CERTSOUT, '>', "Certificate output file"},
191 OPT_SECTION("Keying"),
192 {"secretkey", OPT_SECRETKEY, 's',
193 "Use specified hex-encoded key to decrypt/encrypt recipients or content"},
194 {"secretkeyid", OPT_SECRETKEYID, 's',
195 "Identity of the -secretkey for CMS \"KEKRecipientInfo\" object"},
196 {"pwri_password", OPT_PWRI_PASSWORD, 's',
197 "Specific password for recipient"},
198 {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
199 {"inkey", OPT_INKEY, 's',
200 "Input private key (if not signer or recipient)"},
201 {"keyform", OPT_KEYFORM, 'f', "Input private key format (ENGINE, other values ignored)"},
202 {"keyopt", OPT_KEYOPT, 's', "Set public key parameters as n:v pairs"},
204 OPT_SECTION("Mail header"),
205 {"econtent_type", OPT_ECONTENT_TYPE, 's', "OID for external content"},
206 {"to", OPT_TO, 's', "To address"},
207 {"from", OPT_FROM, 's', "From address"},
208 {"subject", OPT_SUBJECT, 's', "Subject"},
209 {"signer", OPT_SIGNER, 's', "Signer certificate file"},
210 {"originator", OPT_ORIGINATOR, 's', "Originator certificate file"},
211 {"recip", OPT_RECIP, '<', "Recipient cert file for decryption"},
212 {"receipt_request_from", OPT_RR_FROM, 's',
213 "Create signed receipt request with specified email address"},
214 {"receipt_request_to", OPT_RR_TO, 's',
215 "Create signed receipt targeted to specified address"},
217 OPT_SECTION("Encryption"),
218 {"md", OPT_MD, 's', "Digest algorithm to use when signing or resigning"},
219 {"", OPT_CIPHER, '-', "Any supported cipher"},
221 OPT_SECTION("Key-wrapping"),
222 {"aes128-wrap", OPT_AES128_WRAP, '-', "Use AES128 to wrap key"},
223 {"aes192-wrap", OPT_AES192_WRAP, '-', "Use AES192 to wrap key"},
224 {"aes256-wrap", OPT_AES256_WRAP, '-', "Use AES256 to wrap key"},
225 # ifndef OPENSSL_NO_DES
226 {"des3-wrap", OPT_3DES_WRAP, '-', "Use 3DES-EDE to wrap key"},
228 {"wrap", OPT_WRAP, 's', "Any wrap cipher to wrap key"},
235 {"cert", 0, 0, "Recipient certs (optional; used only when encrypting)"},
239 static CMS_ContentInfo *load_content_info(int informat, BIO *in, BIO **indata,
241 OPENSSL_CTX *libctx, const char *propq)
243 CMS_ContentInfo *ret, *ci;
245 ret = CMS_ContentInfo_new_with_libctx(libctx, propq);
247 BIO_printf(bio_err, "Error allocating CMS_contentinfo\n");
252 ci = SMIME_read_CMS_ex(in, indata, &ret);
255 ci = PEM_read_bio_CMS(in, &ret, NULL, NULL);
258 ci = d2i_CMS_bio(in, &ret);
261 BIO_printf(bio_err, "Bad input format for %s\n", name);
265 BIO_printf(bio_err, "Error reading %s Content Info\n", name);
270 CMS_ContentInfo_free(ret);
274 int cms_main(int argc, char **argv)
277 ASN1_OBJECT *econtent_type = NULL;
278 BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
279 CMS_ContentInfo *cms = NULL, *rcms = NULL;
280 CMS_ReceiptRequest *rr = NULL;
282 EVP_PKEY *key = NULL;
283 const EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
284 const EVP_MD *sign_md = NULL;
285 STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
286 STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
287 STACK_OF(X509) *encerts = NULL, *other = NULL;
288 X509 *cert = NULL, *recip = NULL, *signer = NULL, *originator = NULL;
289 X509_STORE *store = NULL;
290 X509_VERIFY_PARAM *vpm = NULL;
291 char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
292 const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
293 char *certsoutfile = NULL;
294 int noCAfile = 0, noCApath = 0, noCAstore = 0;
295 char *infile = NULL, *outfile = NULL, *rctfile = NULL;
296 char *passinarg = NULL, *passin = NULL, *signerfile = NULL, *originatorfile = NULL, *recipfile = NULL;
297 char *to = NULL, *from = NULL, *subject = NULL, *prog;
298 cms_key_param *key_first = NULL, *key_param = NULL;
299 int flags = CMS_DETACHED, noout = 0, print = 0, keyidx = -1, vpmtouched = 0;
300 int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
301 int operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1;
302 int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_PEM;
303 size_t secret_keylen = 0, secret_keyidlen = 0;
304 unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
305 unsigned char *secret_key = NULL, *secret_keyid = NULL;
307 const char *mime_eol = "\n";
309 OPENSSL_CTX *libctx = app_get0_libctx();
310 const char *propq = app_get0_propq();
312 if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
315 prog = opt_init(argc, argv, cms_options);
316 while ((o = opt_next()) != OPT_EOF) {
321 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
324 opt_help(cms_options);
328 if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
332 if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
339 operation = SMIME_ENCRYPT;
342 operation = SMIME_DECRYPT;
345 operation = SMIME_SIGN;
347 case OPT_SIGN_RECEIPT:
348 operation = SMIME_SIGN_RECEIPT;
351 operation = SMIME_RESIGN;
354 operation = SMIME_VERIFY;
356 case OPT_VERIFY_RETCODE:
359 case OPT_VERIFY_RECEIPT:
360 operation = SMIME_VERIFY_RECEIPT;
364 operation = SMIME_CMSOUT;
367 operation = SMIME_DATAOUT;
369 case OPT_DATA_CREATE:
370 operation = SMIME_DATA_CREATE;
372 case OPT_DIGEST_VERIFY:
373 operation = SMIME_DIGEST_VERIFY;
375 case OPT_DIGEST_CREATE:
376 operation = SMIME_DIGEST_CREATE;
379 operation = SMIME_COMPRESS;
382 operation = SMIME_UNCOMPRESS;
385 operation = SMIME_ENCRYPTED_DECRYPT;
388 operation = SMIME_ENCRYPTED_ENCRYPT;
390 case OPT_DEBUG_DECRYPT:
391 flags |= CMS_DEBUG_DECRYPT;
397 flags |= CMS_ASCIICRLF;
400 flags |= CMS_NOINTERN;
403 flags |= CMS_NO_SIGNER_CERT_VERIFY;
406 flags |= CMS_NOCERTS;
412 flags &= ~CMS_DETACHED;
415 flags |= CMS_NOSMIMECAP;
424 flags |= CMS_USE_KEYID;
429 case OPT_NO_CONTENT_VERIFY:
430 flags |= CMS_NO_CONTENT_VERIFY;
432 case OPT_NO_ATTR_VERIFY:
433 flags |= CMS_NO_ATTR_VERIFY;
439 flags &= ~CMS_STREAM;
443 flags |= CMS_CRLFEOL;
458 if (rctformat == FORMAT_ASN1) {
459 if (!opt_format(opt_arg(),
460 OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat))
463 rcms = load_content_info(rctformat, rctin, NULL, "recipient",
468 certfile = opt_arg();
492 contfile = opt_arg();
496 && (rr_from = sk_OPENSSL_STRING_new_null()) == NULL)
498 sk_OPENSSL_STRING_push(rr_from, opt_arg());
502 && (rr_to = sk_OPENSSL_STRING_new_null()) == NULL)
504 sk_OPENSSL_STRING_push(rr_to, opt_arg());
510 if (!set_nameopt(opt_arg()))
514 if (secret_key != NULL) {
515 BIO_printf(bio_err, "Invalid key (supplied twice) %s\n",
519 secret_key = OPENSSL_hexstr2buf(opt_arg(), <mp);
520 if (secret_key == NULL) {
521 BIO_printf(bio_err, "Invalid key %s\n", opt_arg());
524 secret_keylen = (size_t)ltmp;
526 case OPT_SECRETKEYID:
527 if (secret_keyid != NULL) {
528 BIO_printf(bio_err, "Invalid id (supplied twice) %s\n",
532 secret_keyid = OPENSSL_hexstr2buf(opt_arg(), <mp);
533 if (secret_keyid == NULL) {
534 BIO_printf(bio_err, "Invalid id %s\n", opt_arg());
537 secret_keyidlen = (size_t)ltmp;
539 case OPT_PWRI_PASSWORD:
540 pwri_pass = (unsigned char *)opt_arg();
542 case OPT_ECONTENT_TYPE:
543 if (econtent_type != NULL) {
544 BIO_printf(bio_err, "Invalid OID (supplied twice) %s\n",
548 econtent_type = OBJ_txt2obj(opt_arg(), 0);
549 if (econtent_type == NULL) {
550 BIO_printf(bio_err, "Invalid OID %s\n", opt_arg());
555 e = setup_engine(opt_arg(), 0);
558 passinarg = opt_arg();
570 certsoutfile = opt_arg();
573 if (!opt_md(opt_arg(), &sign_md))
577 /* If previous -signer argument add signer to list */
578 if (signerfile != NULL) {
579 if (sksigners == NULL
580 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
582 sk_OPENSSL_STRING_push(sksigners, signerfile);
584 keyfile = signerfile;
586 && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
588 sk_OPENSSL_STRING_push(skkeys, keyfile);
591 signerfile = opt_arg();
594 originatorfile = opt_arg();
597 /* If previous -inkey argument add signer to list */
598 if (keyfile != NULL) {
599 if (signerfile == NULL) {
600 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
603 if (sksigners == NULL
604 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
606 sk_OPENSSL_STRING_push(sksigners, signerfile);
609 && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
611 sk_OPENSSL_STRING_push(skkeys, keyfile);
616 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
620 if (operation == SMIME_ENCRYPT) {
621 if (encerts == NULL && (encerts = sk_X509_new_null()) == NULL)
623 cert = load_cert(opt_arg(), FORMAT_UNDEF,
624 "recipient certificate file");
627 sk_X509_push(encerts, cert);
630 recipfile = opt_arg();
634 if (!opt_cipher(opt_unknown(), &cipher))
639 if (operation == SMIME_ENCRYPT) {
641 keyidx += sk_X509_num(encerts);
643 if (keyfile != NULL || signerfile != NULL)
646 keyidx += sk_OPENSSL_STRING_num(skkeys);
649 BIO_printf(bio_err, "No key specified\n");
652 if (key_param == NULL || key_param->idx != keyidx) {
653 cms_key_param *nparam;
654 nparam = app_malloc(sizeof(*nparam), "key param buffer");
655 nparam->idx = keyidx;
656 if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL)
659 if (key_first == NULL)
662 key_param->next = nparam;
665 sk_OPENSSL_STRING_push(key_param->param, opt_arg());
668 if (!opt_verify(o, vpm))
677 if (!opt_provider(o))
681 conf = app_load_config_modules(opt_arg());
686 # ifndef OPENSSL_NO_DES
687 wrap_cipher = EVP_des_ede3_wrap();
690 case OPT_AES128_WRAP:
691 wrap_cipher = EVP_aes_128_wrap();
693 case OPT_AES192_WRAP:
694 wrap_cipher = EVP_aes_192_wrap();
696 case OPT_AES256_WRAP:
697 wrap_cipher = EVP_aes_256_wrap();
700 if (!opt_cipher(opt_unknown(), &wrap_cipher))
705 argc = opt_num_rest();
708 if ((rr_allorfirst != -1 || rr_from != NULL) && rr_to == NULL) {
709 BIO_puts(bio_err, "No Signed Receipts Recipients\n");
713 if (!(operation & SMIME_SIGNERS) && (rr_to != NULL || rr_from != NULL)) {
714 BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
717 if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) {
718 BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
722 if ((flags & CMS_CADES) != 0) {
723 if ((flags & CMS_NOATTR) != 0) {
724 BIO_puts(bio_err, "Incompatible options: "
725 "CAdES required signed attributes\n");
728 if (operation == SMIME_VERIFY
729 && (flags & (CMS_NO_SIGNER_CERT_VERIFY | CMS_NO_ATTR_VERIFY)) != 0) {
730 BIO_puts(bio_err, "Incompatible options: CAdES validation require"
731 " certs and signed attributes validations\n");
736 if (operation & SMIME_SIGNERS) {
737 if (keyfile != NULL && signerfile == NULL) {
738 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
741 /* Check to see if any final signer needs to be appended */
742 if (signerfile != NULL) {
743 if (sksigners == NULL
744 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
746 sk_OPENSSL_STRING_push(sksigners, signerfile);
747 if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
750 keyfile = signerfile;
751 sk_OPENSSL_STRING_push(skkeys, keyfile);
753 if (sksigners == NULL) {
754 BIO_printf(bio_err, "No signer certificate specified\n");
759 } else if (operation == SMIME_DECRYPT) {
760 if (recipfile == NULL && keyfile == NULL
761 && secret_key == NULL && pwri_pass == NULL) {
763 "No recipient certificate or key specified\n");
766 } else if (operation == SMIME_ENCRYPT) {
767 if (*argv == NULL && secret_key == NULL
768 && pwri_pass == NULL && encerts == NULL) {
769 BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
772 } else if (!operation) {
773 BIO_printf(bio_err, "No operation option (-encrypt|-decrypt|-sign|-verify|...) specified.\n");
777 if (!app_passwd(passinarg, NULL, &passin, NULL)) {
778 BIO_printf(bio_err, "Error getting password\n");
784 if (!(operation & SMIME_SIGNERS))
785 flags &= ~CMS_DETACHED;
787 if (!(operation & SMIME_OP))
788 if (flags & CMS_BINARY)
789 outformat = FORMAT_BINARY;
791 if (!(operation & SMIME_IP))
792 if (flags & CMS_BINARY)
793 informat = FORMAT_BINARY;
795 if (operation == SMIME_ENCRYPT) {
797 # ifndef OPENSSL_NO_DES
798 cipher = EVP_des_ede3_cbc();
800 BIO_printf(bio_err, "No cipher selected\n");
805 if (secret_key && !secret_keyid) {
806 BIO_printf(bio_err, "No secret key id\n");
810 if (*argv && encerts == NULL)
811 if ((encerts = sk_X509_new_null()) == NULL)
814 if ((cert = load_cert(*argv, FORMAT_UNDEF,
815 "recipient certificate file")) == NULL)
817 sk_X509_push(encerts, cert);
823 if (certfile != NULL) {
824 if (!load_certs(certfile, &other, NULL, "certificate file")) {
825 ERR_print_errors(bio_err);
830 if (recipfile != NULL && (operation == SMIME_DECRYPT)) {
831 if ((recip = load_cert(recipfile, FORMAT_UNDEF,
832 "recipient certificate file")) == NULL) {
833 ERR_print_errors(bio_err);
838 if (originatorfile != NULL) {
839 if ((originator = load_cert(originatorfile, FORMAT_UNDEF,
840 "originator certificate file")) == NULL) {
841 ERR_print_errors(bio_err);
846 if (operation == SMIME_SIGN_RECEIPT) {
847 if ((signer = load_cert(signerfile, FORMAT_UNDEF,
848 "receipt signer certificate file")) == NULL) {
849 ERR_print_errors(bio_err);
854 if ((operation == SMIME_DECRYPT) || (operation == SMIME_ENCRYPT)) {
857 } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
859 keyfile = signerfile;
864 if (keyfile != NULL) {
865 key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
870 * TODO: Remove this when CMS has full support for provider-native
873 if (EVP_PKEY_get0(key) == NULL)
877 in = bio_open_default(infile, 'r', informat);
881 if (operation & SMIME_IP) {
882 cms = load_content_info(informat, in, &indata, "SMIME", libctx, propq);
885 if (contfile != NULL) {
887 if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
888 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
892 if (certsoutfile != NULL) {
893 STACK_OF(X509) *allcerts;
894 allcerts = CMS_get1_certs(cms);
895 if (!save_certs(certsoutfile, allcerts)) {
897 "Error writing certs to %s\n", certsoutfile);
901 sk_X509_pop_free(allcerts, X509_free);
905 if (rctfile != NULL) {
906 char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
907 if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) {
908 BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile);
912 rcms = load_content_info(rctformat, rctin, NULL, "recipient", libctx,
918 out = bio_open_default(outfile, 'w', outformat);
922 if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) {
923 if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
924 CAstore, noCAstore)) == NULL)
926 X509_STORE_set_verify_cb(store, cms_cb);
928 X509_STORE_set1_param(store, vpm);
933 if (operation == SMIME_DATA_CREATE) {
934 cms = CMS_data_create_with_libctx(in, flags, libctx, propq);
935 } else if (operation == SMIME_DIGEST_CREATE) {
936 cms = CMS_digest_create_with_libctx(in, sign_md, flags, libctx, propq);
937 } else if (operation == SMIME_COMPRESS) {
938 cms = CMS_compress(in, -1, flags);
939 } else if (operation == SMIME_ENCRYPT) {
941 flags |= CMS_PARTIAL;
942 cms = CMS_encrypt_with_libctx(NULL, in, cipher, flags, libctx, propq);
945 for (i = 0; i < sk_X509_num(encerts); i++) {
946 CMS_RecipientInfo *ri;
947 cms_key_param *kparam;
948 int tflags = flags | CMS_KEY_PARAM; /* This flag enforces allocating the EVP_PKEY_CTX for the recipient here */
950 X509 *x = sk_X509_value(encerts, i);
953 for (kparam = key_first; kparam; kparam = kparam->next) {
954 if (kparam->idx == i) {
958 ri = CMS_add1_recipient(cms, x, key, originator, tflags);
962 pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
963 if (kparam != NULL) {
964 if (!cms_set_pkey_param(pctx, kparam->param))
968 res = EVP_PKEY_CTX_ctrl(pctx, -1, -1,
969 EVP_PKEY_CTRL_CIPHER,
970 EVP_CIPHER_nid(cipher), NULL);
971 if (res <= 0 && res != -2)
974 if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE
976 EVP_CIPHER_CTX *wctx;
977 wctx = CMS_RecipientInfo_kari_get0_ctx(ri);
978 EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL);
982 if (secret_key != NULL) {
983 if (!CMS_add0_recipient_key(cms, NID_undef,
984 secret_key, secret_keylen,
985 secret_keyid, secret_keyidlen,
988 /* NULL these because call absorbs them */
992 if (pwri_pass != NULL) {
993 pwri_tmp = (unsigned char *)OPENSSL_strdup((char *)pwri_pass);
994 if (pwri_tmp == NULL)
996 if (CMS_add0_recipient_password(cms,
997 -1, NID_undef, NID_undef,
998 pwri_tmp, -1, NULL) == NULL)
1002 if (!(flags & CMS_STREAM)) {
1003 if (!CMS_final(cms, in, NULL, flags))
1006 } else if (operation == SMIME_ENCRYPTED_ENCRYPT) {
1007 cms = CMS_EncryptedData_encrypt_with_libctx(in, cipher, secret_key,
1008 secret_keylen, flags,
1011 } else if (operation == SMIME_SIGN_RECEIPT) {
1012 CMS_ContentInfo *srcms = NULL;
1013 STACK_OF(CMS_SignerInfo) *sis;
1015 sis = CMS_get0_SignerInfos(cms);
1018 si = sk_CMS_SignerInfo_value(sis, 0);
1019 srcms = CMS_sign_receipt(si, signer, key, other, flags);
1022 CMS_ContentInfo_free(cms);
1024 } else if (operation & SMIME_SIGNERS) {
1027 * If detached data content we enable streaming if S/MIME output
1030 if (operation == SMIME_SIGN) {
1032 if (flags & CMS_DETACHED) {
1033 if (outformat == FORMAT_SMIME)
1034 flags |= CMS_STREAM;
1036 flags |= CMS_PARTIAL;
1037 cms = CMS_sign_with_libctx(NULL, NULL, other, in, flags, libctx, propq);
1040 if (econtent_type != NULL)
1041 CMS_set1_eContentType(cms, econtent_type);
1043 if (rr_to != NULL) {
1044 rr = make_receipt_request(rr_to, rr_allorfirst, rr_from, libctx,
1048 "Signed Receipt Request Creation Error\n");
1053 flags |= CMS_REUSE_DIGEST;
1055 for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
1057 cms_key_param *kparam;
1059 signerfile = sk_OPENSSL_STRING_value(sksigners, i);
1060 keyfile = sk_OPENSSL_STRING_value(skkeys, i);
1062 signer = load_cert(signerfile, FORMAT_UNDEF,
1063 "signer certificate");
1064 if (signer == NULL) {
1068 key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
1075 * TODO: Remove this when CMS has full support for provider-native
1078 if (EVP_PKEY_get0(key) == NULL)
1081 for (kparam = key_first; kparam; kparam = kparam->next) {
1082 if (kparam->idx == i) {
1083 tflags |= CMS_KEY_PARAM;
1087 si = CMS_add1_signer(cms, signer, key, sign_md, tflags);
1090 if (kparam != NULL) {
1092 pctx = CMS_SignerInfo_get0_pkey_ctx(si);
1093 if (!cms_set_pkey_param(pctx, kparam->param))
1096 if (rr != NULL && !CMS_add1_ReceiptRequest(si, rr))
1103 /* If not streaming or resigning finalize structure */
1104 if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
1105 if (!CMS_final(cms, in, NULL, flags))
1111 BIO_printf(bio_err, "Error creating CMS structure\n");
1116 if (operation == SMIME_DECRYPT) {
1117 if (flags & CMS_DEBUG_DECRYPT)
1118 CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);
1120 if (secret_key != NULL) {
1121 if (!CMS_decrypt_set1_key(cms,
1122 secret_key, secret_keylen,
1123 secret_keyid, secret_keyidlen)) {
1124 BIO_puts(bio_err, "Error decrypting CMS using secret key\n");
1130 if (!CMS_decrypt_set1_pkey_and_peer(cms, key, recip, originator)) {
1131 BIO_puts(bio_err, "Error decrypting CMS using private key\n");
1136 if (pwri_pass != NULL) {
1137 if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
1138 BIO_puts(bio_err, "Error decrypting CMS using password\n");
1143 if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
1144 BIO_printf(bio_err, "Error decrypting CMS structure\n");
1147 } else if (operation == SMIME_DATAOUT) {
1148 if (!CMS_data(cms, out, flags))
1150 } else if (operation == SMIME_UNCOMPRESS) {
1151 if (!CMS_uncompress(cms, indata, out, flags))
1153 } else if (operation == SMIME_DIGEST_VERIFY) {
1154 if (CMS_digest_verify(cms, indata, out, flags) > 0) {
1155 BIO_printf(bio_err, "Verification successful\n");
1157 BIO_printf(bio_err, "Verification failure\n");
1160 } else if (operation == SMIME_ENCRYPTED_DECRYPT) {
1161 if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
1162 indata, out, flags))
1164 } else if (operation == SMIME_VERIFY) {
1165 if (CMS_verify(cms, other, store, indata, out, flags) > 0) {
1166 BIO_printf(bio_err, "%s Verification successful\n",
1167 (flags & CMS_CADES) ? "CAdES" : "CMS");
1169 BIO_printf(bio_err, "Verification failure\n");
1171 ret = verify_err + 32;
1174 if (signerfile != NULL) {
1175 STACK_OF(X509) *signers;
1176 signers = CMS_get0_signers(cms);
1177 if (!save_certs(signerfile, signers)) {
1179 "Error writing signers to %s\n", signerfile);
1183 sk_X509_free(signers);
1186 receipt_request_print(cms);
1188 } else if (operation == SMIME_VERIFY_RECEIPT) {
1189 if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) {
1190 BIO_printf(bio_err, "Verification successful\n");
1192 BIO_printf(bio_err, "Verification failure\n");
1198 ASN1_PCTX *pctx = NULL;
1199 if (get_nameopt() != XN_FLAG_ONELINE) {
1200 pctx = ASN1_PCTX_new();
1201 if (pctx != NULL) { /* Print anyway if malloc failed */
1202 ASN1_PCTX_set_flags(pctx, ASN1_PCTX_FLAGS_SHOW_ABSENT);
1203 ASN1_PCTX_set_str_flags(pctx, get_nameopt());
1204 ASN1_PCTX_set_nm_flags(pctx, get_nameopt());
1207 CMS_ContentInfo_print_ctx(out, cms, 0, pctx);
1208 ASN1_PCTX_free(pctx);
1210 } else if (outformat == FORMAT_SMIME) {
1212 BIO_printf(out, "To: %s%s", to, mime_eol);
1214 BIO_printf(out, "From: %s%s", from, mime_eol);
1216 BIO_printf(out, "Subject: %s%s", subject, mime_eol);
1217 if (operation == SMIME_RESIGN)
1218 ret = SMIME_write_CMS(out, cms, indata, flags);
1220 ret = SMIME_write_CMS(out, cms, in, flags);
1221 } else if (outformat == FORMAT_PEM) {
1222 ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
1223 } else if (outformat == FORMAT_ASN1) {
1224 ret = i2d_CMS_bio_stream(out, cms, in, flags);
1226 BIO_printf(bio_err, "Bad output format for CMS file\n");
1237 ERR_print_errors(bio_err);
1238 sk_X509_pop_free(encerts, X509_free);
1239 sk_X509_pop_free(other, X509_free);
1240 X509_VERIFY_PARAM_free(vpm);
1241 sk_OPENSSL_STRING_free(sksigners);
1242 sk_OPENSSL_STRING_free(skkeys);
1243 OPENSSL_free(secret_key);
1244 OPENSSL_free(secret_keyid);
1245 OPENSSL_free(pwri_tmp);
1246 ASN1_OBJECT_free(econtent_type);
1247 CMS_ReceiptRequest_free(rr);
1248 sk_OPENSSL_STRING_free(rr_to);
1249 sk_OPENSSL_STRING_free(rr_from);
1250 for (key_param = key_first; key_param;) {
1251 cms_key_param *tparam;
1252 sk_OPENSSL_STRING_free(key_param->param);
1253 tparam = key_param->next;
1254 OPENSSL_free(key_param);
1257 X509_STORE_free(store);
1262 CMS_ContentInfo_free(cms);
1263 CMS_ContentInfo_free(rcms);
1269 OPENSSL_free(passin);
1274 static int save_certs(char *signerfile, STACK_OF(X509) *signers)
1278 if (signerfile == NULL)
1280 tmp = BIO_new_file(signerfile, "w");
1283 for (i = 0; i < sk_X509_num(signers); i++)
1284 PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
1289 /* Minimal callback just to output policy info (if any) */
1291 static int cms_cb(int ok, X509_STORE_CTX *ctx)
1295 error = X509_STORE_CTX_get_error(ctx);
1299 if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
1300 && ((error != X509_V_OK) || (ok != 2)))
1303 policies_print(ctx);
1309 static void gnames_stack_print(STACK_OF(GENERAL_NAMES) *gns)
1311 STACK_OF(GENERAL_NAME) *gens;
1315 for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) {
1316 gens = sk_GENERAL_NAMES_value(gns, i);
1317 for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) {
1318 gen = sk_GENERAL_NAME_value(gens, j);
1319 BIO_puts(bio_err, " ");
1320 GENERAL_NAME_print(bio_err, gen);
1321 BIO_puts(bio_err, "\n");
1327 static void receipt_request_print(CMS_ContentInfo *cms)
1329 STACK_OF(CMS_SignerInfo) *sis;
1331 CMS_ReceiptRequest *rr;
1333 STACK_OF(GENERAL_NAMES) *rto, *rlist;
1336 sis = CMS_get0_SignerInfos(cms);
1337 for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) {
1338 si = sk_CMS_SignerInfo_value(sis, i);
1339 rv = CMS_get1_ReceiptRequest(si, &rr);
1340 BIO_printf(bio_err, "Signer %d:\n", i + 1);
1342 BIO_puts(bio_err, " No Receipt Request\n");
1343 } else if (rv < 0) {
1344 BIO_puts(bio_err, " Receipt Request Parse Error\n");
1345 ERR_print_errors(bio_err);
1349 CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst,
1351 BIO_puts(bio_err, " Signed Content ID:\n");
1352 idlen = ASN1_STRING_length(scid);
1353 id = (const char *)ASN1_STRING_get0_data(scid);
1354 BIO_dump_indent(bio_err, id, idlen, 4);
1355 BIO_puts(bio_err, " Receipts From");
1356 if (rlist != NULL) {
1357 BIO_puts(bio_err, " List:\n");
1358 gnames_stack_print(rlist);
1359 } else if (allorfirst == 1) {
1360 BIO_puts(bio_err, ": First Tier\n");
1361 } else if (allorfirst == 0) {
1362 BIO_puts(bio_err, ": All\n");
1364 BIO_printf(bio_err, " Unknown (%d)\n", allorfirst);
1366 BIO_puts(bio_err, " Receipts To:\n");
1367 gnames_stack_print(rto);
1369 CMS_ReceiptRequest_free(rr);
1373 static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns)
1376 STACK_OF(GENERAL_NAMES) *ret;
1377 GENERAL_NAMES *gens = NULL;
1378 GENERAL_NAME *gen = NULL;
1379 ret = sk_GENERAL_NAMES_new_null();
1382 for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) {
1383 char *str = sk_OPENSSL_STRING_value(ns, i);
1384 gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0);
1387 gens = GENERAL_NAMES_new();
1390 if (!sk_GENERAL_NAME_push(gens, gen))
1393 if (!sk_GENERAL_NAMES_push(ret, gens))
1401 sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free);
1402 GENERAL_NAMES_free(gens);
1403 GENERAL_NAME_free(gen);
1407 static CMS_ReceiptRequest *make_receipt_request(
1408 STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst,
1409 STACK_OF(OPENSSL_STRING) *rr_from,
1410 OPENSSL_CTX *libctx, const char *propq)
1412 STACK_OF(GENERAL_NAMES) *rct_to = NULL, *rct_from = NULL;
1413 CMS_ReceiptRequest *rr;
1414 rct_to = make_names_stack(rr_to);
1417 if (rr_from != NULL) {
1418 rct_from = make_names_stack(rr_from);
1419 if (rct_from == NULL)
1424 rr = CMS_ReceiptRequest_create0_with_libctx(NULL, -1, rr_allorfirst,
1425 rct_from, rct_to, libctx, propq);
1428 sk_GENERAL_NAMES_pop_free(rct_to, GENERAL_NAMES_free);
1432 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
1433 STACK_OF(OPENSSL_STRING) *param)
1437 if (sk_OPENSSL_STRING_num(param) <= 0)
1439 for (i = 0; i < sk_OPENSSL_STRING_num(param); i++) {
1440 keyopt = sk_OPENSSL_STRING_value(param, i);
1441 if (pkey_ctrl_string(pctx, keyopt) <= 0) {
1442 BIO_printf(bio_err, "parameter error \"%s\"\n", keyopt);
1443 ERR_print_errors(bio_err);