Skip to content
Vulnerabilities

Investigating PHP2Shell: reproducing the memory corruption and reading the results

Part 3 of our PHP2Shell investigation into CVE-2026-109618 and CVE-2026-109619 - the experiment across five PHP builds, the crash in a debugger, two application-level chains that an upgrade does not fix, and the counting error that halved our first result.

22 min read

Key takeaways

  • On PHP 8.4.26 our test sequence ended with the allocator reporting corruption and the worker aborting in 20 of 20 trials. On four patched builds that happened in 0 of 20.
  • Our validator first reported 10 of 20. It counted log lines through a sliding window. The raw log had the right answer, and the repository now includes a tool that recounts from it.
  • The backtrace shows where the allocator noticed the damage, while a later request was being compiled. It does not show where the damage was done.
  • Two of the three behaviors are application-level. An include sink and a session-handler mismatch gave command execution in our lab, and a PHP upgrade removes neither.
  • We did not demonstrate code execution or memory disclosure through the corruption.

Recap: the question the source could not answer

Part 1 gave us the mechanisms: a lifecycle conditional that can skip extension cleanup, a hash insertion that counts before it fills, and a bailout that can jump out in the middle of an operation. Part 2 compared PHP 8.4.26 with 8.4.27 and found several plausible defenses in the patch: a queued out-of-memory error, hash operations that report failure, a multipart parser that checks for a pending error, and a session safeguard during upload progress.

Reading established what the patch changed. It did not establish which change, if any, matters under a real trigger, or whether the vulnerable build behaves differently from the patched ones at all when you run them.

This part runs that experiment, and spends as much time on what the results do not establish as on what they do. It also includes a mistake of our own. For almost four weeks our headline number was wrong, and section 8.5 explains how.

A reminder on scope. The lab exercises target an isolated local environment only. The harness that produced these results is in the PHP2SHELL repository, in poc/. It is exploitation code. Read the repository's security notes first, and run it only against the lab in lab/, on a machine you control.

7. The research environment and methodology

7.1 Environment

Apache with mod_php, prefork, one worker. We used a single worker because the failure shows up during a later request. Keeping requests on the same worker let us study whether process state persisted between requests.

The memory limit was set below what the request body could expand to. With a large limit and a small body the OOM simply never happens, which is exactly what our first configuration did, and why nothing happened for some time.

ini
memory_limit = 16M
post_max_size = 64M
max_file_uploads = 5000
session.upload_progress.enabled = On

These are experimental conditions, not deployment advice. They are not preconditions either. The PHP advisory says the published exploit was validated with default input and memory limits and with several workers. We chose a low limit and one worker because they make the behavior easy to observe.

Each build ran in its own container, built from the official php:<version>-apache image with the same configuration. Every run recorded the PHP version, image digest, OS, the ini values above, and the raw container log. That is bookkeeping, but without it two runs that look identical may not be.

7.2 Test matrix

The five builds we tested
PHP versionClassification
8.4.26Vulnerable research build
8.4.27Patched comparison
8.2.35Patched comparison
8.3.36Patched comparison
8.5.12Patched comparison

7.3 Three outcomes, kept separate

The validation measured three different things:

  1. whether the request produced an OOM condition,
  2. whether the allocator reported an integrity failure,
  3. whether the worker aborted.

These were kept apart because they are not the same claim.

An OOM error does not imply memory corruption. A worker crash does not imply code execution.

Our first version of the test collapsed them into one "vulnerable / not vulnerable" answer. That was a mistake, and untangling it took longer than writing the original test.

7.4 One trial, and why we ran twenty

A trial is two requests, each on a new connection. Request A is a multipart body built so that parsing it exhausts the memory limit before any application code runs. Request B carries only the upload-progress field. For 8.4.26 and 8.4.27 we also asked the server, before and after each trial, which worker process was answering.

The first validation used five trials, and all five ended in the corruption signal on the vulnerable build. Five trials are a thin basis for anything, so we expanded to 20 per build.

Our validator then reported 10 of 20, and that is the figure we first published. It was wrong. The trials were fine. The counting was not.

