Fix const declarations.
[openssl.git] / apps / pkcs12.c
1 /* pkcs12.c */
2 /* Written by Dr Stephen N Henson (shenson@bigfoot.com) for the OpenSSL
3  * project 1999.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999 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 <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <pem.h>
63 #include <err.h>
64 #include "pkcs12.h"
65
66 #include "apps.h"
67 #define PROG pkcs12_main
68
69 EVP_CIPHER *enc;
70
71 #define _ITER_ 1000
72
73 #define NOKEYS          0x1
74 #define NOCERTS         0x2
75 #define INFO            0x4
76 #define CLCERTS         0x8
77 #define CACERTS         0x10
78
79 #ifndef NOPROTO
80 int get_cert_chain(X509 *cert, STACK **chain);
81 int dump_certs_keys_p12(BIO *out, PKCS12 *p12, unsigned char *pass, int passlen, int options);
82 int dump_certs_pkeys_bags(BIO *out, STACK *bags, unsigned char *pass, int passlen, int options);
83 int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bags, unsigned char *pass, int passlen, int options);
84 int print_attribs(BIO *out, STACK *attrlst, char *name);
85 void hex_prin(BIO *out, unsigned char *buf, int len);
86 int alg_print(BIO *x, X509_ALGOR *alg);
87 int cert_load(BIO *in, STACK *sk);
88 #else
89 int get_cert_chain();
90 int dump_certs_keys_p12();
91 int dump_certs_pkeys_bags();
92 int dump_certs_pkeys_bag();
93 int print_attribs();
94 void hex_prin();
95 int alg_print();
96 int cert_load();
97 #endif
98
99 int MAIN(argc, argv)
100 int argc;
101 char **argv;
102 {
103     char *infile=NULL, *outfile=NULL, *keyname = NULL;  
104     char *certfile=NULL;
105     BIO *in=NULL, *out = NULL, *inkey = NULL, *certsin = NULL;
106     char **args;
107     char *name = NULL;
108     PKCS12 *p12 = NULL;
109     char pass[50], macpass[50];
110     int export_cert = 0;
111     int options = 0;
112     int chain = 0;
113     int badarg = 0;
114     int iter = _ITER_;
115     int maciter = 1;
116     int twopass = 0;
117     int keytype = 0;
118     int cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
119     int ret = 1;
120     int macver = 1;
121     STACK *canames = NULL;
122
123     apps_startup();
124
125     enc = EVP_des_ede3_cbc();
126     if (bio_err == NULL ) bio_err = BIO_new_fp (stderr, BIO_NOCLOSE);
127
128     args = argv + 1;
129
130
131     while (*args) {
132         if (*args[0] == '-') {
133                 if (!strcmp (*args, "-nokeys")) options |= NOKEYS;
134                 else if (!strcmp (*args, "-keyex")) keytype = KEY_EX;
135                 else if (!strcmp (*args, "-keysig")) keytype = KEY_SIG;
136                 else if (!strcmp (*args, "-nocerts")) options |= NOCERTS;
137                 else if (!strcmp (*args, "-clcerts")) options |= CLCERTS;
138                 else if (!strcmp (*args, "-cacerts")) options |= CACERTS;
139                 else if (!strcmp (*args, "-noout")) options |= (NOKEYS|NOCERTS);
140                 else if (!strcmp (*args, "-info")) options |= INFO;
141                 else if (!strcmp (*args, "-chain")) chain = 1;
142                 else if (!strcmp (*args, "-twopass")) twopass = 1;
143                 else if (!strcmp (*args, "-nomacver")) macver = 0;
144                 else if (!strcmp (*args, "-descert"))
145                         cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
146                 else if (!strcmp (*args, "-export")) export_cert = 1;
147                 else if (!strcmp (*args, "-des")) enc=EVP_des_cbc();
148 #ifndef NO_IDEA
149                 else if (!strcmp (*args, "-idea")) enc=EVP_idea_cbc();
150 #endif
151                 else if (!strcmp (*args, "-des3")) enc = EVP_des_ede3_cbc();
152                 else if (!strcmp (*args, "-noiter")) iter = 1;
153                 else if (!strcmp (*args, "-maciter")) maciter = _ITER_;
154                 else if (!strcmp (*args, "-nodes")) enc=NULL;
155                 else if (!strcmp (*args, "-inkey")) {
156                     if (args[1]) {
157                         args++; 
158                         keyname = *args;
159                     } else badarg = 1;
160                 } else if (!strcmp (*args, "-certfile")) {
161                     if (args[1]) {
162                         args++; 
163                         certfile = *args;
164                     } else badarg = 1;
165                 } else if (!strcmp (*args, "-name")) {
166                     if (args[1]) {
167                         args++; 
168                         name = *args;
169                     } else badarg = 1;
170                 } else if (!strcmp (*args, "-caname")) {
171                     if (args[1]) {
172                         args++; 
173                         if (!canames) canames = sk_new(NULL);
174                         sk_push(canames, *args);
175                     } else badarg = 1;
176                 } else if (!strcmp (*args, "-in")) {
177                     if (args[1]) {
178                         args++; 
179                         infile = *args;
180                     } else badarg = 1;
181                 } else if (!strcmp (*args, "-out")) {
182                     if (args[1]) {
183                         args++; 
184                         outfile = *args;
185                     } else badarg = 1;
186                 } else badarg = 1;
187
188         } else badarg = 1;
189         args++;
190     }
191
192     if (badarg) {
193         BIO_printf (bio_err, "Usage: pkcs12 [options]\n");
194         BIO_printf (bio_err, "where options are\n");
195         BIO_printf (bio_err, "-export       output PKCS12 file\n");
196         BIO_printf (bio_err, "-chain        add certificate chain\n");
197         BIO_printf (bio_err, "-inkey file   private key if not infile\n");
198         BIO_printf (bio_err, "-certfile f   add all certs in f\n");
199         BIO_printf (bio_err, "-name \"name\"  use name as friendly name\n");
200         BIO_printf (bio_err, "-caname \"nm\"  use nm as CA friendly name (can be used more than once).\n");
201         BIO_printf (bio_err, "-in  infile   input filename\n");
202         BIO_printf (bio_err, "-out outfile  output filename\n");
203         BIO_printf (bio_err, "-noout        don't output anything, just verify.\n");
204         BIO_printf (bio_err, "-nomacver     don't verify MAC.\n");
205         BIO_printf (bio_err, "-nocerts      don't output certificates.\n");
206         BIO_printf (bio_err, "-clcerts      only output client certificates.\n");
207         BIO_printf (bio_err, "-cacerts      only output CA certificates.\n");
208         BIO_printf (bio_err, "-nokeys       don't output private keys.\n");
209         BIO_printf (bio_err, "-info         give info about PKCS#12 structure.\n");
210         BIO_printf (bio_err, "-des          encrypt private keys with DES\n");
211         BIO_printf (bio_err, "-des3         encrypt private keys with triple DES (default)\n");
212 #ifndef NO_IDEA
213         BIO_printf (bio_err, "-idea         encrypt private keys with idea\n");
214 #endif
215         BIO_printf (bio_err, "-nodes        don't encrypt private keys\n");
216         BIO_printf (bio_err, "-noiter       don't use encryption iteration\n");
217         BIO_printf (bio_err, "-maciter      use MAC iteration\n");
218         BIO_printf (bio_err, "-twopass      separate MAC, encryption passwords\n");
219         BIO_printf (bio_err, "-descert      encrypt PKCS#12 certificates with triple DES (default RC2-40)\n");
220         BIO_printf (bio_err, "-keyex        set MS key exchange type\n");
221         BIO_printf (bio_err, "-keysig       set MS key signature type\n");
222         goto end;
223     }
224
225     ERR_load_crypto_strings();
226
227     in = BIO_new (BIO_s_file());
228     out = BIO_new (BIO_s_file());
229
230     if (!infile) BIO_set_fp (in, stdin, BIO_NOCLOSE);
231     else {
232         if (BIO_read_filename (in, infile) <= 0) {
233             perror (infile);
234             goto end;
235         }
236     }
237
238    if (certfile) {
239         certsin = BIO_new (BIO_s_file());
240         if (BIO_read_filename (certsin, certfile) <= 0) {
241             perror (certfile);
242             goto end;
243         }
244     }
245
246     if (keyname) {
247         inkey = BIO_new (BIO_s_file());
248         if (BIO_read_filename (inkey, keyname) <= 0) {
249             perror (keyname);
250             goto end;
251         }
252      }
253
254     if (!outfile) BIO_set_fp (out, stdout, BIO_NOCLOSE);
255     else {
256         if (BIO_write_filename (out, outfile) <= 0) {
257             perror (outfile);
258             goto end;
259         }
260     }
261     if (twopass) {
262         if(EVP_read_pw_string (macpass, 50, "Enter MAC Password:", export_cert)) {
263             BIO_printf (bio_err, "Can't read Password\n");
264             goto end;
265         }
266     }
267
268 if (export_cert) {
269         EVP_PKEY *key;
270         STACK *bags, *safes;
271         PKCS12_SAFEBAG *bag;
272         PKCS8_PRIV_KEY_INFO *p8;
273         PKCS7 *authsafe;
274         X509 *cert, *ucert = NULL;
275         STACK *certs;
276         char *catmp;
277         int i, pmatch = 0;
278         unsigned char keyid[EVP_MAX_MD_SIZE];
279         int keyidlen;
280         /* Get private key so we can match it to a certificate */
281         key = PEM_read_bio_PrivateKey(inkey ? inkey : in, NULL, NULL);
282         if (!inkey) BIO_reset(in);
283         if (!key) {
284                 BIO_printf (bio_err, "Error loading private key\n");
285                 ERR_print_errors(bio_err);
286                 goto end;
287         }
288
289         certs = sk_new(NULL);
290
291         /* Load in all certs in input file */
292         if(!cert_load(in, certs)) {
293                 BIO_printf(bio_err, "Error loading certificates from input\n");
294                 ERR_print_errors(bio_err);
295                 goto end;
296         }
297         
298         bags = sk_new (NULL);
299
300         /* Add any more certificates asked for */
301         if (certsin) {
302                 if(!cert_load(certsin, certs)) {
303                         BIO_printf(bio_err, "Error loading certificates from certfile\n");
304                         ERR_print_errors(bio_err);
305                         goto end;
306                 }
307                 BIO_free(certsin);
308         }
309
310         /* Find certificate (if any) matching private key */
311
312         for(i = 0; i < sk_num(certs); i++) {
313                         cert = (X509 *)sk_value(certs, i);
314                         if(X509_check_private_key(cert, key)) {
315                                 ucert = cert;
316                                 break;
317                         }
318         }
319
320         if(!ucert) {
321                 BIO_printf(bio_err, "No certificate matches private key\n");
322                 goto end;
323         }
324
325         /* If chaining get chain from user cert */
326         if (chain) {
327                 int vret;
328                 STACK *chain2;
329                         
330                 vret = get_cert_chain (ucert, &chain2);
331                 if (vret) {
332                         BIO_printf (bio_err, "Error %s getting chain.\n",
333                                         X509_verify_cert_error_string(vret));
334                         goto end;
335                 }
336                 /* Exclude verified certificate */
337                 for (i = 1; i < sk_num (chain2) ; i++) 
338                                  sk_push(certs, sk_value (chain2, i));
339                 sk_free(chain2);
340                         
341         }
342
343         /* We now have loads of certificates: include them all */
344         for(i = 0; i < sk_num(certs); i++) {
345                 cert = (X509 *)sk_value(certs, i);
346                 bag = M_PKCS12_x5092certbag(cert);
347                 /* If it matches private key mark it */
348                 if(cert == ucert) {
349                         if(name) PKCS12_add_friendlyname(bag, name, -1);
350                         X509_digest(cert, EVP_sha1(), keyid, &keyidlen);
351                         PKCS12_add_localkeyid(bag, keyid, keyidlen);
352                         pmatch = 1;
353                 } else if((catmp = sk_shift(canames))) 
354                                 PKCS12_add_friendlyname(bag, catmp, -1);
355                 sk_push(bags, (char *)bag);
356         }
357
358         if (canames) sk_free(canames);
359
360         if(EVP_read_pw_string (pass, 50, "Enter Export Password:", 1)) {
361             BIO_printf (bio_err, "Can't read Password\n");
362             goto end;
363         }
364         if (!twopass) strcpy(macpass, pass);
365         /* Turn certbags into encrypted authsafe */
366         authsafe = PKCS12_pack_p7encdata (cert_pbe, pass, -1, NULL, 0,
367                                                                  iter, bags);
368         sk_pop_free(bags, PKCS12_SAFEBAG_free);
369
370         if (!authsafe) {
371                 ERR_print_errors (bio_err);
372                 goto end;
373         }
374
375         safes = sk_new (NULL);
376         sk_push (safes, (char *)authsafe);
377
378         /* Make a shrouded key bag */
379         p8 = EVP_PKEY2PKCS8 (key);
380         EVP_PKEY_free(key);
381         if(keytype) PKCS8_add_keyusage(p8, keytype);
382         bag = PKCS12_MAKE_SHKEYBAG (NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
383                         pass, -1, NULL, 0, iter, p8);
384         PKCS8_PRIV_KEY_INFO_free(p8);
385         if (name) PKCS12_add_friendlyname (bag, name, -1);
386         PKCS12_add_localkeyid (bag, keyid, keyidlen);
387         bags = sk_new(NULL);
388         sk_push (bags, (char *)bag);
389         /* Turn it into unencrypted safe bag */
390         authsafe = PKCS12_pack_p7data (bags);
391         sk_pop_free(bags, PKCS12_SAFEBAG_free);
392         sk_push (safes, (char *)authsafe);
393
394         p12 = PKCS12_init (NID_pkcs7_data);
395
396         M_PKCS12_pack_authsafes (p12, safes);
397
398         sk_pop_free(safes, PKCS7_free);
399
400         PKCS12_set_mac (p12, macpass, -1, NULL, 0, maciter, NULL);
401
402         i2d_PKCS12_bio (out, p12);
403
404         PKCS12_free(p12);
405
406         ret = 0;
407         goto end;
408         
409 }
410
411     if (!(p12 = d2i_PKCS12_bio (in, NULL))) {
412         ERR_print_errors(bio_err);
413         goto end;
414     }
415
416     if(EVP_read_pw_string (pass, 50, "Enter Import Password:", 0)) {
417         BIO_printf (bio_err, "Can't read Password\n");
418         goto end;
419     }
420
421     if (!twopass) strcpy(macpass, pass);
422
423     if (options & INFO) BIO_printf (bio_err, "MAC Iteration %ld\n", p12->mac->iter ? ASN1_INTEGER_get (p12->mac->iter) : 1);
424     if(macver) {
425         if (!PKCS12_verify_mac (p12, macpass, -1)) {
426             BIO_printf (bio_err, "Mac verify errror: invalid password?\n");
427             ERR_print_errors (bio_err);
428             goto end;
429         } else BIO_printf (bio_err, "MAC verified OK\n");
430     }
431
432     if (!dump_certs_keys_p12 (out, p12, pass, -1, options)) {
433         BIO_printf(bio_err, "Error outputting keys and certificates\n");
434         ERR_print_errors (bio_err);
435         goto end;
436     }
437     PKCS12_free(p12);
438     ret = 0;
439     end:
440     EXIT(ret);
441 }
442
443 int dump_cert_text (out, x)
444 BIO *out;
445 X509 *x;
446 {
447         char buf[256];
448         X509_NAME_oneline(X509_get_subject_name(x),buf,256);
449         BIO_puts(out,"subject=");
450         BIO_puts(out,buf);
451
452         X509_NAME_oneline(X509_get_issuer_name(x),buf,256);
453         BIO_puts(out,"\nissuer= ");
454         BIO_puts(out,buf);
455         BIO_puts(out,"\n");
456         return 0;
457 }
458
459 int dump_certs_keys_p12 (out, p12, pass, passlen, options)
460 BIO *out;
461 PKCS12 *p12;
462 unsigned char *pass;
463 int passlen;
464 int options;
465 {
466         STACK *asafes, *bags;
467         int i, bagnid;
468         PKCS7 *p7;
469         if (!( asafes = M_PKCS12_unpack_authsafes (p12))) return 0;
470         for (i = 0; i < sk_num (asafes); i++) {
471                 p7 = (PKCS7 *) sk_value (asafes, i);
472                 bagnid = OBJ_obj2nid (p7->type);
473                 if (bagnid == NID_pkcs7_data) {
474                         bags = M_PKCS12_unpack_p7data (p7);
475                         if (options & INFO) BIO_printf (bio_err, "PKCS7 Data\n");
476                 } else if (bagnid == NID_pkcs7_encrypted) {
477                         if (options & INFO) {
478                                 BIO_printf (bio_err, "PKCS7 Encrypted data: ");
479                                 alg_print (bio_err, 
480                                         p7->d.encrypted->enc_data->algorithm);
481                         }
482                         bags = M_PKCS12_unpack_p7encdata (p7, pass, passlen);
483                 } else continue;
484                 if (!bags) return 0;
485                 if (!dump_certs_pkeys_bags (out, bags, pass, passlen, 
486                                                          options)) {
487                         sk_pop_free (bags, PKCS12_SAFEBAG_free);
488                         return 0;
489                 }
490                 sk_pop_free (bags, PKCS12_SAFEBAG_free);
491         }
492         sk_pop_free (asafes, PKCS7_free);
493         return 1;
494 }
495
496 int dump_certs_pkeys_bags (out, bags, pass, passlen, options)
497 BIO *out;
498 STACK *bags;
499 unsigned char *pass;
500 int passlen;
501 int options;
502 {
503         int i;
504         for (i = 0; i < sk_num (bags); i++) {
505                 if (!dump_certs_pkeys_bag (out,
506                          (PKCS12_SAFEBAG *)sk_value (bags, i), pass, passlen,
507                                                         options)) return 0;
508         }
509         return 1;
510 }
511
512 int dump_certs_pkeys_bag (out, bag, pass, passlen, options)
513 BIO *out;
514 PKCS12_SAFEBAG *bag;
515 unsigned char *pass;
516 int passlen;
517 int options;
518 {
519         EVP_PKEY *pkey;
520         PKCS8_PRIV_KEY_INFO *p8;
521         X509 *x509;
522         
523         switch (M_PKCS12_bag_type(bag))
524         {
525         case NID_keyBag:
526                 if (options & INFO) BIO_printf (bio_err, "Key bag\n");
527                 if (options & NOKEYS) return 1;
528                 print_attribs (out, bag->attrib, "Bag Attributes");
529                 p8 = bag->value.keybag;
530                 if (!(pkey = EVP_PKCS82PKEY (p8))) return 0;
531                 print_attribs (out, p8->attributes, "Key Attributes");
532                 PEM_write_bio_PrivateKey (out, pkey, enc, NULL, 0, NULL);
533                 EVP_PKEY_free(pkey);
534         break;
535
536         case NID_pkcs8ShroudedKeyBag:
537                 if (options & INFO) {
538                         BIO_printf (bio_err, "Shrouded Keybag: ");
539                         alg_print (bio_err, bag->value.shkeybag->algor);
540                 }
541                 if (options & NOKEYS) return 1;
542                 print_attribs (out, bag->attrib, "Bag Attributes");
543                 if (!(p8 = M_PKCS12_decrypt_skey (bag, pass, passlen)))
544                                 return 0;
545                 if (!(pkey = EVP_PKCS82PKEY (p8))) return 0;
546                 print_attribs (out, p8->attributes, "Key Attributes");
547                 PKCS8_PRIV_KEY_INFO_free(p8);
548                 PEM_write_bio_PrivateKey (out, pkey, enc, NULL, 0, NULL);
549                 EVP_PKEY_free(pkey);
550         break;
551
552         case NID_certBag:
553                 if (options & INFO) BIO_printf (bio_err, "Certificate bag\n");
554                 if (options & NOCERTS) return 1;
555                 if (PKCS12_get_attr(bag, NID_localKeyID)) {
556                         if (options & CACERTS) return 1;
557                 } else if (options & CLCERTS) return 1;
558                 print_attribs (out, bag->attrib, "Bag Attributes");
559                 if (M_PKCS12_cert_bag_type(bag) != NID_x509Certificate )
560                                                                  return 1;
561                 if (!(x509 = M_PKCS12_certbag2x509(bag))) return 0;
562                 dump_cert_text (out, x509);
563                 PEM_write_bio_X509 (out, x509);
564                 X509_free(x509);
565         break;
566
567         case NID_safeContentsBag:
568                 if (options & INFO) BIO_printf (bio_err, "Safe Contents bag\n");
569                 print_attribs (out, bag->attrib, "Bag Attributes");
570                 return dump_certs_pkeys_bags (out, bag->value.safes, pass,
571                                                             passlen, options);
572                                         
573         default:
574                 BIO_printf (bio_err, "Warning unsupported bag type: ");
575                 i2a_ASN1_OBJECT (bio_err, bag->type);
576                 BIO_printf (bio_err, "\n");
577                 return 1;
578         break;
579         }
580         return 1;
581 }
582
583 /* Given a single certificate return a verified chain or NULL if error */
584
585 /* Hope this is OK .... */
586
587 int get_cert_chain (cert, chain)
588 X509 *cert;
589 STACK **chain;
590 {
591         X509_STORE *store;
592         X509_STORE_CTX store_ctx;
593         STACK *chn;
594         int i;
595         X509 *x;
596         store = X509_STORE_new ();
597         X509_STORE_set_default_paths (store);
598         X509_STORE_CTX_init(&store_ctx, store, cert, NULL);
599         if (X509_verify_cert(&store_ctx) <= 0) {
600                 i = X509_STORE_CTX_get_error (&store_ctx);
601                 goto err;
602         }
603         chn =  sk_dup(X509_STORE_CTX_get_chain (&store_ctx));
604         for (i = 0; i < sk_num(chn); i++) {
605                 x = (X509 *)sk_value(chn, i);
606                 CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
607         }
608         i = 0;
609         *chain = chn;
610 err:
611         X509_STORE_CTX_cleanup(&store_ctx);
612         X509_STORE_free(store);
613         
614         return i;
615 }       
616
617 int alg_print (x, alg)
618 BIO *x;
619 X509_ALGOR *alg;
620 {
621         PBEPARAM *pbe;
622         unsigned char *p;
623         p = alg->parameter->value.sequence->data;
624         pbe = d2i_PBEPARAM (NULL, &p, alg->parameter->value.sequence->length);
625         BIO_printf (bio_err, "%s, Iteration %d\n", 
626         OBJ_nid2ln(OBJ_obj2nid(alg->algorithm)), ASN1_INTEGER_get(pbe->iter));
627         PBEPARAM_free (pbe);
628         return 0;
629 }
630
631 /* Load all certificates from a given file */
632
633 int cert_load(in, sk)
634 BIO *in;
635 STACK *sk;
636 {
637         int ret;
638         X509 *cert;
639         ret = 0;
640         while((cert = PEM_read_bio_X509(in, NULL, NULL))) {
641                 ret = 1;
642                 sk_push(sk, (char *)cert);
643         }
644         if(ret) ERR_clear_error();
645         return ret;
646 }
647
648 /* Generalised attribute print: handle PKCS#8 and bag attributes */
649
650 int print_attribs (out, attrlst, name)
651 BIO *out;
652 STACK *attrlst;
653 char *name;
654 {
655         X509_ATTRIBUTE *attr;
656         ASN1_TYPE *av;
657         char *value;
658         int i, attr_nid;
659         if(!attrlst) {
660                 BIO_printf(out, "%s: <No Attributes>\n", name);
661                 return 1;
662         }
663         if(!sk_num(attrlst)) {
664                 BIO_printf(out, "%s: <Empty Attributes>\n", name);
665                 return 1;
666         }
667         BIO_printf(out, "%s\n", name);
668         for(i = 0; i < sk_num(attrlst); i++) {
669                 attr = (X509_ATTRIBUTE *) sk_value(attrlst, i);
670                 attr_nid = OBJ_obj2nid(attr->object);
671                 BIO_printf(out, "    ");
672                 if(attr_nid == NID_undef) {
673                         i2a_ASN1_OBJECT (out, attr->object);
674                         BIO_printf(out, ": ");
675                 } else BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
676
677                 if(sk_num(attr->value.set)) {
678                         av = (ASN1_TYPE *)sk_value(attr->value.set, 0);
679                         switch(av->type) {
680                                 case V_ASN1_BMPSTRING:
681                                 value = uni2asc(av->value.bmpstring->data,
682                                                av->value.bmpstring->length);
683                                 BIO_printf(out, "%s\n", value);
684                                 Free(value);
685                                 break;
686
687                                 case V_ASN1_OCTET_STRING:
688                                 hex_prin(out, av->value.bit_string->data,
689                                         av->value.bit_string->length);
690                                 BIO_printf(out, "\n");  
691                                 break;
692
693                                 case V_ASN1_BIT_STRING:
694                                 hex_prin(out, av->value.octet_string->data,
695                                         av->value.octet_string->length);
696                                 BIO_printf(out, "\n");  
697                                 break;
698
699                                 default:
700                                         BIO_printf(out, "<Unsupported tag %d>\n", av->type);
701                                 break;
702                         }
703                 } else BIO_printf(out, "<No Values>\n");
704         }
705         return 1;
706 }
707
708 void hex_prin(out, buf, len)
709 BIO *out;
710 unsigned char *buf;
711 int len;
712 {
713         int i;
714         for (i = 0; i < len; i++) BIO_printf (out, "%02X ", buf[i]);
715 }