Inside a PHP 8 Zero-Day: Turning Session Cookies Into ASLR Bypass Primitives
Hook
A PHP application with zero vulnerable code—no eval(), no unserialize(), no file uploads—can still be exploited to execute arbitrary shell commands by manipulating how sessions handle multipart forms.
Context
Modern PHP exploitation has traditionally relied on two attack surfaces: vulnerable application code (like deserialization chains or command injection) or known CVEs in the PHP interpreter itself. Security researchers have long understood that session.upload_progress, introduced in PHP 5.4, could be weaponized for race condition file writes. But those attacks required writable session directories and specific timing windows.
The 9bie/php2shell-bypass-aslr-exp repository demonstrates something far more sophisticated: a multi-stage remote code execution exploit that works against pristine PHP applications by attacking the session mechanism's internals during the pre-RINIT phase—before your application code even starts executing. It's a masterclass in heap exploitation that bypasses ASLR entirely over HTTP, requiring no vulnerable functions in the target application. While its practical applicability is limited by strict environmental requirements, the techniques it demonstrates represent the cutting edge of memory corruption exploitation in managed runtime environments.
Technical Insight
The exploit architecture operates in three distinct phases, each exploiting a different aspect of PHP's session and memory management systems.
Phase 1: Worker Rotation Through Controlled Crashes
The attack begins by exploiting Apache's prefork MPM behavior. When a worker process crashes (SIGABRT from out-of-memory), Apache spawns a replacement worker with identical ASLR memory mappings—the parent process forks, preserving the address space layout. The exploit triggers this by sending oversized POST fields that exhaust memory_limit:
# Force worker crash while preserving ASLR state
def rotate_worker(session, target_url):
# Send oversized multipart data to trigger OOM
fields = {
'overflow_field': 'A' * (8 * 1024 * 1024), # Exceeds 8M memory_limit
'PHP_SESSION_UPLOAD_PROGRESS': 'crash_trigger'
}
try:
session.post(target_url, files=fields)
except:
pass # Worker crashed, new worker spawned with same ASLR layout
# Next request hits new worker with preserved memory addresses
return session
This gives the attacker a stable memory layout across multiple HTTP requests—a prerequisite for deterministic heap manipulation.
Phase 2: Two-Stage Address Leaking via Fake HashTables
The core innovation lies in exploiting session.upload_progress's initialization sequence. When PHP processes multipart uploads with a field named PHP_SESSION_UPLOAD_PROGRESS, it initializes session tracking before RINIT (request initialization)—even if the application never calls session_start(). If this initialization hits an OOM condition mid-process, it bails out but leaves dangling pointers in PS(http_session_vars) and PS(id).
The exploit carefully constructs multipart fields with precise byte sizes (56B, 55B, 167B) that reclaim these freed memory blocks. These sizes aren't arbitrary—they're calculated to align with Zend Memory Manager's chunk allocation patterns. The reclaimed memory is populated with fake HashTable structures:
// Simplified representation of fake HashTable construction
// Actual exploit builds this via multipart field content
typedef struct _zend_array HashTable;
struct fake_hashtable {
uint32_t nTableMask; // 0xfffffffe (size 2)
zend_array *arData; // Points to controlled chunk containing buckets
uint32_t nNumUsed; // 1 bucket
uint32_t nNumOfElements; // 1 element
// ... other fields ...
dtor_func_t pDestructor; // Key field: will be set to zval_ptr_dtor or zif_system
};
When PHP attempts to URL-encode this fake HashTable for Set-Cookie emission, the php_url_encode function performs an out-of-bounds read on the fake bucket array. Because the bucket array pointer (arData) points to a controlled heap chunk, the OOB read spills into adjacent Zend MM metadata—specifically, chunk pointers that reveal heap addresses. These leak into the Set-Cookie header:
Set-Cookie: PHPSESSID=[chunk_base_0xaa40][chunk_base_0xaa80][...98_total_pointers...]; path=/
With the heap base address leaked, stage two repeats the process but positions PS(id) at a calculated offset (chunk+0xb7400) where zval_ptr_dtor function pointers from libphp.so reside. The same OOB read technique now leaks libphp base addresses, defeating ASLR completely.
Phase 3: Execution via Destructor Hijacking
The final stage constructs a weaponized fake HashTable where pDestructor points to zif_system (PHP's internal implementation of the system() function). The bucket's value is set to an IS_STRING zval containing the shell command. When session cleanup triggers php_session_track_init, the call chain zval_ptr_dtor → zend_reference_destroy → zend_hash_destroy invokes the fake destructor:
# Simplified command execution payload construction
def build_execution_payload(libphp_base, zif_system_offset, command):
payload = {
'pDestructor': libphp_base + zif_system_offset, # zif_system address
'bucket_val': { # Fake zval structure
'type': 6, # IS_STRING
'value': command[:14] # Max 14 bytes due to zval size constraints
}
}
return encode_as_multipart_field(payload)
The 14-byte command limit is a hard constraint imposed by zval structure size. The exploit's workaround—sh</out/c—assumes a pre-staged script exists in a mounted volume, which significantly limits real-world applicability.
Heap Feng Shui Calibration
Perhaps the most intricate aspect is deterministic heap layout. The exploit includes profiling tools (docker/offsets.py) that extract symbol offsets from libphp.so and calculate precise "filler" counts—the number of dummy multipart fields needed to align heap chunks correctly. For Debian 12 (bookworm), this value is 841 fillers. Different PHP builds require re-profiling, making the exploit brittle across environments.
Gotcha
The exploit's environmental requirements are so strict that it functions more as a research proof-of-concept than a practical offensive tool. Most critically, it requires display_errors=On to trigger the max_input_vars warning that sets the headers_sent flag—a configuration almost never enabled in production. The repository mentions a bypass is "coming soon," but as of now, this is a show-stopper.
The Apache prefork single-worker requirement is equally limiting. Production deployments typically run 5-150 prefork workers, or more commonly, use event/worker MPM or nginx+PHP-FPM entirely. Even if you could target prefork, the OOM-based worker rotation generates highly visible SIGABRT crashes and 500 errors that would immediately trigger any competent monitoring system. The exploit also requires memory_limit=8M, far below typical production values of 128M-512M, making the attack surface vanishingly small. Add version-specific heap layout calibration (841 fillers for bookworm must be recalculated for each PHP build), and you have an exploit that works beautifully in a controlled lab environment but falls apart against real infrastructure.
Verdict
Use if: You're a security researcher studying advanced heap exploitation techniques, PHP internals, or modern ASLR bypass methodologies in managed runtimes. This repository is an exceptional educational resource for understanding reference-counting use-after-free chains, deterministic memory layout manipulation, and weaponizing obscure runtime behaviors. If you're developing fuzzing tools for PHP or auditing session mechanism security, the techniques here provide invaluable insight into pre-RINIT attack surfaces that exist independently of application code.
Skip if: You need a practical PHP exploitation tool for penetration testing or red team operations. The environmental constraints (display_errors, single-worker prefork, 8M memory limit, specific PHP version) make this unsuitable for real-world targets. Traditional PHP vulnerabilities—deserialization chains, file upload bypasses, known CVEs like CVE-2024-4577—offer far broader applicability with less complexity. The 14-byte command limit alone disqualifies this for most post-exploitation scenarios. Treat this as an academic masterpiece demonstrating what's theoretically possible, not as a weapon you'd deploy against actual infrastructure.