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