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