Fix bug in mbedtls_asn1_store_named_data()
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 <manuel.pegourie-gonnard@arm.com>
diff --git a/library/asn1write.c b/library/asn1write.c
index 775a9ef..415357b 100644
--- a/library/asn1write.c
+++ b/library/asn1write.c
@@ -412,6 +412,7 @@
} 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 7bd5e74..56af0ce 100644
--- a/tests/suites/test_suite_x509write.data
+++ b/tests/suites/test_suite_x509write.data
@@ -269,11 +269,11 @@
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