2 * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
5 /* ====================================================================
6 * Copyright (c) 1999-2006 The OpenSSL Project. All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
34 * 6. Redistributions of any form whatsoever must retain the following
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
59 #include <openssl/opensslconf.h>
60 #if !defined(OPENSSL_NO_DES)
66 # include <openssl/crypto.h>
67 # include <openssl/err.h>
68 # include <openssl/pem.h>
69 # include <openssl/pkcs12.h>
77 int get_cert_chain(X509 *cert, X509_STORE *store, STACK_OF(X509) **chain);
78 int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass, int passlen,
79 int options, char *pempass, const EVP_CIPHER *enc);
80 int dump_certs_pkeys_bags(BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags,
81 char *pass, int passlen, int options, char *pempass,
82 const EVP_CIPHER *enc);
83 int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bags, char *pass,
84 int passlen, int options, char *pempass,
85 const EVP_CIPHER *enc);
86 int print_attribs(BIO *out, STACK_OF(X509_ATTRIBUTE) *attrlst,
88 void hex_prin(BIO *out, unsigned char *buf, int len);
89 static int alg_print(X509_ALGOR *alg);
90 int cert_load(BIO *in, STACK_OF(X509) *sk);
91 static int set_pbe(int *ppbe, const char *str);
93 typedef enum OPTION_choice {
94 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
95 OPT_CIPHER, OPT_NOKEYS, OPT_KEYEX, OPT_KEYSIG, OPT_NOCERTS, OPT_CLCERTS,
96 OPT_CACERTS, OPT_NOOUT, OPT_INFO, OPT_CHAIN, OPT_TWOPASS, OPT_NOMACVER,
97 OPT_DESCERT, OPT_EXPORT, OPT_NOITER, OPT_MACITER, OPT_NOMACITER,
98 OPT_NOMAC, OPT_LMK, OPT_NODES, OPT_MACALG, OPT_CERTPBE, OPT_KEYPBE,
99 OPT_RAND, OPT_INKEY, OPT_CERTFILE, OPT_NAME, OPT_CSP, OPT_CANAME,
100 OPT_IN, OPT_OUT, OPT_PASSIN, OPT_PASSOUT, OPT_PASSWORD, OPT_CAPATH,
101 OPT_CAFILE, OPT_ENGINE
104 OPTIONS pkcs12_options[] = {
105 {"help", OPT_HELP, '-', "Display this summary"},
106 {"nokeys", OPT_NOKEYS, '-', "Don't output private keys"},
107 {"keyex", OPT_KEYEX, '-', "Set MS key exchange type"},
108 {"keysig", OPT_KEYSIG, '-', "Set MS key signature type"},
109 {"nocerts", OPT_NOCERTS, '-', "Don't output certificates"},
110 {"clcerts", OPT_CLCERTS, '-', "Only output client certificates"},
111 {"cacerts", OPT_CACERTS, '-', "Only output CA certificates"},
112 {"noout", OPT_NOOUT, '-', "Don't output anything, just verify"},
113 {"info", OPT_INFO, '-', "Print info about PKCS#12 structure"},
114 {"chain", OPT_CHAIN, '-', "Add certificate chain"},
115 {"twopass", OPT_TWOPASS, '-', "Separate MAC, encryption passwords"},
116 {"nomacver", OPT_NOMACVER, '-', "Don't verify MAC"},
117 # ifndef OPENSSL_NO_RC2
118 {"descert", OPT_DESCERT, '-',
119 "Encrypt output with 3DES (default RC2-40)"},
120 {"certpbe", OPT_CERTPBE, 's',
121 "Certificate PBE algorithm (default RC2-40)"},
123 {"descert", OPT_DESCERT, '-', "Encrypt output with 3DES (the default)"},
124 {"certpbe", OPT_CERTPBE, 's', "Certificate PBE algorithm (default 3DES)"},
126 {"export", OPT_EXPORT, '-', "Output PKCS12 file"},
127 {"noiter", OPT_NOITER, '-', "Don't use encryption iteration"},
128 {"maciter", OPT_MACITER, '-', "Use MAC iteration"},
129 {"nomaciter", OPT_NOMACITER, '-', "Don't use MAC iteration"},
130 {"nomac", OPT_NOMAC, '-', "Don't generate MAC"},
131 {"LMK", OPT_LMK, '-',
132 "Add local machine keyset attribute to private key"},
133 {"nodes", OPT_NODES, '-', "Don't encrypt private keys"},
134 {"macalg", OPT_MACALG, 's',
135 "Digest algorithm used in MAC (default SHA1)"},
136 {"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default 3DES)"},
137 {"rand", OPT_RAND, 's',
138 "Load the file(s) into the random number generator"},
139 {"inkey", OPT_INKEY, '<', "Private key if not infile"},
140 {"certfile", OPT_CERTFILE, '<', "Load certs from file"},
141 {"name", OPT_NAME, 's', "Use name as friendly name"},
142 {"CSP", OPT_CSP, 's', "Microsoft CSP name"},
143 {"caname", OPT_CANAME, 's',
144 "Use name as CA friendly name (can be repeated)"},
145 {"in", OPT_IN, '<', "Input filename"},
146 {"out", OPT_OUT, '>', "Output filename"},
147 {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
148 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
149 {"password", OPT_PASSWORD, 's', "Set import/export password source"},
150 {"CApath", OPT_CAPATH, '/', "PEM-format directory of CA's"},
151 {"CAfile", OPT_CAFILE, '<', "PEM-format file of CA's"},
152 # ifndef OPENSSL_NO_ENGINE
153 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
155 {"", OPT_CIPHER, '-', "Any supported cipher"},
159 int pkcs12_main(int argc, char **argv)
161 char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL;
162 char *name = NULL, *csp_name = NULL;
163 char pass[50], macpass[50];
164 int export_cert = 0, options = 0, chain = 0, twopass = 0, keytype = 0;
165 int iter = PKCS12_DEFAULT_ITER, maciter = PKCS12_DEFAULT_ITER;
166 # ifndef OPENSSL_NO_RC2
167 int cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
169 int cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
171 int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
172 int ret = 1, macver = 1, noprompt = 0, add_lmk = 0;
173 char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL;
174 char *passin = NULL, *passout = NULL, *inrand = NULL, *macalg = NULL;
175 char *cpass = NULL, *mpass = NULL, *CApath = NULL, *CAfile = NULL;
178 BIO *in = NULL, *out = NULL;
180 STACK_OF(OPENSSL_STRING) *canames = NULL;
181 const EVP_CIPHER *enc = EVP_des_ede3_cbc();
184 prog = opt_init(argc, argv, pkcs12_options);
185 while ((o = opt_next()) != OPT_EOF) {
190 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
193 opt_help(pkcs12_options);
215 options |= (NOKEYS | NOCERTS);
230 cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
236 if (!opt_cipher(opt_unknown(), &enc))
243 maciter = PKCS12_DEFAULT_ITER;
258 if (!set_pbe(&cert_pbe, opt_arg()))
262 if (!set_pbe(&key_pbe, opt_arg()))
272 certfile = opt_arg();
281 csp_name = opt_arg();
285 && (canames = sk_OPENSSL_STRING_new_null()) == NULL)
287 sk_OPENSSL_STRING_push(canames, opt_arg());
296 passinarg = opt_arg();
299 passoutarg = opt_arg();
311 e = setup_engine(opt_arg(), 0);
315 argc = opt_num_rest();
320 passoutarg = passarg;
325 if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
326 BIO_printf(bio_err, "Error getting passwords\n");
345 if (export_cert || inrand) {
346 app_RAND_load_file(NULL, (inrand != NULL));
348 BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
349 app_RAND_load_files(inrand));
352 in = bio_open_default(infile, "rb");
356 out = bio_open_default(outfile, "wb");
361 if (EVP_read_pw_string
362 (macpass, sizeof macpass, "Enter MAC Password:", export_cert)) {
363 BIO_printf(bio_err, "Can't read Password\n");
369 EVP_PKEY *key = NULL;
370 X509 *ucert = NULL, *x = NULL;
371 STACK_OF(X509) *certs = NULL;
372 const EVP_MD *macmd = NULL;
373 unsigned char *catmp = NULL;
376 if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
377 BIO_printf(bio_err, "Nothing to do!\n");
381 if (options & NOCERTS)
384 if (!(options & NOKEYS)) {
385 key = load_key(keyname ? keyname : infile,
386 FORMAT_PEM, 1, passin, e, "private key");
391 /* Load in all certs in input file */
392 if (!(options & NOCERTS)) {
393 certs = load_certs(infile, FORMAT_PEM, NULL, e,
399 /* Look for matching private key */
400 for (i = 0; i < sk_X509_num(certs); i++) {
401 x = sk_X509_value(certs, i);
402 if (X509_check_private_key(x, key)) {
404 /* Zero keyid and alias */
405 X509_keyid_set1(ucert, NULL, 0);
406 X509_alias_set1(ucert, NULL, 0);
407 /* Remove from list */
408 (void)sk_X509_delete(certs, i);
414 "No certificate matches private key\n");
421 /* Add any more certificates asked for */
423 STACK_OF(X509) *morecerts = NULL;
424 if (!(morecerts = load_certs(certfile, FORMAT_PEM, NULL, e,
425 "certificates from certfile")))
427 while (sk_X509_num(morecerts) > 0)
428 sk_X509_push(certs, sk_X509_shift(morecerts));
429 sk_X509_free(morecerts);
432 /* If chaining get chain from user cert */
435 STACK_OF(X509) *chain2;
437 if (!(store = setup_verify(CAfile, CApath)))
440 vret = get_cert_chain(ucert, store, &chain2);
441 X509_STORE_free(store);
444 /* Exclude verified certificate */
445 for (i = 1; i < sk_X509_num(chain2); i++)
446 sk_X509_push(certs, sk_X509_value(chain2, i));
447 /* Free first certificate */
448 X509_free(sk_X509_value(chain2, 0));
449 sk_X509_free(chain2);
452 BIO_printf(bio_err, "Error %s getting chain.\n",
453 X509_verify_cert_error_string(vret));
455 ERR_print_errors(bio_err);
460 /* Add any CA names */
462 for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
463 catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i);
464 X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
468 EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
469 MBSTRING_ASC, (unsigned char *)csp_name,
473 EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);
476 EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:",
478 BIO_printf(bio_err, "Can't read Password\n");
482 BUF_strlcpy(macpass, pass, sizeof macpass);
484 p12 = PKCS12_create(cpass, name, key, ucert, certs,
485 key_pbe, cert_pbe, iter, -1, keytype);
488 ERR_print_errors(bio_err);
493 if (!opt_md(macalg, &macmd))
498 PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd);
500 i2d_PKCS12_bio(out, p12);
507 sk_X509_pop_free(certs, X509_free);
514 if (!(p12 = d2i_PKCS12_bio(in, NULL))) {
515 ERR_print_errors(bio_err);
520 && EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:",
522 BIO_printf(bio_err, "Can't read Password\n");
527 BUF_strlcpy(macpass, pass, sizeof macpass);
529 if ((options & INFO) && p12->mac)
530 BIO_printf(bio_err, "MAC Iteration %ld\n",
531 p12->mac->iter ? ASN1_INTEGER_get(p12->mac->iter) : 1);
533 /* If we enter empty password try no password first */
534 if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
535 /* If mac and crypto pass the same set it to NULL too */
538 } else if (!PKCS12_verify_mac(p12, mpass, -1)) {
539 BIO_printf(bio_err, "Mac verify error: invalid password?\n");
540 ERR_print_errors(bio_err);
545 if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) {
546 BIO_printf(bio_err, "Error outputting keys and certificates\n");
547 ERR_print_errors(bio_err);
553 if (export_cert || inrand)
554 app_RAND_write_file(NULL);
557 sk_OPENSSL_STRING_free(canames);
558 OPENSSL_free(passin);
559 OPENSSL_free(passout);
563 int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass,
564 int passlen, int options, char *pempass,
565 const EVP_CIPHER *enc)
567 STACK_OF(PKCS7) *asafes = NULL;
568 STACK_OF(PKCS12_SAFEBAG) *bags;
573 if (!(asafes = PKCS12_unpack_authsafes(p12)))
575 for (i = 0; i < sk_PKCS7_num(asafes); i++) {
576 p7 = sk_PKCS7_value(asafes, i);
577 bagnid = OBJ_obj2nid(p7->type);
578 if (bagnid == NID_pkcs7_data) {
579 bags = PKCS12_unpack_p7data(p7);
581 BIO_printf(bio_err, "PKCS7 Data\n");
582 } else if (bagnid == NID_pkcs7_encrypted) {
583 if (options & INFO) {
584 BIO_printf(bio_err, "PKCS7 Encrypted data: ");
585 alg_print(p7->d.encrypted->enc_data->algorithm);
587 bags = PKCS12_unpack_p7encdata(p7, pass, passlen);
592 if (!dump_certs_pkeys_bags(out, bags, pass, passlen,
593 options, pempass, enc)) {
594 sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
597 sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
603 sk_PKCS7_pop_free(asafes, PKCS7_free);
607 int dump_certs_pkeys_bags(BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags,
608 char *pass, int passlen, int options, char *pempass,
609 const EVP_CIPHER *enc)
612 for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) {
613 if (!dump_certs_pkeys_bag(out,
614 sk_PKCS12_SAFEBAG_value(bags, i),
615 pass, passlen, options, pempass, enc))
621 int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bag, char *pass,
622 int passlen, int options, char *pempass,
623 const EVP_CIPHER *enc)
626 PKCS8_PRIV_KEY_INFO *p8;
629 switch (M_PKCS12_bag_type(bag)) {
632 BIO_printf(bio_err, "Key bag\n");
633 if (options & NOKEYS)
635 print_attribs(out, bag->attrib, "Bag Attributes");
636 p8 = bag->value.keybag;
637 if (!(pkey = EVP_PKCS82PKEY(p8)))
639 print_attribs(out, p8->attributes, "Key Attributes");
640 PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
644 case NID_pkcs8ShroudedKeyBag:
645 if (options & INFO) {
646 BIO_printf(bio_err, "Shrouded Keybag: ");
647 alg_print(bag->value.shkeybag->algor);
649 if (options & NOKEYS)
651 print_attribs(out, bag->attrib, "Bag Attributes");
652 if (!(p8 = PKCS12_decrypt_skey(bag, pass, passlen)))
654 if (!(pkey = EVP_PKCS82PKEY(p8))) {
655 PKCS8_PRIV_KEY_INFO_free(p8);
658 print_attribs(out, p8->attributes, "Key Attributes");
659 PKCS8_PRIV_KEY_INFO_free(p8);
660 PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
666 BIO_printf(bio_err, "Certificate bag\n");
667 if (options & NOCERTS)
669 if (PKCS12_get_attr(bag, NID_localKeyID)) {
670 if (options & CACERTS)
672 } else if (options & CLCERTS)
674 print_attribs(out, bag->attrib, "Bag Attributes");
675 if (M_PKCS12_cert_bag_type(bag) != NID_x509Certificate)
677 if (!(x509 = PKCS12_certbag2x509(bag)))
679 dump_cert_text(out, x509);
680 PEM_write_bio_X509(out, x509);
684 case NID_safeContentsBag:
686 BIO_printf(bio_err, "Safe Contents bag\n");
687 print_attribs(out, bag->attrib, "Bag Attributes");
688 return dump_certs_pkeys_bags(out, bag->value.safes, pass,
689 passlen, options, pempass, enc);
692 BIO_printf(bio_err, "Warning unsupported bag type: ");
693 i2a_ASN1_OBJECT(bio_err, bag->type);
694 BIO_printf(bio_err, "\n");
700 /* Given a single certificate return a verified chain or NULL if error */
702 /* Hope this is OK .... */
704 int get_cert_chain(X509 *cert, X509_STORE *store, STACK_OF(X509) **chain)
706 X509_STORE_CTX store_ctx;
711 * FIXME: Should really check the return status of X509_STORE_CTX_init
712 * for an error, but how that fits into the return value of this function
715 X509_STORE_CTX_init(&store_ctx, store, cert, NULL);
716 if (X509_verify_cert(&store_ctx) <= 0) {
717 i = X509_STORE_CTX_get_error(&store_ctx);
720 * avoid returning 0 if X509_verify_cert() did not set an
721 * appropriate error value in the context
727 chn = X509_STORE_CTX_get1_chain(&store_ctx);
729 X509_STORE_CTX_cleanup(&store_ctx);
735 static int alg_print(X509_ALGOR *alg)
738 const unsigned char *p = alg->parameter->value.sequence->data;
740 pbe = d2i_PBEPARAM(NULL, &p, alg->parameter->value.sequence->length);
743 BIO_printf(bio_err, "%s, Iteration %ld\n",
744 OBJ_nid2ln(OBJ_obj2nid(alg->algorithm)),
745 ASN1_INTEGER_get(pbe->iter));
750 /* Load all certificates from a given file */
752 int cert_load(BIO *in, STACK_OF(X509) *sk)
757 while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
759 sk_X509_push(sk, cert);
766 /* Generalised attribute print: handle PKCS#8 and bag attributes */
768 int print_attribs(BIO *out, STACK_OF(X509_ATTRIBUTE) *attrlst,
771 X509_ATTRIBUTE *attr;
776 BIO_printf(out, "%s: <No Attributes>\n", name);
779 if (!sk_X509_ATTRIBUTE_num(attrlst)) {
780 BIO_printf(out, "%s: <Empty Attributes>\n", name);
783 BIO_printf(out, "%s\n", name);
784 for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) {
785 ASN1_OBJECT *attr_obj;
786 attr = sk_X509_ATTRIBUTE_value(attrlst, i);
787 attr_obj = X509_ATTRIBUTE_get0_object(attr);
788 attr_nid = OBJ_obj2nid(attr_obj);
789 BIO_printf(out, " ");
790 if (attr_nid == NID_undef) {
791 i2a_ASN1_OBJECT(out, attr_obj);
792 BIO_printf(out, ": ");
794 BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
796 if (X509_ATTRIBUTE_count(attr)) {
797 av = X509_ATTRIBUTE_get0_type(attr, 0);
799 case V_ASN1_BMPSTRING:
800 value = OPENSSL_uni2asc(av->value.bmpstring->data,
801 av->value.bmpstring->length);
802 BIO_printf(out, "%s\n", value);
806 case V_ASN1_OCTET_STRING:
807 hex_prin(out, av->value.octet_string->data,
808 av->value.octet_string->length);
809 BIO_printf(out, "\n");
812 case V_ASN1_BIT_STRING:
813 hex_prin(out, av->value.bit_string->data,
814 av->value.bit_string->length);
815 BIO_printf(out, "\n");
819 BIO_printf(out, "<Unsupported tag %d>\n", av->type);
823 BIO_printf(out, "<No Values>\n");
828 void hex_prin(BIO *out, unsigned char *buf, int len)
831 for (i = 0; i < len; i++)
832 BIO_printf(out, "%02X ", buf[i]);
835 static int set_pbe(int *ppbe, const char *str)
839 if (!strcmp(str, "NONE")) {
843 *ppbe = OBJ_txt2nid(str);
844 if (*ppbe == NID_undef) {
845 BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str);