ssl/tsrc/topenssl/src/pkcs12.c
changeset 0 e4d67989cc36
equal deleted inserted replaced
-1:000000000000 0:e4d67989cc36
       
     1 /* pkcs12.c */
       
     2 /* Written by Dr Stephen N Henson (shenson@bigfoot.com) for the OpenSSL
       
     3  * project.
       
     4  */
       
     5 /* ====================================================================
       
     6  * Copyright (c) 1999-2002 The OpenSSL Project.  All rights reserved.
       
     7  *
       
     8  * Redistribution and use in source and binary forms, with or without
       
     9  * modification, are permitted provided that the following conditions
       
    10  * are met:
       
    11  *
       
    12  * 1. Redistributions of source code must retain the above copyright
       
    13  *    notice, this list of conditions and the following disclaimer. 
       
    14  *
       
    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
       
    18  *    distribution.
       
    19  *
       
    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/)"
       
    24  *
       
    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.
       
    29  *
       
    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.
       
    33  *
       
    34  * 6. Redistributions of any form whatsoever must retain the following
       
    35  *    acknowledgment:
       
    36  *    "This product includes software developed by the OpenSSL Project
       
    37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
       
    38  *
       
    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  * ====================================================================
       
    52  *
       
    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).
       
    56  *
       
    57  */
       
    58 
       
    59 #include <openssl/opensslconf.h>
       
    60 #if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_SHA1)
       
    61 
       
    62 #include <stdio.h>
       
    63 #include <stdlib.h>
       
    64 #include <string.h>
       
    65 #include "apps.h"
       
    66 #include <openssl/crypto.h>
       
    67 #include <openssl/err.h>
       
    68 #include <openssl/pem.h>
       
    69 #include <openssl/pkcs12.h>
       
    70 
       
    71 #define PROG pkcs12_main
       
    72 
       
    73 const EVP_CIPHER *enc;
       
    74 
       
    75 
       
    76 #define NOKEYS		0x1
       
    77 #define NOCERTS 	0x2
       
    78 #define INFO		0x4
       
    79 #define CLCERTS		0x8
       
    80 #define CACERTS		0x10
       
    81 
       
    82 int get_cert_chain (X509 *cert, X509_STORE *store, STACK_OF(X509) **chain);
       
    83 int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass, int passlen, int options, char *pempass);
       
    84 int dump_certs_pkeys_bags(BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags, char *pass,
       
    85 			  int passlen, int options, char *pempass);
       
    86 int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bags, char *pass, int passlen, int options, char *pempass);
       
    87 int print_attribs(BIO *out, STACK_OF(X509_ATTRIBUTE) *attrlst,const char *name);
       
    88 void hex_prin(BIO *out, unsigned char *buf, int len);
       
    89 int alg_print(BIO *x, X509_ALGOR *alg);
       
    90 int cert_load(BIO *in, STACK_OF(X509) *sk);
       
    91 
       
    92 
       
    93 int MAIN(int, char **);
       
    94 
       
    95 int MAIN(int argc, char **argv)
       
    96 {
       
    97     ENGINE *e = NULL;
       
    98     char *infile=NULL, *outfile=NULL, *keyname = NULL;	
       
    99     char *certfile=NULL;
       
   100     BIO *in=NULL, *out = NULL;
       
   101     char **args;
       
   102     char *name = NULL;
       
   103     char *csp_name = NULL;
       
   104     PKCS12 *p12 = NULL;
       
   105     char pass[50], macpass[50];
       
   106     int export_cert = 0;
       
   107     int options = 0;
       
   108     int chain = 0;
       
   109     int badarg = 0;
       
   110     int iter = PKCS12_DEFAULT_ITER;
       
   111     int maciter = PKCS12_DEFAULT_ITER;
       
   112     int twopass = 0;
       
   113     int keytype = 0;
       
   114     int cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
       
   115     int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
       
   116     int ret = 1;
       
   117     int macver = 1;
       
   118     int noprompt = 0;
       
   119     STACK *canames = NULL;
       
   120     char *cpass = NULL, *mpass = NULL;
       
   121     char *passargin = NULL, *passargout = NULL, *passarg = NULL;
       
   122     char *passin = NULL, *passout = NULL;
       
   123     char *inrand = NULL;
       
   124     char *CApath = NULL, *CAfile = NULL;
       
   125 #ifndef OPENSSL_NO_ENGINE
       
   126     char *engine=NULL;
       
   127 #endif
       
   128 
       
   129     apps_startup();
       
   130 
       
   131     enc = EVP_des_ede3_cbc();
       
   132     if (bio_err == NULL )
       
   133     bio_err = BIO_new_fp (stderr, BIO_NOCLOSE);
       
   134   	if (!load_config(bio_err, NULL))
       
   135 		goto end;
       
   136 
       
   137     args = argv + 1;
       
   138 
       
   139 
       
   140     while (*args) {
       
   141 	if (*args[0] == '-') {
       
   142 		if (!strcmp (*args, "-nokeys")) options |= NOKEYS;
       
   143 		else if (!strcmp (*args, "-keyex")) keytype = KEY_EX;
       
   144 		else if (!strcmp (*args, "-keysig")) keytype = KEY_SIG;
       
   145 		else if (!strcmp (*args, "-nocerts")) options |= NOCERTS;
       
   146 		else if (!strcmp (*args, "-clcerts")) options |= CLCERTS;
       
   147 		else if (!strcmp (*args, "-cacerts")) options |= CACERTS;
       
   148 		else if (!strcmp (*args, "-noout")) options |= (NOKEYS|NOCERTS);
       
   149 		else if (!strcmp (*args, "-info")) options |= INFO;
       
   150 		else if (!strcmp (*args, "-chain")) chain = 1;
       
   151 		else if (!strcmp (*args, "-twopass")) twopass = 1;
       
   152 		else if (!strcmp (*args, "-nomacver")) macver = 0;
       
   153 		else if (!strcmp (*args, "-descert"))
       
   154     			cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
       
   155 		else if (!strcmp (*args, "-export")) export_cert = 1;
       
   156 		else if (!strcmp (*args, "-des")) enc=EVP_des_cbc();
       
   157 		else if (!strcmp (*args, "-des3")) enc = EVP_des_ede3_cbc();
       
   158 #ifndef OPENSSL_NO_IDEA
       
   159 		else if (!strcmp (*args, "-idea")) enc=EVP_idea_cbc();
       
   160 #endif
       
   161 		else if (!strcmp (*args, "-des3")) enc = EVP_des_ede3_cbc();
       
   162 #ifndef OPENSSL_NO_AES
       
   163 		else if (!strcmp(*args,"-aes128")) enc=EVP_aes_128_cbc();
       
   164 		else if (!strcmp(*args,"-aes192")) enc=EVP_aes_192_cbc();
       
   165 		else if (!strcmp(*args,"-aes256")) enc=EVP_aes_256_cbc();
       
   166 #endif
       
   167 		else if (!strcmp (*args, "-noiter")) iter = 1;
       
   168 		else if (!strcmp (*args, "-maciter"))
       
   169 					 maciter = PKCS12_DEFAULT_ITER;
       
   170 		else if (!strcmp (*args, "-nomaciter"))
       
   171 					 maciter = 1;
       
   172 		else if (!strcmp (*args, "-nomac"))
       
   173 					 maciter = -1;
       
   174 		else if (!strcmp (*args, "-nodes")) enc=NULL;
       
   175 		else if (!strcmp (*args, "-certpbe")) {
       
   176 			if (args[1]) {
       
   177 				args++;
       
   178 				if (!strcmp(*args, "NONE"))
       
   179 					cert_pbe = -1;
       
   180 				else
       
   181 				cert_pbe=OBJ_txt2nid(*args);
       
   182 				if(cert_pbe == NID_undef) {
       
   183 					BIO_printf(bio_err,
       
   184 						 "Unknown PBE algorithm %s\n", *args);
       
   185 					badarg = 1;
       
   186 				}
       
   187 			} else badarg = 1;
       
   188 		} else if (!strcmp (*args, "-keypbe")) {
       
   189 			if (args[1]) {
       
   190 				args++;
       
   191 				if (!strcmp(*args, "NONE"))
       
   192 					key_pbe = -1;
       
   193 				else
       
   194 					key_pbe=OBJ_txt2nid(*args);
       
   195 				if(key_pbe == NID_undef) {
       
   196 					BIO_printf(bio_err,
       
   197 						 "Unknown PBE algorithm %s\n", *args);
       
   198 					badarg = 1;
       
   199 				}
       
   200 			} else badarg = 1;
       
   201 		} else if (!strcmp (*args, "-rand")) {
       
   202 		    if (args[1]) {
       
   203 			args++;	
       
   204 			inrand = *args;
       
   205 		    } else badarg = 1;
       
   206 		} else if (!strcmp (*args, "-inkey")) {
       
   207 		    if (args[1]) {
       
   208 			args++;	
       
   209 			keyname = *args;
       
   210 		    } else badarg = 1;
       
   211 		} else if (!strcmp (*args, "-certfile")) {
       
   212 		    if (args[1]) {
       
   213 			args++;	
       
   214 			certfile = *args;
       
   215 		    } else badarg = 1;
       
   216 		} else if (!strcmp (*args, "-name")) {
       
   217 		    if (args[1]) {
       
   218 			args++;	
       
   219 			name = *args;
       
   220 		    } else badarg = 1;
       
   221 		} else if (!strcmp (*args, "-CSP")) {
       
   222 		    if (args[1]) {
       
   223 			args++;	
       
   224 			csp_name = *args;
       
   225 		    } else badarg = 1;
       
   226 		} else if (!strcmp (*args, "-caname")) {
       
   227 		    if (args[1]) {
       
   228 			args++;	
       
   229 			if (!canames) canames = sk_new_null();
       
   230 			sk_push(canames, *args);
       
   231 		    } else badarg = 1;
       
   232 		} else if (!strcmp (*args, "-in")) {
       
   233 		    if (args[1]) {
       
   234 			args++;	
       
   235 			infile = *args;
       
   236 		    } else badarg = 1;
       
   237 		} else if (!strcmp (*args, "-out")) {
       
   238 		    if (args[1]) {
       
   239 			args++;	
       
   240 			outfile = *args;
       
   241 		    } else badarg = 1;
       
   242 		} else if (!strcmp(*args,"-passin")) {
       
   243 		    if (args[1]) {
       
   244 			args++;	
       
   245 			passargin = *args;
       
   246 		    } else badarg = 1;
       
   247 		} else if (!strcmp(*args,"-passout")) {
       
   248 		    if (args[1]) {
       
   249 			args++;	
       
   250 			passargout = *args;
       
   251 		    } else badarg = 1;
       
   252 		} else if (!strcmp (*args, "-password")) {
       
   253 		    if (args[1]) {
       
   254 			args++;	
       
   255 			passarg = *args;
       
   256 		    	noprompt = 1;
       
   257 		    } else badarg = 1;
       
   258 		} else if (!strcmp(*args,"-CApath")) {
       
   259 		    if (args[1]) {
       
   260 			args++;	
       
   261 			CApath = *args;
       
   262 		    } else badarg = 1;
       
   263 		} else if (!strcmp(*args,"-CAfile")) {
       
   264 		    if (args[1]) {
       
   265 			args++;	
       
   266 			CAfile = *args;
       
   267 		    } else badarg = 1;
       
   268 #ifndef OPENSSL_NO_ENGINE
       
   269 		} else if (!strcmp(*args,"-engine")) {
       
   270 		    if (args[1]) {
       
   271 			args++;	
       
   272 			engine = *args;
       
   273 		    } else badarg = 1;
       
   274 #endif
       
   275 		} else badarg = 1;
       
   276 
       
   277 	} else badarg = 1;
       
   278 	args++;
       
   279     }
       
   280 
       
   281     if (badarg) {
       
   282 	BIO_printf (bio_err, "Usage: pkcs12 [options]\n");
       
   283 	BIO_printf (bio_err, "where options are\n");
       
   284 	BIO_printf (bio_err, "-export       output PKCS12 file\n");
       
   285 	BIO_printf (bio_err, "-chain        add certificate chain\n");
       
   286 	BIO_printf (bio_err, "-inkey file   private key if not infile\n");
       
   287 	BIO_printf (bio_err, "-certfile f   add all certs in f\n");
       
   288 	BIO_printf (bio_err, "-CApath arg   - PEM format directory of CA's\n");
       
   289 	BIO_printf (bio_err, "-CAfile arg   - PEM format file of CA's\n");
       
   290 	BIO_printf (bio_err, "-name \"name\"  use name as friendly name\n");
       
   291 	BIO_printf (bio_err, "-caname \"nm\"  use nm as CA friendly name (can be used more than once).\n");
       
   292 	BIO_printf (bio_err, "-in  infile   input filename\n");
       
   293 	BIO_printf (bio_err, "-out outfile  output filename\n");
       
   294 	BIO_printf (bio_err, "-noout        don't output anything, just verify.\n");
       
   295 	BIO_printf (bio_err, "-nomacver     don't verify MAC.\n");
       
   296 	BIO_printf (bio_err, "-nocerts      don't output certificates.\n");
       
   297 	BIO_printf (bio_err, "-clcerts      only output client certificates.\n");
       
   298 	BIO_printf (bio_err, "-cacerts      only output CA certificates.\n");
       
   299 	BIO_printf (bio_err, "-nokeys       don't output private keys.\n");
       
   300 	BIO_printf (bio_err, "-info         give info about PKCS#12 structure.\n");
       
   301 	BIO_printf (bio_err, "-des          encrypt private keys with DES\n");
       
   302 	BIO_printf (bio_err, "-des3         encrypt private keys with triple DES (default)\n");
       
   303 #ifndef OPENSSL_NO_IDEA
       
   304 	BIO_printf (bio_err, "-idea         encrypt private keys with idea\n");
       
   305 #endif
       
   306 #ifndef OPENSSL_NO_AES
       
   307 	BIO_printf (bio_err, "-aes128, -aes192, -aes256\n");
       
   308 	BIO_printf (bio_err, "              encrypt PEM output with cbc aes\n");
       
   309 #endif
       
   310 	BIO_printf (bio_err, "-nodes        don't encrypt private keys\n");
       
   311 	BIO_printf (bio_err, "-noiter       don't use encryption iteration\n");
       
   312 	BIO_printf (bio_err, "-maciter      use MAC iteration\n");
       
   313 	BIO_printf (bio_err, "-twopass      separate MAC, encryption passwords\n");
       
   314 	BIO_printf (bio_err, "-descert      encrypt PKCS#12 certificates with triple DES (default RC2-40)\n");
       
   315 	BIO_printf (bio_err, "-certpbe alg  specify certificate PBE algorithm (default RC2-40)\n");
       
   316 	BIO_printf (bio_err, "-keypbe alg   specify private key PBE algorithm (default 3DES)\n");
       
   317 	BIO_printf (bio_err, "-keyex        set MS key exchange type\n");
       
   318 	BIO_printf (bio_err, "-keysig       set MS key signature type\n");
       
   319 	BIO_printf (bio_err, "-password p   set import/export password source\n");
       
   320 	BIO_printf (bio_err, "-passin p     input file pass phrase source\n");
       
   321 	BIO_printf (bio_err, "-passout p    output file pass phrase source\n");
       
   322 #ifndef OPENSSL_NO_ENGINE
       
   323 	BIO_printf (bio_err, "-engine e     use engine e, possibly a hardware device.\n");
       
   324 #endif
       
   325 	BIO_printf(bio_err,  "-rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
       
   326 	BIO_printf(bio_err,  "              load the file (or the files in the directory) into\n");
       
   327 	BIO_printf(bio_err,  "              the random number generator\n");
       
   328     	goto end;
       
   329     }
       
   330 
       
   331 #ifndef OPENSSL_NO_ENGINE
       
   332     e = setup_engine(bio_err, engine, 0);
       
   333 #endif
       
   334 
       
   335     if(passarg) {
       
   336 	if(export_cert) passargout = passarg;
       
   337 	else passargin = passarg;
       
   338     }
       
   339 
       
   340     if(!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
       
   341 	BIO_printf(bio_err, "Error getting passwords\n");
       
   342 	goto end;
       
   343     }
       
   344 
       
   345     if(!cpass) {
       
   346     	if(export_cert) cpass = passout;
       
   347     	else cpass = passin;
       
   348     }
       
   349 
       
   350     if(cpass) {
       
   351 	mpass = cpass;
       
   352 	noprompt = 1;
       
   353     } else {
       
   354 	cpass = pass;
       
   355 	mpass = macpass;
       
   356     }
       
   357 
       
   358     if(export_cert || inrand) {
       
   359     	app_RAND_load_file(NULL, bio_err, (inrand != NULL));
       
   360         if (inrand != NULL)
       
   361 		BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
       
   362 			app_RAND_load_files(inrand));
       
   363     }
       
   364     ERR_load_crypto_strings();
       
   365 
       
   366 #ifdef CRYPTO_MDEBUG
       
   367     CRYPTO_push_info("read files");
       
   368 #endif
       
   369     if (!infile) in = BIO_new_fp(stdin, BIO_NOCLOSE);
       
   370     else in = BIO_new_file(infile, "rb");
       
   371     if (!in) {
       
   372 	    BIO_printf(bio_err, "Error opening input file %s\n",
       
   373 						infile ? infile : "<stdin>");
       
   374 	    perror (infile);
       
   375 	    goto end;
       
   376    }
       
   377 
       
   378 #ifdef CRYPTO_MDEBUG
       
   379     CRYPTO_pop_info();
       
   380     CRYPTO_push_info("write files");
       
   381 #endif
       
   382 
       
   383     if (!outfile) {
       
   384 	out = BIO_new_fp(stdout, BIO_NOCLOSE);
       
   385 
       
   386 #ifdef OPENSSL_SYS_VMS
       
   387 	{
       
   388 	    BIO *tmpbio = BIO_new(BIO_f_linebuffer());
       
   389 	    out = BIO_push(tmpbio, out);
       
   390 	}
       
   391 #endif
       
   392     } else out = BIO_new_file(outfile, "wb");
       
   393     if (!out) {
       
   394 	BIO_printf(bio_err, "Error opening output file %s\n",
       
   395 						outfile ? outfile : "<stdout>");
       
   396 	perror (outfile);
       
   397 	goto end;
       
   398     }
       
   399     if (twopass) {
       
   400 #ifdef CRYPTO_MDEBUG
       
   401     CRYPTO_push_info("read MAC password");
       
   402 #endif
       
   403 	if(EVP_read_pw_string (macpass, sizeof macpass, "Enter MAC Password:", export_cert))
       
   404 	{
       
   405     	    BIO_printf (bio_err, "Can't read Password\n");
       
   406     	    goto end;
       
   407        	}
       
   408 #ifdef CRYPTO_MDEBUG
       
   409     CRYPTO_pop_info();
       
   410 #endif
       
   411     }
       
   412 
       
   413     if (export_cert) {
       
   414 	EVP_PKEY *key = NULL;
       
   415 	X509 *ucert = NULL, *x = NULL;
       
   416 	STACK_OF(X509) *certs=NULL;
       
   417 	unsigned char *catmp = NULL;
       
   418 	int i;
       
   419 
       
   420 	if ((options & (NOCERTS|NOKEYS)) == (NOCERTS|NOKEYS))
       
   421 		{	
       
   422 		BIO_printf(bio_err, "Nothing to do!\n");
       
   423 		goto export_end;
       
   424 		}
       
   425 
       
   426 	if (options & NOCERTS)
       
   427 		chain = 0;
       
   428 
       
   429 #ifdef CRYPTO_MDEBUG
       
   430 	CRYPTO_push_info("process -export_cert");
       
   431 	CRYPTO_push_info("reading private key");
       
   432 #endif
       
   433 	if (!(options & NOKEYS))
       
   434 		{
       
   435 		key = load_key(bio_err, keyname ? keyname : infile,
       
   436 				FORMAT_PEM, 1, passin, e, "private key");
       
   437 		if (!key)
       
   438 			goto export_end;
       
   439 		}
       
   440 
       
   441 #ifdef CRYPTO_MDEBUG
       
   442 	CRYPTO_pop_info();
       
   443 	CRYPTO_push_info("reading certs from input");
       
   444 #endif
       
   445 
       
   446 	/* Load in all certs in input file */
       
   447 	if(!(options & NOCERTS))
       
   448 		{
       
   449 		certs = load_certs(bio_err, infile, FORMAT_PEM, NULL, e,
       
   450 							"certificates");
       
   451 		if (!certs)
       
   452 			goto export_end;
       
   453 
       
   454 		if (key)
       
   455 			{
       
   456 			/* Look for matching private key */
       
   457 			for(i = 0; i < sk_X509_num(certs); i++)
       
   458 				{
       
   459 				x = sk_X509_value(certs, i);
       
   460 				if(X509_check_private_key(x, key))
       
   461 					{
       
   462 					ucert = x;
       
   463 					/* Zero keyid and alias */
       
   464 					X509_keyid_set1(ucert, NULL, 0);
       
   465 					X509_alias_set1(ucert, NULL, 0);
       
   466 					/* Remove from list */
       
   467 					(void)sk_X509_delete(certs, i);
       
   468 					break;
       
   469 					}
       
   470 				}
       
   471 			if (!ucert)
       
   472 				{
       
   473 				BIO_printf(bio_err, "No certificate matches private key\n");
       
   474 				goto export_end;
       
   475 				}
       
   476 			}
       
   477 
       
   478 		}
       
   479 
       
   480 #ifdef CRYPTO_MDEBUG
       
   481 	CRYPTO_pop_info();
       
   482 	CRYPTO_push_info("reading certs from input 2");
       
   483 #endif
       
   484 
       
   485 	/* Add any more certificates asked for */
       
   486 	if(certfile)
       
   487 		{
       
   488 		STACK_OF(X509) *morecerts=NULL;
       
   489 		if(!(morecerts = load_certs(bio_err, certfile, FORMAT_PEM,
       
   490 					    NULL, e,
       
   491 					    "certificates from certfile")))
       
   492 			goto export_end;
       
   493 		while(sk_X509_num(morecerts) > 0)
       
   494 			sk_X509_push(certs, sk_X509_shift(morecerts));
       
   495 		sk_X509_free(morecerts);
       
   496  		}
       
   497 
       
   498 #ifdef CRYPTO_MDEBUG
       
   499 	CRYPTO_pop_info();
       
   500 	CRYPTO_push_info("reading certs from certfile");
       
   501 #endif
       
   502 
       
   503 #ifdef CRYPTO_MDEBUG
       
   504 	CRYPTO_pop_info();
       
   505 	CRYPTO_push_info("building chain");
       
   506 #endif
       
   507 
       
   508 	/* If chaining get chain from user cert */
       
   509 	if (chain) {
       
   510         	int vret;
       
   511 		STACK_OF(X509) *chain2;
       
   512 		X509_STORE *store = X509_STORE_new();
       
   513 		if (!store)
       
   514 			{
       
   515 			BIO_printf (bio_err, "Memory allocation error\n");
       
   516 			goto export_end;
       
   517 			}
       
   518 		if (!X509_STORE_load_locations(store, CAfile, CApath))
       
   519 			X509_STORE_set_default_paths (store);
       
   520 
       
   521 		vret = get_cert_chain (ucert, store, &chain2);
       
   522 		X509_STORE_free(store);
       
   523 
       
   524 		if (!vret) {
       
   525 		    /* Exclude verified certificate */
       
   526 		    for (i = 1; i < sk_X509_num (chain2) ; i++) 
       
   527 			sk_X509_push(certs, sk_X509_value (chain2, i));
       
   528 		    /* Free first certificate */
       
   529 		    X509_free(sk_X509_value(chain2, 0));
       
   530 		    sk_X509_free(chain2);
       
   531 		} else {
       
   532 			if (vret >= 0)
       
   533 			BIO_printf (bio_err, "Error %s getting chain.\n",
       
   534 					X509_verify_cert_error_string(vret));
       
   535 			else
       
   536 				ERR_print_errors(bio_err);
       
   537 			goto export_end;
       
   538 		}			
       
   539     	}
       
   540 
       
   541 	/* Add any CA names */
       
   542 
       
   543 	for (i = 0; i < sk_num(canames); i++)
       
   544 		{
       
   545 		catmp = (unsigned char *)sk_value(canames, i);
       
   546 		X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
       
   547 		}
       
   548 
       
   549 	if (csp_name && key)
       
   550 		EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
       
   551 				MBSTRING_ASC, (unsigned char *)csp_name, -1);
       
   552 		
       
   553 
       
   554 #ifdef CRYPTO_MDEBUG
       
   555 	CRYPTO_pop_info();
       
   556 	CRYPTO_push_info("reading password");
       
   557 #endif
       
   558 
       
   559 	if(!noprompt &&
       
   560 		EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:", 1))
       
   561 		{
       
   562 	    	BIO_printf (bio_err, "Can't read Password\n");
       
   563 	    	goto export_end;
       
   564         	}
       
   565 	if (!twopass) BUF_strlcpy(macpass, pass, sizeof macpass);
       
   566 
       
   567 #ifdef CRYPTO_MDEBUG
       
   568 	CRYPTO_pop_info();
       
   569 	CRYPTO_push_info("creating PKCS#12 structure");
       
   570 #endif
       
   571 
       
   572 	p12 = PKCS12_create(cpass, name, key, ucert, certs,
       
   573 				key_pbe, cert_pbe, iter, -1, keytype);
       
   574 
       
   575 	if (!p12)
       
   576 		{
       
   577 	    	ERR_print_errors (bio_err);
       
   578 		goto export_end;
       
   579 		}
       
   580 
       
   581 	if (maciter != -1)
       
   582 		PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, NULL);
       
   583 
       
   584 #ifdef CRYPTO_MDEBUG
       
   585 	CRYPTO_pop_info();
       
   586 	CRYPTO_push_info("writing pkcs12");
       
   587 #endif
       
   588 
       
   589 	i2d_PKCS12_bio(out, p12);
       
   590 
       
   591 	ret = 0;
       
   592 
       
   593     export_end:
       
   594 #ifdef CRYPTO_MDEBUG
       
   595 	CRYPTO_pop_info();
       
   596 	CRYPTO_pop_info();
       
   597 	CRYPTO_push_info("process -export_cert: freeing");
       
   598 #endif
       
   599 
       
   600 	if (key) EVP_PKEY_free(key);
       
   601 	if (certs) sk_X509_pop_free(certs, X509_free);
       
   602 	if (ucert) X509_free(ucert);
       
   603 
       
   604 #ifdef CRYPTO_MDEBUG
       
   605 	CRYPTO_pop_info();
       
   606 #endif
       
   607 	goto end;
       
   608 	
       
   609     }
       
   610 
       
   611     if (!(p12 = d2i_PKCS12_bio (in, NULL))) {
       
   612 	ERR_print_errors(bio_err);
       
   613 	goto end;
       
   614     }
       
   615 
       
   616 #ifdef CRYPTO_MDEBUG
       
   617     CRYPTO_push_info("read import password");
       
   618 #endif
       
   619     if(!noprompt && EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:", 0)) {
       
   620 	BIO_printf (bio_err, "Can't read Password\n");
       
   621 	goto end;
       
   622     }
       
   623 #ifdef CRYPTO_MDEBUG
       
   624     CRYPTO_pop_info();
       
   625 #endif
       
   626 
       
   627     if (!twopass) BUF_strlcpy(macpass, pass, sizeof macpass);
       
   628 
       
   629     if (options & INFO) BIO_printf (bio_err, "MAC Iteration %ld\n", p12->mac->iter ? ASN1_INTEGER_get (p12->mac->iter) : 1);
       
   630     if(macver) {
       
   631 #ifdef CRYPTO_MDEBUG
       
   632     CRYPTO_push_info("verify MAC");
       
   633 #endif
       
   634 	/* If we enter empty password try no password first */
       
   635 	if(!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
       
   636 		/* If mac and crypto pass the same set it to NULL too */
       
   637 		if(!twopass) cpass = NULL;
       
   638 	} else if (!PKCS12_verify_mac(p12, mpass, -1)) {
       
   639 	    BIO_printf (bio_err, "Mac verify error: invalid password?\n");
       
   640 	    ERR_print_errors (bio_err);
       
   641 	    goto end;
       
   642 	}
       
   643 	BIO_printf (bio_err, "MAC verified OK\n");
       
   644 #ifdef CRYPTO_MDEBUG
       
   645     CRYPTO_pop_info();
       
   646 #endif
       
   647     }
       
   648 
       
   649 #ifdef CRYPTO_MDEBUG
       
   650     CRYPTO_push_info("output keys and certificates");
       
   651 #endif
       
   652     if (!dump_certs_keys_p12 (out, p12, cpass, -1, options, passout)) {
       
   653 	BIO_printf(bio_err, "Error outputting keys and certificates\n");
       
   654 	ERR_print_errors (bio_err);
       
   655 	goto end;
       
   656     }
       
   657 #ifdef CRYPTO_MDEBUG
       
   658     CRYPTO_pop_info();
       
   659 #endif
       
   660     ret = 0;
       
   661  end:
       
   662     if (p12) PKCS12_free(p12);
       
   663     if(export_cert || inrand) app_RAND_write_file(NULL, bio_err);
       
   664 #ifdef CRYPTO_MDEBUG
       
   665     CRYPTO_remove_all_info();
       
   666 #endif
       
   667     BIO_free(in);
       
   668     BIO_free_all(out);
       
   669     if (canames) sk_free(canames);
       
   670     if(passin) OPENSSL_free(passin);
       
   671     if(passout) OPENSSL_free(passout);
       
   672     apps_shutdown();
       
   673     OPENSSL_EXIT(ret);
       
   674 }
       
   675 
       
   676 int dump_certs_keys_p12 (BIO *out, PKCS12 *p12, char *pass,
       
   677 	     int passlen, int options, char *pempass)
       
   678 {
       
   679 	STACK_OF(PKCS7) *asafes = NULL;
       
   680 	STACK_OF(PKCS12_SAFEBAG) *bags;
       
   681 	int i, bagnid;
       
   682 	int ret = 0;
       
   683 	PKCS7 *p7;
       
   684 
       
   685 	if (!( asafes = PKCS12_unpack_authsafes(p12))) return 0;
       
   686 	for (i = 0; i < sk_PKCS7_num (asafes); i++) {
       
   687 		p7 = sk_PKCS7_value (asafes, i);
       
   688 		bagnid = OBJ_obj2nid (p7->type);
       
   689 		if (bagnid == NID_pkcs7_data) {
       
   690 			bags = PKCS12_unpack_p7data(p7);
       
   691 			if (options & INFO) BIO_printf (bio_err, "PKCS7 Data\n");
       
   692 		} else if (bagnid == NID_pkcs7_encrypted) {
       
   693 			if (options & INFO) {
       
   694 				BIO_printf(bio_err, "PKCS7 Encrypted data: ");
       
   695 				alg_print(bio_err, 
       
   696 					p7->d.encrypted->enc_data->algorithm);
       
   697 			}
       
   698 			bags = PKCS12_unpack_p7encdata(p7, pass, passlen);
       
   699 		} else continue;
       
   700 		if (!bags) goto err;
       
   701 	    	if (!dump_certs_pkeys_bags (out, bags, pass, passlen, 
       
   702 						 options, pempass)) {
       
   703 			sk_PKCS12_SAFEBAG_pop_free (bags, PKCS12_SAFEBAG_free);
       
   704 			goto err;
       
   705 		}
       
   706 		sk_PKCS12_SAFEBAG_pop_free (bags, PKCS12_SAFEBAG_free);
       
   707 		bags = NULL;
       
   708 	}
       
   709 	ret = 1;
       
   710 
       
   711 	err:
       
   712 
       
   713 	if (asafes)
       
   714 		sk_PKCS7_pop_free (asafes, PKCS7_free);
       
   715 	return ret;
       
   716 }
       
   717 
       
   718 int dump_certs_pkeys_bags (BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags,
       
   719 			   char *pass, int passlen, int options, char *pempass)
       
   720 {
       
   721 	int i;
       
   722 	for (i = 0; i < sk_PKCS12_SAFEBAG_num (bags); i++) {
       
   723 		if (!dump_certs_pkeys_bag (out,
       
   724 					   sk_PKCS12_SAFEBAG_value (bags, i),
       
   725 					   pass, passlen,
       
   726 					   options, pempass))
       
   727 		    return 0;
       
   728 	}
       
   729 	return 1;
       
   730 }
       
   731 
       
   732 int dump_certs_pkeys_bag (BIO *out, PKCS12_SAFEBAG *bag, char *pass,
       
   733 	     int passlen, int options, char *pempass)
       
   734 {
       
   735 	EVP_PKEY *pkey;
       
   736 	PKCS8_PRIV_KEY_INFO *p8;
       
   737 	X509 *x509;
       
   738 	
       
   739 	switch (M_PKCS12_bag_type(bag))
       
   740 	{
       
   741 	case NID_keyBag:
       
   742 		if (options & INFO) BIO_printf (bio_err, "Key bag\n");
       
   743 		if (options & NOKEYS) return 1;
       
   744 		print_attribs (out, bag->attrib, "Bag Attributes");
       
   745 		p8 = bag->value.keybag;
       
   746 		if (!(pkey = EVP_PKCS82PKEY (p8))) return 0;
       
   747 		print_attribs (out, p8->attributes, "Key Attributes");
       
   748 		PEM_write_bio_PrivateKey (out, pkey, enc, NULL, 0, NULL, pempass);
       
   749 		EVP_PKEY_free(pkey);
       
   750 	break;
       
   751 
       
   752 	case NID_pkcs8ShroudedKeyBag:
       
   753 		if (options & INFO) {
       
   754 			BIO_printf (bio_err, "Shrouded Keybag: ");
       
   755 			alg_print (bio_err, bag->value.shkeybag->algor);
       
   756 		}
       
   757 		if (options & NOKEYS) return 1;
       
   758 		print_attribs (out, bag->attrib, "Bag Attributes");
       
   759 		if (!(p8 = PKCS12_decrypt_skey(bag, pass, passlen)))
       
   760 				return 0;
       
   761 		if (!(pkey = EVP_PKCS82PKEY (p8))) {
       
   762 			PKCS8_PRIV_KEY_INFO_free(p8);
       
   763 			return 0;
       
   764 		}
       
   765 		print_attribs (out, p8->attributes, "Key Attributes");
       
   766 		PKCS8_PRIV_KEY_INFO_free(p8);
       
   767 		PEM_write_bio_PrivateKey (out, pkey, enc, NULL, 0, NULL, pempass);
       
   768 		EVP_PKEY_free(pkey);
       
   769 	break;
       
   770 
       
   771 	case NID_certBag:
       
   772 		if (options & INFO) BIO_printf (bio_err, "Certificate bag\n");
       
   773 		if (options & NOCERTS) return 1;
       
   774                 if (PKCS12_get_attr(bag, NID_localKeyID)) {
       
   775 			if (options & CACERTS) return 1;
       
   776 		} else if (options & CLCERTS) return 1;
       
   777 		print_attribs (out, bag->attrib, "Bag Attributes");
       
   778 		if (M_PKCS12_cert_bag_type(bag) != NID_x509Certificate )
       
   779 								 return 1;
       
   780 		if (!(x509 = PKCS12_certbag2x509(bag))) return 0;
       
   781 		dump_cert_text (out, x509);
       
   782 		PEM_write_bio_X509 (out, x509);
       
   783 		X509_free(x509);
       
   784 	break;
       
   785 
       
   786 	case NID_safeContentsBag:
       
   787 		if (options & INFO) BIO_printf (bio_err, "Safe Contents bag\n");
       
   788 		print_attribs (out, bag->attrib, "Bag Attributes");
       
   789 		return dump_certs_pkeys_bags (out, bag->value.safes, pass,
       
   790 							    passlen, options, pempass);
       
   791 					
       
   792 	default:
       
   793 		BIO_printf (bio_err, "Warning unsupported bag type: ");
       
   794 		i2a_ASN1_OBJECT (bio_err, bag->type);
       
   795 		BIO_printf (bio_err, "\n");
       
   796 		return 1;
       
   797 	break;
       
   798 	}
       
   799 	return 1;
       
   800 }
       
   801 
       
   802 /* Given a single certificate return a verified chain or NULL if error */
       
   803 
       
   804 /* Hope this is OK .... */
       
   805 
       
   806 int get_cert_chain (X509 *cert, X509_STORE *store, STACK_OF(X509) **chain)
       
   807 {
       
   808 	X509_STORE_CTX store_ctx;
       
   809 	STACK_OF(X509) *chn;
       
   810 	int i = 0;
       
   811 
       
   812 	/* FIXME: Should really check the return status of X509_STORE_CTX_init
       
   813 	 * for an error, but how that fits into the return value of this
       
   814 	 * function is less obvious. */
       
   815 	X509_STORE_CTX_init(&store_ctx, store, cert, NULL);
       
   816 	if (X509_verify_cert(&store_ctx) <= 0) {
       
   817 		i = X509_STORE_CTX_get_error (&store_ctx);
       
   818 		if (i == 0)
       
   819 			/* avoid returning 0 if X509_verify_cert() did not
       
   820 			 * set an appropriate error value in the context */
       
   821 			i = -1;
       
   822 		chn = NULL;
       
   823 		goto err;
       
   824 	} else
       
   825 	chn =  X509_STORE_CTX_get1_chain(&store_ctx);
       
   826 err:
       
   827 	X509_STORE_CTX_cleanup(&store_ctx);
       
   828 	*chain = chn;
       
   829 	
       
   830 	return i;
       
   831 }	
       
   832 
       
   833 int alg_print (BIO *x, X509_ALGOR *alg)
       
   834 {
       
   835 	PBEPARAM *pbe;
       
   836 	const unsigned char *p;
       
   837 	p = alg->parameter->value.sequence->data;
       
   838 	pbe = d2i_PBEPARAM (NULL, &p, alg->parameter->value.sequence->length);
       
   839 	if (!pbe)
       
   840 		return 1;
       
   841 	BIO_printf (bio_err, "%s, Iteration %ld\n", 
       
   842 		OBJ_nid2ln(OBJ_obj2nid(alg->algorithm)),
       
   843 		ASN1_INTEGER_get(pbe->iter));
       
   844 	PBEPARAM_free (pbe);
       
   845 	return 1;
       
   846 }
       
   847 
       
   848 /* Load all certificates from a given file */
       
   849 
       
   850 int cert_load(BIO *in, STACK_OF(X509) *sk)
       
   851 {
       
   852 	int ret;
       
   853 	X509 *cert;
       
   854 	ret = 0;
       
   855 #ifdef CRYPTO_MDEBUG
       
   856 	CRYPTO_push_info("cert_load(): reading one cert");
       
   857 #endif
       
   858 	while((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
       
   859 #ifdef CRYPTO_MDEBUG
       
   860 		CRYPTO_pop_info();
       
   861 #endif
       
   862 		ret = 1;
       
   863 		sk_X509_push(sk, cert);
       
   864 #ifdef CRYPTO_MDEBUG
       
   865 		CRYPTO_push_info("cert_load(): reading one cert");
       
   866 #endif
       
   867 	}
       
   868 #ifdef CRYPTO_MDEBUG
       
   869 	CRYPTO_pop_info();
       
   870 #endif
       
   871 	if(ret) ERR_clear_error();
       
   872 	return ret;
       
   873 }
       
   874 
       
   875 /* Generalised attribute print: handle PKCS#8 and bag attributes */
       
   876 
       
   877 int print_attribs (BIO *out, STACK_OF(X509_ATTRIBUTE) *attrlst,const char *name)
       
   878 {
       
   879 	X509_ATTRIBUTE *attr;
       
   880 	ASN1_TYPE *av;
       
   881 	char *value;
       
   882 	int i, attr_nid;
       
   883 	if(!attrlst) {
       
   884 		BIO_printf(out, "%s: <No Attributes>\n", name);
       
   885 		return 1;
       
   886 	}
       
   887 	if(!sk_X509_ATTRIBUTE_num(attrlst)) {
       
   888 		BIO_printf(out, "%s: <Empty Attributes>\n", name);
       
   889 		return 1;
       
   890 	}
       
   891 	BIO_printf(out, "%s\n", name);
       
   892 	for(i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) {
       
   893 		attr = sk_X509_ATTRIBUTE_value(attrlst, i);
       
   894 		attr_nid = OBJ_obj2nid(attr->object);
       
   895 		BIO_printf(out, "    ");
       
   896 		if(attr_nid == NID_undef) {
       
   897 			i2a_ASN1_OBJECT (out, attr->object);
       
   898 			BIO_printf(out, ": ");
       
   899 		} else BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
       
   900 
       
   901 		if(sk_ASN1_TYPE_num(attr->value.set)) {
       
   902 			av = sk_ASN1_TYPE_value(attr->value.set, 0);
       
   903 			switch(av->type) {
       
   904 				case V_ASN1_BMPSTRING:
       
   905         			value = uni2asc(av->value.bmpstring->data,
       
   906                                 	       av->value.bmpstring->length);
       
   907 				BIO_printf(out, "%s\n", value);
       
   908 				OPENSSL_free(value);
       
   909 				break;
       
   910 
       
   911 				case V_ASN1_OCTET_STRING:
       
   912 				hex_prin(out, av->value.octet_string->data,
       
   913 					av->value.octet_string->length);
       
   914 				BIO_printf(out, "\n");	
       
   915 				break;
       
   916 
       
   917 				case V_ASN1_BIT_STRING:
       
   918 				hex_prin(out, av->value.bit_string->data,
       
   919 					av->value.bit_string->length);
       
   920 				BIO_printf(out, "\n");	
       
   921 				break;
       
   922 
       
   923 				default:
       
   924 					BIO_printf(out, "<Unsupported tag %d>\n", av->type);
       
   925 				break;
       
   926 			}
       
   927 		} else BIO_printf(out, "<No Values>\n");
       
   928 	}
       
   929 	return 1;
       
   930 }
       
   931 
       
   932 void hex_prin(BIO *out, unsigned char *buf, int len)
       
   933 {
       
   934 	int i;
       
   935 	for (i = 0; i < len; i++) BIO_printf (out, "%02X ", buf[i]);
       
   936 }
       
   937 
       
   938 #endif