apps: silent warning when loading CSR files with vfyopt option
[openssl.git] / apps / pkcs12.c
1 /*
2  * Copyright 1999-2022 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <openssl/opensslconf.h>
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include "apps.h"
16 #include "progs.h"
17 #include <openssl/conf.h>
18 #include <openssl/asn1.h>
19 #include <openssl/crypto.h>
20 #include <openssl/err.h>
21 #include <openssl/pem.h>
22 #include <openssl/pkcs12.h>
23 #include <openssl/provider.h>
24 #include <openssl/kdf.h>
25 #include <openssl/rand.h>
26
27 #define NOKEYS          0x1
28 #define NOCERTS         0x2
29 #define INFO            0x4
30 #define CLCERTS         0x8
31 #define CACERTS         0x10
32
33 #define PASSWD_BUF_SIZE 2048
34
35 #define WARN_EXPORT(opt) \
36     BIO_printf(bio_err, "Warning: -%s option ignored with -export\n", opt);
37 #define WARN_NO_EXPORT(opt) \
38     BIO_printf(bio_err, "Warning: -%s option ignored without -export\n", opt);
39
40 static int get_cert_chain(X509 *cert, X509_STORE *store,
41                           STACK_OF(X509) *untrusted_certs,
42                           STACK_OF(X509) **chain);
43 int dump_certs_keys_p12(BIO *out, const PKCS12 *p12,
44                         const char *pass, int passlen, int options,
45                         char *pempass, const EVP_CIPHER *enc);
46 int dump_certs_pkeys_bags(BIO *out, const STACK_OF(PKCS12_SAFEBAG) *bags,
47                           const char *pass, int passlen, int options,
48                           char *pempass, const EVP_CIPHER *enc);
49 int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bags,
50                          const char *pass, int passlen,
51                          int options, char *pempass, const EVP_CIPHER *enc);
52 void print_attribute(BIO *out, const ASN1_TYPE *av);
53 int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst,
54                   const char *name);
55 void hex_prin(BIO *out, unsigned char *buf, int len);
56 static int alg_print(const X509_ALGOR *alg);
57 int cert_load(BIO *in, STACK_OF(X509) *sk);
58 static int set_pbe(int *ppbe, const char *str);
59 static int jdk_trust(PKCS12_SAFEBAG *bag, void *cbarg);
60
61 typedef enum OPTION_choice {
62     OPT_COMMON,
63     OPT_CIPHER, OPT_NOKEYS, OPT_KEYEX, OPT_KEYSIG, OPT_NOCERTS, OPT_CLCERTS,
64     OPT_CACERTS, OPT_NOOUT, OPT_INFO, OPT_CHAIN, OPT_TWOPASS, OPT_NOMACVER,
65 #ifndef OPENSSL_NO_DES
66     OPT_DESCERT,
67 #endif
68     OPT_EXPORT, OPT_ITER, OPT_NOITER, OPT_MACITER, OPT_NOMACITER, OPT_MACSALTLEN,
69     OPT_NOMAC, OPT_LMK, OPT_NODES, OPT_NOENC, OPT_MACALG, OPT_CERTPBE, OPT_KEYPBE,
70     OPT_INKEY, OPT_CERTFILE, OPT_UNTRUSTED, OPT_PASSCERTS,
71     OPT_NAME, OPT_CSP, OPT_CANAME,
72     OPT_IN, OPT_OUT, OPT_PASSIN, OPT_PASSOUT, OPT_PASSWORD, OPT_CAPATH,
73     OPT_CAFILE, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_ENGINE,
74     OPT_R_ENUM, OPT_PROV_ENUM,
75 #ifndef OPENSSL_NO_DES
76     OPT_LEGACY_ALG
77 #endif
78 } OPTION_CHOICE;
79
80 const OPTIONS pkcs12_options[] = {
81     OPT_SECTION("General"),
82     {"help", OPT_HELP, '-', "Display this summary"},
83     {"in", OPT_IN, '<', "Input file"},
84     {"out", OPT_OUT, '>', "Output file"},
85     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
86     {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
87     {"password", OPT_PASSWORD, 's', "Set PKCS#12 import/export password source"},
88     {"twopass", OPT_TWOPASS, '-', "Separate MAC, encryption passwords"},
89     {"nokeys", OPT_NOKEYS, '-', "Don't output private keys"},
90     {"nocerts", OPT_NOCERTS, '-', "Don't output certificates"},
91     {"noout", OPT_NOOUT, '-', "Don't output anything, just verify PKCS#12 input"},
92 #ifndef OPENSSL_NO_DES
93     {"legacy", OPT_LEGACY_ALG, '-',
94 # ifdef OPENSSL_NO_RC2
95      "Use legacy encryption algorithm 3DES_CBC for keys and certs"
96 # else
97      "Use legacy encryption: 3DES_CBC for keys, RC2_CBC for certs"
98 # endif
99     },
100 #endif
101 #ifndef OPENSSL_NO_ENGINE
102     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
103 #endif
104     OPT_PROV_OPTIONS,
105     OPT_R_OPTIONS,
106
107     OPT_SECTION("PKCS#12 import (parsing PKCS#12)"),
108     {"info", OPT_INFO, '-', "Print info about PKCS#12 structure"},
109     {"nomacver", OPT_NOMACVER, '-', "Don't verify integrity MAC"},
110     {"clcerts", OPT_CLCERTS, '-', "Only output client certificates"},
111     {"cacerts", OPT_CACERTS, '-', "Only output CA certificates"},
112     {"", OPT_CIPHER, '-', "Any supported cipher for output encryption"},
113     {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"},
114     {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"},
115
116     OPT_SECTION("PKCS#12 output (export)"),
117     {"export", OPT_EXPORT, '-', "Create PKCS12 file"},
118     {"inkey", OPT_INKEY, 's', "Private key, else read from -in input file"},
119     {"certfile", OPT_CERTFILE, '<', "Extra certificates for PKCS12 output"},
120     {"passcerts", OPT_PASSCERTS, 's', "Certificate file pass phrase source"},
121     {"chain", OPT_CHAIN, '-', "Build and add certificate chain for EE cert,"},
122     {OPT_MORE_STR, 0, 0,
123      "which is the 1st cert from -in matching the private key (if given)"},
124     {"untrusted", OPT_UNTRUSTED, '<', "Untrusted certificates for chain building"},
125     {"CAfile", OPT_CAFILE, '<', "PEM-format file of CA's"},
126     {"CApath", OPT_CAPATH, '/', "PEM-format directory of CA's"},
127     {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"},
128     {"no-CAfile", OPT_NOCAFILE, '-',
129      "Do not load the default certificates file"},
130     {"no-CApath", OPT_NOCAPATH, '-',
131      "Do not load certificates from the default certificates directory"},
132     {"no-CAstore", OPT_NOCASTORE, '-',
133      "Do not load certificates from the default certificates store"},
134     {"name", OPT_NAME, 's', "Use name as friendly name"},
135     {"caname", OPT_CANAME, 's',
136      "Use name as CA friendly name (can be repeated)"},
137     {"CSP", OPT_CSP, 's', "Microsoft CSP name"},
138     {"LMK", OPT_LMK, '-',
139      "Add local machine keyset attribute to private key"},
140     {"keyex", OPT_KEYEX, '-', "Set key type to MS key exchange"},
141     {"keysig", OPT_KEYSIG, '-', "Set key type to MS key signature"},
142     {"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default AES-256 CBC)"},
143     {"certpbe", OPT_CERTPBE, 's',
144      "Certificate PBE algorithm (default PBES2 with PBKDF2 and AES-256 CBC)"},
145 #ifndef OPENSSL_NO_DES
146     {"descert", OPT_DESCERT, '-',
147      "Encrypt output with 3DES (default PBES2 with PBKDF2 and AES-256 CBC)"},
148 #endif
149     {"macalg", OPT_MACALG, 's',
150      "Digest algorithm to use in MAC (default SHA256)"},
151     {"iter", OPT_ITER, 'p', "Specify the iteration count for encryption and MAC"},
152     {"noiter", OPT_NOITER, '-', "Don't use encryption iteration"},
153     {"nomaciter", OPT_NOMACITER, '-', "Don't use MAC iteration)"},
154     {"maciter", OPT_MACITER, '-', "Unused, kept for backwards compatibility"},
155     {"macsaltlen", OPT_MACSALTLEN, '-', "Specify the salt len for MAC"},
156     {"nomac", OPT_NOMAC, '-', "Don't generate MAC"},
157     {NULL}
158 };
159
160 int pkcs12_main(int argc, char **argv)
161 {
162     char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL;
163     char *untrusted = NULL, *ciphername = NULL, *enc_name = NULL;
164     char *passcertsarg = NULL, *passcerts = NULL;
165     char *name = NULL, *csp_name = NULL;
166     char pass[PASSWD_BUF_SIZE] = "", macpass[PASSWD_BUF_SIZE] = "";
167     int export_pkcs12 = 0, options = 0, chain = 0, twopass = 0, keytype = 0;
168 #ifndef OPENSSL_NO_DES
169     int use_legacy = 0;
170 #endif
171     /* use library defaults for the iter, maciter, cert, and key PBE */
172     int iter = 0, maciter = 0;
173     int macsaltlen = PKCS12_SALT_LEN;
174     int cert_pbe = NID_undef;
175     int key_pbe = NID_undef;
176     int ret = 1, macver = 1, add_lmk = 0, private = 0;
177     int noprompt = 0;
178     char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL;
179     char *passin = NULL, *passout = NULL, *macalg = NULL;
180     char *cpass = NULL, *mpass = NULL, *badpass = NULL;
181     const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL, *prog;
182     int noCApath = 0, noCAfile = 0, noCAstore = 0;
183     ENGINE *e = NULL;
184     BIO *in = NULL, *out = NULL;
185     PKCS12 *p12 = NULL;
186     STACK_OF(OPENSSL_STRING) *canames = NULL;
187     EVP_CIPHER *default_enc = (EVP_CIPHER *)EVP_aes_256_cbc();
188     EVP_CIPHER *enc = (EVP_CIPHER *)default_enc;
189     OPTION_CHOICE o;
190
191     opt_set_unknown_name("cipher");
192     prog = opt_init(argc, argv, pkcs12_options);
193     while ((o = opt_next()) != OPT_EOF) {
194         switch (o) {
195         case OPT_EOF:
196         case OPT_ERR:
197  opthelp:
198             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
199             goto end;
200         case OPT_HELP:
201             opt_help(pkcs12_options);
202             ret = 0;
203             goto end;
204         case OPT_NOKEYS:
205             options |= NOKEYS;
206             break;
207         case OPT_KEYEX:
208             keytype = KEY_EX;
209             break;
210         case OPT_KEYSIG:
211             keytype = KEY_SIG;
212             break;
213         case OPT_NOCERTS:
214             options |= NOCERTS;
215             break;
216         case OPT_CLCERTS:
217             options |= CLCERTS;
218             break;
219         case OPT_CACERTS:
220             options |= CACERTS;
221             break;
222         case OPT_NOOUT:
223             options |= (NOKEYS | NOCERTS);
224             break;
225         case OPT_INFO:
226             options |= INFO;
227             break;
228         case OPT_CHAIN:
229             chain = 1;
230             break;
231         case OPT_TWOPASS:
232             twopass = 1;
233             break;
234         case OPT_NOMACVER:
235             macver = 0;
236             break;
237 #ifndef OPENSSL_NO_DES
238         case OPT_DESCERT:
239             cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
240             break;
241 #endif
242         case OPT_EXPORT:
243             export_pkcs12 = 1;
244             break;
245         case OPT_NODES:
246         case OPT_NOENC:
247             /*
248              * |enc_name| stores the name of the option used so it
249              * can be printed if an error message is output.
250              */
251             enc_name = opt_flag() + 1;
252             enc = NULL;
253             ciphername = NULL;
254             break;
255         case OPT_CIPHER:
256             enc_name = ciphername = opt_unknown();
257             break;
258         case OPT_ITER:
259             maciter = iter = opt_int_arg();
260             break;
261         case OPT_NOITER:
262             iter = 1;
263             break;
264         case OPT_MACITER:
265             /* no-op */
266             break;
267         case OPT_NOMACITER:
268             maciter = 1;
269             break;
270         case OPT_MACSALTLEN:
271             macsaltlen = opt_int_arg();
272             break;
273         case OPT_NOMAC:
274             cert_pbe = -1;
275             maciter = -1;
276             break;
277         case OPT_MACALG:
278             macalg = opt_arg();
279             break;
280         case OPT_CERTPBE:
281             if (!set_pbe(&cert_pbe, opt_arg()))
282                 goto opthelp;
283             break;
284         case OPT_KEYPBE:
285             if (!set_pbe(&key_pbe, opt_arg()))
286                 goto opthelp;
287             break;
288         case OPT_R_CASES:
289             if (!opt_rand(o))
290                 goto end;
291             break;
292         case OPT_INKEY:
293             keyname = opt_arg();
294             break;
295         case OPT_CERTFILE:
296             certfile = opt_arg();
297             break;
298         case OPT_UNTRUSTED:
299             untrusted = opt_arg();
300             break;
301         case OPT_PASSCERTS:
302             passcertsarg = opt_arg();
303             break;
304         case OPT_NAME:
305             name = opt_arg();
306             break;
307         case OPT_LMK:
308             add_lmk = 1;
309             break;
310         case OPT_CSP:
311             csp_name = opt_arg();
312             break;
313         case OPT_CANAME:
314             if (canames == NULL
315                 && (canames = sk_OPENSSL_STRING_new_null()) == NULL)
316                 goto end;
317             sk_OPENSSL_STRING_push(canames, opt_arg());
318             break;
319         case OPT_IN:
320             infile = opt_arg();
321             break;
322         case OPT_OUT:
323             outfile = opt_arg();
324             break;
325         case OPT_PASSIN:
326             passinarg = opt_arg();
327             break;
328         case OPT_PASSOUT:
329             passoutarg = opt_arg();
330             break;
331         case OPT_PASSWORD:
332             passarg = opt_arg();
333             break;
334         case OPT_CAPATH:
335             CApath = opt_arg();
336             break;
337         case OPT_CASTORE:
338             CAstore = opt_arg();
339             break;
340         case OPT_CAFILE:
341             CAfile = opt_arg();
342             break;
343         case OPT_NOCAPATH:
344             noCApath = 1;
345             break;
346         case OPT_NOCASTORE:
347             noCAstore = 1;
348             break;
349         case OPT_NOCAFILE:
350             noCAfile = 1;
351             break;
352         case OPT_ENGINE:
353             e = setup_engine(opt_arg(), 0);
354             break;
355 #ifndef OPENSSL_NO_DES
356         case OPT_LEGACY_ALG:
357             use_legacy = 1;
358             break;
359 #endif
360         case OPT_PROV_CASES:
361             if (!opt_provider(o))
362                 goto end;
363             break;
364         }
365     }
366
367     /* No extra arguments. */
368     if (!opt_check_rest_arg(NULL))
369         goto opthelp;
370
371     if (!app_RAND_load())
372         goto end;
373
374     if (!opt_cipher_any(ciphername, &enc))
375         goto opthelp;
376     if (export_pkcs12) {
377         if ((options & INFO) != 0)
378             WARN_EXPORT("info");
379         if (macver == 0)
380             WARN_EXPORT("nomacver");
381         if ((options & CLCERTS) != 0)
382             WARN_EXPORT("clcerts");
383         if ((options & CACERTS) != 0)
384             WARN_EXPORT("cacerts");
385         if (enc != default_enc)
386             BIO_printf(bio_err,
387                        "Warning: output encryption option -%s ignored with -export\n", enc_name);
388     } else {
389         if (keyname != NULL)
390             WARN_NO_EXPORT("inkey");
391         if (certfile != NULL)
392             WARN_NO_EXPORT("certfile");
393         if (passcertsarg != NULL)
394             WARN_NO_EXPORT("passcerts");
395         if (chain)
396             WARN_NO_EXPORT("chain");
397         if (untrusted != NULL)
398             WARN_NO_EXPORT("untrusted");
399         if (CAfile != NULL)
400             WARN_NO_EXPORT("CAfile");
401         if (CApath != NULL)
402             WARN_NO_EXPORT("CApath");
403         if (CAstore != NULL)
404             WARN_NO_EXPORT("CAstore");
405         if (noCAfile)
406             WARN_NO_EXPORT("no-CAfile");
407         if (noCApath)
408             WARN_NO_EXPORT("no-CApath");
409         if (noCAstore)
410             WARN_NO_EXPORT("no-CAstore");
411         if (name != NULL)
412             WARN_NO_EXPORT("name");
413         if (canames != NULL)
414             WARN_NO_EXPORT("caname");
415         if (csp_name != NULL)
416             WARN_NO_EXPORT("CSP");
417         if (add_lmk)
418             WARN_NO_EXPORT("LMK");
419         if (keytype == KEY_EX)
420             WARN_NO_EXPORT("keyex");
421         if (keytype == KEY_SIG)
422             WARN_NO_EXPORT("keysig");
423         if (key_pbe != NID_undef)
424             WARN_NO_EXPORT("keypbe");
425         if (cert_pbe != NID_undef && cert_pbe != -1)
426             WARN_NO_EXPORT("certpbe and -descert");
427         if (macalg != NULL)
428             WARN_NO_EXPORT("macalg");
429         if (iter != 0)
430             WARN_NO_EXPORT("iter and -noiter");
431         if (maciter == 1)
432             WARN_NO_EXPORT("nomaciter");
433         if (cert_pbe == -1 && maciter == -1)
434             WARN_NO_EXPORT("nomac");
435         if (macsaltlen != 0)
436             WARN_NO_EXPORT("macsaltlen");
437     }
438 #ifndef OPENSSL_NO_DES
439     if (use_legacy) {
440         /* load the legacy provider if not loaded already*/
441         if (!OSSL_PROVIDER_available(app_get0_libctx(), "legacy")) {
442             if (!app_provider_load(app_get0_libctx(), "legacy"))
443                 goto end;
444             /* load the default provider explicitly */
445             if (!app_provider_load(app_get0_libctx(), "default"))
446                 goto end;
447         }
448         if (cert_pbe == NID_undef) {
449             /* Adapt default algorithm */
450 # ifndef OPENSSL_NO_RC2
451             cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
452 # else
453             cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
454 # endif
455         }
456
457         if (key_pbe == NID_undef)
458             key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
459         if (enc == default_enc)
460             enc = (EVP_CIPHER *)EVP_des_ede3_cbc();
461         if (macalg == NULL)
462             macalg = "sha1";
463     }
464 #endif
465
466     private = 1;
467
468     if (!app_passwd(passcertsarg, NULL, &passcerts, NULL)) {
469         BIO_printf(bio_err, "Error getting certificate file password\n");
470         goto end;
471     }
472
473     if (passarg != NULL) {
474         if (export_pkcs12)
475             passoutarg = passarg;
476         else
477             passinarg = passarg;
478     }
479
480     if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
481         BIO_printf(bio_err, "Error getting passwords\n");
482         goto end;
483     }
484
485     if (cpass == NULL) {
486         if (export_pkcs12)
487             cpass = passout;
488         else
489             cpass = passin;
490     }
491
492     if (cpass != NULL) {
493         mpass = cpass;
494         noprompt = 1;
495         if (twopass) {
496             if (export_pkcs12)
497                 BIO_printf(bio_err, "Option -twopass cannot be used with -passout or -password\n");
498             else
499                 BIO_printf(bio_err, "Option -twopass cannot be used with -passin or -password\n");
500             goto end;
501         }
502     } else {
503         cpass = pass;
504         mpass = macpass;
505     }
506
507     if (twopass) {
508         /* To avoid bit rot */
509         if (1) {
510 #ifndef OPENSSL_NO_UI_CONSOLE
511             if (EVP_read_pw_string(
512                 macpass, sizeof(macpass), "Enter MAC Password:", export_pkcs12)) {
513                 BIO_printf(bio_err, "Can't read Password\n");
514                 goto end;
515             }
516         } else {
517 #endif
518             BIO_printf(bio_err, "Unsupported option -twopass\n");
519             goto end;
520         }
521     }
522
523     if (export_pkcs12) {
524         EVP_PKEY *key = NULL;
525         X509 *ee_cert = NULL, *x = NULL;
526         STACK_OF(X509) *certs = NULL;
527         STACK_OF(X509) *untrusted_certs = NULL;
528         EVP_MD *macmd = NULL;
529         unsigned char *catmp = NULL;
530         int i;
531         CONF *conf = NULL;
532         ASN1_OBJECT *obj = NULL;
533         STACK_OF(CONF_VALUE) *cb_sk = NULL;
534         const char *cb_attr = NULL;
535         const CONF_VALUE *val = NULL;
536
537         if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
538             BIO_printf(bio_err, "Nothing to export due to -noout or -nocerts and -nokeys\n");
539             goto export_end;
540         }
541
542         if ((options & NOCERTS) != 0) {
543             chain = 0;
544             BIO_printf(bio_err, "Warning: -chain option ignored with -nocerts\n");
545         }
546
547         if (!(options & NOKEYS)) {
548             key = load_key(keyname ? keyname : infile,
549                            FORMAT_PEM, 1, passin, e,
550                            keyname ?
551                            "private key from -inkey file" :
552                            "private key from -in file");
553             if (key == NULL)
554                 goto export_end;
555         }
556
557         /* Load all certs in input file */
558         if (!(options & NOCERTS)) {
559             if (!load_certs(infile, 1, &certs, passin,
560                             "certificates from -in file"))
561                 goto export_end;
562             if (sk_X509_num(certs) < 1) {
563                 BIO_printf(bio_err, "No certificate in -in file %s\n", infile);
564                 goto export_end;
565             }
566
567             if (key != NULL) {
568                 /* Look for matching private key */
569                 for (i = 0; i < sk_X509_num(certs); i++) {
570                     x = sk_X509_value(certs, i);
571                     if (cert_matches_key(x, key)) {
572                         ee_cert = x;
573                         /* Zero keyid and alias */
574                         X509_keyid_set1(ee_cert, NULL, 0);
575                         X509_alias_set1(ee_cert, NULL, 0);
576                         /* Remove from list */
577                         (void)sk_X509_delete(certs, i);
578                         break;
579                     }
580                 }
581                 if (ee_cert == NULL) {
582                     BIO_printf(bio_err,
583                                "No cert in -in file '%s' matches private key\n",
584                                infile);
585                     goto export_end;
586                 }
587             }
588         }
589
590         /* Load any untrusted certificates for chain building */
591         if (untrusted != NULL) {
592             if (!load_certs(untrusted, 0, &untrusted_certs, passcerts,
593                             "untrusted certificates"))
594                 goto export_end;
595         }
596
597         /* If chaining get chain from end entity cert */
598         if (chain) {
599             int vret;
600             STACK_OF(X509) *chain2;
601             X509_STORE *store;
602             X509 *ee_cert_tmp = ee_cert;
603
604             /* Assume the first cert if we haven't got anything else */
605             if (ee_cert_tmp == NULL && certs != NULL)
606                 ee_cert_tmp = sk_X509_value(certs, 0);
607
608             if (ee_cert_tmp == NULL) {
609                 BIO_printf(bio_err,
610                            "No end entity certificate to check with -chain\n");
611                 goto export_end;
612             }
613
614             if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath,
615                                       CAstore, noCAstore))
616                     == NULL)
617                 goto export_end;
618
619             vret = get_cert_chain(ee_cert_tmp, store, untrusted_certs, &chain2);
620             X509_STORE_free(store);
621
622             if (vret == X509_V_OK) {
623                 int add_certs;
624                 /* Remove from chain2 the first (end entity) certificate */
625                 X509_free(sk_X509_shift(chain2));
626                 /* Add the remaining certs (except for duplicates) */
627                 add_certs = X509_add_certs(certs, chain2, X509_ADD_FLAG_UP_REF
628                                            | X509_ADD_FLAG_NO_DUP);
629                 OSSL_STACK_OF_X509_free(chain2);
630                 if (!add_certs)
631                     goto export_end;
632             } else {
633                 if (vret != X509_V_ERR_UNSPECIFIED)
634                     BIO_printf(bio_err, "Error getting chain: %s\n",
635                                X509_verify_cert_error_string(vret));
636                 goto export_end;
637             }
638         }
639
640         /* Add any extra certificates asked for */
641         if (certfile != NULL) {
642             if (!load_certs(certfile, 0, &certs, passcerts,
643                             "extra certificates from -certfile"))
644                 goto export_end;
645         }
646
647         /* Add any CA names */
648         for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
649             catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i);
650             X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
651         }
652
653         if (csp_name != NULL && key != NULL)
654             EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
655                                       MBSTRING_ASC, (unsigned char *)csp_name,
656                                       -1);
657
658         if (add_lmk && key != NULL)
659             EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);
660
661         if (!noprompt && !(enc == NULL && maciter == -1)) {
662             /* To avoid bit rot */
663             if (1) {
664 #ifndef OPENSSL_NO_UI_CONSOLE
665                 if (EVP_read_pw_string(pass, sizeof(pass),
666                                        "Enter Export Password:", 1)) {
667                     BIO_printf(bio_err, "Can't read Password\n");
668                     goto export_end;
669                 }
670             } else {
671 #endif
672                 BIO_printf(bio_err, "Password required\n");
673                 goto export_end;
674             }
675         }
676
677         if (!twopass)
678             OPENSSL_strlcpy(macpass, pass, sizeof(macpass));
679
680         /* Load the config file */
681         if ((conf = app_load_config(default_config_file)) == NULL)
682             goto export_end;
683         if (!app_load_modules(conf))
684             goto export_end;
685         /* Find the cert bag section */
686         if ((cb_attr = NCONF_get_string(conf, "pkcs12", "certBagAttr")) != NULL) {
687             if ((cb_sk = NCONF_get_section(conf, cb_attr)) != NULL) {
688                 for (i = 0; i < sk_CONF_VALUE_num(cb_sk); i++) {
689                     val = sk_CONF_VALUE_value(cb_sk, i);
690                     if (strcmp(val->name, "jdkTrustedKeyUsage") == 0) {
691                         obj = OBJ_txt2obj(val->value, 0);
692                         break;
693                     }
694                 }
695             } else {
696                 ERR_clear_error();
697             }
698         } else {
699             ERR_clear_error();
700         }
701
702         p12 = PKCS12_create_ex2(cpass, name, key, ee_cert, certs,
703                                 key_pbe, cert_pbe, iter, -1, keytype,
704                                 app_get0_libctx(), app_get0_propq(),
705                                 jdk_trust, (void*)obj);
706
707         if (p12 == NULL) {
708             BIO_printf(bio_err, "Error creating PKCS12 structure for %s\n",
709                        outfile);
710             goto export_end;
711         }
712
713         if (macalg != NULL) {
714             if (!opt_md(macalg, &macmd))
715                 goto opthelp;
716         }
717
718         if (maciter != -1) {
719             if (!PKCS12_set_mac(p12, mpass, -1, NULL, macsaltlen, maciter, macmd)) {
720                 BIO_printf(bio_err, "Error creating PKCS12 MAC; no PKCS12KDF support?\n");
721                 BIO_printf(bio_err, "Use -nomac if MAC not required and PKCS12KDF support not available.\n");
722                 goto export_end;
723             }
724         }
725         assert(private);
726
727         out = bio_open_owner(outfile, FORMAT_PKCS12, private);
728         if (out == NULL)
729             goto end;
730
731         i2d_PKCS12_bio(out, p12);
732
733         ret = 0;
734
735  export_end:
736
737         EVP_PKEY_free(key);
738         EVP_MD_free(macmd);
739         OSSL_STACK_OF_X509_free(certs);
740         OSSL_STACK_OF_X509_free(untrusted_certs);
741         X509_free(ee_cert);
742         NCONF_free(conf);
743         ASN1_OBJECT_free(obj);
744         ERR_print_errors(bio_err);
745         goto end;
746
747     }
748
749     in = bio_open_default(infile, 'r', FORMAT_PKCS12);
750     if (in == NULL)
751         goto end;
752     out = bio_open_owner(outfile, FORMAT_PEM, private);
753     if (out == NULL)
754         goto end;
755
756     p12 = PKCS12_init_ex(NID_pkcs7_data, app_get0_libctx(), app_get0_propq());
757     if (p12 == NULL) {
758         ERR_print_errors(bio_err);
759         goto end;
760     }
761     if ((p12 = d2i_PKCS12_bio(in, &p12)) == NULL) {
762         ERR_print_errors(bio_err);
763         goto end;
764     }
765
766     if (!noprompt) {
767         if (1) {
768 #ifndef OPENSSL_NO_UI_CONSOLE
769             if (EVP_read_pw_string(pass, sizeof(pass), "Enter Import Password:",
770                                    0)) {
771                 BIO_printf(bio_err, "Can't read Password\n");
772                 goto end;
773             }
774         } else {
775 #endif
776             BIO_printf(bio_err, "Password required\n");
777             goto end;
778         }
779     }
780
781     if (!twopass)
782         OPENSSL_strlcpy(macpass, pass, sizeof(macpass));
783
784     if ((options & INFO) && PKCS12_mac_present(p12)) {
785         const ASN1_INTEGER *tmaciter;
786         const X509_ALGOR *macalgid;
787         const ASN1_OBJECT *macobj;
788         const ASN1_OCTET_STRING *tmac;
789         const ASN1_OCTET_STRING *tsalt;
790
791         PKCS12_get0_mac(&tmac, &macalgid, &tsalt, &tmaciter, p12);
792         /* current hash algorithms do not use parameters so extract just name,
793            in future alg_print() may be needed */
794         X509_ALGOR_get0(&macobj, NULL, NULL, macalgid);
795         BIO_puts(bio_err, "MAC: ");
796         i2a_ASN1_OBJECT(bio_err, macobj);
797         BIO_printf(bio_err, ", Iteration %ld\n",
798                    tmaciter != NULL ? ASN1_INTEGER_get(tmaciter) : 1L);
799         BIO_printf(bio_err, "MAC length: %ld, salt length: %ld\n",
800                    tmac != NULL ? ASN1_STRING_length(tmac) : 0L,
801                    tsalt != NULL ? ASN1_STRING_length(tsalt) : 0L);
802     }
803     if (macver) {
804         EVP_KDF *pkcs12kdf;
805
806         pkcs12kdf = EVP_KDF_fetch(app_get0_libctx(), "PKCS12KDF",
807                                   app_get0_propq());
808         if (pkcs12kdf == NULL) {
809             BIO_printf(bio_err, "Error verifying PKCS12 MAC; no PKCS12KDF support.\n");
810             BIO_printf(bio_err, "Use -nomacver if MAC verification is not required.\n");
811             goto end;
812         }
813         EVP_KDF_free(pkcs12kdf);
814         /* If we enter empty password try no password first */
815         if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
816             /* If mac and crypto pass the same set it to NULL too */
817             if (!twopass)
818                 cpass = NULL;
819         } else if (!PKCS12_verify_mac(p12, mpass, -1)) {
820             /*
821              * May be UTF8 from previous version of OpenSSL:
822              * convert to a UTF8 form which will translate
823              * to the same Unicode password.
824              */
825             unsigned char *utmp;
826             int utmplen;
827             unsigned long err = ERR_peek_error();
828
829             if (ERR_GET_LIB(err) == ERR_LIB_PKCS12
830                 && ERR_GET_REASON(err) == PKCS12_R_MAC_ABSENT) {
831                 BIO_printf(bio_err, "Warning: MAC is absent!\n");
832                 goto dump;
833             }
834
835             utmp = OPENSSL_asc2uni(mpass, -1, NULL, &utmplen);
836             if (utmp == NULL)
837                 goto end;
838             badpass = OPENSSL_uni2utf8(utmp, utmplen);
839             OPENSSL_free(utmp);
840             if (!PKCS12_verify_mac(p12, badpass, -1)) {
841                 BIO_printf(bio_err, "Mac verify error: invalid password?\n");
842                 ERR_print_errors(bio_err);
843                 goto end;
844             } else {
845                 BIO_printf(bio_err, "Warning: using broken algorithm\n");
846                 if (!twopass)
847                     cpass = badpass;
848             }
849         }
850     }
851
852  dump:
853     assert(private);
854     if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) {
855         BIO_printf(bio_err, "Error outputting keys and certificates\n");
856         ERR_print_errors(bio_err);
857         goto end;
858     }
859     ret = 0;
860  end:
861     PKCS12_free(p12);
862     release_engine(e);
863     BIO_free(in);
864     BIO_free_all(out);
865     sk_OPENSSL_STRING_free(canames);
866     OPENSSL_free(badpass);
867     OPENSSL_free(passcerts);
868     OPENSSL_free(passin);
869     OPENSSL_free(passout);
870     return ret;
871 }
872
873 static int jdk_trust(PKCS12_SAFEBAG *bag, void *cbarg)
874 {
875     STACK_OF(X509_ATTRIBUTE) *attrs = NULL;
876     X509_ATTRIBUTE *attr = NULL;
877
878     /* Nothing to do */
879     if (cbarg == NULL)
880         return 1;
881
882     /* Get the current attrs */
883     attrs = (STACK_OF(X509_ATTRIBUTE)*)PKCS12_SAFEBAG_get0_attrs(bag);
884
885     /* Create a new attr for the JDK Trusted Usage and add it */
886     attr = X509_ATTRIBUTE_create(NID_oracle_jdk_trustedkeyusage, V_ASN1_OBJECT, (ASN1_OBJECT*)cbarg);
887
888     /* Add the new attr, if attrs is NULL, it'll be initialised */
889     X509at_add1_attr(&attrs, attr);
890
891     /* Set the bag attrs */
892     PKCS12_SAFEBAG_set0_attrs(bag, attrs);
893
894     X509_ATTRIBUTE_free(attr);
895     return 1;
896 }
897
898 int dump_certs_keys_p12(BIO *out, const PKCS12 *p12, const char *pass,
899                         int passlen, int options, char *pempass,
900                         const EVP_CIPHER *enc)
901 {
902     STACK_OF(PKCS7) *asafes = NULL;
903     STACK_OF(PKCS12_SAFEBAG) *bags;
904     int i, bagnid;
905     int ret = 0;
906     PKCS7 *p7;
907
908     if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL)
909         return 0;
910     for (i = 0; i < sk_PKCS7_num(asafes); i++) {
911         p7 = sk_PKCS7_value(asafes, i);
912         bagnid = OBJ_obj2nid(p7->type);
913         if (bagnid == NID_pkcs7_data) {
914             bags = PKCS12_unpack_p7data(p7);
915             if (options & INFO)
916                 BIO_printf(bio_err, "PKCS7 Data\n");
917         } else if (bagnid == NID_pkcs7_encrypted) {
918             if (options & INFO) {
919                 BIO_printf(bio_err, "PKCS7 Encrypted data: ");
920                 alg_print(p7->d.encrypted->enc_data->algorithm);
921             }
922             bags = PKCS12_unpack_p7encdata(p7, pass, passlen);
923         } else {
924             continue;
925         }
926         if (!bags)
927             goto err;
928         if (!dump_certs_pkeys_bags(out, bags, pass, passlen,
929                                    options, pempass, enc)) {
930             sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
931             goto err;
932         }
933         sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
934         bags = NULL;
935     }
936     ret = 1;
937
938  err:
939     sk_PKCS7_pop_free(asafes, PKCS7_free);
940     return ret;
941 }
942
943 int dump_certs_pkeys_bags(BIO *out, const STACK_OF(PKCS12_SAFEBAG) *bags,
944                           const char *pass, int passlen, int options,
945                           char *pempass, const EVP_CIPHER *enc)
946 {
947     int i;
948     for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) {
949         if (!dump_certs_pkeys_bag(out,
950                                   sk_PKCS12_SAFEBAG_value(bags, i),
951                                   pass, passlen, options, pempass, enc))
952             return 0;
953     }
954     return 1;
955 }
956
957 int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bag,
958                          const char *pass, int passlen, int options,
959                          char *pempass, const EVP_CIPHER *enc)
960 {
961     EVP_PKEY *pkey;
962     PKCS8_PRIV_KEY_INFO *p8;
963     const PKCS8_PRIV_KEY_INFO *p8c;
964     X509 *x509;
965     const STACK_OF(X509_ATTRIBUTE) *attrs;
966     int ret = 0;
967
968     attrs = PKCS12_SAFEBAG_get0_attrs(bag);
969
970     switch (PKCS12_SAFEBAG_get_nid(bag)) {
971     case NID_keyBag:
972         if (options & INFO)
973             BIO_printf(bio_err, "Key bag\n");
974         if (options & NOKEYS)
975             return 1;
976         print_attribs(out, attrs, "Bag Attributes");
977         p8c = PKCS12_SAFEBAG_get0_p8inf(bag);
978         if ((pkey = EVP_PKCS82PKEY(p8c)) == NULL)
979             return 0;
980         print_attribs(out, PKCS8_pkey_get0_attrs(p8c), "Key Attributes");
981         ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
982         EVP_PKEY_free(pkey);
983         break;
984
985     case NID_pkcs8ShroudedKeyBag:
986         if (options & INFO) {
987             const X509_SIG *tp8;
988             const X509_ALGOR *tp8alg;
989
990             BIO_printf(bio_err, "Shrouded Keybag: ");
991             tp8 = PKCS12_SAFEBAG_get0_pkcs8(bag);
992             X509_SIG_get0(tp8, &tp8alg, NULL);
993             alg_print(tp8alg);
994         }
995         if (options & NOKEYS)
996             return 1;
997         print_attribs(out, attrs, "Bag Attributes");
998         if ((p8 = PKCS12_decrypt_skey(bag, pass, passlen)) == NULL)
999             return 0;
1000         if ((pkey = EVP_PKCS82PKEY(p8)) == NULL) {
1001             PKCS8_PRIV_KEY_INFO_free(p8);
1002             return 0;
1003         }
1004         print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes");
1005         PKCS8_PRIV_KEY_INFO_free(p8);
1006         ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass);
1007         EVP_PKEY_free(pkey);
1008         break;
1009
1010     case NID_certBag:
1011         if (options & INFO)
1012             BIO_printf(bio_err, "Certificate bag\n");
1013         if (options & NOCERTS)
1014             return 1;
1015         if (PKCS12_SAFEBAG_get0_attr(bag, NID_localKeyID)) {
1016             if (options & CACERTS)
1017                 return 1;
1018         } else if (options & CLCERTS)
1019             return 1;
1020         print_attribs(out, attrs, "Bag Attributes");
1021         if (PKCS12_SAFEBAG_get_bag_nid(bag) != NID_x509Certificate)
1022             return 1;
1023         if ((x509 = PKCS12_SAFEBAG_get1_cert(bag)) == NULL)
1024             return 0;
1025         dump_cert_text(out, x509);
1026         ret = PEM_write_bio_X509(out, x509);
1027         X509_free(x509);
1028         break;
1029
1030     case NID_secretBag:
1031         if (options & INFO)
1032             BIO_printf(bio_err, "Secret bag\n");
1033         print_attribs(out, attrs, "Bag Attributes");
1034         BIO_printf(bio_err, "Bag Type: ");
1035         i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_bag_type(bag));
1036         BIO_printf(bio_err, "\nBag Value: ");
1037         print_attribute(out, PKCS12_SAFEBAG_get0_bag_obj(bag));
1038         return 1;
1039
1040     case NID_safeContentsBag:
1041         if (options & INFO)
1042             BIO_printf(bio_err, "Safe Contents bag\n");
1043         print_attribs(out, attrs, "Bag Attributes");
1044         return dump_certs_pkeys_bags(out, PKCS12_SAFEBAG_get0_safes(bag),
1045                                      pass, passlen, options, pempass, enc);
1046
1047     default:
1048         BIO_printf(bio_err, "Warning unsupported bag type: ");
1049         i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_type(bag));
1050         BIO_printf(bio_err, "\n");
1051         return 1;
1052     }
1053     return ret;
1054 }
1055
1056 /* Given a single certificate return a verified chain or NULL if error */
1057
1058 static int get_cert_chain(X509 *cert, X509_STORE *store,
1059                           STACK_OF(X509) *untrusted_certs,
1060                           STACK_OF(X509) **chain)
1061 {
1062     X509_STORE_CTX *store_ctx = NULL;
1063     STACK_OF(X509) *chn = NULL;
1064     int i = 0;
1065
1066     store_ctx = X509_STORE_CTX_new_ex(app_get0_libctx(), app_get0_propq());
1067     if (store_ctx == NULL) {
1068         i =  X509_V_ERR_UNSPECIFIED;
1069         goto end;
1070     }
1071     if (!X509_STORE_CTX_init(store_ctx, store, cert, untrusted_certs)) {
1072         i =  X509_V_ERR_UNSPECIFIED;
1073         goto end;
1074     }
1075
1076
1077     if (X509_verify_cert(store_ctx) > 0)
1078         chn = X509_STORE_CTX_get1_chain(store_ctx);
1079     else if ((i = X509_STORE_CTX_get_error(store_ctx)) == 0)
1080         i = X509_V_ERR_UNSPECIFIED;
1081
1082 end:
1083     X509_STORE_CTX_free(store_ctx);
1084     *chain = chn;
1085     return i;
1086 }
1087
1088 static int alg_print(const X509_ALGOR *alg)
1089 {
1090     int pbenid, aparamtype;
1091     const ASN1_OBJECT *aoid;
1092     const void *aparam;
1093     PBEPARAM *pbe = NULL;
1094
1095     X509_ALGOR_get0(&aoid, &aparamtype, &aparam, alg);
1096
1097     pbenid = OBJ_obj2nid(aoid);
1098
1099     BIO_printf(bio_err, "%s", OBJ_nid2ln(pbenid));
1100
1101     /*
1102      * If PBE algorithm is PBES2 decode algorithm parameters
1103      * for additional details.
1104      */
1105     if (pbenid == NID_pbes2) {
1106         PBE2PARAM *pbe2 = NULL;
1107         int encnid;
1108         if (aparamtype == V_ASN1_SEQUENCE)
1109             pbe2 = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBE2PARAM));
1110         if (pbe2 == NULL) {
1111             BIO_puts(bio_err, ", <unsupported parameters>");
1112             goto done;
1113         }
1114         X509_ALGOR_get0(&aoid, &aparamtype, &aparam, pbe2->keyfunc);
1115         pbenid = OBJ_obj2nid(aoid);
1116         X509_ALGOR_get0(&aoid, NULL, NULL, pbe2->encryption);
1117         encnid = OBJ_obj2nid(aoid);
1118         BIO_printf(bio_err, ", %s, %s", OBJ_nid2ln(pbenid),
1119                    OBJ_nid2sn(encnid));
1120         /* If KDF is PBKDF2 decode parameters */
1121         if (pbenid == NID_id_pbkdf2) {
1122             PBKDF2PARAM *kdf = NULL;
1123             int prfnid;
1124             if (aparamtype == V_ASN1_SEQUENCE)
1125                 kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBKDF2PARAM));
1126             if (kdf == NULL) {
1127                 BIO_puts(bio_err, ", <unsupported parameters>");
1128                 goto done;
1129             }
1130
1131             if (kdf->prf == NULL) {
1132                 prfnid = NID_hmacWithSHA1;
1133             } else {
1134                 X509_ALGOR_get0(&aoid, NULL, NULL, kdf->prf);
1135                 prfnid = OBJ_obj2nid(aoid);
1136             }
1137             BIO_printf(bio_err, ", Iteration %ld, PRF %s",
1138                        ASN1_INTEGER_get(kdf->iter), OBJ_nid2sn(prfnid));
1139             PBKDF2PARAM_free(kdf);
1140 #ifndef OPENSSL_NO_SCRYPT
1141         } else if (pbenid == NID_id_scrypt) {
1142             SCRYPT_PARAMS *kdf = NULL;
1143
1144             if (aparamtype == V_ASN1_SEQUENCE)
1145                 kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(SCRYPT_PARAMS));
1146             if (kdf == NULL) {
1147                 BIO_puts(bio_err, ", <unsupported parameters>");
1148                 goto done;
1149             }
1150             BIO_printf(bio_err, ", Salt length: %d, Cost(N): %ld, "
1151                        "Block size(r): %ld, Parallelism(p): %ld",
1152                        ASN1_STRING_length(kdf->salt),
1153                        ASN1_INTEGER_get(kdf->costParameter),
1154                        ASN1_INTEGER_get(kdf->blockSize),
1155                        ASN1_INTEGER_get(kdf->parallelizationParameter));
1156             SCRYPT_PARAMS_free(kdf);
1157 #endif
1158         }
1159         PBE2PARAM_free(pbe2);
1160     } else {
1161         if (aparamtype == V_ASN1_SEQUENCE)
1162             pbe = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBEPARAM));
1163         if (pbe == NULL) {
1164             BIO_puts(bio_err, ", <unsupported parameters>");
1165             goto done;
1166         }
1167         BIO_printf(bio_err, ", Iteration %ld", ASN1_INTEGER_get(pbe->iter));
1168         PBEPARAM_free(pbe);
1169     }
1170  done:
1171     BIO_puts(bio_err, "\n");
1172     return 1;
1173 }
1174
1175 /* Load all certificates from a given file */
1176
1177 int cert_load(BIO *in, STACK_OF(X509) *sk)
1178 {
1179     int ret = 0;
1180     X509 *cert;
1181
1182     while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
1183         ret = 1;
1184         if (!sk_X509_push(sk, cert))
1185             return 0;
1186     }
1187     if (ret)
1188         ERR_clear_error();
1189     return ret;
1190 }
1191
1192 /* Generalised x509 attribute value print */
1193
1194 void print_attribute(BIO *out, const ASN1_TYPE *av)
1195 {
1196     char *value;
1197     const char *ln;
1198     char objbuf[80];
1199
1200     switch (av->type) {
1201     case V_ASN1_BMPSTRING:
1202         value = OPENSSL_uni2asc(av->value.bmpstring->data,
1203                                 av->value.bmpstring->length);
1204         BIO_printf(out, "%s\n", value);
1205         OPENSSL_free(value);
1206         break;
1207
1208     case V_ASN1_UTF8STRING:
1209         BIO_printf(out, "%.*s\n", av->value.utf8string->length,
1210                    av->value.utf8string->data);
1211         break;
1212
1213     case V_ASN1_OCTET_STRING:
1214         hex_prin(out, av->value.octet_string->data,
1215                  av->value.octet_string->length);
1216         BIO_printf(out, "\n");
1217         break;
1218
1219     case V_ASN1_BIT_STRING:
1220         hex_prin(out, av->value.bit_string->data,
1221                  av->value.bit_string->length);
1222         BIO_printf(out, "\n");
1223         break;
1224
1225     case V_ASN1_OBJECT:
1226         ln = OBJ_nid2ln(OBJ_obj2nid(av->value.object));
1227         if (!ln)
1228             ln = "";
1229         OBJ_obj2txt(objbuf, sizeof(objbuf), av->value.object, 1);
1230         BIO_printf(out, "%s (%s)", ln, objbuf);
1231         BIO_printf(out, "\n");
1232         break;
1233
1234     default:
1235         BIO_printf(out, "<Unsupported tag %d>\n", av->type);
1236         break;
1237     }
1238 }
1239
1240 /* Generalised attribute print: handle PKCS#8 and bag attributes */
1241
1242 int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst,
1243                   const char *name)
1244 {
1245     X509_ATTRIBUTE *attr;
1246     ASN1_TYPE *av;
1247     int i, j, attr_nid;
1248     if (!attrlst) {
1249         BIO_printf(out, "%s: <No Attributes>\n", name);
1250         return 1;
1251     }
1252     if (!sk_X509_ATTRIBUTE_num(attrlst)) {
1253         BIO_printf(out, "%s: <Empty Attributes>\n", name);
1254         return 1;
1255     }
1256     BIO_printf(out, "%s\n", name);
1257     for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) {
1258         ASN1_OBJECT *attr_obj;
1259         attr = sk_X509_ATTRIBUTE_value(attrlst, i);
1260         attr_obj = X509_ATTRIBUTE_get0_object(attr);
1261         attr_nid = OBJ_obj2nid(attr_obj);
1262         BIO_printf(out, "    ");
1263         if (attr_nid == NID_undef) {
1264             i2a_ASN1_OBJECT(out, attr_obj);
1265             BIO_printf(out, ": ");
1266         } else {
1267             BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid));
1268         }
1269
1270         if (X509_ATTRIBUTE_count(attr)) {
1271             for (j = 0; j < X509_ATTRIBUTE_count(attr); j++)
1272             {
1273                 av = X509_ATTRIBUTE_get0_type(attr, j);
1274                 print_attribute(out, av);
1275             }
1276         } else {
1277             BIO_printf(out, "<No Values>\n");
1278         }
1279     }
1280     return 1;
1281 }
1282
1283 void hex_prin(BIO *out, unsigned char *buf, int len)
1284 {
1285     int i;
1286     for (i = 0; i < len; i++)
1287         BIO_printf(out, "%02X ", buf[i]);
1288 }
1289
1290 static int set_pbe(int *ppbe, const char *str)
1291 {
1292     if (!str)
1293         return 0;
1294     if (strcmp(str, "NONE") == 0) {
1295         *ppbe = -1;
1296         return 1;
1297     }
1298     *ppbe = OBJ_txt2nid(str);
1299     if (*ppbe == NID_undef) {
1300         BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str);
1301         return 0;
1302     }
1303     return 1;
1304 }