af5f670ba30fb5fb089be525c91bc7217f298eca
[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 NON_EMPTY_TRANSLATION_UNIT
62 #else
63
64 # include <stdio.h>
65 # include <stdlib.h>
66 # include <string.h>
67 # include "apps.h"
68 # include <openssl/crypto.h>
69 # include <openssl/err.h>
70 # include <openssl/pem.h>
71 # include <openssl/pkcs12.h>
72
73 # define NOKEYS          0x1
74 # define NOCERTS         0x2
75 # define INFO            0x4
76 # define CLCERTS         0x8
77 # define CACERTS         0x10
78
79 static int get_cert_chain(X509 *cert, X509_STORE *store,
80                           STACK_OF(X509) **chain);
81 int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass, int passlen,
82                         int options, char *pempass, const EVP_CIPHER *enc);
83 int dump_certs_pkeys_bags(BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags,
84                           char *pass, int passlen, int options, char *pempass,
85                           const EVP_CIPHER *enc);
86 int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bags, char *pass,
87                          int passlen, int options, char *pempass,
88                          const EVP_CIPHER *enc);
89 int print_attribs(BIO *out, STACK_OF(X509_ATTRIBUTE) *attrlst,
90                   const char *name);
91 void hex_prin(BIO *out, unsigned char *buf, int len);
92 static int alg_print(X509_ALGOR *alg);
93 int cert_load(BIO *in, STACK_OF(X509) *sk);
94 static int set_pbe(int *ppbe, const char *str);
95
96 typedef enum OPTION_choice {
97     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
98     OPT_CIPHER, OPT_NOKEYS, OPT_KEYEX, OPT_KEYSIG, OPT_NOCERTS, OPT_CLCERTS,
99     OPT_CACERTS, OPT_NOOUT, OPT_INFO, OPT_CHAIN, OPT_TWOPASS, OPT_NOMACVER,
100     OPT_DESCERT, OPT_EXPORT, OPT_NOITER, OPT_MACITER, OPT_NOMACITER,
101     OPT_NOMAC, OPT_LMK, OPT_NODES, OPT_MACALG, OPT_CERTPBE, OPT_KEYPBE,
102     OPT_RAND, OPT_INKEY, OPT_CERTFILE, OPT_NAME, OPT_CSP, OPT_CANAME,
103     OPT_IN, OPT_OUT, OPT_PASSIN, OPT_PASSOUT, OPT_PASSWORD, OPT_CAPATH,
104     OPT_CAFILE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_ENGINE
105 } OPTION_CHOICE;
106
107 OPTIONS pkcs12_options[] = {
108     {"help", OPT_HELP, '-', "Display this summary"},
109     {"nokeys", OPT_NOKEYS, '-', "Don't output private keys"},
110     {"keyex", OPT_KEYEX, '-', "Set MS key exchange type"},
111     {"keysig", OPT_KEYSIG, '-', "Set MS key signature type"},
112     {"nocerts", OPT_NOCERTS, '-', "Don't output certificates"},
113     {"clcerts", OPT_CLCERTS, '-', "Only output client certificates"},
114     {"cacerts", OPT_CACERTS, '-', "Only output CA certificates"},
115     {"noout", OPT_NOOUT, '-', "Don't output anything, just verify"},
116     {"info", OPT_INFO, '-', "Print info about PKCS#12 structure"},
117     {"chain", OPT_CHAIN, '-', "Add certificate chain"},
118     {"twopass", OPT_TWOPASS, '-', "Separate MAC, encryption passwords"},
119     {"nomacver", OPT_NOMACVER, '-', "Don't verify MAC"},
120 # ifndef OPENSSL_NO_RC2
121     {"descert", OPT_DESCERT, '-',
122      "Encrypt output with 3DES (default RC2-40)"},
123     {"certpbe", OPT_CERTPBE, 's',
124      "Certificate PBE algorithm (default RC2-40)"},
125 # else
126     {"descert", OPT_DESCERT, '-', "Encrypt output with 3DES (the default)"},
127     {"certpbe", OPT_CERTPBE, 's', "Certificate PBE algorithm (default 3DES)"},
128 # endif
129     {"export", OPT_EXPORT, '-', "Output PKCS12 file"},
130     {"noiter", OPT_NOITER, '-', "Don't use encryption iteration"},
131     {"maciter", OPT_MACITER, '-', "Use MAC iteration"},
132     {"nomaciter", OPT_NOMACITER, '-', "Don't use MAC iteration"},
133     {"nomac", OPT_NOMAC, '-', "Don't generate MAC"},
134     {"LMK", OPT_LMK, '-',
135      "Add local machine keyset attribute to private key"},
136     {"nodes", OPT_NODES, '-', "Don't encrypt private keys"},
137     {"macalg", OPT_MACALG, 's',
138      "Digest algorithm used in MAC (default SHA1)"},
139     {"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default 3DES)"},
140     {"rand", OPT_RAND, 's',
141      "Load the file(s) into the random number generator"},
142     {"inkey", OPT_INKEY, '<', "Private key if not infile"},
143     {"certfile", OPT_CERTFILE, '<', "Load certs from file"},
144     {"name", OPT_NAME, 's', "Use name as friendly name"},
145     {"CSP", OPT_CSP, 's', "Microsoft CSP name"},
146     {"caname", OPT_CANAME, 's',
147      "Use name as CA friendly name (can be repeated)"},
148     {"in", OPT_IN, '<', "Input filename"},
149     {"out", OPT_OUT, '>', "Output filename"},
150     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
151     {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
152     {"password", OPT_PASSWORD, 's', "Set import/export password source"},
153     {"CApath", OPT_CAPATH, '/', "PEM-format directory of CA's"},
154     {"CAfile", OPT_CAFILE, '<', "PEM-format file of CA's"},
155     {"no-CAfile", OPT_NOCAFILE, '-',
156      "Do not load the default certificates file"},
157     {"no-CApath", OPT_NOCAPATH, '-',
158      "Do not load certificates from the default certificates directory"},
159     {"", OPT_CIPHER, '-', "Any supported cipher"},
160 # ifndef OPENSSL_NO_ENGINE
161     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
162 # endif
163     {NULL}
164 };
165
166 int pkcs12_main(int argc, char **argv)
167 {
168     char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL;
169     char *name = NULL, *csp_name = NULL;
170     char pass[2048], macpass[2048];
171     int export_cert = 0, options = 0, chain = 0, twopass = 0, keytype = 0;
172     int iter = PKCS12_DEFAULT_ITER, maciter = PKCS12_DEFAULT_ITER;
173 # ifndef OPENSSL_NO_RC2
174     int cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
175 # else
176     int cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
177 # endif
178     int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
179     int ret = 1, macver = 1, add_lmk = 0, private = 0;
180     int noprompt = 0;
181     char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL;
182     char *passin = NULL, *passout = NULL, *inrand = NULL, *macalg = NULL;
183     char *cpass = NULL, *mpass = NULL, *CApath = NULL, *CAfile = NULL;
184     char *prog;
185     int noCApath = 0, noCAfile = 0;
186     ENGINE *e = NULL;
187     BIO *in = NULL, *out = NULL;
188     PKCS12 *p12 = NULL;
189     STACK_OF(OPENSSL_STRING) *canames = NULL;
190     const EVP_CIPHER *enc = EVP_des_ede3_cbc();
191     OPTION_CHOICE o;
192
193     prog = opt_init(argc, argv, pkcs12_options);
194     while ((o = opt_next()) != OPT_EOF) {
195         switch (o) {
196         case OPT_EOF:
197         case OPT_ERR:
198  opthelp:
199             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
200             goto end;
201         case OPT_HELP:
202             opt_help(pkcs12_options);
203             ret = 0;
204             goto end;
205         case OPT_NOKEYS:
206             options |= NOKEYS;
207             break;
208         case OPT_KEYEX:
209             keytype = KEY_EX;
210             break;
211         case OPT_KEYSIG:
212             keytype = KEY_SIG;
213             break;
214         case OPT_NOCERTS:
215             options |= NOCERTS;
216             break;
217         case OPT_CLCERTS:
218             options |= CLCERTS;
219             break;
220         case OPT_CACERTS:
221             options |= CACERTS;
222             break;
223         case OPT_NOOUT:
224             options |= (NOKEYS | NOCERTS);
225             break;
226         case OPT_INFO:
227             options |= INFO;
228             break;
229         case OPT_CHAIN:
230             chain = 1;
231             break;
232         case OPT_TWOPASS:
233             twopass = 1;
234             break;
235         case OPT_NOMACVER:
236             macver = 0;
237             break;
238         case OPT_DESCERT:
239             cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
240             break;
241         case OPT_EXPORT:
242             export_cert = 1;
243             break;
244         case OPT_CIPHER:
245             if (!opt_cipher(opt_unknown(), &enc))
246                 goto opthelp;
247             break;
248         case OPT_NOITER:
249             iter = 1;
250             break;
251         case OPT_MACITER:
252             maciter = PKCS12_DEFAULT_ITER;
253             break;
254         case OPT_NOMACITER:
255             maciter = 1;
256             break;
257         case OPT_NOMAC:
258             maciter = -1;
259             break;
260         case OPT_MACALG:
261             macalg = opt_arg();
262             break;
263         case OPT_NODES:
264             enc = NULL;
265             break;
266         case OPT_CERTPBE:
267             if (!set_pbe(&cert_pbe, opt_arg()))
268                 goto opthelp;
269             break;
270         case OPT_KEYPBE:
271             if (!set_pbe(&key_pbe, opt_arg()))
272                 goto opthelp;
273             break;
274         case OPT_RAND:
275             inrand = opt_arg();
276             break;
277         case OPT_INKEY:
278             keyname = opt_arg();
279             break;
280         case OPT_CERTFILE:
281             certfile = opt_arg();
282             break;
283         case OPT_NAME:
284             name = opt_arg();
285             break;
286         case OPT_LMK:
287             add_lmk = 1;
288             break;
289         case OPT_CSP:
290             csp_name = opt_arg();
291             break;
292         case OPT_CANAME:
293             if (canames == NULL
294                 && (canames = sk_OPENSSL_STRING_new_null()) == NULL)
295                 goto end;
296             sk_OPENSSL_STRING_push(canames, opt_arg());
297             break;
298         case OPT_IN:
299             infile = opt_arg();
300             break;
301         case OPT_OUT:
302             outfile = opt_arg();
303             break;
304         case OPT_PASSIN:
305             passinarg = opt_arg();
306             break;
307         case OPT_PASSOUT:
308             passoutarg = opt_arg();
309             break;
310         case OPT_PASSWORD:
311             passarg = opt_arg();
312             break;
313         case OPT_CAPATH:
314             CApath = opt_arg();
315             break;
316         case OPT_CAFILE:
317             CAfile = opt_arg();
318             break;
319         case OPT_NOCAPATH:
320             noCApath = 1;
321             break;
322         case OPT_NOCAFILE:
323             noCAfile = 1;
324             break;
325         case OPT_ENGINE:
326             e = setup_engine(opt_arg(), 0);
327             break;
328         }
329     }
330     argc = opt_num_rest();
331     if (argc != 0)
332         goto opthelp;
333
334     private = 1;
335
336     if (passarg) {
337         if (export_cert)
338             passoutarg = passarg;
339         else
340             passinarg = passarg;
341     }
342
343     if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
344         BIO_printf(bio_err, "Error getting passwords\n");
345         goto end;
346     }
347
348     if (!cpass) {
349         if (export_cert)
350             cpass = passout;
351         else
352             cpass = passin;
353     }
354
355     if (cpass) {
356         mpass = cpass;
357         noprompt = 1;
358     } else {
359         cpass = pass;
360         mpass = macpass;
361     }
362
363     if (export_cert || inrand) {
364         app_RAND_load_file(NULL, (inrand != NULL));
365         if (inrand != NULL)
366             BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
367                        app_RAND_load_files(inrand));
368     }
369
370     if (twopass) {
371         if (1) {
372 #ifndef OPENSSL_NO_UI
373             if (EVP_read_pw_string
374                 (macpass, sizeof macpass, "Enter MAC Password:", export_cert)) {
375                 BIO_printf(bio_err, "Can't read Password\n");
376                 goto end;
377             }
378         } else {
379 #endif
380             BIO_printf(bio_err, "Unsupported option -twopass\n");
381             goto end;
382         }
383     }
384
385     if (export_cert) {
386         EVP_PKEY *key = NULL;
387         X509 *ucert = NULL, *x = NULL;
388         STACK_OF(X509) *certs = NULL;
389         const EVP_MD *macmd = NULL;
390         unsigned char *catmp = NULL;
391         int i;
392
393         if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
394             BIO_printf(bio_err, "Nothing to do!\n");
395             goto export_end;
396         }
397
398         if (options & NOCERTS)
399             chain = 0;
400
401         if (!(options & NOKEYS)) {
402             key = load_key(keyname ? keyname : infile,
403                            FORMAT_PEM, 1, passin, e, "private key");
404             if (!key)
405                 goto export_end;
406         }
407
408         /* Load in all certs in input file */
409         if (!(options & NOCERTS)) {
410             if (!load_certs(infile, &certs, FORMAT_PEM, NULL,
411                             "certificates"))
412                 goto export_end;
413
414             if (key) {
415                 /* Look for matching private key */
416                 for (i = 0; i < sk_X509_num(certs); i++) {
417                     x = sk_X509_value(certs, i);
418                     if (X509_check_private_key(x, key)) {
419                         ucert = x;
420                         /* Zero keyid and alias */
421                         X509_keyid_set1(ucert, NULL, 0);
422                         X509_alias_set1(ucert, NULL, 0);
423                         /* Remove from list */
424                         (void)sk_X509_delete(certs, i);
425                         break;
426                     }
427                 }
428                 if (!ucert) {
429                     BIO_printf(bio_err,
430                                "No certificate matches private key\n");
431                     goto export_end;
432                 }
433             }
434
435         }
436
437         /* Add any more certificates asked for */
438         if (certfile) {
439             if (!load_certs(certfile, &certs, FORMAT_PEM, NULL,
440                             "certificates from certfile"))
441                 goto export_end;
442         }
443
444         /* If chaining get chain from user cert */
445         if (chain) {
446             int vret;
447             STACK_OF(X509) *chain2;
448             X509_STORE *store;
449             if ((store = setup_verify(CAfile, CApath, noCAfile, noCApath))
450                     == NULL)
451                 goto export_end;
452
453             vret = get_cert_chain(ucert, store, &chain2);
454             X509_STORE_free(store);
455
456             if (vret == X509_V_OK) {
457                 /* Exclude verified certificate */
458                 for (i = 1; i < sk_X509_num(chain2); i++)
459                     sk_X509_push(certs, sk_X509_value(chain2, i));
460                 /* Free first certificate */
461                 X509_free(sk_X509_value(chain2, 0));
462                 sk_X509_free(chain2);
463             } else {
464                 if (vret != X509_V_ERR_UNSPECIFIED)
465                     BIO_printf(bio_err, "Error %s getting chain.\n",
466                                X509_verify_cert_error_string(vret));
467                 else
468                     ERR_print_errors(bio_err);
469                 goto export_end;
470             }
471         }
472
473         /* Add any CA names */
474
475         for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
476             catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i);
477             X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
478         }
479
480         if (csp_name && key)
481             EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
482                                       MBSTRING_ASC, (unsigned char *)csp_name,
483                                       -1);
484
485         if (add_lmk && key)
486             EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);
487
488         if (!noprompt) {
489             if (1) {
490 #ifndef OPENSSL_NO_UI
491                 if (EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:",
492                                        1)) {
493                     BIO_printf(bio_err, "Can't read Password\n");
494                     goto export_end;
495                 }
496             } else {
497 #endif
498                 BIO_printf(bio_err, "Password required\n");
499                 goto export_end;
500             }
501         }
502
503         if (!twopass)
504             OPENSSL_strlcpy(macpass, pass, sizeof macpass);
505
506         p12 = PKCS12_create(cpass, name, key, ucert, certs,
507                             key_pbe, cert_pbe, iter, -1, keytype);
508
509         if (!p12) {
510             ERR_print_errors(bio_err);
511             goto export_end;
512         }
513
514         if (macalg) {
515             if (!opt_md(macalg, &macmd))
516                 goto opthelp;
517         }
518
519         if (maciter != -1)
520             PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd);
521
522         assert(private);
523
524         out = bio_open_owner(outfile, FORMAT_PKCS12, private);
525         if (out == NULL)
526             goto end;
527
528         i2d_PKCS12_bio(out, p12);
529
530         ret = 0;
531
532  export_end:
533
534         EVP_PKEY_free(key);
535         sk_X509_pop_free(certs, X509_free);
536         X509_free(ucert);
537
538         goto end;
539
540     }
541
542     in = bio_open_default(infile, 'r', FORMAT_PKCS12);
543     if (in == NULL)
544         goto end;
545     out = bio_open_owner(outfile, FORMAT_PEM, private);
546     if (out == NULL)
547         goto end;
548
549     if ((p12 = d2i_PKCS12_bio(in, NULL)) == NULL) {
550         ERR_print_errors(bio_err);
551         goto end;
552     }
553
554     if (!noprompt) {
555         if (1) {
556 #ifndef OPENSSL_NO_UI
557             if (EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:",
558                                    0)) {
559                 BIO_printf(bio_err, "Can't read Password\n");
560                 goto end;
561             }
562         } else {
563 #endif
564             BIO_printf(bio_err, "Password required\n");
565             goto end;
566         }
567     }
568
569     if (!twopass)
570         OPENSSL_strlcpy(macpass, pass, sizeof macpass);
571
572     if ((options & INFO) && PKCS12_mac_present(p12)) {
573         ASN1_INTEGER *tmaciter;
574
575         PKCS12_get0_mac(NULL, NULL, NULL, &tmaciter, p12);
576         BIO_printf(bio_err, "MAC Iteration %ld\n",
577                    tmaciter  != NULL ? ASN1_INTEGER_get(tmaciter) : 1L);
578     }
579     if (macver) {
580         /* If we enter empty password try no password first */
581         if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
582             /* If mac and crypto pass the same set it to NULL too */
583             if (!twopass)
584                 cpass = NULL;
585         } else if (!PKCS12_verify_mac(p12, mpass, -1)) {
586             BIO_printf(bio_err, "Mac verify error: invalid password?\n");
587             ERR_print_errors(bio_err);
588             goto end;
589         }
590     }
591
592     assert(private);
593     if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) {
594         BIO_printf(bio_err, "Error outputting keys and certificates\n");
595         ERR_print_errors(bio_err);
596         goto end;
597     }
598     ret = 0;
599  end:
600     PKCS12_free(p12);
601     if (export_cert || inrand)
602         app_RAND_write_file(NULL);
603     BIO_free(in);
604     BIO_free_all(out);
605     sk_OPENSSL_STRING_free(canames);
606     OPENSSL_free(passin);
607     OPENSSL_free(passout);
608     return (ret);
609 }
610
611 int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass,
612                         int passlen, int options, char *pempass,
613                         const EVP_CIPHER *enc)
614 {
615     STACK_OF(PKCS7) *asafes = NULL;
616     STACK_OF(PKCS12_SAFEBAG) *bags;
617     int i, bagnid;
618     int ret = 0;
619     PKCS7 *p7;
620
621     if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL)
622         return 0;
623     for (i = 0; i < sk_PKCS7_num(asafes); i++) {
624         p7 = sk_PKCS7_value(asafes, i);
625         bagnid = OBJ_obj2nid(p7->type);
626         if (bagnid == NID_pkcs7_data) {
627             bags = PKCS12_unpack_p7data(p7);
628             if (options & INFO)
629                 BIO_printf(bio_err, "PKCS7 Data\n");
630         } else if (bagnid == NID_pkcs7_encrypted) {
631             if (options & INFO) {
632                 BIO_printf(bio_err, "PKCS7 Encrypted data: ");
633                 alg_print(p7->d.encrypted->enc_data->algorithm);
634             }
635             bags = PKCS12_unpack_p7encdata(p7, pass, passlen);
636         } else
637             continue;
638         if (!bags)
639             goto err;
640         if (!dump_certs_pkeys_bags(out, bags, pass, passlen,
641                                    options, pempass, enc)) {
642             sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
643             goto err;
644         }
645         sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
646         bags = NULL;
647     }
648     ret = 1;
649
650  err:
651     sk_PKCS7_pop_free(asafes, PKCS7_free);
652     return ret;
653 }
654
655 int dump_certs_pkeys_bags(BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags,
656                           char *pass, int passlen, int options, char *pempass,
657                           const EVP_CIPHER *enc)
658 {
659     int i;
660     for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) {
661         if (!dump_certs_pkeys_bag(out,
662                                   sk_PKCS12_SAFEBAG_value(bags, i),
663                                   pass, passlen, options, pempass, enc))
664             return 0;
665     }
666     return 1;
667 }
668
669 int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bag, char *pass,
670                          int passlen, int options, char *pempass,
671                          const EVP_CIPHER *enc)
672 {
673     EVP_PKEY *pkey;
674     PKCS8_PRIV_KEY_INFO *p8;
675     X509 *x509;
676     STACK_OF(X509_ATTRIBUTE) *attrs;
677     int ret = 0;
678
679     attrs = PKCS12_SAFEBAG_get0_attrs(bag);
680
681     switch (PKCS12_SAFEBAG_get_nid(bag)) {
682     case NID_keyBag:
683         if (options & INFO)
684             BIO_printf(bio_err, "Key bag\n");
685         if (options & NOKEYS)
686             return 1;
687         print_attribs(out, attrs, "Bag Attributes");
688         p8 = PKCS12_SAFEBAG_get0_p8inf(bag);
689         if ((pkey = EVP_PKCS82PKEY(p8)) == NULL)
690             return 0;
691         print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes");
692         ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
693         EVP_PKEY_free(pkey);
694         break;
695
696     case NID_pkcs8ShroudedKeyBag:
697         if (options & INFO) {
698             X509_SIG *tp8;
699             X509_ALGOR *tp8alg;
700
701             BIO_printf(bio_err, "Shrouded Keybag: ");
702             tp8 = PKCS12_SAFEBAG_get0_pkcs8(bag);
703             X509_SIG_get0(&tp8alg, NULL, tp8);
704             alg_print(tp8alg);
705         }
706         if (options & NOKEYS)
707             return 1;
708         print_attribs(out, attrs, "Bag Attributes");
709         if ((p8 = PKCS12_decrypt_skey(bag, pass, passlen)) == NULL)
710             return 0;
711         if ((pkey = EVP_PKCS82PKEY(p8)) == NULL) {
712             PKCS8_PRIV_KEY_INFO_free(p8);
713             return 0;
714         }
715         print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes");
716         PKCS8_PRIV_KEY_INFO_free(p8);
717         ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
718         EVP_PKEY_free(pkey);
719         break;
720
721     case NID_certBag:
722         if (options & INFO)
723             BIO_printf(bio_err, "Certificate bag\n");
724         if (options & NOCERTS)
725             return 1;
726         if (PKCS12_SAFEBAG_get0_attr(bag, NID_localKeyID)) {
727             if (options & CACERTS)
728                 return 1;
729         } else if (options & CLCERTS)
730             return 1;
731         print_attribs(out, attrs, "Bag Attributes");
732         if (PKCS12_SAFEBAG_get_bag_nid(bag) != NID_x509Certificate)
733             return 1;
734         if ((x509 = PKCS12_SAFEBAG_get1_cert(bag)) == NULL)
735             return 0;
736         dump_cert_text(out, x509);
737         ret = PEM_write_bio_X509(out, x509);
738         X509_free(x509);
739         break;
740
741     case NID_safeContentsBag:
742         if (options & INFO)
743             BIO_printf(bio_err, "Safe Contents bag\n");
744         print_attribs(out, attrs, "Bag Attributes");
745         return dump_certs_pkeys_bags(out, PKCS12_SAFEBAG_get0_safes(bag),
746                                      pass, passlen, options, pempass, enc);
747
748     default:
749         BIO_printf(bio_err, "Warning unsupported bag type: ");
750         i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_type(bag));
751         BIO_printf(bio_err, "\n");
752         return 1;
753     }
754     return ret;
755 }
756
757 /* Given a single certificate return a verified chain or NULL if error */
758
759 static int get_cert_chain(X509 *cert, X509_STORE *store,
760                           STACK_OF(X509) **chain)
761 {
762     X509_STORE_CTX *store_ctx = NULL;
763     STACK_OF(X509) *chn = NULL;
764     int i = 0;
765
766     store_ctx = X509_STORE_CTX_new();
767     if (store_ctx == NULL) {
768         i =  X509_V_ERR_UNSPECIFIED;
769         goto end;
770     }
771     if (!X509_STORE_CTX_init(store_ctx, store, cert, NULL)) {
772         i =  X509_V_ERR_UNSPECIFIED;
773         goto end;
774     }
775
776
777     if (X509_verify_cert(store_ctx) > 0)
778         chn = X509_STORE_CTX_get1_chain(store_ctx);
779     else if ((i = X509_STORE_CTX_get_error(store_ctx)) == 0)
780         i = X509_V_ERR_UNSPECIFIED;
781
782 end:
783     X509_STORE_CTX_free(store_ctx);
784     *chain = chn;
785     return i;
786 }
787
788 static int alg_print(X509_ALGOR *alg)
789 {
790     PBEPARAM *pbe;
791     const unsigned char *p = alg->parameter->value.sequence->data;
792
793     pbe = d2i_PBEPARAM(NULL, &p, alg->parameter->value.sequence->length);
794     if (!pbe)
795         return 1;
796     BIO_printf(bio_err, "%s, Iteration %ld\n",
797                OBJ_nid2ln(OBJ_obj2nid(alg->algorithm)),
798                ASN1_INTEGER_get(pbe->iter));
799     PBEPARAM_free(pbe);
800     return 1;
801 }
802
803 /* Load all certificates from a given file */
804
805 int cert_load(BIO *in, STACK_OF(X509) *sk)
806 {
807     int ret;
808     X509 *cert;
809     ret = 0;
810     while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
811         ret = 1;
812         sk_X509_push(sk, cert);
813     }
814     if (ret)
815         ERR_clear_error();
816     return ret;
817 }
818
819 /* Generalised attribute print: handle PKCS#8 and bag attributes */
820
821 int print_attribs(BIO *out, STACK_OF(X509_ATTRIBUTE) *attrlst,
822                   const char *name)
823 {
824     X509_ATTRIBUTE *attr;
825     ASN1_TYPE *av;
826     char *value;
827     int i, attr_nid;
828     if (!attrlst) {
829         BIO_printf(out, "%s: <No Attributes>\n", name);
830         return 1;
831     }
832     if (!sk_X509_ATTRIBUTE_num(attrlst)) {
833         BIO_printf(out, "%s: <Empty Attributes>\n", name);
834         return 1;
835     }
836     BIO_printf(out, "%s\n", name);
837     for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) {
838         ASN1_OBJECT *attr_obj;
839         attr = sk_X509_ATTRIBUTE_value(attrlst, i);
840         attr_obj = X509_ATTRIBUTE_get0_object(attr);
841         attr_nid = OBJ_obj2nid(attr_obj);
842         BIO_printf(out, "    ");
843         if (attr_nid == NID_undef) {
844             i2a_ASN1_OBJECT(out, attr_obj);
845             BIO_printf(out, ": ");
846         } else
847             BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
848
849         if (X509_ATTRIBUTE_count(attr)) {
850             av = X509_ATTRIBUTE_get0_type(attr, 0);
851             switch (av->type) {
852             case V_ASN1_BMPSTRING:
853                 value = OPENSSL_uni2asc(av->value.bmpstring->data,
854                                         av->value.bmpstring->length);
855                 BIO_printf(out, "%s\n", value);
856                 OPENSSL_free(value);
857                 break;
858
859             case V_ASN1_OCTET_STRING:
860                 hex_prin(out, av->value.octet_string->data,
861                          av->value.octet_string->length);
862                 BIO_printf(out, "\n");
863                 break;
864
865             case V_ASN1_BIT_STRING:
866                 hex_prin(out, av->value.bit_string->data,
867                          av->value.bit_string->length);
868                 BIO_printf(out, "\n");
869                 break;
870
871             default:
872                 BIO_printf(out, "<Unsupported tag %d>\n", av->type);
873                 break;
874             }
875         } else
876             BIO_printf(out, "<No Values>\n");
877     }
878     return 1;
879 }
880
881 void hex_prin(BIO *out, unsigned char *buf, int len)
882 {
883     int i;
884     for (i = 0; i < len; i++)
885         BIO_printf(out, "%02X ", buf[i]);
886 }
887
888 static int set_pbe(int *ppbe, const char *str)
889 {
890     if (!str)
891         return 0;
892     if (strcmp(str, "NONE") == 0) {
893         *ppbe = -1;
894         return 1;
895     }
896     *ppbe = OBJ_txt2nid(str);
897     if (*ppbe == NID_undef) {
898         BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str);
899         return 0;
900     }
901     return 1;
902 }
903
904 #endif