PHP2Shell: From Out-of-Memory Error to Remote Code Execution

PHP2Shell hero with the official PHP logo and the four stages from count-first to verified local RCE

The short version

Two critical bugs in PHP itself, both rated CVSS 9.2, can turn a deliberately triggered out-of-memory condition into remote code execution. The attacker aims to exhaust PHP’s request memory at a particular point. The fatal error is part of the attack, not proof that it worked.

Fixed upstream releases (8.5.12 / 8.4.27 / 8.3.36 / 8.2.35) arrived on 21 October 2026. On PHP ≤ 8.1, use a maintained package that explicitly backports the fix; there is no new fixed upstream release for those branches.

Triggering a memory limit is much easier than making the resulting corruption useful. Reliable exploitation depends on the target build and execution path. Calif documented the deeper exploit work (technical writeup).


The three pieces to watch

The bug makes more sense if you keep track of a limit, a bucket and the shutdown path:

  1. memory_limit: the configured heap budget for a request, set to 128 MiB in this example. An allocation that crosses it causes a fatal error and ends the request.
  2. The bucket: one entry in the hash table behind a PHP array. It holds a value and bookkeeping about that value.
  3. Shutdown: when the request ends, PHP walks the buckets and destroys their values. It uses the recorded bucket count (nNumUsed), including an entry that may not have finished initializing.

Three-panel comic: the bucket that got counted first
The ordering matters: PHP records the bucket before it finishes initializing it.

The allocation that goes wrong

Inside PHP’s hash table code, adding an element follows this order:

idx = ht->nNumUsed++;          // 1. count it FIRST ("one more bucket!")
ht->nNumOfElements++;                 // the live-element counter moves too
p = ht->arData + idx;
p->key = zend_string_init(...); // 2. THEN allocate the key; memory_limit may be hit here
p->h = ...;                    // 3. never reached if we died
ZVAL_COPY_VALUE(&p->val, ...); // 4. never reached either

The count changes before the key allocation. If that allocation exhausts the request’s memory, PHP aborts with the count already incremented. Shutdown then treats the unfinished bucket as an initialized entry.

The bucket may still contain bytes left in that heap slot. Destruction code interprets those bytes as a valid value, creating a path from an allocation failure to memory corruption. Turning that corruption into command execution requires the additional, target-specific work described below.

Reaching the memory limit over HTTP

PHP’s post_max_size (8 MB by default) limits request bodies, but the parser can allocate far more memory than the body itself occupies. The research used two techniques:

Empty file parts. A multipart form part with filename="" contains no file and doesn’t count toward max_file_uploads. PHP still builds six $_FILES entries for it: name, full_path, type, tmp_name, error, and size.

Give each part a deeply nested field name such as files[a][b][c]…, and PHP carves out a fresh stack of hash tables per entry. Hundreds of small parts can therefore use much more heap memory than their combined HTTP body size suggests.

No useful declared body length. PHP checks post_max_size against the declared Content-Length before parsing. A chunked HTTP/1.1 request, or an HTTP/2 request without Content-Length, supplies no meaningful declared length for this pre-check. The up-front size check does not account for what the parser subsequently allocates.

In our lab, 940 empty-file parts with 56-deep names plus one 3 MB key made a stock PHP 8.3.35 Apache worker hit the configured 128 MiB limit. The fatal error fired during request parsing, before our PHP code even ran. Application validation cannot stop this startup trigger. The separate FPM chain still needs a suitable decode inside application code after startup.

Why mod_php and PHP-FPM behave differently

mod_php vs FPM fork diagram
The worker’s fate depends on the SAPI and when the fatal error occurs.

The same fatal error has different consequences depending on when and where PHP handles the request:

Apache mod_php has two distinct paths. In the stale-bucket path, Request A’s own shutdown consumes the half-registered $_POST/$_FILES table. A forged destructor can run there; no second request is needed. Calif’s arbitrary-script result covers PHP ≥ 7.3.

The session-global path is different. Early upload-progress initialization leaves session globals pointing into freed heap, and the Apache worker survives. A second multipart request without a file reaches the upload-progress END handler and consumes those stale globals. That path extends arbitrary-script RCE to PHP ≥ 5.4. The trigger and the later read happen in different requests.

PHP-FPM handles a startup fatal differently: the worker exits and takes the stale state with it. There is no Request B. After a successful startup, an application fatal follows ordinary request shutdown, and the worker can survive.

In our lab, session_start() decodes a valid session record, hits the memory limit, and leaves the unserializer bookkeeping pointing into freed heap. A consumer request reaches the same worker with a different session ID. Its multipart body includes a file part, so upload-progress FILE_START processing decodes the consumer session before Basic’s normal request initialization resets the old decoder state.

This path is application-dependent. Calif confirmed pre-auth RCE through WordPress’s maybe_unserialize(), phpMyAdmin’s session_start(), and other reachable decode operations.

Two building blocks also showed up in separate lab probes: FPM workers kept the same pool PIDs across post-startup OOM fatals, and a no-file upload-progress request created session state on a page that never calls session_start(). That no-file probe demonstrates early session initialization; the final FPM consumer itself includes a file part.

The two-request heist

Two-request exploit sequence diagram
Request A leaves the dangling state; request B consumes it. The second request must reach the affected worker.

The two-request session and decoder chains share a simple shape: one request abandons bookkeeping, a later request on the same worker makes PHP trust it again. The one-request stale-bucket teardown is separate. Our final FPM route looks like this:

  1. Request A, the producer: the application calls session_start() on a valid 24 MiB session record with memory_limit=32M. Startup has already succeeded when decoding hits the limit. The decoder’s normal cleanup is skipped, BG(unserialize) still points into the old request heap, and the FPM worker survives.
  2. Request B, the consumer: a request reaches that worker with a different consumer session ID. Two 8191-byte multipart values reclaim the freed 8216-byte decoder allocation. The body also carries PHPSESSID, PHP_SESSION_UPLOAD_PROGRESS, and a small file part; FILE_START processing initializes and decodes the four-key consumer session before Basic’s normal request initialization resets the old decoder state.

