Ensure pkey_set_type handles ENGINE references correctly
authorMatt Caswell <matt@openssl.org>
Fri, 15 Oct 2021 15:23:31 +0000 (16:23 +0100)
committerMatt Caswell <matt@openssl.org>
Tue, 19 Oct 2021 15:20:00 +0000 (16:20 +0100)
pkey_set_type should not consume the ENGINE references that may be
passed to it.

Fixes #16757

Reviewed-by: Tomas Mraz <tomas@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/16846)

crypto/evp/p_lib.c

index 61cfe1efb9558b2554b7b94e2b7daa0e9af1abc3..aabd92d555942760965aa52ac938c5970c9e7b6e 100644 (file)
@@ -1554,7 +1554,6 @@ static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
          */
         if (keymgmt == NULL)
             pkey->ameth = ameth;
-        pkey->engine = e;
 
         /*
          * The EVP_PKEY_ASN1_METHOD |pkey_id| retains its legacy key purpose
@@ -1570,6 +1569,13 @@ static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
         } else {
             pkey->type = EVP_PKEY_KEYMGMT;
         }
+# ifndef OPENSSL_NO_ENGINE
+        if (eptr == NULL && e != NULL && !ENGINE_init(e)) {
+            ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
+            return 0;
+        }
+# endif
+        pkey->engine = e;
 #endif
     }
     return 1;