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