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