fix(bt): Check the peer ECDH public key when using mbedtls

This commit is contained in:
liqigan
2026-08-18 15:05:54 +08:00
parent e719129476
commit 8dc1fd60aa

View File

@@ -295,6 +295,41 @@ static int bredr_psa_gen_keypair(bool p256, uint8_t *public_key, uint8_t *privat
return 0;
}
/*
* CVE-2018-5383: validate the peer's public key is a valid point on the curve
* before using it in the DH computation. PSA validates the point (rejects the
* point at infinity and out-of-range coordinates) when importing it as a public key.
*/
static int bredr_psa_validate_peer_pubkey(bool p256, const uint8_t *peer_pub_key_x, const uint8_t *peer_pub_key_y)
{
const size_t coord_len = p256 ? BREDR_P256_COORD_LEN : BREDR_P192_COORD_LEN;
const size_t pub_len = p256 ? BREDR_PUB_KEY_LEN_P256 : BREDR_PUB_KEY_LEN_P192;
uint8_t pk[BREDR_PUB_KEY_LEN_P256]; /* uncompressed: 0x04 || X || Y */
pk[0] = 0x04;
btdm_swap_buf(&pk[1], peer_pub_key_x, coord_len);
btdm_swap_buf(&pk[1 + coord_len], peer_pub_key_y, coord_len);
psa_key_attributes_t pub_attr = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t pub_key_id = 0;
psa_status_t pub_status;
psa_set_key_type(&pub_attr, PSA_KEY_TYPE_ECC_PUBLIC_KEY(PSA_ECC_FAMILY_SECP_R1));
psa_set_key_bits(&pub_attr, p256 ? 256 : 192);
psa_set_key_usage_flags(&pub_attr, 0);
pub_status = psa_import_key(&pub_attr, pk, pub_len, &pub_key_id);
psa_reset_key_attributes(&pub_attr);
if (pub_status != PSA_SUCCESS) {
ESP_LOGE(TAG_BREDR_CRYPTO, "invalid peer public key: psa_import_key failed: %d", (int)pub_status);
return -1;
}
psa_destroy_key(pub_key_id);
return 0;
}
static int bredr_psa_gen_dhkey(bool p256, const uint8_t *peer_pub_key_x, const uint8_t *peer_pub_key_y,
const uint8_t *our_priv_key, uint8_t *out_dhkey)
{
@@ -306,11 +341,18 @@ static int bredr_psa_gen_dhkey(bool p256, const uint8_t *peer_pub_key_x, const u
uint8_t pk[65];
uint8_t dh[32];
btdm_swap_buf(priv, our_priv_key, priv_len);
/* Validate the peer's public key before using it in the DH computation. */
if (bredr_psa_validate_peer_pubkey(p256, peer_pub_key_x, peer_pub_key_y) != 0) {
return -1;
}
/* Reconstruct the peer public key in uncompressed form (0x04 || X || Y). */
pk[0] = 0x04;
btdm_swap_buf(&pk[1], peer_pub_key_x, coord_len);
btdm_swap_buf(&pk[1 + coord_len], peer_pub_key_y, coord_len);
btdm_swap_buf(priv, our_priv_key, priv_len);
psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key_id = 0;
psa_status_t status;