a031c1ba25ee76154eea223134fb441f25bb8662
[openssl.git] / apps / pkcs12.c
1 /*
2  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3  * project.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999-2006 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58
59 #include <openssl/opensslconf.h>
60 #if !defined(OPENSSL_NO_DES)
61
62 # include <stdio.h>
63 # include <stdlib.h>
64 # include <string.h>
65 # include "apps.h"
66 # include <openssl/crypto.h>
67 # include <openssl/err.h>
68 # include <openssl/pem.h>
69 # include <openssl/pkcs12.h>
70
71 # define NOKEYS          0x1
72 # define NOCERTS         0x2
73 # define INFO            0x4
74 # define CLCERTS         0x8
75 # define CACERTS         0x10
76
77 int get_cert_chain(X509 *cert, X509_STORE *store, STACK_OF(X509) **chain);
78 int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass, int passlen,
79                         int options, char *pempass, const EVP_CIPHER *enc);
80 int dump_certs_pkeys_bags(BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags,
81                           char *pass, int passlen, int options, char *pempass,
82                           const EVP_CIPHER *enc);
83 int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bags, char *pass,
84                          int passlen, int options, char *pempass,
85                          const EVP_CIPHER *enc);
86 int print_attribs(BIO *out, STACK_OF(X509_ATTRIBUTE) *attrlst,
87                   const char *name);
88 void hex_prin(BIO *out, unsigned char *buf, int len);
89 int alg_print(BIO *x, X509_ALGOR *alg);
90 int cert_load(BIO *in, STACK_OF(X509) *sk);
91 static int set_pbe(int *ppbe, const char *str);
92
93 typedef enum OPTION_choice {
94     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
95     OPT_CIPHER, OPT_NOKEYS, OPT_KEYEX, OPT_KEYSIG, OPT_NOCERTS, OPT_CLCERTS,
96     OPT_CACERTS, OPT_NOOUT, OPT_INFO, OPT_CHAIN, OPT_TWOPASS, OPT_NOMACVER,
97     OPT_DESCERT, OPT_EXPORT, OPT_NOITER, OPT_MACITER, OPT_NOMACITER,
98     OPT_NOMAC, OPT_LMK, OPT_NODES, OPT_MACALG, OPT_CERTPBE, OPT_KEYPBE,
99     OPT_RAND, OPT_INKEY, OPT_CERTFILE, OPT_NAME, OPT_CSP, OPT_CANAME,
100     OPT_IN, OPT_OUT, OPT_PASSIN, OPT_PASSOUT, OPT_PASSWORD, OPT_CAPATH,
101     OPT_CAFILE, OPT_ENGINE
102 } OPTION_CHOICE;
103
104 OPTIONS pkcs12_options[] = {
105     {"help", OPT_HELP, '-', "Display this summary"},
106     {"nokeys", OPT_NOKEYS, '-', "Don't output private keys"},
107     {"keyex", OPT_KEYEX, '-', "Set MS key exchange type"},
108     {"keysig", OPT_KEYSIG, '-', "Set MS key signature type"},
109     {"nocerts", OPT_NOCERTS, '-', "Don't output certificates"},
110     {"clcerts", OPT_CLCERTS, '-', "Only output client certificates"},
111     {"cacerts", OPT_CACERTS, '-', "Only output CA certificates"},
112     {"noout", OPT_NOOUT, '-', "Don't output anything, just verify"},
113     {"info", OPT_INFO, '-', "Print info about PKCS#12 structure"},
114     {"chain", OPT_CHAIN, '-', "Add certificate chain"},
115     {"twopass", OPT_TWOPASS, '-', "Separate MAC, encryption passwords"},
116     {"nomacver", OPT_NOMACVER, '-', "Don't verify MAC"},
117 # ifndef OPENSSL_NO_RC2
118     {"descert", OPT_DESCERT, '-',
119      "Encrypt output with 3DES (default RC2-40)"},
120     {"certpbe", OPT_CERTPBE, 's',
121      "Certificate PBE algorithm (default RC2-40)"},
122 # else
123     {"descert", OPT_DESCERT, '-', "Encrypt output with 3DES (the default)"},
124     {"certpbe", OPT_CERTPBE, 's', "Certificate PBE algorithm (default 3DES)"},
125 # endif
126     {"export", OPT_EXPORT, '-', "Output PKCS12 file"},
127     {"noiter", OPT_NOITER, '-', "Don't use encryption iteration"},
128     {"maciter", OPT_MACITER, '-', "Use MAC iteration"},
129     {"nomaciter", OPT_NOMACITER, '-', "Don't use MAC iteration"},
130     {"nomac", OPT_NOMAC, '-', "Don't generate MAC"},
131     {"LMK", OPT_LMK, '-',
132      "Add local machine keyset attribute to private key"},
133     {"nodes", OPT_NODES, '-', "Don't encrypt private keys"},
134     {"macalg", OPT_MACALG, 's',
135      "Digest algorithm used in MAC (default SHA1)"},
136     {"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default 3DES)"},
137     {"rand", OPT_RAND, 's',
138      "Load the file(s) into the random number generator"},
139     {"inkey", OPT_INKEY, '<', "Private key if not infile"},
140     {"certfile", OPT_CERTFILE, '<', "Load certs from file"},
141     {"name", OPT_NAME, 's', "Use name as friendly name"},
142     {"CSP", OPT_CSP, 's', "Microsoft CSP name"},
143     {"caname", OPT_CANAME, 's',
144      "Use name as CA friendly name (can be repeated)"},
145     {"in", OPT_IN, '<', "Input filename"},
146     {"out", OPT_OUT, '>', "Output filename"},
147     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
148     {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
149     {"password", OPT_PASSWORD, 's', "Set import/export password source"},
150     {"CApath", OPT_CAPATH, '/', "PEM-format directory of CA's"},
151     {"CAfile", OPT_CAFILE, '<', "PEM-format file of CA's"},
152 # ifndef OPENSSL_NO_ENGINE
153     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
154 # endif
155     {"", OPT_CIPHER, '-', "Any supported cipher"},
156     {NULL}
157 };
158
159 int pkcs12_main(int argc, char **argv)
160 {
161     char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL;
162     char *name = NULL, *csp_name = NULL;
163     char pass[50], macpass[50];
164     int export_cert = 0, options = 0, chain = 0, twopass = 0, keytype = 0;
165     int iter = PKCS12_DEFAULT_ITER, maciter = PKCS12_DEFAULT_ITER;
166 # ifndef OPENSSL_NO_RC2
167     int cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
168 # else
169     int cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
170 # endif
171     int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
172     int ret = 1, macver = 1, noprompt = 0, add_lmk = 0;
173     char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL;
174     char *passin = NULL, *passout = NULL, *inrand = NULL, *macalg = NULL;
175     char *cpass = NULL, *mpass = NULL, *CApath = NULL, *CAfile = NULL;
176     char *engine = NULL, *prog;
177     ENGINE *e = NULL;
178     BIO *in = NULL, *out = NULL;
179     PKCS12 *p12 = NULL;
180     STACK_OF(OPENSSL_STRING) *canames = NULL;
181     const EVP_CIPHER *enc = EVP_des_ede3_cbc();
182     OPTION_CHOICE o;
183
184     prog = opt_init(argc, argv, pkcs12_options);
185     while ((o = opt_next()) != OPT_EOF) {
186         switch (o) {
187         case OPT_EOF:
188         case OPT_ERR:
189  opthelp:
190             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
191             goto end;
192         case OPT_HELP:
193             opt_help(pkcs12_options);
194             ret = 0;
195             goto end;
196         case OPT_NOKEYS:
197             options |= NOKEYS;
198             break;
199         case OPT_KEYEX:
200             keytype = KEY_EX;
201             break;
202         case OPT_KEYSIG:
203             keytype = KEY_SIG;
204             break;
205         case OPT_NOCERTS:
206             options |= NOCERTS;
207             break;
208         case OPT_CLCERTS:
209             options |= CLCERTS;
210             break;
211         case OPT_CACERTS:
212             options |= CACERTS;
213             break;
214         case OPT_NOOUT:
215             options |= (NOKEYS | NOCERTS);
216             break;
217         case OPT_INFO:
218             options |= INFO;
219             break;
220         case OPT_CHAIN:
221             chain = 1;
222             break;
223         case OPT_TWOPASS:
224             twopass = 1;
225             break;
226         case OPT_NOMACVER:
227             macver = 0;
228             break;
229         case OPT_DESCERT:
230             cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
231             break;
232         case OPT_EXPORT:
233             export_cert = 1;
234             break;
235         case OPT_CIPHER:
236             if (!opt_cipher(opt_unknown(), &enc))
237                 goto opthelp;
238             break;
239         case OPT_NOITER:
240             iter = 1;
241             break;
242         case OPT_MACITER:
243             maciter = PKCS12_DEFAULT_ITER;
244             break;
245         case OPT_NOMACITER:
246             maciter = 1;
247             break;
248         case OPT_NOMAC:
249             maciter = -1;
250             break;
251         case OPT_MACALG:
252             macalg = opt_arg();
253             break;
254         case OPT_NODES:
255             enc = NULL;
256             break;
257         case OPT_CERTPBE:
258             if (!set_pbe(&cert_pbe, opt_arg()))
259                 goto opthelp;
260             break;
261         case OPT_KEYPBE:
262             if (!set_pbe(&key_pbe, opt_arg()))
263                 goto opthelp;
264             break;
265         case OPT_RAND:
266             inrand = opt_arg();
267             break;
268         case OPT_INKEY:
269             keyname = opt_arg();
270             break;
271         case OPT_CERTFILE:
272             certfile = opt_arg();
273             break;
274         case OPT_NAME:
275             name = opt_arg();
276             break;
277         case OPT_LMK:
278             add_lmk = 1;
279             break;
280         case OPT_CSP:
281             csp_name = opt_arg();
282             break;
283         case OPT_CANAME:
284             if (canames == NULL
285                 && (canames = sk_OPENSSL_STRING_new_null()) == NULL)
286                 goto end;
287             sk_OPENSSL_STRING_push(canames, opt_arg());
288             break;
289         case OPT_IN:
290             infile = opt_arg();
291             break;
292         case OPT_OUT:
293             outfile = opt_arg();
294             break;
295         case OPT_PASSIN:
296             passinarg = opt_arg();
297             break;
298         case OPT_PASSOUT:
299             passoutarg = opt_arg();
300             break;
301         case OPT_PASSWORD:
302             passarg = opt_arg();
303             break;
304         case OPT_CAPATH:
305             CApath = opt_arg();
306             break;
307         case OPT_CAFILE:
308             CAfile = opt_arg();
309             break;
310         case OPT_ENGINE:
311             engine = opt_arg();
312             break;
313         }
314     }
315     argc = opt_num_rest();
316     argv = opt_rest();
317
318 # ifndef OPENSSL_NO_ENGINE
319     e = setup_engine(engine, 0);
320 # endif
321
322     if (passarg) {
323         if (export_cert)
324             passoutarg = passarg;
325         else
326             passinarg = passarg;
327     }
328
329     if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
330         BIO_printf(bio_err, "Error getting passwords\n");
331         goto end;
332     }
333
334     if (!cpass) {
335         if (export_cert)
336             cpass = passout;
337         else
338             cpass = passin;
339     }
340
341     if (cpass) {
342         mpass = cpass;
343         noprompt = 1;
344     } else {
345         cpass = pass;
346         mpass = macpass;
347     }
348
349     if (export_cert || inrand) {
350         app_RAND_load_file(NULL, (inrand != NULL));
351         if (inrand != NULL)
352             BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
353                        app_RAND_load_files(inrand));
354     }
355
356     in = bio_open_default(infile, "rb");
357     if (in == NULL)
358         goto end;
359
360     out = bio_open_default(outfile, "wb");
361     if (out == NULL)
362         goto end;
363
364     if (twopass) {
365         if (EVP_read_pw_string
366             (macpass, sizeof macpass, "Enter MAC Password:", export_cert)) {
367             BIO_printf(bio_err, "Can't read Password\n");
368             goto end;
369         }
370     }
371
372     if (export_cert) {
373         EVP_PKEY *key = NULL;
374         X509 *ucert = NULL, *x = NULL;
375         STACK_OF(X509) *certs = NULL;
376         const EVP_MD *macmd = NULL;
377         unsigned char *catmp = NULL;
378         int i;
379
380         if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
381             BIO_printf(bio_err, "Nothing to do!\n");
382             goto export_end;
383         }
384
385         if (options & NOCERTS)
386             chain = 0;
387
388         if (!(options & NOKEYS)) {
389             key = load_key(keyname ? keyname : infile,
390                            FORMAT_PEM, 1, passin, e, "private key");
391             if (!key)
392                 goto export_end;
393         }
394
395         /* Load in all certs in input file */
396         if (!(options & NOCERTS)) {
397             certs = load_certs(infile, FORMAT_PEM, NULL, e,
398                                "certificates");
399             if (!certs)
400                 goto export_end;
401
402             if (key) {
403                 /* Look for matching private key */
404                 for (i = 0; i < sk_X509_num(certs); i++) {
405                     x = sk_X509_value(certs, i);
406                     if (X509_check_private_key(x, key)) {
407                         ucert = x;
408                         /* Zero keyid and alias */
409                         X509_keyid_set1(ucert, NULL, 0);
410                         X509_alias_set1(ucert, NULL, 0);
411                         /* Remove from list */
412                         (void)sk_X509_delete(certs, i);
413                         break;
414                     }
415                 }
416                 if (!ucert) {
417                     BIO_printf(bio_err,
418                                "No certificate matches private key\n");
419                     goto export_end;
420                 }
421             }
422
423         }
424
425         /* Add any more certificates asked for */
426         if (certfile) {
427             STACK_OF(X509) *morecerts = NULL;
428             if (!(morecerts = load_certs(certfile, FORMAT_PEM, NULL, e,
429                                          "certificates from certfile")))
430                 goto export_end;
431             while (sk_X509_num(morecerts) > 0)
432                 sk_X509_push(certs, sk_X509_shift(morecerts));
433             sk_X509_free(morecerts);
434         }
435
436         /* If chaining get chain from user cert */
437         if (chain) {
438             int vret;
439             STACK_OF(X509) *chain2;
440             X509_STORE *store;
441             if (!(store = setup_verify(CAfile, CApath)))
442                 goto export_end;
443
444             vret = get_cert_chain(ucert, store, &chain2);
445             X509_STORE_free(store);
446
447             if (!vret) {
448                 /* Exclude verified certificate */
449                 for (i = 1; i < sk_X509_num(chain2); i++)
450                     sk_X509_push(certs, sk_X509_value(chain2, i));
451                 /* Free first certificate */
452                 X509_free(sk_X509_value(chain2, 0));
453                 sk_X509_free(chain2);
454             } else {
455                 if (vret >= 0)
456                     BIO_printf(bio_err, "Error %s getting chain.\n",
457                                X509_verify_cert_error_string(vret));
458                 else
459                     ERR_print_errors(bio_err);
460                 goto export_end;
461             }
462         }
463
464         /* Add any CA names */
465
466         for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
467             catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i);
468             X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
469         }
470
471         if (csp_name && key)
472             EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
473                                       MBSTRING_ASC, (unsigned char *)csp_name,
474                                       -1);
475
476         if (add_lmk && key)
477             EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);
478
479         if (!noprompt &&
480             EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:",
481                                1)) {
482             BIO_printf(bio_err, "Can't read Password\n");
483             goto export_end;
484         }
485         if (!twopass)
486             BUF_strlcpy(macpass, pass, sizeof macpass);
487
488         p12 = PKCS12_create(cpass, name, key, ucert, certs,
489                             key_pbe, cert_pbe, iter, -1, keytype);
490
491         if (!p12) {
492             ERR_print_errors(bio_err);
493             goto export_end;
494         }
495
496         if (macalg) {
497             if (!opt_md(macalg, &macmd))
498                 goto opthelp;
499         }
500
501         if (maciter != -1)
502             PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd);
503
504         i2d_PKCS12_bio(out, p12);
505
506         ret = 0;
507
508  export_end:
509
510         EVP_PKEY_free(key);
511         if (certs)
512             sk_X509_pop_free(certs, X509_free);
513         if (ucert)
514             X509_free(ucert);
515
516         goto end;
517
518     }
519
520     if (!(p12 = d2i_PKCS12_bio(in, NULL))) {
521         ERR_print_errors(bio_err);
522         goto end;
523     }
524
525     if (!noprompt
526         && EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:",
527                               0)) {
528         BIO_printf(bio_err, "Can't read Password\n");
529         goto end;
530     }
531
532     if (!twopass)
533         BUF_strlcpy(macpass, pass, sizeof macpass);
534
535     if ((options & INFO) && p12->mac)
536         BIO_printf(bio_err, "MAC Iteration %ld\n",
537                    p12->mac->iter ? ASN1_INTEGER_get(p12->mac->iter) : 1);
538     if (macver) {
539         /* If we enter empty password try no password first */
540         if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
541             /* If mac and crypto pass the same set it to NULL too */
542             if (!twopass)
543                 cpass = NULL;
544         } else if (!PKCS12_verify_mac(p12, mpass, -1)) {
545             BIO_printf(bio_err, "Mac verify error: invalid password?\n");
546             ERR_print_errors(bio_err);
547             goto end;
548         }
549     }
550
551     if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) {
552         BIO_printf(bio_err, "Error outputting keys and certificates\n");
553         ERR_print_errors(bio_err);
554         goto end;
555     }
556     ret = 0;
557  end:
558     PKCS12_free(p12);
559     if (export_cert || inrand)
560         app_RAND_write_file(NULL);
561     BIO_free(in);
562     BIO_free_all(out);
563     if (canames)
564         sk_OPENSSL_STRING_free(canames);
565     if (passin)
566         OPENSSL_free(passin);
567     if (passout)
568         OPENSSL_free(passout);
569     return (ret);
570 }
571
572 int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass,
573                         int passlen, int options, char *pempass,
574                         const EVP_CIPHER *enc)
575 {
576     STACK_OF(PKCS7) *asafes = NULL;
577     STACK_OF(PKCS12_SAFEBAG) *bags;
578     int i, bagnid;
579     int ret = 0;
580     PKCS7 *p7;
581
582     if (!(asafes = PKCS12_unpack_authsafes(p12)))
583         return 0;
584     for (i = 0; i < sk_PKCS7_num(asafes); i++) {
585         p7 = sk_PKCS7_value(asafes, i);
586         bagnid = OBJ_obj2nid(p7->type);
587         if (bagnid == NID_pkcs7_data) {
588             bags = PKCS12_unpack_p7data(p7);
589             if (options & INFO)
590                 BIO_printf(bio_err, "PKCS7 Data\n");
591         } else if (bagnid == NID_pkcs7_encrypted) {
592             if (options & INFO) {
593                 BIO_printf(bio_err, "PKCS7 Encrypted data: ");
594                 alg_print(bio_err, p7->d.encrypted->enc_data->algorithm);
595             }
596             bags = PKCS12_unpack_p7encdata(p7, pass, passlen);
597         } else
598             continue;
599         if (!bags)
600             goto err;
601         if (!dump_certs_pkeys_bags(out, bags, pass, passlen,
602                                    options, pempass, enc)) {
603             sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
604             goto err;
605         }
606         sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
607         bags = NULL;
608     }
609     ret = 1;
610
611  err:
612     sk_PKCS7_pop_free(asafes, PKCS7_free);
613     return ret;
614 }
615
616 int dump_certs_pkeys_bags(BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags,
617                           char *pass, int passlen, int options, char *pempass,
618                           const EVP_CIPHER *enc)
619 {
620     int i;
621     for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) {
622         if (!dump_certs_pkeys_bag(out,
623                                   sk_PKCS12_SAFEBAG_value(bags, i),
624                                   pass, passlen, options, pempass, enc))
625             return 0;
626     }
627     return 1;
628 }
629
630 int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bag, char *pass,
631                          int passlen, int options, char *pempass,
632                          const EVP_CIPHER *enc)
633 {
634     EVP_PKEY *pkey;
635     PKCS8_PRIV_KEY_INFO *p8;
636     X509 *x509;
637
638     switch (M_PKCS12_bag_type(bag)) {
639     case NID_keyBag:
640         if (options & INFO)
641             BIO_printf(bio_err, "Key bag\n");
642         if (options & NOKEYS)
643             return 1;
644         print_attribs(out, bag->attrib, "Bag Attributes");
645         p8 = bag->value.keybag;
646         if (!(pkey = EVP_PKCS82PKEY(p8)))
647             return 0;
648         print_attribs(out, p8->attributes, "Key Attributes");
649         PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
650         EVP_PKEY_free(pkey);
651         break;
652
653     case NID_pkcs8ShroudedKeyBag:
654         if (options & INFO) {
655             BIO_printf(bio_err, "Shrouded Keybag: ");
656             alg_print(bio_err, bag->value.shkeybag->algor);
657         }
658         if (options & NOKEYS)
659             return 1;
660         print_attribs(out, bag->attrib, "Bag Attributes");
661         if (!(p8 = PKCS12_decrypt_skey(bag, pass, passlen)))
662             return 0;
663         if (!(pkey = EVP_PKCS82PKEY(p8))) {
664             PKCS8_PRIV_KEY_INFO_free(p8);
665             return 0;
666         }
667         print_attribs(out, p8->attributes, "Key Attributes");
668         PKCS8_PRIV_KEY_INFO_free(p8);
669         PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
670         EVP_PKEY_free(pkey);
671         break;
672
673     case NID_certBag:
674         if (options & INFO)
675             BIO_printf(bio_err, "Certificate bag\n");
676         if (options & NOCERTS)
677             return 1;
678         if (PKCS12_get_attr(bag, NID_localKeyID)) {
679             if (options & CACERTS)
680                 return 1;
681         } else if (options & CLCERTS)
682             return 1;
683         print_attribs(out, bag->attrib, "Bag Attributes");
684         if (M_PKCS12_cert_bag_type(bag) != NID_x509Certificate)
685             return 1;
686         if (!(x509 = PKCS12_certbag2x509(bag)))
687             return 0;
688         dump_cert_text(out, x509);
689         PEM_write_bio_X509(out, x509);
690         X509_free(x509);
691         break;
692
693     case NID_safeContentsBag:
694         if (options & INFO)
695             BIO_printf(bio_err, "Safe Contents bag\n");
696         print_attribs(out, bag->attrib, "Bag Attributes");
697         return dump_certs_pkeys_bags(out, bag->value.safes, pass,
698                                      passlen, options, pempass, enc);
699
700     default:
701         BIO_printf(bio_err, "Warning unsupported bag type: ");
702         i2a_ASN1_OBJECT(bio_err, bag->type);
703         BIO_printf(bio_err, "\n");
704         return 1;
705     }
706     return 1;
707 }
708
709 /* Given a single certificate return a verified chain or NULL if error */
710
711 /* Hope this is OK .... */
712
713 int get_cert_chain(X509 *cert, X509_STORE *store, STACK_OF(X509) **chain)
714 {
715     X509_STORE_CTX store_ctx;
716     STACK_OF(X509) *chn;
717     int i = 0;
718
719     /*
720      * FIXME: Should really check the return status of X509_STORE_CTX_init
721      * for an error, but how that fits into the return value of this function
722      * is less obvious.
723      */
724     X509_STORE_CTX_init(&store_ctx, store, cert, NULL);
725     if (X509_verify_cert(&store_ctx) <= 0) {
726         i = X509_STORE_CTX_get_error(&store_ctx);
727         if (i == 0)
728             /*
729              * avoid returning 0 if X509_verify_cert() did not set an
730              * appropriate error value in the context
731              */
732             i = -1;
733         chn = NULL;
734         goto err;
735     } else
736         chn = X509_STORE_CTX_get1_chain(&store_ctx);
737  err:
738     X509_STORE_CTX_cleanup(&store_ctx);
739     *chain = chn;
740
741     return i;
742 }
743
744 int alg_print(BIO *x, X509_ALGOR *alg)
745 {
746     PBEPARAM *pbe;
747     const unsigned char *p;
748     p = alg->parameter->value.sequence->data;
749     pbe = d2i_PBEPARAM(NULL, &p, alg->parameter->value.sequence->length);
750     if (!pbe)
751         return 1;
752     BIO_printf(bio_err, "%s, Iteration %ld\n",
753                OBJ_nid2ln(OBJ_obj2nid(alg->algorithm)),
754                ASN1_INTEGER_get(pbe->iter));
755     PBEPARAM_free(pbe);
756     return 1;
757 }
758
759 /* Load all certificates from a given file */
760
761 int cert_load(BIO *in, STACK_OF(X509) *sk)
762 {
763     int ret;
764     X509 *cert;
765     ret = 0;
766     while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
767         ret = 1;
768         sk_X509_push(sk, cert);
769     }
770     if (ret)
771         ERR_clear_error();
772     return ret;
773 }
774
775 /* Generalised attribute print: handle PKCS#8 and bag attributes */
776
777 int print_attribs(BIO *out, STACK_OF(X509_ATTRIBUTE) *attrlst,
778                   const char *name)
779 {
780     X509_ATTRIBUTE *attr;
781     ASN1_TYPE *av;
782     char *value;
783     int i, attr_nid;
784     if (!attrlst) {
785         BIO_printf(out, "%s: <No Attributes>\n", name);
786         return 1;
787     }
788     if (!sk_X509_ATTRIBUTE_num(attrlst)) {
789         BIO_printf(out, "%s: <Empty Attributes>\n", name);
790         return 1;
791     }
792     BIO_printf(out, "%s\n", name);
793     for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) {
794         ASN1_OBJECT *attr_obj;
795         attr = sk_X509_ATTRIBUTE_value(attrlst, i);
796         attr_obj = X509_ATTRIBUTE_get0_object(attr);
797         attr_nid = OBJ_obj2nid(attr_obj);
798         BIO_printf(out, "    ");
799         if (attr_nid == NID_undef) {
800             i2a_ASN1_OBJECT(out, attr_obj);
801             BIO_printf(out, ": ");
802         } else
803             BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
804
805         if (X509_ATTRIBUTE_count(attr)) {
806             av = X509_ATTRIBUTE_get0_type(attr, 0);
807             switch (av->type) {
808             case V_ASN1_BMPSTRING:
809                 value = OPENSSL_uni2asc(av->value.bmpstring->data,
810                                         av->value.bmpstring->length);
811                 BIO_printf(out, "%s\n", value);
812                 OPENSSL_free(value);
813                 break;
814
815             case V_ASN1_OCTET_STRING:
816                 hex_prin(out, av->value.octet_string->data,
817                          av->value.octet_string->length);
818                 BIO_printf(out, "\n");
819                 break;
820
821             case V_ASN1_BIT_STRING:
822                 hex_prin(out, av->value.bit_string->data,
823                          av->value.bit_string->length);
824                 BIO_printf(out, "\n");
825                 break;
826
827             default:
828                 BIO_printf(out, "<Unsupported tag %d>\n", av->type);
829                 break;
830             }
831         } else
832             BIO_printf(out, "<No Values>\n");
833     }
834     return 1;
835 }
836
837 void hex_prin(BIO *out, unsigned char *buf, int len)
838 {
839     int i;
840     for (i = 0; i < len; i++)
841         BIO_printf(out, "%02X ", buf[i]);
842 }
843
844 static int set_pbe(int *ppbe, const char *str)
845 {
846     if (!str)
847         return 0;
848     if (!strcmp(str, "NONE")) {
849         *ppbe = -1;
850         return 1;
851     }
852     *ppbe = OBJ_txt2nid(str);
853     if (*ppbe == NID_undef) {
854         BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str);
855         return 0;
856     }
857     return 1;
858 }
859
860 #endif