feat(bt): migrate mbedtls to PSA APIs

This commit is contained in:
Ashish Sharma
2025-12-18 21:18:58 +08:00
parent b4fea9cccc
commit b0da66f7e1
38 changed files with 986 additions and 790 deletions
+46 -94
View File
@@ -1444,16 +1444,10 @@ uint8_t esp_ble_get_chip_rev_version(void)
#if CONFIG_BT_LE_SM_LEGACY || CONFIG_BT_LE_SM_SC #if CONFIG_BT_LE_SM_LEGACY || CONFIG_BT_LE_SM_SC
#define BLE_SM_KEY_ERR 0x17 #define BLE_SM_KEY_ERR 0x17
#if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
#include "mbedtls/aes.h"
#if CONFIG_BT_LE_SM_SC #if CONFIG_BT_LE_SM_SC
#include "mbedtls/cipher.h" #include "psa/crypto.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/cmac.h"
#include "mbedtls/ecdh.h"
#include "mbedtls/ecp.h"
static mbedtls_ecp_keypair keypair; #define BLE_PUB_KEY_LEN 65
#endif // CONFIG_BT_LE_SM_SC #endif // CONFIG_BT_LE_SM_SC
#else #else
@@ -1499,78 +1493,40 @@ int ble_sm_alg_gen_dhkey(const uint8_t *peer_pub_key_x, const uint8_t *peer_pub_
const uint8_t *our_priv_key, uint8_t *out_dhkey) const uint8_t *our_priv_key, uint8_t *out_dhkey)
{ {
uint8_t dh[32]; uint8_t dh[32];
uint8_t pk[64]; uint8_t pk[BLE_PUB_KEY_LEN];
uint8_t priv[32]; uint8_t priv[32];
int rc = BLE_SM_KEY_ERR; int rc = BLE_SM_KEY_ERR;
swap_buf(pk, peer_pub_key_x, 32); pk[0] = 0x04; // Uncompressed format for public key
swap_buf(&pk[32], peer_pub_key_y, 32); swap_buf(&pk[1], peer_pub_key_x, 32);
swap_buf(&pk[33], peer_pub_key_y, 32);
swap_buf(priv, our_priv_key, 32); swap_buf(priv, our_priv_key, 32);
#if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
struct mbedtls_ecp_point pt = {0}, Q = {0}; psa_key_id_t key_id = 0;
mbedtls_mpi z = {0}, d = {0}; psa_status_t status;
mbedtls_ctr_drbg_context ctr_drbg = {0}; psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
mbedtls_entropy_context entropy = {0}; psa_set_key_type(&key_attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1));
psa_set_key_bits(&key_attributes, 256);
uint8_t pub[65] = {0}; psa_set_key_algorithm(&key_attributes, PSA_ALG_ECDH);
/* Hardcoded first byte of pub key for MBEDTLS_ECP_PF_UNCOMPRESSED */ psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
pub[0] = 0x04; status = psa_import_key(&key_attributes, priv, 32, &key_id);
memcpy(&pub[1], pk, 64); if (status != PSA_SUCCESS) {
goto exit;
/* Initialize the required structures here */ }
mbedtls_ecp_point_init(&pt); psa_reset_key_attributes(&key_attributes);
mbedtls_ecp_point_init(&Q); size_t output_len = 0;
mbedtls_ctr_drbg_init(&ctr_drbg); status = psa_raw_key_agreement(PSA_ALG_ECDH, key_id, pk, BLE_PUB_KEY_LEN, dh, sizeof(dh), &output_len);
mbedtls_entropy_init(&entropy); if (status != PSA_SUCCESS) {
mbedtls_mpi_init(&d);
mbedtls_mpi_init(&z);
/* Below 3 steps are to validate public key on curve secp256r1 */
if (mbedtls_ecp_group_load(&keypair.MBEDTLS_PRIVATE(grp), MBEDTLS_ECP_DP_SECP256R1) != 0) {
goto exit; goto exit;
} }
if (mbedtls_ecp_point_read_binary(&keypair.MBEDTLS_PRIVATE(grp), &pt, pub, 65) != 0) { if (output_len != 32) {
goto exit;
}
if (mbedtls_ecp_check_pubkey(&keypair.MBEDTLS_PRIVATE(grp), &pt) != 0) {
goto exit;
}
/* Set PRNG */
if ((rc = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0)) != 0) {
goto exit;
}
/* Prepare point Q from pub key */
if (mbedtls_ecp_point_read_binary(&keypair.MBEDTLS_PRIVATE(grp), &Q, pub, 65) != 0) {
goto exit;
}
if (mbedtls_mpi_read_binary(&d, priv, 32) != 0) {
goto exit;
}
rc = mbedtls_ecdh_compute_shared(&keypair.MBEDTLS_PRIVATE(grp), &z, &Q, &d,
mbedtls_ctr_drbg_random, &ctr_drbg);
if (rc != 0) {
goto exit;
}
rc = mbedtls_mpi_write_binary(&z, dh, 32);
if (rc != 0) {
goto exit; goto exit;
} }
rc = 0;
exit: exit:
mbedtls_ecp_point_free(&pt);
mbedtls_mpi_free(&z);
mbedtls_mpi_free(&d);
mbedtls_ecp_point_free(&Q);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
if (rc != 0) { if (rc != 0) {
return BLE_SM_KEY_ERR; return BLE_SM_KEY_ERR;
} }
@@ -1594,42 +1550,38 @@ exit:
static int mbedtls_gen_keypair(uint8_t *public_key, uint8_t *private_key) static int mbedtls_gen_keypair(uint8_t *public_key, uint8_t *private_key)
{ {
int rc = BLE_SM_KEY_ERR; int rc = BLE_SM_KEY_ERR;
mbedtls_entropy_context entropy = {0}; psa_status_t status;
mbedtls_ctr_drbg_context ctr_drbg = {0}; psa_key_id_t key_id = 0;
psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_algorithm_t alg = PSA_ALG_ECDH;
psa_key_type_t key_type = PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1);
psa_key_usage_t key_usage = PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT;
mbedtls_entropy_init(&entropy); psa_set_key_type(&key_attributes, key_type);
mbedtls_ctr_drbg_init(&ctr_drbg); psa_set_key_bits(&key_attributes, 256);
mbedtls_ecp_keypair_init(&keypair); psa_set_key_algorithm(&key_attributes, alg);
psa_set_key_usage_flags(&key_attributes, key_usage);
if ((rc = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, status = psa_generate_key(&key_attributes, &key_id);
NULL, 0)) != 0) { if (status != PSA_SUCCESS) {
goto exit;
}
if ((rc = mbedtls_ecp_gen_key(MBEDTLS_ECP_DP_SECP256R1, &keypair,
mbedtls_ctr_drbg_random, &ctr_drbg)) != 0) {
goto exit;
}
if ((rc = mbedtls_mpi_write_binary(&keypair.MBEDTLS_PRIVATE(d), private_key, 32)) != 0) {
goto exit; goto exit;
} }
psa_reset_key_attributes(&key_attributes);
size_t olen = 0; size_t olen = 0;
uint8_t pub[65] = {0}; status = psa_export_public_key(key_id, public_key, 65, &olen);
if (status != PSA_SUCCESS || olen != 65) {
if ((rc = mbedtls_ecp_point_write_binary(&keypair.MBEDTLS_PRIVATE(grp), &keypair.MBEDTLS_PRIVATE(Q), MBEDTLS_ECP_PF_UNCOMPRESSED,
&olen, pub, 65)) != 0) {
goto exit; goto exit;
} }
memcpy(public_key, &pub[1], 64); status = psa_export_key(key_id, private_key, 32, &olen);
if (status != PSA_SUCCESS || olen != 32) {
goto exit;
}
psa_destroy_key(key_id);
rc = 0;
exit: exit:
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
if (rc != 0) { if (rc != 0) {
mbedtls_ecp_keypair_free(&keypair);
return BLE_SM_KEY_ERR; return BLE_SM_KEY_ERR;
} }
@@ -1663,8 +1615,8 @@ int ble_sm_alg_gen_key_pair(uint8_t *pub, uint8_t *priv)
/* Make sure generated key isn't debug key. */ /* Make sure generated key isn't debug key. */
} while (memcmp(priv, ble_sm_alg_dbg_priv_key, 32) == 0); } while (memcmp(priv, ble_sm_alg_dbg_priv_key, 32) == 0);
swap_buf(pub, pk, 32); swap_buf(pub, &pk[1], 32);
swap_buf(&pub[32], &pk[32], 32); swap_buf(&pub[32], &pk[33], 32);
swap_in_place(priv, 32); swap_in_place(priv, 32);
#endif // CONFIG_BT_LE_SM_SC_DEBUG_KEYS #endif // CONFIG_BT_LE_SM_SC_DEBUG_KEYS
return 0; return 0;
+47 -95
View File
@@ -1586,16 +1586,10 @@ void esp_ble_controller_log_dump_all(bool output)
#if CONFIG_BT_LE_SM_LEGACY || CONFIG_BT_LE_SM_SC #if CONFIG_BT_LE_SM_LEGACY || CONFIG_BT_LE_SM_SC
#define BLE_SM_KEY_ERR 0x17 #define BLE_SM_KEY_ERR 0x17
#if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
#include "mbedtls/aes.h"
#if CONFIG_BT_LE_SM_SC #if CONFIG_BT_LE_SM_SC
#include "mbedtls/cipher.h" #include "psa/crypto.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/cmac.h"
#include "mbedtls/ecdh.h"
#include "mbedtls/ecp.h"
static mbedtls_ecp_keypair keypair; #define BLE_PUB_KEY_LEN 65
#endif // CONFIG_BT_LE_SM_SC #endif // CONFIG_BT_LE_SM_SC
#else #else
@@ -1640,78 +1634,40 @@ int ble_sm_alg_gen_dhkey(const uint8_t *peer_pub_key_x, const uint8_t *peer_pub_
const uint8_t *our_priv_key, uint8_t *out_dhkey) const uint8_t *our_priv_key, uint8_t *out_dhkey)
{ {
uint8_t dh[32]; uint8_t dh[32];
uint8_t pk[64]; uint8_t pk[BLE_PUB_KEY_LEN];
uint8_t priv[32]; uint8_t priv[32];
int rc = BLE_SM_KEY_ERR; int rc = BLE_SM_KEY_ERR;
swap_buf(pk, peer_pub_key_x, 32); pk[0] = 0x04; // Uncompressed format for public key
swap_buf(&pk[32], peer_pub_key_y, 32); swap_buf(&pk[1], peer_pub_key_x, 32);
swap_buf(&pk[33], peer_pub_key_y, 32);
swap_buf(priv, our_priv_key, 32); swap_buf(priv, our_priv_key, 32);
#if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
struct mbedtls_ecp_point pt = {0}, Q = {0}; psa_key_id_t key_id = 0;
mbedtls_mpi z = {0}, d = {0}; psa_status_t status;
mbedtls_ctr_drbg_context ctr_drbg = {0}; psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
mbedtls_entropy_context entropy = {0}; psa_set_key_type(&key_attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1));
psa_set_key_bits(&key_attributes, 256);
uint8_t pub[65] = {0}; psa_set_key_algorithm(&key_attributes, PSA_ALG_ECDH);
/* Hardcoded first byte of pub key for MBEDTLS_ECP_PF_UNCOMPRESSED */ psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
pub[0] = 0x04; status = psa_import_key(&key_attributes, priv, 32, &key_id);
memcpy(&pub[1], pk, 64); if (status != PSA_SUCCESS) {
goto exit;
/* Initialize the required structures here */ }
mbedtls_ecp_point_init(&pt); psa_reset_key_attributes(&key_attributes);
mbedtls_ecp_point_init(&Q); size_t output_len = 0;
mbedtls_ctr_drbg_init(&ctr_drbg); status = psa_raw_key_agreement(PSA_ALG_ECDH, key_id, pk, BLE_PUB_KEY_LEN, dh, sizeof(dh), &output_len);
mbedtls_entropy_init(&entropy); if (status != PSA_SUCCESS) {
mbedtls_mpi_init(&d);
mbedtls_mpi_init(&z);
/* Below 3 steps are to validate public key on curve secp256r1 */
if (mbedtls_ecp_group_load(&keypair.MBEDTLS_PRIVATE(grp), MBEDTLS_ECP_DP_SECP256R1) != 0) {
goto exit; goto exit;
} }
if (mbedtls_ecp_point_read_binary(&keypair.MBEDTLS_PRIVATE(grp), &pt, pub, 65) != 0) { if (output_len != 32) {
goto exit;
}
if (mbedtls_ecp_check_pubkey(&keypair.MBEDTLS_PRIVATE(grp), &pt) != 0) {
goto exit;
}
/* Set PRNG */
if ((rc = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0)) != 0) {
goto exit;
}
/* Prepare point Q from pub key */
if (mbedtls_ecp_point_read_binary(&keypair.MBEDTLS_PRIVATE(grp), &Q, pub, 65) != 0) {
goto exit;
}
if (mbedtls_mpi_read_binary(&d, priv, 32) != 0) {
goto exit;
}
rc = mbedtls_ecdh_compute_shared(&keypair.MBEDTLS_PRIVATE(grp), &z, &Q, &d,
mbedtls_ctr_drbg_random, &ctr_drbg);
if (rc != 0) {
goto exit;
}
rc = mbedtls_mpi_write_binary(&z, dh, 32);
if (rc != 0) {
goto exit; goto exit;
} }
rc = 0;
exit: exit:
mbedtls_ecp_point_free(&pt);
mbedtls_mpi_free(&z);
mbedtls_mpi_free(&d);
mbedtls_ecp_point_free(&Q);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
if (rc != 0) { if (rc != 0) {
return BLE_SM_KEY_ERR; return BLE_SM_KEY_ERR;
} }
@@ -1735,42 +1691,38 @@ exit:
static int mbedtls_gen_keypair(uint8_t *public_key, uint8_t *private_key) static int mbedtls_gen_keypair(uint8_t *public_key, uint8_t *private_key)
{ {
int rc = BLE_SM_KEY_ERR; int rc = BLE_SM_KEY_ERR;
mbedtls_entropy_context entropy = {0}; psa_status_t status;
mbedtls_ctr_drbg_context ctr_drbg = {0}; psa_key_id_t key_id = 0;
psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_algorithm_t alg = PSA_ALG_ECDH;
psa_key_type_t key_type = PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1);
psa_key_usage_t key_usage = PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT;
mbedtls_entropy_init(&entropy); psa_set_key_type(&key_attributes, key_type);
mbedtls_ctr_drbg_init(&ctr_drbg); psa_set_key_bits(&key_attributes, 256);
mbedtls_ecp_keypair_init(&keypair); psa_set_key_algorithm(&key_attributes, alg);
psa_set_key_usage_flags(&key_attributes, key_usage);
if ((rc = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, status = psa_generate_key(&key_attributes, &key_id);
NULL, 0)) != 0) { if (status != PSA_SUCCESS) {
goto exit;
}
if ((rc = mbedtls_ecp_gen_key(MBEDTLS_ECP_DP_SECP256R1, &keypair,
mbedtls_ctr_drbg_random, &ctr_drbg)) != 0) {
goto exit;
}
if ((rc = mbedtls_mpi_write_binary(&keypair.MBEDTLS_PRIVATE(d), private_key, 32)) != 0) {
goto exit; goto exit;
} }
psa_reset_key_attributes(&key_attributes);
size_t olen = 0; size_t olen = 0;
uint8_t pub[65] = {0}; status = psa_export_public_key(key_id, public_key, 65, &olen);
if (status != PSA_SUCCESS || olen != 65) {
if ((rc = mbedtls_ecp_point_write_binary(&keypair.MBEDTLS_PRIVATE(grp), &keypair.MBEDTLS_PRIVATE(Q), MBEDTLS_ECP_PF_UNCOMPRESSED,
&olen, pub, 65)) != 0) {
goto exit; goto exit;
} }
memcpy(public_key, &pub[1], 64); status = psa_export_key(key_id, private_key, 32, &olen);
if (status != PSA_SUCCESS || olen != 32) {
goto exit;
}
psa_destroy_key(key_id);
rc = 0;
exit: exit:
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
if (rc != 0) { if (rc != 0) {
mbedtls_ecp_keypair_free(&keypair);
return BLE_SM_KEY_ERR; return BLE_SM_KEY_ERR;
} }
@@ -1789,7 +1741,7 @@ int ble_sm_alg_gen_key_pair(uint8_t *pub, uint8_t *priv)
swap_buf(&pub[32], &ble_sm_alg_dbg_pub_key[32], 32); swap_buf(&pub[32], &ble_sm_alg_dbg_pub_key[32], 32);
swap_buf(priv, ble_sm_alg_dbg_priv_key, 32); swap_buf(priv, ble_sm_alg_dbg_priv_key, 32);
#else #else
uint8_t pk[64]; uint8_t pk[BLE_PUB_KEY_LEN];
do { do {
#if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
@@ -1804,8 +1756,8 @@ int ble_sm_alg_gen_key_pair(uint8_t *pub, uint8_t *priv)
/* Make sure generated key isn't debug key. */ /* Make sure generated key isn't debug key. */
} while (memcmp(priv, ble_sm_alg_dbg_priv_key, 32) == 0); } while (memcmp(priv, ble_sm_alg_dbg_priv_key, 32) == 0);
swap_buf(pub, pk, 32); swap_buf(pub, &pk[1], 32);
swap_buf(&pub[32], &pk[32], 32); swap_buf(&pub[32], &pk[33], 32);
swap_in_place(priv, 32); swap_in_place(priv, 32);
#endif // CONFIG_BT_LE_SM_SC_DEBUG_KEYS #endif // CONFIG_BT_LE_SM_SC_DEBUG_KEYS
return 0; return 0;
+47 -95
View File
@@ -1656,16 +1656,10 @@ void esp_ble_controller_log_dump_all(bool output)
#if CONFIG_BT_LE_SM_LEGACY || CONFIG_BT_LE_SM_SC #if CONFIG_BT_LE_SM_LEGACY || CONFIG_BT_LE_SM_SC
#define BLE_SM_KEY_ERR 0x17 #define BLE_SM_KEY_ERR 0x17
#if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
#include "mbedtls/aes.h"
#if CONFIG_BT_LE_SM_SC #if CONFIG_BT_LE_SM_SC
#include "mbedtls/cipher.h" #include "psa/crypto.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/cmac.h"
#include "mbedtls/ecdh.h"
#include "mbedtls/ecp.h"
static mbedtls_ecp_keypair keypair; #define BLE_PUB_KEY_LEN 65
#endif // CONFIG_BT_LE_SM_SC #endif // CONFIG_BT_LE_SM_SC
#else #else
@@ -1709,78 +1703,40 @@ int ble_sm_alg_gen_dhkey(const uint8_t *peer_pub_key_x, const uint8_t *peer_pub_
const uint8_t *our_priv_key, uint8_t *out_dhkey) const uint8_t *our_priv_key, uint8_t *out_dhkey)
{ {
uint8_t dh[32]; uint8_t dh[32];
uint8_t pk[64]; uint8_t pk[BLE_PUB_KEY_LEN];
uint8_t priv[32]; uint8_t priv[32];
int rc = BLE_SM_KEY_ERR; int rc = BLE_SM_KEY_ERR;
swap_buf(pk, peer_pub_key_x, 32); pk[0] = 0x04; // Uncompressed format for public key
swap_buf(&pk[32], peer_pub_key_y, 32); swap_buf(&pk[1], peer_pub_key_x, 32);
swap_buf(&pk[33], peer_pub_key_y, 32);
swap_buf(priv, our_priv_key, 32); swap_buf(priv, our_priv_key, 32);
#if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
struct mbedtls_ecp_point pt = {0}, Q = {0}; psa_key_id_t key_id = 0;
mbedtls_mpi z = {0}, d = {0}; psa_status_t status;
mbedtls_ctr_drbg_context ctr_drbg = {0}; psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
mbedtls_entropy_context entropy = {0}; psa_set_key_type(&key_attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1));
psa_set_key_bits(&key_attributes, 256);
uint8_t pub[65] = {0}; psa_set_key_algorithm(&key_attributes, PSA_ALG_ECDH);
/* Hardcoded first byte of pub key for MBEDTLS_ECP_PF_UNCOMPRESSED */ psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
pub[0] = 0x04; status = psa_import_key(&key_attributes, priv, 32, &key_id);
memcpy(&pub[1], pk, 64); if (status != PSA_SUCCESS) {
goto exit;
/* Initialize the required structures here */ }
mbedtls_ecp_point_init(&pt); psa_reset_key_attributes(&key_attributes);
mbedtls_ecp_point_init(&Q); size_t output_len = 0;
mbedtls_ctr_drbg_init(&ctr_drbg); status = psa_raw_key_agreement(PSA_ALG_ECDH, key_id, pk, BLE_PUB_KEY_LEN, dh, sizeof(dh), &output_len);
mbedtls_entropy_init(&entropy); if (status != PSA_SUCCESS) {
mbedtls_mpi_init(&d);
mbedtls_mpi_init(&z);
/* Below 3 steps are to validate public key on curve secp256r1 */
if (mbedtls_ecp_group_load(&keypair.MBEDTLS_PRIVATE(grp), MBEDTLS_ECP_DP_SECP256R1) != 0) {
goto exit; goto exit;
} }
if (mbedtls_ecp_point_read_binary(&keypair.MBEDTLS_PRIVATE(grp), &pt, pub, 65) != 0) { if (output_len != 32) {
goto exit;
}
if (mbedtls_ecp_check_pubkey(&keypair.MBEDTLS_PRIVATE(grp), &pt) != 0) {
goto exit;
}
/* Set PRNG */
if ((rc = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0)) != 0) {
goto exit;
}
/* Prepare point Q from pub key */
if (mbedtls_ecp_point_read_binary(&keypair.MBEDTLS_PRIVATE(grp), &Q, pub, 65) != 0) {
goto exit;
}
if (mbedtls_mpi_read_binary(&d, priv, 32) != 0) {
goto exit;
}
rc = mbedtls_ecdh_compute_shared(&keypair.MBEDTLS_PRIVATE(grp), &z, &Q, &d,
mbedtls_ctr_drbg_random, &ctr_drbg);
if (rc != 0) {
goto exit;
}
rc = mbedtls_mpi_write_binary(&z, dh, 32);
if (rc != 0) {
goto exit; goto exit;
} }
rc = 0;
exit: exit:
mbedtls_ecp_point_free(&pt);
mbedtls_mpi_free(&z);
mbedtls_mpi_free(&d);
mbedtls_ecp_point_free(&Q);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
if (rc != 0) { if (rc != 0) {
return BLE_SM_KEY_ERR; return BLE_SM_KEY_ERR;
} }
@@ -1804,42 +1760,38 @@ exit:
static int mbedtls_gen_keypair(uint8_t *public_key, uint8_t *private_key) static int mbedtls_gen_keypair(uint8_t *public_key, uint8_t *private_key)
{ {
int rc = BLE_SM_KEY_ERR; int rc = BLE_SM_KEY_ERR;
mbedtls_entropy_context entropy = {0}; psa_status_t status;
mbedtls_ctr_drbg_context ctr_drbg = {0}; psa_key_id_t key_id = 0;
psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_algorithm_t alg = PSA_ALG_ECDH;
psa_key_type_t key_type = PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1);
psa_key_usage_t key_usage = PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT;
mbedtls_entropy_init(&entropy); psa_set_key_type(&key_attributes, key_type);
mbedtls_ctr_drbg_init(&ctr_drbg); psa_set_key_bits(&key_attributes, 256);
mbedtls_ecp_keypair_init(&keypair); psa_set_key_algorithm(&key_attributes, alg);
psa_set_key_usage_flags(&key_attributes, key_usage);
if ((rc = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, status = psa_generate_key(&key_attributes, &key_id);
NULL, 0)) != 0) { if (status != PSA_SUCCESS) {
goto exit;
}
if ((rc = mbedtls_ecp_gen_key(MBEDTLS_ECP_DP_SECP256R1, &keypair,
mbedtls_ctr_drbg_random, &ctr_drbg)) != 0) {
goto exit;
}
if ((rc = mbedtls_mpi_write_binary(&keypair.MBEDTLS_PRIVATE(d), private_key, 32)) != 0) {
goto exit; goto exit;
} }
psa_reset_key_attributes(&key_attributes);
size_t olen = 0; size_t olen = 0;
uint8_t pub[65] = {0}; status = psa_export_public_key(key_id, public_key, BLE_PUB_KEY_LEN, &olen);
if (status != PSA_SUCCESS || olen != BLE_PUB_KEY_LEN) {
if ((rc = mbedtls_ecp_point_write_binary(&keypair.MBEDTLS_PRIVATE(grp), &keypair.MBEDTLS_PRIVATE(Q), MBEDTLS_ECP_PF_UNCOMPRESSED,
&olen, pub, 65)) != 0) {
goto exit; goto exit;
} }
memcpy(public_key, &pub[1], 64); status = psa_export_key(key_id, private_key, 32, &olen);
if (status != PSA_SUCCESS || olen != 32) {
goto exit;
}
psa_destroy_key(key_id);
rc = 0;
exit: exit:
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
if (rc != 0) { if (rc != 0) {
mbedtls_ecp_keypair_free(&keypair);
return BLE_SM_KEY_ERR; return BLE_SM_KEY_ERR;
} }
@@ -1858,7 +1810,7 @@ int ble_sm_alg_gen_key_pair(uint8_t *pub, uint8_t *priv)
swap_buf(&pub[32], &ble_sm_alg_dbg_pub_key[32], 32); swap_buf(&pub[32], &ble_sm_alg_dbg_pub_key[32], 32);
swap_buf(priv, ble_sm_alg_dbg_priv_key, 32); swap_buf(priv, ble_sm_alg_dbg_priv_key, 32);
#else #else
uint8_t pk[64]; uint8_t pk[BLE_PUB_KEY_LEN];
do { do {
#if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
@@ -1873,8 +1825,8 @@ int ble_sm_alg_gen_key_pair(uint8_t *pub, uint8_t *priv)
/* Make sure generated key isn't debug key. */ /* Make sure generated key isn't debug key. */
} while (memcmp(priv, ble_sm_alg_dbg_priv_key, 32) == 0); } while (memcmp(priv, ble_sm_alg_dbg_priv_key, 32) == 0);
swap_buf(pub, pk, 32); swap_buf(pub, &pk[1], 32);
swap_buf(&pub[32], &pk[32], 32); swap_buf(&pub[32], &pk[33], 32);
swap_in_place(priv, 32); swap_in_place(priv, 32);
#endif // CONFIG_BT_LE_SM_SC_DEBUG_KEYS #endif // CONFIG_BT_LE_SM_SC_DEBUG_KEYS
return 0; return 0;
+47 -93
View File
@@ -1608,14 +1608,9 @@ void esp_ble_controller_log_dump_all(bool output)
#if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
#include "mbedtls/aes.h" #include "mbedtls/aes.h"
#if CONFIG_BT_LE_SM_SC #if CONFIG_BT_LE_SM_SC
#include "mbedtls/cipher.h" #include "psa/crypto.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/cmac.h"
#include "mbedtls/ecdh.h"
#include "mbedtls/ecp.h"
static mbedtls_ecp_keypair keypair; #define BLE_PUB_KEY_LEN 65
#endif // CONFIG_BT_LE_SM_SC #endif // CONFIG_BT_LE_SM_SC
#else #else
@@ -1659,78 +1654,40 @@ int ble_sm_alg_gen_dhkey(const uint8_t *peer_pub_key_x, const uint8_t *peer_pub_
const uint8_t *our_priv_key, uint8_t *out_dhkey) const uint8_t *our_priv_key, uint8_t *out_dhkey)
{ {
uint8_t dh[32]; uint8_t dh[32];
uint8_t pk[64]; uint8_t pk[BLE_PUB_KEY_LEN];
uint8_t priv[32]; uint8_t priv[32];
int rc = BLE_SM_KEY_ERR; int rc = BLE_SM_KEY_ERR;
swap_buf(pk, peer_pub_key_x, 32); pk[0] = 0x04; // Uncompressed format for public key
swap_buf(&pk[32], peer_pub_key_y, 32); swap_buf(&pk[1], peer_pub_key_x, 32);
swap_buf(&pk[33], peer_pub_key_y, 32);
swap_buf(priv, our_priv_key, 32); swap_buf(priv, our_priv_key, 32);
#if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS #if CONFIG_BT_LE_CRYPTO_STACK_MBEDTLS
struct mbedtls_ecp_point pt = {0}, Q = {0}; psa_key_id_t key_id = 0;
mbedtls_mpi z = {0}, d = {0}; psa_status_t status;
mbedtls_ctr_drbg_context ctr_drbg = {0}; psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
mbedtls_entropy_context entropy = {0}; psa_set_key_type(&key_attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1));
psa_set_key_bits(&key_attributes, 256);
uint8_t pub[65] = {0}; psa_set_key_algorithm(&key_attributes, PSA_ALG_ECDH);
/* Hardcoded first byte of pub key for MBEDTLS_ECP_PF_UNCOMPRESSED */ psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
pub[0] = 0x04; status = psa_import_key(&key_attributes, priv, 32, &key_id);
memcpy(&pub[1], pk, 64); if (status != PSA_SUCCESS) {
goto exit;
/* Initialize the required structures here */ }
mbedtls_ecp_point_init(&pt); psa_reset_key_attributes(&key_attributes);
mbedtls_ecp_point_init(&Q); size_t output_len = 0;
mbedtls_ctr_drbg_init(&ctr_drbg); status = psa_raw_key_agreement(PSA_ALG_ECDH, key_id, pk, BLE_PUB_KEY_LEN, dh, sizeof(dh), &output_len);
mbedtls_entropy_init(&entropy); if (status != PSA_SUCCESS) {
mbedtls_mpi_init(&d);
mbedtls_mpi_init(&z);
/* Below 3 steps are to validate public key on curve secp256r1 */
if (mbedtls_ecp_group_load(&keypair.MBEDTLS_PRIVATE(grp), MBEDTLS_ECP_DP_SECP256R1) != 0) {
goto exit; goto exit;
} }
if (mbedtls_ecp_point_read_binary(&keypair.MBEDTLS_PRIVATE(grp), &pt, pub, 65) != 0) { if (output_len != 32) {
goto exit;
}
if (mbedtls_ecp_check_pubkey(&keypair.MBEDTLS_PRIVATE(grp), &pt) != 0) {
goto exit;
}
/* Set PRNG */
if ((rc = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0)) != 0) {
goto exit;
}
/* Prepare point Q from pub key */
if (mbedtls_ecp_point_read_binary(&keypair.MBEDTLS_PRIVATE(grp), &Q, pub, 65) != 0) {
goto exit;
}
if (mbedtls_mpi_read_binary(&d, priv, 32) != 0) {
goto exit;
}
rc = mbedtls_ecdh_compute_shared(&keypair.MBEDTLS_PRIVATE(grp), &z, &Q, &d,
mbedtls_ctr_drbg_random, &ctr_drbg);
if (rc != 0) {
goto exit;
}
rc = mbedtls_mpi_write_binary(&z, dh, 32);
if (rc != 0) {
goto exit; goto exit;
} }
rc = 0;
exit: exit:
mbedtls_ecp_point_free(&pt);
mbedtls_mpi_free(&z);
mbedtls_mpi_free(&d);
mbedtls_ecp_point_free(&Q);
mbedtls_entropy_free(&entropy);
mbedtls_ctr_drbg_free(&ctr_drbg);
if (rc != 0) { if (rc != 0) {
return BLE_SM_KEY_ERR; return BLE_SM_KEY_ERR;
} }
@@ -1754,42 +1711,39 @@ exit:
static int mbedtls_gen_keypair(uint8_t *public_key, uint8_t *private_key) static int mbedtls_gen_keypair(uint8_t *public_key, uint8_t *private_key)
{ {
int rc = BLE_SM_KEY_ERR; int rc = BLE_SM_KEY_ERR;
mbedtls_entropy_context entropy = {0}; psa_status_t status;
mbedtls_ctr_drbg_context ctr_drbg = {0}; psa_key_id_t key_id = 0;
psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_algorithm_t alg = PSA_ALG_ECDH;
psa_key_type_t key_type = PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1);
psa_key_usage_t key_usage = PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT;
mbedtls_entropy_init(&entropy); psa_set_key_type(&key_attributes, key_type);
mbedtls_ctr_drbg_init(&ctr_drbg); psa_set_key_bits(&key_attributes, 256);
mbedtls_ecp_keypair_init(&keypair); psa_set_key_algorithm(&key_attributes, alg);
psa_set_key_usage_flags(&key_attributes, key_usage);
if ((rc = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, status = psa_generate_key(&key_attributes, &key_id);
NULL, 0)) != 0) { if (status != PSA_SUCCESS) {
goto exit;
}
if ((rc = mbedtls_ecp_gen_key(MBEDTLS_ECP_DP_SECP256R1, &keypair,
mbedtls_ctr_drbg_random, &ctr_drbg)) != 0) {
goto exit;
}
if ((rc = mbedtls_mpi_write_binary(&keypair.MBEDTLS_PRIVATE(d), private_key, 32)) != 0) {
goto exit; goto exit;
} }
psa_reset_key_attributes(&key_attributes);
size_t olen = 0; size_t olen = 0;
uint8_t pub[65] = {0}; status = psa_export_public_key(key_id, public_key, BLE_PUB_KEY_LEN, &olen);
if (status != PSA_SUCCESS || olen != BLE_PUB_KEY_LEN) {
if ((rc = mbedtls_ecp_point_write_binary(&keypair.MBEDTLS_PRIVATE(grp), &keypair.MBEDTLS_PRIVATE(Q), MBEDTLS_ECP_PF_UNCOMPRESSED,
&olen, pub, 65)) != 0) {
goto exit; goto exit;
} }
memcpy(public_key, &pub[1], 64); status = psa_export_key(key_id, private_key, 32, &olen);
if (status != PSA_SUCCESS || olen != 32) {
goto exit;
}
psa_destroy_key(key_id);
rc = 0;
exit: exit:
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
if (rc != 0) { if (rc != 0) {
mbedtls_ecp_keypair_free(&keypair);
return BLE_SM_KEY_ERR; return BLE_SM_KEY_ERR;
} }
@@ -1823,8 +1777,8 @@ int ble_sm_alg_gen_key_pair(uint8_t *pub, uint8_t *priv)
/* Make sure generated key isn't debug key. */ /* Make sure generated key isn't debug key. */
} while (memcmp(priv, ble_sm_alg_dbg_priv_key, 32) == 0); } while (memcmp(priv, ble_sm_alg_dbg_priv_key, 32) == 0);
swap_buf(pub, pk, 32); swap_buf(pub, &pk[1], 32);
swap_buf(&pub[32], &pk[32], 32); swap_buf(&pub[32], &pk[33], 32);
swap_in_place(priv, 32); swap_in_place(priv, 32);
#endif // CONFIG_BT_LE_SM_SC_DEBUG_KEYS #endif // CONFIG_BT_LE_SM_SC_DEBUG_KEYS
return 0; return 0;
@@ -19,7 +19,7 @@
#include "device/controller.h" #include "device/controller.h"
#if CONFIG_MBEDTLS_HARDWARE_AES #if CONFIG_MBEDTLS_HARDWARE_AES
#include "mbedtls/aes.h" #include "psa/crypto.h"
#endif #endif
#include <tinycrypt/aes.h> #include <tinycrypt/aes.h>
@@ -2580,26 +2580,47 @@ int bt_mesh_encrypt_le(const uint8_t key[16], const uint8_t plaintext[16],
BT_DBG("key %s plaintext %s", bt_hex(key, 16), bt_hex(plaintext, 16)); BT_DBG("key %s plaintext %s", bt_hex(key, 16), bt_hex(plaintext, 16));
#if CONFIG_MBEDTLS_HARDWARE_AES #if CONFIG_MBEDTLS_HARDWARE_AES
mbedtls_aes_context ctx = {0};
mbedtls_aes_init(&ctx);
sys_memcpy_swap(tmp, key, 16); sys_memcpy_swap(tmp, key, 16);
psa_status_t status;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key_id = 0;
psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
psa_algorithm_t alg = PSA_ALG_ECB_NO_PADDING;
psa_set_key_algorithm(&attributes, alg);
psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&attributes, 128);
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
if (mbedtls_aes_setkey_enc(&ctx, tmp, 128) != 0) { status = psa_import_key(&attributes, tmp, 16, &key_id);
mbedtls_aes_free(&ctx); if (status != PSA_SUCCESS) {
BT_ERR("psa_import_key failed with status %d", status);
return -EINVAL;
}
psa_reset_key_attributes(&attributes);
status = psa_cipher_encrypt_setup(&operation, key_id, alg);
if (status != PSA_SUCCESS) {
BT_ERR("psa_cipher_encrypt_setup failed with status %d", status);
psa_destroy_key(key_id);
return -EINVAL;
}
size_t output_length = 0;
status = psa_cipher_update(&operation, plaintext, 16, enc_data, 16, &output_length);
if (status != PSA_SUCCESS || output_length != 16) {
BT_ERR("psa_cipher_update failed with status %d", status);
psa_cipher_abort(&operation);
psa_destroy_key(key_id);
return -EINVAL; return -EINVAL;
} }
sys_memcpy_swap(tmp, plaintext, 16); status = psa_cipher_finish(&operation, enc_data + output_length, 16 - output_length, &output_length);
if (status != PSA_SUCCESS) {
if (mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_ENCRYPT, BT_ERR("psa_cipher_finish failed with status %d", status);
tmp, enc_data) != 0) {
mbedtls_aes_free(&ctx);
return -EINVAL; return -EINVAL;
} }
mbedtls_aes_free(&ctx); psa_destroy_key(key_id);
#else /* CONFIG_MBEDTLS_HARDWARE_AES */ #else /* CONFIG_MBEDTLS_HARDWARE_AES */
struct tc_aes_key_sched_struct s = {0}; struct tc_aes_key_sched_struct s = {0};
@@ -2629,22 +2650,44 @@ int bt_mesh_encrypt_be(const uint8_t key[16], const uint8_t plaintext[16],
BT_DBG("key %s plaintext %s", bt_hex(key, 16), bt_hex(plaintext, 16)); BT_DBG("key %s plaintext %s", bt_hex(key, 16), bt_hex(plaintext, 16));
#if CONFIG_MBEDTLS_HARDWARE_AES #if CONFIG_MBEDTLS_HARDWARE_AES
mbedtls_aes_context ctx = {0}; psa_status_t status;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key_id = 0;
psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
psa_algorithm_t alg = PSA_ALG_ECB_NO_PADDING;
psa_set_key_algorithm(&attributes, alg);
psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&attributes, 128);
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
mbedtls_aes_init(&ctx); status = psa_import_key(&attributes, key, 16, &key_id);
if (status != PSA_SUCCESS) {
if (mbedtls_aes_setkey_enc(&ctx, key, 128) != 0) { BT_ERR("psa_import_key failed with status %d", status);
mbedtls_aes_free(&ctx);
return -EINVAL; return -EINVAL;
} }
if (mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_ENCRYPT, status = psa_cipher_encrypt_setup(&operation, key_id, alg);
plaintext, enc_data) != 0) { if (status != PSA_SUCCESS) {
mbedtls_aes_free(&ctx); BT_ERR("psa_cipher_encrypt_setup failed with status %d", status);
psa_destroy_key(key_id);
return -EINVAL;
}
size_t output_length = 0;
status = psa_cipher_update(&operation, plaintext, 16, enc_data, 16, &output_length);
if (status != PSA_SUCCESS || output_length != 16) {
BT_ERR("psa_cipher_update failed with status %d", status);
psa_cipher_abort(&operation);
psa_destroy_key(key_id);
return -EINVAL; return -EINVAL;
} }
mbedtls_aes_free(&ctx); status = psa_cipher_finish(&operation, enc_data + output_length, 16 - output_length, &output_length);
if (status != PSA_SUCCESS) {
BT_ERR("psa_cipher_finish failed with status %d", status);
return -EINVAL;
}
psa_destroy_key(key_id);
#else /* CONFIG_MBEDTLS_HARDWARE_AES */ #else /* CONFIG_MBEDTLS_HARDWARE_AES */
struct tc_aes_key_sched_struct s = {0}; struct tc_aes_key_sched_struct s = {0};
@@ -11,8 +11,7 @@
#include "btc/btc_task.h" #include "btc/btc_task.h"
#include "osi/alarm.h" #include "osi/alarm.h"
#include "mbedtls/aes.h" #include "psa/crypto.h"
#include "mbedtls/ecp.h"
#include "host/ble_hs.h" #include "host/ble_hs.h"
#include "host/ble_uuid.h" #include "host/ble_uuid.h"
@@ -2665,39 +2664,29 @@ const uint8_t *bt_mesh_pub_key_get(void)
bool bt_mesh_check_public_key(const uint8_t key[64]) bool bt_mesh_check_public_key(const uint8_t key[64])
{ {
struct mbedtls_ecp_point pt = {0}; psa_status_t status = PSA_SUCCESS;
mbedtls_ecp_group grp = {0};
bool rc = false;
uint8_t pub[65] = {0}; uint8_t pub[65] = {0};
/* Hardcoded first byte of pub key for MBEDTLS_ECP_PF_UNCOMPRESSED */ /* Hardcoded first byte of pub key for MBEDTLS_ECP_PF_UNCOMPRESSED */
pub[0] = 0x04; pub[0] = 0x04;
memcpy(&pub[1], key, 64); memcpy(&pub[1], key, 64);
/* Initialize the required structures here */ psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
mbedtls_ecp_point_init(&pt); psa_key_id_t key_id = 0;
mbedtls_ecp_group_init(&grp); psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_HASH);
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA(PSA_ALG_SHA_256));
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_PUBLIC_KEY(PSA_ECC_FAMILY_SECP_R1));
psa_set_key_bits(&attributes, 256);
/* Below 3 steps are to validate public key on curve secp256r1 */ status = psa_import_key(&attributes, pub, sizeof(pub), &key_id);
if (mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_SECP256R1) != 0) { if (status != PSA_SUCCESS) {
goto exit; BT_ERR("Failed to import public key, status: %d", status);
return false;
} }
psa_reset_key_attributes(&attributes);
psa_destroy_key(key_id);
if (mbedtls_ecp_point_read_binary(&grp, &pt, pub, 65) != 0) { return true;
goto exit;
}
if (mbedtls_ecp_check_pubkey(&grp, &pt) != 0) {
goto exit;
}
rc = true;
exit:
mbedtls_ecp_point_free(&pt);
mbedtls_ecp_group_free(&grp);
return rc;
} }
int ble_sm_alg_gen_dhkey(uint8_t *peer_pub_key_x, uint8_t *peer_pub_key_y, int ble_sm_alg_gen_dhkey(uint8_t *peer_pub_key_x, uint8_t *peer_pub_key_y,
@@ -2719,26 +2708,46 @@ int bt_mesh_encrypt_le(const uint8_t key[16], const uint8_t plaintext[16],
BT_DBG("key %s plaintext %s", bt_hex(key, 16), bt_hex(plaintext, 16)); BT_DBG("key %s plaintext %s", bt_hex(key, 16), bt_hex(plaintext, 16));
#if CONFIG_MBEDTLS_HARDWARE_AES #if CONFIG_MBEDTLS_HARDWARE_AES
mbedtls_aes_context ctx = {0};
mbedtls_aes_init(&ctx);
sys_memcpy_swap(tmp, key, 16); sys_memcpy_swap(tmp, key, 16);
psa_status_t status;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key_id = 0;
psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
psa_algorithm_t alg = PSA_ALG_ECB_NO_PADDING;
psa_set_key_algorithm(&attributes, alg);
psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&attributes, 128);
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
if (mbedtls_aes_setkey_enc(&ctx, tmp, 128) != 0) { status = psa_import_key(&attributes, tmp, 16, &key_id);
mbedtls_aes_free(&ctx); if (status != PSA_SUCCESS) {
BT_ERR("psa_import_key failed with status %d", status);
return -EINVAL;
}
psa_reset_key_attributes(&attributes);
status = psa_cipher_encrypt_setup(&operation, key_id, alg);
if (status != PSA_SUCCESS) {
BT_ERR("psa_cipher_encrypt_setup failed with status %d", status);
psa_destroy_key(key_id);
return -EINVAL;
}
size_t output_length = 0;
status = psa_cipher_update(&operation, plaintext, 16, enc_data, 16, &output_length);
if (status != PSA_SUCCESS || output_length != 16) {
BT_ERR("psa_cipher_update failed with status %d", status);
psa_cipher_abort(&operation);
psa_destroy_key(key_id);
return -EINVAL; return -EINVAL;
} }
sys_memcpy_swap(tmp, plaintext, 16); status = psa_cipher_finish(&operation, enc_data + output_length, 16 - output_length, &output_length);
if (status != PSA_SUCCESS) {
if (mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_ENCRYPT, BT_ERR("psa_cipher_finish failed with status %d", status);
tmp, enc_data) != 0) {
mbedtls_aes_free(&ctx);
return -EINVAL; return -EINVAL;
} }
mbedtls_aes_free(&ctx); psa_destroy_key(key_id);
#else /* CONFIG_MBEDTLS_HARDWARE_AES */ #else /* CONFIG_MBEDTLS_HARDWARE_AES */
struct tc_aes_key_sched_struct s = {0}; struct tc_aes_key_sched_struct s = {0};
@@ -2768,22 +2777,45 @@ int bt_mesh_encrypt_be(const uint8_t key[16], const uint8_t plaintext[16],
BT_DBG("key %s plaintext %s", bt_hex(key, 16), bt_hex(plaintext, 16)); BT_DBG("key %s plaintext %s", bt_hex(key, 16), bt_hex(plaintext, 16));
#if CONFIG_MBEDTLS_HARDWARE_AES #if CONFIG_MBEDTLS_HARDWARE_AES
mbedtls_aes_context ctx = {0}; psa_status_t status;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key_id = 0;
psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
psa_algorithm_t alg = PSA_ALG_ECB_NO_PADDING;
psa_set_key_algorithm(&attributes, alg);
psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&attributes, 128);
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
mbedtls_aes_init(&ctx); status = psa_import_key(&attributes, key, 16, &key_id);
if (status != PSA_SUCCESS) {
if (mbedtls_aes_setkey_enc(&ctx, key, 128) != 0) { BT_ERR("psa_import_key failed with status %d", status);
mbedtls_aes_free(&ctx);
return -EINVAL; return -EINVAL;
} }
if (mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_ENCRYPT, status = psa_cipher_encrypt_setup(&operation, key_id, alg);
plaintext, enc_data) != 0) { if (status != PSA_SUCCESS) {
mbedtls_aes_free(&ctx); BT_ERR("psa_cipher_encrypt_setup failed with status %d", status);
psa_destroy_key(key_id);
return -EINVAL;
}
size_t output_length = 0;
status = psa_cipher_update(&operation, plaintext, 16, enc_data, 16, &output_length);
if (status != PSA_SUCCESS || output_length != 16) {
BT_ERR("psa_cipher_update failed with status %d", status);
psa_cipher_abort(&operation);
psa_destroy_key(key_id);
return -EINVAL; return -EINVAL;
} }
mbedtls_aes_free(&ctx); status = psa_cipher_finish(&operation, enc_data + output_length, 16 - output_length, &output_length);
if (status != PSA_SUCCESS) {
BT_ERR("psa_cipher_finish failed with status %d", status);
psa_destroy_key(key_id);
return -EINVAL;
}
psa_destroy_key(key_id);
#else /* CONFIG_MBEDTLS_HARDWARE_AES */ #else /* CONFIG_MBEDTLS_HARDWARE_AES */
struct tc_aes_key_sched_struct s = {0}; struct tc_aes_key_sched_struct s = {0};
+19 -19
View File
@@ -26,26 +26,26 @@
/* setUp runs before every test */ /* setUp runs before every test */
void setUp(void) void setUp(void)
{ {
#if SOC_SHA_SUPPORTED // #if SOC_SHA_SUPPORTED
// Execute esp_sha operation to allocate internal SHA semaphore (in case of ESP32) // // Execute esp_sha operation to allocate internal SHA semaphore (in case of ESP32)
// and initial DMA setup memory which is considered as leaked otherwise // // and initial DMA setup memory which is considered as leaked otherwise
const uint8_t input_buffer[64] = {0}; // const uint8_t input_buffer[64] = {0};
uint8_t output_buffer[64]; // uint8_t output_buffer[64];
esp_sha(SHA_TYPE, input_buffer, sizeof(input_buffer), output_buffer); // esp_sha(SHA_TYPE, input_buffer, sizeof(input_buffer), output_buffer);
#endif // SOC_SHA_SUPPORTED // #endif // SOC_SHA_SUPPORTED
#if SOC_AES_SUPPORTED // #if SOC_AES_SUPPORTED
// Execute mbedtls_aes_init operation to allocate AES interrupt // // Execute mbedtls_aes_init operation to allocate AES interrupt
// allocation memory which is considered as leak otherwise // // allocation memory which is considered as leak otherwise
const uint8_t plaintext[16] = {0}; // const uint8_t plaintext[16] = {0};
uint8_t ciphertext[16]; // uint8_t ciphertext[16];
const uint8_t key[16] = { 0 }; // const uint8_t key[16] = { 0 };
mbedtls_aes_context ctx; // mbedtls_aes_context ctx;
mbedtls_aes_init(&ctx); // mbedtls_aes_init(&ctx);
mbedtls_aes_setkey_enc(&ctx, key, 128); // mbedtls_aes_setkey_enc(&ctx, key, 128);
mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_ENCRYPT, plaintext, ciphertext); // mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_ENCRYPT, plaintext, ciphertext);
mbedtls_aes_free(&ctx); // mbedtls_aes_free(&ctx);
#endif // SOC_AES_SUPPORTED // #endif // SOC_AES_SUPPORTED
test_utils_record_free_mem(); test_utils_record_free_mem();
TEST_ESP_OK(test_utils_set_leak_level(0, ESP_LEAK_TYPE_CRITICAL, ESP_COMP_LEAK_GENERAL)); TEST_ESP_OK(test_utils_set_leak_level(0, ESP_LEAK_TYPE_CRITICAL, ESP_COMP_LEAK_GENERAL));
+1 -1
View File
@@ -27,7 +27,7 @@ extern "C" {
* stronger message digests instead. * stronger message digests instead.
* *
*/ */
typedef struct mbedtls_md5_context { typedef struct md5_context {
uint32_t total[2]; /*!< number of bytes processed */ uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[4]; /*!< intermediate digest state */ uint32_t state[4]; /*!< intermediate digest state */
unsigned char buffer[64]; /*!< data block being processed */ unsigned char buffer[64]; /*!< data block being processed */
+75 -48
View File
@@ -150,9 +150,9 @@ get_target_property(src_tls mbedtls SOURCES)
list(REMOVE_ITEM src_tls ssl_ciphersuites.c ssl_cli.c ssl_tls.c) list(REMOVE_ITEM src_tls ssl_ciphersuites.c ssl_cli.c ssl_tls.c)
set_property(TARGET mbedtls PROPERTY SOURCES ${src_tls}) set_property(TARGET mbedtls PROPERTY SOURCES ${src_tls})
get_target_property(src_crypto tfpsacrypto SOURCES) # get_target_property(src_crypto tfpsacrypto SOURCES)
list(REMOVE_ITEM src_crypto cipher_wrap.c ecdsa.c ecp.c ecp_curves.c oid.c pk_wrap.c) # list(REMOVE_ITEM src_crypto cipher_wrap.c ecdsa.c ecp.c ecp_curves.c oid.c pk_wrap.c)
set_property(TARGET mbedcrypto PROPERTY SOURCES ${src_crypto}) # set_property(TARGET mbedcrypto PROPERTY SOURCES ${src_crypto})
get_target_property(src_x509 mbedx509 SOURCES) get_target_property(src_x509 mbedx509 SOURCES)
list(REMOVE_ITEM src_x509 x509_crt.c) list(REMOVE_ITEM src_x509 x509_crt.c)
@@ -182,7 +182,7 @@ endif()
# While updating to MbedTLS release/v3.4.0, building mbedtls/library/psa_crypto.c # While updating to MbedTLS release/v3.4.0, building mbedtls/library/psa_crypto.c
# clang produces an unreachable-code warning. # clang produces an unreachable-code warning.
if(CMAKE_C_COMPILER_ID MATCHES "Clang") if(CMAKE_C_COMPILER_ID MATCHES "Clang")
target_compile_options(mbedcrypto PRIVATE "-Wno-unreachable-code") target_compile_options(tfpsacrypto PRIVATE "-Wno-unreachable-code")
endif() endif()
# net_sockets.c should only be compiled if BSD socket functions are available. # net_sockets.c should only be compiled if BSD socket functions are available.
@@ -201,9 +201,9 @@ endif()
# Add port files to mbedtls targets # Add port files to mbedtls targets
target_sources(mbedtls PRIVATE ${mbedtls_target_sources}) target_sources(mbedtls PRIVATE ${mbedtls_target_sources})
# if(NOT ${IDF_TARGET} STREQUAL "linux") if(NOT ${IDF_TARGET} STREQUAL "linux")
# target_link_libraries(mbedcrypto PRIVATE idf::esp_security) target_link_libraries(tfpsacrypto PRIVATE idf::esp_security)
# endif() endif()
# Choose peripheral type # Choose peripheral type
@@ -223,16 +223,16 @@ if(CONFIG_SOC_AES_SUPPORTED)
endif() endif()
endif() endif()
# if(SHA_PERIPHERAL_TYPE STREQUAL "core") if(SHA_PERIPHERAL_TYPE STREQUAL "core")
# target_include_directories(mbedcrypto PRIVATE "${COMPONENT_DIR}/port/sha/core/include") target_include_directories(tfpsacrypto PRIVATE "${COMPONENT_DIR}/port/sha/core/include")
# if(CONFIG_SOC_SHA_GDMA) if(CONFIG_SOC_SHA_GDMA)
# set(SHA_CORE_SRCS "${COMPONENT_DIR}/port/sha/core/esp_sha_gdma_impl.c") set(SHA_CORE_SRCS "${COMPONENT_DIR}/port/sha/core/esp_sha_gdma_impl.c")
# elseif(CONFIG_SOC_SHA_CRYPTO_DMA) elseif(CONFIG_SOC_SHA_CRYPTO_DMA)
# set(SHA_CORE_SRCS "${COMPONENT_DIR}/port/sha/core/esp_sha_crypto_dma_impl.c") set(SHA_CORE_SRCS "${COMPONENT_DIR}/port/sha/core/esp_sha_crypto_dma_impl.c")
# endif() endif()
# target_sources(mbedcrypto PRIVATE "${SHA_CORE_SRCS}") target_sources(tfpsacrypto PRIVATE "${SHA_CORE_SRCS}")
# endif() endif()
# if(AES_PERIPHERAL_TYPE STREQUAL "dma") # if(AES_PERIPHERAL_TYPE STREQUAL "dma")
# if(NOT CONFIG_SOC_AES_GDMA) # if(NOT CONFIG_SOC_AES_GDMA)
@@ -247,15 +247,15 @@ endif()
# target_sources(mbedcrypto PRIVATE "${AES_DMA_SRCS}") # target_sources(mbedcrypto PRIVATE "${AES_DMA_SRCS}")
# endif() # endif()
# if((SHA_PERIPHERAL_TYPE STREQUAL "core" AND CONFIG_SOC_SHA_SUPPORT_DMA) OR AES_PERIPHERAL_TYPE STREQUAL "dma") if((SHA_PERIPHERAL_TYPE STREQUAL "core" AND CONFIG_SOC_SHA_SUPPORT_DMA) OR AES_PERIPHERAL_TYPE STREQUAL "dma")
# target_link_libraries(mbedcrypto PRIVATE idf::esp_mm) target_link_libraries(tfpsacrypto PRIVATE idf::esp_mm)
# if(CONFIG_SOC_SHA_GDMA OR CONFIG_SOC_AES_GDMA) if(CONFIG_SOC_SHA_GDMA OR CONFIG_SOC_AES_GDMA)
# if(CONFIG_SOC_AXI_DMA_EXT_MEM_ENC_ALIGNMENT) if(CONFIG_SOC_AXI_DMA_EXT_MEM_ENC_ALIGNMENT)
# target_link_libraries(mbedcrypto PRIVATE idf::bootloader_support) target_link_libraries(tfpsacrypto PRIVATE idf::bootloader_support)
# endif() endif()
# target_sources(mbedcrypto PRIVATE "${COMPONENT_DIR}/port/crypto_shared_gdma/esp_crypto_shared_gdma.c") target_sources(tfpsacrypto PRIVATE "${COMPONENT_DIR}/port/crypto_shared_gdma/esp_crypto_shared_gdma.c")
# endif() endif()
# endif() endif()
# if(NOT ${IDF_TARGET} STREQUAL "linux") # if(NOT ${IDF_TARGET} STREQUAL "linux")
# target_sources(mbedcrypto PRIVATE "${COMPONENT_DIR}/port/esp_hardware.c") # target_sources(mbedcrypto PRIVATE "${COMPONENT_DIR}/port/esp_hardware.c")
@@ -264,26 +264,26 @@ endif()
# "${COMPONENT_DIR}/port/esp_timing.c" # "${COMPONENT_DIR}/port/esp_timing.c"
# ) # )
# if(CONFIG_SOC_AES_SUPPORTED) if(CONFIG_SOC_AES_SUPPORTED)
# target_include_directories(mbedcrypto PRIVATE "${COMPONENT_DIR}/port/aes/include") target_include_directories(tfpsacrypto PRIVATE "${COMPONENT_DIR}/port/aes/include")
# target_sources(mbedcrypto PRIVATE "${COMPONENT_DIR}/port/aes/esp_aes_xts.c" target_sources(tfpsacrypto PRIVATE "${COMPONENT_DIR}/port/aes/esp_aes_xts.c"
# "${COMPONENT_DIR}/port/aes/esp_aes_common.c" "${COMPONENT_DIR}/port/aes/esp_aes_common.c"
# "${COMPONENT_DIR}/port/aes/${AES_PERIPHERAL_TYPE}/esp_aes.c" "${COMPONENT_DIR}/port/aes/${AES_PERIPHERAL_TYPE}/esp_aes.c"
# ) )
# endif()
# if(CONFIG_SOC_SHA_SUPPORTED)
# target_sources(mbedcrypto PRIVATE "${COMPONENT_DIR}/port/sha/esp_sha.c"
# "${COMPONENT_DIR}/port/sha/${SHA_PERIPHERAL_TYPE}/sha.c"
# )
# endif()
if(CONFIG_SOC_DIG_SIGN_SUPPORTED)
target_sources(mbedcrypto PRIVATE
"${COMPONENT_DIR}/port/esp_ds/esp_rsa_sign_alt.c"
"${COMPONENT_DIR}/port/esp_ds/esp_rsa_dec_alt.c"
"${COMPONENT_DIR}/port/esp_ds/esp_ds_common.c")
endif() endif()
if(CONFIG_SOC_SHA_SUPPORTED)
target_sources(tfpsacrypto PRIVATE "${COMPONENT_DIR}/port/sha/esp_sha.c"
"${COMPONENT_DIR}/port/sha/${SHA_PERIPHERAL_TYPE}/sha.c"
)
endif()
# if(CONFIG_SOC_DIG_SIGN_SUPPORTED)
# target_sources(mbedcrypto PRIVATE
# "${COMPONENT_DIR}/port/esp_ds/esp_rsa_sign_alt.c"
# "${COMPONENT_DIR}/port/esp_ds/esp_rsa_dec_alt.c"
# "${COMPONENT_DIR}/port/esp_ds/esp_ds_common.c")
# endif()
# # CONFIG_ESP_TLS_USE_DS_PERIPHERAL can be enabled only for the supported targets. # # CONFIG_ESP_TLS_USE_DS_PERIPHERAL can be enabled only for the supported targets.
# if(CONFIG_ESP_TLS_USE_DS_PERIPHERAL) # if(CONFIG_ESP_TLS_USE_DS_PERIPHERAL)
# target_sources(mbedcrypto PRIVATE "${COMPONENT_DIR}/port/esp_ds/esp_rsa_sign_alt.c") # target_sources(mbedcrypto PRIVATE "${COMPONENT_DIR}/port/esp_ds/esp_rsa_sign_alt.c")
@@ -300,10 +300,10 @@ endif()
# #
# The other port-specific files don't override internal mbedTLS functions, they just add new functions. # The other port-specific files don't override internal mbedTLS functions, they just add new functions.
# if(CONFIG_MBEDTLS_HARDWARE_MPI) if(CONFIG_MBEDTLS_HARDWARE_MPI)
# target_sources(mbedcrypto PRIVATE "${COMPONENT_DIR}/port/bignum/esp_bignum.c" target_sources(tfpsacrypto PRIVATE "${COMPONENT_DIR}/port/bignum/esp_bignum.c"
# "${COMPONENT_DIR}/port/bignum/bignum_alt.c") "${COMPONENT_DIR}/port/bignum/bignum_alt.c")
# endif() endif()
# if(CONFIG_MBEDTLS_HARDWARE_SHA) # if(CONFIG_MBEDTLS_HARDWARE_SHA)
# target_sources(mbedcrypto PRIVATE "${COMPONENT_DIR}/port/sha/${SHA_PERIPHERAL_TYPE}/esp_sha1.c" # target_sources(mbedcrypto PRIVATE "${COMPONENT_DIR}/port/sha/${SHA_PERIPHERAL_TYPE}/esp_sha1.c"
@@ -368,8 +368,10 @@ endif()
# target_link_libraries(${COMPONENT_LIB} PRIVATE "-u mbedtls_rom_osi_functions_init") # target_link_libraries(${COMPONENT_LIB} PRIVATE "-u mbedtls_rom_osi_functions_init")
# endif() # endif()
set(TF_PSA_CRYPTO_CONFIG_FILE "mbedtls/esp_config.h" CACHE STRING "Path to the PSA Crypto configuration file")
foreach(target ${mbedtls_targets}) foreach(target ${mbedtls_targets})
target_compile_definitions(${target} PUBLIC -DMBEDTLS_CONFIG_FILE="mbedtls/esp_config.h") target_compile_definitions(${target} PUBLIC -DMBEDTLS_CONFIG_FILE="mbedtls/esp_config.h")
set_config_files_compile_definitions(${target})
if(CONFIG_COMPILER_STATIC_ANALYZER AND CMAKE_C_COMPILER_ID STREQUAL "GNU") # TODO IDF-10087 if(CONFIG_COMPILER_STATIC_ANALYZER AND CMAKE_C_COMPILER_ID STREQUAL "GNU") # TODO IDF-10087
target_compile_options(${target} PRIVATE "-fno-analyzer") target_compile_options(${target} PRIVATE "-fno-analyzer")
endif() endif()
@@ -379,6 +381,31 @@ foreach(target ${mbedtls_targets})
target_compile_options(${target} PRIVATE "-O2") target_compile_options(${target} PRIVATE "-O2")
endif() endif()
endforeach() endforeach()
target_compile_options(${COMPONENT_LIB} PRIVATE "-fno-analyzer")
if(CONFIG_COMPILER_STATIC_ANALYZER AND CMAKE_C_COMPILER_ID STREQUAL "GNU")
# Apply -fno-analyzer to all targets in mbedTLS subdirectory
get_property(all_mbedtls_targets DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/mbedtls PROPERTY BUILDSYSTEM_TARGETS)
foreach(target ${all_mbedtls_targets})
if(TARGET ${target})
# Check if target has sources or is a compilable target type
get_target_property(target_sources ${target} SOURCES)
get_target_property(target_type ${target} TYPE)
if(target_sources OR
target_type STREQUAL "STATIC_LIBRARY" OR
target_type STREQUAL "SHARED_LIBRARY" OR
target_type STREQUAL "MODULE_LIBRARY" OR
target_type STREQUAL "OBJECT_LIBRARY" OR
target_type STREQUAL "EXECUTABLE")
message(STATUS "Applying -fno-analyzer to target: ${target}")
target_compile_options(${target} PRIVATE "-fno-analyzer")
else()
message(STATUS "Skipping non-compilable target: ${target} (type: ${target_type})")
endif()
endif()
endforeach()
endif()
if(CONFIG_MBEDTLS_COMPILER_OPTIMIZATION_SIZE) if(CONFIG_MBEDTLS_COMPILER_OPTIMIZATION_SIZE)
target_compile_options(${COMPONENT_LIB} PRIVATE "-Os") target_compile_options(${COMPONENT_LIB} PRIVATE "-Os")
+1 -1
View File
@@ -20,7 +20,7 @@
#include "hal/aes_hal.h" #include "hal/aes_hal.h"
#include "hal/aes_types.h" #include "hal/aes_types.h"
#include "soc/soc_caps.h" #include "soc/soc_caps.h"
#include "mbedtls/error.h" // #include "mbedtls/error.h"
#include <string.h> #include <string.h>
+4 -3
View File
@@ -36,6 +36,7 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <sys/lock.h> #include <sys/lock.h>
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "mbedtls/aes.h" #include "mbedtls/aes.h"
#include "aes/esp_aes.h" #include "aes/esp_aes.h"
@@ -124,7 +125,7 @@ int esp_aes_xts_setkey_dec( esp_aes_xts_context *ctx,
return esp_aes_setkey( &ctx->crypt, key1, key1bits ); return esp_aes_setkey( &ctx->crypt, key1, key1bits );
} }
/* Endianess with 64 bits values */ /* Endianness with 64 bits values */
#ifndef GET_UINT64_LE #ifndef GET_UINT64_LE
#define GET_UINT64_LE(n,b,i) \ #define GET_UINT64_LE(n,b,i) \
{ \ { \
@@ -158,7 +159,7 @@ int esp_aes_xts_setkey_dec( esp_aes_xts_context *ctx,
* *
* This function multiplies a field element by x in the polynomial field * This function multiplies a field element by x in the polynomial field
* representation. It uses 64-bit word operations to gain speed but compensates * representation. It uses 64-bit word operations to gain speed but compensates
* for machine endianess and hence works correctly on both big and little * for machine endianness and hence works correctly on both big and little
* endian machines. * endian machines.
*/ */
static void esp_gf128mul_x_ble( unsigned char r[16], static void esp_gf128mul_x_ble( unsigned char r[16],
@@ -254,7 +255,7 @@ int esp_aes_crypt_xts( esp_aes_xts_context *ctx,
unsigned char *prev_output = output - 16; unsigned char *prev_output = output - 16;
/* Copy ciphertext bytes from the previous block to our output for each /* Copy ciphertext bytes from the previous block to our output for each
* byte of cyphertext we won't steal. At the same time, copy the * byte of ciphertext we won't steal. At the same time, copy the
* remainder of the input for this final round (since the loop bounds * remainder of the input for this final round (since the loop bounds
* are the same). */ * are the same). */
for ( i = 0; i < leftover; i++ ) { for ( i = 0; i < leftover; i++ ) {
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
*/ */
#include <assert.h> #include <assert.h>
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "esp_crypto_lock.h" #include "esp_crypto_lock.h"
#include "bignum_impl.h" #include "bignum_impl.h"
#include "mbedtls/bignum.h" #include "mbedtls/bignum.h"
+1 -2
View File
@@ -28,7 +28,7 @@
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/semphr.h" #include "freertos/semphr.h"
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "bignum_impl.h" #include "bignum_impl.h"
#include "mbedtls/bignum.h" #include "mbedtls/bignum.h"
@@ -463,7 +463,6 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A,
{ {
int ret; int ret;
#if defined(MBEDTLS_MPI_EXP_MOD_ALT_FALLBACK) #if defined(MBEDTLS_MPI_EXP_MOD_ALT_FALLBACK)
/* Try hardware API first and then fallback to software */
ret = esp_mpi_exp_mod( X, A, E, N, _RR ); ret = esp_mpi_exp_mod( X, A, E, N, _RR );
if( ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ) { if( ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ) {
ret = mbedtls_mpi_exp_mod_soft( X, A, E, N, _RR ); ret = mbedtls_mpi_exp_mod_soft( X, A, E, N, _RR );
+69 -43
View File
@@ -7,8 +7,12 @@
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
#include <assert.h> #include <assert.h>
#include "psa/crypto.h"
#include "hal/sha_hal.h" #include "hal/sha_hal.h"
#include "hal/sha_types.h" #include "hal/sha_types.h"
#include "psa/crypto_sizes.h"
#include "soc/soc_caps.h" #include "soc/soc_caps.h"
#include "esp_log.h" #include "esp_log.h"
@@ -41,73 +45,95 @@ void esp_sha(esp_sha_type sha_type, const unsigned char *input, size_t ilen, uns
int ret __attribute__((unused)); int ret __attribute__((unused));
assert(input != NULL && output != NULL); assert(input != NULL && output != NULL);
psa_status_t status;
psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
psa_algorithm_t alg = PSA_ALG_NONE;
#if SOC_SHA_SUPPORT_SHA1 #if SOC_SHA_SUPPORT_SHA1
if (sha_type == SHA1) { if (sha_type == SHA1) {
mbedtls_sha1_init(&ctx.sha1); alg = PSA_ALG_SHA_1;
mbedtls_sha1_starts(&ctx.sha1);
ret = mbedtls_sha1_update(&ctx.sha1, input, ilen); // mbedtls_sha1_init(&ctx.sha1);
assert(ret == 0); // mbedtls_sha1_starts(&ctx.sha1);
ret = mbedtls_sha1_finish(&ctx.sha1, output); // ret = mbedtls_sha1_update(&ctx.sha1, input, ilen);
assert(ret == 0); // assert(ret == 0);
mbedtls_sha1_free(&ctx.sha1); // ret = mbedtls_sha1_finish(&ctx.sha1, output);
return; // assert(ret == 0);
// mbedtls_sha1_free(&ctx.sha1);
// return;
} }
#endif //SOC_SHA_SUPPORT_SHA1 #endif //SOC_SHA_SUPPORT_SHA1
#if SOC_SHA_SUPPORT_SHA224 #if SOC_SHA_SUPPORT_SHA224
if (sha_type == SHA2_224) { if (sha_type == SHA2_224) {
mbedtls_sha256_init(&ctx.sha256); alg = PSA_ALG_SHA_224;
mbedtls_sha256_starts(&ctx.sha256, 1); // mbedtls_sha256_init(&ctx.sha256);
ret = mbedtls_sha256_update(&ctx.sha256, input, ilen); // mbedtls_sha256_starts(&ctx.sha256, 1);
assert(ret == 0); // ret = mbedtls_sha256_update(&ctx.sha256, input, ilen);
ret = mbedtls_sha256_finish(&ctx.sha256, output); // assert(ret == 0);
assert(ret == 0); // ret = mbedtls_sha256_finish(&ctx.sha256, output);
mbedtls_sha256_free(&ctx.sha256); // assert(ret == 0);
return; // mbedtls_sha256_free(&ctx.sha256);
// return;
} }
#endif //SOC_SHA_SUPPORT_SHA224 #endif //SOC_SHA_SUPPORT_SHA224
#if SOC_SHA_SUPPORT_SHA256 #if SOC_SHA_SUPPORT_SHA256
if (sha_type == SHA2_256) { if (sha_type == SHA2_256) {
mbedtls_sha256_init(&ctx.sha256); alg = PSA_ALG_SHA_256;
mbedtls_sha256_starts(&ctx.sha256, 0); // mbedtls_sha256_init(&ctx.sha256);
ret = mbedtls_sha256_update(&ctx.sha256, input, ilen); // mbedtls_sha256_starts(&ctx.sha256, 0);
assert(ret == 0); // ret = mbedtls_sha256_update(&ctx.sha256, input, ilen);
ret = mbedtls_sha256_finish(&ctx.sha256, output); // assert(ret == 0);
assert(ret == 0); // ret = mbedtls_sha256_finish(&ctx.sha256, output);
mbedtls_sha256_free(&ctx.sha256); // assert(ret == 0);
return; // mbedtls_sha256_free(&ctx.sha256);
// return;
} }
#endif //SOC_SHA_SUPPORT_SHA256 #endif //SOC_SHA_SUPPORT_SHA256
#if SOC_SHA_SUPPORT_SHA384 #if SOC_SHA_SUPPORT_SHA384
if (sha_type == SHA2_384) { if (sha_type == SHA2_384) {
mbedtls_sha512_init(&ctx.sha512); alg = PSA_ALG_SHA_384;
mbedtls_sha512_starts(&ctx.sha512, 1); // mbedtls_sha512_init(&ctx.sha512);
ret = mbedtls_sha512_update(&ctx.sha512, input, ilen); // mbedtls_sha512_starts(&ctx.sha512, 1);
assert(ret == 0); // ret = mbedtls_sha512_update(&ctx.sha512, input, ilen);
ret = mbedtls_sha512_finish(&ctx.sha512, output); // assert(ret == 0);
assert(ret == 0); // ret = mbedtls_sha512_finish(&ctx.sha512, output);
mbedtls_sha512_free(&ctx.sha512); // assert(ret == 0);
return; // mbedtls_sha512_free(&ctx.sha512);
// return;
} }
#endif //SOC_SHA_SUPPORT_SHA384 #endif //SOC_SHA_SUPPORT_SHA384
#if SOC_SHA_SUPPORT_SHA512 #if SOC_SHA_SUPPORT_SHA512
if (sha_type == SHA2_512) { if (sha_type == SHA2_512) {
mbedtls_sha512_init(&ctx.sha512); alg = PSA_ALG_SHA_512;
mbedtls_sha512_starts(&ctx.sha512, 0); // mbedtls_sha512_init(&ctx.sha512);
ret = mbedtls_sha512_update(&ctx.sha512, input, ilen); // mbedtls_sha512_starts(&ctx.sha512, 0);
assert(ret == 0); // ret = mbedtls_sha512_update(&ctx.sha512, input, ilen);
ret = mbedtls_sha512_finish(&ctx.sha512, output); // assert(ret == 0);
assert(ret == 0); // ret = mbedtls_sha512_finish(&ctx.sha512, output);
mbedtls_sha512_free(&ctx.sha512); // assert(ret == 0);
return; // mbedtls_sha512_free(&ctx.sha512);
// return;
} }
#endif //SOC_SHA_SUPPORT_SHA512 #endif //SOC_SHA_SUPPORT_SHA512
if (alg == PSA_ALG_NONE) {
ESP_LOGE(TAG, "SHA type %d not supported", (int)sha_type); ESP_LOGE(TAG, "SHA type %d not supported", (int)sha_type);
abort(); abort();
}
size_t olen;
size_t output_len = PSA_HASH_LENGTH(alg);
status = psa_hash_compute(alg, input, ilen, output, output_len, &olen);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "SHA computation failed, status %d", status);
abort();
}
if (olen != output_len) {
ESP_LOGE(TAG, "SHA output length mismatch, expected %u, got %u", output_len, olen);
abort();
}
} }
@@ -6,8 +6,7 @@ set(TEST_CRTS "crts/server_cert_chain.pem"
"crts/correct_sig_crt_esp32_com.pem") "crts/correct_sig_crt_esp32_com.pem")
idf_component_register( idf_component_register(
SRCS "app_main.c" SRC_DIRS "."
# SRC_DIRS "."
PRIV_INCLUDE_DIRS "." PRIV_INCLUDE_DIRS "."
PRIV_REQUIRES efuse cmock test_utils mbedtls esp_timer unity spi_flash esp_psram esp_security PRIV_REQUIRES efuse cmock test_utils mbedtls esp_timer unity spi_flash esp_psram esp_security
EMBED_TXTFILES ${TEST_CRTS} EMBED_TXTFILES ${TEST_CRTS}
@@ -5,6 +5,8 @@
*/ */
/* mbedTLS AES test /* mbedTLS AES test
*/ */
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
#include <stdbool.h> #include <stdbool.h>
@@ -8,6 +8,7 @@
#include <stdio.h> #include <stdio.h>
#include <stdbool.h> #include <stdbool.h>
#include <esp_system.h> #include <esp_system.h>
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "mbedtls/aes.h" #include "mbedtls/aes.h"
#include "mbedtls/gcm.h" #include "mbedtls/gcm.h"
#include "unity.h" #include "unity.h"
@@ -9,6 +9,7 @@
#include <stdio.h> #include <stdio.h>
#include <stdbool.h> #include <stdbool.h>
#include <esp_system.h> #include <esp_system.h>
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "mbedtls/aes.h" #include "mbedtls/aes.h"
#include "mbedtls/gcm.h" #include "mbedtls/gcm.h"
#include "unity.h" #include "unity.h"
@@ -6,6 +6,7 @@
#include <string.h> #include <string.h>
#include <stdbool.h> #include <stdbool.h>
#include <esp_system.h> #include <esp_system.h>
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "mbedtls/aes.h" #include "mbedtls/aes.h"
#include "mbedtls/sha256.h" #include "mbedtls/sha256.h"
#include "unity.h" #include "unity.h"
@@ -9,7 +9,7 @@
#include <sdkconfig.h> #include <sdkconfig.h>
#if CONFIG_IDF_TARGET_ESP32 #if CONFIG_IDF_TARGET_ESP32
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "esp_types.h" #include "esp_types.h"
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
+1 -1
View File
@@ -12,7 +12,7 @@
#include <stdbool.h> #include <stdbool.h>
#include <inttypes.h> #include <inttypes.h>
#include <esp_random.h> #include <esp_random.h>
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include <mbedtls/entropy.h> #include <mbedtls/entropy.h>
#include <mbedtls/ctr_drbg.h> #include <mbedtls/ctr_drbg.h>
#include <mbedtls/ecdh.h> #include <mbedtls/ecdh.h>
@@ -6,7 +6,7 @@
* *
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
* *
* SPDX-FileContributor: 2019-2024 Espressif Systems (Shanghai) CO LTD * SPDX-FileContributor: 2019-2025 Espressif Systems (Shanghai) CO LTD
*/ */
#include <string.h> #include <string.h>
#include "esp_err.h" #include "esp_err.h"
@@ -15,7 +15,7 @@
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
#include "freertos/semphr.h" #include "freertos/semphr.h"
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "mbedtls/entropy.h" #include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h" #include "mbedtls/ctr_drbg.h"
#include "mbedtls/x509.h" #include "mbedtls/x509.h"
@@ -115,7 +115,7 @@ esp_err_t server_setup(mbedtls_endpoint_t *server)
} }
ret = mbedtls_pk_parse_key( &server->pkey, (const unsigned char *)server_pk_start, ret = mbedtls_pk_parse_key( &server->pkey, (const unsigned char *)server_pk_start,
server_pk_end - server_pk_start, NULL, 0, myrand, NULL ); server_pk_end - server_pk_start, NULL, 0);
if ( ret != 0 ) { if ( ret != 0 ) {
ESP_LOGE(TAG, "mbedtls_pk_parse_key returned %d", ret ); ESP_LOGE(TAG, "mbedtls_pk_parse_key returned %d", ret );
return ESP_FAIL; return ESP_FAIL;
@@ -144,7 +144,7 @@ esp_err_t server_setup(mbedtls_endpoint_t *server)
return ESP_FAIL; return ESP_FAIL;
} }
mbedtls_ssl_conf_rng( &server->conf, mbedtls_ctr_drbg_random, &server->ctr_drbg ); // mbedtls_ssl_conf_rng( &server->conf, mbedtls_ctr_drbg_random, &server->ctr_drbg );
if (( ret = mbedtls_ssl_conf_own_cert( &server->conf, &server->cert, &server->pkey ) ) != 0 ) { if (( ret = mbedtls_ssl_conf_own_cert( &server->conf, &server->cert, &server->pkey ) ) != 0 ) {
ESP_LOGE(TAG, "mbedtls_ssl_conf_own_cert returned %d", ret ); ESP_LOGE(TAG, "mbedtls_ssl_conf_own_cert returned %d", ret );
@@ -251,7 +251,7 @@ esp_err_t client_setup(mbedtls_endpoint_t *client)
ESP_LOGE(TAG, "mbedtls_ssl_config_defaults returned %d", ret); ESP_LOGE(TAG, "mbedtls_ssl_config_defaults returned %d", ret);
return ESP_FAIL; return ESP_FAIL;
} }
mbedtls_ssl_conf_rng(&client->conf, mbedtls_ctr_drbg_random, &client->ctr_drbg); // mbedtls_ssl_conf_rng(&client->conf, mbedtls_ctr_drbg_random, &client->ctr_drbg);
if ((ret = mbedtls_ssl_setup(&client->ssl, &client->conf)) != 0) { if ((ret = mbedtls_ssl_setup(&client->ssl, &client->conf)) != 0) {
ESP_LOGE(TAG, "mbedtls_ssl_setup returned -0x%x", -ret); ESP_LOGE(TAG, "mbedtls_ssl_setup returned -0x%x", -ret);
@@ -266,26 +266,25 @@ void client_task(void *pvParameters)
SemaphoreHandle_t *client_signal_sem = (SemaphoreHandle_t *) pvParameters; SemaphoreHandle_t *client_signal_sem = (SemaphoreHandle_t *) pvParameters;
int ret = ESP_FAIL; int ret = ESP_FAIL;
mbedtls_endpoint_t client;
esp_crt_validate_res_t res = ESP_CRT_VALIDATE_UNKNOWN; esp_crt_validate_res_t res = ESP_CRT_VALIDATE_UNKNOWN;
if (client_setup(&client) != ESP_OK) { if (client_setup(client) != ESP_OK) {
ESP_LOGE(TAG, "SSL client setup failed"); ESP_LOGE(TAG, "SSL client setup failed");
goto exit; goto exit;
} }
/* Test with default crt bundle that does not contain the ca crt */ /* Test with default crt bundle that does not contain the ca crt */
ESP_LOGI(TAG, "Connecting to %s:%s...", SERVER_ADDRESS, SERVER_PORT); ESP_LOGI(TAG, "Connecting to %s:%s...", SERVER_ADDRESS, SERVER_PORT);
if ((ret = mbedtls_net_connect(&client.client_fd, SERVER_ADDRESS, SERVER_PORT, MBEDTLS_NET_PROTO_TCP)) != 0) { if ((ret = mbedtls_net_connect(&client->client_fd, SERVER_ADDRESS, SERVER_PORT, MBEDTLS_NET_PROTO_TCP)) != 0) {
ESP_LOGE(TAG, "mbedtls_net_connect returned -%x", -ret); ESP_LOGE(TAG, "mbedtls_net_connect returned -%x", -ret);
goto exit; goto exit;
} }
ESP_LOGI(TAG, "Connected."); ESP_LOGI(TAG, "Connected.");
mbedtls_ssl_set_bio(&client.ssl, &client.client_fd, mbedtls_net_send, mbedtls_net_recv, NULL); mbedtls_ssl_set_bio(&client->ssl, &client->client_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
ESP_LOGI(TAG, "Performing the SSL/TLS handshake with bundle that is missing the server root certificate"); ESP_LOGI(TAG, "Performing the SSL/TLS handshake with bundle that is missing the server root certificate");
while ( ( ret = mbedtls_ssl_handshake( &client.ssl ) ) != 0 ) { while ( ( ret = mbedtls_ssl_handshake( &client->ssl ) ) != 0 ) {
if ( ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE ) { if ( ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE ) {
printf( "mbedtls_ssl_handshake failed with -0x%x\n", -ret ); printf( "mbedtls_ssl_handshake failed with -0x%x\n", -ret );
break; break;
@@ -293,7 +292,7 @@ void client_task(void *pvParameters)
} }
ESP_LOGI(TAG, "Verifying peer X.509 certificate for bundle ..."); ESP_LOGI(TAG, "Verifying peer X.509 certificate for bundle ...");
ret = mbedtls_ssl_get_verify_result(&client.ssl); ret = mbedtls_ssl_get_verify_result(&client->ssl);
res = (ret == 0) ? ESP_CRT_VALIDATE_OK : ESP_CRT_VALIDATE_FAIL; res = (ret == 0) ? ESP_CRT_VALIDATE_OK : ESP_CRT_VALIDATE_FAIL;
@@ -305,25 +304,27 @@ void client_task(void *pvParameters)
TEST_ASSERT_EQUAL(ESP_CRT_VALIDATE_FAIL, res); TEST_ASSERT_EQUAL(ESP_CRT_VALIDATE_FAIL, res);
// Reset session before new connection // Reset session before new connection
mbedtls_ssl_close_notify(&client.ssl); mbedtls_ssl_close_notify(&client->ssl);
mbedtls_ssl_session_reset(&client.ssl); mbedtls_ssl_session_reset(&client->ssl);
mbedtls_net_free( &client.client_fd); mbedtls_net_free( &client->client_fd);
/* Test with bundle that does contain the CA crt */ /* Test with bundle that does contain the CA crt */
esp_crt_bundle_attach(&client.conf); esp_crt_bundle_attach(&client->conf);
esp_crt_bundle_set(server_cert_bundle_start, server_cert_bundle_end - server_cert_bundle_start); esp_crt_bundle_set(server_cert_bundle_start, server_cert_bundle_end - server_cert_bundle_start);
ESP_LOGI(TAG, "Connecting to %s:%s...", SERVER_ADDRESS, SERVER_PORT); ESP_LOGI(TAG, "Connecting to %s:%s...", SERVER_ADDRESS, SERVER_PORT);
if ((ret = mbedtls_net_connect(&client.client_fd, SERVER_ADDRESS, SERVER_PORT, MBEDTLS_NET_PROTO_TCP)) != 0) { if ((ret = mbedtls_net_connect(&client->client_fd, SERVER_ADDRESS, SERVER_PORT, MBEDTLS_NET_PROTO_TCP)) != 0) {
ESP_LOGE(TAG, "mbedtls_net_connect returned -%x", -ret); ESP_LOGE(TAG, "mbedtls_net_connect returned -%x", -ret);
goto exit; goto exit;
} }
ESP_LOGI(TAG, "Connected."); ESP_LOGI(TAG, "Connected.");
mbedtls_ssl_set_bio(&client.ssl, &client.client_fd, mbedtls_net_send, mbedtls_net_recv, NULL); mbedtls_ssl_set_bio(&client->ssl, &client->client_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
size_t available_before_handshake = uxTaskGetStackHighWaterMark(NULL);
ESP_LOGI(TAG, "Available stack before handshake: %d", available_before_handshake);
ESP_LOGI(TAG, "Performing the SSL/TLS handshake with bundle that is missing the server root certificate"); ESP_LOGI(TAG, "Performing the SSL/TLS handshake with bundle that is missing the server root certificate");
while ( ( ret = mbedtls_ssl_handshake( &client.ssl ) ) != 0 ) { while ( ( ret = mbedtls_ssl_handshake( &client->ssl ) ) != 0 ) {
if ( ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE ) { if ( ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE ) {
printf( "mbedtls_ssl_handshake failed with -0x%x\n", -ret ); printf( "mbedtls_ssl_handshake failed with -0x%x\n", -ret );
break; break;
@@ -331,7 +332,7 @@ void client_task(void *pvParameters)
} }
ESP_LOGI(TAG, "Verifying peer X.509 certificate for bundle ..."); ESP_LOGI(TAG, "Verifying peer X.509 certificate for bundle ...");
ret = mbedtls_ssl_get_verify_result(&client.ssl); ret = mbedtls_ssl_get_verify_result(&client->ssl);
res = (ret == 0) ? ESP_CRT_VALIDATE_OK : ESP_CRT_VALIDATE_FAIL; res = (ret == 0) ? ESP_CRT_VALIDATE_OK : ESP_CRT_VALIDATE_FAIL;
@@ -343,16 +344,16 @@ void client_task(void *pvParameters)
TEST_ASSERT_EQUAL(ESP_CRT_VALIDATE_OK, res); TEST_ASSERT_EQUAL(ESP_CRT_VALIDATE_OK, res);
// Reset session before new connection // Reset session before new connection
mbedtls_ssl_close_notify(&client.ssl); mbedtls_ssl_close_notify(&client->ssl);
mbedtls_ssl_session_reset(&client.ssl); mbedtls_ssl_session_reset(&client->ssl);
mbedtls_net_free( &client.client_fd); mbedtls_net_free( &client->client_fd);
exit: exit:
mbedtls_ssl_close_notify(&client.ssl); mbedtls_ssl_close_notify(&client->ssl);
mbedtls_ssl_session_reset(&client.ssl); mbedtls_ssl_session_reset(&client->ssl);
esp_crt_bundle_detach(&client.conf); esp_crt_bundle_detach(&client->conf);
endpoint_teardown(&client); endpoint_teardown(client);
xSemaphoreGive(*client_signal_sem); xSemaphoreGive(*client_signal_sem);
vTaskSuspend(NULL); vTaskSuspend(NULL);
} }
@@ -6,6 +6,7 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include "sys/param.h" #include "sys/param.h"
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "esp_heap_caps.h" #include "esp_heap_caps.h"
#include "mbedtls/gcm.h" #include "mbedtls/gcm.h"
#include "sdkconfig.h" #include "sdkconfig.h"
@@ -14,6 +14,7 @@
#include <stdio.h> #include <stdio.h>
#include <stdbool.h> #include <stdbool.h>
#include <esp_system.h> #include <esp_system.h>
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "mbedtls/sha1.h" #include "mbedtls/sha1.h"
#include "mbedtls/sha256.h" #include "mbedtls/sha256.h"
#include "mbedtls/sha512.h" #include "mbedtls/sha512.h"
@@ -9,7 +9,7 @@
#include <stdbool.h> #include <stdbool.h>
#include <inttypes.h> #include <inttypes.h>
#include <esp_log.h> #include <esp_log.h>
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include <mbedtls/entropy.h> #include <mbedtls/entropy.h>
#include <mbedtls/ctr_drbg.h> #include <mbedtls/ctr_drbg.h>
#include <mbedtls/ecdh.h> #include <mbedtls/ecdh.h>
@@ -9,6 +9,7 @@
#include <stdbool.h> #include <stdbool.h>
#include <sys/param.h> #include <sys/param.h>
#include <esp_system.h> #include <esp_system.h>
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "mbedtls/bignum.h" #include "mbedtls/bignum.h"
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
@@ -11,6 +11,7 @@
#include <stdio.h> #include <stdio.h>
#include <stdbool.h> #include <stdbool.h>
#include <esp_system.h> #include <esp_system.h>
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "mbedtls/sha1.h" #include "mbedtls/sha1.h"
#include "mbedtls/sha256.h" #include "mbedtls/sha256.h"
#include "mbedtls/sha512.h" #include "mbedtls/sha512.h"
+4 -3
View File
@@ -11,6 +11,7 @@
#include <stdbool.h> #include <stdbool.h>
#include "esp_system.h" #include "esp_system.h"
#include "esp_task_wdt.h" #include "esp_task_wdt.h"
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "mbedtls/rsa.h" #include "mbedtls/rsa.h"
#include "mbedtls/pk.h" #include "mbedtls/pk.h"
#include "mbedtls/x509_crt.h" #include "mbedtls/x509_crt.h"
@@ -508,13 +509,13 @@ static void rsa_key_operations(int keysize, bool check_performance, bool generat
switch(keysize) { switch(keysize) {
case 4096: case 4096:
res = mbedtls_pk_parse_key(&clientkey, (const uint8_t *)privkey_4096_buf, sizeof(privkey_4096_buf), NULL, 0, myrand, NULL); res = mbedtls_pk_parse_key(&clientkey, (const uint8_t *)privkey_4096_buf, sizeof(privkey_4096_buf), NULL, 0);
break; break;
case 3072: case 3072:
res = mbedtls_pk_parse_key(&clientkey, (const uint8_t *)privkey_3072_buf, sizeof(privkey_3072_buf), NULL, 0, myrand, NULL); res = mbedtls_pk_parse_key(&clientkey, (const uint8_t *)privkey_3072_buf, sizeof(privkey_3072_buf), NULL, 0);
break; break;
case 2048: case 2048:
res = mbedtls_pk_parse_key(&clientkey, (const uint8_t *)privkey_2048_buf, sizeof(privkey_2048_buf), NULL, 0, myrand, NULL); res = mbedtls_pk_parse_key(&clientkey, (const uint8_t *)privkey_2048_buf, sizeof(privkey_2048_buf), NULL, 0);
break; break;
default: default:
TEST_FAIL_MESSAGE("unsupported keysize, pass generate_new_rsa=true or update test"); TEST_FAIL_MESSAGE("unsupported keysize, pass generate_new_rsa=true or update test");
+9 -5
View File
@@ -16,7 +16,7 @@
#include "spi_flash_mmap.h" #include "spi_flash_mmap.h"
#include "soc/soc_caps.h" #include "soc/soc_caps.h"
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "unity.h" #include "unity.h"
#include "test_utils.h" #include "test_utils.h"
#include "mbedtls/sha1.h" #include "mbedtls/sha1.h"
@@ -110,11 +110,15 @@ TEST_CASE("Test esp_sha()", "[hw_crypto]")
free(buffer); free(buffer);
TEST_PERFORMANCE_CCOMP_LESS_THAN(TIME_SHA1_32KB, "%" PRId32 " us", us_sha1); // Commenting this out for now as we only have the software implementation with PSA
// This check fails because it expects the hardware implementation to be available
// and be faster than the software implementation
#if SOC_SHA_SUPPORT_SHA512 // TEST_PERFORMANCE_CCOMP_LESS_THAN(TIME_SHA1_32KB, "%" PRId32 " us", us_sha1);
TEST_PERFORMANCE_CCOMP_LESS_THAN(TIME_SHA512_32KB, "%" PRId32 " us", us_sha512);
#endif // #if SOC_SHA_SUPPORT_SHA512
// TEST_PERFORMANCE_CCOMP_LESS_THAN(TIME_SHA512_32KB, "%" PRId32 " us", us_sha512);
// #endif
} }
/* NOTE: This test attempts to mmap 1MB of flash starting from address 0x00, which overlaps /* NOTE: This test attempts to mmap 1MB of flash starting from address 0x00, which overlaps
@@ -10,6 +10,7 @@
#include <stdio.h> #include <stdio.h>
#include <stdbool.h> #include <stdbool.h>
#include <string.h> #include <string.h>
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "mbedtls/sha256.h" #include "mbedtls/sha256.h"
#include "unity.h" #include "unity.h"
#include "sdkconfig.h" #include "sdkconfig.h"
+53 -19
View File
@@ -70,7 +70,9 @@ int nvs_bootloader_aes_crypt_ecb(enum AES_TYPE mode,
} }
#endif /* CONFIG_ESP_ROM_HAS_MBEDTLS_CRYPTO_LIB */ #endif /* CONFIG_ESP_ROM_HAS_MBEDTLS_CRYPTO_LIB */
#else /* BOOTLOADER_BUILD && !CONFIG_MBEDTLS_USE_CRYPTO_ROM_IMPL_BOOTLOADER */ #else /* BOOTLOADER_BUILD && !CONFIG_MBEDTLS_USE_CRYPTO_ROM_IMPL_BOOTLOADER */
#include "mbedtls/aes.h" #include "psa/crypto.h"
static const char *TAG = "nvs_bootloader_aes";
int nvs_bootloader_aes_crypt_ecb(enum AES_TYPE mode, int nvs_bootloader_aes_crypt_ecb(enum AES_TYPE mode,
const unsigned char *key, const unsigned char *key,
@@ -78,34 +80,66 @@ int nvs_bootloader_aes_crypt_ecb(enum AES_TYPE mode,
const unsigned char input[16], const unsigned char input[16],
unsigned char output[16]) unsigned char output[16])
{ {
int ret = -1; psa_status_t status;
psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
psa_key_id_t key_id = 0;
psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
psa_set_key_algorithm(&key_attributes, PSA_ALG_ECB_NO_PADDING);
psa_set_key_type(&key_attributes, PSA_KEY_TYPE_AES);
uint16_t keybits = key_bits == AES256 ? 256 : key_bits == AES192 ? 192 : 128; uint16_t keybits = key_bits == AES256 ? 256 : key_bits == AES192 ? 192 : 128;
int mbedtls_aes_mode = mode == AES_ENC ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT; psa_set_key_bits(&key_attributes, keybits);
status = psa_import_key(&key_attributes, key, keybits / 8, &key_id);
mbedtls_aes_context ctx; if (status != PSA_SUCCESS) {
mbedtls_aes_init(&ctx); ESP_LOGE(TAG, "Failed to import key: %d", status);
return -1;
}
psa_reset_key_attributes(&key_attributes);
if (mode == AES_ENC) { if (mode == AES_ENC) {
ret = mbedtls_aes_setkey_enc(&ctx, key, keybits); status = psa_cipher_encrypt_setup(&operation, key_id, PSA_ALG_ECB_NO_PADDING);
} else { } else {
ret = mbedtls_aes_setkey_dec(&ctx, key, keybits); status = psa_cipher_decrypt_setup(&operation, key_id, PSA_ALG_ECB_NO_PADDING);
}
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "Failed to setup cipher operation: %d", status);
psa_destroy_key(key_id);
return -1;
} }
if (ret != 0) { size_t output_len = 0;
mbedtls_aes_free(&ctx); status = psa_cipher_update(&operation, input, 16, output, 16, &output_len);
return ret; if (status != PSA_SUCCESS || output_len != 16) {
ESP_LOGE(TAG, "Failed to update cipher operation: %d", status);
psa_cipher_abort(&operation);
psa_destroy_key(key_id);
return -1;
} }
ret = mbedtls_aes_crypt_ecb(&ctx, mbedtls_aes_mode, input, output); status = psa_cipher_finish(&operation, output + output_len, 16 - output_len, &output_len);
if (status != PSA_SUCCESS) {
if (ret != 0) { ESP_LOGE(TAG, "Failed to finish cipher operation: %d", status);
mbedtls_aes_free(&ctx); psa_cipher_abort(&operation);
return ret; psa_destroy_key(key_id);
return -1;
} }
mbedtls_aes_free(&ctx); if (output_len != 0) {
return ret; ESP_LOGE(TAG, "Output length mismatch: expected 0, got %zu", output_len);
psa_cipher_abort(&operation);
psa_destroy_key(key_id);
return -1;
}
status = psa_cipher_finish(&operation, output, 16, &output_len);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "Failed to finish cipher operation: %d", status);
psa_destroy_key(key_id);
return -1;
}
psa_destroy_key(key_id);
return 0;
} }
#endif /* !(BOOTLOADER_BUILD && !CONFIG_MBEDTLS_USE_CRYPTO_ROM_IMPL_BOOTLOADER) */ #endif /* !(BOOTLOADER_BUILD && !CONFIG_MBEDTLS_USE_CRYPTO_ROM_IMPL_BOOTLOADER) */
#endif /* !SOC_AES_SUPPORTED */ #endif /* !SOC_AES_SUPPORTED */
@@ -257,20 +257,26 @@ int nvs_bootloader_aes_crypt_xts(nvs_bootloader_xts_aes_context *ctx,
#endif /* CONFIG_ESP_ROM_HAS_MBEDTLS_CRYPTO_LIB */ #endif /* CONFIG_ESP_ROM_HAS_MBEDTLS_CRYPTO_LIB */
#else /* BOOTLOADER_BUILD && !CONFIG_MBEDTLS_USE_CRYPTO_ROM_IMPL_BOOTLOADER */ #else /* BOOTLOADER_BUILD && !CONFIG_MBEDTLS_USE_CRYPTO_ROM_IMPL_BOOTLOADER */
#include "mbedtls/aes.h" #include "psa/crypto.h"
static mbedtls_aes_xts_context ctx_xts; static const char *TAG = "nvs_bootloader_xts_aes";
static psa_cipher_operation_t operation;
static psa_key_id_t nvs_bootloader_xts_aes_key_id = 0;
void nvs_bootloader_xts_aes_init(nvs_bootloader_xts_aes_context *ctx) void nvs_bootloader_xts_aes_init(nvs_bootloader_xts_aes_context *ctx)
{ {
(void) ctx; (void) ctx;
mbedtls_aes_xts_init(&ctx_xts); // mbedtls_aes_xts_init(&ctx_xts);
// psa_status_t status = PSA_SUCCESS;
} }
void nvs_bootloader_xts_aes_free(nvs_bootloader_xts_aes_context *ctx) void nvs_bootloader_xts_aes_free(nvs_bootloader_xts_aes_context *ctx)
{ {
(void) ctx; (void) ctx;
mbedtls_aes_xts_free(&ctx_xts); psa_cipher_abort(&operation);
psa_destroy_key(nvs_bootloader_xts_aes_key_id);
nvs_bootloader_xts_aes_key_id = 0;
} }
int nvs_bootloader_xts_aes_setkey(nvs_bootloader_xts_aes_context *ctx, int nvs_bootloader_xts_aes_setkey(nvs_bootloader_xts_aes_context *ctx,
@@ -278,7 +284,32 @@ int nvs_bootloader_xts_aes_setkey(nvs_bootloader_xts_aes_context *ctx,
unsigned int key_bytes) unsigned int key_bytes)
{ {
(void) ctx; (void) ctx;
return mbedtls_aes_xts_setkey_dec(&ctx_xts, key, key_bytes * 8); // return mbedtls_aes_xts_setkey_dec(&ctx_xts, key, key_bytes * 8);
psa_status_t status;
psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
psa_set_key_algorithm(&key_attributes, PSA_ALG_XTS);
psa_set_key_type(&key_attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&key_attributes, key_bytes * 8);
status = psa_import_key(&key_attributes, key, key_bytes, &nvs_bootloader_xts_aes_key_id);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "Failed to import key: %d", status);
psa_cipher_abort(&operation);
return -1;
}
psa_reset_key_attributes(&key_attributes);
size_t key_len = key_bytes / 2;
status = psa_cipher_set_iv(&operation, key + key_len, key_len);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "Failed to set IV: %d", status);
psa_cipher_abort(&operation);
psa_destroy_key(nvs_bootloader_xts_aes_key_id);
return -1;
}
ESP_LOGI(TAG, "XTS-AES key set successfully");
return 0;
} }
/* /*
* XTS-AES buffer encryption/decryption * XTS-AES buffer encryption/decryption
@@ -291,9 +322,43 @@ int nvs_bootloader_aes_crypt_xts(nvs_bootloader_xts_aes_context *ctx,
unsigned char *output) unsigned char *output)
{ {
(void) ctx; (void) ctx;
psa_status_t status;
size_t output_len = 0;
if (nvs_bootloader_xts_aes_key_id == 0) {
ESP_LOGE(TAG, "XTS-AES key not set");
return -1;
}
int mbedtls_aes_mode = mode == AES_ENC ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT; if (mode == AES_ENC) {
return mbedtls_aes_crypt_xts(&ctx_xts, mbedtls_aes_mode, length, data_unit, input, output); status = psa_cipher_encrypt_setup(&operation, nvs_bootloader_xts_aes_key_id, PSA_ALG_XTS);
} else {
status = psa_cipher_decrypt_setup(&operation, nvs_bootloader_xts_aes_key_id, PSA_ALG_XTS);
}
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "Failed to setup cipher operation: %d", status);
return -1;
}
status = psa_cipher_update(&operation, input, length, output, length, &output_len);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "Failed to update cipher operation: %d", status);
psa_cipher_abort(&operation);
return -1;
}
if (output_len != length) {
ESP_LOGE(TAG, "Output length mismatch: expected %zu, got %zu", length, output_len);
psa_cipher_abort(&operation);
return -1;
}
status = psa_cipher_finish(&operation, output + output_len, length - output_len, &output_len);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "Failed to finish cipher operation: %d", status);
psa_cipher_abort(&operation);
return -1;
}
return 0;
} }
#endif /* !(BOOTLOADER_BUILD && !CONFIG_MBEDTLS_USE_CRYPTO_ROM_IMPL_BOOTLOADER) */ #endif /* !(BOOTLOADER_BUILD && !CONFIG_MBEDTLS_USE_CRYPTO_ROM_IMPL_BOOTLOADER) */
#endif /* !SOC_AES_SUPPORTED */ #endif /* !SOC_AES_SUPPORTED */
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
*/ */
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "esp_srp_mpi.h" #include "esp_srp_mpi.h"
esp_mpi_t *esp_mpi_new(void) esp_mpi_t *esp_mpi_new(void)
+114 -108
View File
@@ -1,5 +1,5 @@
/* /*
* SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD * SPDX-FileCopyrightText: 2018-2025 Espressif Systems (Shanghai) CO LTD
* *
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
*/ */
@@ -32,6 +32,7 @@
#include <mbedtls/ecdh.h> #include <mbedtls/ecdh.h>
#include <mbedtls/error.h> #include <mbedtls/error.h>
#include <mbedtls/constant_time.h> #include <mbedtls/constant_time.h>
#include "psa/crypto.h"
#include <protocomm_security.h> #include <protocomm_security.h>
#include <protocomm_security1.h> #include <protocomm_security1.h>
@@ -66,7 +67,8 @@ typedef struct session {
uint8_t rand[SZ_RANDOM]; uint8_t rand[SZ_RANDOM];
/* mbedtls context data for AES */ /* mbedtls context data for AES */
mbedtls_aes_context ctx_aes; psa_cipher_operation_t ctx_aes;
psa_key_id_t key_id;
unsigned char stb[16]; unsigned char stb[16];
size_t nc_off; size_t nc_off;
} session_t; } session_t;
@@ -94,7 +96,7 @@ static esp_err_t handle_session_command1(session_t *cur_session,
ESP_LOGD(TAG, "Request to handle setup1_command"); ESP_LOGD(TAG, "Request to handle setup1_command");
Sec1Payload *in = (Sec1Payload *) req->sec1; Sec1Payload *in = (Sec1Payload *) req->sec1;
uint8_t check_buf[PUBLIC_KEY_LEN]; uint8_t check_buf[PUBLIC_KEY_LEN];
int mbed_err; // int mbed_err;
if (cur_session->state != SESSION_STATE_CMD1) { if (cur_session->state != SESSION_STATE_CMD1) {
ESP_LOGE(TAG, "Invalid state of session %d (expected %d)", SESSION_STATE_CMD1, cur_session->state); ESP_LOGE(TAG, "Invalid state of session %d (expected %d)", SESSION_STATE_CMD1, cur_session->state);
@@ -102,38 +104,49 @@ static esp_err_t handle_session_command1(session_t *cur_session,
} }
/* Initialize crypto context */ /* Initialize crypto context */
mbedtls_aes_init(&cur_session->ctx_aes);
memset(cur_session->stb, 0, sizeof(cur_session->stb)); memset(cur_session->stb, 0, sizeof(cur_session->stb));
cur_session->nc_off = 0; cur_session->nc_off = 0;
hexdump("Client verifier", in->sc1->client_verify_data.data, hexdump("Client verifier", in->sc1->client_verify_data.data,
in->sc1->client_verify_data.len); in->sc1->client_verify_data.len);
mbed_err = mbedtls_aes_setkey_enc(&cur_session->ctx_aes, cur_session->sym_key, psa_status_t status;
sizeof(cur_session->sym_key)*8); psa_key_id_t key_id = 0;
if (mbed_err != 0) { psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
ESP_LOGE(TAG, "Failure at mbedtls_aes_setkey_enc with error code : -0x%x", -mbed_err); psa_algorithm_t alg = PSA_ALG_CTR;
mbedtls_aes_free(&cur_session->ctx_aes); psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
psa_set_key_algorithm(&key_attributes, alg);
psa_set_key_type(&key_attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&key_attributes, 128);
status = psa_import_key(&key_attributes, cur_session->sym_key, sizeof(cur_session->sym_key), &key_id);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "psa_import_key failed with status=%d", status);
return ESP_FAIL; return ESP_FAIL;
} }
psa_reset_key_attributes(&key_attributes);
mbed_err = mbedtls_aes_crypt_ctr(&cur_session->ctx_aes, status = psa_cipher_encrypt_setup(&cur_session->ctx_aes, key_id, alg);
PUBLIC_KEY_LEN, &cur_session->nc_off, if (status != PSA_SUCCESS) {
cur_session->rand, cur_session->stb, ESP_LOGE(TAG, "psa_cipher_encrypt_setup failed with status=%d", status);
in->sc1->client_verify_data.data, check_buf); psa_destroy_key(key_id);
if (mbed_err != 0) { return ESP_FAIL;
ESP_LOGE(TAG, "Failure at mbedtls_aes_crypt_ctr with error code : -0x%x", -mbed_err); }
mbedtls_aes_free(&cur_session->ctx_aes); size_t output_len = 0;
status = psa_cipher_encrypt(key_id, alg, in->sc1->client_verify_data.data,
in->sc1->client_verify_data.len, check_buf, sizeof(check_buf), &output_len);
if (status != PSA_SUCCESS || output_len != sizeof(check_buf)) {
ESP_LOGE(TAG, "psa_cipher_encrypt failed with status=%d", status);
psa_cipher_abort(&cur_session->ctx_aes);
psa_destroy_key(key_id);
return ESP_FAIL; return ESP_FAIL;
} }
hexdump("Dec Client verifier", check_buf, sizeof(check_buf)); hexdump("Dec Client verifier", check_buf, sizeof(check_buf));
/* constant time memcmp */ /* constant time memcmp */
if (mbedtls_ct_memcmp(check_buf, cur_session->device_pubkey, if (mbedtls_ct_memcmp(check_buf, cur_session->device_pubkey,
sizeof(cur_session->device_pubkey)) != 0) { sizeof(cur_session->device_pubkey)) != 0) {
ESP_LOGE(TAG, "Key mismatch. Close connection"); ESP_LOGE(TAG, "Key mismatch. Close connection");
mbedtls_aes_free(&cur_session->ctx_aes); psa_cipher_abort(&cur_session->ctx_aes);
psa_destroy_key(key_id);
if (esp_event_post(PROTOCOMM_SECURITY_SESSION_EVENT, PROTOCOMM_SECURITY_SESSION_CREDENTIALS_MISMATCH, NULL, 0, portMAX_DELAY) != ESP_OK) { if (esp_event_post(PROTOCOMM_SECURITY_SESSION_EVENT, PROTOCOMM_SECURITY_SESSION_CREDENTIALS_MISMATCH, NULL, 0, portMAX_DELAY) != ESP_OK) {
ESP_LOGE(TAG, "Failed to post credential mismatch event"); ESP_LOGE(TAG, "Failed to post credential mismatch event");
} }
@@ -146,7 +159,6 @@ static esp_err_t handle_session_command1(session_t *cur_session,
ESP_LOGE(TAG, "Error allocating memory for response1"); ESP_LOGE(TAG, "Error allocating memory for response1");
free(out); free(out);
free(out_resp); free(out_resp);
mbedtls_aes_free(&cur_session->ctx_aes);
return ESP_ERR_NO_MEM; return ESP_ERR_NO_MEM;
} }
@@ -159,20 +171,18 @@ static esp_err_t handle_session_command1(session_t *cur_session,
ESP_LOGE(TAG, "Error allocating ciphertext buffer"); ESP_LOGE(TAG, "Error allocating ciphertext buffer");
free(out); free(out);
free(out_resp); free(out_resp);
mbedtls_aes_free(&cur_session->ctx_aes);
return ESP_ERR_NO_MEM; return ESP_ERR_NO_MEM;
} }
mbed_err = mbedtls_aes_crypt_ctr(&cur_session->ctx_aes, status = psa_cipher_encrypt(key_id, alg, cur_session->client_pubkey,
PUBLIC_KEY_LEN, &cur_session->nc_off, PUBLIC_KEY_LEN, outbuf, PUBLIC_KEY_LEN, &output_len);
cur_session->rand, cur_session->stb, if (status != PSA_SUCCESS || output_len != PUBLIC_KEY_LEN) {
cur_session->client_pubkey, outbuf); ESP_LOGE(TAG, "psa_cipher_encrypt failed with status=%d", status);
if (mbed_err != 0) {
ESP_LOGE(TAG, "Failure at mbedtls_aes_crypt_ctr with error code : -0x%x", -mbed_err);
free(outbuf); free(outbuf);
free(out); free(out);
free(out_resp); free(out_resp);
mbedtls_aes_free(&cur_session->ctx_aes); psa_cipher_abort(&cur_session->ctx_aes);
psa_destroy_key(key_id);
return ESP_FAIL; return ESP_FAIL;
} }
@@ -206,7 +216,6 @@ static esp_err_t handle_session_command0(session_t *cur_session,
ESP_LOGD(TAG, "Request to handle setup0_command"); ESP_LOGD(TAG, "Request to handle setup0_command");
Sec1Payload *in = (Sec1Payload *) req->sec1; Sec1Payload *in = (Sec1Payload *) req->sec1;
esp_err_t ret; esp_err_t ret;
int mbed_err;
if (cur_session->state != SESSION_STATE_CMD0) { if (cur_session->state != SESSION_STATE_CMD0) {
ESP_LOGW(TAG, "Invalid state of session %d (expected %d). Restarting session.", ESP_LOGW(TAG, "Invalid state of session %d (expected %d). Restarting session.",
@@ -233,42 +242,23 @@ static esp_err_t handle_session_command0(session_t *cur_session,
return ESP_ERR_NO_MEM; return ESP_ERR_NO_MEM;
} }
mbedtls_ecdh_init(ctx_server); psa_status_t status;
mbedtls_ecdh_setup(ctx_server, MBEDTLS_ECP_DP_CURVE25519); psa_key_id_t key_id = 0;
mbedtls_ctr_drbg_init(ctr_drbg); psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
mbedtls_entropy_init(entropy); psa_set_key_type(&key_attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_MONTGOMERY));
psa_set_key_bits(&key_attributes, 256);
mbed_err = mbedtls_ctr_drbg_seed(ctr_drbg, mbedtls_entropy_func, psa_set_key_lifetime(&key_attributes, PSA_KEY_LIFETIME_VOLATILE);
entropy, NULL, 0); psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT);
if (mbed_err != 0) { psa_set_key_algorithm(&key_attributes, PSA_ALG_ECDH);
ESP_LOGE(TAG, "Failed at mbedtls_ctr_drbg_seed with error code : -0x%x", -mbed_err); status = psa_generate_key(&key_attributes, &key_id);
ret = ESP_FAIL; if (status != PSA_SUCCESS) {
goto exit_cmd0; ESP_LOGE(TAG, "psa_generate_key failed with status=%d", status);
psa_reset_key_attributes(&key_attributes);
return ESP_FAIL;
} }
psa_reset_key_attributes(&key_attributes);
size_t olen = 0;
mbed_err = mbedtls_ecp_group_load(ACCESS_ECDH(&ctx_server, grp), MBEDTLS_ECP_DP_CURVE25519);
if (mbed_err != 0) {
ESP_LOGE(TAG, "Failed at mbedtls_ecp_group_load with error code : -0x%x", -mbed_err);
ret = ESP_FAIL;
goto exit_cmd0;
}
mbed_err = mbedtls_ecdh_gen_public(ACCESS_ECDH(&ctx_server, grp), ACCESS_ECDH(&ctx_server, d), ACCESS_ECDH(&ctx_server, Q),
mbedtls_ctr_drbg_random, ctr_drbg);
if (mbed_err != 0) {
ESP_LOGE(TAG, "Failed at mbedtls_ecdh_gen_public with error code : -0x%x", -mbed_err);
ret = ESP_FAIL;
goto exit_cmd0;
}
mbed_err = mbedtls_mpi_write_binary(ACCESS_ECDH(&ctx_server, Q).MBEDTLS_PRIVATE(X),
cur_session->device_pubkey,
PUBLIC_KEY_LEN);
if (mbed_err != 0) {
ESP_LOGE(TAG, "Failed at mbedtls_mpi_write_binary with error code : -0x%x", -mbed_err);
ret = ESP_FAIL;
goto exit_cmd0;
}
flip_endian(cur_session->device_pubkey, PUBLIC_KEY_LEN); flip_endian(cur_session->device_pubkey, PUBLIC_KEY_LEN);
memcpy(cur_session->client_pubkey, in->sc0->client_pubkey.data, PUBLIC_KEY_LEN); memcpy(cur_session->client_pubkey, in->sc0->client_pubkey.data, PUBLIC_KEY_LEN);
@@ -278,45 +268,54 @@ static esp_err_t handle_session_command0(session_t *cur_session,
hexdump("Device pubkey", dev_pubkey, PUBLIC_KEY_LEN); hexdump("Device pubkey", dev_pubkey, PUBLIC_KEY_LEN);
hexdump("Client pubkey", cli_pubkey, PUBLIC_KEY_LEN); hexdump("Client pubkey", cli_pubkey, PUBLIC_KEY_LEN);
mbed_err = mbedtls_mpi_lset(ACCESS_ECDH(&ctx_server, Qp).MBEDTLS_PRIVATE(Z), 1); status = psa_raw_key_agreement(PSA_ALG_ECDH, key_id, cur_session->client_pubkey, PUBLIC_KEY_LEN,
if (mbed_err != 0) { cur_session->sym_key, sizeof(cur_session->sym_key), &olen);
ESP_LOGE(TAG, "Failed at mbedtls_mpi_lset with error code : -0x%x", -mbed_err); if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "psa_raw_key_agreement failed with status=%d", status);
ret = ESP_FAIL; ret = ESP_FAIL;
goto exit_cmd0; goto exit_cmd0;
} }
if (olen != sizeof(cur_session->sym_key)) {
ESP_LOGE(TAG, "psa_raw_key_agreement output length mismatch: expected %zu, got %zu",
sizeof(cur_session->sym_key), olen);
ret = ESP_FAIL;
goto exit_cmd0;
}
cur_session->key_id = key_id;
flip_endian(cur_session->client_pubkey, PUBLIC_KEY_LEN);
mbed_err = mbedtls_mpi_read_binary(ACCESS_ECDH(&ctx_server, Qp).MBEDTLS_PRIVATE(X), cli_pubkey, PUBLIC_KEY_LEN);
flip_endian(cur_session->client_pubkey, PUBLIC_KEY_LEN);
if (mbed_err != 0) {
ESP_LOGE(TAG, "Failed at mbedtls_mpi_read_binary with error code : -0x%x", -mbed_err);
ret = ESP_FAIL;
goto exit_cmd0;
}
mbed_err = mbedtls_ecdh_compute_shared(ACCESS_ECDH(&ctx_server, grp), ACCESS_ECDH(&ctx_server, z), ACCESS_ECDH(&ctx_server, Qp),
ACCESS_ECDH(&ctx_server, d), mbedtls_ctr_drbg_random, ctr_drbg);
if (mbed_err != 0) {
ESP_LOGE(TAG, "Failed at mbedtls_ecdh_compute_shared with error code : -0x%x", -mbed_err);
ret = ESP_FAIL;
goto exit_cmd0;
}
mbed_err = mbedtls_mpi_write_binary(ACCESS_ECDH(&ctx_server, z), cur_session->sym_key, PUBLIC_KEY_LEN);
if (mbed_err != 0) {
ESP_LOGE(TAG, "Failed at mbedtls_mpi_write_binary with error code : -0x%x", -mbed_err);
ret = ESP_FAIL;
goto exit_cmd0;
}
flip_endian(cur_session->sym_key, PUBLIC_KEY_LEN); flip_endian(cur_session->sym_key, PUBLIC_KEY_LEN);
if (pop != NULL && pop->data != NULL && pop->len != 0) { if (pop != NULL && pop->data != NULL && pop->len != 0) {
ESP_LOGD(TAG, "Adding proof of possession"); ESP_LOGD(TAG, "Adding proof of possession");
uint8_t sha_out[PUBLIC_KEY_LEN]; uint8_t sha_out[PUBLIC_KEY_LEN];
mbed_err = mbedtls_sha256((const unsigned char *) pop->data, pop->len, sha_out, 0); // mbed_err = mbedtls_sha256((const unsigned char *) pop->data, pop->len, sha_out, 0);
if (mbed_err != 0) { // if (mbed_err != 0) {
ESP_LOGE(TAG, "Failed at mbedtls_sha256_ret with error code : -0x%x", -mbed_err); // ESP_LOGE(TAG, "Failed at mbedtls_sha256_ret with error code : -0x%x", -mbed_err);
// ret = ESP_FAIL;
// goto exit_cmd0;
// }
psa_mac_operation_t mac_operation = PSA_MAC_OPERATION_INIT;
status = psa_mac_sign_setup(&mac_operation, key_id, PSA_ALG_SHA_256);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "psa_mac_sign_setup failed with status=%d", status);
ret = ESP_FAIL;
goto exit_cmd0;
}
status = psa_mac_update(&mac_operation, pop->data, pop->len);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "psa_mac_update failed with status=%d", status);
psa_mac_abort(&mac_operation);
ret = ESP_FAIL;
goto exit_cmd0;
}
status = psa_mac_sign_finish(&mac_operation, sha_out, sizeof(sha_out), &olen);
if (status != PSA_SUCCESS || olen != sizeof(sha_out)) {
ESP_LOGE(TAG, "psa_mac_sign_finish failed with status=%d", status);
psa_mac_abort(&mac_operation);
ret = ESP_FAIL; ret = ESP_FAIL;
goto exit_cmd0; goto exit_cmd0;
} }
@@ -328,9 +327,9 @@ static esp_err_t handle_session_command0(session_t *cur_session,
hexdump("Shared key", cur_session->sym_key, PUBLIC_KEY_LEN); hexdump("Shared key", cur_session->sym_key, PUBLIC_KEY_LEN);
mbed_err = mbedtls_ctr_drbg_random(ctr_drbg, cur_session->rand, SZ_RANDOM); status = psa_generate_random(cur_session->rand, SZ_RANDOM);
if (mbed_err != 0) { if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "Failed at mbedtls_ctr_drbg_random with error code : -0x%x", -mbed_err); ESP_LOGE(TAG, "psa_generate_random failed with status=%d", status);
ret = ESP_FAIL; ret = ESP_FAIL;
goto exit_cmd0; goto exit_cmd0;
} }
@@ -371,14 +370,6 @@ static esp_err_t handle_session_command0(session_t *cur_session,
ret = ESP_OK; ret = ESP_OK;
exit_cmd0: exit_cmd0:
mbedtls_ecdh_free(ctx_server);
free(ctx_server);
mbedtls_ctr_drbg_free(ctr_drbg);
free(ctr_drbg);
mbedtls_entropy_free(entropy);
free(entropy);
return ret; return ret;
} }
@@ -460,7 +451,17 @@ static esp_err_t sec1_close_session(protocomm_security_handle_t handle, uint32_t
if (cur_session->state == SESSION_STATE_DONE) { if (cur_session->state == SESSION_STATE_DONE) {
/* Free AES context data */ /* Free AES context data */
mbedtls_aes_free(&cur_session->ctx_aes); // mbedtls_aes_free(&cur_session->ctx_aes);
psa_status_t status = psa_destroy_key(cur_session->id);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "psa_destroy_key failed with status=%d", status);
return ESP_FAIL;
}
status = psa_cipher_abort(&cur_session->ctx_aes);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "psa_cipher_abort failed with status=%d", status);
return ESP_FAIL;
}
} }
memset(cur_session, 0, sizeof(session_t)); memset(cur_session, 0, sizeof(session_t));
@@ -537,12 +538,17 @@ static esp_err_t sec1_decrypt(protocomm_security_handle_t handle,
return ESP_ERR_NO_MEM; return ESP_ERR_NO_MEM;
} }
int ret = mbedtls_aes_crypt_ctr(&cur_session->ctx_aes, inlen, &cur_session->nc_off, psa_status_t status;
cur_session->rand, cur_session->stb, inbuf, *outbuf); size_t output_len = 0;
if (ret != 0) {
ESP_LOGE(TAG, "Failed at mbedtls_aes_crypt_ctr with error code : %d", ret); psa_algorithm_t alg = PSA_ALG_CTR;
status = psa_cipher_decrypt(cur_session->key_id, alg, inbuf, inlen, *outbuf, *outlen, &output_len);
if (status != PSA_SUCCESS || output_len != *outlen) {
ESP_LOGE(TAG, "psa_cipher_decrypt failed with status=%d", status);
free(*outbuf);
return ESP_FAIL; return ESP_FAIL;
} }
return ESP_OK; return ESP_OK;
} }
+111 -36
View File
@@ -16,6 +16,7 @@
#include <mbedtls/error.h> #include <mbedtls/error.h>
#include <mbedtls/entropy.h> #include <mbedtls/entropy.h>
#include <mbedtls/ctr_drbg.h> #include <mbedtls/ctr_drbg.h>
#include "psa/crypto.h"
#include <protocomm_security.h> #include <protocomm_security.h>
#include <protocomm_security2.h> #include <protocomm_security2.h>
@@ -65,7 +66,9 @@ typedef struct session {
uint16_t session_key_len; uint16_t session_key_len;
uint8_t iv[AES_GCM_IV_SIZE]; uint8_t iv[AES_GCM_IV_SIZE];
/* mbedtls context data for AES-GCM */ /* mbedtls context data for AES-GCM */
mbedtls_gcm_context ctx_gcm; // mbedtls_gcm_context ctx_gcm;
psa_cipher_operation_t ctx_gcm;
psa_key_id_t key_id;
esp_srp_handle_t *srp_hd; esp_srp_handle_t *srp_hd;
} session_t; } session_t;
@@ -215,7 +218,6 @@ static esp_err_t handle_session_command1(session_t *cur_session,
{ {
ESP_LOGD(TAG, "Request to handle setup1_command"); ESP_LOGD(TAG, "Request to handle setup1_command");
Sec2Payload *in = (Sec2Payload *) req->sec2; Sec2Payload *in = (Sec2Payload *) req->sec2;
int mbed_err = -0x0001;
if (cur_session->state != SESSION_STATE_CMD1) { if (cur_session->state != SESSION_STATE_CMD1) {
ESP_LOGE(TAG, "Invalid state of session %d (expected %d)", SESSION_STATE_CMD1, cur_session->state); ESP_LOGE(TAG, "Invalid state of session %d (expected %d)", SESSION_STATE_CMD1, cur_session->state);
@@ -242,24 +244,11 @@ static esp_err_t handle_session_command1(session_t *cur_session,
} }
hexdump("Device proof", device_proof, CLIENT_PROOF_LEN); hexdump("Device proof", device_proof, CLIENT_PROOF_LEN);
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_entropy_init(&entropy);
mbedtls_ctr_drbg_init(&ctr_drbg);
int ret;
ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0);
if (ret != 0) {
ESP_LOGE(TAG, "Failed to seed random number generator");
free(device_proof);
return ESP_FAIL;
}
aes_gcm_iv_t *iv = (aes_gcm_iv_t *) cur_session->iv; aes_gcm_iv_t *iv = (aes_gcm_iv_t *) cur_session->iv;
ret = mbedtls_ctr_drbg_random(&ctr_drbg, iv->session_id, SESSION_ID_LEN); psa_status_t status;
if (ret != 0) { status = psa_generate_random(iv->session_id, SESSION_ID_LEN);
ESP_LOGE(TAG, "Failed to generate random number"); if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "psa_generate_random failed with status=%d", status);
free(device_proof); free(device_proof);
return ESP_FAIL; return ESP_FAIL;
} }
@@ -269,16 +258,30 @@ static esp_err_t handle_session_command1(session_t *cur_session,
hexdump("Initialization vector", (char *)cur_session->iv, AES_GCM_IV_SIZE); hexdump("Initialization vector", (char *)cur_session->iv, AES_GCM_IV_SIZE);
/* Initialize crypto context */ /* Initialize crypto context */
mbedtls_gcm_init(&cur_session->ctx_gcm); cur_session->ctx_gcm = (psa_cipher_operation_t) {0};
psa_algorithm_t alg = PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_GCM, AES_GCM_TAG_LEN);
mbed_err = mbedtls_gcm_setkey(&cur_session->ctx_gcm, MBEDTLS_CIPHER_ID_AES, (unsigned char *)cur_session->session_key, AES_GCM_KEY_LEN); psa_key_id_t key_id = 0;
if (mbed_err != 0) { psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
ESP_LOGE(TAG, "Failure at mbedtls_gcm_setkey_enc with error code : -0x%x", -mbed_err); psa_set_key_type(&key_attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&key_attributes, AES_GCM_KEY_LEN);
psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_ENCRYPT);
psa_set_key_algorithm(&key_attributes, alg);
psa_set_key_lifetime(&key_attributes, PSA_KEY_LIFETIME_VOLATILE);
status = psa_import_key(&key_attributes, (uint8_t *)cur_session->session_key, cur_session->session_key_len, &key_id);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "psa_import_key failed with status=%d", status);
free(device_proof); free(device_proof);
mbedtls_gcm_free(&cur_session->ctx_gcm);
return ESP_FAIL; return ESP_FAIL;
} }
status = psa_cipher_encrypt_setup(&cur_session->ctx_gcm, key_id, alg);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "psa_cipher_encrypt_setup failed with status=%d", status);
free(device_proof);
return ESP_FAIL;
}
cur_session->key_id = key_id;
Sec2Payload *out = (Sec2Payload *) malloc(sizeof(Sec2Payload)); Sec2Payload *out = (Sec2Payload *) malloc(sizeof(Sec2Payload));
S2SessionResp1 *out_resp = (S2SessionResp1 *) malloc(sizeof(S2SessionResp1)); S2SessionResp1 *out_resp = (S2SessionResp1 *) malloc(sizeof(S2SessionResp1));
if (!out || !out_resp) { if (!out || !out_resp) {
@@ -286,7 +289,9 @@ static esp_err_t handle_session_command1(session_t *cur_session,
free(device_proof); free(device_proof);
free(out); free(out);
free(out_resp); free(out_resp);
mbedtls_gcm_free(&cur_session->ctx_gcm); psa_cipher_abort(&cur_session->ctx_gcm);
psa_destroy_key(key_id);
// mbedtls_gcm_free(&cur_session->ctx_gcm);
return ESP_ERR_NO_MEM; return ESP_ERR_NO_MEM;
} }
@@ -391,7 +396,14 @@ static esp_err_t sec2_close_session(protocomm_security_handle_t handle, uint32_t
if (cur_session->state == SESSION_STATE_DONE) { if (cur_session->state == SESSION_STATE_DONE) {
/* Free GCM context data */ /* Free GCM context data */
mbedtls_gcm_free(&cur_session->ctx_gcm); // mbedtls_gcm_free(&cur_session->ctx_gcm);
psa_status_t status = psa_cipher_abort(&cur_session->ctx_gcm);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "psa_cipher_abort failed with status=%d", status);
return ESP_FAIL;
}
psa_destroy_key(cur_session->key_id);
cur_session->key_id = 0;
} }
free(cur_session->username); free(cur_session->username);
@@ -482,13 +494,41 @@ static esp_err_t sec2_encrypt(protocomm_security_handle_t handle,
} }
uint8_t gcm_tag[AES_GCM_TAG_LEN]; uint8_t gcm_tag[AES_GCM_TAG_LEN];
int ret = mbedtls_gcm_crypt_and_tag(&cur_session->ctx_gcm, MBEDTLS_GCM_ENCRYPT, inlen, cur_session->iv, psa_status_t status;
AES_GCM_IV_SIZE, NULL, 0, inbuf, status = psa_cipher_set_iv(&cur_session->ctx_gcm, cur_session->iv, AES_GCM_IV_SIZE);
*outbuf, AES_GCM_TAG_LEN, gcm_tag); if (status != PSA_SUCCESS) {
if (ret != 0) { ESP_LOGE(TAG, "psa_cipher_set_iv failed with status=%d", status);
ESP_LOGE(TAG, "Failed at mbedtls_gcm_crypt_and_tag with error code : %d", ret); free(*outbuf);
return ESP_FAIL; return ESP_FAIL;
} }
size_t out_len = 0;
status = psa_cipher_update(&cur_session->ctx_gcm, inbuf, inlen, *outbuf, *outlen , &out_len);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "psa_cipher_update failed with status=%d", status);
free(*outbuf);
return ESP_FAIL;
}
if (out_len != inlen) {
ESP_LOGE(TAG, "psa_cipher_update output length mismatch: expected %zd, got %zu", inlen, out_len);
free(*outbuf);
return ESP_FAIL;
}
status = psa_cipher_finish(&cur_session->ctx_gcm, gcm_tag, AES_GCM_TAG_LEN, &out_len);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "psa_cipher_finish failed with status=%d", status);
free(*outbuf);
return ESP_FAIL;
}
if (out_len != AES_GCM_TAG_LEN) {
ESP_LOGE(TAG, "psa_cipher_finish output length mismatch: expected %d, got %zu", AES_GCM_TAG_LEN, out_len);
free(*outbuf);
return ESP_FAIL;
}
memcpy(*outbuf + inlen, gcm_tag, AES_GCM_TAG_LEN); memcpy(*outbuf + inlen, gcm_tag, AES_GCM_TAG_LEN);
/* Increment counter value for next operation */ /* Increment counter value for next operation */
@@ -531,13 +571,48 @@ static esp_err_t sec2_decrypt(protocomm_security_handle_t handle,
return ESP_ERR_NO_MEM; return ESP_ERR_NO_MEM;
} }
int ret = mbedtls_gcm_auth_decrypt(&cur_session->ctx_gcm, inlen - AES_GCM_TAG_LEN, cur_session->iv, psa_status_t status;
AES_GCM_IV_SIZE, NULL, 0, inbuf + (inlen - AES_GCM_TAG_LEN), AES_GCM_TAG_LEN, inbuf, *outbuf); status = psa_cipher_set_iv(&cur_session->ctx_gcm, cur_session->iv, AES_GCM_IV_SIZE);
if (ret != 0) { if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "Failed at mbedtls_gcm_auth_decrypt : %d", ret); ESP_LOGE(TAG, "psa_cipher_set_iv failed with status=%d", status);
free(*outbuf);
return ESP_FAIL; return ESP_FAIL;
} }
size_t out_len = 0;
status = psa_cipher_update(&cur_session->ctx_gcm, inbuf, inlen - AES_GCM_TAG_LEN, *outbuf, *outlen, &out_len);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "psa_cipher_update failed with status=%d", status);
free(*outbuf);
return ESP_FAIL;
}
if (out_len != *outlen) {
ESP_LOGE(TAG, "psa_cipher_update output length mismatch: expected %zd, got %zu", *outlen, out_len);
free(*outbuf);
return ESP_FAIL;
}
uint8_t gcm_tag[AES_GCM_TAG_LEN];
memcpy(gcm_tag, inbuf + (inlen - AES_GCM_TAG_LEN), AES_GCM_TAG_LEN);
status = psa_cipher_finish(&cur_session->ctx_gcm, gcm_tag, AES_GCM_TAG_LEN, &out_len);
if (status != PSA_SUCCESS) {
ESP_LOGE(TAG, "psa_cipher_finish failed with status=%d", status);
free(*outbuf);
return ESP_FAIL;
}
if (out_len != 0) {
ESP_LOGE(TAG, "psa_cipher_finish output length mismatch: expected 0, got %zu", out_len);
free(*outbuf);
return ESP_FAIL;
}
if (*outbuf == NULL) {
ESP_LOGE(TAG, "Output buffer is NULL");
return ESP_ERR_INVALID_ARG;
}
/* Increment counter value for next operation */ /* Increment counter value for next operation */
sec2_gcm_iv_counter_increment(cur_session->iv); sec2_gcm_iv_counter_increment(cur_session->iv);
@@ -311,13 +311,74 @@ int esp_fast_psk(const char *password, size_t password_len, const uint8_t *ssid,
} }
/* Compute the first 16 bytes of the PSK */ /* Compute the first 16 bytes of the PSK */
fast_psk_f(password, password_len, ssid, ssid_len, 2, output); // fast_psk_f(password, password_len, ssid, ssid_len, 2, output);
/* Replicate the first 16 bytes to form the second half temporarily */ // /* Replicate the first 16 bytes to form the second half temporarily */
memcpy(output + SHA1_OUTPUT_SZ, output, 32 - SHA1_OUTPUT_SZ); // memcpy(output + SHA1_OUTPUT_SZ, output, 32 - SHA1_OUTPUT_SZ);
/* Compute the second 16 bytes of the PSK */ // // /* Compute the second 16 bytes of the PSK */
fast_psk_f(password, password_len, ssid, ssid_len, 1, output); // fast_psk_f(password, password_len, ssid, ssid_len, 1, output);
/* Compute the full PSK */
psa_status_t status;
psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key_id = 0;
// Set up key attributes for password
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
psa_set_key_algorithm(&attributes, PSA_ALG_PBKDF2_HMAC(PSA_ALG_SHA_1));
psa_set_key_type(&attributes, PSA_KEY_TYPE_DERIVE);
// Import password as key
status = psa_import_key(&attributes, (uint8_t*)password, password_len, &key_id);
if (status != PSA_SUCCESS) {
printf("Failed to import key: %d\n", status);
psa_reset_key_attributes(&attributes);
return -1;
}
// Set up key derivation
status = psa_key_derivation_setup(&operation, PSA_ALG_PBKDF2_HMAC(PSA_ALG_SHA_1));
if (status != PSA_SUCCESS) {
printf("Failed to set up key derivation: %d\n", status);
goto cleanup;
}
// Set iteration count
status = psa_key_derivation_input_integer(&operation, PSA_KEY_DERIVATION_INPUT_COST, iterations);
if (status != PSA_SUCCESS) {
printf("Failed to set iteration count: %d\n", status);
goto cleanup;
}
// Add salt
status = psa_key_derivation_input_bytes(&operation, PSA_KEY_DERIVATION_INPUT_SALT,
ssid, ssid_len);
if (status != PSA_SUCCESS) {
printf("Failed to add salt: %d\n", status);
goto cleanup;
}
// Add password
status = psa_key_derivation_input_bytes(&operation, PSA_KEY_DERIVATION_INPUT_PASSWORD,
(const uint8_t*)password, password_len);
if (status != PSA_SUCCESS) {
printf("Failed to add password: %d\n", status);
goto cleanup;
}
// Generate output
status = psa_key_derivation_output_bytes(&operation, output, output_len);
if (status != PSA_SUCCESS) {
printf("Failed to generate output: %d\n", status);
goto cleanup;
}
cleanup:
psa_key_derivation_abort(&operation);
psa_destroy_key(key_id);
psa_reset_key_attributes(&attributes);
return 0; /* Success */ return 0; /* Success */
} }
@@ -14,7 +14,7 @@
#include "utils/includes.h" #include "utils/includes.h"
#include "crypto/crypto.h" #include "crypto/crypto.h"
#include "crypto/aes_wrap.h" #include "crypto/aes_wrap.h"
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include "mbedtls/ecp.h" #include "mbedtls/ecp.h"
#include "mbedtls/pk.h" #include "mbedtls/pk.h"
#include "test_utils.h" #include "test_utils.h"
@@ -1,5 +1,5 @@
/* /*
* SPDX-FileCopyrightText: 2023-2024 Espressif Systems (Shanghai) CO LTD * SPDX-FileCopyrightText: 2023-2025 Espressif Systems (Shanghai) CO LTD
* *
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
*/ */
@@ -46,22 +46,22 @@ void setUp(void)
#if CONFIG_MBEDTLS_HARDWARE_SHA #if CONFIG_MBEDTLS_HARDWARE_SHA
// Execute esp_sha operation to allocate internal SHA semaphore (in case of ESP32) // Execute esp_sha operation to allocate internal SHA semaphore (in case of ESP32)
// and initial DMA setup memory which is considered as leaked otherwise // and initial DMA setup memory which is considered as leaked otherwise
const uint8_t input_buffer[64] = {0}; // const uint8_t input_buffer[64] = {0};
uint8_t output_buffer[64]; // uint8_t output_buffer[64];
esp_sha(SHA_TYPE, input_buffer, sizeof(input_buffer), output_buffer); // esp_sha(SHA_TYPE, input_buffer, sizeof(input_buffer), output_buffer);
#endif // SOC_SHA_SUPPORTED #endif // SOC_SHA_SUPPORTED
#if CONFIG_MBEDTLS_HARDWARE_AES #if CONFIG_MBEDTLS_HARDWARE_AES
// Execute mbedtls_aes_init operation to allocate AES interrupt // Execute mbedtls_aes_init operation to allocate AES interrupt
// allocation memory which is considered as leak otherwise // allocation memory which is considered as leak otherwise
const uint8_t plaintext[16] = {0}; // const uint8_t plaintext[16] = {0};
uint8_t ciphertext[16]; // uint8_t ciphertext[16];
const uint8_t key[16] = { 0 }; // const uint8_t key[16] = { 0 };
mbedtls_aes_context ctx; // mbedtls_aes_context ctx;
mbedtls_aes_init(&ctx); // mbedtls_aes_init(&ctx);
mbedtls_aes_setkey_enc(&ctx, key, 128); // mbedtls_aes_setkey_enc(&ctx, key, 128);
mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_ENCRYPT, plaintext, ciphertext); // mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_ENCRYPT, plaintext, ciphertext);
mbedtls_aes_free(&ctx); // mbedtls_aes_free(&ctx);
#endif // SOC_AES_SUPPORTED #endif // SOC_AES_SUPPORTED
psa_crypto_init(); psa_crypto_init();