From 9b9b5a52d95c476a66e441706a38e98631c6990e Mon Sep 17 00:00:00 2001 From: Valerio Setti Date: Mon, 29 Jan 2024 16:53:03 +0100 Subject: [PATCH] psa_util: some code improvement to convert_der_to_raw_single_int() This commit also fixes test_suite_psa_crypto_util.data due to the change in one of the return values. Signed-off-by: Valerio Setti --- library/psa_util.c | 10 +++++++--- tests/suites/test_suite_psa_crypto_util.data | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/library/psa_util.c b/library/psa_util.c index 9e21602f6..034987312 100644 --- a/library/psa_util.c +++ b/library/psa_util.c @@ -494,7 +494,7 @@ static int convert_der_to_raw_single_int(unsigned char *der, size_t der_len, } /* Skip possible leading zero */ - if (*p == 0x00) { + if ((*p == 0x00) && (unpadded_len > 0)) { p++; unpadded_len--; /* It should never happen that the input number is all zeros. */ @@ -503,9 +503,13 @@ static int convert_der_to_raw_single_int(unsigned char *der, size_t der_len, } } - if (unpadded_len < coordinate_size) { + if (unpadded_len > coordinate_size) { + /* Parsed number is longer than the maximum expected value. */ + return MBEDTLS_ERR_ASN1_INVALID_DATA; + } else { padding_len = coordinate_size - unpadded_len; - memset(raw, 0x00, padding_len); + /* raw buffer was already zeroed in mbedtls_ecdsa_der_to_raw() so + * zero-padding operation is skipped here. */ } memcpy(raw + padding_len, p, unpadded_len); p += unpadded_len; diff --git a/tests/suites/test_suite_psa_crypto_util.data b/tests/suites/test_suite_psa_crypto_util.data index 45a3cb565..40f639160 100644 --- a/tests/suites/test_suite_psa_crypto_util.data +++ b/tests/suites/test_suite_psa_crypto_util.data @@ -52,7 +52,7 @@ ecdsa_der_to_raw:256:"3044021911111111111111111111111111111111111111111111111111 ECDSA DER -> Raw, 256bit, Wrong r integer length (too large) depends_on:PSA_WANT_ECC_SECP_K1_256 -ecdsa_der_to_raw:256:"30440221111111111111111111111111111111111111111111111111111111111111111102202222222222222222222222222222222222222222222222222222222222222222":"11111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222":MBEDTLS_ERR_ASN1_UNEXPECTED_TAG +ecdsa_der_to_raw:256:"30440221111111111111111111111111111111111111111111111111111111111111111102202222222222222222222222222222222222222222222222222222222222222222":"11111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222":MBEDTLS_ERR_ASN1_INVALID_DATA ECDSA DER -> Raw, 256bit, Wrong s integer length (too small) depends_on:PSA_WANT_ECC_SECP_K1_256