The vulnerability is a heap-based buffer overflow in ImageMagick's MagickCore/blob.c. The root cause of the vulnerability lies in the WriteBlob function when used in conjunction with SeekBlob on a memory-backed BlobStream.
The exploit scenario unfolds in two steps:
- An attacker uses the
SeekBlob function to move the internal offset of a blob to a position far beyond its currently allocated size. The SeekBlob function itself is not flawed; it correctly updates the offset as requested.
- The attacker then calls
WriteBlob to write data to the blob. The vulnerable version of WriteBlob fails to correctly calculate the amount of memory required to accommodate the write at the new, large offset. Instead of calculating the required size based on offset + length, it calculates it based on extent + length + quantum. When the offset is significantly larger than the extent, this results in an undersized memory allocation.
The subsequent memmove operation within WriteBlob attempts to write the data at the specified offset, which now points to a location outside the bounds of the newly allocated (but too small) buffer. This out-of-bounds write corrupts the heap, which can lead to a crash (denial of service) or, potentially, arbitrary code execution.
The provided patch addresses this by changing the allocation logic in both WriteBlob and the inline function WriteBlobStream. The corrected code first calculates the required size (extent) based on the offset and length of the data to be written, ensuring that the buffer is always allocated to a sufficient size to prevent the overflow.