From 51885f3a5e963b24ed93385817ba8262b9cfd162 Mon Sep 17 00:00:00 2001 From: Byonggon Chun Date: Wed, 18 Nov 2020 15:31:04 +0900 Subject: [PATCH] fix wrong memory usage in buildAndsendSetupRequest Summary - The function is supposed to re-allocate memory to increase buffer size, when larger buffer is required to encode the given asn data, but current impl doesn't do that, so it will lead us to seg fault or memory corruption. Changes - make the function to allocate memory in heap for asn encoding buffer rather than stack - make the function to re-allocate memory when encoded data is larger than the given buffer - free allocated memory Issue-ID: RIC-697 Change-Id: I8862f1ee6bff27f898778ae896f8b41830ad6daa Signed-off-by: Byonggon Chun --- RIC-E2-TERMINATION/sctpThread.cpp | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/RIC-E2-TERMINATION/sctpThread.cpp b/RIC-E2-TERMINATION/sctpThread.cpp index 3869450..be75cd7 100644 --- a/RIC-E2-TERMINATION/sctpThread.cpp +++ b/RIC-E2-TERMINATION/sctpThread.cpp @@ -1233,7 +1233,13 @@ static void buildAndSendSetupRequest(ReportingMessages_t &message, asn_enc_rval_t er; auto buffer_size = RECEIVE_SCTP_BUFFER_SIZE * 2; - unsigned char buffer[RECEIVE_SCTP_BUFFER_SIZE * 2]; + unsigned char *buffer = nullptr; + buffer = (unsigned char *) calloc(buffer_size, sizeof(unsigned char)); + if(!buffer) + { + mdclog_write(MDCLOG_ERR, "Allocating buffer for %s failed, %s", asn_DEF_E2AP_PDU.name, strerror(errno)); + return; + } while (true) { er = asn_encode_to_buffer(nullptr, ATS_BASIC_XER, &asn_DEF_E2AP_PDU, pdu, buffer, buffer_size); if (er.encoded == -1) { @@ -1245,7 +1251,17 @@ static void buildAndSendSetupRequest(ReportingMessages_t &message, (int) buffer_size, asn_DEF_E2AP_PDU.name, buffer_size); buffer_size = er.encoded + 128; -// free(buffer); + + unsigned char *newBuffer = nullptr; + newBuffer = (unsigned char *) realloc(buffer, buffer_size); + if (!newBuffer) + { + // out of memory + mdclog_write(MDCLOG_ERR, "Reallocating buffer for %s failed, %s", asn_DEF_E2AP_PDU.name, strerror(errno)); + free(buffer); + return; + } + buffer = newBuffer; continue; } buffer[er.encoded] = '\0'; @@ -1318,9 +1334,13 @@ static void buildAndSendSetupRequest(ReportingMessages_t &message, } message.peerInfo->gotSetup = true; buildJsonMessage(message); + if (rmrMsg != nullptr) { rmr_free_msg(rmrMsg); } + free(buffer); + + return; } #if 0 -- 2.16.6