PHPAfterShell (CVE-2026-126714): Inside PHP’s pwrite()/ftruncate() Session File Splice and Deserialization RCE Chain

Dissecting PHPAfterShell (CVE-2026-126714, CVSS 9.2): how an in-place pwrite()/ftruncate() flaw in PHP's default file session handler (ext/session/mod_files.c) leaves residual session tails on disk that splice into arbitrary PHP Object Injection and RCE on session_start().

PHPAfterShell (CVE-2026-126714) PHP Session pwrite/ftruncate Splice to RCE Architecture
🚨
Vulnerability Intelligence: CVE ID: CVE-2026-126714 ("PHPAfterShell") & CVE-2026-129182 (CWE-367 / CWE-502 Untrusted Session Deserialization via Incomplete Truncation & CWE-416 Use-After-Free) Severity: CRITICAL (SESSION FILE SPLICE TO REMOTE CODE EXECUTION) (CVSS 9.2 Critical (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H)) Threat Actor: Discovered by Depthfirst via Frontier AI Auditing (Disclosed November 2026) Status: Patched in November 2026 PHP Security Releases; Follow-Up to PHP2Shell Trilogy Affected Systems: PHP 8.2.x < 8.2.36, 8.3.x < 8.3.37, 8.4.x < 8.4.28 & 8.5.x < 8.5.13 using default file-based sessions (session.save_handler = files) Fixed In: PHP 8.5.13, PHP 8.4.28, PHP 8.3.37, and PHP 8.2.36

Four weeks ago, we published our emergency teardown of PHP2Shell (CVE-2026-109618 & CVE-2026-109619) followed by our analysis of the unpatched RINIT vs. userland session serializer mismatch (CVE-2026-115560). In November 2026, the PHP Foundation shipped its monthly security release (8.5.13, 8.4.28, 8.3.37, and 8.2.36) to close the third and most surgical chapter of this saga: PHPAfterShell (CVE-2026-126714, CVSS 9.2), uncovered by researchers at Depthfirst using frontier AI models alongside a companion PHP 8.5 fatal-error backtrace Use-After-Free (CVE-2026-129182, CVSS 9.2). Unlike CVE-2026-115560—which required an application to call ini_set('session.serialize_handler', 'php') at runtime—PHPAfterShell strikes PHP’s default file-based session storage engine (ext/session/mod_files.c) directly. Because ps_files_write() overwrites existing sess_<id> files in place from offset 0 via pwrite() and only calls ftruncate() if pwrite() succeeds completely, any interrupted, partial, or raced session write leaves a hybrid "Frankenstein" session file on disk: a newly written short header spliced directly onto the un-truncated tail of the previous session. When session_start() reads that spliced file on the next request, the shifted byte-length prefix (s:<len>:"...") terminates early and feeds the attacker’s leftover tail straight into php_var_unserialize() as a top-level PHP object—achieving arbitrary Remote Code Execution.

PHPAfterShell (CVE-2026-126714) PHP Session pwrite/ftruncate Splice to RCE Architecture
Technical breakdown of PHPAfterShell (CVE-2026-126714): how an in-place pwrite() in ext/session/mod_files.c without prior truncation splices a new short session prefix onto an old attacker-seeded session tail, shifting ps_srlzr_decode_php() byte offsets to trigger arbitrary POP gadget deserialization on session_start().

1. The Fall 2026 PHP Session Exploitation Trilogy

To understand why PHPAfterShell (CVE-2026-126714) is such an important discovery, look at how all five Fall 2026 PHP session CVEs target adjacent layers of the exact same ext/session subsystem:

