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
31 #define PKCS12_DEFAULT_PBE NID_aes_256_cbc
33 #define WARN_EXPORT(opt) \
34 BIO_printf(bio_err, "Warning: -%s option ignored with -export\n", opt);
35 #define WARN_NO_EXPORT(opt) \
36 BIO_printf(bio_err, "Warning: -%s option ignored without -export\n", opt);
38 static int get_cert_chain(X509 *cert, X509_STORE *store,
39 STACK_OF(X509) *untrusted_certs,
40 STACK_OF(X509) **chain);
41 int dump_certs_keys_p12(BIO *out, const PKCS12 *p12,
42 const char *pass, int passlen, int options,
43 char *pempass, const EVP_CIPHER *enc);
44 int dump_certs_pkeys_bags(BIO *out, const STACK_OF(PKCS12_SAFEBAG) *bags,
45 const char *pass, int passlen, int options,
46 char *pempass, const EVP_CIPHER *enc);
47 int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bags,
48 const char *pass, int passlen,
49 int options, char *pempass, const EVP_CIPHER *enc);
50 void print_attribute(BIO *out, const ASN1_TYPE *av);
51 int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst,
53 void hex_prin(BIO *out, unsigned char *buf, int len);
54 static int alg_print(const X509_ALGOR *alg);
55 int cert_load(BIO *in, STACK_OF(X509) *sk);
56 static int set_pbe(int *ppbe, const char *str);
58 typedef enum OPTION_choice {
59 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
60 OPT_CIPHER, OPT_NOKEYS, OPT_KEYEX, OPT_KEYSIG, OPT_NOCERTS, OPT_CLCERTS,
61 OPT_CACERTS, OPT_NOOUT, OPT_INFO, OPT_CHAIN, OPT_TWOPASS, OPT_NOMACVER,
62 OPT_DESCERT, OPT_EXPORT, OPT_ITER, OPT_NOITER, OPT_MACITER, OPT_NOMACITER,
63 OPT_NOMAC, OPT_LMK, OPT_NODES, OPT_NOENC, OPT_MACALG, OPT_CERTPBE, OPT_KEYPBE,
64 OPT_INKEY, OPT_CERTFILE, OPT_UNTRUSTED, OPT_PASSCERTS,
65 OPT_NAME, OPT_CSP, OPT_CANAME,
66 OPT_IN, OPT_OUT, OPT_PASSIN, OPT_PASSOUT, OPT_PASSWORD, OPT_CAPATH,
67 OPT_CAFILE, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_ENGINE,
68 OPT_R_ENUM, OPT_PROV_ENUM, OPT_LEGACY_ALG
71 const OPTIONS pkcs12_options[] = {
72 OPT_SECTION("General"),
73 {"help", OPT_HELP, '-', "Display this summary"},
74 {"in", OPT_IN, '<', "Input file"},
75 {"out", OPT_OUT, '>', "Output file"},
76 {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
77 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
78 {"password", OPT_PASSWORD, 's', "Set PKCS#12 import/export password source"},
79 {"twopass", OPT_TWOPASS, '-', "Separate MAC, encryption passwords"},
80 {"nokeys", OPT_NOKEYS, '-', "Don't output private keys"},
81 {"nocerts", OPT_NOCERTS, '-', "Don't output certificates"},
82 {"noout", OPT_NOOUT, '-', "Don't output anything, just verify PKCS#12 input"},
83 {"legacy", OPT_LEGACY_ALG, '-',
85 "Use legacy encryption algorithm 3DES_CBC for keys and certs"
87 "Use legacy encryption: 3DES_CBC for keys, RC2_CBC for certs"
90 #ifndef OPENSSL_NO_ENGINE
91 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
96 OPT_SECTION("PKCS#12 import (parsing PKCS#12)"),
97 {"info", OPT_INFO, '-', "Print info about PKCS#12 structure"},
98 {"nomacver", OPT_NOMACVER, '-', "Don't verify integrity MAC"},
99 {"clcerts", OPT_CLCERTS, '-', "Only output client certificates"},
100 {"cacerts", OPT_CACERTS, '-', "Only output CA certificates"},
101 {"", OPT_CIPHER, '-', "Any supported cipher for output encryption"},
102 {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"},
103 {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"},
105 OPT_SECTION("PKCS#12 output (export)"),
106 {"export", OPT_EXPORT, '-', "Create PKCS12 file"},
107 {"inkey", OPT_INKEY, 's', "Private key, else read from -in input file"},
108 {"certfile", OPT_CERTFILE, '<', "Extra certificates for PKCS12 output"},
109 {"passcerts", OPT_PASSCERTS, 's', "Certificate file pass phrase source"},
110 {"chain", OPT_CHAIN, '-', "Build and add certificate chain for EE cert,"},
112 "which is the 1st cert from -in matching the privte key (if given)"},
113 {"untrusted", OPT_UNTRUSTED, '<', "Untrusted certificates for chain building"},
114 {"CAfile", OPT_CAFILE, '<', "PEM-format file of CA's"},
115 {"CApath", OPT_CAPATH, '/', "PEM-format directory of CA's"},
116 {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
117 {"no-CAfile", OPT_NOCAFILE, '-',
118 "Do not load the default certificates file"},
119 {"no-CApath", OPT_NOCAPATH, '-',
120 "Do not load certificates from the default certificates directory"},
121 {"no-CAstore", OPT_NOCASTORE, '-',
122 "Do not load certificates from the default certificates store"},
123 {"name", OPT_NAME, 's', "Use name as friendly name"},
124 {"caname", OPT_CANAME, 's',
125 "Use name as CA friendly name (can be repeated)"},
126 {"CSP", OPT_CSP, 's', "Microsoft CSP name"},
127 {"LMK", OPT_LMK, '-',
128 "Add local machine keyset attribute to private key"},
129 {"keyex", OPT_KEYEX, '-', "Set key type to MS key exchange"},
130 {"keysig", OPT_KEYSIG, '-', "Set key type to MS key signature"},
131 {"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default AES-256 CBC)"},
132 {"certpbe", OPT_CERTPBE, 's',
133 "Certificate PBE algorithm (default PBES2 with PBKDF2 and AES-256 CBC)"},
134 {"descert", OPT_DESCERT, '-',
135 "Encrypt output with 3DES (default PBES2 with PBKDF2 and AES-256 CBC)"},
136 {"macalg", OPT_MACALG, 's',
137 "Digest algorithm to use in MAC (default SHA1)"},
138 {"iter", OPT_ITER, 'p', "Specify the iteration count for encryption and MAC"},
139 {"noiter", OPT_NOITER, '-', "Don't use encryption iteration"},
140 {"nomaciter", OPT_NOMACITER, '-', "Don't use MAC iteration)"},
141 {"maciter", OPT_MACITER, '-', "Unused, kept for backwards compatibility"},
142 {"nomac", OPT_NOMAC, '-', "Don't generate MAC"},
146 int pkcs12_main(int argc, char **argv)
148 char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL;
149 char *untrusted = NULL, *ciphername = NULL, *enc_flag = NULL;
150 char *passcertsarg = NULL, *passcerts = NULL;
151 char *name = NULL, *csp_name = NULL;
152 char pass[PASSWD_BUF_SIZE] = "", macpass[PASSWD_BUF_SIZE] = "";
153 int export_pkcs12 = 0, options = 0, chain = 0, twopass = 0, keytype = 0, use_legacy = 0;
154 int iter = PKCS12_DEFAULT_ITER, maciter = PKCS12_DEFAULT_ITER;
155 int cert_pbe = PKCS12_DEFAULT_PBE;
156 int key_pbe = PKCS12_DEFAULT_PBE;
157 int ret = 1, macver = 1, add_lmk = 0, private = 0;
159 char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL;
160 char *passin = NULL, *passout = NULL, *macalg = NULL;
161 char *cpass = NULL, *mpass = NULL, *badpass = NULL;
162 const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL, *prog;
163 int noCApath = 0, noCAfile = 0, noCAstore = 0;
165 BIO *in = NULL, *out = NULL;
167 STACK_OF(OPENSSL_STRING) *canames = NULL;
168 const EVP_CIPHER *const default_enc = EVP_aes_256_cbc();
169 const EVP_CIPHER *enc = default_enc;
172 prog = opt_init(argc, argv, pkcs12_options);
173 while ((o = opt_next()) != OPT_EOF) {
178 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
181 opt_help(pkcs12_options);
203 options |= (NOKEYS | NOCERTS);
218 cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
226 * |enc_flag| stores the name of the option used so it
227 * can be printed if an error message is output.
229 enc_flag = opt_flag() + 1;
234 ciphername = opt_unknown();
235 enc_flag = opt_unknown();
238 if (!opt_int(opt_arg(), &iter))
259 if (!set_pbe(&cert_pbe, opt_arg()))
263 if (!set_pbe(&key_pbe, opt_arg()))
274 certfile = opt_arg();
277 untrusted = opt_arg();
280 passcertsarg = opt_arg();
289 csp_name = opt_arg();
293 && (canames = sk_OPENSSL_STRING_new_null()) == NULL)
295 sk_OPENSSL_STRING_push(canames, opt_arg());
304 passinarg = opt_arg();
307 passoutarg = opt_arg();
331 e = setup_engine(opt_arg(), 0);
337 if (!opt_provider(o))
343 /* No extra arguments. */
344 argc = opt_num_rest();
349 if (ciphername != NULL) {
350 if (!opt_cipher(ciphername, &enc))
354 if ((options & INFO) != 0)
357 WARN_EXPORT("nomacver");
358 if ((options & CLCERTS) != 0)
359 WARN_EXPORT("clcerts");
360 if ((options & CACERTS) != 0)
361 WARN_EXPORT("cacerts");
362 if (enc != default_enc)
364 "Warning: output encryption option -%s ignored with -export\n", enc_flag);
367 WARN_NO_EXPORT("inkey");
368 if (certfile != NULL)
369 WARN_NO_EXPORT("certfile");
370 if (passcertsarg != NULL)
371 WARN_NO_EXPORT("passcerts");
373 WARN_NO_EXPORT("chain");
374 if (untrusted != NULL)
375 WARN_NO_EXPORT("untrusted");
377 WARN_NO_EXPORT("CAfile");
379 WARN_NO_EXPORT("CApath");
381 WARN_NO_EXPORT("CAstore");
383 WARN_NO_EXPORT("no-CAfile");
385 WARN_NO_EXPORT("no-CApath");
387 WARN_NO_EXPORT("no-CAstore");
389 WARN_NO_EXPORT("name");
391 WARN_NO_EXPORT("caname");
392 if (csp_name != NULL)
393 WARN_NO_EXPORT("CSP");
395 WARN_NO_EXPORT("LMK");
396 if (keytype == KEY_EX)
397 WARN_NO_EXPORT("keyex");
398 if (keytype == KEY_SIG)
399 WARN_NO_EXPORT("keysig");
400 if (key_pbe != PKCS12_DEFAULT_PBE)
401 WARN_NO_EXPORT("keypbe");
402 if (cert_pbe != PKCS12_DEFAULT_PBE && cert_pbe != -1)
403 WARN_NO_EXPORT("certpbe and -descert");
405 WARN_NO_EXPORT("macalg");
406 if (iter != PKCS12_DEFAULT_ITER)
407 WARN_NO_EXPORT("iter and -noiter");
409 WARN_NO_EXPORT("nomaciter");
410 if (cert_pbe == -1 && maciter == -1)
411 WARN_NO_EXPORT("nomac");
414 /* load the legacy provider if not loaded already*/
415 if (!OSSL_PROVIDER_available(app_get0_libctx(), "legacy")) {
416 if (!app_provider_load(app_get0_libctx(), "legacy"))
418 /* load the default provider explicitly */
419 if (!app_provider_load(app_get0_libctx(), "default"))
422 if (cert_pbe == PKCS12_DEFAULT_PBE) {
423 /* Adapt default algorithm */
424 #ifndef OPENSSL_NO_RC2
425 cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
427 cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
431 if (key_pbe == PKCS12_DEFAULT_PBE)
432 key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
433 if (enc == default_enc)
434 enc = EVP_des_ede3_cbc();
440 if (!app_passwd(passcertsarg, NULL, &passcerts, NULL)) {
441 BIO_printf(bio_err, "Error getting certificate file password\n");
445 if (passarg != NULL) {
447 passoutarg = passarg;
452 if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
453 BIO_printf(bio_err, "Error getting passwords\n");
469 BIO_printf(bio_err, "Option -twopass cannot be used with -passout or -password\n");
471 BIO_printf(bio_err, "Option -twopass cannot be used with -passin or -password\n");
480 /* To avoid bit rot */
482 #ifndef OPENSSL_NO_UI_CONSOLE
483 if (EVP_read_pw_string(
484 macpass, sizeof(macpass), "Enter MAC Password:", export_pkcs12)) {
485 BIO_printf(bio_err, "Can't read Password\n");
490 BIO_printf(bio_err, "Unsupported option -twopass\n");
496 EVP_PKEY *key = NULL;
497 X509 *ee_cert = NULL, *x = NULL;
498 STACK_OF(X509) *certs = NULL;
499 STACK_OF(X509) *untrusted_certs = NULL;
500 const EVP_MD *macmd = NULL;
501 unsigned char *catmp = NULL;
504 if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
505 BIO_printf(bio_err, "Nothing to export due to -noout or -nocerts and -nokeys\n");
509 if ((options & NOCERTS) != 0) {
511 BIO_printf(bio_err, "Warning: -chain option ignored with -nocerts\n");
514 if (!(options & NOKEYS)) {
515 key = load_key(keyname ? keyname : infile,
516 FORMAT_PEM, 1, passin, e,
518 "private key from -inkey file" :
519 "private key from -in file");
524 /* Load all certs in input file */
525 if (!(options & NOCERTS)) {
526 if (!load_certs(infile, &certs, passin,
527 "certificates from -in file"))
529 if (sk_X509_num(certs) < 1) {
530 BIO_printf(bio_err, "No certificate in -in file %s\n", infile);
535 /* Look for matching private key */
536 for (i = 0; i < sk_X509_num(certs); i++) {
537 x = sk_X509_value(certs, i);
538 if (X509_check_private_key(x, key)) {
540 /* Zero keyid and alias */
541 X509_keyid_set1(ee_cert, NULL, 0);
542 X509_alias_set1(ee_cert, NULL, 0);
543 /* Remove from list */
544 (void)sk_X509_delete(certs, i);
548 if (ee_cert == NULL) {
550 "No cert in -in file '%s' matches private key\n",
555 ee_cert = X509_dup(sk_X509_value(certs, 0)); /* take 1st cert */
559 /* Load any untrusted certificates for chain building */
560 if (untrusted != NULL) {
561 if (!load_certs(untrusted, &untrusted_certs, passcerts,
562 "untrusted certificates"))
566 /* If chaining get chain from end entity cert */
569 STACK_OF(X509) *chain2;
572 if (ee_cert == NULL) {
574 "No end entity certificate to check with -chain\n");
578 if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
583 vret = get_cert_chain(ee_cert, store, untrusted_certs, &chain2);
584 X509_STORE_free(store);
586 if (vret == X509_V_OK) {
588 /* Remove from chain2 the first (end entity) certificate */
589 X509_free(sk_X509_shift(chain2));
590 /* Add the remaining certs (except for duplicates) */
591 add_certs = X509_add_certs(certs, chain2, X509_ADD_FLAG_UP_REF
592 | X509_ADD_FLAG_NO_DUP);
593 sk_X509_pop_free(chain2, X509_free);
597 if (vret != X509_V_ERR_UNSPECIFIED)
598 BIO_printf(bio_err, "Error getting chain: %s\n",
599 X509_verify_cert_error_string(vret));
604 /* Add any extra certificates asked for */
605 if (certfile != NULL) {
606 if (!load_certs(certfile, &certs, passcerts,
607 "extra certificates from -certfile"))
611 /* Add any CA names */
612 for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
613 catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i);
614 X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
617 if (csp_name != NULL && key != NULL)
618 EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
619 MBSTRING_ASC, (unsigned char *)csp_name,
622 if (add_lmk && key != NULL)
623 EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);
625 if (!noprompt && !(enc == NULL && maciter == -1)) {
626 /* To avoid bit rot */
628 #ifndef OPENSSL_NO_UI_CONSOLE
629 if (EVP_read_pw_string(pass, sizeof(pass),
630 "Enter Export Password:", 1)) {
631 BIO_printf(bio_err, "Can't read Password\n");
636 BIO_printf(bio_err, "Password required\n");
642 OPENSSL_strlcpy(macpass, pass, sizeof(macpass));
644 p12 = PKCS12_create(cpass, name, key, ee_cert, certs,
645 key_pbe, cert_pbe, iter, -1, keytype);
648 BIO_printf(bio_err, "Error creating PKCS12 structure for %s\n",
653 if (macalg != NULL) {
654 if (!opt_md(macalg, &macmd))
659 if (!PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd)) {
660 BIO_printf(bio_err, "Error creating PKCS12 MAC; no PKCS12KDF support?\n");
661 BIO_printf(bio_err, "Use -nomac if MAC not required and PKCS12KDF support not available.\n");
667 out = bio_open_owner(outfile, FORMAT_PKCS12, private);
671 i2d_PKCS12_bio(out, p12);
678 sk_X509_pop_free(certs, X509_free);
679 sk_X509_pop_free(untrusted_certs, X509_free);
682 ERR_print_errors(bio_err);
687 in = bio_open_default(infile, 'r', FORMAT_PKCS12);
690 out = bio_open_owner(outfile, FORMAT_PEM, private);
694 if ((p12 = d2i_PKCS12_bio(in, NULL)) == NULL) {
695 ERR_print_errors(bio_err);
701 #ifndef OPENSSL_NO_UI_CONSOLE
702 if (EVP_read_pw_string(pass, sizeof(pass), "Enter Import Password:",
704 BIO_printf(bio_err, "Can't read Password\n");
709 BIO_printf(bio_err, "Password required\n");
715 OPENSSL_strlcpy(macpass, pass, sizeof(macpass));
717 if ((options & INFO) && PKCS12_mac_present(p12)) {
718 const ASN1_INTEGER *tmaciter;
719 const X509_ALGOR *macalgid;
720 const ASN1_OBJECT *macobj;
721 const ASN1_OCTET_STRING *tmac;
722 const ASN1_OCTET_STRING *tsalt;
724 PKCS12_get0_mac(&tmac, &macalgid, &tsalt, &tmaciter, p12);
725 /* current hash algorithms do not use parameters so extract just name,
726 in future alg_print() may be needed */
727 X509_ALGOR_get0(&macobj, NULL, NULL, macalgid);
728 BIO_puts(bio_err, "MAC: ");
729 i2a_ASN1_OBJECT(bio_err, macobj);
730 BIO_printf(bio_err, ", Iteration %ld\n",
731 tmaciter != NULL ? ASN1_INTEGER_get(tmaciter) : 1L);
732 BIO_printf(bio_err, "MAC length: %ld, salt length: %ld\n",
733 tmac != NULL ? ASN1_STRING_length(tmac) : 0L,
734 tsalt != NULL ? ASN1_STRING_length(tsalt) : 0L);
739 pkcs12kdf = EVP_KDF_fetch(NULL, "PKCS12KDF", NULL);
740 if (pkcs12kdf == NULL) {
741 BIO_printf(bio_err, "Error verifying PKCS12 MAC; no PKCS12KDF support.\n");
742 BIO_printf(bio_err, "Use -nomacver if MAC verification is not required.\n");
745 EVP_KDF_free(pkcs12kdf);
746 /* If we enter empty password try no password first */
747 if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
748 /* If mac and crypto pass the same set it to NULL too */
751 } else if (!PKCS12_verify_mac(p12, mpass, -1)) {
753 * May be UTF8 from previous version of OpenSSL:
754 * convert to a UTF8 form which will translate
755 * to the same Unicode password.
759 unsigned long err = ERR_peek_error();
761 if (ERR_GET_LIB(err) == ERR_LIB_PKCS12
762 && ERR_GET_REASON(err) == PKCS12_R_MAC_ABSENT) {
763 BIO_printf(bio_err, "Warning: MAC is absent!\n");
767 utmp = OPENSSL_asc2uni(mpass, -1, NULL, &utmplen);
770 badpass = OPENSSL_uni2utf8(utmp, utmplen);
772 if (!PKCS12_verify_mac(p12, badpass, -1)) {
773 BIO_printf(bio_err, "Mac verify error: invalid password?\n");
774 ERR_print_errors(bio_err);
777 BIO_printf(bio_err, "Warning: using broken algorithm\n");
786 if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) {
787 BIO_printf(bio_err, "Error outputting keys and certificates\n");
788 ERR_print_errors(bio_err);
797 sk_OPENSSL_STRING_free(canames);
798 OPENSSL_free(badpass);
799 OPENSSL_free(passcerts);
800 OPENSSL_free(passin);
801 OPENSSL_free(passout);
805 int dump_certs_keys_p12(BIO *out, const PKCS12 *p12, const char *pass,
806 int passlen, int options, char *pempass,
807 const EVP_CIPHER *enc)
809 STACK_OF(PKCS7) *asafes = NULL;
810 STACK_OF(PKCS12_SAFEBAG) *bags;
815 if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL)
817 for (i = 0; i < sk_PKCS7_num(asafes); i++) {
818 p7 = sk_PKCS7_value(asafes, i);
819 bagnid = OBJ_obj2nid(p7->type);
820 if (bagnid == NID_pkcs7_data) {
821 bags = PKCS12_unpack_p7data(p7);
823 BIO_printf(bio_err, "PKCS7 Data\n");
824 } else if (bagnid == NID_pkcs7_encrypted) {
825 if (options & INFO) {
826 BIO_printf(bio_err, "PKCS7 Encrypted data: ");
827 alg_print(p7->d.encrypted->enc_data->algorithm);
829 bags = PKCS12_unpack_p7encdata(p7, pass, passlen);
835 if (!dump_certs_pkeys_bags(out, bags, pass, passlen,
836 options, pempass, enc)) {
837 sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
840 sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
846 sk_PKCS7_pop_free(asafes, PKCS7_free);
850 int dump_certs_pkeys_bags(BIO *out, const STACK_OF(PKCS12_SAFEBAG) *bags,
851 const char *pass, int passlen, int options,
852 char *pempass, const EVP_CIPHER *enc)
855 for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) {
856 if (!dump_certs_pkeys_bag(out,
857 sk_PKCS12_SAFEBAG_value(bags, i),
858 pass, passlen, options, pempass, enc))
864 int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bag,
865 const char *pass, int passlen, int options,
866 char *pempass, const EVP_CIPHER *enc)
869 PKCS8_PRIV_KEY_INFO *p8;
870 const PKCS8_PRIV_KEY_INFO *p8c;
872 const STACK_OF(X509_ATTRIBUTE) *attrs;
875 attrs = PKCS12_SAFEBAG_get0_attrs(bag);
877 switch (PKCS12_SAFEBAG_get_nid(bag)) {
880 BIO_printf(bio_err, "Key bag\n");
881 if (options & NOKEYS)
883 print_attribs(out, attrs, "Bag Attributes");
884 p8c = PKCS12_SAFEBAG_get0_p8inf(bag);
885 if ((pkey = EVP_PKCS82PKEY(p8c)) == NULL)
887 print_attribs(out, PKCS8_pkey_get0_attrs(p8c), "Key Attributes");
888 ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
892 case NID_pkcs8ShroudedKeyBag:
893 if (options & INFO) {
895 const X509_ALGOR *tp8alg;
897 BIO_printf(bio_err, "Shrouded Keybag: ");
898 tp8 = PKCS12_SAFEBAG_get0_pkcs8(bag);
899 X509_SIG_get0(tp8, &tp8alg, NULL);
902 if (options & NOKEYS)
904 print_attribs(out, attrs, "Bag Attributes");
905 if ((p8 = PKCS12_decrypt_skey(bag, pass, passlen)) == NULL)
907 if ((pkey = EVP_PKCS82PKEY(p8)) == NULL) {
908 PKCS8_PRIV_KEY_INFO_free(p8);
911 print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes");
912 PKCS8_PRIV_KEY_INFO_free(p8);
913 ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
919 BIO_printf(bio_err, "Certificate bag\n");
920 if (options & NOCERTS)
922 if (PKCS12_SAFEBAG_get0_attr(bag, NID_localKeyID)) {
923 if (options & CACERTS)
925 } else if (options & CLCERTS)
927 print_attribs(out, attrs, "Bag Attributes");
928 if (PKCS12_SAFEBAG_get_bag_nid(bag) != NID_x509Certificate)
930 if ((x509 = PKCS12_SAFEBAG_get1_cert(bag)) == NULL)
932 dump_cert_text(out, x509);
933 ret = PEM_write_bio_X509(out, x509);
939 BIO_printf(bio_err, "Secret bag\n");
940 print_attribs(out, attrs, "Bag Attributes");
941 BIO_printf(bio_err, "Bag Type: ");
942 i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_bag_type(bag));
943 BIO_printf(bio_err, "\nBag Value: ");
944 print_attribute(out, PKCS12_SAFEBAG_get0_bag_obj(bag));
947 case NID_safeContentsBag:
949 BIO_printf(bio_err, "Safe Contents bag\n");
950 print_attribs(out, attrs, "Bag Attributes");
951 return dump_certs_pkeys_bags(out, PKCS12_SAFEBAG_get0_safes(bag),
952 pass, passlen, options, pempass, enc);
955 BIO_printf(bio_err, "Warning unsupported bag type: ");
956 i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_type(bag));
957 BIO_printf(bio_err, "\n");
963 /* Given a single certificate return a verified chain or NULL if error */
965 static int get_cert_chain(X509 *cert, X509_STORE *store,
966 STACK_OF(X509) *untrusted_certs,
967 STACK_OF(X509) **chain)
969 X509_STORE_CTX *store_ctx = NULL;
970 STACK_OF(X509) *chn = NULL;
973 store_ctx = X509_STORE_CTX_new_ex(app_get0_libctx(), app_get0_propq());
974 if (store_ctx == NULL) {
975 i = X509_V_ERR_UNSPECIFIED;
978 if (!X509_STORE_CTX_init(store_ctx, store, cert, untrusted_certs)) {
979 i = X509_V_ERR_UNSPECIFIED;
984 if (X509_verify_cert(store_ctx) > 0)
985 chn = X509_STORE_CTX_get1_chain(store_ctx);
986 else if ((i = X509_STORE_CTX_get_error(store_ctx)) == 0)
987 i = X509_V_ERR_UNSPECIFIED;
990 X509_STORE_CTX_free(store_ctx);
995 static int alg_print(const X509_ALGOR *alg)
997 int pbenid, aparamtype;
998 const ASN1_OBJECT *aoid;
1000 PBEPARAM *pbe = NULL;
1002 X509_ALGOR_get0(&aoid, &aparamtype, &aparam, alg);
1004 pbenid = OBJ_obj2nid(aoid);
1006 BIO_printf(bio_err, "%s", OBJ_nid2ln(pbenid));
1009 * If PBE algorithm is PBES2 decode algorithm parameters
1010 * for additional details.
1012 if (pbenid == NID_pbes2) {
1013 PBE2PARAM *pbe2 = NULL;
1015 if (aparamtype == V_ASN1_SEQUENCE)
1016 pbe2 = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBE2PARAM));
1018 BIO_puts(bio_err, ", <unsupported parameters>");
1021 X509_ALGOR_get0(&aoid, &aparamtype, &aparam, pbe2->keyfunc);
1022 pbenid = OBJ_obj2nid(aoid);
1023 X509_ALGOR_get0(&aoid, NULL, NULL, pbe2->encryption);
1024 encnid = OBJ_obj2nid(aoid);
1025 BIO_printf(bio_err, ", %s, %s", OBJ_nid2ln(pbenid),
1026 OBJ_nid2sn(encnid));
1027 /* If KDF is PBKDF2 decode parameters */
1028 if (pbenid == NID_id_pbkdf2) {
1029 PBKDF2PARAM *kdf = NULL;
1031 if (aparamtype == V_ASN1_SEQUENCE)
1032 kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBKDF2PARAM));
1034 BIO_puts(bio_err, ", <unsupported parameters>");
1038 if (kdf->prf == NULL) {
1039 prfnid = NID_hmacWithSHA1;
1041 X509_ALGOR_get0(&aoid, NULL, NULL, kdf->prf);
1042 prfnid = OBJ_obj2nid(aoid);
1044 BIO_printf(bio_err, ", Iteration %ld, PRF %s",
1045 ASN1_INTEGER_get(kdf->iter), OBJ_nid2sn(prfnid));
1046 PBKDF2PARAM_free(kdf);
1047 #ifndef OPENSSL_NO_SCRYPT
1048 } else if (pbenid == NID_id_scrypt) {
1049 SCRYPT_PARAMS *kdf = NULL;
1051 if (aparamtype == V_ASN1_SEQUENCE)
1052 kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(SCRYPT_PARAMS));
1054 BIO_puts(bio_err, ", <unsupported parameters>");
1057 BIO_printf(bio_err, ", Salt length: %d, Cost(N): %ld, "
1058 "Block size(r): %ld, Parallelism(p): %ld",
1059 ASN1_STRING_length(kdf->salt),
1060 ASN1_INTEGER_get(kdf->costParameter),
1061 ASN1_INTEGER_get(kdf->blockSize),
1062 ASN1_INTEGER_get(kdf->parallelizationParameter));
1063 SCRYPT_PARAMS_free(kdf);
1066 PBE2PARAM_free(pbe2);
1068 if (aparamtype == V_ASN1_SEQUENCE)
1069 pbe = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBEPARAM));
1071 BIO_puts(bio_err, ", <unsupported parameters>");
1074 BIO_printf(bio_err, ", Iteration %ld", ASN1_INTEGER_get(pbe->iter));
1078 BIO_puts(bio_err, "\n");
1082 /* Load all certificates from a given file */
1084 int cert_load(BIO *in, STACK_OF(X509) *sk)
1089 while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
1091 if (!sk_X509_push(sk, cert))
1099 /* Generalised x509 attribute value print */
1101 void print_attribute(BIO *out, const ASN1_TYPE *av)
1106 case V_ASN1_BMPSTRING:
1107 value = OPENSSL_uni2asc(av->value.bmpstring->data,
1108 av->value.bmpstring->length);
1109 BIO_printf(out, "%s\n", value);
1110 OPENSSL_free(value);
1113 case V_ASN1_UTF8STRING:
1114 BIO_printf(out, "%s\n", av->value.utf8string->data);
1117 case V_ASN1_OCTET_STRING:
1118 hex_prin(out, av->value.octet_string->data,
1119 av->value.octet_string->length);
1120 BIO_printf(out, "\n");
1123 case V_ASN1_BIT_STRING:
1124 hex_prin(out, av->value.bit_string->data,
1125 av->value.bit_string->length);
1126 BIO_printf(out, "\n");
1130 BIO_printf(out, "<Unsupported tag %d>\n", av->type);
1135 /* Generalised attribute print: handle PKCS#8 and bag attributes */
1137 int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst,
1140 X509_ATTRIBUTE *attr;
1144 BIO_printf(out, "%s: <No Attributes>\n", name);
1147 if (!sk_X509_ATTRIBUTE_num(attrlst)) {
1148 BIO_printf(out, "%s: <Empty Attributes>\n", name);
1151 BIO_printf(out, "%s\n", name);
1152 for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) {
1153 ASN1_OBJECT *attr_obj;
1154 attr = sk_X509_ATTRIBUTE_value(attrlst, i);
1155 attr_obj = X509_ATTRIBUTE_get0_object(attr);
1156 attr_nid = OBJ_obj2nid(attr_obj);
1157 BIO_printf(out, " ");
1158 if (attr_nid == NID_undef) {
1159 i2a_ASN1_OBJECT(out, attr_obj);
1160 BIO_printf(out, ": ");
1162 BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
1165 if (X509_ATTRIBUTE_count(attr)) {
1166 for (j = 0; j < X509_ATTRIBUTE_count(attr); j++)
1168 av = X509_ATTRIBUTE_get0_type(attr, j);
1169 print_attribute(out, av);
1172 BIO_printf(out, "<No Values>\n");
1178 void hex_prin(BIO *out, unsigned char *buf, int len)
1181 for (i = 0; i < len; i++)
1182 BIO_printf(out, "%02X ", buf[i]);
1185 static int set_pbe(int *ppbe, const char *str)
1189 if (strcmp(str, "NONE") == 0) {
1193 *ppbe = OBJ_txt2nid(str);
1194 if (*ppbe == NID_undef) {
1195 BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str);