> your AI agent picks dependencies from memory; give it dated facts — try starlog.dev ↗ vet your agent's deps ↗ vibe-coding is fine. vibe-importing isn’t. — try starlog.dev ↗ vibe-importing isn’t fine ↗ your agent has never seen your private packages — try starlog.dev ↗ facts for private packages ↗ a linter for the dependencies your AI agent picks — try starlog.dev ↗ a linter for agent deps ↗ whois is redacted, cdns mask the rest — get the real operator — try whoisgeni.us ↗ who really runs that domain ↗ domain attribution that shows its work — full evidence chain — try whoisgeni.us ↗ domain intel w/ evidence ↗

← Back to Articles

Inside a Deterministic PHP Type-Confusion Exploit: When 250KB Becomes 128MB

[ View on GitHub ]

Inside a Deterministic PHP Type-Confusion Exploit: When 250KB Becomes 128MB

Hook

Most exploits spray the heap hoping to land a hit. This one sends exactly 20 HTTP requests in sequence—either you get a shell on the first try, or the script aborts. No retries, no probabilistic techniques, just deterministic pointer math that works or doesn't.

Context

Modern web languages like PHP have spent two decades hardening against memory corruption. Unlike C servers where a buffer overflow gives you direct code execution, PHP's Zend engine sits between your HTTP request and actual memory, validating types and managing allocations. This creates a paradox for security researchers: the attack surface is huge (every parser, every upload handler, every session mechanism), but the path from 'I found a bug' to 'I can run arbitrary code' requires intimate knowledge of VM internals that change with every build.

StealMyBitcoin-PoC emerged from a CTF challenge that asked a deceptively simple question: can you steal Bitcoin from a PHP server that's already configured to resist you? The server ran Alpine Linux with PHP 8.4.26, used four worker processes, and exposed nothing but the built-in CLI server. No application code to exploit, no unserialize gadgets, no exposed phpinfo. Just the Zend engine itself. The resulting exploit is a 380-line Python script that demonstrates something rare in public exploit archives—a fully deterministic, single-shot attack chain that extracts heap addresses, fingerprints the exact PHP build, and achieves RCE by forging internal data structures. It's useless as a general-purpose weapon precisely because it's so tightly coupled to one environment, but that specificity makes it invaluable as a teaching tool.

Technical Insight

Stage 1: 250KB Nested Array POST

Memory Expands to 128MB

Partial Write

Stale Heap State

Stage 2: 8 Pipelined Reads

Race Condition Read

256-byte Cookie with Heap Metadata

Extract PHPSESSID Length Error

Stage 3: Different Array Shape OOM

Second Fatal Error

Page Offset 0x112930

Stage 4: Forged HashTable at Calculated Offset

Hardcoded Pointer Math

pDestructor = zif_system

Cleanup Walker Trigger

Attacker Script

PHP Worker

OOM Fatal Error

Session File

Restarted Worker

Leak Parser

Heap Layout Map

Function Pointer Leak

Fingerprint Alpine Build

Fake Call Frame

Command Execution

Shell Access

System architecture — auto-generated

The exploit chains three stages, each exploiting a different facet of PHP's session upload-progress mechanism. Stage one is an asymmetric memory amplifier. When you upload a file with session.upload_progress.enabled, PHP tracks progress by storing POST field names in a session array. Normally this consumes minimal memory, but deeply nested array notation explodes during parsing. A field name like f[0][x][x][x]... with 16,000 nested brackets arrives as 250KB on the wire but expands to 128MB in-process as PHP recursively allocates zval structures for each level. This triggers a memory_limit fatal error that crashes the worker—but crucially, not before some session data gets written to disk in a partially-initialized state.

The script constructs this payload with surgical precision:

stage1_fields = {
    'PHP_SESSION_UPLOAD_PROGRESS': 'A' * 200,
    'f' + '[0][x]' * 16000: 'padding_data'
}
stage1_response = requests.post(
    f'{TARGET}/index.php',
    files={'file': ('exploit.txt', 'X' * (250 * 1024))},
    data=stage1_fields,
    cookies={'PHPSESSID': session_id}
)

The 200-byte progress string and 250KB file body ensure PHP commits just enough to the session before the OOM kills it. When the worker restarts, it inherits file descriptors and heap state—but the session cleanup path didn't run completely. This leaves stale metadata in memory.

Stage two weaponizes PHP-FPM's worker reuse timing. The script pipelines eight consumer requests before reading any responses, increasing odds that at least one hits the same poisoned worker. These consumers request the session data with slight variations in cookie length. Because the stale state includes a miscalculated string length for PHPSESSID, PHP sometimes copies more bytes than intended when reconstructing the session, leaking adjacent heap metadata into the cookie echo. The script hunts for a 256-byte leak containing recognizable patterns—specifically, a zval pointer whose low bits should be zeroed due to alignment.

