Store the PEM certificate in a dynamically allocated buffer
[privoxy.git] / ssl.c
diff --git a/ssl.c b/ssl.c
index b253e19..e07397f 100644 (file)
--- a/ssl.c
+++ b/ssl.c
@@ -1707,6 +1707,7 @@ static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
    struct certs_chain  *last = &(csp->server_certs_chain);
    size_t olen = 0;
    int ret = 0;
    struct certs_chain  *last = &(csp->server_certs_chain);
    size_t olen = 0;
    int ret = 0;
+   size_t pem_buffer_length;
 
    /*
     * Searching for last item in certificates linked list
 
    /*
     * Searching for last item in certificates linked list
@@ -1722,14 +1723,33 @@ static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
    last->next = malloc_or_die(sizeof(struct certs_chain));
    last->next->next = NULL;
    memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
    last->next = malloc_or_die(sizeof(struct certs_chain));
    last->next->next = NULL;
    memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
-   memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
+   last->next->file_buf = NULL;
+
+   ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, crt->raw.p,
+      crt->raw.len, NULL, 0, &olen);
+   if (MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL != ret)
+   {
+      log_error(LOG_LEVEL_ERROR,
+         "Failed to figure out the required X509 PEM certificate buffer size");
+      return -1;
+   }
+   pem_buffer_length = olen;
+
+   last->file_buf = malloc(pem_buffer_length);
+   if (last->file_buf == NULL)
+   {
+      log_error(LOG_LEVEL_ERROR,
+         "Failed to allocate %lu bytes to store the X509 PEM certificate",
+         pem_buffer_length);
+      return -1;
+   }
 
    /*
     * Saving certificate file into buffer
     */
    if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
       crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
 
    /*
     * Saving certificate file into buffer
     */
    if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
       crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
-      sizeof(last->file_buf)-1, &olen)) != 0)
+      pem_buffer_length, &olen)) != 0)
    {
       char err_buf[ERROR_BUF_SIZE];
 
    {
       char err_buf[ERROR_BUF_SIZE];