gdImageColorMatch in gd_color_match.c in the GD Graphics Library (aka LibGD) 2.2.5, as used in the imagecolormatch function in PHP before 5.6.40, 7.x before 7.1.26, 7.2.x before 7.2.14, and 7.3.x before 7.3.1, has a heap-based buffer overflow. This can be exploited by an attacker who is able to trigger imagecolormatch calls with crafted image data.
Created gd tracking bugs for this issue:
Affects: fedora-all [bug 1672210]
Created php tracking bugs for this issue:
Affects: fedora-all [bug 1672209]
Created libwmf tracking bugs for this issue:
Affects: fedora-all [bug 1672240]
This is essentially a flaw in gdImageColorMatch(), which can be triggered via the PHP API imagecolormatch() [http://php.net/manual/en/function.imagecolormatch.php]
The imagecolormatch() takes two gdImagePtr as arguments and compares them. It allocates a buffer based the following:
buf = (unsigned long *)safe_emalloc(sizeof(unsigned long), 5 * im2->colorsTotal, 0);
Here im2>colorsTotal comes from the second image being compared and therefore is under the controller of the attacker. By simply allocating only one color to the second image, the calculation becomes sizeof(unsigned long) (8 byte on a 64 bit system) * 5 * 1, which results in a buffer of 40 bytes.
However, an attacker can set the value of color to be at maximum 255 (since it is a char). This would result in bp pointing at buffer + 1275 bytes. Since buffer is only 40 bytes big, this leads to an out of bounds write with data that is also under the control of the attacker.
The attacker needs to be able to upload a specially crafted image to a PHP script, which uses the imagecolormatch() function in order to trigger this flaw.
Simple way to reproduce from https://gist.github.com/cmb69/1f36d285eb297ed326f5c821d7aafced
$img1 = imagecreatetruecolor(0xfff, 0xfff);
$img2 = imagecreate(0xfff, 0xfff);
imagecolorallocate($img2, 0, 0, 0);
imagesetpixel($img2, 0, 0, 255);