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