8. Experimental results and lessons from failed tests

8.1 Twenty trials per build

Twenty trials per build, recounted from the raw server logs
PHP buildOOM observedAllocator corruption and worker abort
8.4.2620/2020/20
8.4.2720/200/20
8.2.3520/200/20
8.3.3620/200/20
8.5.1220/200/20

On the vulnerable build every trial ended the same way. Request A came back with PHP's out-of-memory error. Then the allocator printed zend_mm_heap corrupted, Apache logged that the worker had aborted, and request B failed with a dropped connection.

The four patched builds reached the same out-of-memory error in every trial, and nothing else happened. Their logs cover each container's whole life and contain no corruption message and no abort.

These figures come from recounting the raw logs, not from the validator's first summary. The logs are in evidence/, and recount.py reproduces the table from them without the lab.

8.2 What 20 of 20 does and does not mean

Twenty out of twenty is what this run observed. It is not a probability of exploitation.

The trials ran one after another against the same container. On 8.4.26 each trial killed its worker, so the next one began on a newly forked worker in much the same state as the last. That makes the trials alike, not independent. Twenty near-identical repetitions tell us the sequence is repeatable in this configuration. They tell us little about another memory limit, another server model or another request.

The result is also specific to this sequence at this size. Elsewhere in the same log are two rounds of five trials in which the outcome alternated. In one trial the follow-up request completed and the worker survived; in the next the worker aborted. Counted by trial, those rounds show an abort in 2 of 5 and in 3 of 5. The log does not record whether they used a different request size, and we do not know what decided between the two outcomes.

For readers who want an interval anyway: under an independent binomial model, 20 of 20 gives a two-sided Wilson 95% interval of 0.84 to 1.00. The model's assumption does not hold here, so read it as a summary of this run and nothing more.

8.3 What 0 of 20 means

No corruption event was observed in those 20 trials on each patched build.

It does not mean corruption is impossible on those builds.

Under an independent binomial model, zero events in 20 trials gives a one-sided 95% upper bound of about 13.9%. That is a conditional statistical bound, conditional on independence, which this experiment does not strictly satisfy. It is not a ceiling for the configuration, and it should not be quoted as one.

8.4 What the difference does and does not show

It shows a difference in observed outcomes under one trigger: one build corrupted and aborted every time, four did not, and all five reached OOM.

It does not show that the patch caused the difference. The builds differ in more than the patch. PHP 8.4.26 and 8.4.27 are 166 commits apart, and the other three are different release branches.

It does not show that a clean patched run generalizes to other configurations.

Keeping those three sentences separate from the table took us an embarrassingly long time, and they are the reason the table is worth anything.

8.5 How we miscounted, and how to count a reproducer

Counting crash lines is not counting reproductions. We got this wrong twice.

The first time was an early run with five trials and nine "abort events". That is not nine reproductions. Our counter matched two different log lines, the allocator's message and Apache's notice that a worker had exited, and a single abort writes both. The number was a count of lines.

The second time cost us our headline figure. To decide whether a trial had corrupted the heap, the validator counted matching lines in the last 400 lines of the container log, before the trial and after it, and looked for an increase.

A tail of a log is a sliding window. The container had been running for hours, and its last 400 lines already held aborts from earlier experiments. From the tenth trial on, each trial pushed at least as many old abort lines out of the window as it added. The count stopped rising, and ten trials in a row were recorded as clean.

trials 0 to 8     window count rises      recorded: corruption
trials 9 to 18    window count is flat    recorded: no corruption
trial 19          window count rises      recorded: corruption

The report said 10 of 20. The raw log that the same validator had saved said something else: an abort for every one of the 20 trials, each naming the process id of the worker that trial had started on. The report itself recorded that the process id changed in all 20. We found the mismatch on 18 November 2026, while checking the repository against Part 1, and corrected the figure the same day.

The same counter had a third fault. When it could not read the log at all, it recorded "no corruption". An unknown is not a no.

Four habits would have caught this, and the repository's tooling now follows them:

  • count over the whole log, never over a tail of it;
  • record the worker's process id before and after each trial, and check that the abort you count names that process;
  • treat "could not read the log" as unknown, never as a negative;
  • keep the raw log, and make the result recountable from it without the lab.

