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