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