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