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