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