Probable write beyond bounds due to nsTSubstring_CharT::Adopt()
The Adopt() method on Mozilla's string class lets callers create strings longer than the normal maximum length, which breaks the invariant that adding two string lengths cannot overflow a 32-bit unsigned integer. Code that adds lengths and then allocates a buffer could therefore allocate too small a buffer and write past its end.
- Fixed in 41 hours
- Paid in 5 days
- Disclosed after 41 hours
nsTSubstring_CharT::Adopt() (xpcom/string/nsTSubstring.cpp) permits its callers to form an ns*String that can be longer than the maximum length ordinarily allowed by nsTSubstring_CharT::MutatePrep(). For single-byte strings, this length is 0x7ffffff5 characters, and for 2-byte strings, it is 0x3ffffff9 characters. These limits guarantee that adding the lengths of 2 ns*Strings -- which is common in the codebase -- will never overflow a uint32_t.
If, however, Adopt() is used to form a string >= 0x80000000 characters, code of the following form can overflow, causing writes beyond bounds:
nsCString s1;
s.Adopt (someLongByteString, someLongByteStringLength);
...
nsCString s2;
...
uint32_t newStringLen = s1.Length() + s2.Length(); // potential overflow...
nsCString s3;
s3.SetLength(newStringLen); // ...and allocation of too-small buffer...
// ...and write beyond bounds.
memcpy (s3.BeginWriting(), s1.BeginReading(), s1.Length());
memcpy (s3.BeginWriting() + s1.Length(), s2.BeginReading(), s2.Length());
The following is from trunk:
501: void
502: nsTSubstring_CharT::Adopt(char_type* aData, size_type aLength)
503: {
504: if (aData) {
505: ::ReleaseData(mData, mFlags);
506:
507: if (aLength == size_type(-1)) {
508: aLength = char_traits::length(aData);
509: }
510:
511: mData = aData;
512: mLength = aLength;
513: SetDataFlags(F_TERMINATED | F_OWNED);
514:
515: STRING_STAT_INCREMENT(Adopt);
516: // Treat this as construction of a "StringAdopt" object for leak
517: // tracking purposes.
518: MOZ_LOG_CTOR(mData, "StringAdopt", 1);
519: } else {
520: SetIsVoid(true);
521: }
522: }
I do not yet have a POC.
What the report shows
The report concerns Mozilla's XPCOM string library, specifically nsTSubstring_CharT::Adopt() in xpcom/string/nsTSubstring.cpp. The report describes a probable write beyond bounds caused by an integer overflow.
The researcher's reasoning is a length invariant argument. nsTSubstring_CharT::MutatePrep() normally caps string length at 0x7ffffff5 characters for single-byte strings and 0x3ffffff9 characters for 2-byte strings. Those caps exist so that adding the lengths of two ns*String objects, a common operation in the codebase, can never overflow a uint32_t. Adopt() permits such a string: it takes a caller-supplied buffer and length and stores them directly, so a string of 0x80000000 characters or more can exist.
Once such a string exists, ordinary length arithmetic overflows. The report gives this pattern:
nsCString s1;
s.Adopt (someLongByteString, someLongByteStringLength);
...
nsCString s2;
...
uint32_t newStringLen = s1.Length() + s2.Length(); // potential overflow...
nsCString s3;
s3.SetLength(newStringLen); // ...and allocation of too-small buffer...
// ...and write beyond bounds.
memcpy (s3.BeginWriting(), s1.BeginReading(), s1.Length());
memcpy (s3.BeginWriting() + s1.Length(), s2.BeginReading(), s2.Length());
If the summed length wraps to a small value, SetLength would allocate a buffer for that small value, and the two memcpy calls would then write the full contents of s1 and s2 into it, past the end of the allocation.
The report quotes the trunk implementation of Adopt():
501: void
502: nsTSubstring_CharT::Adopt(char_type* aData, size_type aLength)
503: {
504: if (aData) {
505: ::ReleaseData(mData, mFlags);
506:
507: if (aLength == size_type(-1)) {
508: aLength = char_traits::length(aData);
509: }
510:
511: mData = aData;
512: mLength = aLength;
513: SetDataFlags(F_TERMINATED | F_OWNED);
514:
515: STRING_STAT_INCREMENT(Adopt);
516: // Treat this as construction of a "StringAdopt" object for leak
517: // tracking purposes.
518: MOZ_LOG_CTOR(mData, "StringAdopt", 1);
519: } else {
520: SetIsVoid(true);
521: }
522: }
The assignment mLength = aLength stores the supplied length with no check against the maximum length. The researcher states plainly that there is no proof of concept yet, so the report stops at the invariant violation and the plausible overflow pattern. It does not describe a trigger, a crash, or a fix.
Root cause
The likely root cause is a missing length validation in Adopt(). MutatePrep() enforces the maximum length that keeps uint32_t length arithmetic safe. Adopt() takes ownership of a caller-supplied buffer and stores the supplied length. That breaks the invariant the rest of the string code relies on: that no string can be long enough for a sum of two lengths to wrap. The overflow itself then happens in caller code, not in the string class, which is why the report frames it as a probable consequence rather than a demonstrated bug.
Impact
If a caller adopts a buffer of 0x80000000 characters or more, and later code adds string lengths in uint32_t, the sum can overflow and lead to a write beyond bounds. In a browser engine that means potential memory corruption, though the report makes no such claim and offers no PoC. The practical precondition is severe: the attacker must first get a string that large adopted, which requires either a very large input or a length value the caller controls. The report's own hedge, "probable" and "potential overflow", should be kept in mind.
How this kind of bug works
Integer overflow in length handling is a mismatch between the width of a size type and the range of values the code assumes. Here the string library deliberately caps lengths so that a + b in uint32_t cannot wrap. Any path that creates an object outside that contract, such as adopting an externally supplied buffer, reintroduces the wrap. When the wrapped value is used for allocation and the unwrapped values are used for copying, the copy writes past the allocation.
The bug class appears wherever a size is computed in a narrow type, checked, and then used in a wider or unchecked context, or vice versa. Classic variants include multiplication overflows in element-count times element-size calculations, signed/unsigned confusion, and truncation when a 64-bit length is stored in a 32-bit field. Defences are straightforward: validate lengths at every entry point that accepts external sizes, use checked arithmetic helpers, keep allocation and copy sizes derived from the same validated value, and enforce invariants in one place (a single maximum-length check) rather than relying on callers.
How to test for it
- Identify features that accept a length, count, or size from the client: uploads, archive or file parsers, image dimensions, array or list parameters, pagination counts, buffer-adoption APIs in native code.
- Look for places where two lengths are added, multiplied, or converted between widths before an allocation.
- Send values near type boundaries: 0x7fffffff, 0x80000000, 0xffffffff, and values whose sum or product wraps. For parsers, craft files whose declared sizes are inconsistent with their actual content.
- A positive result is a crash, a sanitizer report (ASan, UBSan), a heap corruption symptom, or observable memory disclosure. A clean error or a rejected request is a negative result.
- Common false positives: the value is validated before use; the arithmetic is done in 64-bit and checked; the allocation is capped independently; the crash is an ordinary out-of-memory or timeout rather than corruption.
Describe requests in words rather than code: state the endpoint, the parameter, and the boundary value, and note the response or crash signature.
How it is fixed
A fix would be to enforce the same maximum-length check in Adopt() that MutatePrep() enforces, rejecting or truncating lengths that exceed it. More generally: centralise the invariant, use checked addition and multiplication for all size arithmetic, derive allocation and copy sizes from one validated value, and add assertions or fuzzing that exercise boundary lengths. Where adoption of external buffers is required, document and enforce the contract at the API boundary.
Hunting notes
This class hides in native string and buffer libraries, parsers, serialisation code, and any API that transfers ownership of memory. Recon signals include C/C++ codebases with custom string or vector types, comments about maximum lengths, and fast paths that skip validation. To make a report accepted, show the invariant violation concretely and, ideally, a minimal trigger that reaches the overflow with a sanitizer trace; without a PoC, as here, frame it as a probable issue and point to the exact missing check so triagers can confirm it quickly.
What happened, in plain words
Mozilla's codebase is built on a large body of shared code. One part of that code, called XPCOM, provides the string types that the rest of the browser uses to hold text: nsCString for single-byte text and nsString for two-byte text. The report looks at one function in that string library, nsTSubstring_CharT::Adopt(), in the file xpcom/string/nsTSubstring.cpp, and describes a probable write past the end of a memory buffer.
To follow the reasoning you need two ideas. First, a buffer is a block of memory reserved to hold data, like a row of numbered lockers. Writing "beyond bounds" means putting data into lockers past the end of the row, which belong to something else. Second, an integer overflow happens when a fixed-width number type cannot hold a result. A uint32_t is an unsigned 32-bit integer: it counts from 0 up to 0xffffffff (about 4.29 billion) and then wraps back to 0, like a car odometer rolling over.
The string library normally prevents trouble by capping how long a string may be. nsTSubstring_CharT::MutatePrep() enforces a maximum of 0x7ffffff5 characters for single-byte strings and 0x3ffffff9 characters for two-byte strings. Those caps exist so that adding the lengths of two strings, something the codebase does all the time, can never overflow a uint32_t. Adopt() permits such a string. It takes a buffer and a length supplied by the caller and stores them directly, so a string of 0x80000000 characters or more can exist.
Once such a string exists, ordinary length arithmetic goes wrong. The report gives this pattern:
nsCString s1;
s.Adopt (someLongByteString, someLongByteStringLength);
...
nsCString s2;
...
uint32_t newStringLen = s1.Length() + s2.Length(); // potential overflow...
nsCString s3;
s3.SetLength(newStringLen); // ...and allocation of too-small buffer...
// ...and write beyond bounds.
memcpy (s3.BeginWriting(), s1.BeginReading(), s1.Length());
memcpy (s3.BeginWriting() + s1.Length(), s2.BeginReading(), s2.Length());
Line by line: s1 is a single-byte string, and Adopt hands it a caller-supplied buffer and length, which is how an oversized string could be created. s2 is a second string. The next line adds the two lengths into a uint32_t; if s1 is at least 0x80000000 characters, the sum wraps to a small number. s3.SetLength(newStringLen) then reserves a buffer sized for that small number. The two memcpy calls would copy the full contents of s1 and s2 into s3, writing far past the end of the small allocation. That is the potential write beyond bounds.
The report quotes the implementation of Adopt() from the development tree:
501: void
502: nsTSubstring_CharT::Adopt(char_type* aData, size_type aLength)
503: {
504: if (aData) {
505: ::ReleaseData(mData, mFlags);
506:
507: if (aLength == size_type(-1)) {
508: aLength = char_traits::length(aData);
509: }
510:
511: mData = aData;
512: mLength = aLength;
513: SetDataFlags(F_TERMINATED | F_OWNED);
514:
515: STRING_STAT_INCREMENT(Adopt);
516: // Treat this as construction of a "StringAdopt" object for leak
517: // tracking purposes.
518: MOZ_LOG_CTOR(mData, "StringAdopt", 1);
519: } else {
520: SetIsVoid(true);
521: }
522: }
The key line is mLength = aLength;, which stores the supplied length with no check against the maximum. The researcher states plainly that there is no proof of concept yet, so the report stops at the broken rule and the plausible overflow pattern. It does not describe a trigger, a crash or a fix.
In general, how this kind of bug works
An integer overflow in length handling is a mismatch between the width of a number type and the range of values the code assumes. Here the string library deliberately caps lengths so that adding two of them in a uint32_t cannot wrap. Any path that creates a string outside that contract, such as adopting an externally supplied buffer, brings the wrap back. When the wrapped value is used to reserve memory and the unwrapped values are used to copy, the copy runs past the reservation.
The bug class appears wherever a size is computed in a narrow type, checked, and then used in a wider or unchecked context, or the other way round. Common variants include multiplication overflows when multiplying a count by an element size, confusion between signed and unsigned numbers, and truncation when a 64-bit length is stored in a 32-bit field. Defences are straightforward: validate lengths at every entry point that accepts an external size, use checked arithmetic helpers, keep the allocation size and the copy size derived from the same validated value, and enforce the invariant in one place rather than trusting callers.
If you want to look for this class of bug yourself, a sensible approach is:
- Identify features that accept a length, count or size from the client: uploads, archive or file parsers, image dimensions, list parameters, pagination counts, or buffer-adoption APIs in native code.
- Look for places where two lengths are added, multiplied or converted between widths before memory is reserved.
- Try values near the boundaries of the type: 0x7fffffff, 0x80000000, 0xffffffff, and values whose sum or product wraps. For parsers, craft files whose declared sizes do not match their actual content.
- A positive result is a crash, a sanitizer report (ASan, UBSan), a sign of heap corruption, or observable memory disclosure. A clean error or a rejected request is a negative result.
- Common false positives: the value is validated before use, the arithmetic is done in 64-bit and checked, the allocation is capped independently, or the crash is an ordinary out-of-memory or timeout rather than corruption.
Describe requests in words rather than code: state the endpoint, the parameter and the boundary value, and note the response or crash signature.
A fix would be to enforce in Adopt() the same maximum-length check that MutatePrep() enforces, rejecting or truncating lengths that exceed it. More generally: centralise the invariant, use checked addition and multiplication for all size arithmetic, derive allocation and copy sizes from one validated value, and add assertions or fuzzing that exercise boundary lengths. Where adopting external buffers is required, document and enforce the contract at the API boundary.
This class hides in native string and buffer libraries, parsers, serialisation code, and any API that transfers ownership of memory. Signals worth watching for include C/C++ codebases with custom string or vector types, comments about maximum lengths, and fast paths that skip validation. To get a report accepted, show the broken invariant concretely and, ideally, a minimal trigger that reaches the overflow with a sanitizer trace. Without a proof of concept, as here, frame it as a probable issue and point to the exact missing check so that triagers can confirm it quickly.
Glossary
- XPCOM: Mozilla's cross-platform component framework, which includes the shared string types used throughout the browser.
- Buffer: a block of memory reserved to hold data.
- Write beyond bounds: writing data past the end of a reserved buffer, into memory that belongs to something else.
- Integer overflow: when a fixed-width number type cannot hold a result and wraps around to a small value.
- uint32_t: an unsigned 32-bit integer, counting from 0 to 0xffffffff before wrapping.
- Invariant: a rule that the code assumes always holds, here that no string is long enough for two lengths to overflow when added.
- Adopt(): a string function that takes ownership of a caller-supplied buffer and length without copying it.
- MutatePrep(): the string function that enforces the maximum length before a string is grown.
- memcpy: a C library function that copies a given number of bytes from one memory location to another.
- Heap buffer overflow: writing past the end of a buffer allocated on the heap, which can corrupt other data.
- Proof of concept (PoC): a concrete input or program that demonstrates the bug actually happens.
- Sanitizer (ASan, UBSan): debugging tools that detect memory errors and undefined behaviour while a program runs.
- CVSS: a standard scoring system for the severity of a vulnerability.