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