From c7e904cf3eb226e857b7d1a5dab0d85bab4e1bc5 Mon Sep 17 00:00:00 2001 From: Matt Jones <47545907+SoundMatt@users.noreply.github.com> Date: Tue, 5 May 2026 07:25:00 -0700 Subject: [PATCH] lib: fix heap buffer overflow in dlt_with_filename_and_line_number When the source filename string is longer than 255 bytes, dlt_with_filename_and_line_number(fina, linr) overflows the heap buffer it allocates for dlt_user.filename: dlt_user.filenamelen = (uint8_t)strlen(fina); // truncates ... dlt_user.filename = malloc(dlt_user.filenamelen + 1); // small strcpy(dlt_user.filename, fina); // full filenamelen is uint8_t (matching the V2 wire-format field width declared in include/dlt/dlt_user.h.in), so the cast truncates strlen(fina) modulo 256. The subsequent malloc allocates the truncated length + 1, but strcpy copies the entire fina including its real terminator, writing strlen(fina) - filenamelen bytes past the end of the heap chunk. Reachable in practice via long compile-time __FILE__ paths (monorepo-rooted absolute paths) and any application that forwards a user-controlled filename through this function. Fix: clamp strlen(fina) to UINT8_MAX before assigning filenamelen, allocate against the clamped length, and copy with memcpy + explicit null terminator instead of strcpy. The on-wire field still gets the truncated length, which matches the maximum the V2 protocol can encode. --- src/lib/dlt_user.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/lib/dlt_user.c b/src/lib/dlt_user.c index 31e9d3d51..d11eede22 100644 --- a/src/lib/dlt_user.c +++ b/src/lib/dlt_user.c @@ -4673,18 +4673,28 @@ DltReturnValue dlt_with_filename_and_line_number(const char *fina, const int lin /* Set filename and line number */ dlt_user.with_filename_and_line_number = 1; - dlt_user.filenamelen = (uint8_t)strlen(fina); + + /* filenamelen is uint8_t (matching the V2 wire-format field width). + * Clamp the source length to UINT8_MAX before truncation so that + * the malloc + copy below cannot write past the end of the heap + * allocation when strlen(fina) > 255. */ + size_t fina_len = strlen(fina); + if (fina_len > UINT8_MAX) + fina_len = UINT8_MAX; + dlt_user.filenamelen = (uint8_t)fina_len; + if (dlt_user.filename != NULL) { free(dlt_user.filename); dlt_user.filename = NULL; } - dlt_user.filename = (char*)malloc((size_t)dlt_user.filenamelen + 1); + dlt_user.filename = (char*)malloc(fina_len + 1); if (dlt_user.filename == NULL){ dlt_vlog(LOG_ERR, "%s Could not allocate memory for filename", __func__); return DLT_RETURN_ERROR; } - strcpy(dlt_user.filename, fina); + memcpy(dlt_user.filename, fina, fina_len); + dlt_user.filename[fina_len] = '\0'; dlt_user.linenumber = (uint32_t)linr; return DLT_RETURN_OK;