From 72b1ffb7aba8990cfee9e6f3bb70351c80a34e02 Mon Sep 17 00:00:00 2001 From: CodeChronos <1197535+CodeChronos928@users.noreply.github.com> Date: Mon, 13 Jun 2022 06:57:06 -0700 Subject: [PATCH] Fix out-of-bounds memory read (#19500) CopyString copies one byte past the end of a non-terminated source string, then overwrites it with nul. The version of CopyString taking a const char* source expects it to be nul terminated. When called from ScopedMemoryString() the destination buffer is always one byte larger than the source, and the source may not be terminated. The result is a one-byte out-of-bounds memory read in CopyString(). This change modifies ScopedMemoryString() to wrap the source string in a CharSpan, so it calls the version of CopyString that handles unterminated source strings. --- src/lib/support/CHIPMemString.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/lib/support/CHIPMemString.h b/src/lib/support/CHIPMemString.h index 3a7497cb08f9b9..51341192a76250 100644 --- a/src/lib/support/CHIPMemString.h +++ b/src/lib/support/CHIPMemString.h @@ -171,7 +171,10 @@ class ScopedMemoryString : public ScopedMemoryBuffer ScopedMemoryString(const char * string, size_t length) { size_t lengthWithNull = length + 1; - CopyString(Alloc(lengthWithNull).Get(), lengthWithNull, string); + + // We must convert the source string to a CharSpan, so we call the + // version of CopyString that handles unterminated strings. + CopyString(Alloc(lengthWithNull).Get(), lengthWithNull, CharSpan(string, length)); } };