APPS/cmp: Simplify read_write_req_resp() - 'req' arg must not be NULL anyway
[openssl.git] / apps / pkcs12.c
index 60e12cf932d46e0fc9b90be6ad71f82b0222f80d..65dcdad38ac4d7207ea26aabd558454839273036 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the Apache License 2.0 (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -19,6 +19,7 @@
 #include <openssl/pem.h>
 #include <openssl/pkcs12.h>
 #include <openssl/provider.h>
+#include <openssl/kdf.h>
 
 #define NOKEYS          0x1
 #define NOCERTS         0x2
@@ -27,7 +28,6 @@
 #define CACERTS         0x10
 
 #define PASSWD_BUF_SIZE 2048
-#define PKCS12_DEFAULT_PBE NID_aes_256_cbc
 
 #define WARN_EXPORT(opt) \
     BIO_printf(bio_err, "Warning: -%s option ignored with -export\n", opt);
@@ -55,16 +55,22 @@ int cert_load(BIO *in, STACK_OF(X509) *sk);
 static int set_pbe(int *ppbe, const char *str);
 
 typedef enum OPTION_choice {
-    OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
+    OPT_COMMON,
     OPT_CIPHER, OPT_NOKEYS, OPT_KEYEX, OPT_KEYSIG, OPT_NOCERTS, OPT_CLCERTS,
     OPT_CACERTS, OPT_NOOUT, OPT_INFO, OPT_CHAIN, OPT_TWOPASS, OPT_NOMACVER,
-    OPT_DESCERT, OPT_EXPORT, OPT_ITER, OPT_NOITER, OPT_MACITER, OPT_NOMACITER,
+#ifndef OPENSSL_NO_DES
+    OPT_DESCERT,
+#endif
+    OPT_EXPORT, OPT_ITER, OPT_NOITER, OPT_MACITER, OPT_NOMACITER,
     OPT_NOMAC, OPT_LMK, OPT_NODES, OPT_NOENC, OPT_MACALG, OPT_CERTPBE, OPT_KEYPBE,
     OPT_INKEY, OPT_CERTFILE, OPT_UNTRUSTED, OPT_PASSCERTS,
     OPT_NAME, OPT_CSP, OPT_CANAME,
     OPT_IN, OPT_OUT, OPT_PASSIN, OPT_PASSOUT, OPT_PASSWORD, OPT_CAPATH,
     OPT_CAFILE, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_ENGINE,
-    OPT_R_ENUM, OPT_PROV_ENUM, OPT_LEGACY_ALG
+    OPT_R_ENUM, OPT_PROV_ENUM,
+#ifndef OPENSSL_NO_DES
+    OPT_LEGACY_ALG
+#endif
 } OPTION_CHOICE;
 
 const OPTIONS pkcs12_options[] = {
@@ -79,13 +85,15 @@ const OPTIONS pkcs12_options[] = {
     {"nokeys", OPT_NOKEYS, '-', "Don't output private keys"},
     {"nocerts", OPT_NOCERTS, '-', "Don't output certificates"},
     {"noout", OPT_NOOUT, '-', "Don't output anything, just verify PKCS#12 input"},
+#ifndef OPENSSL_NO_DES
     {"legacy", OPT_LEGACY_ALG, '-',
-#ifdef OPENSSL_NO_RC2
+# ifdef OPENSSL_NO_RC2
      "Use legacy encryption algorithm 3DES_CBC for keys and certs"
-#else
+# else
      "Use legacy encryption: 3DES_CBC for keys, RC2_CBC for certs"
-#endif
+# endif
     },
+#endif
 #ifndef OPENSSL_NO_ENGINE
     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
 #endif
@@ -108,7 +116,7 @@ const OPTIONS pkcs12_options[] = {
     {"passcerts", OPT_PASSCERTS, 's', "Certificate file pass phrase source"},
     {"chain", OPT_CHAIN, '-', "Build and add certificate chain for EE cert,"},
     {OPT_MORE_STR, 0, 0,
-     "which is the 1st cert from -in matching the privte key (if given)"},
+     "which is the 1st cert from -in matching the private key (if given)"},
     {"untrusted", OPT_UNTRUSTED, '<', "Untrusted certificates for chain building"},
     {"CAfile", OPT_CAFILE, '<', "PEM-format file of CA's"},
     {"CApath", OPT_CAPATH, '/', "PEM-format directory of CA's"},
@@ -130,8 +138,10 @@ const OPTIONS pkcs12_options[] = {
     {"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default AES-256 CBC)"},
     {"certpbe", OPT_CERTPBE, 's',
      "Certificate PBE algorithm (default PBES2 with PBKDF2 and AES-256 CBC)"},
+#ifndef OPENSSL_NO_DES
     {"descert", OPT_DESCERT, '-',
      "Encrypt output with 3DES (default PBES2 with PBKDF2 and AES-256 CBC)"},
+#endif
     {"macalg", OPT_MACALG, 's',
      "Digest algorithm to use in MAC (default SHA1)"},
     {"iter", OPT_ITER, 'p', "Specify the iteration count for encryption and MAC"},
@@ -145,14 +155,18 @@ const OPTIONS pkcs12_options[] = {
 int pkcs12_main(int argc, char **argv)
 {
     char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL;
-    char *untrusted = NULL;
+    char *untrusted = NULL, *ciphername = NULL, *enc_flag = NULL;
     char *passcertsarg = NULL, *passcerts = NULL;
     char *name = NULL, *csp_name = NULL;
     char pass[PASSWD_BUF_SIZE] = "", macpass[PASSWD_BUF_SIZE] = "";
-    int export_pkcs12 = 0, options = 0, chain = 0, twopass = 0, keytype = 0, use_legacy = 0;
-    int iter = PKCS12_DEFAULT_ITER, maciter = PKCS12_DEFAULT_ITER;
-    int cert_pbe = PKCS12_DEFAULT_PBE;
-    int key_pbe = PKCS12_DEFAULT_PBE;
+    int export_pkcs12 = 0, options = 0, chain = 0, twopass = 0, keytype = 0;
+#ifndef OPENSSL_NO_DES
+    int use_legacy = 0;
+#endif
+    /* use library defaults for the iter, maciter, cert, and key PBE */
+    int iter = 0, maciter = 0;
+    int cert_pbe = NID_undef;
+    int key_pbe = NID_undef;
     int ret = 1, macver = 1, add_lmk = 0, private = 0;
     int noprompt = 0;
     char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL;
@@ -164,9 +178,8 @@ int pkcs12_main(int argc, char **argv)
     BIO *in = NULL, *out = NULL;
     PKCS12 *p12 = NULL;
     STACK_OF(OPENSSL_STRING) *canames = NULL;
-    const char *enc_flag = NULL;
-    const EVP_CIPHER *const default_enc = EVP_aes_256_cbc();
-    const EVP_CIPHER *enc = default_enc;
+    EVP_CIPHER *default_enc = (EVP_CIPHER *)EVP_aes_256_cbc();
+    EVP_CIPHER *enc = (EVP_CIPHER *)default_enc;
     OPTION_CHOICE o;
 
     prog = opt_init(argc, argv, pkcs12_options);
@@ -214,21 +227,30 @@ int pkcs12_main(int argc, char **argv)
         case OPT_NOMACVER:
             macver = 0;
             break;
+#ifndef OPENSSL_NO_DES
         case OPT_DESCERT:
             cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
             break;
+#endif
         case OPT_EXPORT:
             export_pkcs12 = 1;
             break;
+        case OPT_NODES:
+        case OPT_NOENC:
+            /*
+             * |enc_flag| stores the name of the option used so it
+             * can be printed if an error message is output.
+             */
+            enc_flag = opt_flag() + 1;
+            enc = NULL;
+            ciphername = NULL;
+            break;
         case OPT_CIPHER:
+            ciphername = opt_unknown();
             enc_flag = opt_unknown();
-            if (!opt_cipher(enc_flag, &enc))
-                goto opthelp;
             break;
         case OPT_ITER:
-            if (!opt_int(opt_arg(), &iter))
-                goto opthelp;
-            maciter = iter;
+            maciter = iter = opt_int_arg();
             break;
         case OPT_NOITER:
             iter = 1;
@@ -246,11 +268,6 @@ int pkcs12_main(int argc, char **argv)
         case OPT_MACALG:
             macalg = opt_arg();
             break;
-        case OPT_NODES:
-        case OPT_NOENC:
-            enc_flag = opt_flag() + 1;
-            enc = NULL;
-            break;
         case OPT_CERTPBE:
             if (!set_pbe(&cert_pbe, opt_arg()))
                 goto opthelp;
@@ -326,9 +343,11 @@ int pkcs12_main(int argc, char **argv)
         case OPT_ENGINE:
             e = setup_engine(opt_arg(), 0);
             break;
+#ifndef OPENSSL_NO_DES
         case OPT_LEGACY_ALG:
             use_legacy = 1;
             break;
+#endif
         case OPT_PROV_CASES:
             if (!opt_provider(o))
                 goto end;
@@ -337,10 +356,14 @@ int pkcs12_main(int argc, char **argv)
     }
 
     /* No extra arguments. */
-    argc = opt_num_rest();
-    if (argc != 0)
+    if (!opt_check_rest_arg(NULL))
         goto opthelp;
 
+    if (!app_RAND_load())
+        goto end;
+
+    if (!opt_cipher_any(ciphername, &enc))
+        goto opthelp;
     if (export_pkcs12) {
         if ((options & INFO) != 0)
             WARN_EXPORT("info");
@@ -388,19 +411,20 @@ int pkcs12_main(int argc, char **argv)
             WARN_NO_EXPORT("keyex");
         if (keytype == KEY_SIG)
             WARN_NO_EXPORT("keysig");
-        if (key_pbe != PKCS12_DEFAULT_PBE)
+        if (key_pbe != NID_undef)
             WARN_NO_EXPORT("keypbe");
-        if (cert_pbe != PKCS12_DEFAULT_PBE && cert_pbe != -1)
+        if (cert_pbe != NID_undef && cert_pbe != -1)
             WARN_NO_EXPORT("certpbe and -descert");
         if (macalg != NULL)
             WARN_NO_EXPORT("macalg");
-        if (iter != PKCS12_DEFAULT_ITER)
+        if (iter != 0)
             WARN_NO_EXPORT("iter and -noiter");
         if (maciter == 1)
             WARN_NO_EXPORT("nomaciter");
         if (cert_pbe == -1 && maciter == -1)
             WARN_NO_EXPORT("nomac");
     }
+#ifndef OPENSSL_NO_DES
     if (use_legacy) {
         /* load the legacy provider if not loaded already*/
         if (!OSSL_PROVIDER_available(app_get0_libctx(), "legacy")) {
@@ -410,21 +434,23 @@ int pkcs12_main(int argc, char **argv)
             if (!app_provider_load(app_get0_libctx(), "default"))
                 goto end;
         }
-        if (cert_pbe == PKCS12_DEFAULT_PBE) {
+        if (cert_pbe == NID_undef) {
             /* Adapt default algorithm */
-#ifndef OPENSSL_NO_RC2
+# ifndef OPENSSL_NO_RC2
             cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
-#else
+# else
             cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
-#endif
+# endif
         }
 
-        if (key_pbe == PKCS12_DEFAULT_PBE)
+        if (key_pbe == NID_undef)
             key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
         if (enc == default_enc)
-            enc = EVP_des_ede3_cbc();
+            enc = (EVP_CIPHER *)EVP_des_ede3_cbc();
+        if (macalg == NULL)
+            macalg = "sha1";
     }
-
+#endif
 
     private = 1;
 
@@ -488,7 +514,7 @@ int pkcs12_main(int argc, char **argv)
         X509 *ee_cert = NULL, *x = NULL;
         STACK_OF(X509) *certs = NULL;
         STACK_OF(X509) *untrusted_certs = NULL;
-        const EVP_MD *macmd = NULL;
+        EVP_MD *macmd = NULL;
         unsigned char *catmp = NULL;
         int i;
 
@@ -514,7 +540,7 @@ int pkcs12_main(int argc, char **argv)
 
         /* Load all certs in input file */
         if (!(options & NOCERTS)) {
-            if (!load_certs(infile, &certs, passin,
+            if (!load_certs(infile, 1, &certs, passin,
                             "certificates from -in file"))
                 goto export_end;
             if (sk_X509_num(certs) < 1) {
@@ -526,7 +552,7 @@ int pkcs12_main(int argc, char **argv)
                 /* Look for matching private key */
                 for (i = 0; i < sk_X509_num(certs); i++) {
                     x = sk_X509_value(certs, i);
-                    if (X509_check_private_key(x, key)) {
+                    if (cert_matches_key(x, key)) {
                         ee_cert = x;
                         /* Zero keyid and alias */
                         X509_keyid_set1(ee_cert, NULL, 0);
@@ -542,14 +568,12 @@ int pkcs12_main(int argc, char **argv)
                                infile);
                     goto export_end;
                 }
-            } else {
-                ee_cert = X509_dup(sk_X509_value(certs, 0)); /* take 1st cert */
             }
         }
 
         /* Load any untrusted certificates for chain building */
         if (untrusted != NULL) {
-            if (!load_certs(untrusted, &untrusted_certs, passcerts,
+            if (!load_certs(untrusted, 0, &untrusted_certs, passcerts,
                             "untrusted certificates"))
                 goto export_end;
         }
@@ -559,8 +583,13 @@ int pkcs12_main(int argc, char **argv)
             int vret;
             STACK_OF(X509) *chain2;
             X509_STORE *store;
+            X509 *ee_cert_tmp = ee_cert;
+
+            /* Assume the first cert if we haven't got anything else */
+            if (ee_cert_tmp == NULL && certs != NULL)
+                ee_cert_tmp = sk_X509_value(certs, 0);
 
-            if (ee_cert == NULL) {
+            if (ee_cert_tmp == NULL) {
                 BIO_printf(bio_err,
                            "No end entity certificate to check with -chain\n");
                 goto export_end;
@@ -571,7 +600,7 @@ int pkcs12_main(int argc, char **argv)
                     == NULL)
                 goto export_end;
 
-            vret = get_cert_chain(ee_cert, store, untrusted_certs, &chain2);
+            vret = get_cert_chain(ee_cert_tmp, store, untrusted_certs, &chain2);
             X509_STORE_free(store);
 
             if (vret == X509_V_OK) {
@@ -594,7 +623,7 @@ int pkcs12_main(int argc, char **argv)
 
         /* Add any extra certificates asked for */
         if (certfile != NULL) {
-            if (!load_certs(certfile, &certs, passcerts,
+            if (!load_certs(certfile, 0, &certs, passcerts,
                             "extra certificates from -certfile"))
                 goto export_end;
         }
@@ -632,8 +661,9 @@ int pkcs12_main(int argc, char **argv)
         if (!twopass)
             OPENSSL_strlcpy(macpass, pass, sizeof(macpass));
 
-        p12 = PKCS12_create(cpass, name, key, ee_cert, certs,
-                            key_pbe, cert_pbe, iter, -1, keytype);
+        p12 = PKCS12_create_ex(cpass, name, key, ee_cert, certs,
+                               key_pbe, cert_pbe, iter, -1, keytype,
+                               app_get0_libctx(), app_get0_propq());
 
         if (p12 == NULL) {
             BIO_printf(bio_err, "Error creating PKCS12 structure for %s\n",
@@ -647,7 +677,11 @@ int pkcs12_main(int argc, char **argv)
         }
 
         if (maciter != -1)
-            PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd);
+            if (!PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd)) {
+                BIO_printf(bio_err, "Error creating PKCS12 MAC; no PKCS12KDF support?\n");
+                BIO_printf(bio_err, "Use -nomac if MAC not required and PKCS12KDF support not available.\n");
+                goto export_end;
+            }
 
         assert(private);
 
@@ -662,6 +696,7 @@ int pkcs12_main(int argc, char **argv)
  export_end:
 
         EVP_PKEY_free(key);
+        EVP_MD_free(macmd);
         sk_X509_pop_free(certs, X509_free);
         sk_X509_pop_free(untrusted_certs, X509_free);
         X509_free(ee_cert);
@@ -678,7 +713,12 @@ int pkcs12_main(int argc, char **argv)
     if (out == NULL)
         goto end;
 
-    if ((p12 = d2i_PKCS12_bio(in, NULL)) == NULL) {
+    p12 = PKCS12_init_ex(NID_pkcs7_data, app_get0_libctx(), app_get0_propq());
+    if (p12 == NULL) {
+        ERR_print_errors(bio_err);
+        goto end;
+    }
+    if ((p12 = d2i_PKCS12_bio(in, &p12)) == NULL) {
         ERR_print_errors(bio_err);
         goto end;
     }
@@ -721,6 +761,16 @@ int pkcs12_main(int argc, char **argv)
                    tsalt != NULL ? ASN1_STRING_length(tsalt) : 0L);
     }
     if (macver) {
+        EVP_KDF *pkcs12kdf;
+
+        pkcs12kdf = EVP_KDF_fetch(app_get0_libctx(), "PKCS12KDF",
+                                  app_get0_propq());
+        if (pkcs12kdf == NULL) {
+            BIO_printf(bio_err, "Error verifying PKCS12 MAC; no PKCS12KDF support.\n");
+            BIO_printf(bio_err, "Use -nomacver if MAC verification is not required.\n");
+            goto end;
+        }
+        EVP_KDF_free(pkcs12kdf);
         /* If we enter empty password try no password first */
         if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
             /* If mac and crypto pass the same set it to NULL too */
@@ -734,6 +784,14 @@ int pkcs12_main(int argc, char **argv)
              */
             unsigned char *utmp;
             int utmplen;
+            unsigned long err = ERR_peek_error();
+
+            if (ERR_GET_LIB(err) == ERR_LIB_PKCS12
+                && ERR_GET_REASON(err) == PKCS12_R_MAC_ABSENT) {
+                BIO_printf(bio_err, "Warning: MAC is absent!\n");
+                goto dump;
+            }
+
             utmp = OPENSSL_asc2uni(mpass, -1, NULL, &utmplen);
             if (utmp == NULL)
                 goto end;
@@ -751,6 +809,7 @@ int pkcs12_main(int argc, char **argv)
         }
     }
 
+ dump:
     assert(private);
     if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) {
         BIO_printf(bio_err, "Error outputting keys and certificates\n");
@@ -904,7 +963,7 @@ int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bag,
         break;
 
     case NID_secretBag:
-        if (options & INFO) 
+        if (options & INFO)
             BIO_printf(bio_err, "Secret bag\n");
         print_attribs(out, attrs, "Bag Attributes");
         BIO_printf(bio_err, "Bag Type: ");
@@ -1080,7 +1139,8 @@ void print_attribute(BIO *out, const ASN1_TYPE *av)
         break;
 
     case V_ASN1_UTF8STRING:
-        BIO_printf(out, "%s\n", av->value.utf8string->data);
+        BIO_printf(out, "%.*s\n", av->value.utf8string->length,
+                   av->value.utf8string->data);
         break;
 
     case V_ASN1_OCTET_STRING: