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