sha/asm/keccak1600-avx2.pl: optimized remodelled version.
[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_RAND, 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 } OPTION_CHOICE;
60
61 const OPTIONS pkcs12_options[] = {
62     {"help", OPT_HELP, '-', "Display this summary"},
63     {"nokeys", OPT_NOKEYS, '-', "Don't output private keys"},
64     {"keyex", OPT_KEYEX, '-', "Set MS key exchange type"},
65     {"keysig", OPT_KEYSIG, '-', "Set MS key signature type"},
66     {"nocerts", OPT_NOCERTS, '-', "Don't output certificates"},
67     {"clcerts", OPT_CLCERTS, '-', "Only output client certificates"},
68     {"cacerts", OPT_CACERTS, '-', "Only output CA certificates"},
69     {"noout", OPT_NOOUT, '-', "Don't output anything, just verify"},
70     {"info", OPT_INFO, '-', "Print info about PKCS#12 structure"},
71     {"chain", OPT_CHAIN, '-', "Add certificate chain"},
72     {"twopass", OPT_TWOPASS, '-', "Separate MAC, encryption passwords"},
73     {"nomacver", OPT_NOMACVER, '-', "Don't verify MAC"},
74 # ifndef OPENSSL_NO_RC2
75     {"descert", OPT_DESCERT, '-',
76      "Encrypt output with 3DES (default RC2-40)"},
77     {"certpbe", OPT_CERTPBE, 's',
78      "Certificate PBE algorithm (default RC2-40)"},
79 # else
80     {"descert", OPT_DESCERT, '-', "Encrypt output with 3DES (the default)"},
81     {"certpbe", OPT_CERTPBE, 's', "Certificate PBE algorithm (default 3DES)"},
82 # endif
83     {"export", OPT_EXPORT, '-', "Output PKCS12 file"},
84     {"noiter", OPT_NOITER, '-', "Don't use encryption iteration"},
85     {"maciter", OPT_MACITER, '-', "Use MAC iteration"},
86     {"nomaciter", OPT_NOMACITER, '-', "Don't use MAC iteration"},
87     {"nomac", OPT_NOMAC, '-', "Don't generate MAC"},
88     {"LMK", OPT_LMK, '-',
89      "Add local machine keyset attribute to private key"},
90     {"nodes", OPT_NODES, '-', "Don't encrypt private keys"},
91     {"macalg", OPT_MACALG, 's',
92      "Digest algorithm used in MAC (default SHA1)"},
93     {"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default 3DES)"},
94     {"rand", OPT_RAND, 's',
95      "Load the file(s) into the random number generator"},
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, *inrand = 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_RAND:
229             inrand = opt_arg();
230             break;
231         case OPT_INKEY:
232             keyname = opt_arg();
233             break;
234         case OPT_CERTFILE:
235             certfile = opt_arg();
236             break;
237         case OPT_NAME:
238             name = opt_arg();
239             break;
240         case OPT_LMK:
241             add_lmk = 1;
242             break;
243         case OPT_CSP:
244             csp_name = opt_arg();
245             break;
246         case OPT_CANAME:
247             if (canames == NULL
248                 && (canames = sk_OPENSSL_STRING_new_null()) == NULL)
249                 goto end;
250             sk_OPENSSL_STRING_push(canames, opt_arg());
251             break;
252         case OPT_IN:
253             infile = opt_arg();
254             break;
255         case OPT_OUT:
256             outfile = opt_arg();
257             break;
258         case OPT_PASSIN:
259             passinarg = opt_arg();
260             break;
261         case OPT_PASSOUT:
262             passoutarg = opt_arg();
263             break;
264         case OPT_PASSWORD:
265             passarg = opt_arg();
266             break;
267         case OPT_CAPATH:
268             CApath = opt_arg();
269             break;
270         case OPT_CAFILE:
271             CAfile = opt_arg();
272             break;
273         case OPT_NOCAPATH:
274             noCApath = 1;
275             break;
276         case OPT_NOCAFILE:
277             noCAfile = 1;
278             break;
279         case OPT_ENGINE:
280             e = setup_engine(opt_arg(), 0);
281             break;
282         }
283     }
284     argc = opt_num_rest();
285     if (argc != 0)
286         goto opthelp;
287
288     private = 1;
289
290     if (passarg != NULL) {
291         if (export_cert)
292             passoutarg = passarg;
293         else
294             passinarg = passarg;
295     }
296
297     if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
298         BIO_printf(bio_err, "Error getting passwords\n");
299         goto end;
300     }
301
302     if (cpass == NULL) {
303         if (export_cert)
304             cpass = passout;
305         else
306             cpass = passin;
307     }
308
309     if (cpass != NULL) {
310         mpass = cpass;
311         noprompt = 1;
312     } else {
313         cpass = pass;
314         mpass = macpass;
315     }
316
317     if (export_cert || inrand != NULL) {
318         app_RAND_load_file(NULL, (inrand != NULL));
319         if (inrand != NULL)
320             BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
321                        app_RAND_load_files(inrand));
322     }
323
324     if (twopass) {
325         /* To avoid bit rot */
326         if (1) {
327 #ifndef OPENSSL_NO_UI_CONSOLE
328             if (EVP_read_pw_string
329                 (macpass, sizeof macpass, "Enter MAC Password:", export_cert)) {
330                 BIO_printf(bio_err, "Can't read Password\n");
331                 goto end;
332             }
333         } else {
334 #endif
335             BIO_printf(bio_err, "Unsupported option -twopass\n");
336             goto end;
337         }
338     }
339
340     if (export_cert) {
341         EVP_PKEY *key = NULL;
342         X509 *ucert = NULL, *x = NULL;
343         STACK_OF(X509) *certs = NULL;
344         const EVP_MD *macmd = NULL;
345         unsigned char *catmp = NULL;
346         int i;
347
348         if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
349             BIO_printf(bio_err, "Nothing to do!\n");
350             goto export_end;
351         }
352
353         if (options & NOCERTS)
354             chain = 0;
355
356         if (!(options & NOKEYS)) {
357             key = load_key(keyname ? keyname : infile,
358                            FORMAT_PEM, 1, passin, e, "private key");
359             if (key == NULL)
360                 goto export_end;
361         }
362
363         /* Load in all certs in input file */
364         if (!(options & NOCERTS)) {
365             if (!load_certs(infile, &certs, FORMAT_PEM, NULL,
366                             "certificates"))
367                 goto export_end;
368
369             if (key != NULL) {
370                 /* Look for matching private key */
371                 for (i = 0; i < sk_X509_num(certs); i++) {
372                     x = sk_X509_value(certs, i);
373                     if (X509_check_private_key(x, key)) {
374                         ucert = x;
375                         /* Zero keyid and alias */
376                         X509_keyid_set1(ucert, NULL, 0);
377                         X509_alias_set1(ucert, NULL, 0);
378                         /* Remove from list */
379                         (void)sk_X509_delete(certs, i);
380                         break;
381                     }
382                 }
383                 if (ucert == NULL) {
384                     BIO_printf(bio_err,
385                                "No certificate matches private key\n");
386                     goto export_end;
387                 }
388             }
389
390         }
391
392         /* Add any more certificates asked for */
393         if (certfile != NULL) {
394             if (!load_certs(certfile, &certs, FORMAT_PEM, NULL,
395                             "certificates from certfile"))
396                 goto export_end;
397         }
398
399         /* If chaining get chain from user cert */
400         if (chain) {
401             int vret;
402             STACK_OF(X509) *chain2;
403             X509_STORE *store;
404             if ((store = setup_verify(CAfile, CApath, noCAfile, noCApath))
405                     == NULL)
406                 goto export_end;
407
408             vret = get_cert_chain(ucert, store, &chain2);
409             X509_STORE_free(store);
410
411             if (vret == X509_V_OK) {
412                 /* Exclude verified certificate */
413                 for (i = 1; i < sk_X509_num(chain2); i++)
414                     sk_X509_push(certs, sk_X509_value(chain2, i));
415                 /* Free first certificate */
416                 X509_free(sk_X509_value(chain2, 0));
417                 sk_X509_free(chain2);
418             } else {
419                 if (vret != X509_V_ERR_UNSPECIFIED)
420                     BIO_printf(bio_err, "Error %s getting chain.\n",
421                                X509_verify_cert_error_string(vret));
422                 else
423                     ERR_print_errors(bio_err);
424                 goto export_end;
425             }
426         }
427
428         /* Add any CA names */
429
430         for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
431             catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i);
432             X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
433         }
434
435         if (csp_name != NULL && key != NULL)
436             EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
437                                       MBSTRING_ASC, (unsigned char *)csp_name,
438                                       -1);
439
440         if (add_lmk && key != NULL)
441             EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);
442
443         if (!noprompt) {
444             /* To avoid bit rot */
445             if (1) {
446 #ifndef OPENSSL_NO_UI_CONSOLE
447                 if (EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:",
448                                        1)) {
449                     BIO_printf(bio_err, "Can't read Password\n");
450                     goto export_end;
451                 }
452             } else {
453 #endif
454                 BIO_printf(bio_err, "Password required\n");
455                 goto export_end;
456             }
457         }
458
459         if (!twopass)
460             OPENSSL_strlcpy(macpass, pass, sizeof(macpass));
461
462         p12 = PKCS12_create(cpass, name, key, ucert, certs,
463                             key_pbe, cert_pbe, iter, -1, keytype);
464
465         if (!p12) {
466             ERR_print_errors(bio_err);
467             goto export_end;
468         }
469
470         if (macalg) {
471             if (!opt_md(macalg, &macmd))
472                 goto opthelp;
473         }
474
475         if (maciter != -1)
476             PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd);
477
478         assert(private);
479
480         out = bio_open_owner(outfile, FORMAT_PKCS12, private);
481         if (out == NULL)
482             goto end;
483
484         i2d_PKCS12_bio(out, p12);
485
486         ret = 0;
487
488  export_end:
489
490         EVP_PKEY_free(key);
491         sk_X509_pop_free(certs, X509_free);
492         X509_free(ucert);
493
494         goto end;
495
496     }
497
498     in = bio_open_default(infile, 'r', FORMAT_PKCS12);
499     if (in == NULL)
500         goto end;
501     out = bio_open_owner(outfile, FORMAT_PEM, private);
502     if (out == NULL)
503         goto end;
504
505     if ((p12 = d2i_PKCS12_bio(in, NULL)) == NULL) {
506         ERR_print_errors(bio_err);
507         goto end;
508     }
509
510     if (!noprompt) {
511         if (1) {
512 #ifndef OPENSSL_NO_UI_CONSOLE
513             if (EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:",
514                                    0)) {
515                 BIO_printf(bio_err, "Can't read Password\n");
516                 goto end;
517             }
518         } else {
519 #endif
520             BIO_printf(bio_err, "Password required\n");
521             goto end;
522         }
523     }
524
525     if (!twopass)
526         OPENSSL_strlcpy(macpass, pass, sizeof macpass);
527
528     if ((options & INFO) && PKCS12_mac_present(p12)) {
529         const ASN1_INTEGER *tmaciter;
530         const X509_ALGOR *macalgid;
531         const ASN1_OBJECT *macobj;
532         PKCS12_get0_mac(NULL, &macalgid, NULL, &tmaciter, p12);
533         X509_ALGOR_get0(&macobj, NULL, NULL, macalgid);
534         BIO_puts(bio_err, "MAC:");
535         i2a_ASN1_OBJECT(bio_err, macobj);
536         BIO_printf(bio_err, " Iteration %ld\n",
537                    tmaciter  != NULL ? ASN1_INTEGER_get(tmaciter) : 1L);
538     }
539     if (macver) {
540         /* If we enter empty password try no password first */
541         if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
542             /* If mac and crypto pass the same set it to NULL too */
543             if (!twopass)
544                 cpass = NULL;
545         } else if (!PKCS12_verify_mac(p12, mpass, -1)) {
546             /*
547              * May be UTF8 from previous version of OpenSSL:
548              * convert to a UTF8 form which will translate
549              * to the same Unicode password.
550              */
551             unsigned char *utmp;
552             int utmplen;
553             utmp = OPENSSL_asc2uni(mpass, -1, NULL, &utmplen);
554             if (utmp == NULL)
555                 goto end;
556             badpass = OPENSSL_uni2utf8(utmp, utmplen);
557             OPENSSL_free(utmp);
558             if (!PKCS12_verify_mac(p12, badpass, -1)) {
559                 BIO_printf(bio_err, "Mac verify error: invalid password?\n");
560                 ERR_print_errors(bio_err);
561                 goto end;
562             } else {
563                 BIO_printf(bio_err, "Warning: using broken algorithm\n");
564                 if (!twopass)
565                     cpass = badpass;
566             }
567         }
568     }
569
570     assert(private);
571     if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) {
572         BIO_printf(bio_err, "Error outputting keys and certificates\n");
573         ERR_print_errors(bio_err);
574         goto end;
575     }
576     ret = 0;
577  end:
578     PKCS12_free(p12);
579     if (export_cert || inrand)
580         app_RAND_write_file(NULL);
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         }
823         PBE2PARAM_free(pbe2);
824     } else {
825         if (aparamtype == V_ASN1_SEQUENCE)
826             pbe = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBEPARAM));
827         if (pbe == NULL) {
828             BIO_puts(bio_err, "<unsupported parameters>");
829             goto done;
830         }
831         BIO_printf(bio_err, ", Iteration %ld", ASN1_INTEGER_get(pbe->iter));
832         PBEPARAM_free(pbe);
833     }
834  done:
835     BIO_puts(bio_err, "\n");
836     return 1;
837 }
838
839 /* Load all certificates from a given file */
840
841 int cert_load(BIO *in, STACK_OF(X509) *sk)
842 {
843     int ret;
844     X509 *cert;
845     ret = 0;
846     while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
847         ret = 1;
848         sk_X509_push(sk, cert);
849     }
850     if (ret)
851         ERR_clear_error();
852     return ret;
853 }
854
855 /* Generalised attribute print: handle PKCS#8 and bag attributes */
856
857 int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst,
858                   const char *name)
859 {
860     X509_ATTRIBUTE *attr;
861     ASN1_TYPE *av;
862     char *value;
863     int i, attr_nid;
864     if (!attrlst) {
865         BIO_printf(out, "%s: <No Attributes>\n", name);
866         return 1;
867     }
868     if (!sk_X509_ATTRIBUTE_num(attrlst)) {
869         BIO_printf(out, "%s: <Empty Attributes>\n", name);
870         return 1;
871     }
872     BIO_printf(out, "%s\n", name);
873     for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) {
874         ASN1_OBJECT *attr_obj;
875         attr = sk_X509_ATTRIBUTE_value(attrlst, i);
876         attr_obj = X509_ATTRIBUTE_get0_object(attr);
877         attr_nid = OBJ_obj2nid(attr_obj);
878         BIO_printf(out, "    ");
879         if (attr_nid == NID_undef) {
880             i2a_ASN1_OBJECT(out, attr_obj);
881             BIO_printf(out, ": ");
882         } else {
883             BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
884         }
885
886         if (X509_ATTRIBUTE_count(attr)) {
887             av = X509_ATTRIBUTE_get0_type(attr, 0);
888             switch (av->type) {
889             case V_ASN1_BMPSTRING:
890                 value = OPENSSL_uni2asc(av->value.bmpstring->data,
891                                         av->value.bmpstring->length);
892                 BIO_printf(out, "%s\n", value);
893                 OPENSSL_free(value);
894                 break;
895
896             case V_ASN1_OCTET_STRING:
897                 hex_prin(out, av->value.octet_string->data,
898                          av->value.octet_string->length);
899                 BIO_printf(out, "\n");
900                 break;
901
902             case V_ASN1_BIT_STRING:
903                 hex_prin(out, av->value.bit_string->data,
904                          av->value.bit_string->length);
905                 BIO_printf(out, "\n");
906                 break;
907
908             default:
909                 BIO_printf(out, "<Unsupported tag %d>\n", av->type);
910                 break;
911             }
912         } else {
913             BIO_printf(out, "<No Values>\n");
914         }
915     }
916     return 1;
917 }
918
919 void hex_prin(BIO *out, unsigned char *buf, int len)
920 {
921     int i;
922     for (i = 0; i < len; i++)
923         BIO_printf(out, "%02X ", buf[i]);
924 }
925
926 static int set_pbe(int *ppbe, const char *str)
927 {
928     if (!str)
929         return 0;
930     if (strcmp(str, "NONE") == 0) {
931         *ppbe = -1;
932         return 1;
933     }
934     *ppbe = OBJ_txt2nid(str);
935     if (*ppbe == NID_undef) {
936         BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str);
937         return 0;
938     }
939     return 1;
940 }
941
942 #endif