From 07c5ea348c27642976d6adc5756c621a6a981f78 Mon Sep 17 00:00:00 2001
From: Przemek Stekiel <przemyslaw.stekiel@mobica.com>
Date: Tue, 7 Mar 2023 15:43:38 +0100
Subject: [PATCH] Add check for buffer overflow and fix style.

Signed-off-by: Przemek Stekiel <przemyslaw.stekiel@mobica.com>
---
 library/x509write_csr.c | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)

diff --git a/library/x509write_csr.c b/library/x509write_csr.c
index 45e9187766..ca0f88ca9d 100644
--- a/library/x509write_csr.c
+++ b/library/x509write_csr.c
@@ -141,14 +141,10 @@ int mbedtls_x509write_csr_set_subject_alternative_name(mbedtls_x509write_csr *ct
             case MBEDTLS_X509_SAN_IP_ADDRESS:
                 MBEDTLS_ASN1_CHK_CLEANUP_ADD(len,
                                              mbedtls_asn1_write_raw_buffer(&p, buf,
-                                                                           (const unsigned char *)
-                                                                           cur->node.san.
-                                                                           unstructured_name.p,
-                                                                           cur->node.san.
-                                                                           unstructured_name.len));
+                                                                           (const unsigned char *) cur->node.san.unstructured_name.p,
+                                                                           cur->node.san.unstructured_name.len));
                 MBEDTLS_ASN1_CHK_CLEANUP_ADD(len, mbedtls_asn1_write_len(&p, buf,
-                                                                         cur->node.san.
-                                                                         unstructured_name.len));
+                                                                         cur->node.san.unstructured_name.len));
                 MBEDTLS_ASN1_CHK_CLEANUP_ADD(len,
                                              mbedtls_asn1_write_tag(&p, buf,
                                                                     MBEDTLS_ASN1_CONTEXT_SPECIFIC |
@@ -175,6 +171,12 @@ int mbedtls_x509write_csr_set_subject_alternative_name(mbedtls_x509write_csr *ct
         buf + buflen - len,
         len);
 
+    /* If we exceeded the allocated buffer it means that maximum size of the SubjectAltName list
+     * was incorrectly calculated and memory is corrupted. */
+    if ( p < buf ) {
+        ret = MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
+    }
+
 cleanup:
     mbedtls_free(buf);
     return ret;