2 * Copyright 2008-2021 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 /* CMS utility function */
17 #ifndef OPENSSL_NO_CMS
19 # include <openssl/crypto.h>
20 # include <openssl/pem.h>
21 # include <openssl/err.h>
22 # include <openssl/x509_vfy.h>
23 # include <openssl/x509v3.h>
24 # include <openssl/cms.h>
26 static int save_certs(char *signerfile, STACK_OF(X509) *signers);
27 static int cms_cb(int ok, X509_STORE_CTX *ctx);
28 static void receipt_request_print(CMS_ContentInfo *cms);
29 static CMS_ReceiptRequest *make_receipt_request(
30 STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst,
31 STACK_OF(OPENSSL_STRING) *rr_from, OSSL_LIB_CTX *libctx);
32 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
33 STACK_OF(OPENSSL_STRING) *param);
35 # define SMIME_OP 0x10
36 # define SMIME_IP 0x20
37 # define SMIME_SIGNERS 0x40
38 # define SMIME_ENCRYPT (1 | SMIME_OP)
39 # define SMIME_DECRYPT (2 | SMIME_IP)
40 # define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS)
41 # define SMIME_VERIFY (4 | SMIME_IP)
42 # define SMIME_CMSOUT (5 | SMIME_IP | SMIME_OP)
43 # define SMIME_RESIGN (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
44 # define SMIME_DATAOUT (7 | SMIME_IP)
45 # define SMIME_DATA_CREATE (8 | SMIME_OP)
46 # define SMIME_DIGEST_VERIFY (9 | SMIME_IP)
47 # define SMIME_DIGEST_CREATE (10 | SMIME_OP)
48 # define SMIME_UNCOMPRESS (11 | SMIME_IP)
49 # define SMIME_COMPRESS (12 | SMIME_OP)
50 # define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP)
51 # define SMIME_ENCRYPTED_ENCRYPT (14 | SMIME_OP)
52 # define SMIME_SIGN_RECEIPT (15 | SMIME_IP | SMIME_OP)
53 # define SMIME_VERIFY_RECEIPT (16 | SMIME_IP)
55 static int verify_err = 0;
57 typedef struct cms_key_param_st cms_key_param;
59 struct cms_key_param_st {
61 STACK_OF(OPENSSL_STRING) *param;
65 typedef enum OPTION_choice {
66 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
67 OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENCRYPT,
68 OPT_DECRYPT, OPT_SIGN, OPT_CADES, OPT_SIGN_RECEIPT, OPT_RESIGN,
69 OPT_VERIFY, OPT_VERIFY_RETCODE, OPT_VERIFY_RECEIPT,
70 OPT_CMSOUT, OPT_DATA_OUT, OPT_DATA_CREATE, OPT_DIGEST_VERIFY,
71 OPT_DIGEST_CREATE, OPT_COMPRESS, OPT_UNCOMPRESS,
72 OPT_ED_DECRYPT, OPT_ED_ENCRYPT, OPT_DEBUG_DECRYPT, OPT_TEXT,
73 OPT_ASCIICRLF, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCERTS,
74 OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP, OPT_BINARY, OPT_KEYID,
75 OPT_NOSIGS, OPT_NO_CONTENT_VERIFY, OPT_NO_ATTR_VERIFY, OPT_INDEF,
76 OPT_NOINDEF, OPT_CRLFEOL, OPT_NOOUT, OPT_RR_PRINT,
77 OPT_RR_ALL, OPT_RR_FIRST, OPT_RCTFORM, OPT_CERTFILE, OPT_CAFILE,
78 OPT_CAPATH, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE,
79 OPT_CONTENT, OPT_PRINT, OPT_NAMEOPT,
80 OPT_SECRETKEY, OPT_SECRETKEYID, OPT_PWRI_PASSWORD, OPT_ECONTENT_TYPE,
81 OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP,
82 OPT_CERTSOUT, OPT_MD, OPT_INKEY, OPT_KEYFORM, OPT_KEYOPT, OPT_RR_FROM,
83 OPT_RR_TO, OPT_AES128_WRAP, OPT_AES192_WRAP, OPT_AES256_WRAP,
84 OPT_3DES_WRAP, OPT_WRAP, OPT_ENGINE,
86 OPT_PROV_ENUM, OPT_CONFIG,
92 const OPTIONS cms_options[] = {
93 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"},
95 OPT_SECTION("General"),
96 {"help", OPT_HELP, '-', "Display this summary"},
97 {"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"},
98 {"outform", OPT_OUTFORM, 'c',
99 "Output format SMIME (default), PEM or DER"},
100 {"in", OPT_IN, '<', "Input file"},
101 {"out", OPT_OUT, '>', "Output file"},
102 {"debug_decrypt", OPT_DEBUG_DECRYPT, '-',
103 "Disable MMA protection and return an error if no recipient found"
104 " (see documentation)"},
105 {"stream", OPT_INDEF, '-', "Enable CMS streaming"},
106 {"indef", OPT_INDEF, '-', "Same as -stream"},
107 {"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"},
108 {"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of CR only" },
109 {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
110 {"CApath", OPT_CAPATH, '/', "trusted certificates directory"},
111 {"CAstore", OPT_CASTORE, ':', "trusted certificates store URI"},
112 {"no-CAfile", OPT_NOCAFILE, '-',
113 "Do not load the default certificates file"},
114 {"no-CApath", OPT_NOCAPATH, '-',
115 "Do not load certificates from the default certificates directory"},
116 {"no-CAstore", OPT_NOCASTORE, '-',
117 "Do not load certificates from the default certificates store"},
118 # ifndef OPENSSL_NO_ENGINE
119 {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
123 OPT_SECTION("Action"),
124 {"encrypt", OPT_ENCRYPT, '-', "Encrypt message"},
125 {"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"},
126 {"sign", OPT_SIGN, '-', "Sign message"},
127 {"sign_receipt", OPT_SIGN_RECEIPT, '-', "Generate a signed receipt for the message"},
128 {"resign", OPT_RESIGN, '-', "Resign a signed message"},
129 {"cades", OPT_CADES, '-', "Include or check signingCertificate (CAdES-BES)"},
130 {"verify", OPT_VERIFY, '-', "Verify signed message"},
131 {"verify_retcode", OPT_VERIFY_RETCODE, '-',
132 "Exit non-zero on verification failure"},
133 {"verify_receipt", OPT_VERIFY_RECEIPT, '<',
134 "Verify receipts; exit if receipt signatures do not verify"},
135 {"digest_verify", OPT_DIGEST_VERIFY, '-',
136 "Verify a CMS \"DigestedData\" object and output it"},
137 {"digest_create", OPT_DIGEST_CREATE, '-',
138 "Create a CMS \"DigestedData\" object"},
139 {"compress", OPT_COMPRESS, '-', "Create a CMS \"CompressedData\" object"},
140 {"uncompress", OPT_UNCOMPRESS, '-',
141 "Uncompress a CMS \"CompressedData\" object"},
142 {"EncryptedData_decrypt", OPT_ED_DECRYPT, '-',
143 "Decrypt CMS \"EncryptedData\" object using symmetric key"},
144 {"EncryptedData_encrypt", OPT_ED_ENCRYPT, '-',
145 "Create CMS \"EncryptedData\" object using symmetric key"},
146 {"data_out", OPT_DATA_OUT, '-', "Copy CMS \"Data\" object to output"},
147 {"data_create", OPT_DATA_CREATE, '-', "Create a CMS \"Data\" object"},
148 {"cmsout", OPT_CMSOUT, '-', "Output CMS structure"},
149 {"no_content_verify", OPT_NO_CONTENT_VERIFY, '-',
150 "Do not verify signed content signatures"},
151 {"no_attr_verify", OPT_NO_ATTR_VERIFY, '-',
152 "Do not verify signed attribute signatures"},
153 {"nointern", OPT_NOINTERN, '-',
154 "Don't search certificates in message for signer"},
155 {"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"},
157 OPT_SECTION("Formatting"),
158 {"text", OPT_TEXT, '-', "Include or delete text MIME headers"},
159 {"asciicrlf", OPT_ASCIICRLF, '-',
160 "Perform CRLF canonicalisation when signing"},
161 {"nodetach", OPT_NODETACH, '-', "Use opaque signing"},
162 {"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"},
163 {"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"},
164 {"binary", OPT_BINARY, '-', "Don't translate message to text"},
165 {"keyid", OPT_KEYID, '-', "Use subject key identifier"},
166 {"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"},
167 {"nocerts", OPT_NOCERTS, '-',
168 "Don't include signers certificate when signing"},
169 {"noout", OPT_NOOUT, '-',
170 "For the -cmsout operation do not output the parsed CMS structure"},
171 {"receipt_request_print", OPT_RR_PRINT, '-', "Print CMS Receipt Request" },
172 {"receipt_request_all", OPT_RR_ALL, '-',
173 "When signing, create a receipt request for all recipients"},
174 {"receipt_request_first", OPT_RR_FIRST, '-',
175 "When signing, create a receipt request for first recipient"},
176 {"rctform", OPT_RCTFORM, 'F', "Receipt file format"},
177 {"certfile", OPT_CERTFILE, '<', "Other certificates file"},
178 {"content", OPT_CONTENT, '<',
179 "Supply or override content for detached signature"},
180 {"print", OPT_PRINT, '-',
181 "For the -cmsout operation print out all fields of the CMS structure"},
182 {"nameopt", OPT_NAMEOPT, 's',
183 "For the -print option specifies various strings printing options"},
184 {"certsout", OPT_CERTSOUT, '>', "Certificate output file"},
186 OPT_SECTION("Keying"),
187 {"secretkey", OPT_SECRETKEY, 's',
188 "Use specified hex-encoded key to decrypt/encrypt recipients or content"},
189 {"secretkeyid", OPT_SECRETKEYID, 's',
190 "Identity of the -secretkey for CMS \"KEKRecipientInfo\" object"},
191 {"pwri_password", OPT_PWRI_PASSWORD, 's',
192 "Specific password for recipient"},
193 {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
194 {"inkey", OPT_INKEY, 's',
195 "Input private key (if not signer or recipient)"},
196 {"keyform", OPT_KEYFORM, 'f', "Input private key format (ENGINE, other values ignored)"},
197 {"keyopt", OPT_KEYOPT, 's', "Set public key parameters as n:v pairs"},
199 OPT_SECTION("Mail header"),
200 {"econtent_type", OPT_ECONTENT_TYPE, 's', "OID for external content"},
201 {"to", OPT_TO, 's', "To address"},
202 {"from", OPT_FROM, 's', "From address"},
203 {"subject", OPT_SUBJECT, 's', "Subject"},
204 {"signer", OPT_SIGNER, 's', "Signer certificate file"},
205 {"originator", OPT_ORIGINATOR, 's', "Originator certificate file"},
206 {"recip", OPT_RECIP, '<', "Recipient cert file for decryption"},
207 {"receipt_request_from", OPT_RR_FROM, 's',
208 "Create signed receipt request with specified email address"},
209 {"receipt_request_to", OPT_RR_TO, 's',
210 "Create signed receipt targeted to specified address"},
212 OPT_SECTION("Encryption"),
213 {"md", OPT_MD, 's', "Digest algorithm to use when signing or resigning"},
214 {"", OPT_CIPHER, '-', "Any supported cipher"},
216 OPT_SECTION("Key-wrapping"),
217 {"aes128-wrap", OPT_AES128_WRAP, '-', "Use AES128 to wrap key"},
218 {"aes192-wrap", OPT_AES192_WRAP, '-', "Use AES192 to wrap key"},
219 {"aes256-wrap", OPT_AES256_WRAP, '-', "Use AES256 to wrap key"},
220 # ifndef OPENSSL_NO_DES
221 {"des3-wrap", OPT_3DES_WRAP, '-', "Use 3DES-EDE to wrap key"},
223 {"wrap", OPT_WRAP, 's', "Any wrap cipher to wrap key"},
230 {"cert", 0, 0, "Recipient certs (optional; used only when encrypting)"},
234 static CMS_ContentInfo *load_content_info(int informat, BIO *in, BIO **indata,
236 OSSL_LIB_CTX *libctx,
239 CMS_ContentInfo *ret, *ci;
241 ret = CMS_ContentInfo_new_ex(libctx, propq);
243 BIO_printf(bio_err, "Error allocating CMS_contentinfo\n");
248 ci = SMIME_read_CMS_ex(in, indata, &ret);
251 ci = PEM_read_bio_CMS(in, &ret, NULL, NULL);
254 ci = d2i_CMS_bio(in, &ret);
257 BIO_printf(bio_err, "Bad input format for %s\n", name);
261 BIO_printf(bio_err, "Error reading %s Content Info\n", name);
266 CMS_ContentInfo_free(ret);
270 int cms_main(int argc, char **argv)
273 ASN1_OBJECT *econtent_type = NULL;
274 BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
275 CMS_ContentInfo *cms = NULL, *rcms = NULL;
276 CMS_ReceiptRequest *rr = NULL;
278 EVP_PKEY *key = NULL;
279 const EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
280 const EVP_MD *sign_md = NULL;
281 STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
282 STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
283 STACK_OF(X509) *encerts = NULL, *other = NULL;
284 X509 *cert = NULL, *recip = NULL, *signer = NULL, *originator = NULL;
285 X509_STORE *store = NULL;
286 X509_VERIFY_PARAM *vpm = NULL;
287 char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
288 const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
289 char *certsoutfile = NULL, *digestname = NULL;
290 int noCAfile = 0, noCApath = 0, noCAstore = 0;
291 char *infile = NULL, *outfile = NULL, *rctfile = NULL;
292 char *passinarg = NULL, *passin = NULL, *signerfile = NULL;
293 char *originatorfile = NULL, *recipfile = NULL, *ciphername = NULL;
294 char *to = NULL, *from = NULL, *subject = NULL, *prog;
295 cms_key_param *key_first = NULL, *key_param = NULL;
296 int flags = CMS_DETACHED, noout = 0, print = 0, keyidx = -1, vpmtouched = 0;
297 int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
298 int operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1;
299 int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_PEM;
300 size_t secret_keylen = 0, secret_keyidlen = 0;
301 unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
302 unsigned char *secret_key = NULL, *secret_keyid = NULL;
304 const char *mime_eol = "\n";
306 OSSL_LIB_CTX *libctx = app_get0_libctx();
308 if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
311 prog = opt_init(argc, argv, cms_options);
312 while ((o = opt_next()) != OPT_EOF) {
317 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
320 opt_help(cms_options);
324 if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
328 if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
335 operation = SMIME_ENCRYPT;
338 operation = SMIME_DECRYPT;
341 operation = SMIME_SIGN;
343 case OPT_SIGN_RECEIPT:
344 operation = SMIME_SIGN_RECEIPT;
347 operation = SMIME_RESIGN;
350 operation = SMIME_VERIFY;
352 case OPT_VERIFY_RETCODE:
355 case OPT_VERIFY_RECEIPT:
356 operation = SMIME_VERIFY_RECEIPT;
360 operation = SMIME_CMSOUT;
363 operation = SMIME_DATAOUT;
365 case OPT_DATA_CREATE:
366 operation = SMIME_DATA_CREATE;
368 case OPT_DIGEST_VERIFY:
369 operation = SMIME_DIGEST_VERIFY;
371 case OPT_DIGEST_CREATE:
372 operation = SMIME_DIGEST_CREATE;
375 operation = SMIME_COMPRESS;
378 operation = SMIME_UNCOMPRESS;
381 operation = SMIME_ENCRYPTED_DECRYPT;
384 operation = SMIME_ENCRYPTED_ENCRYPT;
386 case OPT_DEBUG_DECRYPT:
387 flags |= CMS_DEBUG_DECRYPT;
393 flags |= CMS_ASCIICRLF;
396 flags |= CMS_NOINTERN;
399 flags |= CMS_NO_SIGNER_CERT_VERIFY;
402 flags |= CMS_NOCERTS;
408 flags &= ~CMS_DETACHED;
411 flags |= CMS_NOSMIMECAP;
420 flags |= CMS_USE_KEYID;
425 case OPT_NO_CONTENT_VERIFY:
426 flags |= CMS_NO_CONTENT_VERIFY;
428 case OPT_NO_ATTR_VERIFY:
429 flags |= CMS_NO_ATTR_VERIFY;
435 flags &= ~CMS_STREAM;
439 flags |= CMS_CRLFEOL;
454 if (rctformat == FORMAT_ASN1) {
455 if (!opt_format(opt_arg(),
456 OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat))
459 rcms = load_content_info(rctformat, rctin, NULL, "recipient",
460 libctx, app_get0_propq());
464 certfile = opt_arg();
488 contfile = opt_arg();
492 && (rr_from = sk_OPENSSL_STRING_new_null()) == NULL)
494 sk_OPENSSL_STRING_push(rr_from, opt_arg());
498 && (rr_to = sk_OPENSSL_STRING_new_null()) == NULL)
500 sk_OPENSSL_STRING_push(rr_to, opt_arg());
506 if (!set_nameopt(opt_arg()))
510 if (secret_key != NULL) {
511 BIO_printf(bio_err, "Invalid key (supplied twice) %s\n",
515 secret_key = OPENSSL_hexstr2buf(opt_arg(), <mp);
516 if (secret_key == NULL) {
517 BIO_printf(bio_err, "Invalid key %s\n", opt_arg());
520 secret_keylen = (size_t)ltmp;
522 case OPT_SECRETKEYID:
523 if (secret_keyid != NULL) {
524 BIO_printf(bio_err, "Invalid id (supplied twice) %s\n",
528 secret_keyid = OPENSSL_hexstr2buf(opt_arg(), <mp);
529 if (secret_keyid == NULL) {
530 BIO_printf(bio_err, "Invalid id %s\n", opt_arg());
533 secret_keyidlen = (size_t)ltmp;
535 case OPT_PWRI_PASSWORD:
536 pwri_pass = (unsigned char *)opt_arg();
538 case OPT_ECONTENT_TYPE:
539 if (econtent_type != NULL) {
540 BIO_printf(bio_err, "Invalid OID (supplied twice) %s\n",
544 econtent_type = OBJ_txt2obj(opt_arg(), 0);
545 if (econtent_type == NULL) {
546 BIO_printf(bio_err, "Invalid OID %s\n", opt_arg());
551 e = setup_engine(opt_arg(), 0);
554 passinarg = opt_arg();
566 certsoutfile = opt_arg();
569 digestname = opt_arg();
572 /* If previous -signer argument add signer to list */
573 if (signerfile != NULL) {
574 if (sksigners == NULL
575 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
577 sk_OPENSSL_STRING_push(sksigners, signerfile);
579 keyfile = signerfile;
581 && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
583 sk_OPENSSL_STRING_push(skkeys, keyfile);
586 signerfile = opt_arg();
589 originatorfile = opt_arg();
592 /* If previous -inkey argument add signer to list */
593 if (keyfile != NULL) {
594 if (signerfile == NULL) {
595 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
598 if (sksigners == NULL
599 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
601 sk_OPENSSL_STRING_push(sksigners, signerfile);
604 && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
606 sk_OPENSSL_STRING_push(skkeys, keyfile);
611 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
615 if (operation == SMIME_ENCRYPT) {
616 if (encerts == NULL && (encerts = sk_X509_new_null()) == NULL)
618 cert = load_cert(opt_arg(), "recipient certificate file");
621 sk_X509_push(encerts, cert);
624 recipfile = opt_arg();
628 ciphername = opt_unknown();
632 if (operation == SMIME_ENCRYPT) {
634 keyidx += sk_X509_num(encerts);
636 if (keyfile != NULL || signerfile != NULL)
639 keyidx += sk_OPENSSL_STRING_num(skkeys);
642 BIO_printf(bio_err, "No key specified\n");
645 if (key_param == NULL || key_param->idx != keyidx) {
646 cms_key_param *nparam;
647 nparam = app_malloc(sizeof(*nparam), "key param buffer");
648 if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL) {
649 OPENSSL_free(nparam);
652 nparam->idx = keyidx;
654 if (key_first == NULL)
657 key_param->next = nparam;
660 sk_OPENSSL_STRING_push(key_param->param, opt_arg());
663 if (!opt_verify(o, vpm))
672 if (!opt_provider(o))
676 conf = app_load_config_modules(opt_arg());
681 # ifndef OPENSSL_NO_DES
682 wrap_cipher = EVP_des_ede3_wrap();
685 case OPT_AES128_WRAP:
686 wrap_cipher = EVP_aes_128_wrap();
688 case OPT_AES192_WRAP:
689 wrap_cipher = EVP_aes_192_wrap();
691 case OPT_AES256_WRAP:
692 wrap_cipher = EVP_aes_256_wrap();
695 if (!opt_cipher(opt_unknown(), &wrap_cipher))
700 if (!app_RAND_load())
703 if (digestname != NULL) {
704 if (!opt_md(digestname, &sign_md))
707 if (ciphername != NULL) {
708 if (!opt_cipher(ciphername, &cipher))
712 /* Remaining args are files to process. */
713 argc = opt_num_rest();
716 if ((rr_allorfirst != -1 || rr_from != NULL) && rr_to == NULL) {
717 BIO_puts(bio_err, "No Signed Receipts Recipients\n");
721 if (!(operation & SMIME_SIGNERS) && (rr_to != NULL || rr_from != NULL)) {
722 BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
725 if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) {
726 BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
730 if ((flags & CMS_CADES) != 0) {
731 if ((flags & CMS_NOATTR) != 0) {
732 BIO_puts(bio_err, "Incompatible options: "
733 "CAdES requires signed attributes\n");
736 if (operation == SMIME_VERIFY
737 && (flags & (CMS_NO_SIGNER_CERT_VERIFY | CMS_NO_ATTR_VERIFY)) != 0) {
738 BIO_puts(bio_err, "Incompatible options: CAdES validation requires"
739 " certs and signed attributes validations\n");
744 if (operation & SMIME_SIGNERS) {
745 if (keyfile != NULL && signerfile == NULL) {
746 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
749 /* Check to see if any final signer needs to be appended */
750 if (signerfile != NULL) {
751 if (sksigners == NULL
752 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
754 sk_OPENSSL_STRING_push(sksigners, signerfile);
755 if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
758 keyfile = signerfile;
759 sk_OPENSSL_STRING_push(skkeys, keyfile);
761 if (sksigners == NULL) {
762 BIO_printf(bio_err, "No signer certificate specified\n");
767 } else if (operation == SMIME_DECRYPT) {
768 if (recipfile == NULL && keyfile == NULL
769 && secret_key == NULL && pwri_pass == NULL) {
771 "No recipient certificate or key specified\n");
774 } else if (operation == SMIME_ENCRYPT) {
775 if (*argv == NULL && secret_key == NULL
776 && pwri_pass == NULL && encerts == NULL) {
777 BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
780 } else if (!operation) {
781 BIO_printf(bio_err, "No operation option (-encrypt|-decrypt|-sign|-verify|...) specified.\n");
785 if (!app_passwd(passinarg, NULL, &passin, NULL)) {
786 BIO_printf(bio_err, "Error getting password\n");
792 if (!(operation & SMIME_SIGNERS))
793 flags &= ~CMS_DETACHED;
795 if (!(operation & SMIME_OP))
796 if (flags & CMS_BINARY)
797 outformat = FORMAT_BINARY;
799 if (!(operation & SMIME_IP))
800 if (flags & CMS_BINARY)
801 informat = FORMAT_BINARY;
803 if (operation == SMIME_ENCRYPT) {
805 # ifndef OPENSSL_NO_DES
806 cipher = EVP_des_ede3_cbc();
808 BIO_printf(bio_err, "No cipher selected\n");
813 if (secret_key && !secret_keyid) {
814 BIO_printf(bio_err, "No secret key id\n");
818 if (*argv && encerts == NULL)
819 if ((encerts = sk_X509_new_null()) == NULL)
822 if ((cert = load_cert(*argv, "recipient certificate file")) == NULL)
824 sk_X509_push(encerts, cert);
830 if (certfile != NULL) {
831 if (!load_certs(certfile, 0, &other, NULL, "certificate file")) {
832 ERR_print_errors(bio_err);
837 if (recipfile != NULL && (operation == SMIME_DECRYPT)) {
838 if ((recip = load_cert(recipfile,
839 "recipient certificate file")) == NULL) {
840 ERR_print_errors(bio_err);
845 if (originatorfile != NULL) {
846 if ((originator = load_cert(originatorfile,
847 "originator certificate file")) == NULL) {
848 ERR_print_errors(bio_err);
853 if (operation == SMIME_SIGN_RECEIPT) {
854 if ((signer = load_cert(signerfile,
855 "receipt signer certificate file")) == NULL) {
856 ERR_print_errors(bio_err);
861 if ((operation == SMIME_DECRYPT) || (operation == SMIME_ENCRYPT)) {
864 } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
866 keyfile = signerfile;
871 if (keyfile != NULL) {
872 key = load_key(keyfile, keyform, 0, passin, e, "signing key");
877 in = bio_open_default(infile, 'r', informat);
881 if (operation & SMIME_IP) {
882 cms = load_content_info(informat, in, &indata, "SMIME", libctx, app_get0_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_ex(in, flags, libctx, app_get0_propq());
935 } else if (operation == SMIME_DIGEST_CREATE) {
936 cms = CMS_digest_create_ex(in, sign_md, flags, libctx, app_get0_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_ex(NULL, in, cipher, flags, libctx, app_get0_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_ex(in, cipher, secret_key,
1008 secret_keylen, flags, libctx, app_get0_propq());
1010 } else if (operation == SMIME_SIGN_RECEIPT) {
1011 CMS_ContentInfo *srcms = NULL;
1012 STACK_OF(CMS_SignerInfo) *sis;
1014 sis = CMS_get0_SignerInfos(cms);
1017 si = sk_CMS_SignerInfo_value(sis, 0);
1018 srcms = CMS_sign_receipt(si, signer, key, other, flags);
1021 CMS_ContentInfo_free(cms);
1023 } else if (operation & SMIME_SIGNERS) {
1026 * If detached data content we enable streaming if S/MIME output
1029 if (operation == SMIME_SIGN) {
1031 if (flags & CMS_DETACHED) {
1032 if (outformat == FORMAT_SMIME)
1033 flags |= CMS_STREAM;
1035 flags |= CMS_PARTIAL;
1036 cms = CMS_sign_ex(NULL, NULL, other, in, flags, libctx, app_get0_propq());
1039 if (econtent_type != NULL)
1040 CMS_set1_eContentType(cms, econtent_type);
1042 if (rr_to != NULL) {
1043 rr = make_receipt_request(rr_to, rr_allorfirst, rr_from, libctx);
1046 "Signed Receipt Request Creation Error\n");
1051 flags |= CMS_REUSE_DIGEST;
1053 for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
1055 cms_key_param *kparam;
1057 signerfile = sk_OPENSSL_STRING_value(sksigners, i);
1058 keyfile = sk_OPENSSL_STRING_value(skkeys, i);
1060 signer = load_cert(signerfile, "signer certificate");
1061 if (signer == NULL) {
1065 key = load_key(keyfile, keyform, 0, passin, e, "signing key");
1071 for (kparam = key_first; kparam; kparam = kparam->next) {
1072 if (kparam->idx == i) {
1073 tflags |= CMS_KEY_PARAM;
1077 si = CMS_add1_signer(cms, signer, key, sign_md, tflags);
1080 if (kparam != NULL) {
1082 pctx = CMS_SignerInfo_get0_pkey_ctx(si);
1083 if (!cms_set_pkey_param(pctx, kparam->param))
1086 if (rr != NULL && !CMS_add1_ReceiptRequest(si, rr))
1093 /* If not streaming or resigning finalize structure */
1094 if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
1095 if (!CMS_final(cms, in, NULL, flags))
1101 BIO_printf(bio_err, "Error creating CMS structure\n");
1106 if (operation == SMIME_DECRYPT) {
1107 if (flags & CMS_DEBUG_DECRYPT)
1108 CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);
1110 if (secret_key != NULL) {
1111 if (!CMS_decrypt_set1_key(cms,
1112 secret_key, secret_keylen,
1113 secret_keyid, secret_keyidlen)) {
1114 BIO_puts(bio_err, "Error decrypting CMS using secret key\n");
1120 if (!CMS_decrypt_set1_pkey_and_peer(cms, key, recip, originator)) {
1121 BIO_puts(bio_err, "Error decrypting CMS using private key\n");
1126 if (pwri_pass != NULL) {
1127 if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
1128 BIO_puts(bio_err, "Error decrypting CMS using password\n");
1133 if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
1134 BIO_printf(bio_err, "Error decrypting CMS structure\n");
1137 } else if (operation == SMIME_DATAOUT) {
1138 if (!CMS_data(cms, out, flags))
1140 } else if (operation == SMIME_UNCOMPRESS) {
1141 if (!CMS_uncompress(cms, indata, out, flags))
1143 } else if (operation == SMIME_DIGEST_VERIFY) {
1144 if (CMS_digest_verify(cms, indata, out, flags) > 0) {
1145 BIO_printf(bio_err, "Verification successful\n");
1147 BIO_printf(bio_err, "Verification failure\n");
1150 } else if (operation == SMIME_ENCRYPTED_DECRYPT) {
1151 if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
1152 indata, out, flags))
1154 } else if (operation == SMIME_VERIFY) {
1155 if (CMS_verify(cms, other, store, indata, out, flags) > 0) {
1156 BIO_printf(bio_err, "%s Verification successful\n",
1157 (flags & CMS_CADES) ? "CAdES" : "CMS");
1159 BIO_printf(bio_err, "Verification failure\n");
1161 ret = verify_err + 32;
1164 if (signerfile != NULL) {
1165 STACK_OF(X509) *signers;
1166 signers = CMS_get0_signers(cms);
1167 if (!save_certs(signerfile, signers)) {
1169 "Error writing signers to %s\n", signerfile);
1173 sk_X509_free(signers);
1176 receipt_request_print(cms);
1178 } else if (operation == SMIME_VERIFY_RECEIPT) {
1179 if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) {
1180 BIO_printf(bio_err, "Verification successful\n");
1182 BIO_printf(bio_err, "Verification failure\n");
1188 ASN1_PCTX *pctx = NULL;
1189 if (get_nameopt() != XN_FLAG_ONELINE) {
1190 pctx = ASN1_PCTX_new();
1191 if (pctx != NULL) { /* Print anyway if malloc failed */
1192 ASN1_PCTX_set_flags(pctx, ASN1_PCTX_FLAGS_SHOW_ABSENT);
1193 ASN1_PCTX_set_str_flags(pctx, get_nameopt());
1194 ASN1_PCTX_set_nm_flags(pctx, get_nameopt());
1197 CMS_ContentInfo_print_ctx(out, cms, 0, pctx);
1198 ASN1_PCTX_free(pctx);
1200 } else if (outformat == FORMAT_SMIME) {
1202 BIO_printf(out, "To: %s%s", to, mime_eol);
1204 BIO_printf(out, "From: %s%s", from, mime_eol);
1206 BIO_printf(out, "Subject: %s%s", subject, mime_eol);
1207 if (operation == SMIME_RESIGN)
1208 ret = SMIME_write_CMS(out, cms, indata, flags);
1210 ret = SMIME_write_CMS(out, cms, in, flags);
1211 } else if (outformat == FORMAT_PEM) {
1212 ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
1213 } else if (outformat == FORMAT_ASN1) {
1214 ret = i2d_CMS_bio_stream(out, cms, in, flags);
1216 BIO_printf(bio_err, "Bad output format for CMS file\n");
1227 ERR_print_errors(bio_err);
1228 sk_X509_pop_free(encerts, X509_free);
1229 sk_X509_pop_free(other, X509_free);
1230 X509_VERIFY_PARAM_free(vpm);
1231 sk_OPENSSL_STRING_free(sksigners);
1232 sk_OPENSSL_STRING_free(skkeys);
1233 OPENSSL_free(secret_key);
1234 OPENSSL_free(secret_keyid);
1235 OPENSSL_free(pwri_tmp);
1236 ASN1_OBJECT_free(econtent_type);
1237 CMS_ReceiptRequest_free(rr);
1238 sk_OPENSSL_STRING_free(rr_to);
1239 sk_OPENSSL_STRING_free(rr_from);
1240 for (key_param = key_first; key_param;) {
1241 cms_key_param *tparam;
1242 sk_OPENSSL_STRING_free(key_param->param);
1243 tparam = key_param->next;
1244 OPENSSL_free(key_param);
1247 X509_STORE_free(store);
1252 CMS_ContentInfo_free(cms);
1253 CMS_ContentInfo_free(rcms);
1259 OPENSSL_free(passin);
1264 static int save_certs(char *signerfile, STACK_OF(X509) *signers)
1268 if (signerfile == NULL)
1270 tmp = BIO_new_file(signerfile, "w");
1273 for (i = 0; i < sk_X509_num(signers); i++)
1274 PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
1279 /* Minimal callback just to output policy info (if any) */
1281 static int cms_cb(int ok, X509_STORE_CTX *ctx)
1285 error = X509_STORE_CTX_get_error(ctx);
1289 if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
1290 && ((error != X509_V_OK) || (ok != 2)))
1293 policies_print(ctx);
1299 static void gnames_stack_print(STACK_OF(GENERAL_NAMES) *gns)
1301 STACK_OF(GENERAL_NAME) *gens;
1305 for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) {
1306 gens = sk_GENERAL_NAMES_value(gns, i);
1307 for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) {
1308 gen = sk_GENERAL_NAME_value(gens, j);
1309 BIO_puts(bio_err, " ");
1310 GENERAL_NAME_print(bio_err, gen);
1311 BIO_puts(bio_err, "\n");
1317 static void receipt_request_print(CMS_ContentInfo *cms)
1319 STACK_OF(CMS_SignerInfo) *sis;
1321 CMS_ReceiptRequest *rr;
1323 STACK_OF(GENERAL_NAMES) *rto, *rlist;
1326 sis = CMS_get0_SignerInfos(cms);
1327 for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) {
1328 si = sk_CMS_SignerInfo_value(sis, i);
1329 rv = CMS_get1_ReceiptRequest(si, &rr);
1330 BIO_printf(bio_err, "Signer %d:\n", i + 1);
1332 BIO_puts(bio_err, " No Receipt Request\n");
1333 } else if (rv < 0) {
1334 BIO_puts(bio_err, " Receipt Request Parse Error\n");
1335 ERR_print_errors(bio_err);
1339 CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst,
1341 BIO_puts(bio_err, " Signed Content ID:\n");
1342 idlen = ASN1_STRING_length(scid);
1343 id = (const char *)ASN1_STRING_get0_data(scid);
1344 BIO_dump_indent(bio_err, id, idlen, 4);
1345 BIO_puts(bio_err, " Receipts From");
1346 if (rlist != NULL) {
1347 BIO_puts(bio_err, " List:\n");
1348 gnames_stack_print(rlist);
1349 } else if (allorfirst == 1) {
1350 BIO_puts(bio_err, ": First Tier\n");
1351 } else if (allorfirst == 0) {
1352 BIO_puts(bio_err, ": All\n");
1354 BIO_printf(bio_err, " Unknown (%d)\n", allorfirst);
1356 BIO_puts(bio_err, " Receipts To:\n");
1357 gnames_stack_print(rto);
1359 CMS_ReceiptRequest_free(rr);
1363 static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns)
1366 STACK_OF(GENERAL_NAMES) *ret;
1367 GENERAL_NAMES *gens = NULL;
1368 GENERAL_NAME *gen = NULL;
1369 ret = sk_GENERAL_NAMES_new_null();
1372 for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) {
1373 char *str = sk_OPENSSL_STRING_value(ns, i);
1374 gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0);
1377 gens = GENERAL_NAMES_new();
1380 if (!sk_GENERAL_NAME_push(gens, gen))
1383 if (!sk_GENERAL_NAMES_push(ret, gens))
1391 sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free);
1392 GENERAL_NAMES_free(gens);
1393 GENERAL_NAME_free(gen);
1397 static CMS_ReceiptRequest *make_receipt_request(
1398 STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst,
1399 STACK_OF(OPENSSL_STRING) *rr_from,
1400 OSSL_LIB_CTX *libctx)
1402 STACK_OF(GENERAL_NAMES) *rct_to = NULL, *rct_from = NULL;
1403 CMS_ReceiptRequest *rr;
1404 rct_to = make_names_stack(rr_to);
1407 if (rr_from != NULL) {
1408 rct_from = make_names_stack(rr_from);
1409 if (rct_from == NULL)
1414 rr = CMS_ReceiptRequest_create0_ex(NULL, -1, rr_allorfirst, rct_from,
1415 rct_to, libctx, app_get0_propq());
1418 sk_GENERAL_NAMES_pop_free(rct_to, GENERAL_NAMES_free);
1422 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
1423 STACK_OF(OPENSSL_STRING) *param)
1427 if (sk_OPENSSL_STRING_num(param) <= 0)
1429 for (i = 0; i < sk_OPENSSL_STRING_num(param); i++) {
1430 keyopt = sk_OPENSSL_STRING_value(param, i);
1431 if (pkey_ctrl_string(pctx, keyopt) <= 0) {
1432 BIO_printf(bio_err, "parameter error \"%s\"\n", keyopt);
1433 ERR_print_errors(bio_err);