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