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