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