Apr 13, 2026·8 min read·4 visits
An integer underflow in ImageMagick's XML parser allows an attacker to write an out-of-bounds null byte, corrupting heap metadata. This primitive causes application crashes and presents a theoretical path to remote code execution.
ImageMagick versions prior to 7.1.2-19 and 6.9.13-44 contain a heap-based buffer overflow vulnerability in the XML parsing engine. The flaw arises from an integer underflow during UTF-16 to UTF-8 character conversion in the `NewXMLTree` function, leading to a single null byte being written out of bounds. This memory corruption can compromise heap metadata, reliably causing a denial of service and introducing the potential for remote code execution under specific heap manipulation conditions.
ImageMagick is a ubiquitous software suite and library utilized by countless web applications, content management systems, and backend services for processing digital images. Its extensive format support relies on various internal parsing engines, including an XML processor used for interpreting embedded image profiles, metadata schemas, and vector graphics like SVG. The vulnerability resides within the MagickCore/xml-tree.c component, specifically within the NewXMLTree function responsible for instantiating XML tree structures in memory.
The core issue is a heap-based buffer overflow (CWE-122) precipitated by an integer underflow (CWE-191). When the XML parser processes incoming data, it performs character encoding conversions to standardize internal representations. If an attacker supplies a specialized payload that yields an empty string during the conversion from UTF-16 to UTF-8, the application miscalculates the required buffer indexing.
This miscalculation translates into an out-of-bounds memory write. The application writes a single null byte precisely one byte before the start of an allocated heap buffer. While restricted to a single byte of value zero, this specific corruption primitive targets a highly sensitive area of process memory: the heap chunk metadata.
The widespread integration of ImageMagick via wrappers (such as PHP's Imagick, Ruby's Paperclip, and Magick.NET) amplifies the attack surface. Applications that process user-supplied images without strict format sanitization expose the vulnerable XML parsing paths to external network actors, fulfilling the requirements for remote exploitation.
The execution flow leading to the vulnerability begins when NewXMLTree processes XML data structures containing text encoded in UTF-16. The function invokes a conversion routine, ConvertUTF16ToUTF8, to normalize the text for subsequent processing. The application captures the length of the resulting UTF-8 sequence in the length variable, a signed integer type.
The vulnerability manifests when the supplied XML payload forces the conversion routine to return an empty string. In this scenario, the length variable correctly evaluates to 0. However, the code immediately proceeds to null-terminate the converted string or inspect its final character using the expression length - 1 as the array index.
Because length is 0, the expression underflows, yielding -1. The C standard permits negative array indices, effectively subtracting the offset from the base pointer. The instruction utf8[-1] = '\0' thus executes, instructing the CPU to write a zero byte to the memory address immediately preceding the utf8 heap allocation.
In modern heap implementations like glibc's ptmalloc, the memory preceding an allocated user payload contains critical structural metadata. The 8 or 16 bytes immediately before the user data pointer typically store the chunk's size and status flags, including the crucial PREV_INUSE bit. Overwriting the least significant byte of this size field with zero can shrink the perceived size of the chunk or clear the PREV_INUSE flag, severely compromising the structural integrity of the heap manager.
The vulnerable code path in MagickCore/xml-tree.c assumed that a successful return from the conversion routine guaranteed at least one byte of output data. The developers directly utilized the length calculation without a preceding bounds check.
// Vulnerable implementation
terminal=utf8[length-1];
utf8[length-1]='\0';
p=utf8;The upstream maintainers addressed this vulnerability in commit ae679e2fd19ec656bfab9f822ae4cf06bf91604d. The patch introduces the MagickMax macro to clamp the index array evaluation, ensuring the offset never falls below zero.
--- a/MagickCore/xml-tree.c
+++ b/MagickCore/xml-tree.c
@@ -1919,8 +1919,8 @@ MagickExport XMLTreeInfo *NewXMLTree(const char *xml,ExceptionInfo *exception)
"ParseError","UTF16 to UTF8 failed");
return((XMLTreeInfo *) NULL);
}
- terminal=utf8[length-1];
- utf8[length-1]='\0';
+ terminal=utf8[MagickMax(length-1,0)];
+ utf8[MagickMax(length-1,0)]='\0';
p=utf8;
while ((*p != '\0') && (*p != '<'))
p++;While this modification successfully prevents the negative index and the subsequent -1 out-of-bounds write, the resulting state requires precise scrutiny. If length is zero, the clamped index defaults to zero, executing utf8[0] = '\0'.
If the ConvertUTF16ToUTF8 function returns a pointer to a strictly zero-byte heap allocation, writing to utf8[0] still constitutes a one-byte heap overflow into the adjacent chunk. The security boundary relies entirely on the allocator's internal behavior. Most allocators enforce minimum chunk sizes (e.g., 24 or 32 bytes), meaning a zero-byte request returns a pointer with sufficient slack space to safely absorb the single byte write. However, on custom allocators or highly constrained environments, this clamped write might remain exploitable.
Exploiting this vulnerability requires network access to an endpoint that passes user-controlled data to ImageMagick's parsing engine. The primary vector involves uploading image formats that inherently embed or support XML schemas. SVG files, XMP metadata blocks embedded in JPEGs or PNGs, and specialized XML configuration files serve as valid delivery mechanisms.
The attacker engineers the payload to survive initial application validation while ensuring the embedded XML text contains UTF-16 byte sequences that map to an empty representation upon UTF-8 conversion. When the target application processes the image, the XML parsing loop triggers the specific conversion anomaly, resulting in a zero-length output and executing the underflow logic.
The immediate result is an off-by-one (specifically, off-by-minus-one) null byte overwrite, often termed a "poison null byte" vulnerability. In exploitation scenarios against the glibc heap, attackers leverage this primitive to orchestrate a chunk unlinking attack. By overwriting the least significant byte of the chunk size field, the attacker creates a discrepancy between the actual chunk boundaries and the boundaries tracked by the heap manager.
The attacker must then predictably trigger subsequent memory allocations and deallocations. The heap manager, relying on the corrupted metadata, attempts to consolidate free chunks. The discrepancy forces the manager to process overlapping chunks, allowing the attacker to corrupt forward and backward pointers within the heap. Ultimately, this manipulation yields an arbitrary memory write primitive, enabling control over program execution flow via hijacked function pointers or saved return addresses.
Currently, no public proof-of-concept exists for this specific vulnerability. Weaponizing a poison null byte requires deep knowledge of the target's operating system, heap layout, and allocation patterns. The attack complexity is significantly elevated by modern memory protections such as Address Space Layout Randomization (ASLR) and Position Independent Executables (PIE).
The immediate, highly reliable impact of this vulnerability is a Denial of Service (DoS). When heap metadata is corrupted, any subsequent call to malloc or free that traverses the affected heap segment will detect the inconsistency. The standard response by modern heap managers is an immediate process abort (e.g., corrupted size vs. prev_size). In environments where ImageMagick processes images synchronously within the main application thread, this abort terminates the entire service.
The potential for Remote Code Execution (RCE) dictates the severe underlying risk. While the CVSS v3.1 vector categorizes the impact as Availability: Low (A:L) and Confidentiality/Integrity as None (C:N, I:N), this strict interpretation reflects the difficulty of exploitation rather than the theoretical limits of the primitive. A successful chunk unlinking attack bypasses these limitations, granting the attacker full execution privileges under the context of the ImageMagick process.
The vulnerability does not currently appear in the CISA Known Exploited Vulnerabilities (KEV) catalog. The lack of active exploitation aligns with the high technical barrier required to chain a single null byte overwrite into reliable RCE across diverse server environments.
The definitive remediation strategy requires upgrading the ImageMagick installation. System administrators and developers must deploy ImageMagick version 7.1.2-19 or 6.9.13-44. Development teams utilizing the Magick.NET wrapper must update their dependencies to version 14.12.0 to inherit the upstream parsing fixes. Following the upgrade, operators must restart all services reliant on the library to ensure the patched binaries are loaded into memory.
In environments where immediate patching is prohibited by operational constraints, administrators can deploy configuration-based mitigations. Modifying ImageMagick's policy.xml configuration file to explicitly deny the processing of XML-based image formats significantly restricts the attack surface. Operators should add strict policy rules disabling readers for SVG, MVG, and internal XML delegates.
Network defenders must implement Web Application Firewall (WAF) or Intrusion Prevention System (IPS) rules designed to intercept malformed XML payloads targeting image upload endpoints. Detection logic should scrutinize embedded XML profiles for anomalous UTF-16 byte sequences that resolve to empty strings. Furthermore, Software Composition Analysis (SCA) pipelines must be configured to flag any container images or application dependencies referencing vulnerable MagickCore libraries.
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L| Product | Affected Versions | Fixed Version |
|---|---|---|
ImageMagick ImageMagick | < 7.1.2-19 | 7.1.2-19 |
ImageMagick ImageMagick | < 6.9.13-44 | 6.9.13-44 |
Magick.NET dlemstra | < 14.12.0 | 14.12.0 |
| Attribute | Detail |
|---|---|
| CWE ID | CWE-122, CWE-191 |
| Attack Vector | Network |
| CVSS Score | 5.3 (Medium) |
| Impact | Denial of Service / Potential RCE |
| Exploit Status | Unexploited |
| KEV Status | Not Listed |
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.