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