From 1c763e29d138db87665e98983f468d2dd0f286c1 Mon Sep 17 00:00:00 2001
From: Jakub Jelen <jjelen@redhat.com>
Date: Wed, 6 Aug 2025 15:32:56 +0200
Subject: [PATCH 3/3] CVE-2025-8277: mbedtls: Avoid leaking ecdh keys

Signed-off-by: Jakub Jelen <jjelen@redhat.com>
Reviewed-by: Andreas Schneider <asn@cryptomilk.org>
(cherry picked from commit ffed80f8c078122990a4eba2b275facd56dd43e0)

CVE: CVE-2025-8277

Upstream-Status: Backport [https://git.libssh.org/projects/libssh.git/commit/?h=stable-0.11&id=1c763e29d138db87665e98983f468d2dd0f286c1]

Signed-off-by: Rajeshkumar Ramasamy <rajeshkumar.ramasamy@windriver.com>
---
 src/ecdh_mbedcrypto.c | 1 +
 src/wrapper.c         | 5 ++++-
 2 files changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/ecdh_mbedcrypto.c b/src/ecdh_mbedcrypto.c
index f7b0301b..ab323a7e 100644
--- a/src/ecdh_mbedcrypto.c
+++ b/src/ecdh_mbedcrypto.c
@@ -109,6 +109,7 @@ int ssh_client_ecdh_init(ssh_session session)
         goto out;
     }
 
+    SSH_STRING_FREE(session->next_crypto->ecdh_client_pubkey);
     session->next_crypto->ecdh_client_pubkey = client_pubkey;
     client_pubkey = NULL;
 
diff --git a/src/wrapper.c b/src/wrapper.c
index 6e15d54e..fc1110f4 100644
--- a/src/wrapper.c
+++ b/src/wrapper.c
@@ -169,7 +169,10 @@ void crypto_free(struct ssh_crypto_struct *crypto)
         EC_KEY_free(crypto->ecdh_privkey);
 #elif defined HAVE_GCRYPT_ECC
         gcry_sexp_release(crypto->ecdh_privkey);
-#endif
+#elif defined HAVE_LIBMBEDCRYPTO
+        mbedtls_ecp_keypair_free(crypto->ecdh_privkey);
+        SAFE_FREE(crypto->ecdh_privkey);
+#endif /* HAVE_LIBGCRYPT */
         crypto->ecdh_privkey = NULL;
     }
 #endif
-- 
2.48.1