The unit of evidence is the trial. Report trials with corruption over trials run, and report the number of aborts separately if you want to describe severity.

The full account, with the files it affects, is in the repository's ERRATA.

8.6 Lessons from the failed configurations

Most of our early runs were meaningless, and each failure taught something.

The session directory was not what we assumed. We had hard-coded a path. When the code reported the configured path, the files were somewhere else entirely. Exercise 3 in Part 1 exists because of this.

The window was shorter than we thought. With cleanup enabled, the progress entry disappears when the upload completes. Anything that reads it afterwards sees an empty file.

Malformed requests can be silently truncated. Request-variable and upload-count limits can stop parsing partway without an obvious error.

More than one worker destroys the observation. If the next request lands on a fresh child, there is nothing to observe regardless of what the previous one did.

Minimization can destroy the experiment. When we shrank the input, the vulnerable build still crashed, but the patched build stopped reaching the precondition altogether. "No corruption on patched" had quietly become "no memory pressure on patched".

The fix was a rule: a smaller input is only an improvement if it still reproduces and the control still reaches the same precondition.

We also recorded results for sizes in between, some intermittent and some with no corruption at all. Those figures came from the same faulty counter as the 10 of 20, and we have withdrawn them. What the raw log does show is the pair of alternating rounds from section 8.2. So inputs that behave differently from the canonical one exist, but we cannot say which sizes they were, and nothing in the log supports calling any size a clean negative.

We have left the exact trigger dimensions out of this article. The lesson, that an acceptance rule matters more than a smaller number, is the part worth keeping.

9. Analyzing the crash with GDB

GDB lets us inspect a process at the moment it stops. A backtrace shows the active calls.

Our recorded trace, shortened:

zend_mm_panic("zend_mm_heap corrupted")
zend_mm_get_next_free_slot
zend_mm_alloc_small
zend_mm_alloc_heap
_emalloc
zend_string_alloc
zend_string_init
lex_scan
zendlex
zendparse
zend_compile
zend_execute_script
php_handler

Read from the bottom up:

  • php_handler: Apache is processing a PHP request.
  • zend_execute_script, zend_compile: PHP is preparing a script to run.
  • zend_string_alloc, _emalloc: PHP asks the allocator for memory.
  • zend_mm_get_next_free_slot: the allocator looks for a free slot.
  • zend_mm_panic: the allocator detects an internal inconsistency.

The allocator noticed damage while servicing an allocation.

It did not notice when the damage was done.

Two values at the stop place the crash in time. Extension startup had completed, and no session id was set. So this is a later request being compiled, not the request that ran out of memory.

The trace comes from a separate build of 8.4.26 compiled with debug symbols, with GDB attached to the single worker.

9.1 Detection site versus creation site

The detection site is where the program notices something is wrong. The creation site is where the invalid memory operation happened.

They are frequently different. Here, the corruption was detected while a later request was being compiled, and the experiment did not establish when or where it originated.

What the backtrace settles, and what it leaves open
QuestionResult
Was allocator corruption detected?Yes
Was the detection site identified?Yes
Was the original corruption site identified?No
Was the causal request conclusively established?No
Was code execution demonstrated through this corruption?No

The backtrace is evidence of an integrity failure. It is not evidence of a complete causal chain.

9.2 Debugging notes

A few things cost us hours:

  • Symbol names differ from function names. The breakpoint that silently never bound was zend_bailout; the symbol in this build is _zend_bailout. Check with nm libphp.so | grep bailout before trusting a breakpoint to bind.
  • ptrace needs permission. A container needs --cap-add=SYS_PTRACE; without it, attach fails with "Operation not permitted".
  • Attach to a worker, not the master, and keep a single prefork worker if you want to know which process served the request.
  • Do not dereference the pointer you are investigating. Printing ps_globals.id->val can fault, or return bytes from a reused allocation, and either way proves nothing about lifetime. Print the pointer value, not the pointee. We did this early on and had to discard the "evidence" it gave us.
  • Instrumentation changes behavior. A debug allocator, a sanitizer or a watchpoint all perturb timing and layout. -g -O0 without ZEND_DEBUG is a reasonable middle ground: symbols, without changing the allocator.