CVE Identifier Codename & Date Vulnerable Component Root Cause & Exploit Primitive Fixed In
CVE-2026-109618 PHP2Shell (Pt 1)
Oct 21, 2026
main/rfc1867.c Multipart stream & memory exhaustion during RINIT upload parsing. 8.5.12, 8.4.27, 8.3.36, 8.2.35
CVE-2026-109619 PHP2Shell (Pt 2)
Oct 21, 2026
ext/session/session.c Heap Use-After-Free (zval * dangling pointers) when fatal error handler intersects session upload progress. 8.5.12, 8.4.27, 8.3.36, 8.2.35
CVE-2026-115560 Handler Mismatch
Oct 23, 2026
ext/session/session.c RINIT writes session via php_serialize, then userland calls ini_set('session.serialize_handler', 'php'), parsing injected |O:... pipe delimiters. 8.5.13, 8.4.28, 8.3.37, 8.2.36
CVE-2026-126714 PHPAfterShell
Nov 2026 (Depthfirst)
ext/session/mod_files.c (ps_files_write) In-place pwrite() without pre-truncation leaves un-truncated old session tail on interrupted/short writes; splices shifted string lengths into |O:... deserialization on session_start(). 8.5.13, 8.4.28, 8.3.37, 8.2.36
CVE-2026-129182 Backtrace UAF
Nov 2026 (PHP 8.5)
PG(last_error_backtrace) Incomplete cleanup/repopulation of fatal error backtrace after request shutdown (residual CVE-2026-109619 variant in PHP 8.5) -> Heap UAF. 8.5.13

2. Root Cause Analysis: Inside ext/session/mod_files.c (ps_files_write)

By default, every standard PHP installation stores session data on the local filesystem (session.save_handler = files), writing one file per session ID (sess_<id>) inside /var/lib/php/sessions or /tmp. When a PHP request finishes (or when session_write_close() runs), PHP serializes the $_SESSION array into a buffer (val, of length vallen) and passes it to PS_WRITE_FUNC(files) (ps_files_write) in ext/session/mod_files.c:

/* Vulnerable logic in PHP ext/session/mod_files.c :: PS_WRITE_FUNC(files) */
PS_WRITE_FUNC(files)
{
	ps_files *data = PS_GET_MOD_DATA();
	ssize_t n = 0;

	/* ... opens/validates data->fd and stats existing file size into data->st_size ... */

	if (vallen == 0) {
		if (ftruncate(data->fd, 0) < 0) {
			return FAILURE;
		}
		return SUCCESS;
	}

	/*
	 * BUG 1: Overwrites the existing session file IN-PLACE from byte offset 0
	 * WITHOUT truncating the file first or writing to a temporary atomic file!
	 */
	n = pwrite(data->fd, val, vallen, 0);

	if (n != (ssize_t)vallen) {
		if (n == -1) {
			php_error_docref(NULL, E_WARNING, "write failed: %s (%d)", strerror(errno), errno);
		} else {
			php_error_docref(NULL, E_WARNING, "Wrote " ZEND_LONG_FMT " bytes, expected " ZEND_ULONG_FMT, (zend_long)n, (zend_ulong)vallen);
		}
		/*
		 * BUG 2: If pwrite() performs a partial/short write (0 < n < vallen)
		 * or is interrupted/aborted before ftruncate() runs, ps_files_write()
		 * returns FAILURE immediately — leaving the file in a HALF-OVERWRITTEN,
		 * UN-TRUNCATED hybrid state on disk!
		 */
		return FAILURE;
	}

	/*
	 * BUG 3: ftruncate() is only reached AFTER pwrite() succeeds completely!
	 */
	if (vallen < (size_t)data->st_size) {
		if (ftruncate(data->fd, vallen) < 0) {
			php_error_docref(NULL, E_WARNING, "truncate failed: %s (%d)", strerror(errno), errno);
			return FAILURE;
		}
	}

	return SUCCESS;
}
🔬
Why Overwriting Before Truncating Breaks Length-Prefixed Deserialization Instead of truncating the file to zero bytes first or performing an atomic write-and-rename, ps_files_write() overwrites the live file from offset 0 and only calls ftruncate() if n == vallen. If pwrite() performs a short write (due to disk quota/block boundaries, RLIMIT_FSIZE, signal interruption, or resource exhaustion) or is raced before ftruncate() runs, bytes 0..n-1 contain the new session prefix while bytes n..st_size-1 retain the old session tail!

3. The Three-Stage Exploit Path: Splicing into php_var_unserialize()

Here is how an attacker turns that spliced [New Prefix][Old Tail] session file into arbitrary PHP Object Injection and Remote Code Execution under PHP's default php serializer (ps_srlzr_decode_php):

STAGE 1: Seed the Long Session File (st_size = 320 bytes)
┌────────────────────────────────────────────────────────────────────────────┐
│ user|s:4:"anon";avatar|s:260:"AAAA...AAAA";exploit|O:18:"Monolog\Handler.."│
└──────────────────────────────────────────┬─────────────────────────────────┘
                                           │ Inside Request 1, the string
                                           │ ";exploit|O:18:..." is harmlessly
                                           │ encapsulated inside avatar's
                                           │ 260-byte string literal (s:260:)!
                                           ▼
