PHP2Shell: Two bugs in how PHP handles request memory

We use PHP at Antsand. ShivasNotes, the site you're reading, runs on PHP too. When the PHP2Shell fixes came out, I wanted to understand what went wrong inside PHP and how to check that our running servers had the fix.

The first bug starts when PHP adds an entry to a table. PHP increases the entry count before it finishes building the entry. If a memory allocation fails in between, cleanup uses that count and tries to read an unfinished entry. In the second bug, a worker keeps a pointer to memory that was freed at the end of a request.

I made a three-panel comic for the first bug and a small C lab so you can see what changes when we update the count last.

Four-stage failure map: request input creates memory pressure, fallible native work is interrupted, cleanup trusts unfinished or freed state, and a reused worker can consume stale state
Follow the arrows from a web request to memory pressure, interrupted work, cleanup, and a reused worker. Open full-size SVG.

What the October 21 release fixed

PHP released 8.2.35, 8.3.36, 8.4.27, and 8.5.12 on October 21 to fix two critical remote-code-execution vulnerabilities. I started with the PHP security announcement for the versions and the Calif report for the code. I read the second bug separately because it involves what a worker keeps between requests.

FindingBroken assumptionWhere the damage appears
CVE-2026-109618OOM may interrupt native code between publishing a structure and completing it.Cleanup reads partly initialized request memory as though it were valid.
CVE-2026-109619A persistent worker global may still point into a request heap after that heap is freed.A later request accesses stale state before normal initialization replaces it.

For the first bug I followed the table's entry count into cleanup. For the second I followed the pointer from the request that allocated it to the worker that kept it. Two layers I maintainPHP runtime and Antsand codePatching php-src handles the engine bug. Our checkout and reader authorization still need their own tests.

Earlier reports on allocation and cleanup

Stefan Esser's 2004 advisory described cleanup of a partly initialized HashTable after PHP hit a memory limit. In 2020, bug #78876 documented a temporary-file cleanup problem after a multipart parser ran out of memory. Calif's report also notes a related finding from a 2024 audit. These were separate bugs. Reading them together helped me see why the failure branch is worth tracing on its own.

Timeline with distinct milestones in 2004, 2020, 2024, August 2026 and October 2026, ending in the supported PHP security releases
Different bugs, a recurring question: what can run after an allocation fails? Open full-size SVG.

The linked archived Immunity paper is part of that historical trail, but I could not verify its contents from the archived copy while preparing this post. I do not use it as evidence for the 2026 mechanism. The separate May 2026 unserialize() use-after-free study is also worth reading: it examines a missing serialization lock around a user-defined Serializable callback, with a much narrower remote precondition. It is not the same defect as the October vulnerabilities discussed here.

Step 1: Count what PHP allocates while parsing a request

I started with the memory bill for a request. Each field can give PHP more than a value to store: it can need a key, an entry in a table, and parsing metadata. The request body size tells me how many bytes arrived. To estimate how much PHP allocates, I also need to count the objects it builds from those bytes. The PHP advisory explains why the parser matters here.

\[M_{\mathrm{request}} \approx M_{\mathrm{body}} + \sum_i M_{\mathrm{keys},i} + \sum_i M_{\mathrm{buckets},i} + M_{\mathrm{metadata}}\]

This is an accounting model, not a measured exploit formula. The important inequality is that \(M_{\mathrm{request}}\) can be much larger than \(M_{\mathrm{body}}\).

Step 2: Follow the table's entry count into cleanup

In _zend_hash_str_add_or_update_i(), I followed three operations in order: increment the count, allocate the key, fill in the new entry. PHP calls that entry a bucket. If PHP runs out of memory while allocating the key, it can leave the function before it writes the rest of the bucket. Cleanup still sees the incremented count. Here's the ordering in the researchers' excerpt.

Pre-fix ordering · php-src · abbreviatedC
idx = ht->nNumUsed++;           /* bucket is now visible to teardown */
ht->nNumOfElements++;
p = ht->arData + idx;
p->key = zend_string_init(str, len, persistent); /* allocation may abort */
p->h = ZSTR_H(p->key) = h;
ZVAL_COPY_VALUE(&p->val, pData);