We are deliberately not describing how to shape the request to make the crash more reliable. That is a different kind of work from reading a backtrace correctly, and it does not belong in a study meant for learning.

10. Three behaviors: two application-level chains and one engine-level failure

The research describes three categories. We spent most of our time on the third, but the first two deserve proper explanation. They are the ones you are most likely to meet in a real application, and the ones a PHP upgrade will not fix.

10.1 Why they are different

Category C concerns memory handling inside the PHP engine. In our laboratory, PHP 8.4.26 produced allocator integrity failures under the tested conditions, and the four patched comparison builds did not.

Categories A and B are application-level problems. They use documented PHP behavior exactly as intended.

Our lab record has both working on PHP 7.4.33, 8.1.34 and 8.4.27, the last of which is a patched release. That is not evidence that 8.4.27 is vulnerable to the two CVEs. It is evidence that application-level bugs outlive engine-level fixes. We did not keep raw logs of those runs, so the repository holds none. Treat this as our record, not as published evidence.

10.2 Category A: an include sink plus session data

Two ordinary features combine:

  1. a page that includes a file named by the request, and
  2. session.upload_progress, which records upload metadata, including the client-supplied filename, in the session store.

Neither is a vulnerability alone. The include is the sink. The session store is the source of attacker-influenced bytes.

For the progress feature, PHP serializes an array containing the uploaded file's name:

upload_progress_probe|a:5:{ ... s:4:"name";s:N:"<client-supplied filename>"; ... }

If that file is later passed to include, PHP parses it as source. Any PHP inside the recorded filename executes.

The filename is not treated as data to display. It is bytes in a file, and a file passed to include is source.

Why it is a race. With cleanup enabled, the progress entry is deleted when the upload finishes. A quick POST leaves an empty session file. The entry exists only while the body is in flight.

uploader:  [=========>                  ]   body still arriving
includer:  GET ?page=...                    lookup during that window

Why patching does not help. Nothing here is a memory-safety bug. The include is the application's decision, and the filename recording is documented session behavior. The fixes are architectural: never build an include path from request input; disable upload progress where it is not needed; keep session files outside includeable paths.

Safe exercise. Build a page that includes only from an allowlist:

php
<?php
$allowed = ['about', 'help', 'terms'];

$page = $_GET['page'] ?? 'about';

if (!in_array($page, $allowed, true)) {
    http_response_code(400);
    exit("Unknown page");
}

include __DIR__ . "/pages/{$page}.php";

Create pages/about.php, pages/help.php and pages/terms.php first. Each can be a single echo. Otherwise even the allowed requests produce include warnings.

Then try ?page=../../etc/passwd and observe that it is rejected. The lesson is the sink, an include whose argument comes from the request, not a working traversal. Keep the exercise on loopback.

10.3 Category B: two serializers, one session directory

Two parts of one application share a session directory but use different serialize handlers:

apache
<Directory /app/seed>
    php_value session.serialize_handler php_serialize
</Directory>
<Directory /app/api>
    php_value session.serialize_handler php
</Directory>

This usually happens by accident: a legacy directory, a copied vhost, a framework default that differs from the application's own setting.

php_serialize stores the session as a serialized array. The php handler expects key|serialized_value. It finds the first pipe, which may be inside the value, and splits there.

A schematic illustration, not a valid payload, with the lengths abbreviated:

php_serialize stored:  a:1:{s:4:"data";s:9:"x|PAYLOAD";}
                                             ^ the pipe sits inside the value