STAGE 2: Trigger Short/Interrupted pwrite() or Prefix Shift (Without Truncate)
┌──────────────────────────────────────────┬─────────────────────────────────┐
│ user|s:14:"authenticated!";avatar|s:100:"│A";exploit|O:18:"Monolog\Handler"│
└─────────────────────┬────────────────────┴─────────────────┬───────────────┘
                      │                                      │
          New Prefix Written at Offset 0             Old Residual Tail Left
          (Note: avatar is now s:100:!)              on Disk (Un-truncated!)
                                           │
                                           ▼
STAGE 3: Next Request Calls session_start() -> ps_srlzr_decode_php()
┌────────────────────────────────────────────────────────────────────────────┐
│ 1. Parses key "user"   -> s:14:"authenticated!"                            │
│ 2. Parses key "avatar" -> reads s:100:, consumes exactly 100 bytes of "A"s │
│    and hits the closing '";' inside the OLD tail!                          │
│ 3. Next byte in stream is:  exploit|O:18:"Monolog\Handler..."              │
│ 4. ps_srlzr_decode_php() sees '|' delimiter -> calls php_var_unserialize() │
│    on O:18:"Monolog\Handler..."!                                           │
│    └─► 💥 POP GADGET CHAIN EXECUTES (__destruct / __wakeup) -> RCE!        │
└────────────────────────────────────────────────────────────────────────────┘
  1. Stage 1 (Seeding the Dormant Tail): The attacker populates a long session string (via user-controlled $_SESSION fields or PHP_SESSION_UPLOAD_PROGRESS metadata) whose trailing bytes contain ";exploit|O:32:"MonologHandlerSyslogUdpHandler":.... In Stage 1, those bytes are completely inert because they sit inside a properly length-prefixed string literal (s:260:"...").
  2. Stage 2 (Creating the Hybrid Splice): On a subsequent session update that writes a shorter string length in the header (or experiences a partial pwrite() that aborts before ftruncate()), the new header is written at offset 0 while the tail of the Stage 1 session file remains at the end of sess_<id>.
  3. Stage 3 (session_start() Deserialization to RCE): When the next request calls session_start(), ps_srlzr_decode_php() reads the shorter string length s:100:, consumes 100 bytes into the old tail, closes the string literal at ";, and immediately encounters exploit|O:32:... at the top level of the session parser—feeding the attacker's object directly into php_var_unserialize()!

4. Exploit Telemetry & Production Detection Rules (ModSecurity, YARA, auditd, Sigma & SIEM)

1. Multi-Stage Exploit Telemetry Across HTTP, PHP Logs, and Disk

