CVE-2024-29195: Insufficient Information (NVD-CWE-noinfo)
value: The azure-c-shared-utility is a C library for AMQP/MQTT communication to Azure Cloud Services. This library may be used by the Azure IoT C SDK for communication between IoT Hub and IoT Hub devices. An attacker can cause an integer wraparound or under-allocation or heap buffer overflow due to vulnerabilities in parameter checking mechanism, by exploiting the buffer length parameter in Azure C SDK, which may lead to remote code execution. Requirements for RCE are 1. Compromised Azure account allowing malformed payloads to be sent to the device via IoT Hub service, 2. By passing IoT hub service max message payload limit of 128KB, and 3. Ability to overwrite code space with remote code. Fixed in commit https://github.com/Azure/azure-c-shared-utility/commit/1129147c38ac02ad974c4c701a1e01b2141b9fe2.
CWE description: There is insufficient information about the issue to classify it; details are unkown or unspecified.
Published: 2024-03-26T03:15Z
Repository: https://github.com/Azure/azure-c-shared-utility
Language: C
Files changed: adapters/httpapi_compact.c, adapters/httpapi_curl.c, adapters/httpapi_tirtos.c, adapters/httpapi_winhttp.c, adapters/socketio_berkeley.c, adapters/socketio_win32.c, adapters/string_utils.c, adapters/tlsio_mbedtls.c, adapters/tlsio_openssl.c, adapters/tlsio_schannel.c, adapters/tlsio_wolfssl.c, adapters/x509_schannel.c, inc/azure_c_shared_utility/xlogging.h, src/buffer.c, src/constbuffer.c
Commit date: 2024-01-26 14:37:39 -0800
Commit message: Add malloc size checks (#652)

* Add malloc size checks

* Update adapters/socketio_berkeley.c

Co-authored-by: Valerie Avva Lim <54871851+vaavva@users.noreply.github.com>

* Update adapters/string_utils.c

Co-authored-by: Valerie Avva Lim <54871851+vaavva@users.noreply.github.com>

* PR review

---------

Co-authored-by: Valerie Avva Lim <54871851+vaavva@users.noreply.github.com>
Diff: diff --git a/adapters/httpapi_compact.c b/adapters/httpapi_compact.c
index 23c0ce74..feca4a27 100644
--- a/adapters/httpapi_compact.c
+++ b/adapters/httpapi_compact.c
@@ -16,10 +16,11 @@
 #include "azure_c_shared_utility/platform.h"
 #include "azure_c_shared_utility/tlsio.h"
 #include "azure_c_shared_utility/threadapi.h"
 #include "azure_c_shared_utility/shared_util_options.h"
 #include "azure_c_shared_utility/http_proxy_io.h"
+#include "azure_c_shared_utility/safe_math.h"
 
 #ifdef _MSC_VER
 #define snprintf _snprintf
 #endif
 
@@ -429,11 +430,22 @@ static void on_bytes_received(void* context, const unsigned char* buffer, size_t
             LogError("NULL pointer error");
         }
         else
         {
             /* Here we got some bytes so we'll buffer them so the receive functions can consumer it */
-            new_received_bytes = (unsigned char*)realloc(http_instance->received_bytes, http_instance->received_bytes_count + size);
+            size_t malloc_size = http_instance->received_bytes_count + size;
+            if (malloc_size < size)
+            {
+                // check for int overflow
+                new_received_bytes = NULL;
+                LogError("Invalid size parameter");
+            }
+            else
+            {
+                new_received_bytes = (unsigned char*)realloc(http_instance->received_bytes, malloc_size);
+            }
+
             if (new_received_bytes == NULL)
             {
                 http_instance->is_io_error = 1;
                 LogError("Error allocating memory for received data");
             }
@@ -1299,19 +1311,29 @@ HTTPAPI_RESULT HTTPAPI_SetOption(HTTP_HANDLE handle, const char* optionName, con
     {
 #ifdef DO_NOT_COPY_TRUSTED_CERTS_STRING
         result = HTTPAPI_OK;
         http_instance->certificate = (char*)value;
 #else
-        int len;
 
         if (http_instance->certificate)
         {
             free(http_instance->certificate);
         }
 
-        len = (int)strlen((char*)value);
-        http_instance->certificate = (char*)malloc((len + 1) * sizeof(char));
+        size_t len = strlen((char*)value);
+        size_t malloc_size = safe_add_size_t(len, 1);
+        malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
+        if (malloc_size == SIZE_MAX)
+        {
+            LogError("Invalid malloc size");
+            http_instance->certificate = NULL;
+        }
+        else
+        {
+            http_instance->certificate = (char*)malloc(malloc_size);
+        }
+
         if (http_instance->certificate == NULL)
         {
             /*Codes_SRS_HTTPAPI_COMPACT_21_062: [ If any memory allocation get fail, the HTTPAPI_SetOption shall return HTTPAPI_ALLOC_FAILED. ]*/
             result = HTTPAPI_ALLOC_FAILED;
             LogInfo("unable to allocate memory for the certificate in HTTPAPI_SetOption");
@@ -1324,18 +1346,28 @@ HTTPAPI_RESULT HTTPAPI_SetOption(HTTP_HANDLE handle, const char* optionName, con
         }
 #endif // DO_NOT_COPY_TRUSTED_CERTS_STRING
     }
     else if (strcmp(SU_OPTION_X509_CERT, optionName) == 0 || strcmp(OPTION_X509_ECC_CERT, optionName) == 0)
     {
-        int len;
         if (http_instance->x509ClientCertificate)
         {
             free(http_instance->x509ClientCertificate);
         }
 
-        len = (int)strlen((char*)value);
-        http_instance->x509ClientCertificate = (char*)malloc((len + 1) * sizeof(char));
+        size_t len = strlen((char*)value);
+        size_t malloc_size = safe_add_size_t(len, 1);
+        malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
+        if (malloc_size == SIZE_MAX)
+        {
+            LogError("Invalid malloc size");
+            http_instance->x509ClientCertificate = NULL;
+        }
+        else
+        {
+            http_instance->x509ClientCertificate = (char*)malloc(malloc_size);
+        }
+
         if (http_instance->x509ClientCertificate == NULL)
         {
             /*Codes_SRS_HTTPAPI_COMPACT_21_062: [ If any memory allocation get fail, the HTTPAPI_SetOption shall return HTTPAPI_ALLOC_FAILED. ]*/
             result = HTTPAPI_ALLOC_FAILED;
             LogInfo("unable to allocate memory for the client certificate in HTTPAPI_SetOption");
@@ -1347,18 +1379,28 @@ HTTPAPI_RESULT HTTPAPI_SetOption(HTTP_HANDLE handle, const char* optionName, con
             result = HTTPAPI_OK;
         }
     }
     else if (strcmp(SU_OPTION_X509_PRIVATE_KEY, optionName) == 0 || strcmp(OPTION_X509_ECC_KEY, optionName) == 0)
     {
-        int len;
         if (http_instance->x509ClientPrivateKey)
         {
             free(http_instance->x509ClientPrivateKey);
         }
 
-        len = (int)strlen((char*)value);
-        http_instance->x509ClientPrivateKey = (char*)malloc((len + 1) * sizeof(char));
+        size_t len = strlen((char*)value);
+        size_t malloc_size = safe_add_size_t(len, 1);
+        malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
+        if (malloc_size == SIZE_MAX)
+        {
+            LogError("Invalid malloc size");
+            http_instance->x509ClientPrivateKey = NULL;
+        }
+        else
+        {
+            http_instance->x509ClientPrivateKey = (char*)malloc(malloc_size);
+        }
+
         if (http_instance->x509ClientPrivateKey == NULL)
         {
             /*Codes_SRS_HTTPAPI_COMPACT_21_062: [ If any memory allocation get fail, the HTTPAPI_SetOption shall return HTTPAPI_ALLOC_FAILED. ]*/
             result = HTTPAPI_ALLOC_FAILED;
             LogInfo("unable to allocate memory for the client private key in HTTPAPI_SetOption");
@@ -1480,11 +1522,21 @@ HTTPAPI_RESULT HTTPAPI_CloneOption(const char* optionName, const void* value, co
 #ifdef DO_NOT_COPY_TRUSTED_CERTS_STRING
         *savedValue = (const void*)value;
         result = HTTPAPI_OK;
 #else
         certLen = strlen((const char*)value);
-        tempCert = (char*)malloc((certLen + 1) * sizeof(char));
+        size_t malloc_size = safe_add_size_t(certLen, 1);
+        malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
+        if (malloc_size == SIZE_MAX)
+        {
+            tempCert = NULL;
+        }
+        else
+        {
+            tempCert = (char*)malloc(malloc_size);
+        }
+
         if (tempCert == NULL)
         {
             /*Codes_SRS_HTTPAPI_COMPACT_21_070: [ If any memory allocation get fail, the HTTPAPI_CloneOption shall return HTTPAPI_ALLOC_FAILED. ]*/
             result = HTTPAPI_ALLOC_FAILED;
         }
@@ -1498,11 +1550,22 @@ HTTPAPI_RESULT HTTPAPI_CloneOption(const char* optionName, const void* value, co
 #endif // DO_NOT_COPY_TRUSTED_CERTS_STRING
     }
     else if (strcmp(SU_OPTION_X509_CERT, optionName) == 0 || strcmp(OPTION_X509_ECC_CERT, optionName) == 0)
     {
         certLen = strlen((const char*)value);
-        tempCert = (char*)malloc((certLen + 1) * sizeof(char));
+        size_t malloc_size = safe_add_size_t(certLen, 1);
+        malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
+        if (malloc_size == SIZE_MAX)
+        {
+            LogError("Invalid malloc size");
+            tempCert = NULL;
+        }
+        else
+        {
+            tempCert = (char*)malloc(malloc_size);
+        }
+
         if (tempCert == NULL)
         {
             /*Codes_SRS_HTTPAPI_COMPACT_21_070: [ If any memory allocation get fail, the HTTPAPI_CloneOption shall return HTTPAPI_ALLOC_FAILED. ]*/
             result = HTTPAPI_ALLOC_FAILED;
         }
@@ -1515,11 +1578,22 @@ HTTPAPI_RESULT HTTPAPI_CloneOption(const char* optionName, const void* value, co
         }
     }
     else if (strcmp(SU_OPTION_X509_PRIVATE_KEY, optionName) == 0 || strcmp(OPTION_X509_ECC_KEY, optionName) == 0)
     {
         certLen = strlen((const char*)value);
-        tempCert = (char*)malloc((certLen + 1) * sizeof(char));
+        size_t malloc_size = safe_add_size_t(certLen, 1);
+        malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
+        if (malloc_size == SIZE_MAX)
+        {
+            LogError("Invalid malloc size");
+            tempCert = NULL;
+        }
+        else
+        {
+            tempCert = (char*)malloc(malloc_size);
+        }
+
         if (tempCert == NULL)
         {
             /*Codes_SRS_HTTPAPI_COMPACT_21_070: [ If any memory allocation get fail, the HTTPAPI_CloneOption shall return HTTPAPI_ALLOC_FAILED. ]*/
             result = HTTPAPI_ALLOC_FAILED;
         }
diff --git a/adapters/httpapi_curl.c b/adapters/httpapi_curl.c
index fa4817a2..14d25ba9 100644
--- a/adapters/httpapi_curl.c
+++ b/adapters/httpapi_curl.c
@@ -25,10 +25,11 @@
 #elif USE_MBEDTLS
 #include "mbedtls/x509_crt.h"
 #include "mbedtls/ssl.h"
 #endif
 #include "azure_c_shared_utility/shared_util_options.h"
+#include "azure_c_shared_utility/safe_math.h"
 
 #define TEMP_BUFFER_SIZE 1024
 
 MU_DEFINE_ENUM_STRINGS(HTTPAPI_RESULT, HTTPAPI_RESULT_VALUES);
 
@@ -116,12 +117,22 @@ HTTP_HANDLE HTTPAPI_CreateConnection(const char* hostName)
     else
     {
         httpHandleData = (HTTP_HANDLE_DATA*)malloc(sizeof(HTTP_HANDLE_DATA));
         if (httpHandleData != NULL)
         {
-            size_t hostURL_size = strlen("https://") + strlen(hostName) + 1;
-            httpHandleData->hostURL = malloc(hostURL_size);
+            size_t hostURL_size = safe_add_size_t(strlen("https://"), strlen(hostName));
+            hostURL_size = safe_add_size_t(hostURL_size, 1);
+
+            if (hostURL_size == SIZE_MAX)
+            {
+                LogError("invalid malloc size");
+                httpHandleData->hostURL = NULL;
+            }
+            else
+            {
+                httpHandleData->hostURL = malloc(hostURL_size);
+            }
 
             if (httpHandleData->hostURL == NULL)
             {
                 LogError("unable to malloc");
                 free(httpHandleData);
@@ -280,20 +291,33 @@ static size_t ContentWriteFunction(void *ptr, size_t size, size_t nmemb, void *u
     HTTP_RESPONSE_CONTENT_BUFFER* responseContentBuffer = (HTTP_RESPONSE_CONTENT_BUFFER*)userdata;
     if ((userdata != NULL) &&
         (ptr != NULL) &&
         (size * nmemb > 0))
     {
-        void* newBuffer = realloc(responseContentBuffer->buffer, responseContentBuffer->bufferSize + (size * nmemb));
+        size_t malloc_size = safe_multiply_size_t(size, nmemb);
+        malloc_size = safe_add_size_t(malloc_size, responseContentBuffer->bufferSize);
+
+        void* newBuffer;
+        if (malloc_size == SIZE_MAX)
+        {
+            LogError("Invalid buffer size");
+            newBuffer = NULL;
+        }
+        else
+        {
+            newBuffer = realloc(responseContentBuffer->buffer, malloc_size);
+        }
+
         if (newBuffer != NULL)
         {
             responseContentBuffer->buffer = newBuffer;
             memcpy(responseContentBuffer->buffer + responseContentBuffer->bufferSize, ptr, size * nmemb);
             responseContentBuffer->bufferSize += size * nmemb;
         }
         else
         {
-            LogError("Could not allocate buffer of size %lu", (unsigned long)(responseContentBuffer->bufferSize + (size * nmemb)));
+            LogError("Could not allocate buffer of size %lu", (unsigned long)(malloc_size));
             responseContentBuffer->error = 1;
             if (responseContentBuffer->buffer != NULL)
             {
                 free(responseContentBuffer->buffer);
             }
@@ -450,12 +474,22 @@ HTTPAPI_RESULT HTTPAPI_ExecuteRequest(HTTP_HANDLE handle, HTTPAPI_REQUEST_TYPE r
         LogError("(result = %" PRI_MU_ENUM ")", MU_ENUM_VALUE(HTTPAPI_RESULT, result));
     }
     else
     {
         char* tempHostURL;
-        size_t tempHostURL_size = strlen(httpHandleData->hostURL) + strlen(relativePath) + 1;
-        tempHostURL = malloc(tempHostURL_size);
+        size_t tempHostURL_size = safe_add_size_t(strlen(httpHandleData->hostURL), strlen(relativePath));
+        tempHostURL_size = safe_add_size_t(tempHostURL_size, 1);
+        if (tempHostURL_size == SIZE_MAX)
+        {
+            LogError("Invalid malloc size");
+            tempHostURL = NULL;
+        }
+        else
+        {
+            tempHostURL = malloc(tempHostURL_size);
+        }
+
         if (tempHostURL == NULL)
         {
             result = HTTPAPI_ERROR;
             LogError("(result = %" PRI_MU_ENUM ")", MU_ENUM_VALUE(HTTPAPI_RESULT, result));
         }
@@ -961,12 +995,22 @@ HTTPAPI_RESULT HTTPAPI_SetOption(HTTP_HANDLE handle, const char* optionName, con
                 }
                 else
                 {
                     if (proxy_data->username != NULL && proxy_data->password != NULL)
                     {
-                        size_t authLen = strlen(proxy_data->username)+strlen(proxy_data->password)+1;
-                        proxy_auth = malloc(authLen+1);
+                        size_t authLen = safe_add_size_t(strlen(proxy_data->username), strlen(proxy_data->password));
+                        authLen = safe_add_size_t(authLen, 2);
+                        if (authLen == SIZE_MAX)
+                        {
+                            LogError("Invalid malloc size");
+                            proxy_auth = NULL;
+                        }
+                        else
+                        {
+                            proxy_auth = malloc(authLen);
+                        }
+
                         if (proxy_auth == NULL)
                         {
                             LogError("failure allocating proxy authentication");
                             result = HTTPAPI_ERROR;
                         }
diff --git a/adapters/httpapi_tirtos.c b/adapters/httpapi_tirtos.c
index ba7a8eae..88d0b993 100644
--- a/adapters/httpapi_tirtos.c
+++ b/adapters/httpapi_tirtos.c
@@ -8,10 +8,11 @@
 #include <ti/net/http/httpcli.h>
 
 #include "azure_c_shared_utility/httpapi.h"
 #include "azure_c_shared_utility/strings.h"
 #include "azure_c_shared_utility/xlogging.h"
+#include "azure_c_shared_utility/safe_math.h"
 
 #define CONTENT_BUF_LEN     128
 
 static const char* getHttpMethod(HTTPAPI_REQUEST_TYPE requestType)
 {
@@ -196,11 +197,21 @@ HTTPAPI_RESULT HTTPAPI_ExecuteRequest(HTTP_HANDLE handle,
             /* All headers read */
             goto headersDone;
         }
 
         if (cnt < offset + ret) {
-            hname = (char *)realloc(hname, offset + ret);
+            size_t malloc_size = safe_add_size_t(offset, ret);
+            if (malloc_size == SIZE_MAX)
+            {
+                LogError("invalid realloc size");
+                hname = NULL;
+            }
+            else
+            {
+                hname = (char*)realloc(hname, malloc_size);
+            }
+
             if (hname == NULL) {
                 LogError("Failed reallocating memory");
                 ret = HTTPAPI_ALLOC_FAILED;
                 goto headersDone;
             }
diff --git a/adapters/httpapi_winhttp.c b/adapters/httpapi_winhttp.c
index ce9c0ad1..a1d992c0 100644
--- a/adapters/httpapi_winhttp.c
+++ b/adapters/httpapi_winhttp.c
@@ -14,10 +14,11 @@
 #include "azure_c_shared_utility/httpheaders.h"
 #include "azure_c_shared_utility/xlogging.h"
 #include "azure_c_shared_utility/strings.h"
 #include "azure_c_shared_utility/x509_schannel.h"
 #include "azure_c_shared_utility/shared_util_options.h"
+#include "azure_c_shared_utility/safe_math.h"
 
 MU_DEFINE_ENUM_STRINGS(HTTPAPI_RESULT, HTTPAPI_RESULT_VALUES)
 
 typedef enum HTTPAPI_STATE_TAG
 {
@@ -49,12 +50,24 @@ static HTTPAPI_STATE g_HTTPAPIState = HTTPAPI_NOT_INITIALIZED;
 static HINTERNET g_SessionHandle;
 static size_t nUsersOfHTTPAPI = 0; /*used for reference counting (a weak one)*/
 
 static char* ConcatHttpHeaders(HTTP_HEADERS_HANDLE httpHeadersHandle, size_t toAlloc, size_t headersCount)
 {
-    char *result = (char*)malloc(toAlloc * sizeof(char) + 1);
     size_t i;
+    char* result;
+
+    size_t malloc_size = safe_multiply_size_t(toAlloc, sizeof(char));
+    malloc_size = safe_add_size_t(malloc_size, 1);
+    if (malloc_size == SIZE_MAX)
+    {
+        LogError("Invalid malloc size");
+        result = NULL;
+    }
+    else
+    {
+        result = (char*)malloc(malloc_size);
+    }
     
     if (result == NULL)
     {
         LogError("unable to malloc");
     }
@@ -130,10 +143,11 @@ static HTTPAPI_RESULT ConstructHeadersString(HTTP_HEADERS_HANDLE httpHeadersHand
         }
         else
         {
             char *httpHeadersA;
             size_t requiredCharactersForHeaders;
+            size_t malloc_size;
 
             if ((httpHeadersA = ConcatHttpHeaders(httpHeadersHandle, toAlloc, headersCount)) == NULL)
             {
                 result = HTTPAPI_ERROR;
                 LogError("Cannot concatenate headers");
@@ -141,11 +155,12 @@ static HTTPAPI_RESULT ConstructHeadersString(HTTP_HEADERS_HANDLE httpHeadersHand
             else if ((requiredCharactersForHeaders = MultiByteToWideChar(CP_ACP, 0, httpHeadersA, -1, NULL, 0)) == 0)
             {
                 result = HTTPAPI_STRING_PROCESSING_ERROR;
                 LogError("MultiByteToWideChar failed, GetLastError=0x%08x (result = %" PRI_MU_ENUM ")", GetLastError(), MU_ENUM_VALUE(HTTPAPI_RESULT, result));
             }
-            else if ((*httpHeaders = (wchar_t*)malloc((requiredCharactersForHeaders + 1) * sizeof(wchar_t))) == NULL)
+            else if ((malloc_size = safe_multiply_size_t(safe_add_size_t(requiredCharactersForHeaders, 1), sizeof(wchar_t))) == SIZE_MAX ||
+                (*httpHeaders = (wchar_t*)malloc(malloc_size)) == NULL)
             {
                 result = HTTPAPI_ALLOC_FAILED;
                 LogError("Cannot allocate memory (result = %" PRI_MU_ENUM ")", MU_ENUM_VALUE(HTTPAPI_RESULT, result));
             }
             else if (MultiByteToWideChar(CP_ACP, 0, httpHeadersA, -1, *httpHeaders, (int)requiredCharactersForHeaders) == 0)
@@ -330,11 +345,21 @@ HTTP_HANDLE HTTPAPI_CreateConnection(const char* hostName)
                 free(result);
                 result = NULL;
             }
             else
             {
-                hostNameTemp = (wchar_t*)malloc(sizeof(wchar_t) * hostNameTemp_size);
+                size_t malloc_size = safe_multiply_size_t(sizeof(wchar_t), hostNameTemp_size);
+                if (malloc_size == SIZE_MAX)
+                {
+                    LogError("Invalid malloc size");
+                    hostNameTemp = NULL;
+                }
+                else
+                {
+                    hostNameTemp = (wchar_t*)malloc(malloc_size);
+                }
+
                 if (hostNameTemp == NULL)
                 {
                     LogError("malloc failed");
                     free(result);
                     result = NULL;
@@ -452,22 +477,28 @@ static HTTPAPI_RESULT InitiateWinhttpRequest(HTTP_HANDLE_DATA* handleData, HTTPA
 {
     HTTPAPI_RESULT result;
     const wchar_t* requestTypeString;
     size_t requiredCharactersForRelativePath;
     wchar_t* relativePathTemp = NULL;
-    
+    size_t malloc_size;
+
     if ((requestTypeString = GetHttpRequestString(requestType)) == NULL)
     {
         result = HTTPAPI_INVALID_ARG;
         LogError("requestTypeString was NULL (result = %" PRI_MU_ENUM ")", MU_ENUM_VALUE(HTTPAPI_RESULT, result));
     }
     else if ((requiredCharactersForRelativePath = MultiByteToWideChar(CP_ACP, 0, relativePath, -1, NULL, 0)) == 0)
     {
         result = HTTPAPI_STRING_PROCESSING_ERROR;
         LogError("MultiByteToWideChar failed, GetLastError=0x%08x", GetLastError());
     }
-    else if ((relativePathTemp = (wchar_t*)malloc((requiredCharactersForRelativePath + 1) * sizeof(wchar_t))) == NULL)
+    else if ((malloc_size = safe_multiply_size_t(safe_add_size_t(requiredCharactersForRelativePath, 1), sizeof(wchar_t))) == SIZE_MAX)
+    {
+        LogError("malloc invalid size");
+        result = HTTPAPI_ALLOC_FAILED;
+    }
+    else if ((relativePathTemp = (wchar_t*)malloc(malloc_size)) == NULL)
     {
         result = HTTPAPI_ALLOC_FAILED;
         LogError("malloc failed (result = %" PRI_MU_ENUM ")", MU_ENUM_VALUE(HTTPAPI_RESULT, result));
     }
     else if (MultiByteToWideChar(CP_ACP, 0, relativePath, -1, relativePathTemp, (int)requiredCharactersForRelativePath) == 0)
@@ -778,11 +809,22 @@ static HTTPAPI_RESULT ReceiveResponseHeaders(HINTERNET requestHandle, HTTP_HEADE
         WINHTTP_HEADER_NAME_BY_INDEX,
         WINHTTP_NO_OUTPUT_BUFFER,
         &responseHeadersTempLength,
         WINHTTP_NO_HEADER_INDEX);
 
-    if ((responseHeadersTemp = (wchar_t*)malloc((size_t)responseHeadersTempLength + 2)) == NULL)
+    size_t malloc_size = safe_add_size_t((size_t)responseHeadersTempLength, 2);
+    if (malloc_size == SIZE_MAX)
+    {
+        LogError("Invalid malloc size");
+        responseHeadersTemp = NULL;
+    }
+    else
+    {
+        responseHeadersTemp = (wchar_t*)malloc(malloc_size);
+    }
+
+    if (responseHeadersTemp == NULL)
     {
         result = HTTPAPI_ALLOC_FAILED;
         LogError("malloc failed: (result = %" PRI_MU_ENUM ")", MU_ENUM_VALUE(HTTPAPI_RESULT, result));
     }
     else if (! WinHttpQueryHeaders(
@@ -814,11 +856,17 @@ static HTTPAPI_RESULT ReceiveResponseHeaders(HINTERNET requestHandle, HTTP_HEADE
             {
                 result = HTTPAPI_STRING_PROCESSING_ERROR;
                 LogError("WideCharToMultiByte failed");
                 break;
             }
-            else if ((tokenTemp = (char*)malloc(sizeof(char) * tokenTemp_size)) == NULL)
+            else if ((malloc_size = safe_multiply_size_t(sizeof(char), tokenTemp_size)) == SIZE_MAX)
+            {
+                result = HTTPAPI_ALLOC_FAILED;
+                LogError("invalid malloc size");
+                break;
+            }
+            else if ((tokenTemp = (char*)malloc(malloc_size)) == NULL)
             {
                 result = HTTPAPI_ALLOC_FAILED;
                 LogError("malloc failed");
                 break;
             }
diff --git a/adapters/socketio_berkeley.c b/adapters/socketio_berkeley.c
index f482db62..475caefc 100755
--- a/adapters/socketio_berkeley.c
+++ b/adapters/socketio_berkeley.c
@@ -45,10 +45,11 @@
 #include "azure_c_shared_utility/optionhandler.h"
 #include "azure_c_shared_utility/shared_util_options.h"
 #include "azure_c_shared_utility/xlogging.h"
 #include "azure_c_shared_utility/const_defines.h"
 #include "azure_c_shared_utility/dns_resolver.h"
+#include "azure_c_shared_utility/safe_math.h"
 #include <sys/ioctl.h>
 #include <netinet/in.h>
 #include <arpa/inet.h>
 #include <sys/un.h>
 
@@ -124,11 +125,17 @@ static void* socketio_CloneOption(const char* name, const void* value)
             {
                 LogError("Failed cloning option %s (value is NULL)", name);
             }
             else
             {
-                if ((result = malloc(sizeof(char) * (strlen((char*)value) + 1))) == NULL)
+                size_t malloc_size = safe_add_size_t(strlen((char*)value), 1);
+                malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
+                if (malloc_size == SIZE_MAX)
+                {
+                    LogError("Invalid malloc size");
+                }
+                else if ((result = malloc(malloc_size)) == NULL)
                 {
                     LogError("Failed cloning option %s (malloc failed)", name);
                 }
                 else
                 {
@@ -311,16 +318,23 @@ static void destroy_network_interface_descriptions(NETWORK_INTERFACE_DESCRIPTION
 }
 
 static NETWORK_INTERFACE_DESCRIPTION* create_network_interface_description(struct ifreq *ifr, NETWORK_INTERFACE_DESCRIPTION* previous_nid)
 {
     NETWORK_INTERFACE_DESCRIPTION* result;
+    size_t malloc_size;
 
     if ((result = (NETWORK_INTERFACE_DESCRIPTION*)malloc(sizeof(NETWORK_INTERFACE_DESCRIPTION))) == NULL)
     {
         LogError("Failed allocating NETWORK_INTERFACE_DESCRIPTION");
     }
-    else if ((result->name = (char*)malloc(sizeof(char) * (strlen(ifr->ifr_name) + 1))) == NULL)
+    else if ((malloc_size = safe_multiply_size_t(safe_add_size_t(strlen(ifr->ifr_name), 1), sizeof(char))) == SIZE_MAX)
+    {
+        LogError("invalid malloc size");
+        destroy_network_interface_descriptions(result);
+        result = NULL;
+    }
+    else if ((result->name = (char*)malloc(malloc_size)) == NULL)
     {
         LogError("failed setting interface description name (malloc failed)");
         destroy_network_interface_descriptions(result);
         result = NULL;
     }
@@ -328,14 +342,16 @@ static NETWORK_INTERFACE_DESCRIPTION* create_network_interface_description(struc
     {
         strcpy(result->name, ifr->ifr_name);
 
         char* ip_address;
         unsigned char* mac = (unsigned char*)ifr->ifr_hwaddr.sa_data;
+        size_t malloc_size = safe_multiply_size_t(sizeof(char), MAC_ADDRESS_STRING_LENGTH);
 
-        if ((result->mac_address = (char*)malloc(sizeof(char) * MAC_ADDRESS_STRING_LENGTH)) == NULL)
+        if (malloc_size == SIZE_MAX ||
+                (result->mac_address = (char*)malloc(malloc_size)) == NULL)
         {
-            LogError("failed formatting mac address (malloc failed)");
+            LogError("failed formatting mac address (malloc failed) size:%zu", malloc_size);
             destroy_network_interface_descriptions(result);
             result = NULL;
         }
         else if (sprintf(result->mac_address, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]) <= 0)
         {
@@ -347,11 +363,17 @@ static NETWORK_INTERFACE_DESCRIPTION* create_network_interface_description(struc
         {
             LogError("failed setting the ip address (inet_ntoa failed)");
             destroy_network_interface_descriptions(result);
             result = NULL;
         }
-        else if ((result->ip_address = (char*)malloc(sizeof(char) * (strlen(ip_address) + 1))) == NULL)
+        else if ((malloc_size = safe_multiply_size_t(safe_add_size_t(strlen(ip_address), 1), sizeof(char))) == SIZE_MAX)
+        {
+            LogError("invalid malloc size");
+            destroy_network_interface_descriptions(result);
+            result = NULL;
+        }
+        else if ((result->ip_address = (char*)malloc(malloc_size)) == NULL)
         {
             LogError("failed setting the ip address (malloc failed)");
             destroy_network_interface_descriptions(result);
             result = NULL;
         }
@@ -740,14 +762,23 @@ CONCRETE_IO_HANDLE socketio_create(void* io_create_parameters)
             }
             else
             {
                 if (socket_io_config->hostname != NULL)
                 {
-                    result->hostname = (char*)malloc(strlen(socket_io_config->hostname) + 1);
-                    if (result->hostname != NULL)
+                    size_t malloc_size = safe_add_size_t(strlen(socket_io_config->hostname), 1);
+                    if (malloc_size == SIZE_MAX)
                     {
-                        (void)strcpy(result->hostname, socket_io_config->hostname);
+                        LogError("invalid malloc size");
+                        result->hostname = NULL;
+                    }
+                    else
+                    {
+                        result->hostname = (char*)malloc(malloc_size);
+                        if (result->hostname != NULL)
+                        {
+                            (void)strcpy(result->hostname, socket_io_config->hostname);
+                        }
                     }
 
                     result->socket = INVALID_SOCKET;
                 }
                 else
@@ -1203,16 +1234,23 @@ int socketio_setoption(CONCRETE_IO_HANDLE socket_io, const char* optionName, con
         {
 #ifdef __APPLE__
             LogError("option not supported.");
             result = MU_FAILURE;
 #else
+            size_t malloc_size;
             if (strlen(value) == 0)
             {
                 LogError("option value must be a valid mac address");
                 result = MU_FAILURE;
             }
-            else if ((socket_io_instance->target_mac_address = (char*)malloc(sizeof(char) * (strlen(value) + 1))) == NULL)
+            else if ((malloc_size = safe_multiply_size_t(safe_add_size_t(strlen(value), 1), sizeof(char))) == SIZE_MAX)
+            {
+                LogError("invalid malloc size");
+                result = MU_FAILURE;
+                socket_io_instance->target_mac_address = NULL;
+            }
+            else if ((socket_io_instance->target_mac_address = (char*)malloc(malloc_size)) == NULL)
             {
                 LogError("failed setting net_interface_mac_address option (malloc failed)");
                 result = MU_FAILURE;
             }
             else
diff --git a/adapters/socketio_win32.c b/adapters/socketio_win32.c
index 99f1fdc0..97f02c91 100644
--- a/adapters/socketio_win32.c
+++ b/adapters/socketio_win32.c
@@ -16,10 +16,11 @@
 #include "azure_c_shared_utility/gbnetwork.h"
 #include "azure_c_shared_utility/optimize_size.h"
 #include "azure_c_shared_utility/shared_util_options.h"
 #include "azure_c_shared_utility/xlogging.h"
 #include "azure_c_shared_utility/dns_resolver.h"
+#include "azure_c_shared_utility/safe_math.h"
 
 typedef enum IO_STATE_TAG
 {
     IO_STATE_CLOSED,
     IO_STATE_OPENING,
@@ -334,14 +335,23 @@ CONCRETE_IO_HANDLE socketio_create(void* io_create_parameters)
             }
             else
             {
                 if (socket_io_config->hostname != NULL)
                 {
-                    result->hostname = (char*)malloc(strlen(socket_io_config->hostname) + 1);
-                    if (result->hostname != NULL)
+                    size_t malloc_size = safe_add_size_t(strlen(socket_io_config->hostname), 1);
+                    if (malloc_size == SIZE_MAX)
                     {
-                        (void)strcpy(result->hostname, socket_io_config->hostname);
+                        LogError("Invalid malloc size");
+                        result->hostname = NULL;
+                    }
+                    else
+                    {
+                        result->hostname = (char*)malloc(malloc_size);
+                        if (result->hostname != NULL)
+                        {
+                            (void)strcpy(result->hostname, socket_io_config->hostname);
+                        }
                     }
 
                     result->socket = INVALID_SOCKET;
                 }
                 else
diff --git a/adapters/string_utils.c b/adapters/string_utils.c
index d8ea2944..582f9b19 100644
--- a/adapters/string_utils.c
+++ b/adapters/string_utils.c
@@ -8,10 +8,11 @@
 #include "windows.h"
 
 #include "azure_macro_utils/macro_utils.h"
 #include "azure_c_shared_utility/gballoc.h"
 #include "azure_c_shared_utility/xlogging.h"
+#include "azure_c_shared_utility/safe_math.h"
 
 #include "azure_c_shared_utility/string_utils.h"
 
 IMPLEMENT_MOCKABLE_FUNCTION(, char*, vsprintf_char, const char*, format, va_list, va)
 {
@@ -22,12 +23,19 @@ IMPLEMENT_MOCKABLE_FUNCTION(, char*, vsprintf_char, const char*, format, va_list
         LogError("failure in vsnprintf");
         result = NULL;
     }
     else
     {
-        result = (char*)malloc(((unsigned long long)neededSize + 1) * sizeof(char));
-        if (result == NULL)
+        size_t malloc_size = safe_add_size_t((unsigned long long)neededSize, 1);
+        malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
+        if (malloc_size == SIZE_MAX)
+        {
+            LogError("invalid malloc size");
+            result = NULL;
+            /*return as is*/
+        }
+        else if ((result = (char*)malloc(malloc_size)) == NULL)
         {
             LogError("failure in malloc");
             /*return as is*/
         }
         else
@@ -52,12 +60,19 @@ IMPLEMENT_MOCKABLE_FUNCTION(, wchar_t*, vsprintf_wchar, const wchar_t*, format,
         LogError("failure in swprintf");
         result = NULL;
     }
     else
     {
-        result = (wchar_t*)malloc(((unsigned long long)neededSize + 1)*sizeof(wchar_t));
-        if (result == NULL)
+        size_t malloc_size = safe_add_size_t((unsigned long long)neededSize, 1);
+        malloc_size = safe_multiply_size_t(malloc_size, sizeof(wchar_t));
+        if (malloc_size == SIZE_MAX)
+        {
+            LogError("invalid malloc size");
+            result = NULL;
+            /*return as is*/
+        }
+        else if ((result = (wchar_t*)malloc(malloc_size)) == NULL)
         {
             LogError("failure in malloc");
             /*return as is*/
         }
         else
@@ -167,12 +182,19 @@ IMPLEMENT_MOCKABLE_FUNCTION(, wchar_t*, mbs_to_wcs, const char*, source)
             LogError("failure to get the length of the string %s in multibyte characters", strerror(errno));
             result = NULL;
         }
         else
         {
-            result = (wchar_t*)malloc(sizeof(wchar_t)*(nwc+1));
-            if (result == NULL)
+            size_t malloc_size = safe_add_size_t(nwc, 1);
+            malloc_size = safe_multiply_size_t(malloc_size, sizeof(wchar_t));
+            if (malloc_size == SIZE_MAX)
+            {
+                LogError("invalid malloc size");
+                result = NULL;
+                /*return as is*/
+            }
+            else if ((result = (wchar_t*)malloc(malloc_size)) == NULL)
             {
                 LogError("failure in malloc");
                 /*return as is*/
             }
             else
@@ -214,12 +236,19 @@ IMPLEMENT_MOCKABLE_FUNCTION(, char*, wcs_to_mbs, const wchar_t*, source)
             LogError("failure to get the length of the string %s in characters", strerror(errno));
             result = NULL;
         }
         else
         {
-            result = (char*)malloc(sizeof(char)*(nc + 1));
-            if (result == NULL)
+            size_t malloc_size = safe_add_size_t(nc, 1);
+            malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
+            if (malloc_size == SIZE_MAX)
+            {
+                LogError("invalid malloc size");
+                result = NULL;
+                /*return as is*/
+            }
+            else if ((result = (char*)malloc(malloc_size)) == NULL)
             {
                 LogError("failure in malloc");
                 /*return as is*/
             }
             else
diff --git a/adapters/tlsio_mbedtls.c b/adapters/tlsio_mbedtls.c
index 0b4aa3e8..db99b0d6 100644
--- a/adapters/tlsio_mbedtls.c
+++ b/adapters/tlsio_mbedtls.c
@@ -22,10 +22,11 @@
 #include "azure_c_shared_utility/tlsio_mbedtls.h"
 #include "azure_c_shared_utility/socketio.h"
 #include "azure_c_shared_utility/crt_abstractions.h"
 #include "azure_c_shared_utility/shared_util_options.h"
 #include "azure_c_shared_utility/threadapi.h"
+#include "azure_c_shared_utility/safe_math.h"
 
 static const char *const OPTION_UNDERLYING_IO_OPTIONS = "underlying_io_options";
 
 #define HANDSHAKE_TIMEOUT_MS 5000
 #define HANDSHAKE_WAIT_INTERVAL_MS 10
@@ -204,16 +205,23 @@ static void on_underlying_io_open_complete(void *context, IO_OPEN_RESULT open_re
 
 static void on_underlying_io_bytes_received(void *context, const unsigned char *buffer, size_t size)
 {
     if (context != NULL)
     {
+        unsigned char* new_socket_io_read_bytes;
         TLS_IO_INSTANCE *tls_io_instance = (TLS_IO_INSTANCE *)context;
 
-        unsigned char *new_socket_io_read_bytes = (unsigned char *)realloc(tls_io_instance->socket_io_read_bytes, tls_io_instance->socket_io_read_byte_count + size);
-
-        if (new_socket_io_read_bytes == NULL)
+        size_t realloc_size = safe_add_size_t(tls_io_instance->socket_io_read_byte_count, size);
+        if (realloc_size == SIZE_MAX)
+        {
+            LogError("Invalid realloc size");
+            tls_io_instance->tlsio_state = TLSIO_STATE_ERROR;
+            indicate_error(tls_io_instance);
+        }
+        else if ((new_socket_io_read_bytes = (unsigned char*)realloc(tls_io_instance->socket_io_read_bytes, realloc_size)) == NULL)
         {
+            LogError("realloc failed");
             tls_io_instance->tlsio_state = TLSIO_STATE_ERROR;
             indicate_error(tls_io_instance);
         }
         else
         {
diff --git a/adapters/tlsio_openssl.c b/adapters/tlsio_openssl.c
index f03687d0..5c758444 100644
--- a/adapters/tlsio_openssl.c
+++ b/adapters/tlsio_openssl.c
@@ -19,10 +19,11 @@
 #include "azure_c_shared_utility/crt_abstractions.h"
 #include "azure_c_shared_utility/x509_openssl.h"
 #include "azure_c_shared_utility/shared_util_options.h"
 #include "azure_c_shared_utility/gballoc.h"
 #include "azure_c_shared_utility/const_defines.h"
+#include "azure_c_shared_utility/safe_math.h"
 
 typedef enum TLSIO_STATE_TAG
 {
     TLSIO_STATE_NOT_OPEN,
     TLSIO_STATE_OPENING_UNDERLYING_IO,
@@ -605,14 +606,15 @@ static int openssl_static_locks_install(void)
         LogInfo("Locks already initialized");
         result = MU_FAILURE;
     }
     else
     {
-        openssl_locks = malloc(CRYPTO_num_locks() * sizeof(LOCK_HANDLE));
-        if (openssl_locks == NULL)
+        size_t malloc_size = safe_multiply_size_t(CRYPTO_num_locks(), sizeof(LOCK_HANDLE));
+        if (malloc_size == SIZE_MAX ||
+            (openssl_locks = malloc(malloc_size)) == NULL)
         {
-            LogError("Failed to allocate locks");
+            LogError("Failed to allocate locks, size:%zu", malloc_size);
             result = MU_FAILURE;
         }
         else
         {
             int i;
@@ -1652,13 +1654,15 @@ int tlsio_openssl_setoption(CONCRETE_IO_HANDLE tls_io, const char* optionName, c
                 tls_io_instance->certificate = NULL;
             }
 
             // Store the certificate
             len = strlen(cert);
-            tls_io_instance->certificate = malloc(len + 1);
-            if (tls_io_instance->certificate == NULL)
+            size_t malloc_size = safe_add_size_t(len, 1);
+            if (malloc_size == SIZE_MAX ||
+                (tls_io_instance->certificate = malloc(malloc_size)) == NULL)
             {
+                LogError("malloc failure, size:%zu", malloc_size);
                 result = MU_FAILURE;
             }
             else
             {
                 strcpy(tls_io_instance->certificate, cert);
diff --git a/adapters/tlsio_schannel.c b/adapters/tlsio_schannel.c
index 901c4208..3f439d68 100644
--- a/adapters/tlsio_schannel.c
+++ b/adapters/tlsio_schannel.c
@@ -19,10 +19,11 @@
 #include "azure_c_shared_utility/x509_schannel.h"
 #include "azure_c_shared_utility/crt_abstractions.h"
 #include "azure_c_shared_utility/singlylinkedlist.h"
 #include "azure_c_shared_utility/shared_util_options.h"
 #include "azure_c_shared_utility/gballoc.h"
+#include "azure_c_shared_utility/safe_math.h"
 
 #define TLSIO_STATE_VALUES                        \
     TLSIO_STATE_NOT_OPEN,                         \
     TLSIO_STATE_OPENING_UNDERLYING_IO,            \
     TLSIO_STATE_HANDSHAKE_CLIENT_HELLO_SENT,      \
@@ -513,17 +514,19 @@ static int send_chunk(CONCRETE_IO_HANDLE tls_io, const void* buffer, size_t size
                 LogError("QueryContextAttributes failed: %x", status);
                 result = MU_FAILURE;
             }
             else
             {
+                unsigned char* out_buffer;
                 SecBuffer security_buffers[4];
                 SecBufferDesc security_buffers_desc;
-                size_t needed_buffer = sizes.cbHeader + size + sizes.cbTrailer;
-                unsigned char* out_buffer = (unsigned char*)malloc(needed_buffer);
-                if (out_buffer == NULL)
+                size_t needed_buffer = safe_add_size_t(sizes.cbHeader, size);
+                needed_buffer = safe_add_size_t(needed_buffer, sizes.cbTrailer);
+                if (needed_buffer == SIZE_MAX ||
+                    (out_buffer = (unsigned char*)malloc(needed_buffer)) == NULL)
                 {
-                    LogError("malloc failed");
+                    LogError("malloc failed, size:%zu", needed_buffer);
                     result = MU_FAILURE;
                 }
                 else
                 {
                     (void)memcpy(out_buffer + sizes.cbHeader, buffer, size);
@@ -1087,14 +1090,16 @@ CONCRETE_IO_HANDLE tlsio_schannel_create(void* io_create_parameters)
         }
         else
         {
             (void)memset(result, 0, sizeof(TLS_IO_INSTANCE));
 
-            result->host_name = (SEC_TCHAR*)malloc(sizeof(SEC_TCHAR) * (1 + strlen(tls_io_config->hostname)));
-            if (result->host_name == NULL)
+            size_t malloc_size = safe_add_size_t(strlen(tls_io_config->hostname), 1);
+            malloc_size = safe_multiply_size_t(malloc_size, sizeof(SEC_TCHAR));
+            if (malloc_size == SIZE_MAX ||
+                (result->host_name = (SEC_TCHAR*)malloc(malloc_size)) == NULL)
             {
-                LogError("malloc failed");
+                LogError("malloc failed, size:%zu", malloc_size);
                 free(result);
                 result = NULL;
             }
             else
             {
diff --git a/adapters/tlsio_wolfssl.c b/adapters/tlsio_wolfssl.c
index 3bebadcb..0f1950e8 100644
--- a/adapters/tlsio_wolfssl.c
+++ b/adapters/tlsio_wolfssl.c
@@ -16,10 +16,11 @@
 #include "azure_c_shared_utility/socketio.h"
 #include "azure_c_shared_utility/crt_abstractions.h"
 #include "azure_c_shared_utility/optimize_size.h"
 #include "azure_c_shared_utility/xlogging.h"
 #include "azure_c_shared_utility/shared_util_options.h"
+#include "azure_c_shared_utility/safe_math.h"
 
 typedef enum TLSIO_STATE_ENUM_TAG
 {
     TLSIO_STATE_NOT_OPEN,
     TLSIO_STATE_OPENING_UNDERLYING_IO,
@@ -301,15 +302,17 @@ static void on_underlying_io_open_complete(void* context, IO_OPEN_RESULT open_re
 static void on_underlying_io_bytes_received(void* context, const unsigned char* buffer, size_t size)
 {
     if (context != NULL)
     {
         TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)context;
+        unsigned char* new_socket_io_read_bytes;
 
-        unsigned char* new_socket_io_read_bytes = (unsigned char*)realloc(tls_io_instance->socket_io_read_bytes, tls_io_instance->socket_io_read_byte_count + size);
-        if (new_socket_io_read_bytes == NULL)
+        size_t realloc_size = safe_add_size_t(tls_io_instance->socket_io_read_byte_count, size);
+        if (realloc_size == SIZE_MAX ||
+            (new_socket_io_read_bytes = (unsigned char*)realloc(tls_io_instance->socket_io_read_bytes, realloc_size)) == NULL)
         {
-            LogError("Failed allocating memory for received bytes");
+            LogError("Failed allocating memory for received bytes, size:%zu", realloc_size);
             tls_io_instance->tlsio_state = TLSIO_STATE_ERROR;
             indicate_error(tls_io_instance);
         }
         else
         {
diff --git a/adapters/x509_schannel.c b/adapters/x509_schannel.c
index 03f9b81b..4fc3b217 100644
--- a/adapters/x509_schannel.c
+++ b/adapters/x509_schannel.c
@@ -4,10 +4,12 @@
 #include "windows.h"
 
 #include "azure_c_shared_utility/gballoc.h"
 #include "azure_c_shared_utility/x509_schannel.h"
 #include "azure_c_shared_utility/xlogging.h"
+#include "azure_c_shared_utility/safe_math.h"
+
 #if _MSC_VER > 1500
 #include <ncrypt.h>
 #endif
 
 #define KEY_NAME L"AzureAliasKey"
@@ -151,23 +153,25 @@ static unsigned char* decode_crypt_object(unsigned char* private_key, DWORD key_
 
 static int set_ecc_certificate_info(X509_SCHANNEL_HANDLE_DATA* x509_handle, unsigned char* x509privatekeyBlob)
 {
     int result;
 #if _MSC_VER > 1500
+    BCRYPT_ECCKEY_BLOB* pKeyBlob;
     SECURITY_STATUS status;
     CRYPT_BIT_BLOB* pPubKeyBlob = &x509_handle->x509certificate_context->pCertInfo->SubjectPublicKeyInfo.PublicKey;
     CRYPT_ECC_PRIVATE_KEY_INFO* pPrivKeyInfo = (CRYPT_ECC_PRIVATE_KEY_INFO*)x509privatekeyBlob;
     DWORD pubSize = pPubKeyBlob->cbData - 1;
     DWORD privSize = pPrivKeyInfo->PrivateKey.cbData;
-    DWORD keyBlobSize = sizeof(BCRYPT_ECCKEY_BLOB) + pubSize + privSize;
+    size_t keyBlobSize = safe_add_size_t(safe_add_size_t(sizeof(BCRYPT_ECCKEY_BLOB), pubSize), privSize);
     BYTE* pubKeyBuf = pPubKeyBlob->pbData + 1;
     BYTE* privKeyBuf = pPrivKeyInfo->PrivateKey.pbData;
-    BCRYPT_ECCKEY_BLOB* pKeyBlob = (BCRYPT_ECCKEY_BLOB*)malloc(keyBlobSize);
-    if (pKeyBlob == NULL)
+
+    if (keyBlobSize == SIZE_MAX ||
+        (pKeyBlob = (BCRYPT_ECCKEY_BLOB*)malloc(keyBlobSize)) == NULL)
     {
         /*Codes_SRS_X509_SCHANNEL_02_010: [ Otherwise, x509_schannel_create shall fail and return a NULL X509_SCHANNEL_HANDLE. ]*/
-        LogError("Failed to malloc NCrypt private key blob");
+        LogError("Failed to malloc NCrypt private key blob, size:%zu", keyBlobSize);
         result = MU_FAILURE;
     }
     else
     {
         pKeyBlob->dwMagic = privSize == ECC_256_MAGIC_NUMBER ? BCRYPT_ECDSA_PRIVATE_P256_MAGIC
@@ -198,11 +202,11 @@ static int set_ecc_certificate_info(X509_SCHANNEL_HANDLE_DATA* x509_handle, unsi
 
             CRYPT_KEY_PROV_INFO keyProvInfo = { KEY_NAME, MS_KEY_STORAGE_PROVIDER, 0, 0, 0, NULL, 0 };
 
             /*Codes_SRS_X509_SCHANNEL_02_006: [ x509_schannel_create shall import the private key by calling CryptImportKey. ] */
             /*NOTE: As no WinCrypt key storage provider supports ECC keys, NCrypt is used instead*/
-            status = NCryptImportKey(x509_handle->hProv, 0, BCRYPT_ECCPRIVATE_BLOB, &ncBufDesc, &x509_handle->x509hcryptkey, (BYTE*)pKeyBlob, keyBlobSize, NCRYPT_OVERWRITE_KEY_FLAG);
+            status = NCryptImportKey(x509_handle->hProv, 0, BCRYPT_ECCPRIVATE_BLOB, &ncBufDesc, &x509_handle->x509hcryptkey, (BYTE*)pKeyBlob, (DWORD)keyBlobSize, NCRYPT_OVERWRITE_KEY_FLAG);
             if (status == ERROR_SUCCESS)
             {
                 status2 = NCryptFreeObject(x509_handle->x509hcryptkey);
                 if (status2 != ERROR_SUCCESS)
                 {
diff --git a/inc/azure_c_shared_utility/xlogging.h b/inc/azure_c_shared_utility/xlogging.h
index 216e1bfd..f64c3f96 100644
--- a/inc/azure_c_shared_utility/xlogging.h
+++ b/inc/azure_c_shared_utility/xlogging.h
@@ -134,13 +134,15 @@ typedef void(*LOGGER_LOG_GETLASTERROR)(const char* file, const char* func, int l
             {                                                                                                                                                           \
                 l(log_category, __FILE__, FUNC_NAME, __LINE__, log_options, format, __VA_ARGS__);                                                                       \
             }                                                                                                                                                           \
             else                                                                                                                                                        \
             {                                                                                                                                                           \
+                char* formatWithStack;                                                                                                                                  \
                 size_t formatSize = strlen(format);                                                                                                                     \
-                char* formatWithStack = (char*)logging_malloc(formatSize + sizeof("STACK_PRINT_FORMAT"));                                                               \
-                if (formatWithStack == NULL)                                                                                                                            \
+                size_t mallocSize = formatSize + sizeof("STACK_PRINT_FORMAT");                                                                                          \
+                if (mallocSize < formatSize ||   /* int overflow check */                                                                                               \
+                    (formatWithStack = (char*)logging_malloc(mallocSize)) == NULL)                                                                                      \
                 {                                                                                                                                                       \
                     l(log_category, __FILE__, FUNC_NAME, __LINE__, log_options, format, __VA_ARGS__);                                                                   \
                 }                                                                                                                                                       \
                 else                                                                                                                                                    \
                 {                                                                                                                                                       \
diff --git a/src/buffer.c b/src/buffer.c
index 47de368d..84599428 100644
--- a/src/buffer.c
+++ b/src/buffer.c
@@ -226,15 +226,17 @@ int BUFFER_append_build(BUFFER_HANDLE handle, const unsigned char* source, size_
             }
         }
         else
         {
             /* Codes_SRS_BUFFER_07_032: [ if handle->buffer is not NULL BUFFER_append_build shall realloc the buffer to be the handle->size + size ] */
-            unsigned char* temp = (unsigned char*)realloc(handle->buffer, handle->size + size);
-            if (temp == NULL)
+            unsigned char* temp;
+            size_t malloc_size = safe_add_size_t(handle->size, size);
+            if (malloc_size == SIZE_MAX || 
+                (temp = (unsigned char*)realloc(handle->buffer, malloc_size)) == NULL)
             {
                 /* Codes_SRS_BUFFER_07_035: [ If any error is encountered BUFFER_append_build shall return a non-null value. ] */
-                LogError("Failure reallocating temporary buffer");
+                LogError("Failure reallocating temporary buffer, size:%zu", malloc_size);
                 result = MU_FAILURE;
             }
             else
             {
                 /* Codes_SRS_BUFFER_07_033: [ ... and copy the contents of source to the end of the buffer. ] */
@@ -355,16 +357,18 @@ int BUFFER_enlarge(BUFFER_HANDLE handle, size_t enlargeSize)
         LogError("Failure: enlargeSize size is 0.");
         result = MU_FAILURE;
     }
     else
     {
+        unsigned char* temp;
         BUFFER* b = (BUFFER*)handle;
-        unsigned char* temp = (unsigned char*)realloc(b->buffer, b->size + enlargeSize);
-        if (temp == NULL)
+        size_t malloc_size = safe_add_size_t(b->size, enlargeSize);
+        if (malloc_size == SIZE_MAX ||
+            (temp = (unsigned char*)realloc(b->buffer, malloc_size)) == NULL)
         {
             /* Codes_SRS_BUFFER_07_018: [BUFFER_enlarge shall return a nonzero result if any error is encountered.] */
-            LogError("Failure: allocating temp buffer.");
+            LogError("Failure: allocating temp buffer, size:%zu", malloc_size);
             result = MU_FAILURE;
         }
         else
         {
             b->buffer = temp;
@@ -492,12 +496,14 @@ int BUFFER_append(BUFFER_HANDLE handle1, BUFFER_HANDLE handle2)
                 result = 0;
             }
             else
             {
                 // b2->size != 0, whatever b1->size is
-                unsigned char* temp = (unsigned char*)realloc(b1->buffer, b1->size + b2->size);
-                if (temp == NULL)
+                unsigned char* temp;
+                size_t malloc_size = safe_add_size_t(b1->size, b2->size);
+                if (malloc_size == SIZE_MAX || 
+                    (temp = (unsigned char*)realloc(b1->buffer, malloc_size)) == NULL)
                 {
                     /* Codes_SRS_BUFFER_07_023: [BUFFER_append shall return a nonzero upon any error that is encountered.] */
                     LogError("Failure: allocating temp buffer.");
                     result = MU_FAILURE;
                 }
diff --git a/src/constbuffer.c b/src/constbuffer.c
index 78414f05..873846b7 100644
--- a/src/constbuffer.c
+++ b/src/constbuffer.c
@@ -31,11 +31,22 @@ typedef struct CONSTBUFFER_HANDLE_DATA_TAG
 static CONSTBUFFER_HANDLE CONSTBUFFER_Create_Internal(const unsigned char* source, size_t size)
 {
     CONSTBUFFER_HANDLE result;
     /*Codes_SRS_CONSTBUFFER_02_005: [The non-NULL handle returned by CONSTBUFFER_Create shall have its ref count set to "1".]*/
     /*Codes_SRS_CONSTBUFFER_02_010: [The non-NULL handle returned by CONSTBUFFER_CreateFromBuffer shall have its ref count set to "1".]*/
-    result = (CONSTBUFFER_HANDLE)calloc(1, (sizeof(CONSTBUFFER_HANDLE_DATA) + size));
+    size_t malloc_size = sizeof(CONSTBUFFER_HANDLE_DATA) + size;
+    if (malloc_size < size)
+    {
+        result = NULL;
+        LogError("invalid size parameter");
+        /*return as is*/
+    }
+    else
+    {
+        result = (CONSTBUFFER_HANDLE)calloc(1, malloc_size);
+    }
+
     if (result == NULL)
     {
         /*Codes_SRS_CONSTBUFFER_02_003: [If creating the copy fails then CONSTBUFFER_Create shall return NULL.]*/
         /*Codes_SRS_CONSTBUFFER_02_008: [If copying the content fails, then CONSTBUFFER_CreateFromBuffer shall fail and return NULL.] */
         LogError("unable to malloc");

Vulnerable code:             new_received_bytes = (unsigned char*)realloc(http_instance->received_bytes, http_instance->received_bytes_count + size);
        int len;
        len = (int)strlen((char*)value);
        http_instance->certificate = (char*)malloc((len + 1) * sizeof(char));
        int len;
        len = (int)strlen((char*)value);
        http_instance->x509ClientCertificate = (char*)malloc((len + 1) * sizeof(char));
        int len;
        len = (int)strlen((char*)value);
        http_instance->x509ClientPrivateKey = (char*)malloc((len + 1) * sizeof(char));
        tempCert = (char*)malloc((certLen + 1) * sizeof(char));
        tempCert = (char*)malloc((certLen + 1) * sizeof(char));
        tempCert = (char*)malloc((certLen + 1) * sizeof(char));
            size_t hostURL_size = strlen("https://") + strlen(hostName) + 1;
            httpHandleData->hostURL = malloc(hostURL_size);
        void* newBuffer = realloc(responseContentBuffer->buffer, responseContentBuffer->bufferSize + (size * nmemb));
            LogError("Could not allocate buffer of size %lu", (unsigned long)(responseContentBuffer->bufferSize + (size * nmemb)));
        size_t tempHostURL_size = strlen(httpHandleData->hostURL) + strlen(relativePath) + 1;
        tempHostURL = malloc(tempHostURL_size);
                        size_t authLen = strlen(proxy_data->username)+strlen(proxy_data->password)+1;
                        proxy_auth = malloc(authLen+1);
            hname = (char *)realloc(hname, offset + ret);
    char *result = (char*)malloc(toAlloc * sizeof(char) + 1);
            else if ((*httpHeaders = (wchar_t*)malloc((requiredCharactersForHeaders + 1) * sizeof(wchar_t))) == NULL)
                hostNameTemp = (wchar_t*)malloc(sizeof(wchar_t) * hostNameTemp_size);
    
    else if ((relativePathTemp = (wchar_t*)malloc((requiredCharactersForRelativePath + 1) * sizeof(wchar_t))) == NULL)
    if ((responseHeadersTemp = (wchar_t*)malloc((size_t)responseHeadersTempLength + 2)) == NULL)
            else if ((tokenTemp = (char*)malloc(sizeof(char) * tokenTemp_size)) == NULL)
                if ((result = malloc(sizeof(char) * (strlen((char*)value) + 1))) == NULL)
    else if ((result->name = (char*)malloc(sizeof(char) * (strlen(ifr->ifr_name) + 1))) == NULL)
        if ((result->mac_address = (char*)malloc(sizeof(char) * MAC_ADDRESS_STRING_LENGTH)) == NULL)
            LogError("failed formatting mac address (malloc failed)");
        else if ((result->ip_address = (char*)malloc(sizeof(char) * (strlen(ip_address) + 1))) == NULL)
                    result->hostname = (char*)malloc(strlen(socket_io_config->hostname) + 1);
                    if (result->hostname != NULL)
                        (void)strcpy(result->hostname, socket_io_config->hostname);
            else if ((socket_io_instance->target_mac_address = (char*)malloc(sizeof(char) * (strlen(value) + 1))) == NULL)
                    result->hostname = (char*)malloc(strlen(socket_io_config->hostname) + 1);
                    if (result->hostname != NULL)
                        (void)strcpy(result->hostname, socket_io_config->hostname);
        result = (char*)malloc(((unsigned long long)neededSize + 1) * sizeof(char));
        if (result == NULL)
        result = (wchar_t*)malloc(((unsigned long long)neededSize + 1)*sizeof(wchar_t));
        if (result == NULL)
            result = (wchar_t*)malloc(sizeof(wchar_t)*(nwc+1));
            if (result == NULL)
            result = (char*)malloc(sizeof(char)*(nc + 1));
            if (result == NULL)
        unsigned char *new_socket_io_read_bytes = (unsigned char *)realloc(tls_io_instance->socket_io_read_bytes, tls_io_instance->socket_io_read_byte_count + size);

        if (new_socket_io_read_bytes == NULL)
        openssl_locks = malloc(CRYPTO_num_locks() * sizeof(LOCK_HANDLE));
        if (openssl_locks == NULL)
            LogError("Failed to allocate locks");
            tls_io_instance->certificate = malloc(len + 1);
            if (tls_io_instance->certificate == NULL)
                size_t needed_buffer = sizes.cbHeader + size + sizes.cbTrailer;
                unsigned char* out_buffer = (unsigned char*)malloc(needed_buffer);
                if (out_buffer == NULL)
                    LogError("malloc failed");
            result->host_name = (SEC_TCHAR*)malloc(sizeof(SEC_TCHAR) * (1 + strlen(tls_io_config->hostname)));
            if (result->host_name == NULL)
                LogError("malloc failed");
        unsigned char* new_socket_io_read_bytes = (unsigned char*)realloc(tls_io_instance->socket_io_read_bytes, tls_io_instance->socket_io_read_byte_count + size);
        if (new_socket_io_read_bytes == NULL)
            LogError("Failed allocating memory for received bytes");
    DWORD keyBlobSize = sizeof(BCRYPT_ECCKEY_BLOB) + pubSize + privSize;
    BCRYPT_ECCKEY_BLOB* pKeyBlob = (BCRYPT_ECCKEY_BLOB*)malloc(keyBlobSize);
    if (pKeyBlob == NULL)
        LogError("Failed to malloc NCrypt private key blob");
            status = NCryptImportKey(x509_handle->hProv, 0, BCRYPT_ECCPRIVATE_BLOB, &ncBufDesc, &x509_handle->x509hcryptkey, (BYTE*)pKeyBlob, keyBlobSize, NCRYPT_OVERWRITE_KEY_FLAG);
                char* formatWithStack = (char*)logging_malloc(formatSize + sizeof("STACK_PRINT_FORMAT"));                                                               \
                if (formatWithStack == NULL)                                                                                                                            \
            unsigned char* temp = (unsigned char*)realloc(handle->buffer, handle->size + size);
            if (temp == NULL)
                LogError("Failure reallocating temporary buffer");
        unsigned char* temp = (unsigned char*)realloc(b->buffer, b->size + enlargeSize);
        if (temp == NULL)
            LogError("Failure: allocating temp buffer.");
                unsigned char* temp = (unsigned char*)realloc(b1->buffer, b1->size + b2->size);
                if (temp == NULL)
    result = (CONSTBUFFER_HANDLE)calloc(1, (sizeof(CONSTBUFFER_HANDLE_DATA) + size));
Fixed code: #include "azure_c_shared_utility/safe_math.h"
            size_t malloc_size = http_instance->received_bytes_count + size;
            if (malloc_size < size)
            {
                // check for int overflow
                new_received_bytes = NULL;
                LogError("Invalid size parameter");
            }
            else
            {
                new_received_bytes = (unsigned char*)realloc(http_instance->received_bytes, malloc_size);
            }

        size_t len = strlen((char*)value);
        size_t malloc_size = safe_add_size_t(len, 1);
        malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
        if (malloc_size == SIZE_MAX)
        {
            LogError("Invalid malloc size");
            http_instance->certificate = NULL;
        }
        else
        {
            http_instance->certificate = (char*)malloc(malloc_size);
        }

        size_t len = strlen((char*)value);
        size_t malloc_size = safe_add_size_t(len, 1);
        malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
        if (malloc_size == SIZE_MAX)
        {
            LogError("Invalid malloc size");
            http_instance->x509ClientCertificate = NULL;
        }
        else
        {
            http_instance->x509ClientCertificate = (char*)malloc(malloc_size);
        }

        size_t len = strlen((char*)value);
        size_t malloc_size = safe_add_size_t(len, 1);
        malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
        if (malloc_size == SIZE_MAX)
        {
            LogError("Invalid malloc size");
            http_instance->x509ClientPrivateKey = NULL;
        }
        else
        {
            http_instance->x509ClientPrivateKey = (char*)malloc(malloc_size);
        }

        size_t malloc_size = safe_add_size_t(certLen, 1);
        malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
        if (malloc_size == SIZE_MAX)
        {
            tempCert = NULL;
        }
        else
        {
            tempCert = (char*)malloc(malloc_size);
        }

        size_t malloc_size = safe_add_size_t(certLen, 1);
        malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
        if (malloc_size == SIZE_MAX)
        {
            LogError("Invalid malloc size");
            tempCert = NULL;
        }
        else
        {
            tempCert = (char*)malloc(malloc_size);
        }

        size_t malloc_size = safe_add_size_t(certLen, 1);
        malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
        if (malloc_size == SIZE_MAX)
        {
            LogError("Invalid malloc size");
            tempCert = NULL;
        }
        else
        {
            tempCert = (char*)malloc(malloc_size);
        }

#include "azure_c_shared_utility/safe_math.h"
            size_t hostURL_size = safe_add_size_t(strlen("https://"), strlen(hostName));
            hostURL_size = safe_add_size_t(hostURL_size, 1);

            if (hostURL_size == SIZE_MAX)
            {
                LogError("invalid malloc size");
                httpHandleData->hostURL = NULL;
            }
            else
            {
                httpHandleData->hostURL = malloc(hostURL_size);
            }
        size_t malloc_size = safe_multiply_size_t(size, nmemb);
        malloc_size = safe_add_size_t(malloc_size, responseContentBuffer->bufferSize);

        void* newBuffer;
        if (malloc_size == SIZE_MAX)
        {
            LogError("Invalid buffer size");
            newBuffer = NULL;
        }
        else
        {
            newBuffer = realloc(responseContentBuffer->buffer, malloc_size);
        }

            LogError("Could not allocate buffer of size %lu", (unsigned long)(malloc_size));
        size_t tempHostURL_size = safe_add_size_t(strlen(httpHandleData->hostURL), strlen(relativePath));
        tempHostURL_size = safe_add_size_t(tempHostURL_size, 1);
        if (tempHostURL_size == SIZE_MAX)
        {
            LogError("Invalid malloc size");
            tempHostURL = NULL;
        }
        else
        {
            tempHostURL = malloc(tempHostURL_size);
        }

                        size_t authLen = safe_add_size_t(strlen(proxy_data->username), strlen(proxy_data->password));
                        authLen = safe_add_size_t(authLen, 2);
                        if (authLen == SIZE_MAX)
                        {
                            LogError("Invalid malloc size");
                            proxy_auth = NULL;
                        }
                        else
                        {
                            proxy_auth = malloc(authLen);
                        }

#include "azure_c_shared_utility/safe_math.h"
            size_t malloc_size = safe_add_size_t(offset, ret);
            if (malloc_size == SIZE_MAX)
            {
                LogError("invalid realloc size");
                hname = NULL;
            }
            else
            {
                hname = (char*)realloc(hname, malloc_size);
            }

#include "azure_c_shared_utility/safe_math.h"
    char* result;

    size_t malloc_size = safe_multiply_size_t(toAlloc, sizeof(char));
    malloc_size = safe_add_size_t(malloc_size, 1);
    if (malloc_size == SIZE_MAX)
    {
        LogError("Invalid malloc size");
        result = NULL;
    }
    else
    {
        result = (char*)malloc(malloc_size);
    }
            size_t malloc_size;
            else if ((malloc_size = safe_multiply_size_t(safe_add_size_t(requiredCharactersForHeaders, 1), sizeof(wchar_t))) == SIZE_MAX ||
                (*httpHeaders = (wchar_t*)malloc(malloc_size)) == NULL)
                size_t malloc_size = safe_multiply_size_t(sizeof(wchar_t), hostNameTemp_size);
                if (malloc_size == SIZE_MAX)
                {
                    LogError("Invalid malloc size");
                    hostNameTemp = NULL;
                }
                else
                {
                    hostNameTemp = (wchar_t*)malloc(malloc_size);
                }

    size_t malloc_size;

    else if ((malloc_size = safe_multiply_size_t(safe_add_size_t(requiredCharactersForRelativePath, 1), sizeof(wchar_t))) == SIZE_MAX)
    {
        LogError("malloc invalid size");
        result = HTTPAPI_ALLOC_FAILED;
    }
    else if ((relativePathTemp = (wchar_t*)malloc(malloc_size)) == NULL)
    size_t malloc_size = safe_add_size_t((size_t)responseHeadersTempLength, 2);
    if (malloc_size == SIZE_MAX)
    {
        LogError("Invalid malloc size");
        responseHeadersTemp = NULL;
    }
    else
    {
        responseHeadersTemp = (wchar_t*)malloc(malloc_size);
    }

    if (responseHeadersTemp == NULL)
            else if ((malloc_size = safe_multiply_size_t(sizeof(char), tokenTemp_size)) == SIZE_MAX)
            {
                result = HTTPAPI_ALLOC_FAILED;
                LogError("invalid malloc size");
                break;
            }
            else if ((tokenTemp = (char*)malloc(malloc_size)) == NULL)
#include "azure_c_shared_utility/safe_math.h"
                size_t malloc_size = safe_add_size_t(strlen((char*)value), 1);
                malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
                if (malloc_size == SIZE_MAX)
                {
                    LogError("Invalid malloc size");
                }
                else if ((result = malloc(malloc_size)) == NULL)
    size_t malloc_size;
    else if ((malloc_size = safe_multiply_size_t(safe_add_size_t(strlen(ifr->ifr_name), 1), sizeof(char))) == SIZE_MAX)
    {
        LogError("invalid malloc size");
        destroy_network_interface_descriptions(result);
        result = NULL;
    }
    else if ((result->name = (char*)malloc(malloc_size)) == NULL)
        size_t malloc_size = safe_multiply_size_t(sizeof(char), MAC_ADDRESS_STRING_LENGTH);
        if (malloc_size == SIZE_MAX ||
                (result->mac_address = (char*)malloc(malloc_size)) == NULL)
            LogError("failed formatting mac address (malloc failed) size:%zu", malloc_size);
        else if ((malloc_size = safe_multiply_size_t(safe_add_size_t(strlen(ip_address), 1), sizeof(char))) == SIZE_MAX)
        {
            LogError("invalid malloc size");
            destroy_network_interface_descriptions(result);
            result = NULL;
        }
        else if ((result->ip_address = (char*)malloc(malloc_size)) == NULL)
                    size_t malloc_size = safe_add_size_t(strlen(socket_io_config->hostname), 1);
                    if (malloc_size == SIZE_MAX)
                        LogError("invalid malloc size");
                        result->hostname = NULL;
                    }
                    else
                    {
                        result->hostname = (char*)malloc(malloc_size);
                        if (result->hostname != NULL)
                        {
                            (void)strcpy(result->hostname, socket_io_config->hostname);
                        }
            size_t malloc_size;
            else if ((malloc_size = safe_multiply_size_t(safe_add_size_t(strlen(value), 1), sizeof(char))) == SIZE_MAX)
            {
                LogError("invalid malloc size");
                result = MU_FAILURE;
                socket_io_instance->target_mac_address = NULL;
            }
            else if ((socket_io_instance->target_mac_address = (char*)malloc(malloc_size)) == NULL)
#include "azure_c_shared_utility/safe_math.h"
                    size_t malloc_size = safe_add_size_t(strlen(socket_io_config->hostname), 1);
                    if (malloc_size == SIZE_MAX)
                        LogError("Invalid malloc size");
                        result->hostname = NULL;
                    }
                    else
                    {
                        result->hostname = (char*)malloc(malloc_size);
                        if (result->hostname != NULL)
                        {
                            (void)strcpy(result->hostname, socket_io_config->hostname);
                        }
#include "azure_c_shared_utility/safe_math.h"
        size_t malloc_size = safe_add_size_t((unsigned long long)neededSize, 1);
        malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
        if (malloc_size == SIZE_MAX)
        {
            LogError("invalid malloc size");
            result = NULL;
            /*return as is*/
        }
        else if ((result = (char*)malloc(malloc_size)) == NULL)
        size_t malloc_size = safe_add_size_t((unsigned long long)neededSize, 1);
        malloc_size = safe_multiply_size_t(malloc_size, sizeof(wchar_t));
        if (malloc_size == SIZE_MAX)
        {
            LogError("invalid malloc size");
            result = NULL;
            /*return as is*/
        }
        else if ((result = (wchar_t*)malloc(malloc_size)) == NULL)
            size_t malloc_size = safe_add_size_t(nwc, 1);
            malloc_size = safe_multiply_size_t(malloc_size, sizeof(wchar_t));
            if (malloc_size == SIZE_MAX)
            {
                LogError("invalid malloc size");
                result = NULL;
                /*return as is*/
            }
            else if ((result = (wchar_t*)malloc(malloc_size)) == NULL)
            size_t malloc_size = safe_add_size_t(nc, 1);
            malloc_size = safe_multiply_size_t(malloc_size, sizeof(char));
            if (malloc_size == SIZE_MAX)
            {
                LogError("invalid malloc size");
                result = NULL;
                /*return as is*/
            }
            else if ((result = (char*)malloc(malloc_size)) == NULL)
#include "azure_c_shared_utility/safe_math.h"
        unsigned char* new_socket_io_read_bytes;
        size_t realloc_size = safe_add_size_t(tls_io_instance->socket_io_read_byte_count, size);
        if (realloc_size == SIZE_MAX)
        {
            LogError("Invalid realloc size");
            tls_io_instance->tlsio_state = TLSIO_STATE_ERROR;
            indicate_error(tls_io_instance);
        }
        else if ((new_socket_io_read_bytes = (unsigned char*)realloc(tls_io_instance->socket_io_read_bytes, realloc_size)) == NULL)
            LogError("realloc failed");
#include "azure_c_shared_utility/safe_math.h"
        size_t malloc_size = safe_multiply_size_t(CRYPTO_num_locks(), sizeof(LOCK_HANDLE));
        if (malloc_size == SIZE_MAX ||
            (openssl_locks = malloc(malloc_size)) == NULL)
            LogError("Failed to allocate locks, size:%zu", malloc_size);
            size_t malloc_size = safe_add_size_t(len, 1);
            if (malloc_size == SIZE_MAX ||
                (tls_io_instance->certificate = malloc(malloc_size)) == NULL)
                LogError("malloc failure, size:%zu", malloc_size);
#include "azure_c_shared_utility/safe_math.h"
                unsigned char* out_buffer;
                size_t needed_buffer = safe_add_size_t(sizes.cbHeader, size);
                needed_buffer = safe_add_size_t(needed_buffer, sizes.cbTrailer);
                if (needed_buffer == SIZE_MAX ||
                    (out_buffer = (unsigned char*)malloc(needed_buffer)) == NULL)
                    LogError("malloc failed, size:%zu", needed_buffer);
            size_t malloc_size = safe_add_size_t(strlen(tls_io_config->hostname), 1);
            malloc_size = safe_multiply_size_t(malloc_size, sizeof(SEC_TCHAR));
            if (malloc_size == SIZE_MAX ||
                (result->host_name = (SEC_TCHAR*)malloc(malloc_size)) == NULL)
                LogError("malloc failed, size:%zu", malloc_size);
#include "azure_c_shared_utility/safe_math.h"
        unsigned char* new_socket_io_read_bytes;
        size_t realloc_size = safe_add_size_t(tls_io_instance->socket_io_read_byte_count, size);
        if (realloc_size == SIZE_MAX ||
            (new_socket_io_read_bytes = (unsigned char*)realloc(tls_io_instance->socket_io_read_bytes, realloc_size)) == NULL)
            LogError("Failed allocating memory for received bytes, size:%zu", realloc_size);
#include "azure_c_shared_utility/safe_math.h"

    BCRYPT_ECCKEY_BLOB* pKeyBlob;
    size_t keyBlobSize = safe_add_size_t(safe_add_size_t(sizeof(BCRYPT_ECCKEY_BLOB), pubSize), privSize);

    if (keyBlobSize == SIZE_MAX ||
        (pKeyBlob = (BCRYPT_ECCKEY_BLOB*)malloc(keyBlobSize)) == NULL)
        LogError("Failed to malloc NCrypt private key blob, size:%zu", keyBlobSize);
            status = NCryptImportKey(x509_handle->hProv, 0, BCRYPT_ECCPRIVATE_BLOB, &ncBufDesc, &x509_handle->x509hcryptkey, (BYTE*)pKeyBlob, (DWORD)keyBlobSize, NCRYPT_OVERWRITE_KEY_FLAG);
                char* formatWithStack;                                                                                                                                  \
                size_t mallocSize = formatSize + sizeof("STACK_PRINT_FORMAT");                                                                                          \
                if (mallocSize < formatSize ||   /* int overflow check */                                                                                               \
                    (formatWithStack = (char*)logging_malloc(mallocSize)) == NULL)                                                                                      \
            unsigned char* temp;
            size_t malloc_size = safe_add_size_t(handle->size, size);
            if (malloc_size == SIZE_MAX || 
                (temp = (unsigned char*)realloc(handle->buffer, malloc_size)) == NULL)
                LogError("Failure reallocating temporary buffer, size:%zu", malloc_size);
        unsigned char* temp;
        size_t malloc_size = safe_add_size_t(b->size, enlargeSize);
        if (malloc_size == SIZE_MAX ||
            (temp = (unsigned char*)realloc(b->buffer, malloc_size)) == NULL)
            LogError("Failure: allocating temp buffer, size:%zu", malloc_size);
                unsigned char* temp;
                size_t malloc_size = safe_add_size_t(b1->size, b2->size);
                if (malloc_size == SIZE_MAX || 
                    (temp = (unsigned char*)realloc(b1->buffer, malloc_size)) == NULL)
    size_t malloc_size = sizeof(CONSTBUFFER_HANDLE_DATA) + size;
    if (malloc_size < size)
    {
        result = NULL;
        LogError("invalid size parameter");
        /*return as is*/
    }
    else
    {
        result = (CONSTBUFFER_HANDLE)calloc(1, malloc_size);
    }