2 * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (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>
11 #if defined(OPENSSL_NO_DES)
12 NON_EMPTY_TRANSLATION_UNIT
19 # include <openssl/crypto.h>
20 # include <openssl/err.h>
21 # include <openssl/pem.h>
22 # include <openssl/pkcs12.h>
30 static int get_cert_chain(X509 *cert, X509_STORE *store,
31 STACK_OF(X509) **chain);
32 int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass, int passlen,
33 int options, char *pempass, const EVP_CIPHER *enc);
34 int dump_certs_pkeys_bags(BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags,
35 char *pass, int passlen, int options, char *pempass,
36 const EVP_CIPHER *enc);
37 int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bags, char *pass,
38 int passlen, int options, char *pempass,
39 const EVP_CIPHER *enc);
40 int print_attribs(BIO *out, STACK_OF(X509_ATTRIBUTE) *attrlst,
42 void hex_prin(BIO *out, unsigned char *buf, int len);
43 static int alg_print(X509_ALGOR *alg);
44 int cert_load(BIO *in, STACK_OF(X509) *sk);
45 static int set_pbe(int *ppbe, const char *str);
47 typedef enum OPTION_choice {
48 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
49 OPT_CIPHER, OPT_NOKEYS, OPT_KEYEX, OPT_KEYSIG, OPT_NOCERTS, OPT_CLCERTS,
50 OPT_CACERTS, OPT_NOOUT, OPT_INFO, OPT_CHAIN, OPT_TWOPASS, OPT_NOMACVER,
51 OPT_DESCERT, OPT_EXPORT, OPT_NOITER, OPT_MACITER, OPT_NOMACITER,
52 OPT_NOMAC, OPT_LMK, OPT_NODES, OPT_MACALG, OPT_CERTPBE, OPT_KEYPBE,
53 OPT_RAND, OPT_INKEY, OPT_CERTFILE, OPT_NAME, OPT_CSP, OPT_CANAME,
54 OPT_IN, OPT_OUT, OPT_PASSIN, OPT_PASSOUT, OPT_PASSWORD, OPT_CAPATH,
55 OPT_CAFILE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_ENGINE
58 OPTIONS pkcs12_options[] = {
59 {"help", OPT_HELP, '-', "Display this summary"},
60 {"nokeys", OPT_NOKEYS, '-', "Don't output private keys"},
61 {"keyex", OPT_KEYEX, '-', "Set MS key exchange type"},
62 {"keysig", OPT_KEYSIG, '-', "Set MS key signature type"},
63 {"nocerts", OPT_NOCERTS, '-', "Don't output certificates"},
64 {"clcerts", OPT_CLCERTS, '-', "Only output client certificates"},
65 {"cacerts", OPT_CACERTS, '-', "Only output CA certificates"},
66 {"noout", OPT_NOOUT, '-', "Don't output anything, just verify"},
67 {"info", OPT_INFO, '-', "Print info about PKCS#12 structure"},
68 {"chain", OPT_CHAIN, '-', "Add certificate chain"},
69 {"twopass", OPT_TWOPASS, '-', "Separate MAC, encryption passwords"},
70 {"nomacver", OPT_NOMACVER, '-', "Don't verify MAC"},
71 # ifndef OPENSSL_NO_RC2
72 {"descert", OPT_DESCERT, '-',
73 "Encrypt output with 3DES (default RC2-40)"},
74 {"certpbe", OPT_CERTPBE, 's',
75 "Certificate PBE algorithm (default RC2-40)"},
77 {"descert", OPT_DESCERT, '-', "Encrypt output with 3DES (the default)"},
78 {"certpbe", OPT_CERTPBE, 's', "Certificate PBE algorithm (default 3DES)"},
80 {"export", OPT_EXPORT, '-', "Output PKCS12 file"},
81 {"noiter", OPT_NOITER, '-', "Don't use encryption iteration"},
82 {"maciter", OPT_MACITER, '-', "Use MAC iteration"},
83 {"nomaciter", OPT_NOMACITER, '-', "Don't use MAC iteration"},
84 {"nomac", OPT_NOMAC, '-', "Don't generate MAC"},
86 "Add local machine keyset attribute to private key"},
87 {"nodes", OPT_NODES, '-', "Don't encrypt private keys"},
88 {"macalg", OPT_MACALG, 's',
89 "Digest algorithm used in MAC (default SHA1)"},
90 {"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default 3DES)"},
91 {"rand", OPT_RAND, 's',
92 "Load the file(s) into the random number generator"},
93 {"inkey", OPT_INKEY, '<', "Private key if not infile"},
94 {"certfile", OPT_CERTFILE, '<', "Load certs from file"},
95 {"name", OPT_NAME, 's', "Use name as friendly name"},
96 {"CSP", OPT_CSP, 's', "Microsoft CSP name"},
97 {"caname", OPT_CANAME, 's',
98 "Use name as CA friendly name (can be repeated)"},
99 {"in", OPT_IN, '<', "Input filename"},
100 {"out", OPT_OUT, '>', "Output filename"},
101 {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
102 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
103 {"password", OPT_PASSWORD, 's', "Set import/export password source"},
104 {"CApath", OPT_CAPATH, '/', "PEM-format directory of CA's"},
105 {"CAfile", OPT_CAFILE, '<', "PEM-format file of CA's"},
106 {"no-CAfile", OPT_NOCAFILE, '-',
107 "Do not load the default certificates file"},
108 {"no-CApath", OPT_NOCAPATH, '-',
109 "Do not load certificates from the default certificates directory"},
110 {"", OPT_CIPHER, '-', "Any supported cipher"},
111 # ifndef OPENSSL_NO_ENGINE
112 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
117 int pkcs12_main(int argc, char **argv)
119 char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL;
120 char *name = NULL, *csp_name = NULL;
121 char pass[2048], macpass[2048];
122 int export_cert = 0, options = 0, chain = 0, twopass = 0, keytype = 0;
123 int iter = PKCS12_DEFAULT_ITER, maciter = PKCS12_DEFAULT_ITER;
124 # ifndef OPENSSL_NO_RC2
125 int cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
127 int cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
129 int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
130 int ret = 1, macver = 1, add_lmk = 0, private = 0;
132 char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL;
133 char *passin = NULL, *passout = NULL, *inrand = NULL, *macalg = NULL;
134 char *cpass = NULL, *mpass = NULL, *CApath = NULL, *CAfile = NULL;
136 int noCApath = 0, noCAfile = 0;
138 BIO *in = NULL, *out = NULL;
140 STACK_OF(OPENSSL_STRING) *canames = NULL;
141 const EVP_CIPHER *enc = EVP_des_ede3_cbc();
144 prog = opt_init(argc, argv, pkcs12_options);
145 while ((o = opt_next()) != OPT_EOF) {
150 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
153 opt_help(pkcs12_options);
175 options |= (NOKEYS | NOCERTS);
190 cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
196 if (!opt_cipher(opt_unknown(), &enc))
203 maciter = PKCS12_DEFAULT_ITER;
218 if (!set_pbe(&cert_pbe, opt_arg()))
222 if (!set_pbe(&key_pbe, opt_arg()))
232 certfile = opt_arg();
241 csp_name = opt_arg();
245 && (canames = sk_OPENSSL_STRING_new_null()) == NULL)
247 sk_OPENSSL_STRING_push(canames, opt_arg());
256 passinarg = opt_arg();
259 passoutarg = opt_arg();
277 e = setup_engine(opt_arg(), 0);
281 argc = opt_num_rest();
289 passoutarg = passarg;
294 if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
295 BIO_printf(bio_err, "Error getting passwords\n");
314 if (export_cert || inrand) {
315 app_RAND_load_file(NULL, (inrand != NULL));
317 BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
318 app_RAND_load_files(inrand));
323 #ifndef OPENSSL_NO_UI
324 if (EVP_read_pw_string
325 (macpass, sizeof macpass, "Enter MAC Password:", export_cert)) {
326 BIO_printf(bio_err, "Can't read Password\n");
331 BIO_printf(bio_err, "Unsupported option -twopass\n");
337 EVP_PKEY *key = NULL;
338 X509 *ucert = NULL, *x = NULL;
339 STACK_OF(X509) *certs = NULL;
340 const EVP_MD *macmd = NULL;
341 unsigned char *catmp = NULL;
344 if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
345 BIO_printf(bio_err, "Nothing to do!\n");
349 if (options & NOCERTS)
352 if (!(options & NOKEYS)) {
353 key = load_key(keyname ? keyname : infile,
354 FORMAT_PEM, 1, passin, e, "private key");
359 /* Load in all certs in input file */
360 if (!(options & NOCERTS)) {
361 if (!load_certs(infile, &certs, FORMAT_PEM, NULL,
366 /* Look for matching private key */
367 for (i = 0; i < sk_X509_num(certs); i++) {
368 x = sk_X509_value(certs, i);
369 if (X509_check_private_key(x, key)) {
371 /* Zero keyid and alias */
372 X509_keyid_set1(ucert, NULL, 0);
373 X509_alias_set1(ucert, NULL, 0);
374 /* Remove from list */
375 (void)sk_X509_delete(certs, i);
381 "No certificate matches private key\n");
388 /* Add any more certificates asked for */
390 if (!load_certs(certfile, &certs, FORMAT_PEM, NULL,
391 "certificates from certfile"))
395 /* If chaining get chain from user cert */
398 STACK_OF(X509) *chain2;
400 if ((store = setup_verify(CAfile, CApath, noCAfile, noCApath))
404 vret = get_cert_chain(ucert, store, &chain2);
405 X509_STORE_free(store);
407 if (vret == X509_V_OK) {
408 /* Exclude verified certificate */
409 for (i = 1; i < sk_X509_num(chain2); i++)
410 sk_X509_push(certs, sk_X509_value(chain2, i));
411 /* Free first certificate */
412 X509_free(sk_X509_value(chain2, 0));
413 sk_X509_free(chain2);
415 if (vret != X509_V_ERR_UNSPECIFIED)
416 BIO_printf(bio_err, "Error %s getting chain.\n",
417 X509_verify_cert_error_string(vret));
419 ERR_print_errors(bio_err);
424 /* Add any CA names */
426 for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
427 catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i);
428 X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
432 EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
433 MBSTRING_ASC, (unsigned char *)csp_name,
437 EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);
441 #ifndef OPENSSL_NO_UI
442 if (EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:",
444 BIO_printf(bio_err, "Can't read Password\n");
449 BIO_printf(bio_err, "Password required\n");
455 OPENSSL_strlcpy(macpass, pass, sizeof macpass);
457 p12 = PKCS12_create(cpass, name, key, ucert, certs,
458 key_pbe, cert_pbe, iter, -1, keytype);
461 ERR_print_errors(bio_err);
466 if (!opt_md(macalg, &macmd))
471 PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd);
475 out = bio_open_owner(outfile, FORMAT_PKCS12, private);
479 i2d_PKCS12_bio(out, p12);
486 sk_X509_pop_free(certs, X509_free);
493 in = bio_open_default(infile, 'r', FORMAT_PKCS12);
496 out = bio_open_owner(outfile, FORMAT_PEM, private);
500 if ((p12 = d2i_PKCS12_bio(in, NULL)) == NULL) {
501 ERR_print_errors(bio_err);
507 #ifndef OPENSSL_NO_UI
508 if (EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:",
510 BIO_printf(bio_err, "Can't read Password\n");
515 BIO_printf(bio_err, "Password required\n");
521 OPENSSL_strlcpy(macpass, pass, sizeof macpass);
523 if ((options & INFO) && PKCS12_mac_present(p12)) {
524 ASN1_INTEGER *tmaciter;
526 PKCS12_get0_mac(NULL, NULL, NULL, &tmaciter, p12);
527 BIO_printf(bio_err, "MAC Iteration %ld\n",
528 tmaciter != NULL ? ASN1_INTEGER_get(tmaciter) : 1L);
531 /* If we enter empty password try no password first */
532 if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
533 /* If mac and crypto pass the same set it to NULL too */
536 } else if (!PKCS12_verify_mac(p12, mpass, -1)) {
537 BIO_printf(bio_err, "Mac verify error: invalid password?\n");
538 ERR_print_errors(bio_err);
544 if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) {
545 BIO_printf(bio_err, "Error outputting keys and certificates\n");
546 ERR_print_errors(bio_err);
552 if (export_cert || inrand)
553 app_RAND_write_file(NULL);
556 sk_OPENSSL_STRING_free(canames);
557 OPENSSL_free(passin);
558 OPENSSL_free(passout);
562 int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass,
563 int passlen, int options, char *pempass,
564 const EVP_CIPHER *enc)
566 STACK_OF(PKCS7) *asafes = NULL;
567 STACK_OF(PKCS12_SAFEBAG) *bags;
572 if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL)
574 for (i = 0; i < sk_PKCS7_num(asafes); i++) {
575 p7 = sk_PKCS7_value(asafes, i);
576 bagnid = OBJ_obj2nid(p7->type);
577 if (bagnid == NID_pkcs7_data) {
578 bags = PKCS12_unpack_p7data(p7);
580 BIO_printf(bio_err, "PKCS7 Data\n");
581 } else if (bagnid == NID_pkcs7_encrypted) {
582 if (options & INFO) {
583 BIO_printf(bio_err, "PKCS7 Encrypted data: ");
584 alg_print(p7->d.encrypted->enc_data->algorithm);
586 bags = PKCS12_unpack_p7encdata(p7, pass, passlen);
591 if (!dump_certs_pkeys_bags(out, bags, pass, passlen,
592 options, pempass, enc)) {
593 sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
596 sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
602 sk_PKCS7_pop_free(asafes, PKCS7_free);
606 int dump_certs_pkeys_bags(BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags,
607 char *pass, int passlen, int options, char *pempass,
608 const EVP_CIPHER *enc)
611 for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) {
612 if (!dump_certs_pkeys_bag(out,
613 sk_PKCS12_SAFEBAG_value(bags, i),
614 pass, passlen, options, pempass, enc))
620 int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bag, char *pass,
621 int passlen, int options, char *pempass,
622 const EVP_CIPHER *enc)
625 PKCS8_PRIV_KEY_INFO *p8;
627 STACK_OF(X509_ATTRIBUTE) *attrs;
630 attrs = PKCS12_SAFEBAG_get0_attrs(bag);
632 switch (PKCS12_SAFEBAG_get_nid(bag)) {
635 BIO_printf(bio_err, "Key bag\n");
636 if (options & NOKEYS)
638 print_attribs(out, attrs, "Bag Attributes");
639 p8 = PKCS12_SAFEBAG_get0_p8inf(bag);
640 if ((pkey = EVP_PKCS82PKEY(p8)) == NULL)
642 print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes");
643 ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
647 case NID_pkcs8ShroudedKeyBag:
648 if (options & INFO) {
652 BIO_printf(bio_err, "Shrouded Keybag: ");
653 tp8 = PKCS12_SAFEBAG_get0_pkcs8(bag);
654 X509_SIG_get0(&tp8alg, NULL, tp8);
657 if (options & NOKEYS)
659 print_attribs(out, attrs, "Bag Attributes");
660 if ((p8 = PKCS12_decrypt_skey(bag, pass, passlen)) == NULL)
662 if ((pkey = EVP_PKCS82PKEY(p8)) == NULL) {
663 PKCS8_PRIV_KEY_INFO_free(p8);
666 print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes");
667 PKCS8_PRIV_KEY_INFO_free(p8);
668 ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
674 BIO_printf(bio_err, "Certificate bag\n");
675 if (options & NOCERTS)
677 if (PKCS12_SAFEBAG_get0_attr(bag, NID_localKeyID)) {
678 if (options & CACERTS)
680 } else if (options & CLCERTS)
682 print_attribs(out, attrs, "Bag Attributes");
683 if (PKCS12_SAFEBAG_get_bag_nid(bag) != NID_x509Certificate)
685 if ((x509 = PKCS12_SAFEBAG_get1_cert(bag)) == NULL)
687 dump_cert_text(out, x509);
688 ret = PEM_write_bio_X509(out, x509);
692 case NID_safeContentsBag:
694 BIO_printf(bio_err, "Safe Contents bag\n");
695 print_attribs(out, attrs, "Bag Attributes");
696 return dump_certs_pkeys_bags(out, PKCS12_SAFEBAG_get0_safes(bag),
697 pass, passlen, options, pempass, enc);
700 BIO_printf(bio_err, "Warning unsupported bag type: ");
701 i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_type(bag));
702 BIO_printf(bio_err, "\n");
708 /* Given a single certificate return a verified chain or NULL if error */
710 static int get_cert_chain(X509 *cert, X509_STORE *store,
711 STACK_OF(X509) **chain)
713 X509_STORE_CTX *store_ctx = NULL;
714 STACK_OF(X509) *chn = NULL;
717 store_ctx = X509_STORE_CTX_new();
718 if (store_ctx == NULL) {
719 i = X509_V_ERR_UNSPECIFIED;
722 if (!X509_STORE_CTX_init(store_ctx, store, cert, NULL)) {
723 i = X509_V_ERR_UNSPECIFIED;
728 if (X509_verify_cert(store_ctx) > 0)
729 chn = X509_STORE_CTX_get1_chain(store_ctx);
730 else if ((i = X509_STORE_CTX_get_error(store_ctx)) == 0)
731 i = X509_V_ERR_UNSPECIFIED;
734 X509_STORE_CTX_free(store_ctx);
739 static int alg_print(X509_ALGOR *alg)
742 const unsigned char *p = alg->parameter->value.sequence->data;
744 pbe = d2i_PBEPARAM(NULL, &p, alg->parameter->value.sequence->length);
747 BIO_printf(bio_err, "%s, Iteration %ld\n",
748 OBJ_nid2ln(OBJ_obj2nid(alg->algorithm)),
749 ASN1_INTEGER_get(pbe->iter));
754 /* Load all certificates from a given file */
756 int cert_load(BIO *in, STACK_OF(X509) *sk)
761 while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
763 sk_X509_push(sk, cert);
770 /* Generalised attribute print: handle PKCS#8 and bag attributes */
772 int print_attribs(BIO *out, STACK_OF(X509_ATTRIBUTE) *attrlst,
775 X509_ATTRIBUTE *attr;
780 BIO_printf(out, "%s: <No Attributes>\n", name);
783 if (!sk_X509_ATTRIBUTE_num(attrlst)) {
784 BIO_printf(out, "%s: <Empty Attributes>\n", name);
787 BIO_printf(out, "%s\n", name);
788 for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) {
789 ASN1_OBJECT *attr_obj;
790 attr = sk_X509_ATTRIBUTE_value(attrlst, i);
791 attr_obj = X509_ATTRIBUTE_get0_object(attr);
792 attr_nid = OBJ_obj2nid(attr_obj);
793 BIO_printf(out, " ");
794 if (attr_nid == NID_undef) {
795 i2a_ASN1_OBJECT(out, attr_obj);
796 BIO_printf(out, ": ");
798 BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
800 if (X509_ATTRIBUTE_count(attr)) {
801 av = X509_ATTRIBUTE_get0_type(attr, 0);
803 case V_ASN1_BMPSTRING:
804 value = OPENSSL_uni2asc(av->value.bmpstring->data,
805 av->value.bmpstring->length);
806 BIO_printf(out, "%s\n", value);
810 case V_ASN1_OCTET_STRING:
811 hex_prin(out, av->value.octet_string->data,
812 av->value.octet_string->length);
813 BIO_printf(out, "\n");
816 case V_ASN1_BIT_STRING:
817 hex_prin(out, av->value.bit_string->data,
818 av->value.bit_string->length);
819 BIO_printf(out, "\n");
823 BIO_printf(out, "<Unsupported tag %d>\n", av->type);
827 BIO_printf(out, "<No Values>\n");
832 void hex_prin(BIO *out, unsigned char *buf, int len)
835 for (i = 0; i < len; i++)
836 BIO_printf(out, "%02X ", buf[i]);
839 static int set_pbe(int *ppbe, const char *str)
843 if (strcmp(str, "NONE") == 0) {
847 *ppbe = OBJ_txt2nid(str);
848 if (*ppbe == NID_undef) {
849 BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str);