Overflow in makeSpace causes potential memory-safety bug
- Fixed in 2.0 years
- Paid in 3 months
- Disclosed after 2.0 years
Created attachment 8686863
POC. Use with a breakpoint in makeSpace to see the bug in action.
makeSpace (gfx\skia\skia\include\core\SkPathRef.h) can experience an integer overflow. If it does, it attempts to allocate a buffer that is far too small. makeSpace's callers then overrun the buffer, writing to memory that they don't own. This bug can ever practically be realized only in 32 bit builds.
Because of Windows memory allocations policies and another bug, this bug appears unlikely to be realizable on Windows 7. It might be realizable under other OSes.
Details
-------
The bug is in line 389, which doesn't check for overflow:
373: void makeSpace(size_t size) {
374: SkDEBUGCODE(this->validate();)
375: ptrdiff_t growSize = size - fFreeSpace;
376: if (growSize <= 0) {
377: return;
378: }
379: size_t oldSize = this->currSize();
380: // round to next multiple of 8 bytes
381: growSize = (growSize + 7) & ~static_cast<size_t>(7);
382: // we always at least double the allocation
383: if (static_cast<size_t>(growSize) < oldSize) {
384: growSize = oldSize;
385: }
386: if (growSize < kMinSize) {
387: growSize = kMinSize;
388: }
389: size_t newSize = oldSize + growSize;
390: // Note that realloc could memcpy more than we need. It seems to be a win anyway. TODO:
391: // encapsulate this.
392: fPoints = reinterpret_cast<SkPoint*>(sk_realloc_throw(fPoints, newSize));
...
402: }
Under Windows 7 SP1, the bug appears unlikely to be realizable because of a confluence between Windows 7's memory allocation policy and something of a bug in |huge_ralloc| (memory\mozjemalloc\jemalloc.c). That bug is that |huge_ralloc| only ever (1) extends an existing block forward in memory or (2) mallocs a new block, copies the existing block to it, and frees the old block. What it doesn't do is (3) to attempt to extend an existing block *backward* in memory, then memmove the existing contents as appropriate; and/or (4) extend an existing block forward in memory if it's in a different "size class". The upshot is that |huge_ralloc| sometimes fails to satisfy a request that it could satisfy. (Which, while dodging a security bug here, must cause some unnecessary OOM crashes).
The above two factors make the makeSpace bug unlikely to be realized in our case. When running the POC under Windows 7, |newSize| in the call to |sk_realloc_throw| (line 392) eventually becomes 0x20000000. Windows allocates that block at 0x80000000. Then the next time line 392 reallocs, the size is 0x40000000. |huge_ralloc| treats this as a different "size class" from 0x20000000, and so doesn't try to extend the block at 0x80000000. Instead, it allocates a new block (which Windows puts at 0xa0000000), copies the existing block into it, and frees it, thus fragmenting the address space. Then the final time line 392 reallocs, the size is 0x80000000. Again this is a different "size class" from the old size, so |huge_ralloc| tries again the malloc-and-free approach. But there is no contiguous block of address space large enough, so the malloc fails.
The bug might still be realizable if the OS allocates memory in the "right" way. This would occur if, for example, the OS allocated the 0x20000000-long block at 0x80000000, the 0x40000000-long block at 0x40000000 (with |huge_ralloc| then freeing the 0x20000000-long block), then the 0x80000000-long block at 0x80000000 (with |huge_ralloc| then freeing the 0x40000000-long block). This also would occur if |huge_ralloc| repeatedly extended an existing 0x20000000-long block that was allocated at 0x80000000. (Note some OSes, e.g., Windows 7, reserve a few hundred KB at the very top of the address space, so the previous addresses might have to be adjusted downward by that amount).
Finally, there is also a technical bug in line 375: |ptrdiff_t| is guaranteed only to be able to contain the difference between any two *valid* pointers into the *same array* (see C++11 s.5.7(6)). It is not guaranteed to be able to contain the difference of two arbitrary |size_t|s ("Unless both pointers point to elements of the same array object, or one past the last element of the array object, the behavior is undefined." Id.).
What the report shows
The affected code is the makeSpace method in SkPathRef.h, in the Core: Graphics area. and specifically the makeSpace method in SkPathRef.h. The researcher attached a proof of concept and asked that it be run with a breakpoint in makeSpace so the bug can be watched in action.
The claim is that makeSpace can suffer an integer overflow. When it does, it tries to allocate a buffer that is far too small, and its callers then write past the end of that buffer into memory they do not own. The researcher states that the bug can practically be realised only in 32-bit builds. On Windows 7 SP1 it appears unlikely to be realisable, for reasons explained below, but it might be realisable on other operating systems.
The researcher created an attachment containing a POC, to be run with a breakpoint in makeSpace.
Root cause
The report points at line 389, which computes the new allocation size without checking for overflow:
373: void makeSpace(size_t size) {
374: SkDEBUGCODE(this->validate();)
375: ptrdiff_t growSize = size - fFreeSpace;
376: if (growSize <= 0) {
377: return;
378: }
379: size_t oldSize = this->currSize();
380: // round to next multiple of 8 bytes
381: growSize = (growSize + 7) & ~static_cast<size_t>(7);
382: // we always at least double the allocation
383: if (static_cast<size_t>(growSize) < oldSize) {
384: growSize = oldSize;
385: }
386: if (growSize < kMinSize) {
387: growSize = kMinSize;
388: }
389: size_t newSize = oldSize + growSize;
390: // Note that realloc could memcpy more than we need. It seems to be a win anyway. TODO:
391: // encapsulate this.
392: fPoints = reinterpret_cast<SkPoint*>(sk_realloc_throw(fPoints, newSize));
...
402: }
The addition on line 389 is unchecked, so an overflow can produce a newSize that is far too small, and that value is passed to sk_realloc_throw. The buffer is then smaller than the callers assume, and their writes overrun it.
The researcher also flags a second, technical problem on line 375: ptrdiff_t is only guaranteed to hold the difference between two valid pointers into the same array, not the difference of two arbitrary size_t values, so the subtraction size - fFreeSpace is not guaranteed to be representable.
Why Windows 7 did not trigger it
The report explains that two factors combine to make the bug unlikely on Windows 7 SP1: the operating system's memory allocation policy and a shortcoming in huge_ralloc in memory\mozjemalloc\jemalloc.c. That function only ever extends an existing block forward in memory, or allocates a new block, copies the old contents into it and frees the old block. It does not try to extend a block backward and memmove the contents, and it does not extend a block forward when the new size falls in a different size class. As a result it sometimes fails a request it could have satisfied, which the researcher notes must also cause unnecessary out-of-memory crashes.
Running the proof of concept on Windows 7, newSize in the call to sk_realloc_throw eventually reaches 0x20000000, and Windows places that block at 0x80000000. The next reallocation asks for 0x40000000, which huge_ralloc treats as a different size class, so it allocates a fresh block (placed at 0xa0000000), copies and frees the old one, fragmenting the address space. The final reallocation asks for 0x80000000; again the size class differs, the malloc-and-copy path is taken, and no contiguous region large enough exists, so the allocation fails.
The bug could still be realised if the OS allocated memory in a more convenient order, for example placing the 0x20000000 block at 0x80000000, the 0x40000000 block at 0x40000000 and the 0x80000000 block back at 0x80000000, freeing each predecessor in turn. It would also be realised if huge_ralloc repeatedly extended an existing 0x20000000 block allocated at 0x80000000. The report notes that some systems, Windows 7 among them, reserve a few hundred KB at the top of the address space, so these addresses may need adjusting downward.
Impact
Where the overflow is reached, callers of makeSpace overrun the too-small buffer and write to memory they do not own. The report hedges this heavily. It is practical only in 32-bit builds, and on Windows 7 SP1 the allocator behaviour described above makes it unlikely to be realised. Other operating systems might allow it.
How this kind of bug works
Integer overflows in size arithmetic arise when a length is computed from untrusted or attacker-influenced values without checking the result. In C and C++, unsigned arithmetic wraps silently, so a sum that should be large becomes small. If that small value is then used as an allocation size, the allocation succeeds and the code that follows writes as though the full, intended amount of space existed. The same class covers multiplication overflows in element-count times element-size calculations, and signed/unsigned confusion where a negative value is reinterpreted as a huge unsigned length.
The defence is to validate before allocating: check that the operands cannot overflow, use checked arithmetic helpers, or reject sizes above a sane maximum. Allocators that return null on failure only help if the caller checks the result, and here the failure mode is not a failed allocation but a successful, too-small one.
How to test for it
- Identify code paths where a size is derived from input: image dimensions, path point counts, buffer lengths, chunk sizes in file formats, or anything parsed from a document.
- Look for arithmetic on those values close to an allocation or reallocation call, especially additions and multiplications that are not range-checked.
- On 32-bit builds, drive the value towards the wrap point. For a 32-bit process, sizes near
0x80000000and above are the interesting region; the report's own trace shows the progression through0x20000000,0x40000000and0x80000000. - Watch the allocator under a debugger or with sanitizers. A positive result is an allocation whose returned size is smaller than the value the surrounding code believes it has, followed by a write beyond that buffer.
- Treat allocator behaviour as part of the test. A failure to reproduce on one OS does not clear the bug; the report shows the same code failing to trigger purely because of how the platform placed and extended blocks.
Common false positives: arithmetic that wraps but whose result is never used as a length; sizes that are clamped or rejected earlier in the call chain; and 64-bit builds where the wrap point is unreachable in practice.
How it is fixed
Checked-arithmetic helpers and explicit upper bounds on allocation sizes achieve the same result.
Hunting notes
This class hides in parsers and graphics code: image decoders, path and geometry handling, font and document formats, and anywhere a count from the file is multiplied by a structure size. Recon signals include 32-bit build targets, custom allocators or wrappers around realloc, and code comments admitting that a size calculation is unchecked. To make a report land, show the wrapped value, the resulting allocation, and the out-of-bounds write under a sanitizer or debugger, and state clearly which build width and platform are required. If a platform's allocator masks the bug, say so and show the conditions under which it would not, as this report does.
What happened, in plain words
This report is about the makeSpace function in SkPathRef.h, in the Core: Graphics area. Inside Skia there is a small helper function called makeSpace, defined in SkPathRef.h. Its job is to make room in memory when more space is needed. When more points need to fit, makeSpace asks the system for a bigger block of memory.
The researcher found that makeSpace can suffer an integer overflow. An integer overflow is what happens when a number gets too big for the fixed amount of space used to store it, so it wraps around to a small value, like a car odometer rolling from 999999 back to 000000. When that happens here, makeSpace asks for a buffer that is far too small. The code that called makeSpace still believes it has the larger space, so it writes past the end of the small buffer, into memory it does not own. That is a memory-safety bug: the program writes to memory it does not own.
The researcher created an attachment containing a POC, to be used with a breakpoint in makeSpace so the bug can be seen in action. A breakpoint is a marker that pauses a program under a debugger, a tool that lets you step through code and inspect memory.
The researcher states that the bug can practically be realised only in 32-bit builds. A 32-bit build is a version of the program that can only address about 4 GB of memory, which makes number wrap-around much easier to reach. On Windows 7 SP1 the bug appears unlikely to be realisable, for reasons explained below, but it might be realisable on other operating systems.
Root cause
The report points at line 389, which computes the new allocation size without checking for overflow:
373: void makeSpace(size_t size) {
374: SkDEBUGCODE(this->validate();)
375: ptrdiff_t growSize = size - fFreeSpace;
376: if (growSize <= 0) {
377: return;
378: }
379: size_t oldSize = this->currSize();
380: // round to next multiple of 8 bytes
381: growSize = (growSize + 7) & ~static_cast<size_t>(7);
382: // we always at least double the allocation
383: if (static_cast<size_t>(growSize) < oldSize) {
384: growSize = oldSize;
385: }
386: if (growSize < kMinSize) {
387: growSize = kMinSize;
388: }
389: size_t newSize = oldSize + growSize;
390: // Note that realloc could memcpy more than we need. It seems to be a win anyway. TODO:
391: // encapsulate this.
392: fPoints = reinterpret_cast<SkPoint*>(sk_realloc_throw(fPoints, newSize));
...
402: }
Line by line, in plain terms:
- Line 373 declares the function and the amount of extra space requested,
size. - Line 375 works out how much the buffer needs to grow, by subtracting the free space already available. The result is stored in a signed type,
ptrdiff_t. - Lines 376 to 378 say: if no growth is needed, stop.
- Line 379 records the current buffer size.
- Line 381 rounds the growth up to a multiple of 8 bytes, a common alignment trick.
- Lines 383 to 385 make sure the buffer at least doubles.
- Lines 386 to 388 enforce a minimum size.
- Line 389 adds the old size and the growth together. This is the unchecked addition: if the sum is too large for the number type, it wraps to a small value.
- Line 392 asks the memory allocator, through
sk_realloc_throw, to resize the buffer tonewSize. IfnewSizewrapped, the buffer is now smaller than the callers assume, and their writes overrun it.
The researcher also flags a second, technical problem on line 375: ptrdiff_t is only guaranteed to hold the difference between two valid pointers into the same array, not the difference of two arbitrary size_t values, so the subtraction size - fFreeSpace is not guaranteed to be representable.
Why Windows 7 did not trigger it
The report explains that two factors combine to make the bug unlikely on Windows 7 SP1: the operating system's memory allocation policy and a shortcoming in huge_ralloc in memory\mozjemalloc\jemalloc.c. That function only ever extends an existing block forward in memory, or allocates a new block, copies the old contents into it and frees the old block. It does not try to extend a block backward and memmove the contents, and it does not extend a block forward when the new size falls in a different size class. A size class is a bucket of similar-sized allocations that the allocator manages together. As a result it sometimes fails a request it could have satisfied, which the researcher notes must also cause unnecessary out-of-memory crashes.
Running the proof of concept on Windows 7, newSize in the call to sk_realloc_throw eventually reaches 0x20000000, and Windows places that block at 0x80000000. The next reallocation asks for 0x40000000, which huge_ralloc treats as a different size class, so it allocates a fresh block (placed at 0xa0000000), copies and frees the old one, fragmenting the address space. The final reallocation asks for 0x80000000; again the size class differs, the malloc-and-copy path is taken, and no contiguous region large enough exists, so the allocation fails.
The bug could still be realised if the OS allocated memory in a more convenient order, for example placing the 0x20000000 block at 0x80000000, the 0x40000000 block at 0x40000000 and the 0x80000000 block back at 0x80000000, freeing each predecessor in turn. It would also be realised if huge_ralloc repeatedly extended an existing 0x20000000 block allocated at 0x80000000. The report notes that some systems, Windows 7 among them, reserve a few hundred KB at the top of the address space, so these addresses may need adjusting downward.
Impact
Where the overflow is reached, callers of makeSpace overrun the too-small buffer and write to memory they do not own. The report hedges this heavily. It is practical only in 32-bit builds, and on Windows 7 SP1 the allocator behaviour described above makes it unlikely to be realised. Other operating systems might allow it.
In general, how this kind of bug works
Integer overflows in size arithmetic arise when a length is computed from untrusted or attacker-influenced values without checking the result. In C and C++, unsigned arithmetic wraps silently, so a sum that should be large becomes small. If that small value is then used as an allocation size, the allocation succeeds and the code that follows writes as though the full, intended amount of space existed. The same class covers multiplication overflows in element-count times element-size calculations, and signed/unsigned confusion where a negative value is reinterpreted as a huge unsigned length.
The defence is to validate before allocating: check that the operands cannot overflow, use checked arithmetic helpers, or reject sizes above a sane maximum. Allocators that return null on failure only help if the caller checks the result, and here the failure mode is not a failed allocation but a successful, too-small one.
In general, how to test for it
- Identify code paths where a size is derived from input: image dimensions, path point counts, buffer lengths, chunk sizes in file formats, or anything parsed from a document.
- Look for arithmetic on those values close to an allocation or reallocation call, especially additions and multiplications that are not range-checked.
- On 32-bit builds, drive the value towards the wrap point. For a 32-bit process, sizes near
0x80000000and above are the interesting region; the report's own trace shows the progression through0x20000000,0x40000000and0x80000000. - Watch the allocator under a debugger or with sanitizers. A positive result is an allocation whose returned size is smaller than the value the surrounding code believes it has, followed by a write beyond that buffer.
- Treat allocator behaviour as part of the test. A failure to reproduce on one OS does not clear the bug; the report shows the same code failing to trigger purely because of how the platform placed and extended blocks.
Common false positives: arithmetic that wraps but whose result is never used as a length; sizes that are clamped or rejected earlier in the call chain; and 64-bit builds where the wrap point is unreachable in practice.
In general, how it is fixed
Checked-arithmetic helpers and explicit upper bounds on allocation sizes achieve the same result.
In general, hunting notes
This class hides in parsers and graphics code: image decoders, path and geometry handling, font and document formats, and anywhere a count from the file is multiplied by a structure size. Recon signals include 32-bit build targets, custom allocators or wrappers around realloc, and code comments admitting that a size calculation is unchecked. To make a report land, show the wrapped value, the resulting allocation, and the out-of-bounds write under a sanitizer or debugger, and state clearly which build width and platform are required. If a platform's allocator masks the bug, say so and show the conditions under which it would not, as this report does.
Glossary
- Buffer: a block of memory set aside to hold data.
- Integer overflow: when a number grows too large for its storage type and wraps around to a small value.
- 32-bit build: a version of a program that can address only about 4 GB of memory, making wrap-around easier to reach.
- Proof of concept (POC): a small program that demonstrates a bug.
- Breakpoint: a marker that pauses a program under a debugger so you can inspect it.
- Debugger: a tool for stepping through a running program and examining its memory.
- Memory-safety bug: a flaw where a program reads or writes memory it should not.
- Heap buffer overflow: writing past the end of a block of memory allocated at runtime.
- Allocator: the part of a program or system that hands out and resizes blocks of memory.
realloc: a standard function that resizes an existing memory block.ptrdiff_t: a signed integer type meant to hold the difference between two pointers.size_t: an unsigned integer type used for sizes and counts.- Size class: a bucket of similar-sized allocations that an allocator manages together.
- Address space: the range of memory addresses a program can use.
- Fragmentation: when free memory is split into small pieces that cannot satisfy a large request.
- Out-of-memory (OOM): when an allocation fails because no memory is available.
- Sanitizer: a tool that instruments a program to detect memory errors at runtime.
- False positive: a test result that looks like a bug but is not one.