Because CVE-2026-126714 is a stateful, multi-request file-splicing vulnerability inside ext/session/mod_files.c, an exploit attempt leaves correlated forensic traces across three distinct telemetry planes:

  1. Plane 1 — HTTP Request Telemetry (Splice Seeding & Concurrent PHPSESSID Racing): To survive Stage 1 inside a string literal and then awaken in Stage 3 as a top-level session variable after the byte-offset shift, the attacker seeds a string containing a closing quote-semicolon, a dummy key name, a pipe delimiter (|), and a serialized object header (";<key>|O:<len>:"<ClassName>":...), followed by high-concurrency requests sharing the exact same PHPSESSID cookie to race or interrupt ps_files_write().
  2. Plane 2 — PHP-FPM / SAPI Error Log Telemetry (ps_files_write Warnings): Whenever pwrite(data->fd, val, vallen, 0) returns a short write (0 < n < vallen) or -1 and skips ftruncate(), ext/session/mod_files.c emits deterministic E_WARNING log entries: PHP Warning: session_write_close(): Wrote <N> bytes, expected <M> or write failed: / truncate failed:.
  3. Plane 3 — Filesystem & Syscall Telemetry (/var/lib/php/sessions/sess_*): On disk, a spliced sess_<id> file contains a string variable near the start of the file whose declared byte count (s:<N>:"...) lands inside the residual tail of an older, longer session right in front of |O:<M>:"....

2. ModSecurity / Coraza WAF Rules (IDs 950024–950026, Extending php-rce-test)

# SPDX-License-Identifier: GPL-2.0-only
# Copyright (C) 2026 James Luther <[email protected]>
# ColibriSec Detection Rules for PHPAfterShell (CVE-2026-126714 & CVE-2026-115560)

# --- 950024: PHP session string-escape + pipe-delimiter splice payload -------
SecRule REQUEST_URI|REQUEST_BODY|ARGS|FILES_NAMES \
  "@rx \";[a-zA-Z0-9_\\x7f-\\xff]{1,64}\\|(?:[OC]:[0-9]+:\"|a:[0-9]+:\\{)" \
  "id:950024,phase:2,deny,status:403,log,auditlog,t:none,t:urlDecodeUni,\
msg:'PHPAfterShell (CVE-2026-126714): Session string-escape pipe deserialization splice',\
tag:'attack-deserialization',tag:'cve-2026-126714',tag:'phpaftershell'"

# --- 950025: Pipe-prefixed PHP serialized object in multipart or form data ---
SecRule REQUEST_URI|REQUEST_BODY|ARGS|FILES_NAMES \
  "@rx \\|(?:[OC]:[0-9]+:\"[a-zA-Z0-9_\\\\]+|R:[0-9]+;|r:[0-9]+;)" \
  "id:950025,phase:2,deny,status:403,log,auditlog,t:none,t:urlDecodeUni,\
msg:'PHPAfterShell (CVE-2026-126714): Pipe-delimited PHP serialized object injection',\
tag:'attack-deserialization',tag:'cve-2026-126714',tag:'phpaftershell'"

# --- 950026: Known PHP POP Gadget Chain Classes in Request Stream ------------
SecRule REQUEST_URI|REQUEST_BODY|ARGS|FILES_NAMES \
  "@rx (?:monolog\\\\handler\\\\|guzzlehttp\\\\psr7\\\\|illuminate\\\\broadcasting\\\\|symfony\\\\component\\\\|laminas\\\\|phar://)" \
  "id:950026,phase:2,deny,status:403,log,auditlog,t:none,t:urlDecodeUni,t:lowercase,\
msg:'PHPAfterShell (CVE-2026-126714): Known PHP POP gadget chain class in request',\
tag:'attack-deserialization',tag:'cve-2026-126714',tag:'phpaftershell'"

3. YARA Forensic Rule for Live Session Directories (sess_*)

rule ColibriSec_PHPAfterShell_CVE_2026_126714_Spliced_Session {
    meta:
        description = "Detects spliced or tail-seeded PHP session files (sess_*) containing embedded pipe-delimited serialized objects for CVE-2026-126714 (PHPAfterShell)"
        author = "James Luther <[email protected]>"
        cve = "CVE-2026-126714"
        date = "2026-11-19"
        severity = "critical"
    strings:
        $splice_obj  = /\";[a-zA-Z0-9_]{1,32}\|[OC]:[0-9]{1,4}:\"[a-zA-Z0-9_\\]+/
        $upload_prog = "upload_progress_" ascii
        $pipe_obj    = /\|[OC]:[0-9]{1,4}:\"[a-zA-Z0-9_\\]+\":[0-9]{1,4}:\{/
        $gadget_1    = "Monolog\\Handler\\" ascii nocase
        $gadget_2    = "GuzzleHttp\\Psr7\\" ascii nocase
        $gadget_3    = "Illuminate\\Broadcasting\\" ascii nocase
        $gadget_4    = "Symfony\\Component\\" ascii nocase
    condition:
        filesize < 10MB and (
            $splice_obj or
            ($upload_prog and $pipe_obj) or
            ($pipe_obj and any of ($gadget_*))
        )
}

4. Linux auditd Rules (/etc/audit/rules.d/61-phpaftershell.rules)

# 1. Watch PHP session storage directories for write/attribute modifications:
-w /var/lib/php/sessions -p wa -k php_session_splice
-w /var/lib/php/session  -p wa -k php_session_splice

# 2. Log failed pwrite64 / ftruncate syscalls by the web/PHP user (euid=33 / www-data):
-a always,exit -F arch=b64 -S pwrite64 -S ftruncate -F euid=33 -F success=0 -k php_pwrite_fail

# 3. Alert on any command execution (execve) spawned by the PHP worker user (euid=33):
-a always,exit -F arch=b64 -S execve -F euid=33 -k php_aftershell_rce

5. Sigma Rules for PHP Error Logs & Process Telemetry

title: PHP Session Partial pwrite() or ftruncate() Failure (CVE-2026-126714 / PHPAfterShell)
id: 5d81e2a4-3b90-51c4-8f2a-126714009201
status: experimental
description: >
  Detects PHP E_WARNING log messages generated by ps_files_write() in ext/session/mod_files.c
  when pwrite() performs a partial/short write ("Wrote N bytes, expected M") or when
  ftruncate() fails—the exact disk-splicing trigger for PHPAfterShell (CVE-2026-126714).
author: James Luther (ColibriSec)
date: 2026/11/19
logsource:
  product: php
  category: webserver
detection:
  selection_func:
    - 'session_write_close():'
    - 'Unknown:'
  selection_warning:
    - 'Wrote '
    - ' bytes, expected '
    - 'truncate failed:'
    - 'write failed:'
  condition: selection_func and selection_warning
level: critical
tags:
  - attack.t1190
  - cve.2026.126714
---
title: PHP-FPM Worker SIGSEGV or Shell Spawn (CVE-2026-126714 & CVE-2026-129182)
id: 8c47f109-6a23-5e19-9d41-129182009202
status: experimental
author: James Luther (ColibriSec)
date: 2026/11/19
logsource:
  category: process_creation
  product: linux
detection:
  selection_parent:
    ParentImage|endswith:
      - '/php-fpm'
      - '/php-fpm8.2'
      - '/php-fpm8.3'
      - '/php-fpm8.4'
      - '/php-fpm8.5'
      - '/php-cgi'
  selection_child:
    Image|endswith:
      - '/sh'
      - '/bash'
      - '/dash'
      - '/curl'
      - '/wget'
      - '/nc'
      - '/python3'
      - '/socat'
  condition: selection_parent and selection_child
level: critical
tags:
  - attack.t1190
  - attack.t1059.004
  - cve.2026.126714
  - cve.2026.129182

6. Splunk SIEM Hunting Queries

# 1. Detect ps_files_write() partial pwrite() warnings in PHP/web error logs:
index=web_errors OR index=php ("Wrote " AND " bytes, expected ") OR ("session_write_close" AND ("write failed" OR "truncate failed"))
| table _time host source _raw

# 2. Detect high-concurrency same-PHPSESSID racing (>=15 requests/2s on a single session ID):
index=web cookie="*PHPSESSID=*"
| rex field=cookie "PHPSESSID=(?<php_sess_id>[a-zA-Z0-9,-]{16,128})"
| bin _time span=2s
| stats count dc(uri) as unique_uris values(status) as statuses by clientip, php_sess_id, _time
| where count >= 15

5. Remediation & Defense-in-Depth Playbook

🔍
Detection & Incident Response Checklist: Hunt PHP Error Logs for Partial pwrite() Warnings: Search /var/log/php*-fpm.log and web server error logs for session_write_close(): Wrote <N> bytes, expected <M>, write failed:, or truncate failed:. Scan /var/lib/php/sessions/sess_* for Injected Pipe Objects: Grep active session files on disk for |[OC]:[0-9]+:" patterns. Upgrade the Host PHP Runtime: Because CVE-2026-126714 lives in ext/session/mod_files.c, updating CMS or Composer packages does not patch the bug—upgrade PHP to 8.5.13, 8.4.28, 8.3.37, or 8.2.36.
# 1. Upgrade PHP to November 2026 patched builds (8.5.13 / 8.4.28 / 8.3.37 / 8.2.36):
sudo apt-get update && sudo apt-get install --only-upgrade "php*"
sudo systemctl restart php8.4-fpm

# 2. Hunt PHP logs and session directories for PHPAfterShell exploitation artifacts:
grep -rnE "Wrote [0-9]+ bytes, expected|truncate failed:|write failed:" /var/log/php* /var/log/nginx/ /var/log/apache2/ 2>/dev/null
grep -rnE '\|[OC]:[0-9]+:"' /var/lib/php/sessions/sess_* /tmp/sess_* 2>/dev/null

# 3. Lock defense-in-depth session controls in /etc/php/8.x/fpm/pool.d/www.conf:
# php_admin_flag[session.upload_progress.enabled] = off
# php_admin_flag[session.use_strict_mode] = on
# php_admin_value[session.serialize_handler] = php_serialize

Read more