GD Graphics Library Integer Overflow Leading to a Heap Overflow
28 Oct. 2004
Summary
GD is an ANSI C library for the dynamic creation of images. GD creates PNG, JPEG and GIF images, among other formats. It is also library used by PHP to manipulate images. There is an integer overflow when allocating memory in the routine that handles loading PNG image files. This later leads to heap data structures being overwritten.
Credit:
The information has been provided by sean.
Vulnerable Systems:
* GD Version 2.0.28 (versions probably vulnerable as well)
If an attacker trick a user into loading a malicious PNG image, they could leverage this into executing arbitrary code in the context of the user opening image. Many programs use GD, such as ImageMagick, and more importantly it is also the image library used for PHP, and there is a Perl module as well. One possible target would be PHP driven photo websites that let users upload images. Some of them will resize/compress the image when the user uploads them. If this is done using GD, this could be used to execute code on the server. There is a mitigating factor, in order to reach the vulnerable code, a large amount of memory needs to be allocated. My 128MB p2 crapped out one allocation before it reached the overflow. However, I think on a newer box with lots of memory and swap space, that won't be a problem.
Vulnerable Code:
The vulnerable code occurs in the file gd_png.c, in the function gdImageCreateFromPngCtx(), which is called by gdImageCreateFromPng(). The function is used to load an image file into GD data structures. The problem occurs when allocating memory for the image rows, line 314 or so. Two user supplied values are multiplied together (rowbytes * height), and used to allocate memory for an array of pointers. This pointer array is then passed to the png_read_image() function, which belongs to the libPNG library. In that function, the pointers are passed to the png_read_row() function. The data for the rows is decompressed using zLib function inflate(), and then passed to the png_combine_row() function, where the deflated data is memcpy()'d into the heap buffer. Exploitation would require using zLib functions to compress the payload. Successful exploitation would lead to executing arbitrary code.
Vendor Status:
The author was contacted and replied that the issue will be resolved in the upcoming release.
/*
* a chunk looks like:
* [ 4 byte len ] - just the length of data
* [ 4 byte id] - identifies chunk data type
* [ 0+ data] -
* [ 4 byte crc ] - covers the id and data
*/
/* identifies a file as a png */
#define MAJIC_LEN sizeof(png_majic)
u_char png_majic[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };