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