diff --git a/include/mbedtls/x509.h b/include/mbedtls/x509.h index 82cffff36a..73730dcd72 100644 --- a/include/mbedtls/x509.h +++ b/include/mbedtls/x509.h @@ -379,7 +379,8 @@ int mbedtls_x509_time_is_future(const mbedtls_x509_time *from); /** * \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_time_is_future(const mbedtls_x509_time *from); */ 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 da772b843d..f8695d4a98 100644 --- a/library/x509.c +++ b/library/x509.c @@ -1283,6 +1283,7 @@ int mbedtls_x509_get_subject_alt_name(unsigned char **p, 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 @@ int mbedtls_x509_parse_subject_alt_name(const mbedtls_x509_buf *san_buf, 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 @@ int mbedtls_x509_info_subject_alt_name(char **buf, size_t *size, 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 @@ int mbedtls_x509_info_subject_alt_name(char **buf, size_t *size, 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 abdc5aafc8..29c05745ad 100644 --- a/tests/suites/test_suite_x509parse.function +++ b/tests/suites/test_suite_x509parse.function @@ -461,7 +461,9 @@ void x509_parse_san(char *crt_file, char *result_str) * 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; }