Say the table has three buckets. With nNumUsed = 3, cleanup can visit slots 0, 1, and 2. Once the count becomes 4, cleanup can also visit slot 3. That fourth slot is the one I want to inspect: which of its fields have been written by the time the allocation can fail?

Before OOM a HashTable has n complete buckets; after the count increments it advertises n plus one; key allocation aborts and teardown reads the unfinished bucket; safe design avoids exposing an unfinished bucket or aborts the worker without unsafe teardown
That last bucket is where the count and the actual contents disagree. Open full-size SVG.
Three-panel comic: a worker prepares a key, marks a memory drawer ready before construction finishes, then an inspector follows that premature ready signal to the unfinished drawer
The drawer is the new table entry. The “ready” label is the entry count. Cleanup follows that label and finds an unfinished drawer.

Five-minute C lab: When is a slot ready?

I wrote a two-slot table in C so I could see the count separately from the bucket. In the example, passing fail=true makes copy_key() return NULL at the same point on every run. We can compare the two orderings without exhausting the machine's memory.

half_published_bucket.c · complete, runnable teaching modelC
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char *key;
    bool ready;
} Bucket;

typedef struct {
    Bucket slots[2];
    size_t used; /* Teardown assumes every slot below used is ready. */
} Table;

static char *copy_key(const char *key, bool fail)
{
    /* Force failure at the interesting point; do not exhaust real RAM. */
    if (fail) return NULL;
    size_t bytes = strlen(key) + 1;
    char *copy = malloc(bytes);
    if (copy) memcpy(copy, key, bytes);
    return copy;
}

static int add_buggy(Table *table, const char *key, bool fail)
{
    if (table->used == 2) return -1;
    size_t index = table->used++; /* BUG: publish the slot first. */
    Bucket *bucket = &table->slots[index];
    bucket->key = copy_key(key, fail); /* Allocation may fail here. */
    if (!bucket->key) return -1;       /* used stays incremented. */
    bucket->ready = true;
    return 0;
}

static int add_fixed(Table *table, const char *key, bool fail)
{
    if (table->used == 2) return -1;
    char *owned_key = copy_key(key, fail); /* Fallible work first. */
    if (!owned_key) return -1;            /* Table still unchanged. */
    size_t index = table->used;
    table->slots[index].key = owned_key;
    table->slots[index].ready = true;
    table->used = index + 1; /* Publish only a complete bucket. */
    return 0;
}

static bool safe_to_destroy(const Table *table)
{
    /* A real destructor may trust used and inspect these fields. */
    for (size_t i = 0; i < table->used; i++) {
        if (!table->slots[i].ready) return false;
    }
    return true;
}

int main(void)
{
    Table broken = {0};
    Table fixed = {0};
    int old_result = add_buggy(&broken, "example", true);
    int new_result = add_fixed(&fixed, "example", true);
    bool old_safe = safe_to_destroy(&broken);
    bool new_safe = safe_to_destroy(&fixed);

    printf("old: result=%d used=%zu safe_to_destroy=%s\n",
           old_result, broken.used, old_safe ? "yes" : "NO");
    printf("fixed: result=%d used=%zu safe_to_destroy=%s\n",
           new_result, fixed.used, new_safe ? "yes" : "NO");

    /* Detect the violation, but never dereference the bad bucket. */
    return old_result == -1 && broken.used == 1 && !old_safe &&
           new_result == -1 && fixed.used == 0 && new_safe ? 0 : 1;
}

Build it with cc -std=c11 -Wall -Wextra -Werror -fsanitize=address,undefined -o /tmp/half_published_bucket half_published_bucket.c, then run /tmp/half_published_bucket. The expected output is:

Deterministic failure resultoutput
old: result=-1 used=1 safe_to_destroy=NO
fixed: result=-1 used=0 safe_to_destroy=yes

Start with Table broken = {0}. Both slots are empty and used is zero. In add_buggy(), the expression table->used++ does two jobs: it gives us slot zero and tells everybody that slot zero is part of the table. Only then do we call copy_key(). With fail=true, that call returns NULL. We leave immediately, never reaching ready = true. The table now claims it has one entry, but that entry is unfinished.

