2 * Copyright 2008-2019 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 /* CMS utility function */
17 #ifndef OPENSSL_NO_CMS
19 # include <openssl/crypto.h>
20 # include <openssl/pem.h>
21 # include <openssl/err.h>
22 # include <openssl/x509_vfy.h>
23 # include <openssl/x509v3.h>
24 # include <openssl/cms.h>
26 static int save_certs(char *signerfile, STACK_OF(X509) *signers);
27 static int cms_cb(int ok, X509_STORE_CTX *ctx);
28 static void receipt_request_print(CMS_ContentInfo *cms);
29 static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING)
30 *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING)
32 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
33 STACK_OF(OPENSSL_STRING) *param);
35 # define SMIME_OP 0x10
36 # define SMIME_IP 0x20
37 # define SMIME_SIGNERS 0x40
38 # define SMIME_ENCRYPT (1 | SMIME_OP)
39 # define SMIME_DECRYPT (2 | SMIME_IP)
40 # define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS)
41 # define SMIME_VERIFY (4 | SMIME_IP)
42 # define SMIME_CMSOUT (5 | SMIME_IP | SMIME_OP)
43 # define SMIME_RESIGN (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
44 # define SMIME_DATAOUT (7 | SMIME_IP)
45 # define SMIME_DATA_CREATE (8 | SMIME_OP)
46 # define SMIME_DIGEST_VERIFY (9 | SMIME_IP)
47 # define SMIME_DIGEST_CREATE (10 | SMIME_OP)
48 # define SMIME_UNCOMPRESS (11 | SMIME_IP)
49 # define SMIME_COMPRESS (12 | SMIME_OP)
50 # define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP)
51 # define SMIME_ENCRYPTED_ENCRYPT (14 | SMIME_OP)
52 # define SMIME_SIGN_RECEIPT (15 | SMIME_IP | SMIME_OP)
53 # define SMIME_VERIFY_RECEIPT (16 | SMIME_IP)
55 static int verify_err = 0;
57 typedef struct cms_key_param_st cms_key_param;
59 struct cms_key_param_st {
61 STACK_OF(OPENSSL_STRING) *param;
65 typedef enum OPTION_choice {
66 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
67 OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENCRYPT,
68 OPT_DECRYPT, OPT_SIGN, OPT_CADES, OPT_SIGN_RECEIPT, OPT_RESIGN,
69 OPT_VERIFY, OPT_VERIFY_RETCODE, OPT_VERIFY_RECEIPT,
70 OPT_CMSOUT, OPT_DATA_OUT, OPT_DATA_CREATE, OPT_DIGEST_VERIFY,
71 OPT_DIGEST_CREATE, OPT_COMPRESS, OPT_UNCOMPRESS,
72 OPT_ED_DECRYPT, OPT_ED_ENCRYPT, OPT_DEBUG_DECRYPT, OPT_TEXT,
73 OPT_ASCIICRLF, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCERTS,
74 OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP, OPT_BINARY, OPT_KEYID,
75 OPT_NOSIGS, OPT_NO_CONTENT_VERIFY, OPT_NO_ATTR_VERIFY, OPT_INDEF,
76 OPT_NOINDEF, OPT_CRLFEOL, OPT_NOOUT, OPT_RR_PRINT,
77 OPT_RR_ALL, OPT_RR_FIRST, OPT_RCTFORM, OPT_CERTFILE, OPT_CAFILE,
78 OPT_CAPATH, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE,
79 OPT_CONTENT, OPT_PRINT,
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,
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"},
122 OPT_SECTION("Action"),
123 {"encrypt", OPT_ENCRYPT, '-', "Encrypt message"},
124 {"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"},
125 {"sign", OPT_SIGN, '-', "Sign message"},
126 {"sign_receipt", OPT_SIGN_RECEIPT, '-', "Generate a signed receipt for the message"},
127 {"resign", OPT_RESIGN, '-', "Resign a signed message"},
128 {"cades", OPT_CADES, '-', "Include signer certificate digest"},
129 {"verify", OPT_VERIFY, '-', "Verify signed message"},
130 {"verify_retcode", OPT_VERIFY_RETCODE, '-',
131 "Exit non-zero on verification failure"},
132 {"verify_receipt", OPT_VERIFY_RECEIPT, '<',
133 "Verify receipts; exit if receipt signatures do not verify"},
134 {"digest_verify", OPT_DIGEST_VERIFY, '-',
135 "Verify a CMS \"DigestedData\" object and output it"},
136 {"digest_create", OPT_DIGEST_CREATE, '-',
137 "Create a CMS \"DigestedData\" object"},
138 {"compress", OPT_COMPRESS, '-', "Create a CMS \"CompressedData\" object"},
139 {"uncompress", OPT_UNCOMPRESS, '-',
140 "Uncompress a CMS \"CompressedData\" object"},
141 {"EncryptedData_decrypt", OPT_ED_DECRYPT, '-',
142 "Decrypt CMS \"EncryptedData\" object using symmetric key"},
143 {"EncryptedData_encrypt", OPT_ED_ENCRYPT, '-',
144 "Create CMS \"EncryptedData\" object using symmetric key"},
145 {"data_out", OPT_DATA_OUT, '-', "Copy CMS \"Data\" object to output"},
146 {"data_create", OPT_DATA_CREATE, '-', "Create a CMS \"Data\" object"},
147 {"cmsout", OPT_CMSOUT, '-', "Output CMS structure"},
148 {"no_content_verify", OPT_NO_CONTENT_VERIFY, '-',
149 "Do not verify signed content signatures"},
150 {"no_attr_verify", OPT_NO_ATTR_VERIFY, '-',
151 "Do not verify signed attribute signatures"},
152 {"nointern", OPT_NOINTERN, '-',
153 "Don't search certificates in message for signer"},
154 {"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"},
156 OPT_SECTION("Formatting"),
157 {"text", OPT_TEXT, '-', "Include or delete text MIME headers"},
158 {"asciicrlf", OPT_ASCIICRLF, '-',
159 "Perform CRLF canonicalisation when signing"},
160 {"nodetach", OPT_NODETACH, '-', "Use opaque signing"},
161 {"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"},
162 {"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"},
163 {"binary", OPT_BINARY, '-', "Don't translate message to text"},
164 {"keyid", OPT_KEYID, '-', "Use subject key identifier"},
165 {"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"},
166 {"nocerts", OPT_NOCERTS, '-',
167 "Don't include signers certificate when signing"},
168 {"noout", OPT_NOOUT, '-',
169 "For the -cmsout operation do not output the parsed CMS structure"},
170 {"receipt_request_print", OPT_RR_PRINT, '-', "Print CMS Receipt Request" },
171 {"receipt_request_all", OPT_RR_ALL, '-',
172 "When signing, create a receipt request for all recipients"},
173 {"receipt_request_first", OPT_RR_FIRST, '-',
174 "When signing, create a receipt request for first recipient"},
175 {"rctform", OPT_RCTFORM, 'F', "Receipt file format"},
176 {"certfile", OPT_CERTFILE, '<', "Other certificates file"},
177 {"content", OPT_CONTENT, '<',
178 "Supply or override content for detached signature"},
179 {"print", OPT_PRINT, '-',
180 "For the -cmsout operation print out all fields of the CMS structure"},
181 {"certsout", OPT_CERTSOUT, '>', "Certificate output file"},
183 OPT_SECTION("Keying"),
184 {"secretkey", OPT_SECRETKEY, 's',
185 "Use specified hex-encoded key to decrypt/encrypt recipients or content"},
186 {"secretkeyid", OPT_SECRETKEYID, 's',
187 "Identity of the -secretkey for CMS \"KEKRecipientInfo\" object"},
188 {"pwri_password", OPT_PWRI_PASSWORD, 's',
189 "Specific password for recipient"},
190 {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
191 {"inkey", OPT_INKEY, 's',
192 "Input private key (if not signer or recipient)"},
193 {"keyform", OPT_KEYFORM, 'f', "Input private key format (PEM or ENGINE)"},
194 {"keyopt", OPT_KEYOPT, 's', "Set public key parameters as n:v pairs"},
196 OPT_SECTION("Mail header"),
197 {"econtent_type", OPT_ECONTENT_TYPE, 's', "OID for external content"},
198 {"to", OPT_TO, 's', "To address"},
199 {"from", OPT_FROM, 's', "From address"},
200 {"subject", OPT_SUBJECT, 's', "Subject"},
201 {"signer", OPT_SIGNER, 's', "Signer certificate file"},
202 {"originator", OPT_ORIGINATOR, 's', "Originator certificate file"},
203 {"recip", OPT_RECIP, '<', "Recipient cert file for decryption"},
204 {"receipt_request_from", OPT_RR_FROM, 's',
205 "Create signed receipt request with specified email address"},
206 {"receipt_request_to", OPT_RR_TO, 's',
207 "Create signed receipt targeted to specified address"},
209 OPT_SECTION("Encryption"),
210 {"md", OPT_MD, 's', "Digest algorithm to use when signing or resigning"},
211 {"", OPT_CIPHER, '-', "Any supported cipher"},
213 OPT_SECTION("Key-wrapping"),
214 {"aes128-wrap", OPT_AES128_WRAP, '-', "Use AES128 to wrap key"},
215 {"aes192-wrap", OPT_AES192_WRAP, '-', "Use AES192 to wrap key"},
216 {"aes256-wrap", OPT_AES256_WRAP, '-', "Use AES256 to wrap key"},
217 # ifndef OPENSSL_NO_DES
218 {"des3-wrap", OPT_3DES_WRAP, '-', "Use 3DES-EDE to wrap key"},
220 {"wrap", OPT_WRAP, 's', "Any wrap cipher to wrap key"},
227 {"cert", 0, 0, "Recipient certs (optional; used only when encrypting)"},
231 int cms_main(int argc, char **argv)
233 ASN1_OBJECT *econtent_type = NULL;
234 BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
235 CMS_ContentInfo *cms = NULL, *rcms = NULL;
236 CMS_ReceiptRequest *rr = NULL;
238 EVP_PKEY *key = NULL;
239 const EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
240 const EVP_MD *sign_md = NULL;
241 STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
242 STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
243 STACK_OF(X509) *encerts = NULL, *other = NULL;
244 X509 *cert = NULL, *recip = NULL, *signer = NULL, *originator = NULL;
245 X509_STORE *store = NULL;
246 X509_VERIFY_PARAM *vpm = NULL;
247 char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
248 const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
249 char *certsoutfile = NULL;
250 int noCAfile = 0, noCApath = 0, noCAstore = 0;
251 char *infile = NULL, *outfile = NULL, *rctfile = NULL;
252 char *passinarg = NULL, *passin = NULL, *signerfile = NULL, *originatorfile = NULL, *recipfile = NULL;
253 char *to = NULL, *from = NULL, *subject = NULL, *prog;
254 cms_key_param *key_first = NULL, *key_param = NULL;
255 int flags = CMS_DETACHED, noout = 0, print = 0, keyidx = -1, vpmtouched = 0;
256 int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
257 int operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1;
258 int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_PEM;
259 size_t secret_keylen = 0, secret_keyidlen = 0;
260 unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
261 unsigned char *secret_key = NULL, *secret_keyid = NULL;
263 const char *mime_eol = "\n";
266 if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
269 prog = opt_init(argc, argv, cms_options);
270 while ((o = opt_next()) != OPT_EOF) {
275 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
278 opt_help(cms_options);
282 if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
286 if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
293 operation = SMIME_ENCRYPT;
296 operation = SMIME_DECRYPT;
299 operation = SMIME_SIGN;
301 case OPT_SIGN_RECEIPT:
302 operation = SMIME_SIGN_RECEIPT;
305 operation = SMIME_RESIGN;
308 operation = SMIME_VERIFY;
310 case OPT_VERIFY_RETCODE:
313 case OPT_VERIFY_RECEIPT:
314 operation = SMIME_VERIFY_RECEIPT;
318 operation = SMIME_CMSOUT;
321 operation = SMIME_DATAOUT;
323 case OPT_DATA_CREATE:
324 operation = SMIME_DATA_CREATE;
326 case OPT_DIGEST_VERIFY:
327 operation = SMIME_DIGEST_VERIFY;
329 case OPT_DIGEST_CREATE:
330 operation = SMIME_DIGEST_CREATE;
333 operation = SMIME_COMPRESS;
336 operation = SMIME_UNCOMPRESS;
339 operation = SMIME_ENCRYPTED_DECRYPT;
342 operation = SMIME_ENCRYPTED_ENCRYPT;
344 case OPT_DEBUG_DECRYPT:
345 flags |= CMS_DEBUG_DECRYPT;
351 flags |= CMS_ASCIICRLF;
354 flags |= CMS_NOINTERN;
357 flags |= CMS_NO_SIGNER_CERT_VERIFY;
360 flags |= CMS_NOCERTS;
366 flags &= ~CMS_DETACHED;
369 flags |= CMS_NOSMIMECAP;
378 flags |= CMS_USE_KEYID;
383 case OPT_NO_CONTENT_VERIFY:
384 flags |= CMS_NO_CONTENT_VERIFY;
386 case OPT_NO_ATTR_VERIFY:
387 flags |= CMS_NO_ATTR_VERIFY;
393 flags &= ~CMS_STREAM;
397 flags |= CMS_CRLFEOL;
412 if (rctformat == FORMAT_SMIME)
413 rcms = SMIME_read_CMS(rctin, NULL);
414 else if (rctformat == FORMAT_PEM)
415 rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL);
416 else if (rctformat == FORMAT_ASN1)
417 if (!opt_format(opt_arg(),
418 OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat))
422 certfile = opt_arg();
446 contfile = opt_arg();
450 && (rr_from = sk_OPENSSL_STRING_new_null()) == NULL)
452 sk_OPENSSL_STRING_push(rr_from, opt_arg());
456 && (rr_to = sk_OPENSSL_STRING_new_null()) == NULL)
458 sk_OPENSSL_STRING_push(rr_to, opt_arg());
464 if (secret_key != NULL) {
465 BIO_printf(bio_err, "Invalid key (supplied twice) %s\n",
469 secret_key = OPENSSL_hexstr2buf(opt_arg(), <mp);
470 if (secret_key == NULL) {
471 BIO_printf(bio_err, "Invalid key %s\n", opt_arg());
474 secret_keylen = (size_t)ltmp;
476 case OPT_SECRETKEYID:
477 if (secret_keyid != NULL) {
478 BIO_printf(bio_err, "Invalid id (supplied twice) %s\n",
482 secret_keyid = OPENSSL_hexstr2buf(opt_arg(), <mp);
483 if (secret_keyid == NULL) {
484 BIO_printf(bio_err, "Invalid id %s\n", opt_arg());
487 secret_keyidlen = (size_t)ltmp;
489 case OPT_PWRI_PASSWORD:
490 pwri_pass = (unsigned char *)opt_arg();
492 case OPT_ECONTENT_TYPE:
493 if (econtent_type != NULL) {
494 BIO_printf(bio_err, "Invalid OID (supplied twice) %s\n",
498 econtent_type = OBJ_txt2obj(opt_arg(), 0);
499 if (econtent_type == NULL) {
500 BIO_printf(bio_err, "Invalid OID %s\n", opt_arg());
505 e = setup_engine(opt_arg(), 0);
508 passinarg = opt_arg();
520 certsoutfile = opt_arg();
523 if (!opt_md(opt_arg(), &sign_md))
527 /* If previous -signer argument add signer to list */
528 if (signerfile != NULL) {
529 if (sksigners == NULL
530 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
532 sk_OPENSSL_STRING_push(sksigners, signerfile);
534 keyfile = signerfile;
536 && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
538 sk_OPENSSL_STRING_push(skkeys, keyfile);
541 signerfile = opt_arg();
544 originatorfile = opt_arg();
547 /* If previous -inkey argument add signer to list */
548 if (keyfile != NULL) {
549 if (signerfile == NULL) {
550 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
553 if (sksigners == NULL
554 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
556 sk_OPENSSL_STRING_push(sksigners, signerfile);
559 && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
561 sk_OPENSSL_STRING_push(skkeys, keyfile);
566 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
570 if (operation == SMIME_ENCRYPT) {
571 if (encerts == NULL && (encerts = sk_X509_new_null()) == NULL)
573 cert = load_cert(opt_arg(), FORMAT_PEM,
574 "recipient certificate file");
577 sk_X509_push(encerts, cert);
580 recipfile = opt_arg();
584 if (!opt_cipher(opt_unknown(), &cipher))
589 if (operation == SMIME_ENCRYPT) {
591 keyidx += sk_X509_num(encerts);
593 if (keyfile != NULL || signerfile != NULL)
596 keyidx += sk_OPENSSL_STRING_num(skkeys);
599 BIO_printf(bio_err, "No key specified\n");
602 if (key_param == NULL || key_param->idx != keyidx) {
603 cms_key_param *nparam;
604 nparam = app_malloc(sizeof(*nparam), "key param buffer");
605 nparam->idx = keyidx;
606 if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL)
609 if (key_first == NULL)
612 key_param->next = nparam;
615 sk_OPENSSL_STRING_push(key_param->param, opt_arg());
618 if (!opt_verify(o, vpm))
627 if (!opt_provider(o))
631 # ifndef OPENSSL_NO_DES
632 wrap_cipher = EVP_des_ede3_wrap();
635 case OPT_AES128_WRAP:
636 wrap_cipher = EVP_aes_128_wrap();
638 case OPT_AES192_WRAP:
639 wrap_cipher = EVP_aes_192_wrap();
641 case OPT_AES256_WRAP:
642 wrap_cipher = EVP_aes_256_wrap();
645 if (!opt_cipher(opt_unknown(), &wrap_cipher))
650 argc = opt_num_rest();
653 if ((rr_allorfirst != -1 || rr_from != NULL) && rr_to == NULL) {
654 BIO_puts(bio_err, "No Signed Receipts Recipients\n");
658 if (!(operation & SMIME_SIGNERS) && (rr_to != NULL || rr_from != NULL)) {
659 BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
662 if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) {
663 BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
667 if (flags & CMS_CADES) {
668 if (flags & CMS_NOATTR) {
669 BIO_puts(bio_err, "Incompatible options: "
670 "CAdES required signed attributes\n");
675 if (operation & SMIME_SIGNERS) {
676 if (keyfile != NULL && signerfile == NULL) {
677 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
680 /* Check to see if any final signer needs to be appended */
681 if (signerfile != NULL) {
682 if (sksigners == NULL
683 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
685 sk_OPENSSL_STRING_push(sksigners, signerfile);
686 if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
689 keyfile = signerfile;
690 sk_OPENSSL_STRING_push(skkeys, keyfile);
692 if (sksigners == NULL) {
693 BIO_printf(bio_err, "No signer certificate specified\n");
698 } else if (operation == SMIME_DECRYPT) {
699 if (recipfile == NULL && keyfile == NULL
700 && secret_key == NULL && pwri_pass == NULL) {
702 "No recipient certificate or key specified\n");
705 } else if (operation == SMIME_ENCRYPT) {
706 if (*argv == NULL && secret_key == NULL
707 && pwri_pass == NULL && encerts == NULL) {
708 BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
711 } else if (!operation) {
712 BIO_printf(bio_err, "No operation option (-encrypt|-decrypt|-sign|-verify|...) specified.\n");
716 if (!app_passwd(passinarg, NULL, &passin, NULL)) {
717 BIO_printf(bio_err, "Error getting password\n");
723 if (!(operation & SMIME_SIGNERS))
724 flags &= ~CMS_DETACHED;
726 if (!(operation & SMIME_OP))
727 if (flags & CMS_BINARY)
728 outformat = FORMAT_BINARY;
730 if (!(operation & SMIME_IP))
731 if (flags & CMS_BINARY)
732 informat = FORMAT_BINARY;
734 if (operation == SMIME_ENCRYPT) {
736 # ifndef OPENSSL_NO_DES
737 cipher = EVP_des_ede3_cbc();
739 BIO_printf(bio_err, "No cipher selected\n");
744 if (secret_key && !secret_keyid) {
745 BIO_printf(bio_err, "No secret key id\n");
749 if (*argv && encerts == NULL)
750 if ((encerts = sk_X509_new_null()) == NULL)
753 if ((cert = load_cert(*argv, FORMAT_PEM,
754 "recipient certificate file")) == NULL)
756 sk_X509_push(encerts, cert);
762 if (certfile != NULL) {
763 if (!load_certs(certfile, &other, FORMAT_PEM, NULL,
764 "certificate file")) {
765 ERR_print_errors(bio_err);
770 if (recipfile != NULL && (operation == SMIME_DECRYPT)) {
771 if ((recip = load_cert(recipfile, FORMAT_PEM,
772 "recipient certificate file")) == NULL) {
773 ERR_print_errors(bio_err);
778 if (originatorfile != NULL) {
779 if ((originator = load_cert(originatorfile, FORMAT_PEM,
780 "originator certificate file")) == NULL) {
781 ERR_print_errors(bio_err);
786 if (operation == SMIME_SIGN_RECEIPT) {
787 if ((signer = load_cert(signerfile, FORMAT_PEM,
788 "receipt signer certificate file")) == NULL) {
789 ERR_print_errors(bio_err);
794 if ((operation == SMIME_DECRYPT) || (operation == SMIME_ENCRYPT)) {
797 } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
799 keyfile = signerfile;
804 if (keyfile != NULL) {
805 key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
810 in = bio_open_default(infile, 'r', informat);
814 if (operation & SMIME_IP) {
815 if (informat == FORMAT_SMIME) {
816 cms = SMIME_read_CMS(in, &indata);
817 } else if (informat == FORMAT_PEM) {
818 cms = PEM_read_bio_CMS(in, NULL, NULL, NULL);
819 } else if (informat == FORMAT_ASN1) {
820 cms = d2i_CMS_bio(in, NULL);
822 BIO_printf(bio_err, "Bad input format for CMS file\n");
827 BIO_printf(bio_err, "Error reading S/MIME message\n");
830 if (contfile != NULL) {
832 if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
833 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
837 if (certsoutfile != NULL) {
838 STACK_OF(X509) *allcerts;
839 allcerts = CMS_get1_certs(cms);
840 if (!save_certs(certsoutfile, allcerts)) {
842 "Error writing certs to %s\n", certsoutfile);
846 sk_X509_pop_free(allcerts, X509_free);
850 if (rctfile != NULL) {
851 char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
852 if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) {
853 BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile);
857 if (rctformat == FORMAT_SMIME) {
858 rcms = SMIME_read_CMS(rctin, NULL);
859 } else if (rctformat == FORMAT_PEM) {
860 rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL);
861 } else if (rctformat == FORMAT_ASN1) {
862 rcms = d2i_CMS_bio(rctin, NULL);
864 BIO_printf(bio_err, "Bad input format for receipt\n");
869 BIO_printf(bio_err, "Error reading receipt\n");
874 out = bio_open_default(outfile, 'w', outformat);
878 if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) {
879 if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
880 CAstore, noCAstore)) == NULL)
882 X509_STORE_set_verify_cb(store, cms_cb);
884 X509_STORE_set1_param(store, vpm);
889 if (operation == SMIME_DATA_CREATE) {
890 cms = CMS_data_create(in, flags);
891 } else if (operation == SMIME_DIGEST_CREATE) {
892 cms = CMS_digest_create(in, sign_md, flags);
893 } else if (operation == SMIME_COMPRESS) {
894 cms = CMS_compress(in, -1, flags);
895 } else if (operation == SMIME_ENCRYPT) {
897 flags |= CMS_PARTIAL;
898 cms = CMS_encrypt(NULL, in, cipher, flags);
901 for (i = 0; i < sk_X509_num(encerts); i++) {
902 CMS_RecipientInfo *ri;
903 cms_key_param *kparam;
904 int tflags = flags | CMS_KEY_PARAM; /* This flag enforces allocating the EVP_PKEY_CTX for the recipient here */
906 X509 *x = sk_X509_value(encerts, i);
909 for (kparam = key_first; kparam; kparam = kparam->next) {
910 if (kparam->idx == i) {
914 ri = CMS_add1_recipient(cms, x, key, originator, tflags);
918 pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
919 if (kparam != NULL) {
920 if (!cms_set_pkey_param(pctx, kparam->param))
924 res = EVP_PKEY_CTX_ctrl(pctx, -1, -1,
925 EVP_PKEY_CTRL_CIPHER,
926 EVP_CIPHER_nid(cipher), NULL);
927 if (res <= 0 && res != -2)
930 if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE
932 EVP_CIPHER_CTX *wctx;
933 wctx = CMS_RecipientInfo_kari_get0_ctx(ri);
934 EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL);
938 if (secret_key != NULL) {
939 if (!CMS_add0_recipient_key(cms, NID_undef,
940 secret_key, secret_keylen,
941 secret_keyid, secret_keyidlen,
944 /* NULL these because call absorbs them */
948 if (pwri_pass != NULL) {
949 pwri_tmp = (unsigned char *)OPENSSL_strdup((char *)pwri_pass);
950 if (pwri_tmp == NULL)
952 if (CMS_add0_recipient_password(cms,
953 -1, NID_undef, NID_undef,
954 pwri_tmp, -1, NULL) == NULL)
958 if (!(flags & CMS_STREAM)) {
959 if (!CMS_final(cms, in, NULL, flags))
962 } else if (operation == SMIME_ENCRYPTED_ENCRYPT) {
963 cms = CMS_EncryptedData_encrypt(in, cipher,
964 secret_key, secret_keylen, flags);
966 } else if (operation == SMIME_SIGN_RECEIPT) {
967 CMS_ContentInfo *srcms = NULL;
968 STACK_OF(CMS_SignerInfo) *sis;
970 sis = CMS_get0_SignerInfos(cms);
973 si = sk_CMS_SignerInfo_value(sis, 0);
974 srcms = CMS_sign_receipt(si, signer, key, other, flags);
977 CMS_ContentInfo_free(cms);
979 } else if (operation & SMIME_SIGNERS) {
982 * If detached data content we enable streaming if S/MIME output
985 if (operation == SMIME_SIGN) {
987 if (flags & CMS_DETACHED) {
988 if (outformat == FORMAT_SMIME)
991 flags |= CMS_PARTIAL;
992 cms = CMS_sign(NULL, NULL, other, in, flags);
995 if (econtent_type != NULL)
996 CMS_set1_eContentType(cms, econtent_type);
999 rr = make_receipt_request(rr_to, rr_allorfirst, rr_from);
1002 "Signed Receipt Request Creation Error\n");
1007 flags |= CMS_REUSE_DIGEST;
1009 for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
1011 cms_key_param *kparam;
1013 signerfile = sk_OPENSSL_STRING_value(sksigners, i);
1014 keyfile = sk_OPENSSL_STRING_value(skkeys, i);
1016 signer = load_cert(signerfile, FORMAT_PEM, "signer certificate");
1017 if (signer == NULL) {
1021 key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
1026 for (kparam = key_first; kparam; kparam = kparam->next) {
1027 if (kparam->idx == i) {
1028 tflags |= CMS_KEY_PARAM;
1032 si = CMS_add1_signer(cms, signer, key, sign_md, tflags);
1035 if (kparam != NULL) {
1037 pctx = CMS_SignerInfo_get0_pkey_ctx(si);
1038 if (!cms_set_pkey_param(pctx, kparam->param))
1041 if (rr != NULL && !CMS_add1_ReceiptRequest(si, rr))
1048 /* If not streaming or resigning finalize structure */
1049 if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
1050 if (!CMS_final(cms, in, NULL, flags))
1056 BIO_printf(bio_err, "Error creating CMS structure\n");
1061 if (operation == SMIME_DECRYPT) {
1062 if (flags & CMS_DEBUG_DECRYPT)
1063 CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);
1065 if (secret_key != NULL) {
1066 if (!CMS_decrypt_set1_key(cms,
1067 secret_key, secret_keylen,
1068 secret_keyid, secret_keyidlen)) {
1069 BIO_puts(bio_err, "Error decrypting CMS using secret key\n");
1075 if (!CMS_decrypt_set1_pkey_and_peer(cms, key, recip, originator)) {
1076 BIO_puts(bio_err, "Error decrypting CMS using private key\n");
1081 if (pwri_pass != NULL) {
1082 if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
1083 BIO_puts(bio_err, "Error decrypting CMS using password\n");
1088 if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
1089 BIO_printf(bio_err, "Error decrypting CMS structure\n");
1092 } else if (operation == SMIME_DATAOUT) {
1093 if (!CMS_data(cms, out, flags))
1095 } else if (operation == SMIME_UNCOMPRESS) {
1096 if (!CMS_uncompress(cms, indata, out, flags))
1098 } else if (operation == SMIME_DIGEST_VERIFY) {
1099 if (CMS_digest_verify(cms, indata, out, flags) > 0) {
1100 BIO_printf(bio_err, "Verification successful\n");
1102 BIO_printf(bio_err, "Verification failure\n");
1105 } else if (operation == SMIME_ENCRYPTED_DECRYPT) {
1106 if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
1107 indata, out, flags))
1109 } else if (operation == SMIME_VERIFY) {
1110 if (CMS_verify(cms, other, store, indata, out, flags) > 0) {
1111 BIO_printf(bio_err, "Verification successful\n");
1113 BIO_printf(bio_err, "Verification failure\n");
1115 ret = verify_err + 32;
1118 if (signerfile != NULL) {
1119 STACK_OF(X509) *signers;
1120 signers = CMS_get0_signers(cms);
1121 if (!save_certs(signerfile, signers)) {
1123 "Error writing signers to %s\n", signerfile);
1127 sk_X509_free(signers);
1130 receipt_request_print(cms);
1132 } else if (operation == SMIME_VERIFY_RECEIPT) {
1133 if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) {
1134 BIO_printf(bio_err, "Verification successful\n");
1136 BIO_printf(bio_err, "Verification failure\n");
1142 CMS_ContentInfo_print_ctx(out, cms, 0, NULL);
1143 } else if (outformat == FORMAT_SMIME) {
1145 BIO_printf(out, "To: %s%s", to, mime_eol);
1147 BIO_printf(out, "From: %s%s", from, mime_eol);
1149 BIO_printf(out, "Subject: %s%s", subject, mime_eol);
1150 if (operation == SMIME_RESIGN)
1151 ret = SMIME_write_CMS(out, cms, indata, flags);
1153 ret = SMIME_write_CMS(out, cms, in, flags);
1154 } else if (outformat == FORMAT_PEM) {
1155 ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
1156 } else if (outformat == FORMAT_ASN1) {
1157 ret = i2d_CMS_bio_stream(out, cms, in, flags);
1159 BIO_printf(bio_err, "Bad output format for CMS file\n");
1170 ERR_print_errors(bio_err);
1171 sk_X509_pop_free(encerts, X509_free);
1172 sk_X509_pop_free(other, X509_free);
1173 X509_VERIFY_PARAM_free(vpm);
1174 sk_OPENSSL_STRING_free(sksigners);
1175 sk_OPENSSL_STRING_free(skkeys);
1176 OPENSSL_free(secret_key);
1177 OPENSSL_free(secret_keyid);
1178 OPENSSL_free(pwri_tmp);
1179 ASN1_OBJECT_free(econtent_type);
1180 CMS_ReceiptRequest_free(rr);
1181 sk_OPENSSL_STRING_free(rr_to);
1182 sk_OPENSSL_STRING_free(rr_from);
1183 for (key_param = key_first; key_param;) {
1184 cms_key_param *tparam;
1185 sk_OPENSSL_STRING_free(key_param->param);
1186 tparam = key_param->next;
1187 OPENSSL_free(key_param);
1190 X509_STORE_free(store);
1195 CMS_ContentInfo_free(cms);
1196 CMS_ContentInfo_free(rcms);
1202 OPENSSL_free(passin);
1206 static int save_certs(char *signerfile, STACK_OF(X509) *signers)
1210 if (signerfile == NULL)
1212 tmp = BIO_new_file(signerfile, "w");
1215 for (i = 0; i < sk_X509_num(signers); i++)
1216 PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
1221 /* Minimal callback just to output policy info (if any) */
1223 static int cms_cb(int ok, X509_STORE_CTX *ctx)
1227 error = X509_STORE_CTX_get_error(ctx);
1231 if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
1232 && ((error != X509_V_OK) || (ok != 2)))
1235 policies_print(ctx);
1241 static void gnames_stack_print(STACK_OF(GENERAL_NAMES) *gns)
1243 STACK_OF(GENERAL_NAME) *gens;
1247 for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) {
1248 gens = sk_GENERAL_NAMES_value(gns, i);
1249 for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) {
1250 gen = sk_GENERAL_NAME_value(gens, j);
1251 BIO_puts(bio_err, " ");
1252 GENERAL_NAME_print(bio_err, gen);
1253 BIO_puts(bio_err, "\n");
1259 static void receipt_request_print(CMS_ContentInfo *cms)
1261 STACK_OF(CMS_SignerInfo) *sis;
1263 CMS_ReceiptRequest *rr;
1265 STACK_OF(GENERAL_NAMES) *rto, *rlist;
1268 sis = CMS_get0_SignerInfos(cms);
1269 for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) {
1270 si = sk_CMS_SignerInfo_value(sis, i);
1271 rv = CMS_get1_ReceiptRequest(si, &rr);
1272 BIO_printf(bio_err, "Signer %d:\n", i + 1);
1274 BIO_puts(bio_err, " No Receipt Request\n");
1275 } else if (rv < 0) {
1276 BIO_puts(bio_err, " Receipt Request Parse Error\n");
1277 ERR_print_errors(bio_err);
1281 CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst,
1283 BIO_puts(bio_err, " Signed Content ID:\n");
1284 idlen = ASN1_STRING_length(scid);
1285 id = (const char *)ASN1_STRING_get0_data(scid);
1286 BIO_dump_indent(bio_err, id, idlen, 4);
1287 BIO_puts(bio_err, " Receipts From");
1288 if (rlist != NULL) {
1289 BIO_puts(bio_err, " List:\n");
1290 gnames_stack_print(rlist);
1291 } else if (allorfirst == 1) {
1292 BIO_puts(bio_err, ": First Tier\n");
1293 } else if (allorfirst == 0) {
1294 BIO_puts(bio_err, ": All\n");
1296 BIO_printf(bio_err, " Unknown (%d)\n", allorfirst);
1298 BIO_puts(bio_err, " Receipts To:\n");
1299 gnames_stack_print(rto);
1301 CMS_ReceiptRequest_free(rr);
1305 static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns)
1308 STACK_OF(GENERAL_NAMES) *ret;
1309 GENERAL_NAMES *gens = NULL;
1310 GENERAL_NAME *gen = NULL;
1311 ret = sk_GENERAL_NAMES_new_null();
1314 for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) {
1315 char *str = sk_OPENSSL_STRING_value(ns, i);
1316 gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0);
1319 gens = GENERAL_NAMES_new();
1322 if (!sk_GENERAL_NAME_push(gens, gen))
1325 if (!sk_GENERAL_NAMES_push(ret, gens))
1333 sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free);
1334 GENERAL_NAMES_free(gens);
1335 GENERAL_NAME_free(gen);
1339 static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING)
1340 *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING)
1343 STACK_OF(GENERAL_NAMES) *rct_to = NULL, *rct_from = NULL;
1344 CMS_ReceiptRequest *rr;
1345 rct_to = make_names_stack(rr_to);
1348 if (rr_from != NULL) {
1349 rct_from = make_names_stack(rr_from);
1350 if (rct_from == NULL)
1355 rr = CMS_ReceiptRequest_create0(NULL, -1, rr_allorfirst, rct_from,
1359 sk_GENERAL_NAMES_pop_free(rct_to, GENERAL_NAMES_free);
1363 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
1364 STACK_OF(OPENSSL_STRING) *param)
1368 if (sk_OPENSSL_STRING_num(param) <= 0)
1370 for (i = 0; i < sk_OPENSSL_STRING_num(param); i++) {
1371 keyopt = sk_OPENSSL_STRING_value(param, i);
1372 if (pkey_ctrl_string(pctx, keyopt) <= 0) {
1373 BIO_printf(bio_err, "parameter error \"%s\"\n", keyopt);
1374 ERR_print_errors(bio_err);