From d9a0c763637fc247ccfd393476e5bd2342cd5d48 Mon Sep 17 00:00:00 2001 From: liujinchang Date: Mon, 30 Nov 2026 10:12:47 +0800 Subject: [PATCH] fix(encodes): fix heap buffer overflow read in detectCharset MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace the NUL-terminator pointer scan in detectCharset with a size-bounded index loop; the ESC branch could consume the terminator via unbounded reads and then read one byte beyond the heap buffer (CWE-125, reported as heap-buffer-overflow-read by ASan) - Add bounds checks before every byte read in the ISO-2022 escape handling; charset detection results stay identical for all in-bounds inputs - Drop the dead initial read of *text which could touch an empty raw buffer 修复(encodes): 修复 detectCharset 堆缓冲区越界读 - detectCharset 由 NUL 终止符指针扫描改为按 size 的有界索引循环;原 ESC 分支可能经无界读取耗尽终止符后越过堆缓冲区尾再读 1 字节(CWE-125,ASan 报 heap-buffer-overflow-read) - ISO-2022 转义处理每处字节读取前补边界检查;所有合法输入的字符集判定结果保持不变 - 移除开头对 *text 的死读取,避免触碰空 raw 缓冲 Log: 修复编码探测 detectCharset 因 NUL 扫描与 ESC 转义分支无界读导致的堆缓冲区越界读(CWE-125) Bug: https://pms.uniontech.com/bug-view-384151.html PMS: BUG-384151 --- src/common/encoding.cpp | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/common/encoding.cpp b/src/common/encoding.cpp index c5579562..1df51768 100644 --- a/src/common/encoding.cpp +++ b/src/common/encoding.cpp @@ -744,13 +744,15 @@ const QString detectCharset (const QByteArray& byteArray) { qCDebug(appLog) << "Entering detectCharset"; const char* text = byteArray.constData(); - uint8_t c = *text; + const qsizetype size = byteArray.size(); + int pos = 0; + uint8_t c = 0; std::string charset; if (validateUTF8 (byteArray)) { qCDebug(appLog) << "validateUTF8 is true"; - while ((c = *text++) != '\0') + while (pos < size && (c = static_cast(text[pos++])) != '\0') { if (c > 0x7F) { @@ -761,11 +763,15 @@ const QString detectCharset (const QByteArray& byteArray) if (c == 0x1B) /* ESC */ { qCDebug(appLog) << "c == 0x1B"; - c = *text++; + if (pos >= size) + break; + c = static_cast(text[pos++]); if (c == '$') { qCDebug(appLog) << "c == '$'"; - c = *text++; + if (pos >= size) + break; + c = static_cast(text[pos++]); switch (c) { case 'B': // JIS X 0208-1983 @@ -778,7 +784,9 @@ const QString detectCharset (const QByteArray& byteArray) charset = "ISO-2022-JP-2"; break; case '(': - c = *text++; + if (pos >= size) + break; + c = static_cast(text[pos++]); switch (c) { case 'C': // KSC5601-1987 @@ -788,7 +796,9 @@ const QString detectCharset (const QByteArray& byteArray) } break; case ')': - c = *text++; + if (pos >= size) + break; + c = static_cast(text[pos++]); if (c == 'C') { qCDebug(appLog) << "c == 'C'";