php handler splits at the first pipe:
    name  = a:1:{s:4:"data";s:9:"x
    value = PAYLOAD";}          -> unserialize()

The second half. In our lab, on PHP 8.1.34, the value passed to unserialize() had trailing characters, so decoding failed and PHP printed "Failed to decode session object". The same response also contained output from the destructor, despite the decoding failure. That confirmed that the destructor executed during the request. We did not establish its exact timing.

We want to label that clearly. It is what we observed, in one lab, with one PHP build and a specific input. Object creation, destructor timing and decode behavior depend on the version and the input. Do not read it as a general guarantee about PHP's session implementation.

Why patching does not help. Each handler does what it documents. The fixes are configuration: one handler per session store; no shared session directory between applications; avoid destructive magic methods in request-scoped data.

Optional advanced exercise. This one needs two directories with different php_value session.serialize_handler settings, which is more setup than anything else in this series. If you want to try it: add the two <Directory> blocks shown above, send the same session cookie to both, write a plain string containing a pipe through the php_serialize side, and read it back through the php side. Print what comes back.

The interesting part is that the same bytes mean different things to the two handlers. No object, no gadget, just the confusion. If the setup is more than you want, the diagram above carries the lesson on its own.

10.4 The three behaviors side by side

The three behaviors compared
A: include + session dataB: serializer mismatchC: OOM corruption
Layerapplication + PHP featureapplication configurationPHP engine
Tested conditionsinclude sinktwo handlers, one storefinite limit, mod_php
Fixed by a PHP upgrade?nonono corruption observed in tested patched builds
Lab resultcommand execution (7.4 / 8.1 / 8.4.27)command execution (same)corruption and abort on 8.4.26, 20/20 trials
Defensive controlallowlist the includeone handler per storeupgrade + upload progress off

The middle row is the one we would read twice. For C, the honest phrasing is "no corruption was observed in the tested patched builds", not "patched builds are safe under all conditions".

11. Defensive recommendations

The primary recommendation is to run a PHP release containing the fixes. At the time of writing the advisories name 8.5.12, 8.4.27, 8.3.36 and 8.2.35. Check the current advisory before relying on those numbers, since this article will age faster than the advisory will.

For applications that do not need upload-progress reporting, turn it off. The advisory for CVE-2026-109619 suggests doing so even after patching:

ini
session.upload_progress.enabled = Off

Also:

  • never build an include path from request input; use an allowlist;
  • use one session serialize handler per session store;
  • do not share a session directory between unrelated applications;
  • apply request-size, upload and worker-resource limits as defense in depth;
  • monitor for worker crashes and allocator errors such as zend_mm_heap corrupted.

Those messages warrant investigation. They do not, on their own, establish exploitation.

11.1 A note on memory_limit

For servers that cannot be updated yet, the advisory for CVE-2026-109618 names memory_limit=-1 as the main configuration stopgap. It removes the predictable per-request limit that the published exploit relies on.

The advisory is equally clear that this is not a complete mitigation. If an underlying allocation fails, PHP can still jump out in the same way. Removing the limit also turns a bounded memory problem into an unbounded one, which makes a machine less predictable under load. Use it as a stopgap until the update, not as a fix.

A conservative post_max_size, and limits on input nesting, input variables and uploads, reduce exposure in the same way, and the advisory recommends them even after patching. Our own results (section 8.6) show that whether a given body reaches the limit depends on the build as well as on the size. Treat these as hardening.

11.2 Both layers

Patching the engine does not fix a page that includes a file from a query parameter, or two directories that disagree about a session handler.

Both layers need attention.

12. Limitations and conclusion

12.1 Limitations

  • A corrected count. Our first figure for 8.4.26 was wrong by half because of a fault in our own tooling. The corrected figure comes from recounting the saved logs. We have not rerun the experiment with the fixed validator.
  • Independence. Trials ran one after another against one container. The 20 of 20 is an observation for this run, not a probability estimate.
  • Sample size. Twenty trials separate 20 of 20 from 0 of 20 clearly. They say nothing precise about rare events on the patched builds.
  • One host, one configuration per version. Five PHP versions were compared, each under a single configuration on a single host. Allocator layout also depends on compiler, libc and build options. Our 16M limit and single worker were chosen to make the behavior easy to see. They are not preconditions: the advisory reports the published exploit working with default limits and several workers.
  • Synthetic applications. Category A's include sink and Category B's handler pair were built for the test, and we kept no raw logs of those runs.
  • Partial attribution. Detection site confirmed; creation site unknown; causal request not established.
  • No exploitation of the corruption. No memory disclosure, no control-flow hijack and no code execution was demonstrated through it.

12.2 What we learned

Reproducing an error is not the same as understanding the vulnerability. We reproduced OOM long before we had any evidence about corruption.

Check the counter before you trust the count. Our tool reported 50% for a run in which every trial aborted. The raw log had the right answer the whole time.

A backtrace is not a root cause. It tells you where the program noticed, not where the damage began.

Source analysis and runtime evidence have to support each other. A plausible explanation from the code is not automatically the explanation for an observed crash.

And one habit we would keep: write down what you did not establish. In this project that list was longer than the list of things we could prove, and it is the part we trust most.

12.3 Conclusion

PHP2Shell is an interesting case study because it brings together HTTP parsing, sessions, memory allocation, nonlocal error handling and request lifecycle management.

The most useful part of the investigation was not getting PHP to crash. It was learning to say precisely what each observation meant, correcting our own count when the raw log disagreed with it, and separating established findings from plausible mechanisms.

For anyone starting in memory-corruption research: learn how memory is allocated and released, understand pointers and data structures, get comfortable reading small sections of C, and practice reading backtraces. Those skills transfer far beyond PHP.

A crash is an observation. Understanding why it happened requires evidence.

Appendices

Glossary

Terms used in this series
TermMeaning
SAPIInterface between PHP and the web server (here mod_php, named apache2handler)
WorkerProcess handling one request at a time
Soft limitmemory_limit as configured
Hard limitDerived ceiling above the soft limit; crossing it ends the worker process
Fallible modePer-allocation flag; failure is reported instead of raised
BailoutPHP's nonlocal jump on fatal errors
BucketOne slot in a hash table
Detection siteWhere the damage is noticed
Creation siteWhere the damage was written
TrialOne run of the request sequence; the unit that results are counted in

Reading list

Four source files, and what to look for in each
FileWhat to look for
main/main.cphp_request_startup() ordering, the modules_activated conditional
Zend/zend_hash.cinsertion order, zend_array_destroy()
Zend/zend_alloc.climit checks, delayed OOM handling
ext/session/session.cupload-progress callback, session shutdown

Pitfall checklist

  • session files are not where you assume, so read session.save_path;
  • the progress entry exists only while the body is in flight;
  • request-variable and upload limits can truncate parsing silently;
  • several workers make "the next request" a different process;
  • a memory limit above the body expansion means no OOM at all;
  • count trials, not log lines, and count over the whole log, not a tail of it;
  • a minimized case whose control no longer reaches the precondition is not a smaller experiment. It is a different one.

References

Identifiers were checked on 18 November 2026. The NEWS file shipped with the 8.4.27 tag ties both advisory identifiers to both CVE numbers in one entry. The advisories were published on 21 October 2026, and that NEWS entry is dated 22 October 2026, so cite the date of the artifact you are pointing at, not a single "release date". Both advisory pages are public on php-src.

Research note: figures and source observations in this series come from our laboratory records. The artifact set should be reviewed independently before the results are treated as a verified reproduction of the published vulnerabilities.

FAQ

Questions this raises

Is PHP 8.4.27 safe from PHP2Shell?

In our lab, none of the four patched builds (8.4.27, 8.3.36, 8.2.35 and 8.5.12) showed corruption or a worker abort in 20 trials each. That means no corruption was observed under one test in one configuration. It is not proof that none is possible, so keep following the PHP advisories.

Why did your first result say 10 of 20?

Our validator counted abort lines in the last 400 lines of the container log before and after each trial. Once that window had filled with earlier abort lines, new ones pushed old ones out and the count stopped rising. The raw log shows an abort in all 20 trials. We corrected the figure on 18 November 2026 and published the recount.

Does removing the memory limit fix it?

No. For servers that cannot update yet, the PHP advisory names memory_limit=-1 as the main configuration stopgap, and says it is not a complete mitigation. An allocation can still fail, and unlimited memory makes a server less predictable under load. Updating PHP is the fix.