ECDH: test calc_secret output buffer too small

Signed-off-by: Manuel Pégourié-Gonnard <manuel.pegourie-gonnard@arm.com>
This commit is contained in:
Manuel Pégourié-Gonnard 2026-03-26 12:00:37 +01:00
parent df13f5cd52
commit 0d318a0f3a

View File

@ -374,7 +374,8 @@ void ecdh_exchange_calc_secret(int grp_id,
mbedtls_ecp_keypair our_key;
mbedtls_ecp_keypair their_key;
mbedtls_ecdh_context ecdh;
unsigned char shared_secret[MBEDTLS_ECP_MAX_BYTES];
unsigned char *buf = NULL;
size_t min_buf_size = 0;
size_t shared_secret_length = 0;
memset(&rnd_info, 0x00, sizeof(mbedtls_test_rnd_pseudo_info));
@ -402,17 +403,48 @@ void ecdh_exchange_calc_secret(int grp_id,
&ecdh, &our_key, MBEDTLS_ECDH_OURS) == 0);
}
/* Perform the ECDH calculation. */
TEST_ASSERT(mbedtls_ecdh_calc_secret(
&ecdh,
&shared_secret_length,
shared_secret, sizeof(shared_secret),
&mbedtls_test_rnd_pseudo_rand, &rnd_info) == 0);
TEST_ASSERT(shared_secret_length == expected->len);
TEST_ASSERT(memcmp(expected->x, shared_secret,
shared_secret_length) == 0);
/* Compute minimal size of output buffer */
min_buf_size = (our_key.grp.pbits + 7) / 8;
TEST_LE_U(min_buf_size, MBEDTLS_ECP_MAX_BYTES);
/* Perform the ECDH calculation with exact size output buffer */
TEST_CALLOC(buf, min_buf_size);
TEST_EQUAL(0,
mbedtls_ecdh_calc_secret(
&ecdh, &shared_secret_length,
buf, min_buf_size,
&mbedtls_test_rnd_pseudo_rand, &rnd_info));
TEST_MEMORY_COMPARE(expected->x, expected->len,
buf, shared_secret_length);
mbedtls_free(buf);
buf = NULL;
shared_secret_length = 0;
/* Try again with an output buffer that's larger. */
TEST_CALLOC(buf, min_buf_size + 1);
TEST_EQUAL(0,
mbedtls_ecdh_calc_secret(
&ecdh, &shared_secret_length,
buf, min_buf_size + 1,
&mbedtls_test_rnd_pseudo_rand, &rnd_info));
TEST_MEMORY_COMPARE(expected->x, expected->len,
buf, shared_secret_length);
mbedtls_free(buf);
buf = NULL;
shared_secret_length = 0;
/* Try again with an output buffer that's too short. */
TEST_CALLOC(buf, min_buf_size - 1);
TEST_EQUAL(MBEDTLS_ERR_ECP_BAD_INPUT_DATA,
mbedtls_ecdh_calc_secret(
&ecdh, &shared_secret_length,
buf, min_buf_size - 1,
&mbedtls_test_rnd_pseudo_rand, &rnd_info));
exit:
mbedtls_free(buf);
mbedtls_ecdh_free(&ecdh);
mbedtls_ecp_keypair_free(&our_key);
mbedtls_ecp_keypair_free(&their_key);