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