Notice what safe_to_destroy() does: it walks from zero to used - 1, just as cleanup code might. It finds an unready slot and says NO. We deliberately stop there rather than make the demonstration itself dereference bad memory. In add_fixed(), copy_key() runs before used changes. When it fails, the table is still empty. On success, we fill in the key and readiness flag first, then publish the new count. That is the whole ordering change in this miniature example.

MomentBuggy functionFixed function
Before allocationused becomes 1used stays 0
Allocation failsSlot 0 exists only according to the countNo slot has been published
Cleanup checks entriesFinds slot 0 unreadyHas zero entries to inspect

Try this: Before you run the program, predict what each version prints for used. Then add ++table->used; just before the if (!owned_key) return -1; line in add_fixed(), rebuild, and run again with the same simulated failure. The fixed version should now report used=1 and safe_to_destroy=NO. The program exits with status 1 because that breaks its test. Remove the extra increment to make the test pass again.

The same ordering in a C cache

A cache entry. Suppose a C cache sets ready before allocating its value. Cleanup after an allocation failure can see ready == true while value is still NULL. I would allocate into a temporary pointer, check it, assign the value, and set ready last. If other threads read the cache, this also needs proper synchronization; statement order alone is not a thread-safety mechanism.

Cache entry · another small C ordering exampleC
char *value = malloc(bytes);
if (value == NULL) return -1;

entry->value = value;
entry->ready = true;  /* Advertise it only after it exists. */

I initially wondered whether FPM changed the answer, since our sites use it. It changes one path: after a startup failure, Apache's mod_php can still run request shutdown and touch that malformed table; FPM exits the child instead. But a failure after startup can still leave state behind in a surviving FPM worker. The research and PHP advisory separate those paths. The invariantCount only committed bucketsIf cleanup walks by nNumUsed, every advertised entry must be fully initialized or cleanup must be skipped safely.

Split path: on startup failure mod_php runs request cleanup while FPM exits its worker; after successful startup a later fatal may leave an FPM worker alive with stale state
Same failure point, different startup behavior in Apache and FPM. Open full-size SVG.

Step 3: Follow a pointer from one request to the next

Draw two boxes: the request's heap and the worker's globals. The worker may serve many requests. The heap belongs to just one. If a worker global points into that heap, I look for the code that clears the pointer before releasing the heap. The second advisory describes what happens when an error skips that reset.

Lifecycle model · explanatory pseudocode, not a PHP patchtext
request A: publish pointer to A-owned memory in worker global
           fatal skips the matching reset
           free A's heap; worker continues

request B: early hook reads worker global before ordinary initialization
           pointer still names the old, freed allocation

The detail I needed for our sites was whether the worker survives the error. A worker that exits takes its globals with it. A surviving worker can take them into the next request. The Calif report separates the cases for Apache and PHP-FPM.

What changed in PHP

When I read the PHP 8.4 fix, I looked for two changes: where PHP handles an allocation failure, and where it clears request-owned pointers. The allocation advisory describes two limits. At the lower one, PHP records the error and handles it when the interpreter reaches a safe point. At the higher one, the worker exits immediately. The second advisory covers the changes to the globals.

Architecture diff · conceptual summary, not literal upstream linesdiff
- Allocation failure can jump out of native code immediately.
+ Soft OOM requests a controlled exit at a VM safe point.
+ Hard OOM exits the worker without running cleanup on partly initialized state.

- Request-owned pointers can remain in persistent globals after shutdown.
+ Shutdown and startup clear or safely initialize relevant globals.

- Parser work can expand beyond apparent input limits.
+ Multipart and input-accounting paths gain tighter bounds and tests.

In Zend/zend_alloc.c, look for the pending error flag and the request for a VM interrupt. Here are a few lines from different parts of the upstream diff. The commit also adds .phpt tests for out-of-memory handling.

