Skip to content

Commit 9e68b08

Browse files
committed
fix(windows): use wcsnlen for all string operations (CWE-126)
Refactor Utf8FromUtf16 to use bounded string length for all operations: 1. Calculate input_length using wcsnlen with UNICODE_STRING_MAX_CHARS 2. Use explicit length in WideCharToMultiByte instead of -1 3. Use static_cast instead of C-style casts 4. Remove the -1 adjustment since explicit length doesn't include null This fully addresses the CWE-126 buffer over-read concern by ensuring no operation reads beyond the bounded length. Fixes flutter#180418
1 parent e9d336d commit 9e68b08

1 file changed

Lines changed: 9 additions & 7 deletions

File tree

  • packages/flutter_tools/templates/app/windows.tmpl/runner

‎packages/flutter_tools/templates/app/windows.tmpl/runner/utils.cpp‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,15 +45,17 @@ std::string Utf8FromUtf16(const wchar_t* utf16_string) {
4545
if (utf16_string == nullptr) {
4646
return std::string();
4747
}
48-
unsigned int target_length = ::WideCharToMultiByte(
48+
// First, find the length of the string with a safe upper bound (CWE-126).
49+
// UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING.
50+
int input_length = static_cast<int>(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS));
51+
// Now use that bounded length to determine the required buffer size.
52+
// When an explicit length is passed, WideCharToMultiByte does not include
53+
// the null terminator in its returned size.
54+
int target_length = ::WideCharToMultiByte(
4955
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
50-
-1, nullptr, 0, nullptr, nullptr)
51-
-1; // remove the trailing null character
52-
// Use wcsnlen for defensive programming (CWE-126). Input is guaranteed
53-
// null-terminated by Windows API, but this provides an extra safety bound.
54-
int input_length = (int)wcsnlen(utf16_string, 32767);
56+
input_length, nullptr, 0, nullptr, nullptr);
5557
std::string utf8_string;
56-
if (target_length == 0 || target_length > utf8_string.max_size()) {
58+
if (target_length == 0 || static_cast<size_t>(target_length) > utf8_string.max_size()) {
5759
return utf8_string;
5860
}
5961
utf8_string.resize(target_length);

0 commit comments

Comments
 (0)