From 2df7ab7c0c3d5bb8a31481073c494521d10d4eba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9gouri=C3=A9-Gonnard?= Date: Mon, 26 May 2025 10:42:14 +0200 Subject: [PATCH] Fix bug in mbedtls_asn1_store_named_data() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When passed a zero-length val, the function was free-ing the buffer as the documentation suggests: * \param val_len The minimum length of the data buffer needed. * If this is 0, do not allocate a buffer for the associated * data. * If the OID was already present, enlarge, shrink or free * the existing buffer to fit \p val_len. However it kept the previous length, leaving the val structure in the corresponding item in the output list in an inconsistent state: p == NULL but len != 0 As a result, functions that would try using this item in the list (including the same function!) afterwards would trip an dereference the NULL pointer. Signed-off-by: Manuel Pégourié-Gonnard --- library/asn1write.c | 1 + tests/suites/test_suite_x509write.data | 8 ++++---- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/library/asn1write.c b/library/asn1write.c index 775a9ef530..415357b7b5 100644 --- a/library/asn1write.c +++ b/library/asn1write.c @@ -412,6 +412,7 @@ mbedtls_asn1_named_data *mbedtls_asn1_store_named_data( } else if (val_len == 0) { mbedtls_free(cur->val.p); cur->val.p = NULL; + cur->val.len = 0; } else if (cur->val.len != val_len) { /* * Enlarge existing value buffer if needed diff --git a/tests/suites/test_suite_x509write.data b/tests/suites/test_suite_x509write.data index 7bd5e74e1f..56af0ce8a8 100644 --- a/tests/suites/test_suite_x509write.data +++ b/tests/suites/test_suite_x509write.data @@ -269,11 +269,11 @@ mbedtls_x509_string_to_names:"CN=ab,CN=cd,CN=ef":"CN=ef":0:0 X509 String to Names (repeated OID, 1st is zero-length) mbedtls_x509_string_to_names:"CN=#0400,CN=cd,CN=ef":"CN=ef":0:0 -#X509 String to Names (repeated OID, middle is zero-length) -#mbedtls_x509_string_to_names:"CN=ab,CN=#0400,CN=ef":"CN=ef":0:0 +X509 String to Names (repeated OID, middle is zero-length) +mbedtls_x509_string_to_names:"CN=ab,CN=#0400,CN=ef":"CN=ef":0:0 -#X509 String to Names (repeated OID, last is zero-length) -#mbedtls_x509_string_to_names:"CN=ab,CN=cd,CN=#0400":"CN=ef":0:0 +X509 String to Names (repeated OID, last is zero-length) +mbedtls_x509_string_to_names:"CN=ab,CN=cd,CN=#0400":"CN=#0000":0:MAY_FAIL_GET_NAME X509 Round trip test (Escaped characters) mbedtls_x509_string_to_names:"CN=Lu\\C4\\8Di\\C4\\87, O=Offspark, OU=PolarSSL":"CN=Lu\\C4\\8Di\\C4\\87, O=Offspark, OU=PolarSSL":0:0