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