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(
36 STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst,
37 STACK_OF(OPENSSL_STRING) *rr_from, OPENSSL_CTX *libctx, const char *propq);
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, OPT_NAMEOPT,
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,
92 OPT_PROV_ENUM, OPT_CONFIG,
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"},
129 OPT_SECTION("Action"),
130 {"encrypt", OPT_ENCRYPT, '-', "Encrypt message"},
131 {"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"},
132 {"sign", OPT_SIGN, '-', "Sign message"},
133 {"sign_receipt", OPT_SIGN_RECEIPT, '-', "Generate a signed receipt for the message"},
134 {"resign", OPT_RESIGN, '-', "Resign a signed message"},
135 {"cades", OPT_CADES, '-', "Include signer certificate digest"},
136 {"verify", OPT_VERIFY, '-', "Verify signed message"},
137 {"verify_retcode", OPT_VERIFY_RETCODE, '-',
138 "Exit non-zero on verification failure"},
139 {"verify_receipt", OPT_VERIFY_RECEIPT, '<',
140 "Verify receipts; exit if receipt signatures do not verify"},
141 {"digest_verify", OPT_DIGEST_VERIFY, '-',
142 "Verify a CMS \"DigestedData\" object and output it"},
143 {"digest_create", OPT_DIGEST_CREATE, '-',
144 "Create a CMS \"DigestedData\" object"},
145 {"compress", OPT_COMPRESS, '-', "Create a CMS \"CompressedData\" object"},
146 {"uncompress", OPT_UNCOMPRESS, '-',
147 "Uncompress a CMS \"CompressedData\" object"},
148 {"EncryptedData_decrypt", OPT_ED_DECRYPT, '-',
149 "Decrypt CMS \"EncryptedData\" object using symmetric key"},
150 {"EncryptedData_encrypt", OPT_ED_ENCRYPT, '-',
151 "Create CMS \"EncryptedData\" object using symmetric key"},
152 {"data_out", OPT_DATA_OUT, '-', "Copy CMS \"Data\" object to output"},
153 {"data_create", OPT_DATA_CREATE, '-', "Create a CMS \"Data\" object"},
154 {"cmsout", OPT_CMSOUT, '-', "Output CMS structure"},
155 {"no_content_verify", OPT_NO_CONTENT_VERIFY, '-',
156 "Do not verify signed content signatures"},
157 {"no_attr_verify", OPT_NO_ATTR_VERIFY, '-',
158 "Do not verify signed attribute signatures"},
159 {"nointern", OPT_NOINTERN, '-',
160 "Don't search certificates in message for signer"},
161 {"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"},
163 OPT_SECTION("Formatting"),
164 {"text", OPT_TEXT, '-', "Include or delete text MIME headers"},
165 {"asciicrlf", OPT_ASCIICRLF, '-',
166 "Perform CRLF canonicalisation when signing"},
167 {"nodetach", OPT_NODETACH, '-', "Use opaque signing"},
168 {"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"},
169 {"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"},
170 {"binary", OPT_BINARY, '-', "Don't translate message to text"},
171 {"keyid", OPT_KEYID, '-', "Use subject key identifier"},
172 {"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"},
173 {"nocerts", OPT_NOCERTS, '-',
174 "Don't include signers certificate when signing"},
175 {"noout", OPT_NOOUT, '-',
176 "For the -cmsout operation do not output the parsed CMS structure"},
177 {"receipt_request_print", OPT_RR_PRINT, '-', "Print CMS Receipt Request" },
178 {"receipt_request_all", OPT_RR_ALL, '-',
179 "When signing, create a receipt request for all recipients"},
180 {"receipt_request_first", OPT_RR_FIRST, '-',
181 "When signing, create a receipt request for first recipient"},
182 {"rctform", OPT_RCTFORM, 'F', "Receipt file format"},
183 {"certfile", OPT_CERTFILE, '<', "Other certificates file"},
184 {"content", OPT_CONTENT, '<',
185 "Supply or override content for detached signature"},
186 {"print", OPT_PRINT, '-',
187 "For the -cmsout operation print out all fields of the CMS structure"},
188 {"nameopt", OPT_NAMEOPT, 's',
189 "For the -print option specifies various strings printing options"},
190 {"certsout", OPT_CERTSOUT, '>', "Certificate output file"},
192 OPT_SECTION("Keying"),
193 {"secretkey", OPT_SECRETKEY, 's',
194 "Use specified hex-encoded key to decrypt/encrypt recipients or content"},
195 {"secretkeyid", OPT_SECRETKEYID, 's',
196 "Identity of the -secretkey for CMS \"KEKRecipientInfo\" object"},
197 {"pwri_password", OPT_PWRI_PASSWORD, 's',
198 "Specific password for recipient"},
199 {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
200 {"inkey", OPT_INKEY, 's',
201 "Input private key (if not signer or recipient)"},
202 {"keyform", OPT_KEYFORM, 'f', "Input private key format (ENGINE, other values ignored)"},
203 {"keyopt", OPT_KEYOPT, 's', "Set public key parameters as n:v pairs"},
205 OPT_SECTION("Mail header"),
206 {"econtent_type", OPT_ECONTENT_TYPE, 's', "OID for external content"},
207 {"to", OPT_TO, 's', "To address"},
208 {"from", OPT_FROM, 's', "From address"},
209 {"subject", OPT_SUBJECT, 's', "Subject"},
210 {"signer", OPT_SIGNER, 's', "Signer certificate file"},
211 {"originator", OPT_ORIGINATOR, 's', "Originator certificate file"},
212 {"recip", OPT_RECIP, '<', "Recipient cert file for decryption"},
213 {"receipt_request_from", OPT_RR_FROM, 's',
214 "Create signed receipt request with specified email address"},
215 {"receipt_request_to", OPT_RR_TO, 's',
216 "Create signed receipt targeted to specified address"},
218 OPT_SECTION("Encryption"),
219 {"md", OPT_MD, 's', "Digest algorithm to use when signing or resigning"},
220 {"", OPT_CIPHER, '-', "Any supported cipher"},
222 OPT_SECTION("Key-wrapping"),
223 {"aes128-wrap", OPT_AES128_WRAP, '-', "Use AES128 to wrap key"},
224 {"aes192-wrap", OPT_AES192_WRAP, '-', "Use AES192 to wrap key"},
225 {"aes256-wrap", OPT_AES256_WRAP, '-', "Use AES256 to wrap key"},
226 # ifndef OPENSSL_NO_DES
227 {"des3-wrap", OPT_3DES_WRAP, '-', "Use 3DES-EDE to wrap key"},
229 {"wrap", OPT_WRAP, 's', "Any wrap cipher to wrap key"},
236 {"cert", 0, 0, "Recipient certs (optional; used only when encrypting)"},
240 static CMS_ContentInfo *load_content_info(int informat, BIO *in, BIO **indata,
242 OPENSSL_CTX *libctx, const char *propq)
244 CMS_ContentInfo *ret, *ci;
246 ret = CMS_ContentInfo_new_with_libctx(libctx, propq);
248 BIO_printf(bio_err, "Error allocating CMS_contentinfo\n");
253 ci = SMIME_read_CMS_ex(in, indata, &ret);
256 ci = PEM_read_bio_CMS(in, &ret, NULL, NULL);
259 ci = d2i_CMS_bio(in, &ret);
262 BIO_printf(bio_err, "Bad input format for %s\n", name);
266 BIO_printf(bio_err, "Error reading %s Content Info\n", name);
271 CMS_ContentInfo_free(ret);
275 int cms_main(int argc, char **argv)
278 ASN1_OBJECT *econtent_type = NULL;
279 BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
280 CMS_ContentInfo *cms = NULL, *rcms = NULL;
281 CMS_ReceiptRequest *rr = NULL;
283 EVP_PKEY *key = NULL;
284 const EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
285 const EVP_MD *sign_md = NULL;
286 STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
287 STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
288 STACK_OF(X509) *encerts = NULL, *other = NULL;
289 X509 *cert = NULL, *recip = NULL, *signer = NULL, *originator = NULL;
290 X509_STORE *store = NULL;
291 X509_VERIFY_PARAM *vpm = NULL;
292 char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
293 const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
294 char *certsoutfile = NULL;
295 int noCAfile = 0, noCApath = 0, noCAstore = 0;
296 char *infile = NULL, *outfile = NULL, *rctfile = NULL;
297 char *passinarg = NULL, *passin = NULL, *signerfile = NULL, *originatorfile = NULL, *recipfile = NULL;
298 char *to = NULL, *from = NULL, *subject = NULL, *prog;
299 cms_key_param *key_first = NULL, *key_param = NULL;
300 int flags = CMS_DETACHED, noout = 0, print = 0, keyidx = -1, vpmtouched = 0;
301 int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
302 int operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1;
303 int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_PEM;
304 size_t secret_keylen = 0, secret_keyidlen = 0;
305 unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
306 unsigned char *secret_key = NULL, *secret_keyid = NULL;
308 const char *mime_eol = "\n";
310 OPENSSL_CTX *libctx = app_get0_libctx();
311 const char *propq = app_get0_propq();
313 if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
316 prog = opt_init(argc, argv, cms_options);
317 while ((o = opt_next()) != OPT_EOF) {
322 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
325 opt_help(cms_options);
329 if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
333 if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
340 operation = SMIME_ENCRYPT;
343 operation = SMIME_DECRYPT;
346 operation = SMIME_SIGN;
348 case OPT_SIGN_RECEIPT:
349 operation = SMIME_SIGN_RECEIPT;
352 operation = SMIME_RESIGN;
355 operation = SMIME_VERIFY;
357 case OPT_VERIFY_RETCODE:
360 case OPT_VERIFY_RECEIPT:
361 operation = SMIME_VERIFY_RECEIPT;
365 operation = SMIME_CMSOUT;
368 operation = SMIME_DATAOUT;
370 case OPT_DATA_CREATE:
371 operation = SMIME_DATA_CREATE;
373 case OPT_DIGEST_VERIFY:
374 operation = SMIME_DIGEST_VERIFY;
376 case OPT_DIGEST_CREATE:
377 operation = SMIME_DIGEST_CREATE;
380 operation = SMIME_COMPRESS;
383 operation = SMIME_UNCOMPRESS;
386 operation = SMIME_ENCRYPTED_DECRYPT;
389 operation = SMIME_ENCRYPTED_ENCRYPT;
391 case OPT_DEBUG_DECRYPT:
392 flags |= CMS_DEBUG_DECRYPT;
398 flags |= CMS_ASCIICRLF;
401 flags |= CMS_NOINTERN;
404 flags |= CMS_NO_SIGNER_CERT_VERIFY;
407 flags |= CMS_NOCERTS;
413 flags &= ~CMS_DETACHED;
416 flags |= CMS_NOSMIMECAP;
425 flags |= CMS_USE_KEYID;
430 case OPT_NO_CONTENT_VERIFY:
431 flags |= CMS_NO_CONTENT_VERIFY;
433 case OPT_NO_ATTR_VERIFY:
434 flags |= CMS_NO_ATTR_VERIFY;
440 flags &= ~CMS_STREAM;
444 flags |= CMS_CRLFEOL;
459 if (rctformat == FORMAT_ASN1) {
460 if (!opt_format(opt_arg(),
461 OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat))
464 rcms = load_content_info(rctformat, rctin, NULL, "recipient",
469 certfile = opt_arg();
493 contfile = opt_arg();
497 && (rr_from = sk_OPENSSL_STRING_new_null()) == NULL)
499 sk_OPENSSL_STRING_push(rr_from, opt_arg());
503 && (rr_to = sk_OPENSSL_STRING_new_null()) == NULL)
505 sk_OPENSSL_STRING_push(rr_to, opt_arg());
511 if (!set_nameopt(opt_arg()))
515 if (secret_key != NULL) {
516 BIO_printf(bio_err, "Invalid key (supplied twice) %s\n",
520 secret_key = OPENSSL_hexstr2buf(opt_arg(), <mp);
521 if (secret_key == NULL) {
522 BIO_printf(bio_err, "Invalid key %s\n", opt_arg());
525 secret_keylen = (size_t)ltmp;
527 case OPT_SECRETKEYID:
528 if (secret_keyid != NULL) {
529 BIO_printf(bio_err, "Invalid id (supplied twice) %s\n",
533 secret_keyid = OPENSSL_hexstr2buf(opt_arg(), <mp);
534 if (secret_keyid == NULL) {
535 BIO_printf(bio_err, "Invalid id %s\n", opt_arg());
538 secret_keyidlen = (size_t)ltmp;
540 case OPT_PWRI_PASSWORD:
541 pwri_pass = (unsigned char *)opt_arg();
543 case OPT_ECONTENT_TYPE:
544 if (econtent_type != NULL) {
545 BIO_printf(bio_err, "Invalid OID (supplied twice) %s\n",
549 econtent_type = OBJ_txt2obj(opt_arg(), 0);
550 if (econtent_type == NULL) {
551 BIO_printf(bio_err, "Invalid OID %s\n", opt_arg());
556 e = setup_engine(opt_arg(), 0);
559 passinarg = opt_arg();
571 certsoutfile = opt_arg();
574 if (!opt_md(opt_arg(), &sign_md))
578 /* If previous -signer argument add signer to list */
579 if (signerfile != NULL) {
580 if (sksigners == NULL
581 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
583 sk_OPENSSL_STRING_push(sksigners, signerfile);
585 keyfile = signerfile;
587 && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
589 sk_OPENSSL_STRING_push(skkeys, keyfile);
592 signerfile = opt_arg();
595 originatorfile = opt_arg();
598 /* If previous -inkey argument add signer to list */
599 if (keyfile != NULL) {
600 if (signerfile == NULL) {
601 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
604 if (sksigners == NULL
605 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
607 sk_OPENSSL_STRING_push(sksigners, signerfile);
610 && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
612 sk_OPENSSL_STRING_push(skkeys, keyfile);
617 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
621 if (operation == SMIME_ENCRYPT) {
622 if (encerts == NULL && (encerts = sk_X509_new_null()) == NULL)
624 cert = load_cert(opt_arg(), FORMAT_UNDEF,
625 "recipient certificate file");
628 sk_X509_push(encerts, cert);
631 recipfile = opt_arg();
635 if (!opt_cipher(opt_unknown(), &cipher))
640 if (operation == SMIME_ENCRYPT) {
642 keyidx += sk_X509_num(encerts);
644 if (keyfile != NULL || signerfile != NULL)
647 keyidx += sk_OPENSSL_STRING_num(skkeys);
650 BIO_printf(bio_err, "No key specified\n");
653 if (key_param == NULL || key_param->idx != keyidx) {
654 cms_key_param *nparam;
655 nparam = app_malloc(sizeof(*nparam), "key param buffer");
656 nparam->idx = keyidx;
657 if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL)
660 if (key_first == NULL)
663 key_param->next = nparam;
666 sk_OPENSSL_STRING_push(key_param->param, opt_arg());
669 if (!opt_verify(o, vpm))
678 if (!opt_provider(o))
682 conf = app_load_config_modules(opt_arg());
687 # ifndef OPENSSL_NO_DES
688 wrap_cipher = EVP_des_ede3_wrap();
691 case OPT_AES128_WRAP:
692 wrap_cipher = EVP_aes_128_wrap();
694 case OPT_AES192_WRAP:
695 wrap_cipher = EVP_aes_192_wrap();
697 case OPT_AES256_WRAP:
698 wrap_cipher = EVP_aes_256_wrap();
701 if (!opt_cipher(opt_unknown(), &wrap_cipher))
706 argc = opt_num_rest();
709 if ((rr_allorfirst != -1 || rr_from != NULL) && rr_to == NULL) {
710 BIO_puts(bio_err, "No Signed Receipts Recipients\n");
714 if (!(operation & SMIME_SIGNERS) && (rr_to != NULL || rr_from != NULL)) {
715 BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
718 if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) {
719 BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
723 if ((flags & CMS_CADES) != 0) {
724 if ((flags & CMS_NOATTR) != 0) {
725 BIO_puts(bio_err, "Incompatible options: "
726 "CAdES required signed attributes\n");
729 if (operation == SMIME_VERIFY
730 && (flags & (CMS_NO_SIGNER_CERT_VERIFY | CMS_NO_ATTR_VERIFY)) != 0) {
731 BIO_puts(bio_err, "Incompatible options: CAdES validation require"
732 " certs and signed attributes validations\n");
737 if (operation & SMIME_SIGNERS) {
738 if (keyfile != NULL && signerfile == NULL) {
739 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
742 /* Check to see if any final signer needs to be appended */
743 if (signerfile != NULL) {
744 if (sksigners == NULL
745 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
747 sk_OPENSSL_STRING_push(sksigners, signerfile);
748 if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
751 keyfile = signerfile;
752 sk_OPENSSL_STRING_push(skkeys, keyfile);
754 if (sksigners == NULL) {
755 BIO_printf(bio_err, "No signer certificate specified\n");
760 } else if (operation == SMIME_DECRYPT) {
761 if (recipfile == NULL && keyfile == NULL
762 && secret_key == NULL && pwri_pass == NULL) {
764 "No recipient certificate or key specified\n");
767 } else if (operation == SMIME_ENCRYPT) {
768 if (*argv == NULL && secret_key == NULL
769 && pwri_pass == NULL && encerts == NULL) {
770 BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
773 } else if (!operation) {
774 BIO_printf(bio_err, "No operation option (-encrypt|-decrypt|-sign|-verify|...) specified.\n");
778 if (!app_passwd(passinarg, NULL, &passin, NULL)) {
779 BIO_printf(bio_err, "Error getting password\n");
785 if (!(operation & SMIME_SIGNERS))
786 flags &= ~CMS_DETACHED;
788 if (!(operation & SMIME_OP))
789 if (flags & CMS_BINARY)
790 outformat = FORMAT_BINARY;
792 if (!(operation & SMIME_IP))
793 if (flags & CMS_BINARY)
794 informat = FORMAT_BINARY;
796 if (operation == SMIME_ENCRYPT) {
798 # ifndef OPENSSL_NO_DES
799 cipher = EVP_des_ede3_cbc();
801 BIO_printf(bio_err, "No cipher selected\n");
806 if (secret_key && !secret_keyid) {
807 BIO_printf(bio_err, "No secret key id\n");
811 if (*argv && encerts == NULL)
812 if ((encerts = sk_X509_new_null()) == NULL)
815 if ((cert = load_cert(*argv, FORMAT_UNDEF,
816 "recipient certificate file")) == NULL)
818 sk_X509_push(encerts, cert);
824 if (certfile != NULL) {
825 if (!load_certs(certfile, &other, NULL, "certificate file")) {
826 ERR_print_errors(bio_err);
831 if (recipfile != NULL && (operation == SMIME_DECRYPT)) {
832 if ((recip = load_cert(recipfile, FORMAT_UNDEF,
833 "recipient certificate file")) == NULL) {
834 ERR_print_errors(bio_err);
839 if (originatorfile != NULL) {
840 if ((originator = load_cert(originatorfile, FORMAT_UNDEF,
841 "originator certificate file")) == NULL) {
842 ERR_print_errors(bio_err);
847 if (operation == SMIME_SIGN_RECEIPT) {
848 if ((signer = load_cert(signerfile, FORMAT_UNDEF,
849 "receipt signer certificate file")) == NULL) {
850 ERR_print_errors(bio_err);
855 if ((operation == SMIME_DECRYPT) || (operation == SMIME_ENCRYPT)) {
858 } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
860 keyfile = signerfile;
865 if (keyfile != NULL) {
866 key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
871 * TODO: Remove this when CMS has full support for provider-native
874 if (EVP_PKEY_get0(key) == NULL)
878 in = bio_open_default(infile, 'r', informat);
882 if (operation & SMIME_IP) {
883 cms = load_content_info(informat, in, &indata, "SMIME", libctx, propq);
886 if (contfile != NULL) {
888 if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
889 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
893 if (certsoutfile != NULL) {
894 STACK_OF(X509) *allcerts;
895 allcerts = CMS_get1_certs(cms);
896 if (!save_certs(certsoutfile, allcerts)) {
898 "Error writing certs to %s\n", certsoutfile);
902 sk_X509_pop_free(allcerts, X509_free);
906 if (rctfile != NULL) {
907 char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
908 if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) {
909 BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile);
913 rcms = load_content_info(rctformat, rctin, NULL, "recipient", libctx,
919 out = bio_open_default(outfile, 'w', outformat);
923 if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) {
924 if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
925 CAstore, noCAstore)) == NULL)
927 X509_STORE_set_verify_cb(store, cms_cb);
929 X509_STORE_set1_param(store, vpm);
934 if (operation == SMIME_DATA_CREATE) {
935 cms = CMS_data_create_with_libctx(in, flags, libctx, propq);
936 } else if (operation == SMIME_DIGEST_CREATE) {
937 cms = CMS_digest_create_with_libctx(in, sign_md, flags, libctx, propq);
938 } else if (operation == SMIME_COMPRESS) {
939 cms = CMS_compress(in, -1, flags);
940 } else if (operation == SMIME_ENCRYPT) {
942 flags |= CMS_PARTIAL;
943 cms = CMS_encrypt_with_libctx(NULL, in, cipher, flags, libctx, propq);
946 for (i = 0; i < sk_X509_num(encerts); i++) {
947 CMS_RecipientInfo *ri;
948 cms_key_param *kparam;
949 int tflags = flags | CMS_KEY_PARAM; /* This flag enforces allocating the EVP_PKEY_CTX for the recipient here */
951 X509 *x = sk_X509_value(encerts, i);
954 for (kparam = key_first; kparam; kparam = kparam->next) {
955 if (kparam->idx == i) {
959 ri = CMS_add1_recipient(cms, x, key, originator, tflags);
963 pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
964 if (kparam != NULL) {
965 if (!cms_set_pkey_param(pctx, kparam->param))
969 res = EVP_PKEY_CTX_ctrl(pctx, -1, -1,
970 EVP_PKEY_CTRL_CIPHER,
971 EVP_CIPHER_nid(cipher), NULL);
972 if (res <= 0 && res != -2)
975 if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE
977 EVP_CIPHER_CTX *wctx;
978 wctx = CMS_RecipientInfo_kari_get0_ctx(ri);
979 EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL);
983 if (secret_key != NULL) {
984 if (!CMS_add0_recipient_key(cms, NID_undef,
985 secret_key, secret_keylen,
986 secret_keyid, secret_keyidlen,
989 /* NULL these because call absorbs them */
993 if (pwri_pass != NULL) {
994 pwri_tmp = (unsigned char *)OPENSSL_strdup((char *)pwri_pass);
995 if (pwri_tmp == NULL)
997 if (CMS_add0_recipient_password(cms,
998 -1, NID_undef, NID_undef,
999 pwri_tmp, -1, NULL) == NULL)
1003 if (!(flags & CMS_STREAM)) {
1004 if (!CMS_final(cms, in, NULL, flags))
1007 } else if (operation == SMIME_ENCRYPTED_ENCRYPT) {
1008 cms = CMS_EncryptedData_encrypt_with_libctx(in, cipher, secret_key,
1009 secret_keylen, flags,
1012 } else if (operation == SMIME_SIGN_RECEIPT) {
1013 CMS_ContentInfo *srcms = NULL;
1014 STACK_OF(CMS_SignerInfo) *sis;
1016 sis = CMS_get0_SignerInfos(cms);
1019 si = sk_CMS_SignerInfo_value(sis, 0);
1020 srcms = CMS_sign_receipt(si, signer, key, other, flags);
1023 CMS_ContentInfo_free(cms);
1025 } else if (operation & SMIME_SIGNERS) {
1028 * If detached data content we enable streaming if S/MIME output
1031 if (operation == SMIME_SIGN) {
1033 if (flags & CMS_DETACHED) {
1034 if (outformat == FORMAT_SMIME)
1035 flags |= CMS_STREAM;
1037 flags |= CMS_PARTIAL;
1038 cms = CMS_sign_with_libctx(NULL, NULL, other, in, flags, libctx, propq);
1041 if (econtent_type != NULL)
1042 CMS_set1_eContentType(cms, econtent_type);
1044 if (rr_to != NULL) {
1045 rr = make_receipt_request(rr_to, rr_allorfirst, rr_from, libctx,
1049 "Signed Receipt Request Creation Error\n");
1054 flags |= CMS_REUSE_DIGEST;
1056 for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
1058 cms_key_param *kparam;
1060 signerfile = sk_OPENSSL_STRING_value(sksigners, i);
1061 keyfile = sk_OPENSSL_STRING_value(skkeys, i);
1063 signer = load_cert(signerfile, FORMAT_UNDEF,
1064 "signer certificate");
1065 if (signer == NULL) {
1069 key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
1076 * TODO: Remove this when CMS has full support for provider-native
1079 if (EVP_PKEY_get0(key) == NULL)
1082 for (kparam = key_first; kparam; kparam = kparam->next) {
1083 if (kparam->idx == i) {
1084 tflags |= CMS_KEY_PARAM;
1088 si = CMS_add1_signer(cms, signer, key, sign_md, tflags);
1091 if (kparam != NULL) {
1093 pctx = CMS_SignerInfo_get0_pkey_ctx(si);
1094 if (!cms_set_pkey_param(pctx, kparam->param))
1097 if (rr != NULL && !CMS_add1_ReceiptRequest(si, rr))
1104 /* If not streaming or resigning finalize structure */
1105 if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
1106 if (!CMS_final(cms, in, NULL, flags))
1112 BIO_printf(bio_err, "Error creating CMS structure\n");
1117 if (operation == SMIME_DECRYPT) {
1118 if (flags & CMS_DEBUG_DECRYPT)
1119 CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);
1121 if (secret_key != NULL) {
1122 if (!CMS_decrypt_set1_key(cms,
1123 secret_key, secret_keylen,
1124 secret_keyid, secret_keyidlen)) {
1125 BIO_puts(bio_err, "Error decrypting CMS using secret key\n");
1131 if (!CMS_decrypt_set1_pkey_and_peer(cms, key, recip, originator)) {
1132 BIO_puts(bio_err, "Error decrypting CMS using private key\n");
1137 if (pwri_pass != NULL) {
1138 if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
1139 BIO_puts(bio_err, "Error decrypting CMS using password\n");
1144 if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
1145 BIO_printf(bio_err, "Error decrypting CMS structure\n");
1148 } else if (operation == SMIME_DATAOUT) {
1149 if (!CMS_data(cms, out, flags))
1151 } else if (operation == SMIME_UNCOMPRESS) {
1152 if (!CMS_uncompress(cms, indata, out, flags))
1154 } else if (operation == SMIME_DIGEST_VERIFY) {
1155 if (CMS_digest_verify(cms, indata, out, flags) > 0) {
1156 BIO_printf(bio_err, "Verification successful\n");
1158 BIO_printf(bio_err, "Verification failure\n");
1161 } else if (operation == SMIME_ENCRYPTED_DECRYPT) {
1162 if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
1163 indata, out, flags))
1165 } else if (operation == SMIME_VERIFY) {
1166 if (CMS_verify(cms, other, store, indata, out, flags) > 0) {
1167 BIO_printf(bio_err, "%s Verification successful\n",
1168 (flags & CMS_CADES) ? "CAdES" : "CMS");
1170 BIO_printf(bio_err, "Verification failure\n");
1172 ret = verify_err + 32;
1175 if (signerfile != NULL) {
1176 STACK_OF(X509) *signers;
1177 signers = CMS_get0_signers(cms);
1178 if (!save_certs(signerfile, signers)) {
1180 "Error writing signers to %s\n", signerfile);
1184 sk_X509_free(signers);
1187 receipt_request_print(cms);
1189 } else if (operation == SMIME_VERIFY_RECEIPT) {
1190 if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) {
1191 BIO_printf(bio_err, "Verification successful\n");
1193 BIO_printf(bio_err, "Verification failure\n");
1199 ASN1_PCTX *pctx = NULL;
1200 if (get_nameopt() != XN_FLAG_ONELINE) {
1201 pctx = ASN1_PCTX_new();
1202 if (pctx != NULL) { /* Print anyway if malloc failed */
1203 ASN1_PCTX_set_flags(pctx, ASN1_PCTX_FLAGS_SHOW_ABSENT);
1204 ASN1_PCTX_set_str_flags(pctx, get_nameopt());
1205 ASN1_PCTX_set_nm_flags(pctx, get_nameopt());
1208 CMS_ContentInfo_print_ctx(out, cms, 0, pctx);
1209 ASN1_PCTX_free(pctx);
1211 } else if (outformat == FORMAT_SMIME) {
1213 BIO_printf(out, "To: %s%s", to, mime_eol);
1215 BIO_printf(out, "From: %s%s", from, mime_eol);
1217 BIO_printf(out, "Subject: %s%s", subject, mime_eol);
1218 if (operation == SMIME_RESIGN)
1219 ret = SMIME_write_CMS(out, cms, indata, flags);
1221 ret = SMIME_write_CMS(out, cms, in, flags);
1222 } else if (outformat == FORMAT_PEM) {
1223 ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
1224 } else if (outformat == FORMAT_ASN1) {
1225 ret = i2d_CMS_bio_stream(out, cms, in, flags);
1227 BIO_printf(bio_err, "Bad output format for CMS file\n");
1238 ERR_print_errors(bio_err);
1239 sk_X509_pop_free(encerts, X509_free);
1240 sk_X509_pop_free(other, X509_free);
1241 X509_VERIFY_PARAM_free(vpm);
1242 sk_OPENSSL_STRING_free(sksigners);
1243 sk_OPENSSL_STRING_free(skkeys);
1244 OPENSSL_free(secret_key);
1245 OPENSSL_free(secret_keyid);
1246 OPENSSL_free(pwri_tmp);
1247 ASN1_OBJECT_free(econtent_type);
1248 CMS_ReceiptRequest_free(rr);
1249 sk_OPENSSL_STRING_free(rr_to);
1250 sk_OPENSSL_STRING_free(rr_from);
1251 for (key_param = key_first; key_param;) {
1252 cms_key_param *tparam;
1253 sk_OPENSSL_STRING_free(key_param->param);
1254 tparam = key_param->next;
1255 OPENSSL_free(key_param);
1258 X509_STORE_free(store);
1263 CMS_ContentInfo_free(cms);
1264 CMS_ContentInfo_free(rcms);
1270 OPENSSL_free(passin);
1275 static int save_certs(char *signerfile, STACK_OF(X509) *signers)
1279 if (signerfile == NULL)
1281 tmp = BIO_new_file(signerfile, "w");
1284 for (i = 0; i < sk_X509_num(signers); i++)
1285 PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
1290 /* Minimal callback just to output policy info (if any) */
1292 static int cms_cb(int ok, X509_STORE_CTX *ctx)
1296 error = X509_STORE_CTX_get_error(ctx);
1300 if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
1301 && ((error != X509_V_OK) || (ok != 2)))
1304 policies_print(ctx);
1310 static void gnames_stack_print(STACK_OF(GENERAL_NAMES) *gns)
1312 STACK_OF(GENERAL_NAME) *gens;
1316 for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) {
1317 gens = sk_GENERAL_NAMES_value(gns, i);
1318 for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) {
1319 gen = sk_GENERAL_NAME_value(gens, j);
1320 BIO_puts(bio_err, " ");
1321 GENERAL_NAME_print(bio_err, gen);
1322 BIO_puts(bio_err, "\n");
1328 static void receipt_request_print(CMS_ContentInfo *cms)
1330 STACK_OF(CMS_SignerInfo) *sis;
1332 CMS_ReceiptRequest *rr;
1334 STACK_OF(GENERAL_NAMES) *rto, *rlist;
1337 sis = CMS_get0_SignerInfos(cms);
1338 for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) {
1339 si = sk_CMS_SignerInfo_value(sis, i);
1340 rv = CMS_get1_ReceiptRequest(si, &rr);
1341 BIO_printf(bio_err, "Signer %d:\n", i + 1);
1343 BIO_puts(bio_err, " No Receipt Request\n");
1344 } else if (rv < 0) {
1345 BIO_puts(bio_err, " Receipt Request Parse Error\n");
1346 ERR_print_errors(bio_err);
1350 CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst,
1352 BIO_puts(bio_err, " Signed Content ID:\n");
1353 idlen = ASN1_STRING_length(scid);
1354 id = (const char *)ASN1_STRING_get0_data(scid);
1355 BIO_dump_indent(bio_err, id, idlen, 4);
1356 BIO_puts(bio_err, " Receipts From");
1357 if (rlist != NULL) {
1358 BIO_puts(bio_err, " List:\n");
1359 gnames_stack_print(rlist);
1360 } else if (allorfirst == 1) {
1361 BIO_puts(bio_err, ": First Tier\n");
1362 } else if (allorfirst == 0) {
1363 BIO_puts(bio_err, ": All\n");
1365 BIO_printf(bio_err, " Unknown (%d)\n", allorfirst);
1367 BIO_puts(bio_err, " Receipts To:\n");
1368 gnames_stack_print(rto);
1370 CMS_ReceiptRequest_free(rr);
1374 static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns)
1377 STACK_OF(GENERAL_NAMES) *ret;
1378 GENERAL_NAMES *gens = NULL;
1379 GENERAL_NAME *gen = NULL;
1380 ret = sk_GENERAL_NAMES_new_null();
1383 for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) {
1384 char *str = sk_OPENSSL_STRING_value(ns, i);
1385 gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0);
1388 gens = GENERAL_NAMES_new();
1391 if (!sk_GENERAL_NAME_push(gens, gen))
1394 if (!sk_GENERAL_NAMES_push(ret, gens))
1402 sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free);
1403 GENERAL_NAMES_free(gens);
1404 GENERAL_NAME_free(gen);
1408 static CMS_ReceiptRequest *make_receipt_request(
1409 STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst,
1410 STACK_OF(OPENSSL_STRING) *rr_from,
1411 OPENSSL_CTX *libctx, const char *propq)
1413 STACK_OF(GENERAL_NAMES) *rct_to = NULL, *rct_from = NULL;
1414 CMS_ReceiptRequest *rr;
1415 rct_to = make_names_stack(rr_to);
1418 if (rr_from != NULL) {
1419 rct_from = make_names_stack(rr_from);
1420 if (rct_from == NULL)
1425 rr = CMS_ReceiptRequest_create0_with_libctx(NULL, -1, rr_allorfirst,
1426 rct_from, rct_to, libctx, propq);
1429 sk_GENERAL_NAMES_pop_free(rct_to, GENERAL_NAMES_free);
1433 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
1434 STACK_OF(OPENSSL_STRING) *param)
1438 if (sk_OPENSSL_STRING_num(param) <= 0)
1440 for (i = 0; i < sk_OPENSSL_STRING_num(param); i++) {
1441 keyopt = sk_OPENSSL_STRING_value(param, i);
1442 if (pkey_ctrl_string(pctx, keyopt) <= 0) {
1443 BIO_printf(bio_err, "parameter error \"%s\"\n", keyopt);
1444 ERR_print_errors(bio_err);