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