2 * Copyright 1999-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 #include <openssl/opensslconf.h>
17 #include <openssl/crypto.h>
18 #include <openssl/err.h>
19 #include <openssl/pem.h>
20 #include <openssl/pkcs12.h>
21 #include <openssl/provider.h>
22 #include <openssl/kdf.h>
30 #define PASSWD_BUF_SIZE 2048
32 #define WARN_EXPORT(opt) \
33 BIO_printf(bio_err, "Warning: -%s option ignored with -export\n", opt);
34 #define WARN_NO_EXPORT(opt) \
35 BIO_printf(bio_err, "Warning: -%s option ignored without -export\n", opt);
37 static int get_cert_chain(X509 *cert, X509_STORE *store,
38 STACK_OF(X509) *untrusted_certs,
39 STACK_OF(X509) **chain);
40 int dump_certs_keys_p12(BIO *out, const PKCS12 *p12,
41 const char *pass, int passlen, int options,
42 char *pempass, const EVP_CIPHER *enc);
43 int dump_certs_pkeys_bags(BIO *out, const STACK_OF(PKCS12_SAFEBAG) *bags,
44 const char *pass, int passlen, int options,
45 char *pempass, const EVP_CIPHER *enc);
46 int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bags,
47 const char *pass, int passlen,
48 int options, char *pempass, const EVP_CIPHER *enc);
49 void print_attribute(BIO *out, const ASN1_TYPE *av);
50 int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst,
52 void hex_prin(BIO *out, unsigned char *buf, int len);
53 static int alg_print(const X509_ALGOR *alg);
54 int cert_load(BIO *in, STACK_OF(X509) *sk);
55 static int set_pbe(int *ppbe, const char *str);
57 typedef enum OPTION_choice {
59 OPT_CIPHER, OPT_NOKEYS, OPT_KEYEX, OPT_KEYSIG, OPT_NOCERTS, OPT_CLCERTS,
60 OPT_CACERTS, OPT_NOOUT, OPT_INFO, OPT_CHAIN, OPT_TWOPASS, OPT_NOMACVER,
61 #ifndef OPENSSL_NO_DES
64 OPT_EXPORT, OPT_ITER, OPT_NOITER, OPT_MACITER, OPT_NOMACITER,
65 OPT_NOMAC, OPT_LMK, OPT_NODES, OPT_NOENC, OPT_MACALG, OPT_CERTPBE, OPT_KEYPBE,
66 OPT_INKEY, OPT_CERTFILE, OPT_UNTRUSTED, OPT_PASSCERTS,
67 OPT_NAME, OPT_CSP, OPT_CANAME,
68 OPT_IN, OPT_OUT, OPT_PASSIN, OPT_PASSOUT, OPT_PASSWORD, OPT_CAPATH,
69 OPT_CAFILE, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_ENGINE,
70 OPT_R_ENUM, OPT_PROV_ENUM,
71 #ifndef OPENSSL_NO_DES
76 const OPTIONS pkcs12_options[] = {
77 OPT_SECTION("General"),
78 {"help", OPT_HELP, '-', "Display this summary"},
79 {"in", OPT_IN, '<', "Input file"},
80 {"out", OPT_OUT, '>', "Output file"},
81 {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
82 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
83 {"password", OPT_PASSWORD, 's', "Set PKCS#12 import/export password source"},
84 {"twopass", OPT_TWOPASS, '-', "Separate MAC, encryption passwords"},
85 {"nokeys", OPT_NOKEYS, '-', "Don't output private keys"},
86 {"nocerts", OPT_NOCERTS, '-', "Don't output certificates"},
87 {"noout", OPT_NOOUT, '-', "Don't output anything, just verify PKCS#12 input"},
88 #ifndef OPENSSL_NO_DES
89 {"legacy", OPT_LEGACY_ALG, '-',
90 # ifdef OPENSSL_NO_RC2
91 "Use legacy encryption algorithm 3DES_CBC for keys and certs"
93 "Use legacy encryption: 3DES_CBC for keys, RC2_CBC for certs"
97 #ifndef OPENSSL_NO_ENGINE
98 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
103 OPT_SECTION("PKCS#12 import (parsing PKCS#12)"),
104 {"info", OPT_INFO, '-', "Print info about PKCS#12 structure"},
105 {"nomacver", OPT_NOMACVER, '-', "Don't verify integrity MAC"},
106 {"clcerts", OPT_CLCERTS, '-', "Only output client certificates"},
107 {"cacerts", OPT_CACERTS, '-', "Only output CA certificates"},
108 {"", OPT_CIPHER, '-', "Any supported cipher for output encryption"},
109 {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"},
110 {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"},
112 OPT_SECTION("PKCS#12 output (export)"),
113 {"export", OPT_EXPORT, '-', "Create PKCS12 file"},
114 {"inkey", OPT_INKEY, 's', "Private key, else read from -in input file"},
115 {"certfile", OPT_CERTFILE, '<', "Extra certificates for PKCS12 output"},
116 {"passcerts", OPT_PASSCERTS, 's', "Certificate file pass phrase source"},
117 {"chain", OPT_CHAIN, '-', "Build and add certificate chain for EE cert,"},
119 "which is the 1st cert from -in matching the private key (if given)"},
120 {"untrusted", OPT_UNTRUSTED, '<', "Untrusted certificates for chain building"},
121 {"CAfile", OPT_CAFILE, '<', "PEM-format file of CA's"},
122 {"CApath", OPT_CAPATH, '/', "PEM-format directory of CA's"},
123 {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
124 {"no-CAfile", OPT_NOCAFILE, '-',
125 "Do not load the default certificates file"},
126 {"no-CApath", OPT_NOCAPATH, '-',
127 "Do not load certificates from the default certificates directory"},
128 {"no-CAstore", OPT_NOCASTORE, '-',
129 "Do not load certificates from the default certificates store"},
130 {"name", OPT_NAME, 's', "Use name as friendly name"},
131 {"caname", OPT_CANAME, 's',
132 "Use name as CA friendly name (can be repeated)"},
133 {"CSP", OPT_CSP, 's', "Microsoft CSP name"},
134 {"LMK", OPT_LMK, '-',
135 "Add local machine keyset attribute to private key"},
136 {"keyex", OPT_KEYEX, '-', "Set key type to MS key exchange"},
137 {"keysig", OPT_KEYSIG, '-', "Set key type to MS key signature"},
138 {"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default AES-256 CBC)"},
139 {"certpbe", OPT_CERTPBE, 's',
140 "Certificate PBE algorithm (default PBES2 with PBKDF2 and AES-256 CBC)"},
141 #ifndef OPENSSL_NO_DES
142 {"descert", OPT_DESCERT, '-',
143 "Encrypt output with 3DES (default PBES2 with PBKDF2 and AES-256 CBC)"},
145 {"macalg", OPT_MACALG, 's',
146 "Digest algorithm to use in MAC (default SHA1)"},
147 {"iter", OPT_ITER, 'p', "Specify the iteration count for encryption and MAC"},
148 {"noiter", OPT_NOITER, '-', "Don't use encryption iteration"},
149 {"nomaciter", OPT_NOMACITER, '-', "Don't use MAC iteration)"},
150 {"maciter", OPT_MACITER, '-', "Unused, kept for backwards compatibility"},
151 {"nomac", OPT_NOMAC, '-', "Don't generate MAC"},
155 int pkcs12_main(int argc, char **argv)
157 char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL;
158 char *untrusted = NULL, *ciphername = NULL, *enc_flag = NULL;
159 char *passcertsarg = NULL, *passcerts = NULL;
160 char *name = NULL, *csp_name = NULL;
161 char pass[PASSWD_BUF_SIZE] = "", macpass[PASSWD_BUF_SIZE] = "";
162 int export_pkcs12 = 0, options = 0, chain = 0, twopass = 0, keytype = 0;
163 #ifndef OPENSSL_NO_DES
166 /* use library defaults for the iter, maciter, cert, and key PBE */
167 int iter = 0, maciter = 0;
168 int cert_pbe = NID_undef;
169 int key_pbe = NID_undef;
170 int ret = 1, macver = 1, add_lmk = 0, private = 0;
172 char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL;
173 char *passin = NULL, *passout = NULL, *macalg = NULL;
174 char *cpass = NULL, *mpass = NULL, *badpass = NULL;
175 const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL, *prog;
176 int noCApath = 0, noCAfile = 0, noCAstore = 0;
178 BIO *in = NULL, *out = NULL;
180 STACK_OF(OPENSSL_STRING) *canames = NULL;
181 EVP_CIPHER *default_enc = (EVP_CIPHER *)EVP_aes_256_cbc();
182 EVP_CIPHER *enc = (EVP_CIPHER *)default_enc;
185 prog = opt_init(argc, argv, pkcs12_options);
186 while ((o = opt_next()) != OPT_EOF) {
191 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
194 opt_help(pkcs12_options);
216 options |= (NOKEYS | NOCERTS);
230 #ifndef OPENSSL_NO_DES
232 cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
241 * |enc_flag| stores the name of the option used so it
242 * can be printed if an error message is output.
244 enc_flag = opt_flag() + 1;
249 ciphername = opt_unknown();
250 enc_flag = opt_unknown();
253 maciter = iter = opt_int_arg();
272 if (!set_pbe(&cert_pbe, opt_arg()))
276 if (!set_pbe(&key_pbe, opt_arg()))
287 certfile = opt_arg();
290 untrusted = opt_arg();
293 passcertsarg = opt_arg();
302 csp_name = opt_arg();
306 && (canames = sk_OPENSSL_STRING_new_null()) == NULL)
308 sk_OPENSSL_STRING_push(canames, opt_arg());
317 passinarg = opt_arg();
320 passoutarg = opt_arg();
344 e = setup_engine(opt_arg(), 0);
346 #ifndef OPENSSL_NO_DES
352 if (!opt_provider(o))
358 /* No extra arguments. */
359 argc = opt_num_rest();
363 if (!app_RAND_load())
366 if (ciphername != NULL) {
367 if (!opt_cipher(ciphername, &enc))
371 if ((options & INFO) != 0)
374 WARN_EXPORT("nomacver");
375 if ((options & CLCERTS) != 0)
376 WARN_EXPORT("clcerts");
377 if ((options & CACERTS) != 0)
378 WARN_EXPORT("cacerts");
379 if (enc != default_enc)
381 "Warning: output encryption option -%s ignored with -export\n", enc_flag);
384 WARN_NO_EXPORT("inkey");
385 if (certfile != NULL)
386 WARN_NO_EXPORT("certfile");
387 if (passcertsarg != NULL)
388 WARN_NO_EXPORT("passcerts");
390 WARN_NO_EXPORT("chain");
391 if (untrusted != NULL)
392 WARN_NO_EXPORT("untrusted");
394 WARN_NO_EXPORT("CAfile");
396 WARN_NO_EXPORT("CApath");
398 WARN_NO_EXPORT("CAstore");
400 WARN_NO_EXPORT("no-CAfile");
402 WARN_NO_EXPORT("no-CApath");
404 WARN_NO_EXPORT("no-CAstore");
406 WARN_NO_EXPORT("name");
408 WARN_NO_EXPORT("caname");
409 if (csp_name != NULL)
410 WARN_NO_EXPORT("CSP");
412 WARN_NO_EXPORT("LMK");
413 if (keytype == KEY_EX)
414 WARN_NO_EXPORT("keyex");
415 if (keytype == KEY_SIG)
416 WARN_NO_EXPORT("keysig");
417 if (key_pbe != NID_undef)
418 WARN_NO_EXPORT("keypbe");
419 if (cert_pbe != NID_undef && cert_pbe != -1)
420 WARN_NO_EXPORT("certpbe and -descert");
422 WARN_NO_EXPORT("macalg");
424 WARN_NO_EXPORT("iter and -noiter");
426 WARN_NO_EXPORT("nomaciter");
427 if (cert_pbe == -1 && maciter == -1)
428 WARN_NO_EXPORT("nomac");
430 #ifndef OPENSSL_NO_DES
432 /* load the legacy provider if not loaded already*/
433 if (!OSSL_PROVIDER_available(app_get0_libctx(), "legacy")) {
434 if (!app_provider_load(app_get0_libctx(), "legacy"))
436 /* load the default provider explicitly */
437 if (!app_provider_load(app_get0_libctx(), "default"))
440 if (cert_pbe == NID_undef) {
441 /* Adapt default algorithm */
442 # ifndef OPENSSL_NO_RC2
443 cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
445 cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
449 if (key_pbe == NID_undef)
450 key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
451 if (enc == default_enc)
452 enc = (EVP_CIPHER *)EVP_des_ede3_cbc();
460 if (!app_passwd(passcertsarg, NULL, &passcerts, NULL)) {
461 BIO_printf(bio_err, "Error getting certificate file password\n");
465 if (passarg != NULL) {
467 passoutarg = passarg;
472 if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
473 BIO_printf(bio_err, "Error getting passwords\n");
489 BIO_printf(bio_err, "Option -twopass cannot be used with -passout or -password\n");
491 BIO_printf(bio_err, "Option -twopass cannot be used with -passin or -password\n");
500 /* To avoid bit rot */
502 #ifndef OPENSSL_NO_UI_CONSOLE
503 if (EVP_read_pw_string(
504 macpass, sizeof(macpass), "Enter MAC Password:", export_pkcs12)) {
505 BIO_printf(bio_err, "Can't read Password\n");
510 BIO_printf(bio_err, "Unsupported option -twopass\n");
516 EVP_PKEY *key = NULL;
517 X509 *ee_cert = NULL, *x = NULL;
518 STACK_OF(X509) *certs = NULL;
519 STACK_OF(X509) *untrusted_certs = NULL;
520 EVP_MD *macmd = NULL;
521 unsigned char *catmp = NULL;
524 if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
525 BIO_printf(bio_err, "Nothing to export due to -noout or -nocerts and -nokeys\n");
529 if ((options & NOCERTS) != 0) {
531 BIO_printf(bio_err, "Warning: -chain option ignored with -nocerts\n");
534 if (!(options & NOKEYS)) {
535 key = load_key(keyname ? keyname : infile,
536 FORMAT_PEM, 1, passin, e,
538 "private key from -inkey file" :
539 "private key from -in file");
544 /* Load all certs in input file */
545 if (!(options & NOCERTS)) {
546 if (!load_certs(infile, 1, &certs, passin,
547 "certificates from -in file"))
549 if (sk_X509_num(certs) < 1) {
550 BIO_printf(bio_err, "No certificate in -in file %s\n", infile);
555 /* Look for matching private key */
556 for (i = 0; i < sk_X509_num(certs); i++) {
557 x = sk_X509_value(certs, i);
558 if (X509_check_private_key(x, key)) {
560 /* Zero keyid and alias */
561 X509_keyid_set1(ee_cert, NULL, 0);
562 X509_alias_set1(ee_cert, NULL, 0);
563 /* Remove from list */
564 (void)sk_X509_delete(certs, i);
568 if (ee_cert == NULL) {
570 "No cert in -in file '%s' matches private key\n",
575 ee_cert = X509_dup(sk_X509_value(certs, 0)); /* take 1st cert */
579 /* Load any untrusted certificates for chain building */
580 if (untrusted != NULL) {
581 if (!load_certs(untrusted, 0, &untrusted_certs, passcerts,
582 "untrusted certificates"))
586 /* If chaining get chain from end entity cert */
589 STACK_OF(X509) *chain2;
592 if (ee_cert == NULL) {
594 "No end entity certificate to check with -chain\n");
598 if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
603 vret = get_cert_chain(ee_cert, store, untrusted_certs, &chain2);
604 X509_STORE_free(store);
606 if (vret == X509_V_OK) {
608 /* Remove from chain2 the first (end entity) certificate */
609 X509_free(sk_X509_shift(chain2));
610 /* Add the remaining certs (except for duplicates) */
611 add_certs = X509_add_certs(certs, chain2, X509_ADD_FLAG_UP_REF
612 | X509_ADD_FLAG_NO_DUP);
613 sk_X509_pop_free(chain2, X509_free);
617 if (vret != X509_V_ERR_UNSPECIFIED)
618 BIO_printf(bio_err, "Error getting chain: %s\n",
619 X509_verify_cert_error_string(vret));
624 /* Add any extra certificates asked for */
625 if (certfile != NULL) {
626 if (!load_certs(certfile, 0, &certs, passcerts,
627 "extra certificates from -certfile"))
631 /* Add any CA names */
632 for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
633 catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i);
634 X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
637 if (csp_name != NULL && key != NULL)
638 EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
639 MBSTRING_ASC, (unsigned char *)csp_name,
642 if (add_lmk && key != NULL)
643 EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);
645 if (!noprompt && !(enc == NULL && maciter == -1)) {
646 /* To avoid bit rot */
648 #ifndef OPENSSL_NO_UI_CONSOLE
649 if (EVP_read_pw_string(pass, sizeof(pass),
650 "Enter Export Password:", 1)) {
651 BIO_printf(bio_err, "Can't read Password\n");
656 BIO_printf(bio_err, "Password required\n");
662 OPENSSL_strlcpy(macpass, pass, sizeof(macpass));
664 p12 = PKCS12_create_ex(cpass, name, key, ee_cert, certs,
665 key_pbe, cert_pbe, iter, -1, keytype,
666 app_get0_libctx(), app_get0_propq());
669 BIO_printf(bio_err, "Error creating PKCS12 structure for %s\n",
674 if (macalg != NULL) {
675 if (!opt_md(macalg, &macmd))
680 if (!PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd)) {
681 BIO_printf(bio_err, "Error creating PKCS12 MAC; no PKCS12KDF support?\n");
682 BIO_printf(bio_err, "Use -nomac if MAC not required and PKCS12KDF support not available.\n");
688 out = bio_open_owner(outfile, FORMAT_PKCS12, private);
692 i2d_PKCS12_bio(out, p12);
700 sk_X509_pop_free(certs, X509_free);
701 sk_X509_pop_free(untrusted_certs, X509_free);
704 ERR_print_errors(bio_err);
709 in = bio_open_default(infile, 'r', FORMAT_PKCS12);
712 out = bio_open_owner(outfile, FORMAT_PEM, private);
716 p12 = PKCS12_init_ex(NID_pkcs7_data, app_get0_libctx(), app_get0_propq());
718 ERR_print_errors(bio_err);
721 if ((p12 = d2i_PKCS12_bio(in, &p12)) == NULL) {
722 ERR_print_errors(bio_err);
728 #ifndef OPENSSL_NO_UI_CONSOLE
729 if (EVP_read_pw_string(pass, sizeof(pass), "Enter Import Password:",
731 BIO_printf(bio_err, "Can't read Password\n");
736 BIO_printf(bio_err, "Password required\n");
742 OPENSSL_strlcpy(macpass, pass, sizeof(macpass));
744 if ((options & INFO) && PKCS12_mac_present(p12)) {
745 const ASN1_INTEGER *tmaciter;
746 const X509_ALGOR *macalgid;
747 const ASN1_OBJECT *macobj;
748 const ASN1_OCTET_STRING *tmac;
749 const ASN1_OCTET_STRING *tsalt;
751 PKCS12_get0_mac(&tmac, &macalgid, &tsalt, &tmaciter, p12);
752 /* current hash algorithms do not use parameters so extract just name,
753 in future alg_print() may be needed */
754 X509_ALGOR_get0(&macobj, NULL, NULL, macalgid);
755 BIO_puts(bio_err, "MAC: ");
756 i2a_ASN1_OBJECT(bio_err, macobj);
757 BIO_printf(bio_err, ", Iteration %ld\n",
758 tmaciter != NULL ? ASN1_INTEGER_get(tmaciter) : 1L);
759 BIO_printf(bio_err, "MAC length: %ld, salt length: %ld\n",
760 tmac != NULL ? ASN1_STRING_length(tmac) : 0L,
761 tsalt != NULL ? ASN1_STRING_length(tsalt) : 0L);
766 pkcs12kdf = EVP_KDF_fetch(NULL, "PKCS12KDF", NULL);
767 if (pkcs12kdf == NULL) {
768 BIO_printf(bio_err, "Error verifying PKCS12 MAC; no PKCS12KDF support.\n");
769 BIO_printf(bio_err, "Use -nomacver if MAC verification is not required.\n");
772 EVP_KDF_free(pkcs12kdf);
773 /* If we enter empty password try no password first */
774 if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
775 /* If mac and crypto pass the same set it to NULL too */
778 } else if (!PKCS12_verify_mac(p12, mpass, -1)) {
780 * May be UTF8 from previous version of OpenSSL:
781 * convert to a UTF8 form which will translate
782 * to the same Unicode password.
786 unsigned long err = ERR_peek_error();
788 if (ERR_GET_LIB(err) == ERR_LIB_PKCS12
789 && ERR_GET_REASON(err) == PKCS12_R_MAC_ABSENT) {
790 BIO_printf(bio_err, "Warning: MAC is absent!\n");
794 utmp = OPENSSL_asc2uni(mpass, -1, NULL, &utmplen);
797 badpass = OPENSSL_uni2utf8(utmp, utmplen);
799 if (!PKCS12_verify_mac(p12, badpass, -1)) {
800 BIO_printf(bio_err, "Mac verify error: invalid password?\n");
801 ERR_print_errors(bio_err);
804 BIO_printf(bio_err, "Warning: using broken algorithm\n");
813 if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) {
814 BIO_printf(bio_err, "Error outputting keys and certificates\n");
815 ERR_print_errors(bio_err);
824 sk_OPENSSL_STRING_free(canames);
825 OPENSSL_free(badpass);
826 OPENSSL_free(passcerts);
827 OPENSSL_free(passin);
828 OPENSSL_free(passout);
832 int dump_certs_keys_p12(BIO *out, const PKCS12 *p12, const char *pass,
833 int passlen, int options, char *pempass,
834 const EVP_CIPHER *enc)
836 STACK_OF(PKCS7) *asafes = NULL;
837 STACK_OF(PKCS12_SAFEBAG) *bags;
842 if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL)
844 for (i = 0; i < sk_PKCS7_num(asafes); i++) {
845 p7 = sk_PKCS7_value(asafes, i);
846 bagnid = OBJ_obj2nid(p7->type);
847 if (bagnid == NID_pkcs7_data) {
848 bags = PKCS12_unpack_p7data(p7);
850 BIO_printf(bio_err, "PKCS7 Data\n");
851 } else if (bagnid == NID_pkcs7_encrypted) {
852 if (options & INFO) {
853 BIO_printf(bio_err, "PKCS7 Encrypted data: ");
854 alg_print(p7->d.encrypted->enc_data->algorithm);
856 bags = PKCS12_unpack_p7encdata(p7, pass, passlen);
862 if (!dump_certs_pkeys_bags(out, bags, pass, passlen,
863 options, pempass, enc)) {
864 sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
867 sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
873 sk_PKCS7_pop_free(asafes, PKCS7_free);
877 int dump_certs_pkeys_bags(BIO *out, const STACK_OF(PKCS12_SAFEBAG) *bags,
878 const char *pass, int passlen, int options,
879 char *pempass, const EVP_CIPHER *enc)
882 for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) {
883 if (!dump_certs_pkeys_bag(out,
884 sk_PKCS12_SAFEBAG_value(bags, i),
885 pass, passlen, options, pempass, enc))
891 int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bag,
892 const char *pass, int passlen, int options,
893 char *pempass, const EVP_CIPHER *enc)
896 PKCS8_PRIV_KEY_INFO *p8;
897 const PKCS8_PRIV_KEY_INFO *p8c;
899 const STACK_OF(X509_ATTRIBUTE) *attrs;
902 attrs = PKCS12_SAFEBAG_get0_attrs(bag);
904 switch (PKCS12_SAFEBAG_get_nid(bag)) {
907 BIO_printf(bio_err, "Key bag\n");
908 if (options & NOKEYS)
910 print_attribs(out, attrs, "Bag Attributes");
911 p8c = PKCS12_SAFEBAG_get0_p8inf(bag);
912 if ((pkey = EVP_PKCS82PKEY(p8c)) == NULL)
914 print_attribs(out, PKCS8_pkey_get0_attrs(p8c), "Key Attributes");
915 ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
919 case NID_pkcs8ShroudedKeyBag:
920 if (options & INFO) {
922 const X509_ALGOR *tp8alg;
924 BIO_printf(bio_err, "Shrouded Keybag: ");
925 tp8 = PKCS12_SAFEBAG_get0_pkcs8(bag);
926 X509_SIG_get0(tp8, &tp8alg, NULL);
929 if (options & NOKEYS)
931 print_attribs(out, attrs, "Bag Attributes");
932 if ((p8 = PKCS12_decrypt_skey(bag, pass, passlen)) == NULL)
934 if ((pkey = EVP_PKCS82PKEY(p8)) == NULL) {
935 PKCS8_PRIV_KEY_INFO_free(p8);
938 print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes");
939 PKCS8_PRIV_KEY_INFO_free(p8);
940 ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
946 BIO_printf(bio_err, "Certificate bag\n");
947 if (options & NOCERTS)
949 if (PKCS12_SAFEBAG_get0_attr(bag, NID_localKeyID)) {
950 if (options & CACERTS)
952 } else if (options & CLCERTS)
954 print_attribs(out, attrs, "Bag Attributes");
955 if (PKCS12_SAFEBAG_get_bag_nid(bag) != NID_x509Certificate)
957 if ((x509 = PKCS12_SAFEBAG_get1_cert(bag)) == NULL)
959 dump_cert_text(out, x509);
960 ret = PEM_write_bio_X509(out, x509);
966 BIO_printf(bio_err, "Secret bag\n");
967 print_attribs(out, attrs, "Bag Attributes");
968 BIO_printf(bio_err, "Bag Type: ");
969 i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_bag_type(bag));
970 BIO_printf(bio_err, "\nBag Value: ");
971 print_attribute(out, PKCS12_SAFEBAG_get0_bag_obj(bag));
974 case NID_safeContentsBag:
976 BIO_printf(bio_err, "Safe Contents bag\n");
977 print_attribs(out, attrs, "Bag Attributes");
978 return dump_certs_pkeys_bags(out, PKCS12_SAFEBAG_get0_safes(bag),
979 pass, passlen, options, pempass, enc);
982 BIO_printf(bio_err, "Warning unsupported bag type: ");
983 i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_type(bag));
984 BIO_printf(bio_err, "\n");
990 /* Given a single certificate return a verified chain or NULL if error */
992 static int get_cert_chain(X509 *cert, X509_STORE *store,
993 STACK_OF(X509) *untrusted_certs,
994 STACK_OF(X509) **chain)
996 X509_STORE_CTX *store_ctx = NULL;
997 STACK_OF(X509) *chn = NULL;
1000 store_ctx = X509_STORE_CTX_new_ex(app_get0_libctx(), app_get0_propq());
1001 if (store_ctx == NULL) {
1002 i = X509_V_ERR_UNSPECIFIED;
1005 if (!X509_STORE_CTX_init(store_ctx, store, cert, untrusted_certs)) {
1006 i = X509_V_ERR_UNSPECIFIED;
1011 if (X509_verify_cert(store_ctx) > 0)
1012 chn = X509_STORE_CTX_get1_chain(store_ctx);
1013 else if ((i = X509_STORE_CTX_get_error(store_ctx)) == 0)
1014 i = X509_V_ERR_UNSPECIFIED;
1017 X509_STORE_CTX_free(store_ctx);
1022 static int alg_print(const X509_ALGOR *alg)
1024 int pbenid, aparamtype;
1025 const ASN1_OBJECT *aoid;
1027 PBEPARAM *pbe = NULL;
1029 X509_ALGOR_get0(&aoid, &aparamtype, &aparam, alg);
1031 pbenid = OBJ_obj2nid(aoid);
1033 BIO_printf(bio_err, "%s", OBJ_nid2ln(pbenid));
1036 * If PBE algorithm is PBES2 decode algorithm parameters
1037 * for additional details.
1039 if (pbenid == NID_pbes2) {
1040 PBE2PARAM *pbe2 = NULL;
1042 if (aparamtype == V_ASN1_SEQUENCE)
1043 pbe2 = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBE2PARAM));
1045 BIO_puts(bio_err, ", <unsupported parameters>");
1048 X509_ALGOR_get0(&aoid, &aparamtype, &aparam, pbe2->keyfunc);
1049 pbenid = OBJ_obj2nid(aoid);
1050 X509_ALGOR_get0(&aoid, NULL, NULL, pbe2->encryption);
1051 encnid = OBJ_obj2nid(aoid);
1052 BIO_printf(bio_err, ", %s, %s", OBJ_nid2ln(pbenid),
1053 OBJ_nid2sn(encnid));
1054 /* If KDF is PBKDF2 decode parameters */
1055 if (pbenid == NID_id_pbkdf2) {
1056 PBKDF2PARAM *kdf = NULL;
1058 if (aparamtype == V_ASN1_SEQUENCE)
1059 kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBKDF2PARAM));
1061 BIO_puts(bio_err, ", <unsupported parameters>");
1065 if (kdf->prf == NULL) {
1066 prfnid = NID_hmacWithSHA1;
1068 X509_ALGOR_get0(&aoid, NULL, NULL, kdf->prf);
1069 prfnid = OBJ_obj2nid(aoid);
1071 BIO_printf(bio_err, ", Iteration %ld, PRF %s",
1072 ASN1_INTEGER_get(kdf->iter), OBJ_nid2sn(prfnid));
1073 PBKDF2PARAM_free(kdf);
1074 #ifndef OPENSSL_NO_SCRYPT
1075 } else if (pbenid == NID_id_scrypt) {
1076 SCRYPT_PARAMS *kdf = NULL;
1078 if (aparamtype == V_ASN1_SEQUENCE)
1079 kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(SCRYPT_PARAMS));
1081 BIO_puts(bio_err, ", <unsupported parameters>");
1084 BIO_printf(bio_err, ", Salt length: %d, Cost(N): %ld, "
1085 "Block size(r): %ld, Parallelism(p): %ld",
1086 ASN1_STRING_length(kdf->salt),
1087 ASN1_INTEGER_get(kdf->costParameter),
1088 ASN1_INTEGER_get(kdf->blockSize),
1089 ASN1_INTEGER_get(kdf->parallelizationParameter));
1090 SCRYPT_PARAMS_free(kdf);
1093 PBE2PARAM_free(pbe2);
1095 if (aparamtype == V_ASN1_SEQUENCE)
1096 pbe = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBEPARAM));
1098 BIO_puts(bio_err, ", <unsupported parameters>");
1101 BIO_printf(bio_err, ", Iteration %ld", ASN1_INTEGER_get(pbe->iter));
1105 BIO_puts(bio_err, "\n");
1109 /* Load all certificates from a given file */
1111 int cert_load(BIO *in, STACK_OF(X509) *sk)
1116 while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
1118 if (!sk_X509_push(sk, cert))
1126 /* Generalised x509 attribute value print */
1128 void print_attribute(BIO *out, const ASN1_TYPE *av)
1133 case V_ASN1_BMPSTRING:
1134 value = OPENSSL_uni2asc(av->value.bmpstring->data,
1135 av->value.bmpstring->length);
1136 BIO_printf(out, "%s\n", value);
1137 OPENSSL_free(value);
1140 case V_ASN1_UTF8STRING:
1141 BIO_printf(out, "%s\n", av->value.utf8string->data);
1144 case V_ASN1_OCTET_STRING:
1145 hex_prin(out, av->value.octet_string->data,
1146 av->value.octet_string->length);
1147 BIO_printf(out, "\n");
1150 case V_ASN1_BIT_STRING:
1151 hex_prin(out, av->value.bit_string->data,
1152 av->value.bit_string->length);
1153 BIO_printf(out, "\n");
1157 BIO_printf(out, "<Unsupported tag %d>\n", av->type);
1162 /* Generalised attribute print: handle PKCS#8 and bag attributes */
1164 int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst,
1167 X509_ATTRIBUTE *attr;
1171 BIO_printf(out, "%s: <No Attributes>\n", name);
1174 if (!sk_X509_ATTRIBUTE_num(attrlst)) {
1175 BIO_printf(out, "%s: <Empty Attributes>\n", name);
1178 BIO_printf(out, "%s\n", name);
1179 for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) {
1180 ASN1_OBJECT *attr_obj;
1181 attr = sk_X509_ATTRIBUTE_value(attrlst, i);
1182 attr_obj = X509_ATTRIBUTE_get0_object(attr);
1183 attr_nid = OBJ_obj2nid(attr_obj);
1184 BIO_printf(out, " ");
1185 if (attr_nid == NID_undef) {
1186 i2a_ASN1_OBJECT(out, attr_obj);
1187 BIO_printf(out, ": ");
1189 BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
1192 if (X509_ATTRIBUTE_count(attr)) {
1193 for (j = 0; j < X509_ATTRIBUTE_count(attr); j++)
1195 av = X509_ATTRIBUTE_get0_type(attr, j);
1196 print_attribute(out, av);
1199 BIO_printf(out, "<No Values>\n");
1205 void hex_prin(BIO *out, unsigned char *buf, int len)
1208 for (i = 0; i < len; i++)
1209 BIO_printf(out, "%02X ", buf[i]);
1212 static int set_pbe(int *ppbe, const char *str)
1216 if (strcmp(str, "NONE") == 0) {
1220 *ppbe = OBJ_txt2nid(str);
1221 if (*ppbe == NID_undef) {
1222 BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str);