From a47b82c20a40ea486886f4b60ab699c5daf0d3a0 Mon Sep 17 00:00:00 2001 From: Waleed Elmelegy Date: Wed, 13 Nov 2024 13:11:47 +0000 Subject: [PATCH] Fix issue exporting generated key to raw intermediate buffer * Used bignum helper API instead of memcpy * changed the key length output to the size of the curve because: - using the bignum produces a bigger size than the curve size due to the limb size being 8 bytes and import key rejects the key if it's not exactly curve size. - we know that the generated key is filled with leading zeros becuase the generated key is bounded by the modulas. * skipped leading zeros when passing the buffer to import_key() due to the intermediate buffer allocated to the maximum size possible and import_key() needs the exact size. Signed-off-by: Waleed Elmelegy --- tf-psa-crypto/core/psa_crypto.c | 7 +++++-- tf-psa-crypto/drivers/builtin/src/psa_crypto_ecp.c | 6 ++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/tf-psa-crypto/core/psa_crypto.c b/tf-psa-crypto/core/psa_crypto.c index 40617b4cd9..5a11b2b57d 100644 --- a/tf-psa-crypto/core/psa_crypto.c +++ b/tf-psa-crypto/core/psa_crypto.c @@ -8192,12 +8192,15 @@ psa_status_t psa_generate_key_iop_complete( } status = mbedtls_psa_generate_key_iop_complete(&operation->ctx, key_data, - MBEDTLS_ECP_MAX_BYTES, &key_len); + sizeof(key_data), &key_len); if (status != PSA_SUCCESS) { goto exit; } - status = psa_import_key(&operation->attributes, key_data, key_len, key); + status = psa_import_key(&operation->attributes, + key_data + (sizeof(key_data) - key_len), + key_len, + key); exit: if (status != PSA_OPERATION_INCOMPLETE) { diff --git a/tf-psa-crypto/drivers/builtin/src/psa_crypto_ecp.c b/tf-psa-crypto/drivers/builtin/src/psa_crypto_ecp.c index cce993cf6e..82e873680e 100644 --- a/tf-psa-crypto/drivers/builtin/src/psa_crypto_ecp.c +++ b/tf-psa-crypto/drivers/builtin/src/psa_crypto_ecp.c @@ -634,11 +634,13 @@ psa_status_t mbedtls_psa_generate_key_iop_complete( operation->num_ops = 1; - *key_len = operation->ecp.d.n * sizeof(mbedtls_mpi_uint); + *key_len = PSA_BITS_TO_BYTES(operation->ecp.grp.nbits); + if (*key_len > key_output_size) { return PSA_ERROR_BUFFER_TOO_SMALL; } - memcpy(key_output, operation->ecp.d.p, *key_len); + + mbedtls_mpi_write_binary(&operation->ecp.d, key_output, key_output_size); return mbedtls_to_psa_error(status); }