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 #include <openssl/crypto.h>
18 #include <openssl/pem.h>
19 #include <openssl/err.h>
20 #include <openssl/x509_vfy.h>
21 #include <openssl/x509v3.h>
22 #include <openssl/cms.h>
24 static int save_certs(char *signerfile, STACK_OF(X509) *signers);
25 static int cms_cb(int ok, X509_STORE_CTX *ctx);
26 static void receipt_request_print(CMS_ContentInfo *cms);
27 static CMS_ReceiptRequest
28 *make_receipt_request(STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst,
29 STACK_OF(OPENSSL_STRING) *rr_from);
30 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
31 STACK_OF(OPENSSL_STRING) *param);
33 #define SMIME_OP 0x100
34 #define SMIME_IP 0x200
35 #define SMIME_SIGNERS 0x400
36 #define SMIME_ENCRYPT (1 | SMIME_OP)
37 #define SMIME_DECRYPT (2 | SMIME_IP)
38 #define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS)
39 #define SMIME_VERIFY (4 | SMIME_IP)
40 #define SMIME_RESIGN (5 | SMIME_IP | SMIME_OP | SMIME_SIGNERS)
41 #define SMIME_SIGN_RECEIPT (6 | SMIME_IP | SMIME_OP)
42 #define SMIME_VERIFY_RECEIPT (7 | SMIME_IP)
43 #define SMIME_DIGEST_CREATE (8 | SMIME_OP)
44 #define SMIME_DIGEST_VERIFY (9 | SMIME_IP)
45 #define SMIME_COMPRESS (10 | SMIME_OP)
46 #define SMIME_UNCOMPRESS (11 | SMIME_IP)
47 #define SMIME_ENCRYPTED_ENCRYPT (12 | SMIME_OP)
48 #define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP)
49 #define SMIME_DATA_CREATE (14 | SMIME_OP)
50 #define SMIME_DATA_OUT (15 | SMIME_IP)
51 #define SMIME_CMSOUT (16 | SMIME_IP | SMIME_OP)
53 static int verify_err = 0;
55 typedef struct cms_key_param_st cms_key_param;
57 struct cms_key_param_st {
59 STACK_OF(OPENSSL_STRING) *param;
63 typedef enum OPTION_choice {
65 OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENCRYPT,
66 OPT_DECRYPT, OPT_SIGN, OPT_CADES, OPT_SIGN_RECEIPT, OPT_RESIGN,
67 OPT_VERIFY, OPT_VERIFY_RETCODE, OPT_VERIFY_RECEIPT,
68 OPT_CMSOUT, OPT_DATA_OUT, OPT_DATA_CREATE, OPT_DIGEST_VERIFY,
69 OPT_DIGEST_CREATE, OPT_COMPRESS, OPT_UNCOMPRESS,
70 OPT_ED_DECRYPT, OPT_ED_ENCRYPT, OPT_DEBUG_DECRYPT, OPT_TEXT,
71 OPT_ASCIICRLF, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCERTS,
72 OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP, OPT_BINARY, OPT_KEYID,
73 OPT_NOSIGS, OPT_NO_CONTENT_VERIFY, OPT_NO_ATTR_VERIFY, OPT_INDEF,
74 OPT_NOINDEF, OPT_CRLFEOL, OPT_NOOUT, OPT_RR_PRINT,
75 OPT_RR_ALL, OPT_RR_FIRST, OPT_RCTFORM, OPT_CERTFILE, OPT_CAFILE,
76 OPT_CAPATH, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE,
77 OPT_CONTENT, OPT_PRINT, OPT_NAMEOPT,
78 OPT_SECRETKEY, OPT_SECRETKEYID, OPT_PWRI_PASSWORD, OPT_ECONTENT_TYPE,
79 OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP,
80 OPT_CERTSOUT, OPT_MD, OPT_INKEY, OPT_KEYFORM, OPT_KEYOPT, OPT_RR_FROM,
81 OPT_RR_TO, OPT_AES128_WRAP, OPT_AES192_WRAP, OPT_AES256_WRAP,
82 OPT_3DES_WRAP, OPT_WRAP, OPT_ENGINE,
84 OPT_PROV_ENUM, OPT_CONFIG,
90 const OPTIONS cms_options[] = {
91 {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"},
92 {"help", OPT_HELP, '-', "Display this summary"},
94 OPT_SECTION("General"),
95 {"in", OPT_IN, '<', "Input file"},
96 {"out", OPT_OUT, '>', "Output file"},
99 OPT_SECTION("Operation"),
100 {"encrypt", OPT_ENCRYPT, '-', "Encrypt message"},
101 {"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"},
102 {"sign", OPT_SIGN, '-', "Sign message"},
103 {"verify", OPT_VERIFY, '-', "Verify signed message"},
104 {"resign", OPT_RESIGN, '-', "Resign a signed message"},
105 {"sign_receipt", OPT_SIGN_RECEIPT, '-',
106 "Generate a signed receipt for a message"},
107 {"verify_receipt", OPT_VERIFY_RECEIPT, '<',
108 "Verify receipts; exit if receipt signatures do not verify"},
109 {"digest_create", OPT_DIGEST_CREATE, '-',
110 "Create a CMS \"DigestedData\" object"},
111 {"digest_verify", OPT_DIGEST_VERIFY, '-',
112 "Verify a CMS \"DigestedData\" object and output it"},
113 {"compress", OPT_COMPRESS, '-', "Create a CMS \"CompressedData\" object"},
114 {"uncompress", OPT_UNCOMPRESS, '-',
115 "Uncompress a CMS \"CompressedData\" object"},
116 {"EncryptedData_encrypt", OPT_ED_ENCRYPT, '-',
117 "Create CMS \"EncryptedData\" object using symmetric key"},
118 {"EncryptedData_decrypt", OPT_ED_DECRYPT, '-',
119 "Decrypt CMS \"EncryptedData\" object using symmetric key"},
120 {"data_create", OPT_DATA_CREATE, '-', "Create a CMS \"Data\" object"},
121 {"data_out", OPT_DATA_OUT, '-', "Copy CMS \"Data\" object to output"},
122 {"cmsout", OPT_CMSOUT, '-', "Output CMS structure"},
124 OPT_SECTION("File format"),
125 {"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"},
126 {"outform", OPT_OUTFORM, 'c',
127 "Output format SMIME (default), PEM or DER"},
128 {"rctform", OPT_RCTFORM, 'F', "Receipt file format"},
129 {"stream", OPT_INDEF, '-', "Enable CMS streaming"},
130 {"indef", OPT_INDEF, '-', "Same as -stream"},
131 {"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"},
132 {"binary", OPT_BINARY, '-',
133 "Treat input as binary: do not translate to canonical form"},
134 {"crlfeol", OPT_CRLFEOL, '-',
135 "Use CRLF as EOL termination instead of CR only" },
136 {"asciicrlf", OPT_ASCIICRLF, '-',
137 "Perform CRLF canonicalisation when signing"},
139 OPT_SECTION("Keys and passwords"),
140 {"pwri_password", OPT_PWRI_PASSWORD, 's',
141 "Specific password for recipient"},
142 {"secretkey", OPT_SECRETKEY, 's',
143 "Use specified hex-encoded key to decrypt/encrypt recipients or content"},
144 {"secretkeyid", OPT_SECRETKEYID, 's',
145 "Identity of the -secretkey for CMS \"KEKRecipientInfo\" object"},
146 {"inkey", OPT_INKEY, 's',
147 "Input private key (if not signer or recipient)"},
148 {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
149 {"keyopt", OPT_KEYOPT, 's', "Set public key parameters as n:v pairs"},
150 {"keyform", OPT_KEYFORM, 'f',
151 "Input private key format (ENGINE, other values ignored)"},
152 #ifndef OPENSSL_NO_ENGINE
153 {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
158 OPT_SECTION("Encryption and decryption"),
159 {"originator", OPT_ORIGINATOR, 's', "Originator certificate file"},
160 {"recip", OPT_RECIP, '<', "Recipient cert file"},
161 {"cert...", OPT_PARAM, '.',
162 "Recipient certs (optional; used only when encrypting)"},
163 {"", OPT_CIPHER, '-',
164 "The encryption algorithm to use (any supported cipher)"},
165 {"wrap", OPT_WRAP, 's',
166 "Key wrap algorithm to use when encrypting with key agreement"},
167 {"aes128-wrap", OPT_AES128_WRAP, '-', "Use AES128 to wrap key"},
168 {"aes192-wrap", OPT_AES192_WRAP, '-', "Use AES192 to wrap key"},
169 {"aes256-wrap", OPT_AES256_WRAP, '-', "Use AES256 to wrap key"},
170 {"des3-wrap", OPT_3DES_WRAP, '-', "Use 3DES-EDE to wrap key"},
171 {"debug_decrypt", OPT_DEBUG_DECRYPT, '-',
172 "Disable MMA protection, return error if no recipient found (see doc)"},
174 OPT_SECTION("Signing"),
175 {"md", OPT_MD, 's', "Digest algorithm to use"},
176 {"signer", OPT_SIGNER, 's', "Signer certificate input file"},
177 {"certfile", OPT_CERTFILE, '<', "Other certificates file"},
178 {"cades", OPT_CADES, '-',
179 "Include signingCertificate attribute (CAdES-BES)"},
180 {"nodetach", OPT_NODETACH, '-', "Use opaque signing"},
181 {"nocerts", OPT_NOCERTS, '-',
182 "Don't include signer's certificate when signing"},
183 {"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"},
184 {"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"},
185 {"receipt_request_all", OPT_RR_ALL, '-',
186 "When signing, create a receipt request for all recipients"},
187 {"receipt_request_first", OPT_RR_FIRST, '-',
188 "When signing, create a receipt request for first recipient"},
189 {"receipt_request_from", OPT_RR_FROM, 's',
190 "Create signed receipt request with specified email address"},
191 {"receipt_request_to", OPT_RR_TO, 's',
192 "Create signed receipt targeted to specified address"},
194 OPT_SECTION("Verification"),
195 {"signer", OPT_DUP, 's', "Signer certificate(s) output file"},
196 {"content", OPT_CONTENT, '<',
197 "Supply or override content for detached signature"},
198 {"no_content_verify", OPT_NO_CONTENT_VERIFY, '-',
199 "Do not verify signed content signatures"},
200 {"no_attr_verify", OPT_NO_ATTR_VERIFY, '-',
201 "Do not verify signed attribute signatures"},
202 {"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"},
203 {"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"},
204 {"nointern", OPT_NOINTERN, '-',
205 "Don't search certificates in message for signer"},
206 {"cades", OPT_DUP, '-', "Check signingCertificate (CAdES-BES)"},
207 {"verify_retcode", OPT_VERIFY_RETCODE, '-',
208 "Exit non-zero on verification failure"},
209 {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
210 {"CApath", OPT_CAPATH, '/', "Trusted certificates directory"},
211 {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"},
212 {"no-CAfile", OPT_NOCAFILE, '-',
213 "Do not load the default certificates file"},
214 {"no-CApath", OPT_NOCAPATH, '-',
215 "Do not load certificates from the default certificates directory"},
216 {"no-CAstore", OPT_NOCASTORE, '-',
217 "Do not load certificates from the default certificates store"},
219 OPT_SECTION("Output"),
220 {"keyid", OPT_KEYID, '-', "Use subject key identifier"},
221 {"econtent_type", OPT_ECONTENT_TYPE, 's', "OID for external content"},
222 {"text", OPT_TEXT, '-', "Include or delete text MIME headers"},
223 {"certsout", OPT_CERTSOUT, '>', "Certificate output file"},
224 {"to", OPT_TO, 's', "To address"},
225 {"from", OPT_FROM, 's', "From address"},
226 {"subject", OPT_SUBJECT, 's', "Subject"},
228 OPT_SECTION("Printing"),
229 {"noout", OPT_NOOUT, '-',
230 "For the -cmsout operation do not output the parsed CMS structure"},
231 {"print", OPT_PRINT, '-',
232 "For the -cmsout operation print out all fields of the CMS structure"},
233 {"nameopt", OPT_NAMEOPT, 's',
234 "For the -print option specifies various strings printing options"},
235 {"receipt_request_print", OPT_RR_PRINT, '-', "Print CMS Receipt Request" },
241 static CMS_ContentInfo *load_content_info(int informat, BIO *in, int flags,
242 BIO **indata, const char *name)
244 CMS_ContentInfo *ret, *ci;
246 ret = CMS_ContentInfo_new_ex(app_get0_libctx(), app_get0_propq());
248 BIO_printf(bio_err, "Error allocating CMS_contentinfo\n");
253 ci = SMIME_read_CMS_ex(in, flags, 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 static void warn_binary(const char *file)
278 unsigned char linebuf[1024], *cur, *end;
281 if ((bio = bio_open_default(file, 'r', FORMAT_BINARY)) == NULL)
282 return; /* cannot give a proper warning since there is an error */
283 while ((len = BIO_read(bio, linebuf, sizeof(linebuf))) > 0) {
285 for (cur = linebuf; cur < end; cur++) {
286 if (*cur == '\0' || *cur >= 0x80) {
287 BIO_printf(bio_err, "Warning: input file '%s' contains %s"
288 " character; better use -binary option\n",
289 file, *cur == '\0' ? "NUL" : "8-bit");
297 int cms_main(int argc, char **argv)
300 ASN1_OBJECT *econtent_type = NULL;
301 BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
302 CMS_ContentInfo *cms = NULL, *rcms = NULL;
303 CMS_ReceiptRequest *rr = NULL;
305 EVP_PKEY *key = NULL;
306 EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
307 EVP_MD *sign_md = NULL;
308 STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
309 STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
310 STACK_OF(X509) *encerts = sk_X509_new_null(), *other = NULL;
311 X509 *cert = NULL, *recip = NULL, *signer = NULL, *originator = NULL;
312 X509_STORE *store = NULL;
313 X509_VERIFY_PARAM *vpm = X509_VERIFY_PARAM_new();
314 char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
315 const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
316 char *certsoutfile = NULL, *digestname = NULL, *wrapname = NULL;
317 int noCAfile = 0, noCApath = 0, noCAstore = 0;
318 char *infile = NULL, *outfile = NULL, *rctfile = NULL;
319 char *passinarg = NULL, *passin = NULL, *signerfile = NULL;
320 char *originatorfile = NULL, *recipfile = NULL, *ciphername = NULL;
321 char *to = NULL, *from = NULL, *subject = NULL, *prog;
322 cms_key_param *key_first = NULL, *key_param = NULL;
323 int flags = CMS_DETACHED, noout = 0, print = 0, keyidx = -1, vpmtouched = 0;
324 int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
325 int operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1;
326 int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_UNDEF;
327 size_t secret_keylen = 0, secret_keyidlen = 0;
328 unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
329 unsigned char *secret_key = NULL, *secret_keyid = NULL;
331 const char *mime_eol = "\n";
333 OSSL_LIB_CTX *libctx = app_get0_libctx();
335 if (encerts == NULL || vpm == NULL)
338 prog = opt_init(argc, argv, cms_options);
339 while ((o = opt_next()) != OPT_EOF) {
344 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
347 opt_help(cms_options);
351 if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
355 if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
363 operation = SMIME_ENCRYPT;
366 operation = SMIME_DECRYPT;
369 operation = SMIME_SIGN;
372 operation = SMIME_VERIFY;
375 operation = SMIME_RESIGN;
377 case OPT_SIGN_RECEIPT:
378 operation = SMIME_SIGN_RECEIPT;
380 case OPT_VERIFY_RECEIPT:
381 operation = SMIME_VERIFY_RECEIPT;
384 case OPT_VERIFY_RETCODE:
387 case OPT_DIGEST_CREATE:
388 operation = SMIME_DIGEST_CREATE;
390 case OPT_DIGEST_VERIFY:
391 operation = SMIME_DIGEST_VERIFY;
394 operation = SMIME_COMPRESS;
397 operation = SMIME_UNCOMPRESS;
400 operation = SMIME_ENCRYPTED_ENCRYPT;
403 operation = SMIME_ENCRYPTED_DECRYPT;
405 case OPT_DATA_CREATE:
406 operation = SMIME_DATA_CREATE;
409 operation = SMIME_DATA_OUT;
412 operation = SMIME_CMSOUT;
415 case OPT_DEBUG_DECRYPT:
416 flags |= CMS_DEBUG_DECRYPT;
422 flags |= CMS_ASCIICRLF;
425 flags |= CMS_NOINTERN;
428 flags |= CMS_NO_SIGNER_CERT_VERIFY;
431 flags |= CMS_NOCERTS;
437 flags &= ~CMS_DETACHED;
440 flags |= CMS_NOSMIMECAP;
449 flags |= CMS_USE_KEYID;
454 case OPT_NO_CONTENT_VERIFY:
455 flags |= CMS_NO_CONTENT_VERIFY;
457 case OPT_NO_ATTR_VERIFY:
458 flags |= CMS_NO_ATTR_VERIFY;
464 flags &= ~CMS_STREAM;
468 flags |= CMS_CRLFEOL;
483 if (rctformat == FORMAT_ASN1) {
484 if (!opt_format(opt_arg(),
485 OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat))
488 rcms = load_content_info(rctformat, rctin, 0, NULL, "recipient");
492 certfile = opt_arg();
516 contfile = opt_arg();
520 && (rr_from = sk_OPENSSL_STRING_new_null()) == NULL)
522 sk_OPENSSL_STRING_push(rr_from, opt_arg());
526 && (rr_to = sk_OPENSSL_STRING_new_null()) == NULL)
528 sk_OPENSSL_STRING_push(rr_to, opt_arg());
534 if (!set_nameopt(opt_arg()))
538 if (secret_key != NULL) {
539 BIO_printf(bio_err, "Invalid key (supplied twice) %s\n",
543 secret_key = OPENSSL_hexstr2buf(opt_arg(), <mp);
544 if (secret_key == NULL) {
545 BIO_printf(bio_err, "Invalid key %s\n", opt_arg());
548 secret_keylen = (size_t)ltmp;
550 case OPT_SECRETKEYID:
551 if (secret_keyid != NULL) {
552 BIO_printf(bio_err, "Invalid id (supplied twice) %s\n",
556 secret_keyid = OPENSSL_hexstr2buf(opt_arg(), <mp);
557 if (secret_keyid == NULL) {
558 BIO_printf(bio_err, "Invalid id %s\n", opt_arg());
561 secret_keyidlen = (size_t)ltmp;
563 case OPT_PWRI_PASSWORD:
564 pwri_pass = (unsigned char *)opt_arg();
566 case OPT_ECONTENT_TYPE:
567 if (econtent_type != NULL) {
568 BIO_printf(bio_err, "Invalid OID (supplied twice) %s\n",
572 econtent_type = OBJ_txt2obj(opt_arg(), 0);
573 if (econtent_type == NULL) {
574 BIO_printf(bio_err, "Invalid OID %s\n", opt_arg());
579 e = setup_engine(opt_arg(), 0);
582 passinarg = opt_arg();
594 certsoutfile = opt_arg();
597 digestname = opt_arg();
600 /* If previous -signer argument add signer to list */
601 if (signerfile != NULL) {
602 if (sksigners == NULL
603 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
605 sk_OPENSSL_STRING_push(sksigners, signerfile);
607 keyfile = signerfile;
609 && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
611 sk_OPENSSL_STRING_push(skkeys, keyfile);
614 signerfile = opt_arg();
617 originatorfile = opt_arg();
620 /* If previous -inkey argument add signer to list */
621 if (keyfile != NULL) {
622 if (signerfile == NULL) {
623 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
626 if (sksigners == NULL
627 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
629 sk_OPENSSL_STRING_push(sksigners, signerfile);
632 && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
634 sk_OPENSSL_STRING_push(skkeys, keyfile);
639 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
643 if (operation == SMIME_ENCRYPT) {
644 cert = load_cert(opt_arg(), FORMAT_UNDEF,
645 "recipient certificate file");
648 sk_X509_push(encerts, cert);
651 recipfile = opt_arg();
655 ciphername = opt_unknown();
659 if (operation == SMIME_ENCRYPT) {
660 if (sk_X509_num(encerts) > 0)
661 keyidx += sk_X509_num(encerts);
663 if (keyfile != NULL || signerfile != NULL)
666 keyidx += sk_OPENSSL_STRING_num(skkeys);
669 BIO_printf(bio_err, "No key specified\n");
672 if (key_param == NULL || key_param->idx != keyidx) {
673 cms_key_param *nparam;
674 nparam = app_malloc(sizeof(*nparam), "key param buffer");
675 if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL) {
676 OPENSSL_free(nparam);
679 nparam->idx = keyidx;
681 if (key_first == NULL)
684 key_param->next = nparam;
687 sk_OPENSSL_STRING_push(key_param->param, opt_arg());
690 if (!opt_verify(o, vpm))
699 if (!opt_provider(o))
703 conf = app_load_config_modules(opt_arg());
708 wrapname = opt_unknown();
710 case OPT_AES128_WRAP:
711 case OPT_AES192_WRAP:
712 case OPT_AES256_WRAP:
714 wrapname = opt_flag() + 1;
718 if (!app_RAND_load())
721 if (digestname != NULL) {
722 if (!opt_md(digestname, &sign_md))
725 if (ciphername != NULL) {
726 if (!opt_cipher(ciphername, &cipher))
729 if (wrapname != NULL) {
730 if (!opt_cipher(wrapname, &wrap_cipher))
734 /* Remaining args are files to process. */
735 argc = opt_num_rest();
738 if ((rr_allorfirst != -1 || rr_from != NULL) && rr_to == NULL) {
739 BIO_puts(bio_err, "No Signed Receipts Recipients\n");
743 if (!(operation & SMIME_SIGNERS) && (rr_to != NULL || rr_from != NULL)) {
744 BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
747 if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) {
748 BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
752 if ((flags & CMS_CADES) != 0) {
753 if ((flags & CMS_NOATTR) != 0) {
754 BIO_puts(bio_err, "Incompatible options: "
755 "CAdES requires signed attributes\n");
758 if (operation == SMIME_VERIFY
759 && (flags & (CMS_NO_SIGNER_CERT_VERIFY | CMS_NO_ATTR_VERIFY)) != 0) {
760 BIO_puts(bio_err, "Incompatible options: CAdES validation requires"
761 " certs and signed attributes validations\n");
766 if (operation & SMIME_SIGNERS) {
767 if (keyfile != NULL && signerfile == NULL) {
768 BIO_puts(bio_err, "Illegal -inkey without -signer\n");
771 /* Check to see if any final signer needs to be appended */
772 if (signerfile != NULL) {
773 if (sksigners == NULL
774 && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
776 sk_OPENSSL_STRING_push(sksigners, signerfile);
777 if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
780 keyfile = signerfile;
781 sk_OPENSSL_STRING_push(skkeys, keyfile);
783 if (sksigners == NULL) {
784 BIO_printf(bio_err, "No signer certificate specified\n");
789 } else if (operation == SMIME_DECRYPT) {
790 if (recipfile == NULL && keyfile == NULL
791 && secret_key == NULL && pwri_pass == NULL) {
793 "No recipient certificate or key specified\n");
796 } else if (operation == SMIME_ENCRYPT) {
797 if (*argv == NULL && secret_key == NULL
798 && pwri_pass == NULL && sk_X509_num(encerts) <= 0) {
799 BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
802 } else if (!operation) {
803 BIO_printf(bio_err, "No operation option (-encrypt|-decrypt|-sign|-verify|...) specified.\n");
807 if (!app_passwd(passinarg, NULL, &passin, NULL)) {
808 BIO_printf(bio_err, "Error getting password\n");
814 if (!(operation & SMIME_SIGNERS))
815 flags &= ~CMS_DETACHED;
817 if ((flags & CMS_BINARY) != 0) {
818 if (!(operation & SMIME_OP))
819 outformat = FORMAT_BINARY;
820 if (!(operation & SMIME_IP))
821 informat = FORMAT_BINARY;
824 if (operation == SMIME_ENCRYPT) {
826 #ifndef OPENSSL_NO_DES
827 cipher = (EVP_CIPHER *)EVP_des_ede3_cbc();
829 BIO_printf(bio_err, "No cipher selected\n");
834 if (secret_key && !secret_keyid) {
835 BIO_printf(bio_err, "No secret key id\n");
840 if (operation == SMIME_ENCRYPT) {
841 for (; *argv != NULL; argv++) {
842 cert = load_cert(*argv, FORMAT_UNDEF,
843 "recipient certificate file");
846 sk_X509_push(encerts, cert);
850 BIO_printf(bio_err, "Warning: recipient certificate file parameters ignored for operation other than -encrypt\n");
855 if (certfile != NULL) {
856 if (!load_certs(certfile, 0, &other, NULL, "certificate file")) {
857 ERR_print_errors(bio_err);
862 if (recipfile != NULL && (operation == SMIME_DECRYPT)) {
863 if ((recip = load_cert(recipfile, FORMAT_UNDEF,
864 "recipient certificate file")) == NULL) {
865 ERR_print_errors(bio_err);
870 if (originatorfile != NULL) {
871 if ((originator = load_cert(originatorfile, FORMAT_UNDEF,
872 "originator certificate file")) == NULL) {
873 ERR_print_errors(bio_err);
878 if (operation == SMIME_SIGN_RECEIPT) {
879 if ((signer = load_cert(signerfile, FORMAT_UNDEF,
880 "receipt signer certificate file")) == NULL) {
881 ERR_print_errors(bio_err);
886 if ((operation == SMIME_DECRYPT) || (operation == SMIME_ENCRYPT)) {
889 } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
891 keyfile = signerfile;
896 if (keyfile != NULL) {
897 key = load_key(keyfile, keyform, 0, passin, e, "signing key");
902 if ((flags & CMS_BINARY) == 0)
904 in = bio_open_default(infile, 'r',
905 (flags & CMS_BINARY) != 0 ? FORMAT_BINARY : informat);
909 if (operation & SMIME_IP) {
910 cms = load_content_info(informat, in, flags, &indata, "SMIME");
913 if (contfile != NULL) {
915 if ((flags & CMS_BINARY) == 0)
916 warn_binary(contfile);
917 if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
918 BIO_printf(bio_err, "Can't read content file %s\n", contfile);
922 if (certsoutfile != NULL) {
923 STACK_OF(X509) *allcerts;
924 allcerts = CMS_get1_certs(cms);
925 if (!save_certs(certsoutfile, allcerts)) {
927 "Error writing certs to %s\n", certsoutfile);
931 sk_X509_pop_free(allcerts, X509_free);
935 if (rctfile != NULL) {
936 char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
938 if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) {
939 BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile);
943 rcms = load_content_info(rctformat, rctin, 0, NULL, "recipient");
948 out = bio_open_default(outfile, 'w', outformat);
952 if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) {
953 if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
954 CAstore, noCAstore)) == NULL)
956 X509_STORE_set_verify_cb(store, cms_cb);
958 X509_STORE_set1_param(store, vpm);
963 if (operation == SMIME_DATA_CREATE) {
964 cms = CMS_data_create_ex(in, flags, libctx, app_get0_propq());
965 } else if (operation == SMIME_DIGEST_CREATE) {
966 cms = CMS_digest_create_ex(in, sign_md, flags, libctx, app_get0_propq());
967 } else if (operation == SMIME_COMPRESS) {
968 cms = CMS_compress(in, -1, flags);
969 } else if (operation == SMIME_ENCRYPT) {
971 flags |= CMS_PARTIAL;
972 cms = CMS_encrypt_ex(NULL, in, cipher, flags, libctx, app_get0_propq());
975 for (i = 0; i < sk_X509_num(encerts); i++) {
976 CMS_RecipientInfo *ri;
977 cms_key_param *kparam;
978 int tflags = flags | CMS_KEY_PARAM;
979 /* This flag enforces allocating the EVP_PKEY_CTX for the recipient here */
981 X509 *x = sk_X509_value(encerts, i);
984 for (kparam = key_first; kparam; kparam = kparam->next) {
985 if (kparam->idx == i) {
989 ri = CMS_add1_recipient(cms, x, key, originator, tflags);
993 pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
994 if (kparam != NULL) {
995 if (!cms_set_pkey_param(pctx, kparam->param))
999 res = EVP_PKEY_CTX_ctrl(pctx, -1, -1,
1000 EVP_PKEY_CTRL_CIPHER,
1001 EVP_CIPHER_nid(cipher), NULL);
1002 if (res <= 0 && res != -2)
1005 if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE
1006 && wrap_cipher != NULL) {
1007 EVP_CIPHER_CTX *wctx;
1008 wctx = CMS_RecipientInfo_kari_get0_ctx(ri);
1009 EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL);
1013 if (secret_key != NULL) {
1014 if (!CMS_add0_recipient_key(cms, NID_undef,
1015 secret_key, secret_keylen,
1016 secret_keyid, secret_keyidlen,
1019 /* NULL these because call absorbs them */
1021 secret_keyid = NULL;
1023 if (pwri_pass != NULL) {
1024 pwri_tmp = (unsigned char *)OPENSSL_strdup((char *)pwri_pass);
1025 if (pwri_tmp == NULL)
1027 if (CMS_add0_recipient_password(cms,
1028 -1, NID_undef, NID_undef,
1029 pwri_tmp, -1, NULL) == NULL)
1033 if (!(flags & CMS_STREAM)) {
1034 if (!CMS_final(cms, in, NULL, flags))
1037 } else if (operation == SMIME_ENCRYPTED_ENCRYPT) {
1038 cms = CMS_EncryptedData_encrypt_ex(in, cipher, secret_key,
1039 secret_keylen, flags, libctx, app_get0_propq());
1041 } else if (operation == SMIME_SIGN_RECEIPT) {
1042 CMS_ContentInfo *srcms = NULL;
1043 STACK_OF(CMS_SignerInfo) *sis;
1045 sis = CMS_get0_SignerInfos(cms);
1048 si = sk_CMS_SignerInfo_value(sis, 0);
1049 srcms = CMS_sign_receipt(si, signer, key, other, flags);
1052 CMS_ContentInfo_free(cms);
1054 } else if (operation & SMIME_SIGNERS) {
1057 * If detached data content we enable streaming if S/MIME output
1060 if (operation == SMIME_SIGN) {
1062 if (flags & CMS_DETACHED) {
1063 if (outformat == FORMAT_SMIME)
1064 flags |= CMS_STREAM;
1066 flags |= CMS_PARTIAL;
1067 cms = CMS_sign_ex(NULL, NULL, other, in, flags, libctx, app_get0_propq());
1070 if (econtent_type != NULL)
1071 CMS_set1_eContentType(cms, econtent_type);
1074 && ((rr = make_receipt_request(rr_to, rr_allorfirst, rr_from))
1076 BIO_puts(bio_err, "Signed Receipt Request Creation Error\n");
1080 flags |= CMS_REUSE_DIGEST;
1082 for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
1084 cms_key_param *kparam;
1086 signerfile = sk_OPENSSL_STRING_value(sksigners, i);
1087 keyfile = sk_OPENSSL_STRING_value(skkeys, i);
1089 signer = load_cert(signerfile, FORMAT_UNDEF, "signer certificate");
1090 if (signer == NULL) {
1094 key = load_key(keyfile, keyform, 0, passin, e, "signing key");
1100 for (kparam = key_first; kparam; kparam = kparam->next) {
1101 if (kparam->idx == i) {
1102 tflags |= CMS_KEY_PARAM;
1106 si = CMS_add1_signer(cms, signer, key, sign_md, tflags);
1109 if (kparam != NULL) {
1111 pctx = CMS_SignerInfo_get0_pkey_ctx(si);
1112 if (!cms_set_pkey_param(pctx, kparam->param))
1115 if (rr != NULL && !CMS_add1_ReceiptRequest(si, rr))
1122 /* If not streaming or resigning finalize structure */
1123 if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
1124 if (!CMS_final(cms, in, NULL, flags))
1130 BIO_printf(bio_err, "Error creating CMS structure\n");
1135 if (operation == SMIME_DECRYPT) {
1136 if (flags & CMS_DEBUG_DECRYPT)
1137 CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);
1139 if (secret_key != NULL) {
1140 if (!CMS_decrypt_set1_key(cms,
1141 secret_key, secret_keylen,
1142 secret_keyid, secret_keyidlen)) {
1143 BIO_puts(bio_err, "Error decrypting CMS using secret key\n");
1149 if (!CMS_decrypt_set1_pkey_and_peer(cms, key, recip, originator)) {
1150 BIO_puts(bio_err, "Error decrypting CMS using private key\n");
1155 if (pwri_pass != NULL) {
1156 if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
1157 BIO_puts(bio_err, "Error decrypting CMS using password\n");
1162 if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
1163 BIO_printf(bio_err, "Error decrypting CMS structure\n");
1166 } else if (operation == SMIME_DATA_OUT) {
1167 if (!CMS_data(cms, out, flags))
1169 } else if (operation == SMIME_UNCOMPRESS) {
1170 if (!CMS_uncompress(cms, indata, out, flags))
1172 } else if (operation == SMIME_DIGEST_VERIFY) {
1173 if (CMS_digest_verify(cms, indata, out, flags) > 0) {
1174 BIO_printf(bio_err, "Verification successful\n");
1176 BIO_printf(bio_err, "Verification failure\n");
1179 } else if (operation == SMIME_ENCRYPTED_DECRYPT) {
1180 if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
1181 indata, out, flags))
1183 } else if (operation == SMIME_VERIFY) {
1184 if (CMS_verify(cms, other, store, indata, out, flags) > 0) {
1185 BIO_printf(bio_err, "%s Verification successful\n",
1186 (flags & CMS_CADES) != 0 ? "CAdES" : "CMS");
1188 BIO_printf(bio_err, "%s Verification failure\n",
1189 (flags & CMS_CADES) != 0 ? "CAdES" : "CMS");
1191 ret = verify_err + 32;
1194 if (signerfile != NULL) {
1195 STACK_OF(X509) *signers = CMS_get0_signers(cms);
1197 if (!save_certs(signerfile, signers)) {
1199 "Error writing signers to %s\n", signerfile);
1203 sk_X509_free(signers);
1206 receipt_request_print(cms);
1208 } else if (operation == SMIME_VERIFY_RECEIPT) {
1209 if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) {
1210 BIO_printf(bio_err, "Verification successful\n");
1212 BIO_printf(bio_err, "Verification failure\n");
1218 ASN1_PCTX *pctx = NULL;
1219 if (get_nameopt() != XN_FLAG_ONELINE) {
1220 pctx = ASN1_PCTX_new();
1221 if (pctx != NULL) { /* Print anyway if malloc failed */
1222 ASN1_PCTX_set_flags(pctx, ASN1_PCTX_FLAGS_SHOW_ABSENT);
1223 ASN1_PCTX_set_str_flags(pctx, get_nameopt());
1224 ASN1_PCTX_set_nm_flags(pctx, get_nameopt());
1227 CMS_ContentInfo_print_ctx(out, cms, 0, pctx);
1228 ASN1_PCTX_free(pctx);
1230 } else if (outformat == FORMAT_SMIME) {
1232 BIO_printf(out, "To: %s%s", to, mime_eol);
1234 BIO_printf(out, "From: %s%s", from, mime_eol);
1236 BIO_printf(out, "Subject: %s%s", subject, mime_eol);
1237 if (operation == SMIME_RESIGN)
1238 ret = SMIME_write_CMS(out, cms, indata, flags);
1240 ret = SMIME_write_CMS(out, cms, in, flags);
1241 } else if (outformat == FORMAT_PEM) {
1242 ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
1243 } else if (outformat == FORMAT_ASN1) {
1244 ret = i2d_CMS_bio_stream(out, cms, in, flags);
1246 BIO_printf(bio_err, "Bad output format for CMS file\n");
1257 ERR_print_errors(bio_err);
1258 sk_X509_pop_free(encerts, X509_free);
1259 sk_X509_pop_free(other, X509_free);
1260 X509_VERIFY_PARAM_free(vpm);
1261 sk_OPENSSL_STRING_free(sksigners);
1262 sk_OPENSSL_STRING_free(skkeys);
1263 OPENSSL_free(secret_key);
1264 OPENSSL_free(secret_keyid);
1265 OPENSSL_free(pwri_tmp);
1266 ASN1_OBJECT_free(econtent_type);
1267 CMS_ReceiptRequest_free(rr);
1268 sk_OPENSSL_STRING_free(rr_to);
1269 sk_OPENSSL_STRING_free(rr_from);
1270 for (key_param = key_first; key_param;) {
1271 cms_key_param *tparam;
1272 sk_OPENSSL_STRING_free(key_param->param);
1273 tparam = key_param->next;
1274 OPENSSL_free(key_param);
1277 X509_STORE_free(store);
1282 EVP_CIPHER_free(cipher);
1283 EVP_CIPHER_free(wrap_cipher);
1284 EVP_MD_free(sign_md);
1285 CMS_ContentInfo_free(cms);
1286 CMS_ContentInfo_free(rcms);
1292 OPENSSL_free(passin);
1297 static int save_certs(char *signerfile, STACK_OF(X509) *signers)
1301 if (signerfile == NULL)
1303 tmp = BIO_new_file(signerfile, "w");
1306 for (i = 0; i < sk_X509_num(signers); i++)
1307 PEM_write_bio_X509(tmp, sk_X509_value(signers, i));
1312 /* Minimal callback just to output policy info (if any) */
1314 static int cms_cb(int ok, X509_STORE_CTX *ctx)
1318 error = X509_STORE_CTX_get_error(ctx);
1322 if ((error != X509_V_ERR_NO_EXPLICIT_POLICY)
1323 && ((error != X509_V_OK) || (ok != 2)))
1326 policies_print(ctx);
1332 static void gnames_stack_print(STACK_OF(GENERAL_NAMES) *gns)
1334 STACK_OF(GENERAL_NAME) *gens;
1338 for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) {
1339 gens = sk_GENERAL_NAMES_value(gns, i);
1340 for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) {
1341 gen = sk_GENERAL_NAME_value(gens, j);
1342 BIO_puts(bio_err, " ");
1343 GENERAL_NAME_print(bio_err, gen);
1344 BIO_puts(bio_err, "\n");
1350 static void receipt_request_print(CMS_ContentInfo *cms)
1352 STACK_OF(CMS_SignerInfo) *sis;
1354 CMS_ReceiptRequest *rr;
1356 STACK_OF(GENERAL_NAMES) *rto, *rlist;
1359 sis = CMS_get0_SignerInfos(cms);
1360 for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) {
1361 si = sk_CMS_SignerInfo_value(sis, i);
1362 rv = CMS_get1_ReceiptRequest(si, &rr);
1363 BIO_printf(bio_err, "Signer %d:\n", i + 1);
1365 BIO_puts(bio_err, " No Receipt Request\n");
1366 } else if (rv < 0) {
1367 BIO_puts(bio_err, " Receipt Request Parse Error\n");
1368 ERR_print_errors(bio_err);
1372 CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst,
1374 BIO_puts(bio_err, " Signed Content ID:\n");
1375 idlen = ASN1_STRING_length(scid);
1376 id = (const char *)ASN1_STRING_get0_data(scid);
1377 BIO_dump_indent(bio_err, id, idlen, 4);
1378 BIO_puts(bio_err, " Receipts From");
1379 if (rlist != NULL) {
1380 BIO_puts(bio_err, " List:\n");
1381 gnames_stack_print(rlist);
1382 } else if (allorfirst == 1) {
1383 BIO_puts(bio_err, ": First Tier\n");
1384 } else if (allorfirst == 0) {
1385 BIO_puts(bio_err, ": All\n");
1387 BIO_printf(bio_err, " Unknown (%d)\n", allorfirst);
1389 BIO_puts(bio_err, " Receipts To:\n");
1390 gnames_stack_print(rto);
1392 CMS_ReceiptRequest_free(rr);
1396 static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns)
1399 STACK_OF(GENERAL_NAMES) *ret;
1400 GENERAL_NAMES *gens = NULL;
1401 GENERAL_NAME *gen = NULL;
1402 ret = sk_GENERAL_NAMES_new_null();
1405 for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) {
1406 char *str = sk_OPENSSL_STRING_value(ns, i);
1407 gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0);
1410 gens = GENERAL_NAMES_new();
1413 if (!sk_GENERAL_NAME_push(gens, gen))
1416 if (!sk_GENERAL_NAMES_push(ret, gens))
1424 sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free);
1425 GENERAL_NAMES_free(gens);
1426 GENERAL_NAME_free(gen);
1430 static CMS_ReceiptRequest
1431 *make_receipt_request(STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst,
1432 STACK_OF(OPENSSL_STRING) *rr_from)
1434 STACK_OF(GENERAL_NAMES) *rct_to = NULL, *rct_from = NULL;
1436 rct_to = make_names_stack(rr_to);
1439 if (rr_from != NULL) {
1440 rct_from = make_names_stack(rr_from);
1441 if (rct_from == NULL)
1446 return CMS_ReceiptRequest_create0_ex(NULL, -1, rr_allorfirst, rct_from,
1447 rct_to, app_get0_libctx());
1449 sk_GENERAL_NAMES_pop_free(rct_to, GENERAL_NAMES_free);
1453 static int cms_set_pkey_param(EVP_PKEY_CTX *pctx,
1454 STACK_OF(OPENSSL_STRING) *param)
1458 if (sk_OPENSSL_STRING_num(param) <= 0)
1460 for (i = 0; i < sk_OPENSSL_STRING_num(param); i++) {
1461 keyopt = sk_OPENSSL_STRING_value(param, i);
1462 if (pkey_ctrl_string(pctx, keyopt) <= 0) {
1463 BIO_printf(bio_err, "parameter error \"%s\"\n", keyopt);
1464 ERR_print_errors(bio_err);