Small nits and cleanups
[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, const 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;
135     const char *CApath = NULL, *CAfile = NULL, *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         X509_ALGOR *macalgid;
526         const ASN1_OBJECT *macobj;
527         PKCS12_get0_mac(NULL, &macalgid, NULL, &tmaciter, p12);
528         X509_ALGOR_get0(&macobj, NULL, NULL, macalgid);
529         BIO_puts(bio_err, "MAC:");
530         i2a_ASN1_OBJECT(bio_err, macobj);
531         BIO_printf(bio_err, " Iteration %ld\n",
532                    tmaciter  != NULL ? ASN1_INTEGER_get(tmaciter) : 1L);
533     }
534     if (macver) {
535         /* If we enter empty password try no password first */
536         if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
537             /* If mac and crypto pass the same set it to NULL too */
538             if (!twopass)
539                 cpass = NULL;
540         } else if (!PKCS12_verify_mac(p12, mpass, -1)) {
541             BIO_printf(bio_err, "Mac verify error: invalid password?\n");
542             ERR_print_errors(bio_err);
543             goto end;
544         }
545     }
546
547     assert(private);
548     if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) {
549         BIO_printf(bio_err, "Error outputting keys and certificates\n");
550         ERR_print_errors(bio_err);
551         goto end;
552     }
553     ret = 0;
554  end:
555     PKCS12_free(p12);
556     if (export_cert || inrand)
557         app_RAND_write_file(NULL);
558     BIO_free(in);
559     BIO_free_all(out);
560     sk_OPENSSL_STRING_free(canames);
561     OPENSSL_free(passin);
562     OPENSSL_free(passout);
563     return (ret);
564 }
565
566 int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass,
567                         int passlen, int options, char *pempass,
568                         const EVP_CIPHER *enc)
569 {
570     STACK_OF(PKCS7) *asafes = NULL;
571     STACK_OF(PKCS12_SAFEBAG) *bags;
572     int i, bagnid;
573     int ret = 0;
574     PKCS7 *p7;
575
576     if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL)
577         return 0;
578     for (i = 0; i < sk_PKCS7_num(asafes); i++) {
579         p7 = sk_PKCS7_value(asafes, i);
580         bagnid = OBJ_obj2nid(p7->type);
581         if (bagnid == NID_pkcs7_data) {
582             bags = PKCS12_unpack_p7data(p7);
583             if (options & INFO)
584                 BIO_printf(bio_err, "PKCS7 Data\n");
585         } else if (bagnid == NID_pkcs7_encrypted) {
586             if (options & INFO) {
587                 BIO_printf(bio_err, "PKCS7 Encrypted data: ");
588                 alg_print(p7->d.encrypted->enc_data->algorithm);
589             }
590             bags = PKCS12_unpack_p7encdata(p7, pass, passlen);
591         } else
592             continue;
593         if (!bags)
594             goto err;
595         if (!dump_certs_pkeys_bags(out, bags, pass, passlen,
596                                    options, pempass, enc)) {
597             sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
598             goto err;
599         }
600         sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
601         bags = NULL;
602     }
603     ret = 1;
604
605  err:
606     sk_PKCS7_pop_free(asafes, PKCS7_free);
607     return ret;
608 }
609
610 int dump_certs_pkeys_bags(BIO *out, STACK_OF(PKCS12_SAFEBAG) *bags,
611                           char *pass, int passlen, int options, char *pempass,
612                           const EVP_CIPHER *enc)
613 {
614     int i;
615     for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) {
616         if (!dump_certs_pkeys_bag(out,
617                                   sk_PKCS12_SAFEBAG_value(bags, i),
618                                   pass, passlen, options, pempass, enc))
619             return 0;
620     }
621     return 1;
622 }
623
624 int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bag, char *pass,
625                          int passlen, int options, char *pempass,
626                          const EVP_CIPHER *enc)
627 {
628     EVP_PKEY *pkey;
629     PKCS8_PRIV_KEY_INFO *p8;
630     X509 *x509;
631     STACK_OF(X509_ATTRIBUTE) *attrs;
632     int ret = 0;
633
634     attrs = PKCS12_SAFEBAG_get0_attrs(bag);
635
636     switch (PKCS12_SAFEBAG_get_nid(bag)) {
637     case NID_keyBag:
638         if (options & INFO)
639             BIO_printf(bio_err, "Key bag\n");
640         if (options & NOKEYS)
641             return 1;
642         print_attribs(out, attrs, "Bag Attributes");
643         p8 = PKCS12_SAFEBAG_get0_p8inf(bag);
644         if ((pkey = EVP_PKCS82PKEY(p8)) == NULL)
645             return 0;
646         print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes");
647         ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
648         EVP_PKEY_free(pkey);
649         break;
650
651     case NID_pkcs8ShroudedKeyBag:
652         if (options & INFO) {
653             X509_SIG *tp8;
654             X509_ALGOR *tp8alg;
655
656             BIO_printf(bio_err, "Shrouded Keybag: ");
657             tp8 = PKCS12_SAFEBAG_get0_pkcs8(bag);
658             X509_SIG_get0(&tp8alg, NULL, tp8);
659             alg_print(tp8alg);
660         }
661         if (options & NOKEYS)
662             return 1;
663         print_attribs(out, attrs, "Bag Attributes");
664         if ((p8 = PKCS12_decrypt_skey(bag, pass, passlen)) == NULL)
665             return 0;
666         if ((pkey = EVP_PKCS82PKEY(p8)) == NULL) {
667             PKCS8_PRIV_KEY_INFO_free(p8);
668             return 0;
669         }
670         print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes");
671         PKCS8_PRIV_KEY_INFO_free(p8);
672         ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
673         EVP_PKEY_free(pkey);
674         break;
675
676     case NID_certBag:
677         if (options & INFO)
678             BIO_printf(bio_err, "Certificate bag\n");
679         if (options & NOCERTS)
680             return 1;
681         if (PKCS12_SAFEBAG_get0_attr(bag, NID_localKeyID)) {
682             if (options & CACERTS)
683                 return 1;
684         } else if (options & CLCERTS)
685             return 1;
686         print_attribs(out, attrs, "Bag Attributes");
687         if (PKCS12_SAFEBAG_get_bag_nid(bag) != NID_x509Certificate)
688             return 1;
689         if ((x509 = PKCS12_SAFEBAG_get1_cert(bag)) == NULL)
690             return 0;
691         dump_cert_text(out, x509);
692         ret = PEM_write_bio_X509(out, x509);
693         X509_free(x509);
694         break;
695
696     case NID_safeContentsBag:
697         if (options & INFO)
698             BIO_printf(bio_err, "Safe Contents bag\n");
699         print_attribs(out, attrs, "Bag Attributes");
700         return dump_certs_pkeys_bags(out, PKCS12_SAFEBAG_get0_safes(bag),
701                                      pass, passlen, options, pempass, enc);
702
703     default:
704         BIO_printf(bio_err, "Warning unsupported bag type: ");
705         i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_type(bag));
706         BIO_printf(bio_err, "\n");
707         return 1;
708     }
709     return ret;
710 }
711
712 /* Given a single certificate return a verified chain or NULL if error */
713
714 static int get_cert_chain(X509 *cert, X509_STORE *store,
715                           STACK_OF(X509) **chain)
716 {
717     X509_STORE_CTX *store_ctx = NULL;
718     STACK_OF(X509) *chn = NULL;
719     int i = 0;
720
721     store_ctx = X509_STORE_CTX_new();
722     if (store_ctx == NULL) {
723         i =  X509_V_ERR_UNSPECIFIED;
724         goto end;
725     }
726     if (!X509_STORE_CTX_init(store_ctx, store, cert, NULL)) {
727         i =  X509_V_ERR_UNSPECIFIED;
728         goto end;
729     }
730
731
732     if (X509_verify_cert(store_ctx) > 0)
733         chn = X509_STORE_CTX_get1_chain(store_ctx);
734     else if ((i = X509_STORE_CTX_get_error(store_ctx)) == 0)
735         i = X509_V_ERR_UNSPECIFIED;
736
737 end:
738     X509_STORE_CTX_free(store_ctx);
739     *chain = chn;
740     return i;
741 }
742
743 static int alg_print(X509_ALGOR *alg)
744 {
745     int pbenid, aparamtype;
746     const ASN1_OBJECT *aoid;
747     const void *aparam;
748     PBEPARAM *pbe = NULL;
749
750     X509_ALGOR_get0(&aoid, &aparamtype, &aparam, alg);
751
752     pbenid = OBJ_obj2nid(aoid);
753
754     BIO_printf(bio_err, "%s", OBJ_nid2ln(pbenid));
755
756     /*
757      * If PBE algorithm is PBES2 decode algorithm parameters
758      * for additional details.
759      */
760     if (pbenid == NID_pbes2) {
761         PBE2PARAM *pbe2 = NULL;
762         int encnid;
763         if (aparamtype == V_ASN1_SEQUENCE)
764             pbe2 = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBE2PARAM));
765         if (pbe2 == NULL) {
766             BIO_puts(bio_err, "<unsupported parameters>");
767             goto done;
768         }
769         X509_ALGOR_get0(&aoid, &aparamtype, &aparam, pbe2->keyfunc);
770         pbenid = OBJ_obj2nid(aoid);
771         X509_ALGOR_get0(&aoid, NULL, NULL, pbe2->encryption);
772         encnid = OBJ_obj2nid(aoid);
773         BIO_printf(bio_err, ", %s, %s", OBJ_nid2ln(pbenid),
774                    OBJ_nid2sn(encnid));
775         /* If KDF is PBKDF2 decode parameters */
776         if (pbenid == NID_id_pbkdf2) {
777             PBKDF2PARAM *kdf = NULL;
778             int prfnid;
779             if (aparamtype == V_ASN1_SEQUENCE)
780                 kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBKDF2PARAM));
781             if (kdf == NULL) {
782                 BIO_puts(bio_err, "<unsupported parameters>");
783                 goto done;
784             }
785
786             if (kdf->prf == NULL) {
787                 prfnid = NID_hmacWithSHA1;
788             } else {
789                 X509_ALGOR_get0(&aoid, NULL, NULL, kdf->prf);
790                 prfnid = OBJ_obj2nid(aoid);
791             }
792             BIO_printf(bio_err, ", Iteration %ld, PRF %s",
793                        ASN1_INTEGER_get(kdf->iter), OBJ_nid2sn(prfnid));
794             PBKDF2PARAM_free(kdf);
795         }
796         PBE2PARAM_free(pbe2);
797     } else {
798         if (aparamtype == V_ASN1_SEQUENCE)
799             pbe = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBEPARAM));
800         if (pbe == NULL) {
801             BIO_puts(bio_err, "<unsupported parameters>");
802             goto done;
803         }
804         BIO_printf(bio_err, ", Iteration %ld", ASN1_INTEGER_get(pbe->iter));
805         PBEPARAM_free(pbe);
806     }
807  done:
808     BIO_puts(bio_err, "\n");
809     return 1;
810 }
811
812 /* Load all certificates from a given file */
813
814 int cert_load(BIO *in, STACK_OF(X509) *sk)
815 {
816     int ret;
817     X509 *cert;
818     ret = 0;
819     while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
820         ret = 1;
821         sk_X509_push(sk, cert);
822     }
823     if (ret)
824         ERR_clear_error();
825     return ret;
826 }
827
828 /* Generalised attribute print: handle PKCS#8 and bag attributes */
829
830 int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst,
831                   const char *name)
832 {
833     X509_ATTRIBUTE *attr;
834     ASN1_TYPE *av;
835     char *value;
836     int i, attr_nid;
837     if (!attrlst) {
838         BIO_printf(out, "%s: <No Attributes>\n", name);
839         return 1;
840     }
841     if (!sk_X509_ATTRIBUTE_num(attrlst)) {
842         BIO_printf(out, "%s: <Empty Attributes>\n", name);
843         return 1;
844     }
845     BIO_printf(out, "%s\n", name);
846     for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) {
847         ASN1_OBJECT *attr_obj;
848         attr = sk_X509_ATTRIBUTE_value(attrlst, i);
849         attr_obj = X509_ATTRIBUTE_get0_object(attr);
850         attr_nid = OBJ_obj2nid(attr_obj);
851         BIO_printf(out, "    ");
852         if (attr_nid == NID_undef) {
853             i2a_ASN1_OBJECT(out, attr_obj);
854             BIO_printf(out, ": ");
855         } else
856             BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
857
858         if (X509_ATTRIBUTE_count(attr)) {
859             av = X509_ATTRIBUTE_get0_type(attr, 0);
860             switch (av->type) {
861             case V_ASN1_BMPSTRING:
862                 value = OPENSSL_uni2asc(av->value.bmpstring->data,
863                                         av->value.bmpstring->length);
864                 BIO_printf(out, "%s\n", value);
865                 OPENSSL_free(value);
866                 break;
867
868             case V_ASN1_OCTET_STRING:
869                 hex_prin(out, av->value.octet_string->data,
870                          av->value.octet_string->length);
871                 BIO_printf(out, "\n");
872                 break;
873
874             case V_ASN1_BIT_STRING:
875                 hex_prin(out, av->value.bit_string->data,
876                          av->value.bit_string->length);
877                 BIO_printf(out, "\n");
878                 break;
879
880             default:
881                 BIO_printf(out, "<Unsupported tag %d>\n", av->type);
882                 break;
883             }
884         } else
885             BIO_printf(out, "<No Values>\n");
886     }
887     return 1;
888 }
889
890 void hex_prin(BIO *out, unsigned char *buf, int len)
891 {
892     int i;
893     for (i = 0; i < len; i++)
894         BIO_printf(out, "%02X ", buf[i]);
895 }
896
897 static int set_pbe(int *ppbe, const char *str)
898 {
899     if (!str)
900         return 0;
901     if (strcmp(str, "NONE") == 0) {
902         *ppbe = -1;
903         return 1;
904     }
905     *ppbe = OBJ_txt2nid(str);
906     if (*ppbe == NID_undef) {
907         BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str);
908         return 0;
909     }
910     return 1;
911 }
912
913 #endif