From 5f0c6e82fb88049569b7d1f87f4cfd120c80c689 Mon Sep 17 00:00:00 2001 From: Andrzej Kurek Date: Mon, 27 Feb 2023 16:03:41 -0500 Subject: [PATCH] Add missing deallocation of subject alt name Since mbedtls_x509_get_name allocates memory when parsing a directoryName, deallocation has to be performed if anything fails in the meantime. Signed-off-by: Andrzej Kurek --- include/mbedtls/x509.h | 6 ++++-- library/x509.c | 7 ++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/include/mbedtls/x509.h b/include/mbedtls/x509.h index 73730dcd72..0cb8aa08c6 100644 --- a/include/mbedtls/x509.h +++ b/include/mbedtls/x509.h @@ -379,8 +379,10 @@ int mbedtls_x509_time_is_future(const mbedtls_x509_time *from); /** * \brief This function parses an item in the SubjectAlternativeNames - * extension. Please note that mbedtls_x509_free_subject_alt_name - * has to be called to dispose of the structure afterwards. + * extension. Please note that this function might allocate + * additional memory for a subject alternative name, thus + * 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. diff --git a/library/x509.c b/library/x509.c index 4b4e1b6d6e..c9524c958e 100644 --- a/library/x509.c +++ b/library/x509.c @@ -1590,10 +1590,15 @@ int mbedtls_x509_info_subject_alt_name(char **buf, size_t *size, case MBEDTLS_X509_SAN_DIRECTORY_NAME: { ret = mbedtls_snprintf(p, n, "\n%s directoryName : ", prefix); + if (ret < 0 || (size_t) ret >= n) { + mbedtls_x509_free_subject_alt_name(&san); + } + MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_dn_gets(p, n, &san.san.directory_name); if (ret < 0) { + mbedtls_x509_free_subject_alt_name(&san); return ret; } @@ -1611,7 +1616,7 @@ int mbedtls_x509_info_subject_alt_name(char **buf, size_t *size, } /* So far memory is freed only in the case of directoryName - * parsing succeeding, as mbedtls_x509_dn_gets allocates memory. */ + * parsing succeeding, as mbedtls_x509_get_name allocates memory. */ mbedtls_x509_free_subject_alt_name(&san); cur = cur->next; }