From c29df535eea63765e6a0fa91da4a736595fe9898 Mon Sep 17 00:00:00 2001
From: Gilles Peskine <Gilles.Peskine@arm.com>
Date: Mon, 2 Oct 2023 14:59:26 +0200
Subject: [PATCH] Improve robustness of ECDH public key length validation

In client-side code with MBEDTLS_USE_PSA_CRYPTO, use the buffer size to
validate what is written in handshake->xxdh_psa_peerkey. The previous code
was correct, but a little fragile to misconfiguration or maintenance.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
---
 library/ssl_tls12_client.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/library/ssl_tls12_client.c b/library/ssl_tls12_client.c
index cc22a3fe1..02f6cd369 100644
--- a/library/ssl_tls12_client.c
+++ b/library/ssl_tls12_client.c
@@ -1779,7 +1779,7 @@ static int ssl_parse_server_ecdh_params(mbedtls_ssl_context *ssl,
         return MBEDTLS_ERR_SSL_DECODE_ERROR;
     }
 
-    if (ecpoint_len > PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS)) {
+    if (ecpoint_len > sizeof(handshake->xxdh_psa_peerkey)) {
         return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
     }
 
@@ -2059,7 +2059,7 @@ static int ssl_get_ecdh_params_from_cert(mbedtls_ssl_context *ssl)
     ret = mbedtls_ecp_point_write_binary(&peer_key->grp, &peer_key->Q,
                                          MBEDTLS_ECP_PF_UNCOMPRESSED, &olen,
                                          ssl->handshake->xxdh_psa_peerkey,
-                                         MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH);
+                                         sizeof(ssl->handshake->xxdh_psa_peerkey));
 
     if (ret != 0) {
         MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ecp_point_write_binary"), ret);