From a2ec44f21cb7149881a7d2ec865bfe4822a0855a Mon Sep 17 00:00:00 2001
From: tb <>
Date: Thu, 28 Dec 2023 22:06:41 +0000
Subject: Rework pkey_dh_keygen()

Single exit, fix error checking and hold on to the DH by keeping a
reference. In other words, switch from EVP_PKEY_assign() to using
EVP_PKEY_set1_DH() and free unconditionally in the error path.

ok jsing
---
 src/lib/libcrypto/dh/dh_pmeth.c | 28 +++++++++++++++++++---------
 1 file changed, 19 insertions(+), 9 deletions(-)

(limited to 'src/lib')

diff --git a/src/lib/libcrypto/dh/dh_pmeth.c b/src/lib/libcrypto/dh/dh_pmeth.c
index 7a598da27b..5a43acceff 100644
--- a/src/lib/libcrypto/dh/dh_pmeth.c
+++ b/src/lib/libcrypto/dh/dh_pmeth.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: dh_pmeth.c,v 1.13 2022/11/26 16:08:51 tb Exp $ */
+/* $OpenBSD: dh_pmeth.c,v 1.14 2023/12/28 22:06:41 tb Exp $ */
 /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
  * project 2006.
  */
@@ -215,19 +215,29 @@ static int
 pkey_dh_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
 {
 	DH *dh = NULL;
+	int ret = 0;
 
 	if (ctx->pkey == NULL) {
 		DHerror(DH_R_NO_PARAMETERS_SET);
-		return 0;
+		goto err;
 	}
-	dh = DH_new();
-	if (!dh)
-		return 0;
-	EVP_PKEY_assign_DH(pkey, dh);
-	/* Note: if error return, pkey is freed by parent routine */
+
+	if ((dh = DH_new()) == NULL)
+		goto err;
+	if (!EVP_PKEY_set1_DH(pkey, dh))
+		goto err;
+
 	if (!EVP_PKEY_copy_parameters(pkey, ctx->pkey))
-		return 0;
-	return DH_generate_key(pkey->pkey.dh);
+		goto err;
+	if (!DH_generate_key(dh))
+		goto err;
+
+	ret = 1;
+
+ err:
+	DH_free(dh);
+
+	return ret;
 }
 
 static int
-- 
cgit v1.2.3-55-g6feb