GHSL-2023-112, GHSL-2023-102, GHSL-2023-103, GHSL-2023-092: Buffer Overflows in Notepad++ - CVE-2023-40031, CVE-2023-40036, CVE-2023-40164, CVE-2023-40166
Notepad++ contains four memory-safety bugs in its file-loading and encoding-detection code. Opening a crafted file can cause out-of-bounds reads and a heap write overflow, which the report says may lead to arbitrary code execution or leak internal memory information.
Notepad++ reads and writes past the end of a buffer bounds on opening a crafted file.
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
Notepad++ is a Windows text and source code editor. On opening a file it reads the content in blocks, converts between encodings, and runs language and encoding detection over the first bytes of the file. Four separate memory-safety bugs were found in that path, all reachable simply by opening a crafted file. They were reported to the Notepad++ maintainer as GHSL-2023-092, GHSL-2023-102, GHSL-2023-103 and GHSL-2023-112, and published on 2023-08-21 under the GitHub Security Lab coordinated disclosure policy.
The affected code is in PowerEditor/src: the UTF-16 to UTF-8 converter (Utf8_16.cpp), a diverged copy of the uchardet encoding detection library (uchardet/), and the file loading and language detection logic in ScintillaComponent/Buffer.cpp.
Setup
- Product: Notepad++ v8.5.2 (the tested version).
- Platform: Windows. The proof of concept outputs come from AddressSanitizer builds; the report notes that building with ASAN is optional because the reports contain enough information to set breakpoints and reproduce with the PoC files.
- Tools: an ASAN build of Notepad++ (the report links the MSVC ASAN documentation), and for the fourth issue GFlags to enable page heap for
notepad++.exe. - No account or special role is needed: the precondition for every issue is that a victim opens a crafted file.
Finding it
The common thread is that file content is treated as trusted input to size calculations and array indexes. In the converter, the output buffer size is computed from the input length with an assumption that breaks for an odd byte count. In the uchardet copy, table indexes derived from file bytes are compared against a table size that does not match the actual array, or are not checked at all. In the language detector, a fixed 40-byte read is taken from a pointer that may already be at the end of the loaded block. Each was confirmed with a small crafted file and an ASAN build (or a breakpoint).
Exploitation
Issue 1: Heap buffer write overflow in Utf8_16_Read::convert (GHSL-2023-112, CVE-2023-40031)
Utf8_16_Read::convert allocates a new buffer for UTF-16 to UTF-8 conversion and sizes it assuming that, in the worst case, every two UTF-16 input bytes need three UTF-8 bytes:
...
case uni16LE: {
size_t newSize = len + len / 2 + 1; // [2]
if (m_nAllocatedBufSize != newSize)
{
if (m_pNewBuf)
delete[] m_pNewBuf;
m_pNewBuf = NULL;
m_pNewBuf = new ubyte[newSize]; // [1]
m_nAllocatedBufSize = newSize;
}
ubyte* pCur = m_pNewBuf;
m_Iter16.set(m_pBuf + nSkip, len - nSkip, m_eEncoding);
while (m_Iter16)
{
++m_Iter16; // [3]
utf8 c;
while (m_Iter16.get(&c)) // [4]
*pCur++ = c; // [5]
}
...
When the input length is a malformed odd number of bytes the calculation is off. In the PoC, when a second chunk of bytes is processed, len is 9 and newSize becomes 14 (9 + 9 / 2 + 1). After the first 8 input bytes are consumed ([3] and [4]), pCur has already been shifted by 12 elements in the 14-element m_pNewBuf array. Utf16_Iter::operator++ then consumes the last 9th byte and the 10th byte beyond the input len. Because Notepad++ reads files in chunks, that 10th byte is still inside a valid buffer but holds old chunk data. The write in [5] then puts three bytes into pCur, overflowing the array.
The report's suggested fix is to make the iterator's validity operator check both the current and the next pointer against the end, since Utf16_Iter::read() always consumes two bytes:
operator bool() { return (m_pRead + 1 < m_pEnd) || (m_out1st != m_outLst); };
To reproduce:
- Create a file with the following python script:
with open("poc", "wb") as f:
f.write(b'\xfe\xff')
f.write(b'\xff' * (128 * 1024 + 4 - 2 + 1))
- Make an ASAN build of Notepad++.
- Open the file in Notepad++ to hit the out of bounds access with ASAN.
The ASAN output shows a heap-buffer-overflow write of size 1 in Utf8_16_Read::convert at Utf8_16.cpp:181, reached from FileManager::loadFileData, FileManager::loadFile, Notepad_plus::doOpen and the window message loop. The address is 0 bytes to the right of a 2-byte region allocated by operator new[] in Utf8_16_Read::convert at Utf8_16.cpp:168. The report's impact statement for this issue is that it may lead to arbitrary code execution.
Issue 2: Global buffer read overflow in CharDistributionAnalysis::HandleOneChar (GHSL-2023-102, CVE-2023-40036)
Notepad++ uses a diverged copy of uchardet. In HandleOneChar, the array index order in [1] depends on the input file content and can be set larger than the size of the mCharToFreqOrder buffer, producing an out of bounds read:
//Feed a character with known length
void HandleOneChar(const char* aStr, PRUint32 aCharLen)
{
PRInt32 order;
//we only care about 2-bytes character in our distribution analysis
order = (aCharLen == 2) ? GetOrder(aStr) : -1;
if (order >= 0)
{
mTotalChars++;
//order is valid
if ((PRUint32)order < mTableSize) // [2]
{
if (512 > mCharToFreqOrder[order]) // [1] buffer read overflow
mFreqChars++;
}
}
}
In the PoC, order is set to 5419 while mCharToFreqOrder (a pointer to the global array EUCTWCharToFreqOrder) has 5376 elements. There is a check [2] against mTableSize, but mTableSize for EUCTWCharToFreqOrder is declared as 8102, so the check does not stop the out of bounds index. The report notes that this behaviour has been fixed in the freedesktop.org uchardet.
To reproduce:
with open("poc", "wb") as f:
f.write(b'\xfd\xde')
- Make an ASAN build of Notepad++ or set a breakpoint at
if (512 > mCharToFreqOrder(order)). - Open the file to hit the breakpoint or the out of bounds access with ASAN.
The ASAN output reports a global-buffer-overflow, READ of size 2, in HandleOneChar at CharDistribution.h:69:19, called from nsEUCTWProber::HandleData, nsMBCSGroupProber::HandleData, nsUniversalDetector::HandleData and uchardet_handle_data. The address is 86 bytes to the right of the global variable EUCTWCharToFreqOrder (size 10752).
Issue 3: Global buffer read overflow in nsCodingStateMachine::NextState (GHSL-2023-103, CVE-2023-40164)
In the same uchardet copy, the array index byteCls in [1] depends on the input file content and can be set larger than the size of the charLenTable buffer:
nsSMState NextState(char c) {
//for each byte we get its class , if it is first byte, we also get byte length
PRUint32 byteCls = GETCLASS(c);
if (mCurrentState == eStart)
{
mCurrentBytePos = 0;
mCurrentCharLen = mModel->charLenTable[byteCls]; // [1] buffer read overflow
}
In the PoC, byteCls is set to 9, while charLenTable points to ISO2022JPCharLenTable, which contains only 8 elements. This behaviour has also been fixed in the freedesktop.org uchardet.
To reproduce:
with open("poc", "wb") as f:
f.write(b'\x49\x7e\x7b')
- Make an ASAN build of Notepad++ or set a conditional breakpoint at
mCurrentCharLen = mModel->charLenTable(byteCls);whenbyteCls == 9.
The ASAN output reports a global-buffer-overflow, READ of size 4, in NextState at nsCodingStateMachine.h:72:25, called from nsEscCharSetProber::HandleData, nsUniversalDetector::HandleData and uchardet_handle_data. The address is 4 bytes to the right of the global variable ISO2022JPCharLenTable (size 32), 28 bytes to the left of a string literal ISO-2022-JP, and 60 bytes to the left of ISO2022KRSMModel.
For both uchardet issues the report states that exploitability is not clear, and that they may potentially be used to leak internal memory allocation information.
Issue 4: Heap buffer read overflow in FileManager::detectLanguageFromTextBegining (GHSL-2023-092, CVE-2023-40166)
On file open, FileManager::loadFile allocates a fixed size buffer:
char* data = new char[blockSize + 8]; // +8 for incomplete multibyte char
...
bool res = loadFileData(doc, fileSize, backupFileName ? backupFileName : fullpath, data, &UnicodeConvertor, loadedFileFormat);
delete[] data;
FileManager::loadFileData loads the first block of data into the buffer [1] and calls detectLanguageFromTextBegining to identify the content type from the beginning of the file [2]:
lenFile = fread(data + incompleteMultibyteChar, 1, blockSize - incompleteMultibyteChar, fp) + incompleteMultibyteChar; // 1
if (ferror(fp)) != 0)
{
success = false;
break;
}
if (lenFile == 0) break;
...
fileFormat._language = detectLanguageFromTextBegining((unsigned char *)data, lenFile); // 2
FileManager::detectLanguageFromTextBegining advances the data pointer until a non-space character is found or lenFile is reached [3]. In the latter case it keeps going and reads 32 bytes (40 - 8, the extra padding added for the incomplete multibyte character case) past the end of the data buffer [4]:
LangType FileManager::detectLanguageFromTextBegining(const unsigned char *data, size_t dataLen)
{
...
// Skip any space-like char
for (; i < dataLen; ++i) // 3
{
if (data[i] != ' ' && data[i] != '\t' && data[i] != '\n' && data[i] != '\r')
break;
}
// Create the buffer to need to test
const size_t longestLength = 40; // shebangs can be large
std::string buf2Test = std::string((const char*)data + i, longestLength); // 4 OOB READ
The report's fix suggestion is to check, at the end of the loop, that i + longestLength is still less than dataLen.
To reproduce:
- Enable page heap for
notepad++.exein GFlags. - Create a
poc.xmlwith the following python script:
with open("poc.xml", "w") as f:
f.write(" " * (128 * 1024 + 4))
- Open the file with Notepad++ to trigger the memory read exception.
As with the uchardet issues, the report states that exploitability is not clear and that the bug may potentially be used to leak internal memory allocation information.
Root cause
Each issue is a bounds mistake on data derived from the file:
- The UTF-16 to UTF-8 converter sizes its output buffer for an even byte count and its iterator consumes two bytes at a time, but the validity check does not require the next byte to be inside the input. An odd
lentherefore lets the iterator step past the input and the writer run past the allocation. HandleOneCharvalidatesorderagainstmTableSize, butmTableSizeforEUCTWCharToFreqOrderis declared as 8102 while the array has 5376 elements, so the guard passes for indexes that are out of bounds.NextStateindexescharLenTablewith a byte class taken from the input without any bounds check, whileISO2022JPCharLenTablehas only 8 elements.detectLanguageFromTextBeginingskips leading whitespace up todataLenand then unconditionally constructs a 40-byte string fromdata + i, without checking thati + longestLengthis withindataLen.
In the first case the chunked reading of files means the byte read past len is still inside a valid buffer, which is why the overflow shows up as a write rather than an immediate read fault.
Impact
- GHSL-2023-112: may lead to arbitrary code execution.
- GHSL-2023-102, GHSL-2023-103 and GHSL-2023-092: exploitability is not clear; potentially usable to leak internal memory allocation information.
All four are triggered by opening a crafted file, so the attacker needs the victim to open it in Notepad++.
Fix
The report gives fix suggestions for GHSL-2023-112 (the iterator validity check shown above) and GHSL-2023-092 (check i + longestLength against dataLen). For GHSL-2023-102 and GHSL-2023-103 it points to the upstream fixes in freedesktop.org uchardet. Private security advisories and private pull requests with fix suggestions were created for the maintainer. The timeline records that Notepad++ v8.5.3 (2023-05-15), v8.5.4 (2023-06-18), v8.5.5 (2023-08-09) and v8.5.6 (2023-08-15) were released without the fixes before publication.
Variants to test
- Odd-length UTF-16 input in any editor or converter that sizes an output buffer from the input length: a positive result is an ASAN heap-buffer-overflow write in the conversion routine when the file is opened.
- Encoding detection libraries with table-driven indexes: compare each table's declared size with the actual array length, and try inputs that drive the index past the real array. A positive result is an ASAN global-buffer-overflow read in the prober.
- Fixed-length reads after a scan loop (shebang or language detection, magic-byte checks): feed a file made only of the scanned character up to the block boundary. A positive result is a read past the allocated block, visible with page heap or ASAN.
- Chunked file readers: look for logic that assumes the next byte after a chunk is valid, since stale chunk data can mask a read and turn it into a write.
Hunting notes
This class of bug hides in code that parses untrusted files before any validation: encoding converters, charset detectors, language and shebang detection, and anything that computes a buffer size from an input length. During review, look for size formulas with integer division or fixed padding, table lookups indexed by input bytes, and loops that advance a pointer to a length limit and then read a fixed amount. The report's evidence pattern is effective for a program: a minimal generator script, a reproducible ASAN (or page heap) crash with the exact function and line, and a concrete fix suggestion. The timeline also shows the value of persisting: the maintainer asked for a binary PoC instead of a Python script and reported that v8.5.4 did not compile with ASAN, and the researchers provided the binary PoC and confirmed the issue was still reproducible in their setup before publishing.
What happened, in plain words
Notepad++ is a free text and source code editor for Windows. When you open a file in it, the program has to read the bytes of that file, work out what kind of text it contains (for example, which character encoding it uses), and convert it into a form the editor can display. That reading and guessing happens before you have done anything with the file, and it trusts the file to be well formed.
Four separate mistakes were found in that early reading path. Each one is a memory-safety bug: a situation where the program reads or writes memory it should not touch. All four can be triggered simply by opening a specially crafted file. They were reported to the Notepad++ maintainer as GHSL-2023-092, GHSL-2023-102, GHSL-2023-103 and GHSL-2023-112, and published on 2023-08-21 under the GitHub Security Lab coordinated disclosure policy.
To understand the rest of this article you need one idea: a program keeps its data in memory, a big numbered shelf of small storage slots. Each slot has an address, like a house number. A buffer is a reserved run of neighbouring slots that the program has set aside for one purpose, for example to hold the contents of a file. Reading or writing outside that reserved run is called a buffer overflow (or out of bounds access). It is dangerous because the neighbouring slots may belong to something else entirely, and the program has no idea it is trampling them.
The affected code lives in the PowerEditor/src folder of the Notepad++ source: the converter that turns UTF-16 text into UTF-8 (Utf8_16.cpp), a modified copy of a library called uchardet that guesses character encodings (uchardet/), and the file loading and language detection code in ScintillaComponent/Buffer.cpp.
Setting the scene
- Product: Notepad++ version 8.5.2, the version the researchers tested.
- Platform: Windows. The crash outputs shown below come from builds made with AddressSanitizer (ASAN), a tool that adds checks around memory so that an out of bounds access is caught immediately and reported with a stack trace instead of silently corrupting things. The report notes that building with ASAN is optional, because the reports contain enough detail to set breakpoints and reproduce the problem with the proof of concept files.
- Tools: an ASAN build of Notepad++ (the report links the Microsoft documentation for building with ASAN), and for the fourth issue a Microsoft tool called GFlags to enable page heap for
notepad++.exe. Page heap is a Windows debugging option that places guard pages around memory allocations so that reading or writing just past an allocation causes an immediate crash. - No account or special role is needed. The only precondition for every issue is that a victim opens a crafted file.
A proof of concept (PoC) is a small, harmless example that demonstrates a bug: here, a tiny file, or a short script that creates one, which makes the editor misbehave.
Finding it
The common thread is that file content is treated as trusted input to size calculations and array indexes. In the converter, the output buffer size is computed from the input length with an assumption that breaks for an odd byte count. In the uchardet copy, table indexes derived from file bytes are compared against a table size that does not match the actual array, or are not checked at all. In the language detector, a fixed 40-byte read is taken from a pointer that may already be at the end of the loaded block. Each was confirmed with a small crafted file and an ASAN build (or a breakpoint).
A breakpoint is a marker you place in a debugger on a particular line of code; when the program reaches that line, it pauses so you can inspect what is happening.
Exploitation
Issue 1: Heap buffer write overflow in Utf8_16_Read::convert (GHSL-2023-112, CVE-2023-40031)
Text can be stored in different encodings, which are agreed ways of turning characters into bytes. UTF-16 uses two bytes per character, UTF-8 uses one to four. When Notepad++ opens a UTF-16 file it converts the content to UTF-8, and it needs a new buffer to hold the result. Utf8_16_Read::convert allocates that buffer and sizes it assuming that, in the worst case, every two UTF-16 input bytes need three UTF-8 bytes:
...
case uni16LE: {
size_t newSize = len + len / 2 + 1; // [2]
if (m_nAllocatedBufSize != newSize)
{
if (m_pNewBuf)
delete[] m_pNewBuf;
m_pNewBuf = NULL;
m_pNewBuf = new ubyte[newSize]; // [1]
m_nAllocatedBufSize = newSize;
}
ubyte* pCur = m_pNewBuf;
m_Iter16.set(m_pBuf + nSkip, len - nSkip, m_eEncoding);
while (m_Iter16)
{
++m_Iter16; // [3]
utf8 c;
while (m_Iter16.get(&c)) // [4]
*pCur++ = c; // [5]
}
...
Line by line, in plain words:
case uni16LE:means this branch handles little-endian UTF-16 input, one of the UTF-16 byte orders.size_t newSize = len + len / 2 + 1;computes how big the output buffer must be.lenis the number of input bytes.len / 2is the number of UTF-16 characters (two bytes each), and each of those may need up to three UTF-8 bytes, so the formula adds half oflenagain, plus one. The comment[2]marks this calculation.- The
if (m_nAllocatedBufSize != newSize)block reuses the existing buffer if it is already the right size; otherwise it frees the old one withdelete[]and allocates a fresh one withnew ubyte[newSize]. The comment[1]marks the allocation. ubyte* pCur = m_pNewBuf;sets a pointer,pCur, to the start of the new buffer. A pointer is a variable that holds the address of a memory slot, like a bookmark.m_Iter16.set(...)tells an iterator object where the input starts and how long it is. An iterator is a helper that walks through a sequence one item at a time.- The outer
while (m_Iter16)loops while the iterator still has data. ++m_Iter16;(comment[3]) advances the iterator.- The inner
while (m_Iter16.get(&c))(comment[4]) pulls out one converted character at a time intoc. *pCur++ = c;(comment[5]) writes that character into the output buffer and moves the pointer forward by one. This is the write that can run past the end.
When the input length is a malformed odd number of bytes the calculation is off. In the PoC, when a second chunk of bytes is processed, len is 9 and newSize becomes 14 (9 + 9 / 2 + 1). After the first 8 input bytes are consumed ([3] and [4]), pCur has already been shifted by 12 elements in the 14-element m_pNewBuf array. Utf16_Iter::operator++ then consumes the last 9th byte and the 10th byte beyond the input len. Because Notepad++ reads files in chunks, that 10th byte is still inside a valid buffer but holds old chunk data. The write in [5] then puts three bytes into pCur, overflowing the array.
The report's suggested fix is to make the iterator's validity operator check both the current and the next pointer against the end, since Utf16_Iter::read() always consumes two bytes:
operator bool() { return (m_pRead + 1 < m_pEnd) || (m_out1st != m_outLst); };
This one line says: the iterator counts as valid only if there is still room for a full two-byte character (m_pRead + 1 < m_pEnd), or if a character has already been read and is waiting to be handed out (m_out1st != m_outLst).
To reproduce:
- Create a file with the following python script:
with open("poc", "wb") as f:
f.write(b'\xfe\xff')
f.write(b'\xff' * (128 * 1024 + 4 - 2 + 1))
This script opens a new file called poc in binary write mode ("wb"). It first writes the two bytes \xfe\xff, which are the byte order mark for UTF-16: a short signature at the start of a file that tells the program which encoding follows. It then writes the byte \xff repeated 128 * 1024 + 4 - 2 + 1 times, which is 131,075 bytes, after the two-byte mark. The file is read in chunks, and one chunk ends up with an odd length, which is exactly the malformed case described above.
- Make an ASAN build of Notepad++.
- Open the file in Notepad++ to hit the out of bounds access with ASAN.
The ASAN output shows a heap-buffer-overflow write of size 1 in Utf8_16_Read::convert at Utf8_16.cpp:181, reached from FileManager::loadFileData, FileManager::loadFile, Notepad_plus::doOpen and the window message loop. The address is 0 bytes to the right of a 2-byte region allocated by operator new[] in Utf8_16_Read::convert at Utf8_16.cpp:168. The report's impact statement for this issue is that it may lead to arbitrary code execution.
Arbitrary code execution means an attacker could get their own instructions to run on the victim's computer, not just crash the editor. A heap is the general-purpose pool of memory a program uses for buffers it creates while running; a heap buffer overflow is an overflow in one of those buffers.
Issue 2: Global buffer read overflow in CharDistributionAnalysis::HandleOneChar (GHSL-2023-102, CVE-2023-40036)
Notepad++ uses a diverged copy of uchardet, a library that guesses which character encoding a file uses by looking at its bytes. In HandleOneChar, the array index order in [1] depends on the input file content and can be set larger than the size of the mCharToFreqOrder buffer, producing an out of bounds read:
//Feed a character with known length
void HandleOneChar(const char* aStr, PRUint32 aCharLen)
{
PRInt32 order;
//we only care about 2-bytes character in our distribution analysis
order = (aCharLen == 2) ? GetOrder(aStr) : -1;
if (order >= 0)
{
mTotalChars++;
//order is valid
if ((PRUint32)order < mTableSize) // [2]
{
if (512 > mCharToFreqOrder[order]) // [1] buffer read overflow
mFreqChars++;
}
}
}
Line by line:
void HandleOneChar(const char* aStr, PRUint32 aCharLen)is a function that receives a pointer to a character and its length in bytes.PRInt32 order;declares a whole number calledorder.order = (aCharLen == 2) ? GetOrder(aStr) : -1;setsorderto a lookup value fromGetOrderif the character is two bytes long, otherwise to -1. The? :form is a compact if/else.if (order >= 0)skips anything that is not a two-byte character.mTotalChars++;counts the character.if ((PRUint32)order < mTableSize)(comment[2]) is meant to be the safety check: only useorderas an index if it is smaller than the table size.if (512 > mCharToFreqOrder[order])(comment[1]) looks up the table entry at positionorder. This is the read that can go out of bounds.mFreqChars++;counts how many characters fall into a certain frequency band.
In the PoC, order is set to 5419 while mCharToFreqOrder (a pointer to the global array EUCTWCharToFreqOrder) has 5376 elements. There is a check [2] against mTableSize, but mTableSize for EUCTWCharToFreqOrder is declared as 8102, so the check does not stop the out of bounds index. The report notes that this behaviour has been fixed in the freedesktop.org uchardet.
A global variable is one that exists for the whole life of the program, rather than being created inside a function. A global buffer overflow is an overflow in one of those long-lived arrays.
To reproduce:
with open("poc", "wb") as f:
f.write(b'\xfd\xde')
This writes just two bytes, \xfd\xde, into a file called poc. In the PoC, the detector computes an order value of 5419.
- Make an ASAN build of Notepad++ or set a breakpoint at
if (512 > mCharToFreqOrder(order)). - Open the file to hit the breakpoint or the out of bounds access with ASAN.
The ASAN output reports a global-buffer-overflow, READ of size 2, in HandleOneChar at CharDistribution.h:69:19, called from nsEUCTWProber::HandleData, nsMBCSGroupProber::HandleData, nsUniversalDetector::HandleData and uchardet_handle_data. The address is 86 bytes to the right of the global variable EUCTWCharToFreqOrder (size 10752).
Issue 3: Global buffer read overflow in nsCodingStateMachine::NextState (GHSL-2023-103, CVE-2023-40164)
In the same uchardet copy, the array index byteCls in [1] depends on the input file content and can be set larger than the size of the charLenTable buffer:
nsSMState NextState(char c) {
//for each byte we get its class , if it is first byte, we also get byte length
PRUint32 byteCls = GETCLASS(c);
if (mCurrentState == eStart)
{
mCurrentBytePos = 0;
mCurrentCharLen = mModel->charLenTable[byteCls]; // [1] buffer read overflow
}
Line by line:
nsSMState NextState(char c)is a function that takes one byte of input and returns the next state of a small state machine. A state machine is a piece of logic that remembers where it is in a sequence and moves from state to state as it reads input.PRUint32 byteCls = GETCLASS(c);works out a class number for the bytec. The class is derived from the byte value, so the file controls it.if (mCurrentState == eStart)runs the following lines only when the machine is at the start of a character.mCurrentBytePos = 0;resets the position inside the character.mCurrentCharLen = mModel->charLenTable[byteCls];(comment[1]) looks up how many bytes this character should have, usingbyteClsas the index intocharLenTable.
In the PoC, byteCls is set to 9, while charLenTable points to ISO2022JPCharLenTable, which contains only 8 elements. This behaviour has also been fixed in the freedesktop.org uchardet.
To reproduce:
with open("poc", "wb") as f:
f.write(b'\x49\x7e\x7b')
This writes three bytes, \x49\x7e\x7b, into a file called poc. In the PoC, byteCls is set to 9, one past the end of the eight-element table.
- Make an ASAN build of Notepad++ or set a conditional breakpoint at
mCurrentCharLen = mModel->charLenTable(byteCls);whenbyteCls == 9.
The ASAN output reports a global-buffer-overflow, READ of size 4, in NextState at nsCodingStateMachine.h:72:25, called from nsEscCharSetProber::HandleData, nsUniversalDetector::HandleData and uchardet_handle_data. The address is 4 bytes to the right of the global variable ISO2022JPCharLenTable (size 32), 28 bytes to the left of a string literal ISO-2022-JP, and 60 bytes to the left of ISO2022KRSMModel.
For both uchardet issues the report states that exploitability is not clear, and that they may potentially be used to leak internal memory allocation information. Leaking memory means the program might reveal bytes from memory it should not show, which can help an attacker learn how memory is laid out.
Issue 4: Heap buffer read overflow in FileManager::detectLanguageFromTextBegining (GHSL-2023-092, CVE-2023-40166)
On file open, FileManager::loadFile allocates a fixed size buffer:
char* data = new char[blockSize + 8]; // +8 for incomplete multibyte char
...
bool res = loadFileData(doc, fileSize, backupFileName ? backupFileName : fullpath, data, &UnicodeConvertor, loadedFileFormat);
delete[] data;
Line by line:
char* data = new char[blockSize + 8];creates a buffer of characters,blockSizebytes plus 8 extra. The comment explains the extra 8 are there in case a multi-byte character is split across two blocks.bool res = loadFileData(...);calls the function that actually reads the file into that buffer, passing the buffer and some other details.delete[] data;frees the buffer when it is no longer needed.
FileManager::loadFileData loads the first block of data into the buffer [1] and calls detectLanguageFromTextBegining to identify the content type from the beginning of the file [2]:
lenFile = fread(data + incompleteMultibyteChar, 1, blockSize - incompleteMultibyteChar, fp) + incompleteMultibyteChar; // 1
if (ferror(fp)) != 0)
{
success = false;
break;
}
if (lenFile == 0) break;
...
fileFormat._language = detectLanguageFromTextBegining((unsigned char *)data, lenFile); // 2
Line by line:
lenFile = fread(...) + incompleteMultibyteChar;(comment[1]) reads up toblockSize - incompleteMultibyteCharbytes from the file into the buffer, starting after any leftover partial character, and stores how many bytes were actually read inlenFile.if (ferror(fp)) != 0)checks whether the read failed; if so it marks the operation unsuccessful and stops.if (lenFile == 0) break;stops if the file turned out to be empty.fileFormat._language = detectLanguageFromTextBegining((unsigned char *)data, lenFile);(comment[2]) asks the language detector to guess the file type from the first bytes, passing the buffer and its length.
FileManager::detectLanguageFromTextBegining advances the data pointer until a non-space character is found or lenFile is reached [3]. In the latter case it keeps going and reads 32 bytes (40 - 8, the extra padding added for the incomplete multibyte character case) past the end of the data buffer [4]:
LangType FileManager::detectLanguageFromTextBegining(const unsigned char *data, size_t dataLen)
{
...
// Skip any space-like char
for (; i < dataLen; ++i) // 3
{
if (data[i] != ' ' && data[i] != '\t' && data[i] != '\n' && data[i] != '\r')
break;
}
// Create the buffer to need to test
const size_t longestLength = 40; // shebangs can be large
std::string buf2Test = std::string((const char*)data + i, longestLength); // 4 OOB READ
Line by line:
LangType FileManager::detectLanguageFromTextBegining(const unsigned char *data, size_t dataLen)is the function, receiving the buffer and its length.- The
for (; i < dataLen; ++i)loop (comment[3]) walks forward through the buffer whileiis still inside it. if (data[i] != ' ' && data[i] != '\t' && data[i] != '\n' && data[i] != '\r') break;stops the loop as soon as it finds a byte that is not a space, tab, newline or carriage return. In other words, it skips leading whitespace.const size_t longestLength = 40;sets a fixed length of 40 bytes to look at. The comment explains that shebangs (the#!line at the top of scripts) can be long.std::string buf2Test = std::string((const char*)data + i, longestLength);(comment[4]) builds a string of 40 bytes starting at positioni. If the loop ran all the way todataLen,iis at the end of the buffer, and this reads past it. That is the out of bounds read.
The report's fix suggestion is to check, at the end of the loop, that i + longestLength is still less than dataLen.
To reproduce:
- Enable page heap for
notepad++.exein GFlags. - Create a
poc.xmlwith the following python script:
with open("poc.xml", "w") as f:
f.write(" " * (128 * 1024 + 4))
This opens a text file called poc.xml and writes a single space character repeated 128 * 1024 + 4 times. Because the file is nothing but whitespace, the loop that skips spaces runs to the very end of the loaded block, and the 40-byte read then starts past the buffer.
- Open the file with Notepad++ to trigger the memory read exception.
As with the uchardet issues, the report states that exploitability is not clear and that the bug may potentially be used to leak internal memory allocation information.
Root cause
Each issue is a bounds mistake on data derived from the file:
- The UTF-16 to UTF-8 converter sizes its output buffer for an even byte count and its iterator consumes two bytes at a time, but the validity check does not require the next byte to be inside the input. An odd
lentherefore lets the iterator step past the input and the writer run past the allocation. HandleOneCharvalidatesorderagainstmTableSize, butmTableSizeforEUCTWCharToFreqOrderis declared as 8102 while the array has 5376 elements, so the guard passes for indexes that are out of bounds.NextStateindexescharLenTablewith a byte class taken from the input without any bounds check, whileISO2022JPCharLenTablehas only 8 elements.detectLanguageFromTextBeginingskips leading whitespace up todataLenand then unconditionally constructs a 40-byte string fromdata + i, without checking thati + longestLengthis withindataLen.
In the first case the chunked reading of files means the byte read past len is still inside a valid buffer, which is why the overflow shows up as a write rather than an immediate read fault.
Impact
- GHSL-2023-112: may lead to arbitrary code execution.
- GHSL-2023-102, GHSL-2023-103 and GHSL-2023-092: exploitability is not clear; potentially usable to leak internal memory allocation information.
All four are triggered by opening a crafted file, so the attacker needs the victim to open it in Notepad++.
Fix
The report gives fix suggestions for GHSL-2023-112 (the iterator validity check shown above) and GHSL-2023-092 (check i + longestLength against dataLen). For GHSL-2023-102 and GHSL-2023-103 it points to the upstream fixes in freedesktop.org uchardet. Private security advisories and private pull requests with fix suggestions were created for the maintainer. The timeline records that Notepad++ v8.5.3 (2023-05-15), v8.5.4 (2023-06-18), v8.5.5 (2023-08-09) and v8.5.6 (2023-08-15) were released without the fixes before publication.
A security advisory is a private note shared with a project maintainer describing a vulnerability before it is made public. A pull request is a proposed change to a code repository that the maintainer can review and merge.
Variants to test
- Odd-length UTF-16 input in any editor or converter that sizes an output buffer from the input length: a positive result is an ASAN heap-buffer-overflow write in the conversion routine when the file is opened.
- Encoding detection libraries with table-driven indexes: compare each table's declared size with the actual array length, and try inputs that drive the index past the real array. A positive result is an ASAN global-buffer-overflow read in the prober.
- Fixed-length reads after a scan loop (shebang or language detection, magic-byte checks): feed a file made only of the scanned character up to the block boundary. A positive result is a read past the allocated block, visible with page heap or ASAN.
- Chunked file readers: look for logic that assumes the next byte after a chunk is valid, since stale chunk data can mask a read and turn it into a write.
Hunting notes
This class of bug hides in code that parses untrusted files before any validation: encoding converters, charset detectors, language and shebang detection, and anything that computes a buffer size from an input length. During review, look for size formulas with integer division or fixed padding, table lookups indexed by input bytes, and loops that advance a pointer to a length limit and then read a fixed amount. The report's evidence pattern is effective for a program: a minimal generator script, a reproducible ASAN (or page heap) crash with the exact function and line, and a concrete fix suggestion. The timeline also shows the value of persisting: the maintainer asked for a binary PoC instead of a Python script and reported that v8.5.4 did not compile with ASAN, and the researchers provided the binary PoC and confirmed the issue was still reproducible in their setup before publishing.
Glossary
- AddressSanitizer (ASAN): a debugging tool that adds checks around memory so that out of bounds reads and writes are caught and reported immediately.
- Arbitrary code execution: a situation where an attacker can make their own instructions run on someone else's computer.
- Array: a numbered list of values stored one after another in memory, accessed by an index.
- Block: a fixed-size portion of a file that a program reads at a time, rather than loading the whole file at once.
- Bounds: the start and end of a reserved memory region; staying inside them is safe, going outside is an overflow.
- Breakpoint: a marker in a debugger that pauses the program on a chosen line so you can inspect it.
- Buffer: a reserved run of memory set aside to hold data such as a file's contents.
- Buffer overflow: reading or writing memory outside the reserved run, which can corrupt other data or crash the program.
- Byte: the basic unit of computer storage, a number from 0 to 255.
- Byte order mark (BOM): a short signature at the start of a file that identifies its encoding, such as
\xfe\xfffor UTF-16. - Character encoding: an agreed way of turning characters into bytes, such as UTF-8 or UTF-16.
- Chunk: see block; files are often read in chunks.
- Conditional breakpoint: a breakpoint that only pauses when a condition is true, for example when a variable equals 9.
- CVE: a public identifier for a known vulnerability, so people can refer to it unambiguously.
- Debugger: a tool that lets you pause a running program, inspect its variables and step through its code.
- Encoding detection: guessing which character encoding a file uses by examining its bytes.
- Exploitability: how practical it is for an attacker to turn a bug into real harm.
- GFlags: a Microsoft tool for enabling Windows debugging options such as page heap for a specific program.
- Global variable: a variable that exists for the whole life of the program rather than inside one function.
- Heap: the general-purpose pool of memory a program uses for buffers it creates while running.
- Index: the position used to pick an item out of an array.
- Iterator: a helper object that walks through a sequence one item at a time.
- Leak (memory): revealing bytes from memory that should not be visible, which can help an attacker learn how memory is laid out.
- Memory: the computer's working storage, a large numbered set of slots holding data while a program runs.
- Memory-safety bug: a bug where a program reads or writes memory it should not touch.
- Out of bounds access: reading or writing outside a reserved memory region.
- Page heap: a Windows debugging option that puts guard pages around allocations so overflows crash immediately.
- Pointer: a variable that holds the address of a memory slot, like a bookmark.
- Proof of concept (PoC): a small, harmless example that demonstrates a bug.
- Pull request: a proposed change to a code repository that the maintainer can review and merge.
- Security advisory: a private note shared with a project maintainer describing a vulnerability before it is made public.
- Shebang: the
#!line at the top of a script that names the interpreter to run it. - State machine: logic that remembers where it is in a sequence and moves from state to state as it reads input.
- Table-driven lookup: using a value from the input as an index into a fixed table of data.
- UTF-8 / UTF-16: two common character encodings; UTF-8 uses one to four bytes per character, UTF-16 uses two or four.
- uchardet: a library that guesses a file's character encoding from its bytes; Notepad++ uses a modified copy.