A few PHP structures matter here. A zval is PHP’s record of a value and its type. A HashTable is the internal table behind an array. The table’s pDestructor is the function pointer PHP calls to destroy its values.

The consumer record has exactly four top-level keys. The first two placeholders are calibrated addresses; <array gc> is a packed array-header value. None of them is literal exploit text:

a|a:1:{i:0;i:0;}b|i:<fake var_entries>;c|i:<second dtor block>;z|i:<array gc>;

a supplies a genuine session array; b and c steer writes through the reclaimed decoder bookkeeping; z supplies the packed array-header value for the fake array. Those controlled writes replace the genuine array’s HashTable with a forged one. Its bucket contains the string id, and its pDestructor points at system. When the session decoder runs its normal destructor-list cleanup, it destroys the corrupted a value; the forged table’s pDestructor then calls system("id").

The worker then aborts and a fresh worker takes over. That crash is not evidence of command execution. The evidence is the log marker uid=33(www-data). An HTTP 502 by itself proves nothing.

Where does negative used_slots fit?

Each destructor block has a signed slot counter. On the tested 64-bit layout, PHP chooses a slot at block + 16 + 16 × used_slots. If reclaimed bytes set that counter to -1, the calculation selects memory before the intended array.

In a separate debugger-checked run, we proved that PHP accepts the negative count and copies a genuine zval into the fake block header. That is a real write primitive.

It is also a different evidence level from the final four-key, fake-array RCE route above. That debugger run establishes a write primitive, but it is not itself proof of the four-key RCE route.

What our lab runs showed

Every exploit request below stayed on loopback against disposable containers. “Command execution” means an actual id marker, never a crash or an HTTP error by itself.

Local chain Vulnerable result Patched control
Multipart OOM trigger PHP 8.3.35: request-startup memory fatal PHP 8.3.36: normal application response
mod_php stale bucket PHP 8.2.6: uid=33(www-data) marker PHP 8.2.35: no marker; HTTP 200
mod_php session globals PHP 8.4.26: marker in two ASLR-distinct runs PHP 8.4.27: no marker; normal OK response
FPM stale decoder PHP 8.3.35: uid=33(www-data) log marker in two runs PHP 8.3.36: no marker; normal response to a byte-identical request
GNOME Terminal running the Python exploit against real WordPress on loopback, with PROOF uid=33(www-data)
Exploit running against WordPress 7.1.2 on PHP 8.4.26 in a disposable container

The limits matter. The stale-bucket and FPM runs are local white-box exploits: debugger and process inspection supply calibration and code addresses. The session-global chain obtains its heap and libphp ASLR bases over HTTP and succeeded twice with different bases, but still uses target-specific build offsets in this lab. None of this is a universal remote ASLR bypass, a claim about a production host, or proof that every public PoC works on a default installation.

The patched controls matter as much as the exploit runs. In the matched tests, the fixed builds either handled the request safely or produced no command-output marker. The 8.3.36 source adds ZEND_HAS_OOM() early-abort checks in variable registration and fallible hash-table allocation paths. The practical response is to install a patched PHP build.

Patch and mitigation panel
Patched versions, the backport warning, partial mitigations, and our lab’s before/after differential.

Check the PHP build serving your site

Start on your server:

php -v                                   # fixed upstream: 8.2.35 / 8.3.36 / 8.4.27 / 8.5.12
php -i | grep -E 'memory_limit|upload_progress'
ps aux | grep -E 'php-fpm|apache'        # which SAPI?

The CLI can use a different PHP build and configuration from the web handler. Confirm the version and SAPI through the handler that serves the site, and check the package changelog for the CVE. Do not solve this by leaving a public phpinfo() page behind.

  • PHP ≤ 8.1: no new fixed upstream release exists for these branches. Use a maintained distribution or extended-support package with an explicit backport; a version number alone cannot tell you whether that patch is present.
  • mod_php + unpatched: arbitrary-script RCE paths exist, with the applicable version range depending on the path.
  • FPM + unpatched: the demonstrated route needs a reachable post-startup decode and reuse of the same worker. “The app calls unserialize() somewhere” is not enough to conclude remote exploitability.

Temporary mitigations are partial. Blocking multipart/form-data at the web server removes the known trigger shape, but can break uploads and forms. memory_limit=-1 removes this OOM trigger while letting PHP consume real RAM instead. On both mod_php and FPM, session.upload_progress.enabled=0 reduces exposure to the early-session producer/consumer, but is not sufficient on its own. Combine temporary controls where their trade-offs are acceptable, then patch.

We checked our own hosting after the details landed on 21 October. SiteGround was running patched PHP 8.3.36, which we verified during a brief site shutdown. Ask your provider for the version used by the web handler, not just the version printed by a CLI command.

Disclosure timeline

  • 2004: Stefan Esser finds an earlier PHP memory_limit remote bug.
  • 2020: a related OOM-in-multipart issue is reported (#78876).
  • 2024: OSTIF/Quarkslab flag a related bug in an audit; exploitation unproven.
  • Aug 2026: Calif reports multiple RCE paths to PHP; a proof of concept is confirmed.
  • 20 Oct 2026: embargo details appear early on Hacker News.
  • 21 Oct 2026: PHP releases patches in 8.5.12, 8.4.27, 8.3.36 and 8.2.35.

About Post Author