for i in range(8):
    pipeline_session = base_session + f'_leak_{i}'
    responses.append(session.post(
        f'{TARGET}/index.php?read_session',
        cookies={'PHPSESSID': pipeline_session},
        stream=True
    ))

for resp in responses:
    leaked_cookie = resp.cookies.get('session_data', '')
    if len(leaked_cookie) > 200:
        heap_metadata = parse_leak(leaked_cookie)
        if heap_metadata.zval_ptr_dtor:
            zend_heap_base = heap_metadata.zval_ptr_dtor & 0xFFFFFFFFF0000000

Once it extracts a heap address, stage three performs build fingerprinting. The script knows that Alpine PHP 8.4.26 places zval_ptr_dtor at offset 0x112930 from the Zend heap base. It checks the low 21 bits (which ASLR doesn't randomize within a binary) against this known value. If the fingerprint doesn't match, the script aborts—this prevents attempting exploitation against a different PHP build where all subsequent offset calculations would be garbage.

The final stage constructs a fake HashTable in memory by sending another OOM-inducing request with different array shapes. This time, the nested structure is crafted so that when PHP allocates and then partially frees it during the crash, a specific heap chunk ends up at a calculable offset from the leaked base address. The script writes a forged HashTable containing a pDestructor function pointer that points to zif_system (PHP's internal implementation of system()) and a fake bucket with a zend_string holding the command to execute.

fake_table_offset = zend_heap_base - 0x8400000 + 0x16D1D8
fake_hashtable = struct.pack('<Q', zif_system_addr)  # pDestructor
fake_hashtable += struct.pack('<Q', fake_bucket_addr)  # arData
fake_hashtable += struct.pack('<I', 1)  # nNumUsed
fake_hashtable += struct.pack('<I', 0)  # nTableMask

command_str = b'cat /flag.txt > /proc/self/fd/4'  # fd hunt
fake_zend_string = struct.pack('<I', len(command_str))
fake_zend_string += struct.pack('<I', 0)  # hash
fake_zend_string += command_str

When PHP's cleanup walker processes shutdown, it iterates the fake HashTable, finds the pDestructor, and calls it with the fake string as an argument—executing the command. The output redirection to /proc/self/fd/4 is critical: PHP CLI server workers don't inherit stdout, so the script first loops through file descriptors to find the active socket connection, then targets that fd for command output.

The entire chain succeeds or fails based on heap determinism. Change the Alpine image, adjust worker count from four to eight, or switch from CLI server to FPM, and every hardcoded offset breaks. But that's not a bug—it's proof that reliable exploitation at this level requires exhaustive target knowledge, not just a working primitive.

Gotcha

The elephant in the room: this exploit only works on PHP 8.4.26 running on Alpine Linux with exactly four CLI server workers. The hardcoded offset zend_heap_base - 0x8400000 + 0x16D1D8 assumes a specific heap layout that changes with worker count, glibc version, and PHP compilation flags. If you're running Debian's PHP build, the zval_ptr_dtor fingerprint check will fail before attempting exploitation. If you've configured eight workers instead of four, the heap allocator produces different chunk patterns and the fake_table lands in the wrong place, causing a segfault instead of code execution.

The single-shot execution model is both a strength and weakness. There's no retry logic, no adaptive offset calculation, no fallback if a leak returns empty. Network hiccups kill the entire chain. The pipelined consumer requests in stage two waste seven attempts if stage one fails, because the script sends all eight before checking if any succeeded. For production use, you'd need version detection, worker count enumeration, and a retry mechanism—essentially rebuilding the deterministic approach into something probabilistic. Command length is capped at 231 bytes by the fake zend_string layout, which works for 'cat flag.txt' but complicates more sophisticated post-exploitation. You'd need to stage a full shell through multiple invocations or base64-encode a longer payload and decode it in the command string.

Verdict

Use this if you're a security researcher studying PHP internals, building CTF challenges, or need a reference implementation for type-confusion attacks against memory-managed languages. It's the best publicly available example of deterministic heap exploitation in a modern VM, showing exactly how upload-progress parsing, worker reuse timing, and cleanup-path bugs can chain into RCE when you control the runtime. The single-file format with extensive comments makes it trivial to adapt for educational workshops or red-team training scenarios where you want to demonstrate 'exploitation without spraying.' Skip this if you need a working PHP shell for pentesting—the Alpine-specific offsets make it useless against real-world targets, and any sysadmin who changes worker count or updates PHP breaks your entire chain. Also skip if you're looking for a generalizable attack: traditional deserialization exploits or FastCGI bugs work across versions and distributions without requiring heap address leaks. This is a scalpel, not a Swiss Army knife, valuable precisely because it sacrifices portability for determinism.