From bab1b2ca3c80dc97cfeec23df291064147e4c013 Mon Sep 17 00:00:00 2001 From: Rick Altherr Date: Mon, 24 Jun 2024 15:21:42 -0700 Subject: [PATCH] Fix buffer overflow in Log Log line prefix is written to the buffer before the log message. While the buffer start was being adjusted when writing the log message via vsnprintf(), the buffer size was not. This would allow a log message to write past the end of the stack-allocated buffer. --- Log.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Log.cpp b/Log.cpp index 752601e5..9c94b0fd 100644 --- a/Log.cpp +++ b/Log.cpp @@ -149,25 +149,29 @@ void Log(unsigned int level, const char* fmt, ...) { assert(fmt != NULL); - char buffer[501U]; + size_t buffer_len = 501U; + char buffer[buffer_len]; + int count; #if defined(_WIN32) || defined(_WIN64) SYSTEMTIME st; ::GetSystemTime(&st); - ::sprintf(buffer, "%c: %04u-%02u-%02u %02u:%02u:%02u.%03u ", LEVELS[level], st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); + count = ::snprintf(buffer, buffer_len, "%c: %04u-%02u-%02u %02u:%02u:%02u.%03u ", LEVELS[level], st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); #else struct timeval now; ::gettimeofday(&now, NULL); struct tm* tm = ::gmtime(&now.tv_sec); - ::sprintf(buffer, "%c: %04d-%02d-%02d %02d:%02d:%02d.%03lld ", LEVELS[level], tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, now.tv_usec / 1000LL); + count = ::snprintf(buffer, buffer_len, "%c: %04d-%02d-%02d %02d:%02d:%02d.%03lld ", LEVELS[level], tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, now.tv_usec / 1000LL); #endif + assert(count >= 0); + buffer_len -= count; va_list vl; va_start(vl, fmt); - ::vsnprintf(buffer + ::strlen(buffer), 500, fmt, vl); + ::vsnprintf(buffer + count, buffer_len, fmt, vl); va_end(vl);