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