refactor(lab): drive docker from python so the cli works on windows and posix without bash

This commit is contained in:
ZSecurity
2026-10-24 14:07:06 +07:00
parent 8366583c43
commit 476b3d2078
8 changed files with 305 additions and 54 deletions
+25
View File
@@ -213,3 +213,28 @@ that one literal widened and nothing else changed, produced
control test's value — it separates "my rebuild is broken" from "the reference's assumption does
not hold in this environment".
## 11. Portability — never shell out to `bash` from the CLI
On Windows, `bash` is ambiguous. Python's `shutil.which("bash")` and `CreateProcess` disagree:
the former searches `PATH`, the latter searches the application directory, then the working
directory, then `System32` — so from a stock PowerShell `PATH`, `bash` resolves to
`C:\Windows\System32\bash.exe`, which is **WSL** and cannot open `C:/Users/...` paths. The failure
surfaces as `/bin/bash: C:/…/lab/up.sh: No such file or directory` for a file that plainly exists.
The same code worked from git-bash purely because git-bash's `PATH` put its own `usr/bin` first.
Rule: the CLI must not depend on a shell existing or on which one wins. `poc/lab.py` calls the
Docker CLI directly with an argument vector (no shell string, no `bash`), so the identical
`python -m poc lab` works from PowerShell, cmd, git-bash, zsh, and bash. Consequences that are
easy to get wrong:
- **Volume paths are OS-specific.** Windows needs `C:/Users/...` (forward slashes, drive letter);
POSIX needs the path unchanged. `host_path()` converts separators only — it deliberately does
not call `os.path.abspath`, because that maps `/srv/x` to `C:\srv\x` on Windows.
- **`os.path.join` is host-dependent**, so it is correct to use it with a host root and wrong to
use it with a foreign-style root in tests.
- **The container entrypoint must not contain `CRLF`.** `INIT` is passed as one argv element to
`/bin/sh -c`; a stray `\r` breaks it inside the container. There is a unit test for this.
- The `lab/*.sh` files are thin shims (`exec python -m poc …`), so there is one implementation
rather than a shell copy and a Python copy that drift apart.
+33 -8
View File
@@ -74,16 +74,34 @@ not a citation:
## Requirements
- Docker with a Linux engine, x86_64
- Python 3.11+ (tested on 3.14.7), standard library only
- bash (git-bash on Windows is fine)
- Python 3.11+ (tested on 3.14.7 on Windows, stdlib only — no third-party packages)
- No shell required: the CLI talks to the Docker CLI directly, so it behaves identically from
PowerShell, cmd, git-bash, zsh, and bash. The `lab/*.sh` files are conveniences that wrap the
same Python entry points.
## Quickstart
Windows (PowerShell) and Linux/macOS are the same commands:
```powershell
python -m poc lab # bring the target up, check it, run the chain
cat out\p1 # uid=33(www-data)
```
```bash
./lab/up.sh # php:8.4.26-apache, php.ini-production, one prefork child
python -m poc lab
cat out/p1
```
Step by step, if you want to see each stage:
```bash
./lab/up.sh # or: python -m poc lab --up-only
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
cat out/p1 # uid=33(www-data)
python -m poc status # container diagnostics
python -m poc lab --down # or: ./lab/down.sh
```
One command does the whole flow:
@@ -96,8 +114,9 @@ python -m poc lab # brings the container up, checks it, runs the chai
| Command | Purpose |
|---|---|
| `poc lab` | `lab/up.sh`, then `check`, then `exploit` |
| `poc lab` | bring the target up, then `check`, then `exploit`. `--up-only` stops after the check; `--down` removes the container; `--image` / `--net` override the target |
| `poc check` | preflight: php version + vulnerable/patched verdict, nine ini values, `libphp.so` sha256 → profile, worker count. Exit 1 when the target is patched or the build is unknown. Sends no exploit traffic. |
| `poc status` | container diagnostics: php/apache version, the nine ini values, libphp sha256, worker count |
| `poc offsets --lib PATH` | derive `zval_ptr_dtor`, `zif_system`, `zif_passthru` from an ELF `.symtab`/`.dynsym` |
| `poc leak` | A1 + B1 only: produce and classify the disclosure cookie (`--save` keeps the raw response) |
| `poc exploit` | full chain; `--dry-run` forges and hashes all four bodies without touching the network; `--retries N`; `--cmd`; `--proof` |
@@ -106,6 +125,11 @@ python -m poc lab # brings the container up, checks it, runs the chai
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.
## Status — what was verified, and how
Every row below is a command that was actually run in this environment, with its own artifact.
@@ -114,11 +138,12 @@ 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 .` | 32 tests, all pass, 0 skipped |
| Offline suite | `python -m unittest discover -s tests -t .` | 45 tests, all pass, 0 skipped |
| Body parity | `tests/test_bodies_parity.py` | A1/A2/B1 SHA-256 identical to the reference generators (`8e8fc166…`, `7af66c8f…`, `b6c547e0…`) |
| Stage 1–2 (disclosure) | `python -m poc leak` | A1 → 500; B1 → 200 with an 819 208-byte decoded cookie; `zval_ptr_dtor` ×1095; `libphp − main` in range; main-chunk fingerprint count 87 |
| Stage 3–4 (RCE) | `python -m poc exploit` | `[4/4] … RCE OK`, `out/p1` contains `uid=33(www-data) gid=33(www-data) groups=33(www-data)`; exit 0 |
| Reproducibility | 3 fresh containers, one run each | 3/3 `uid=33(www-data)` |
| Windows shell independence | `python -m poc lab` 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 | `IMAGE=php:8.4.27-apache …` then `poc check` / `poc exploit` | `check` → `8.4.27 patched`, `NOT READY`, exit 1; `exploit` → A1 returns 200 (no OOM abort), B1 yields no pointers, exit 1, and **no proof file is created** |
| Reference control | unchanged reference chain against this lab | same proof — confirms the lab build is the one the published offsets describe |
@@ -167,8 +192,8 @@ target's `libphp.so` SHA-256.
## Repository layout
```
lab/ docker target (php.ini-production copied in place, one-worker MPM override)
poc/ profiles · elf · wire · bodies · forge · leak · cli
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
```
+7 -2
View File
@@ -1,4 +1,9 @@
#!/usr/bin/env bash
set -eu
docker rm -f "${NAME:-p2s-lab}" >/dev/null 2>&1 || true
echo "down"
HERE=$(cd "$(dirname "$0")" && pwd)
cd "$HERE/.."
PY=${PYTHON:-}
if [ -z "$PY" ]; then
if command -v python >/dev/null 2>&1; then PY=python; else PY=python3; fi
fi
exec "$PY" -m poc lab --down "$@"
+7 -7
View File
@@ -1,9 +1,9 @@
#!/usr/bin/env bash
set -eu
NAME=${NAME:-p2s-lab}
docker exec "$NAME" php -v | head -1
docker exec "$NAME" php -i 2>/dev/null | grep -E '^(display_errors|memory_limit|post_max_size|output_buffering|max_file_uploads|max_input_vars|session.upload_progress.enabled|session.save_handler|session.serialize_handler)'
docker exec "$NAME" sha256sum /usr/lib/apache2/modules/libphp.so
docker exec "$NAME" apache2 -v | head -1
docker exec "$NAME" sh -c "grep -v '^#' /etc/apache2/conf-enabled/zz-p2s.conf | grep -v '^$'"
docker exec "$NAME" sh -c 'pgrep -c apache2'
HERE=$(cd "$(dirname "$0")" && pwd)
cd "$HERE/.."
PY=${PYTHON:-}
if [ -z "$PY" ]; then
if command -v python >/dev/null 2>&1; then PY=python; else PY=python3; fi
fi
exec "$PY" -m poc status "$@"
+6 -31
View File
@@ -1,34 +1,9 @@
#!/usr/bin/env bash
set -eu
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -W)
ROOT=$(cd "$HERE/.." && pwd -W)
IMAGE=${IMAGE:-php:8.4.26-apache}
NAME=${NAME:-p2s-lab}
PORT=${PORT:-18110}
NET=${NET:-}
docker rm -f "$NAME" >/dev/null 2>&1 || true
mkdir -p "$ROOT/out"
NETARG=""
if [ -n "$NET" ]; then
docker network create "$NET" >/dev/null 2>&1 || true
NETARG="--network $NET"
HERE=$(cd "$(dirname "$0")" && pwd)
cd "$HERE/.."
PY=${PYTHON:-}
if [ -z "$PY" ]; then
if command -v python >/dev/null 2>&1; then PY=python; else PY=python3; fi
fi
docker run -d --name "$NAME" $NETARG \
-p "127.0.0.1:$PORT:80" \
-v "$HERE/index.php:/var/www/html/index.php:ro" \
-v "$HERE/apache-single-worker.conf:/etc/apache2/conf-enabled/zz-p2s.conf:ro" \
-v "$ROOT/out:/out" \
"$IMAGE" /bin/sh -c 'cp /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini
chown -R www-data:www-data /out 2>/dev/null || true
exec apache2-foreground' >/dev/null
for _ in $(seq 1 60); do
if curl -s -m 2 "http://127.0.0.1:$PORT/index.php" >/dev/null 2>&1; then
break
fi
sleep 0.5
done
echo "target: $(curl -s -m 3 "http://127.0.0.1:$PORT/index.php")"
exec "$PY" -m poc lab --up-only "$@"
+41 -6
View File
@@ -2,12 +2,11 @@ import argparse
import hashlib
import json
import os
import shutil
import subprocess
import sys
import time
from poc import bodies, elf, forge, leak, profiles, wire
from poc import bodies, elf, forge, lab, leak, profiles, wire
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -247,19 +246,46 @@ def cmd_exploit(args):
def cmd_lab(args):
up = os.path.join(ROOT, "lab", "up.sh").replace("\\", "/")
shell = shutil.which("bash") or "/bin/bash"
r = subprocess.run([shell, up])
if r.returncode != 0:
image = args.image or os.environ.get("IMAGE") or "php:8.4.26-apache"
name = args.name or os.environ.get("NAME") or "p2s-lab"
port = args.port or int(os.environ.get("PORT") or 18110)
net = args.net or os.environ.get("NET") or ""
try:
if args.down:
lab.down(name)
print("down")
return 0
body = lab.up(ROOT, image, name, port, net, args.host)
print("target: %s" % body)
except lab.LabError as exc:
print(str(exc), file=sys.stderr)
print("lab up failed", file=sys.stderr)
return 1
args.name = name
args.port = port
code = cmd_check(args)
if code != 0:
print("target not ready", file=sys.stderr)
return code
if getattr(args, "up_only", False):
return 0
return cmd_exploit(args)
def cmd_status(args):
try:
rows = lab.status(ROOT, args.name, args.lib_path)
except lab.LabError as exc:
print(str(exc), file=sys.stderr)
return 1
if args.json:
print(json.dumps(dict(rows), indent=2))
else:
for key, val in rows:
print("%-40s %s" % (key, val))
return 0
def cmd_offsets(args):
syms = elf.symbol_offsets(args.lib, ["zval_ptr_dtor", "zif_system", "zif_passthru"])
if args.json:
@@ -323,12 +349,21 @@ def build_parser():
p = sub.add_parser("lab")
common(p)
p.set_defaults(name=None, port=None)
p.add_argument("--image", default="")
p.add_argument("--net", default="")
p.add_argument("--up-only", action="store_true")
p.add_argument("--down", action="store_true")
p.add_argument("--cmd", default="id>/out/p1")
p.add_argument("--proof", default=os.path.join(ROOT, "out", "p1"))
p.add_argument("--dry-run", action="store_true")
p.add_argument("--retries", type=int, default=3)
p.set_defaults(func=cmd_lab)
p = sub.add_parser("status")
common(p)
p.set_defaults(func=cmd_status)
p = sub.add_parser("offsets")
p.add_argument("--lib", required=True)
p.add_argument("--json", action="store_true")
+116
View File
@@ -0,0 +1,116 @@
import os
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.request
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")
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(root, name):
exe = docker()
cmd = [exe, "exec", name] + root
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
return proc.stdout
def wait_ready(port, host="127.0.0.1", attempts=60, delay=0.5):
url = "http://%s:%d/index.php" % (host, port)
for _ in range(attempts):
try:
with urllib.request.urlopen(url, timeout=2) as resp:
body = resp.read().decode("latin1").strip()
return body
except (urllib.error.URLError, OSError):
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 become ready on port %d\n%s" % (port, logs.stdout + logs.stderr))
return body
def down(name):
run(["rm", "-f", name], check=False)
return True
def status(root, name, lib_path):
rows = []
ver = executable(["php", "-v"], name).splitlines()
rows.append(("php", ver[0] if ver else "?"))
info = executable(["php", "-i"], name)
keep = {"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"}
for line in info.splitlines():
key, _, val = line.partition("=>")
key = key.strip()
if key in keep:
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 "?"))
workers = executable(["sh", "-c", "pgrep -c apache2"], name).strip()
rows.append(("workers", workers))
return rows
+70
View File
@@ -0,0 +1,70 @@
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.assertEqual("\\" in got, not NT)
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_no_backslashes_in_volumes_on_windows(self):
vols = [self.args[i + 1] for i, a in enumerate(self.args) if a == "-v"]
for vol in vols:
self.assertEqual("\\" in vol, not NT)
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)