Introduce proper memory management for SANs
DirectoryName parsing performs allocation that has to be handled.
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
diff --git a/include/mbedtls/x509.h b/include/mbedtls/x509.h
index 82cffff..73730dc 100644
--- a/include/mbedtls/x509.h
+++ b/include/mbedtls/x509.h
@@ -379,7 +379,8 @@
/**
* \brief This function parses an item in the SubjectAlternativeNames
- * extension.
+ * extension. Please note that mbedtls_x509_free_subject_alt_name
+ * has to be called to dispose of the structure afterwards.
*
* \param san_buf The buffer holding the raw data item of the subject
* alternative name.
@@ -407,6 +408,12 @@
*/
int mbedtls_x509_parse_subject_alt_name(const mbedtls_x509_buf *san_buf,
mbedtls_x509_subject_alternative_name *san);
+/**
+ * \brief Unallocate all data related to subject alternative name
+ *
+ * \param san SAN structure to free
+ */
+void mbedtls_x509_free_subject_alt_name(mbedtls_x509_subject_alternative_name *san);
/** \} addtogroup x509_module */
diff --git a/library/x509.c b/library/x509.c
index da772b8..f8695d4 100644
--- a/library/x509.c
+++ b/library/x509.c
@@ -1283,6 +1283,7 @@
return ret;
}
+ mbedtls_x509_free_subject_alt_name(&dummy_san_buf);
/* Allocate and assign next pointer */
if (cur->buf.p != NULL) {
if (cur->next != NULL) {
@@ -1467,6 +1468,13 @@
return 0;
}
+void mbedtls_x509_free_subject_alt_name(mbedtls_x509_subject_alternative_name *san)
+{
+ if (san->type == MBEDTLS_X509_SAN_DIRECTORY_NAME) {
+ mbedtls_asn1_free_named_data_list_shallow(san->san.directory_name.next);
+ }
+}
+
#if !defined(MBEDTLS_X509_REMOVE_INFO)
int mbedtls_x509_info_subject_alt_name(char **buf, size_t *size,
const mbedtls_x509_sequence
@@ -1586,6 +1594,7 @@
ret = mbedtls_snprintf(p, n, "\n%s directoryName : ", prefix);
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_dn_gets(p, n, &san.san.directory_name);
+
if (ret < 0) {
return ret;
}
@@ -1603,6 +1612,9 @@
break;
}
+ /* So far memory is freed only in the case of directoryName
+ * parsing succeeding, as mbedtls_x509_dn_gets allocates memory. */
+ mbedtls_x509_free_subject_alt_name(&san);
cur = cur->next;
}
diff --git a/tests/suites/test_suite_x509parse.function b/tests/suites/test_suite_x509parse.function
index abdc5aa..29c0574 100644
--- a/tests/suites/test_suite_x509parse.function
+++ b/tests/suites/test_suite_x509parse.function
@@ -461,7 +461,9 @@
* If san type not supported, ignore.
*/
if (ret == 0) {
- TEST_ASSERT(verify_parse_san(&san, &p, &n) == 0);
+ ret = verify_parse_san(&san, &p, &n);
+ mbedtls_x509_free_subject_alt_name(&san);
+ TEST_EQUAL(ret, 0);
}
cur = cur->next;
}