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