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