Real upstream lines · selected, noncontiguousdiff
- zend_bailout();
+ EG(delayed_oom).state = ZEND_OOM_STATE_PENDING;
+ zend_atomic_bool_store_ex(&EG(vm_interrupt), true);
Three defensive lanes in PHP's patch: delay a soft out-of-memory error until a VM safe point, terminate on a hard limit, and reset request-owned globals before a worker handles another request
Three pieces working together: leave native work safely, exit when the hard limit is reached, and clear stale pointers. Open full-size SVG.

What I check on our PHP sites

We kept PHP for Antsand's generated sites. It already runs the membership flows we use: accounts, billing, and protected reading. For this issue, I wanted to update the runtime and run those flows again on the updated workers.

The Antsand Dockerfile for this rollout names php:8.4.27-fpm-bookworm. I still need to check which image the live workers are running after the restart, then run the smoke tests on the generated site.

BoundaryWhat I want to verifyWhat it does not prove
RuntimeSupported patched PHP build in every web worker; restart completed; October 23 guidance reviewed.That application authorization is correct.
Request edgeDecoded body and multipart structure limits; upload-progress policy; least-privilege worker.That limits replace the engine patch.
Generated siteSource/deployed parity; protected-route tests; purchase, refund, and entitlement checks.That an arbitrary new product policy is automatically safe.
Incident evidenceVersion inventory, logs, regression results, and rollout/rollback record.That an absence of observed attacks proves no exposure.

How the researchers used AI

The Calif report describes using an LLM to suggest places in the source to inspect. The researchers then followed those paths in C, tested the behavior, and worked with the PHP maintainers on a fix. OpenAI's account describes the collaboration. In the lab above, I used a similar starting question: after this line fails, what value does the next function see?

\[\text{hypothesis} \rightarrow \text{source path} \rightarrow \text{failure point} \rightarrow \text{reproducer} \rightarrow \text{patch invariant} \rightarrow \text{deployed evidence}\]

There is one extra step for Antsand: we generate sites. If I fix a template but forget to update an existing site, the production worker will never see my fix. I need to check the generated copy and the process serving it. Question for a code reviewWhere is the promise made?Find the line that says an entry exists or a pointer is live. What could fail immediately after that line?

My PHP rollout checklist

  1. List the PHP builds in use across generated sites, scheduled CLI jobs, FPM pools, and older containers. Record the versions reported by the running environments.
  2. Update supported branches to at least the October 21 fixed releases or verified vendor backports, then restart the workers. Review the October 23 upload-progress advisory for the additional configuration-specific issue.
  3. Keep request-size and parser limits in place. The PHP advisory explains what those settings cover.
  4. Run application tests after rollout, especially uploads, sessions, checkout, private reading, and generated-site authorization. Review logs for crashes and unusual worker restarts.
  5. Record the runtime version or image digest, the deployed revision, and the tests that passed.

A map for reading other C memory bugs

In How Pointers Work in C, I draw the pointer as one box and the object it points to as another. Keep those two boxes here and ask a few more questions: Is there an object at the other end? Is it still alive? Is the access inside its bounds? Has the part we're about to read been initialized?

Four checks on a C memory access: bounds, a non-null pointer, a live object, and initialized state
Explore the four checks in the Antsand diagram. Step through the memory blocks to see which value changes, where a pointer stops, or which slot cleanup was about to read.
  • Buffer overflow: A four-element buffer has indices 0 through 3. A write at index 4 is outside that object. A wrong loop limit, a byte count used as an element count, or a wrapped allocation size can all lead to the same bounds failure.
  • Null dereference: A failed allocation returns NULL. Check the result before using it. A non-null check only answers this one question; it doesn't tell you whether the object is still alive.
  • Use after free: Two pointers can refer to the same object. Freeing it ends its lifetime through both paths. Clearing one pointer doesn't update the other.
  • Partly initialized state: The slot can be inside the array and still be unready. Count only complete entries, or give cleanup an explicit way to recognize and handle an incomplete one.

Several different mistakes can break the same rule. Some bugs are caught by a guard or a test; others cause crashes or corrupt data. The diagram stops at the failed check so you can see exactly what the code needed to establish before using memory.

Primary reading