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