Repository navigation
Expand file tree
/
Copy pathphp2shell_scan.py
More file actions
1669 lines (1505 loc) · 67.9 KB
/
Copy pathphp2shell_scan.py
File metadata and controls
1669 lines (1505 loc) · 67.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
php2shell_scan.py — Non-destructive scanner (with opt-in probe) for
CVE-2026-109618 (RCE via OOM corruption — longjmp on OOM leaves invalid
request memory at shutdown) and CVE-2026-109619 (RCE via stale global
state — global state from a previous request reused by a persistent
worker). Core PHP bugs, fixed in 8.2.35 / 8.3.36 / 8.4.27 / 8.5.12.
Official advisories (published 2026-10-21, Critical, by bukka):
CVE-2026-109618 — GHSA-w8hw-w9fx-j79w
https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w
CVE-2026-109619 — GHSA-6wmf-4rv5-p3rp
https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp
Fixed-version table below matches the advisories exactly (verified 2026-10-21).
Strategies:
1. LOCAL : php -v / php -i (max precision — exact runtime version).
2. REMOTE : version fingerprint via headers (X-Powered-By, Server) and
exposed phpinfo() files (phpinfo.php, info.php, ...).
3. PRESENCE : PHP detection without version (PHPSESSID, .php, redirects).
4. BANNER : robust banner grabbing — raw socket HEAD/GET/OPTIONS across
http/https, all header variants, error-page disclosure.
5. RECON : subdomain enumeration via crt.sh (Certificate Transparency),
with ProjectDiscovery subfinder as fallback/merge source,
then fan-out scan each resolved host.
6. PROBE : (--probe) large multipart requests to observe worker
instability. Low-confidence heuristic; MAY cause DoS in
production. Authorized use only.
Usage:
python3 php2shell_scan.py --local
python3 php2shell_scan.py https://example.com --phpinfo-paths
python3 php2shell_scan.py example.com --recon --threads 10 -o out.json
python3 php2shell_scan.py -f targets.txt --banner
python3 php2shell_scan.py example.com --deep-version --origin-scan
python3 php2shell_scan.py https://example.com --probe --probe-count 5
Authorization: run only against assets you own or are explicitly
permitted to test.
"""
import argparse
import base64
import concurrent.futures
import ipaddress
import json
import os
import re
import shutil
import socket
import ssl
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass, field, asdict
# ---------------------------------------------------------------------------
# Vulnerability data (GHSA-w8hw-w9fx-j79w / GHSA-6wmf-4rv5-p3rp, 2026-10-21)
# ---------------------------------------------------------------------------
CVES = {
"CVE-2026-109618": "RCE via OOM corruption (longjmp on OOM leaves invalid request memory at shutdown)",
"CVE-2026-109619": "RCE via stale global state (prior-request global state reused by a persistent worker)",
}
# Official advisory references (verified against php-src 2026-10-21)
ADVISORIES = {
"CVE-2026-109618": "GHSA-w8hw-w9fx-j79w",
"CVE-2026-109619": "GHSA-6wmf-4rv5-p3rp",
}
# Minimum FIXED version per branch (matches both advisories exactly)
FIXED = {
(8, 2): (8, 2, 35),
(8, 3): (8, 3, 36),
(8, 4): (8, 4, 27),
(8, 5): (8, 5, 12),
}
SUPPORTED_BRANCHES = sorted(FIXED) # 8.2..8.5
EOL_CEILING = (8, 2, 0) # < 8.2 => EOL, no official patch
FIRST_REPORTED = (5, 4, 0) # reports: PHP >= 5.4 affected
UA = "php2shell-scan/2.0 (authorized-security-assessment)"
print_lock = threading.Lock()
def say(msg):
with print_lock:
print(msg, flush=True)
# ---------------------------------------------------------------------------
# Version comparison
# ---------------------------------------------------------------------------
def parse_version(s):
"""'8.3.14' -> (8,3,14). '8.1' -> (8,1,0). None if non-numeric."""
if not s:
return None
m = re.match(r"(\d+)\.(\d+)(?:\.(\d+))?", s.strip())
if not m:
return None
return (int(m.group(1)), int(m.group(2)), int(m.group(3) or 0))
def version_tuple(vstr):
return parse_version(vstr)
def classify(version):
"""
Return a dict with a per-CVE verdict for a PHP version.
verdicts: VULNERABLE / PATCHED / VULNERABLE_EOL / UNKNOWN
"""
out = {
"version": version,
"status": None,
"detail": "",
"cves": {},
}
if version is None:
out["status"] = "UNKNOWN"
out["detail"] = "PHP detected, version not disclosed"
for c in CVES:
out["cves"][c] = "SUSPECTED (no version)"
return out
t = version_tuple(version)
if t is None:
out["status"] = "UNKNOWN"
for c in CVES:
out["cves"][c] = "UNKNOWN"
return out
major, minor, patch = t
branch = (major, minor)
if major < 8 or (major == 8 and minor < 2):
out["status"] = "VULNERABLE_EOL"
out["detail"] = (
"PHP %s is EOL (< 8.2) — no official PHP Group patch; "
"check distro/OSV backport" % version
)
for c in CVES:
out["cves"][c] = "VULNERABLE (EOL, no upstream fix)"
return out
if branch in FIXED:
fixed = FIXED[branch]
if t < fixed:
out["status"] = "VULNERABLE"
out["detail"] = "PHP %s < fixed %s" % (version, ".".join(map(str, fixed)))
for c in CVES:
out["cves"][c] = "VULNERABLE"
else:
out["status"] = "PATCHED"
out["detail"] = "PHP %s >= fixed %s" % (version, ".".join(map(str, fixed)))
for c in CVES:
out["cves"][c] = "PATCHED"
return out
if branch > SUPPORTED_BRANCHES[-1]:
out["status"] = "UNKNOWN"
out["detail"] = "Branch %d.%d above advisory range — check vendor changelog" % (major, minor)
for c in CVES:
out["cves"][c] = "UNKNOWN"
return out
# 8.6+ handled above; 5.x/7.x handled above. Extra safety:
out["status"] = "UNKNOWN"
for c in CVES:
out["cves"][c] = "UNKNOWN"
return out
# ---------------------------------------------------------------------------
# HTTP helpers (stdlib only)
# ---------------------------------------------------------------------------
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *a, **k):
return None
def make_opener(insecure=False):
ctx = ssl.create_default_context()
if insecure:
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
opener = urllib.request.build_opener(
urllib.request.HTTPSHandler(context=ctx),
urllib.request.HTTPCookieProcessor(),
)
return opener
def http_get(opener, url, timeout=10, max_bytes=200_000, method="GET"):
req = urllib.request.Request(url, headers={
"User-Agent": UA,
"Accept": "text/html,application/xhtml+xml,*/*;q=0.8",
"Connection": "close",
}, method=method)
try:
resp = opener.open(req, timeout=timeout)
body = resp.read(max_bytes)
headers = dict(resp.headers.items())
return {"status": resp.status, "headers": headers, "body": body.decode("utf-8", "replace"), "url": resp.geturl()}
except urllib.error.HTTPError as e:
body = b""
try:
body = e.read(20_000)
except Exception:
pass
return {"status": e.code, "headers": dict(e.headers.items()) if e.headers else {}, "body": body.decode("utf-8", "replace"), "url": url}
except Exception as e:
return {"status": None, "error": str(e), "url": url}
# ---------------------------------------------------------------------------
# Remote version fingerprint
# ---------------------------------------------------------------------------
VER_PATTERNS = [
# X-Powered-By: PHP/8.3.14
re.compile(r"PHP[/ ](\d+\.\d+(?:\.\d+)?)", re.I),
# Server: Apache/2.4.58 (Unix) PHP/8.2.20
re.compile(r"PHP/(\d+\.\d+(?:\.\d+)?)", re.I),
]
PHPINFO_PATTERNS = [
re.compile(r"PHP Version\s*</?b?[^>]*>?\s*([578]\.\d+\.\d+)"),
re.compile(r"php-version[^0-9]*([578]\.\d+\.\d+)", re.I),
re.compile(r"PHP Version ([578]\.\d+\.\d+)"),
]
DEFAULT_PHPINFO_PATHS = [
"/phpinfo.php", "/phpinfo().php", "/info.php", "/php_info.php",
"/test.php", "/p.php", "/pi.php", "/phpversion.php", "/version.php",
"/server-info.php", "/phpinfo.txt",
]
def fingerprint_headers(res):
"""Return (version, source) from a response's headers."""
for h in ("x-powered-by", "server", "x-php-version"):
val = None
for k, v in res.get("headers", {}).items():
if k.lower() == h:
val = v
break
if not val:
continue
for pat in VER_PATTERNS:
m = pat.search(val)
if m:
return m.group(1), "header:%s" % h
return None, None
def fingerprint_phpinfo(opener, base, paths):
"""Look for exposed phpinfo(); return (version, path, body) or (None, None, None)."""
for p in paths:
url = urllib.parse.urljoin(base + "/", p.lstrip("/"))
res = http_get(opener, url)
if res.get("status") == 200 and res.get("body"):
body = res["body"]
if "phpinfo()" in body or "PHP Version" in body or "php-core" in body:
for pat in PHPINFO_PATTERNS:
m = pat.search(body)
if m:
return m.group(1), p, body
return None, None, None
# ---------------------------------------------------------------------------
# Passive enrichment — extra signals to judge exposure WITHOUT exploitation
# ---------------------------------------------------------------------------
# Persistent-worker SAPIs reuse request state across requests => directly
# relevant to CVE-2026-109619 (stale global state). Per-request SAPIs (plain
# CGI) spin a fresh process per request and are far less exposed to it.
PERSISTENT_SAPIS = ("fpm", "fpm-fcgi", "apache2handler", "mod_php", "litespeed", "phpdbg", "cli-server")
PERREQUEST_SAPIS = ("cgi", "cgi-fcgi")
PROXY_MARKERS = [
("Cloudflare", ("server:cloudflare", "cf-ray", "cf-cache-status")),
("Akamai", ("server:akamaighost", "x-akamai", "akamai")),
("AWS CloudFront", ("x-amz-cf-id", "via:cloudfront", "server:cloudfront")),
("Fastly", ("x-served-by", "x-fastly", "fastly")),
("Sucuri WAF", ("x-sucuri-id", "server:sucuri")),
("Imperva/Incapsula", ("x-iinfo", "incap_ses", "visid_incap")),
("Varnish", ("x-varnish", "via:varnish")),
("nginx proxy", ("via:nginx",)),
]
# Distro build suffixes: version looks upstream-vulnerable but the distro may
# have backported the fix without bumping the upstream number => reduce
# confidence, do not report a hard VULNERABLE from version alone.
DISTRO_RX = re.compile(r"(ubuntu|debian|deb\d|\+deb|\.el\d|~dfsg|\.fc\d|suse|amzn|alpine)", re.I)
def _header(hdrs_lower, name):
return hdrs_lower.get(name.lower(), "")
def detect_sapi(hdrs_lower, phpinfo=None):
"""
Infer the PHP SAPI / worker model from headers and phpinfo.
Returns (sapi_label, persistent: bool|None). Passive only.
"""
if phpinfo and phpinfo.get("sapi"):
s = phpinfo["sapi"].lower()
if any(k in s for k in PERSISTENT_SAPIS):
return phpinfo["sapi"], True
if any(k in s for k in PERREQUEST_SAPIS):
return phpinfo["sapi"], False
return phpinfo["sapi"], None
xpb = _header(hdrs_lower, "x-powered-by").lower()
server = _header(hdrs_lower, "server").lower()
if "php-fpm" in xpb or "fpm" in xpb:
return "fpm", True
if "mod_php" in server or ("apache" in server and "php/" in server):
return "apache2handler (mod_php)", True
if "litespeed" in server:
return "litespeed", True
if "php-cgi" in xpb or "cgi" in xpb:
return "cgi", False
# nginx + PHP almost always means php-fpm in practice
if "nginx" in server:
return "fpm (inferred: nginx)", True
return None, None
def detect_proxy(hdrs_lower):
"""Identify a CDN/WAF/proxy in front; its banner may not be the origin's."""
blob = " ".join("%s:%s" % (k, v) for k, v in hdrs_lower.items()).lower()
hits = []
for name, markers in PROXY_MARKERS:
for mk in markers:
if mk in blob:
hits.append(name)
break
return ", ".join(dict.fromkeys(hits)) or None
def parse_phpinfo_deep(body):
"""
Extract non-exploit config fields from an exposed phpinfo() page. These
refine exposure: memory_limit/post_max_size/max_input_vars size the OOM
attack surface (CVE-2026-109618); Server API gives the real SAPI;
disable_functions is a mitigation signal.
"""
out = {}
def grab(label, rx):
m = re.search(rx, body, re.I)
if m:
out[label] = m.group(1).strip()
grab("sapi", r"Server API\s*</td>\s*<td[^>]*>\s*([^<]+)")
grab("build_date", r"Build Date\s*</td>\s*<td[^>]*>\s*([^<]+)")
grab("zend", r"Zend Engine\s*v?([\d.]+)")
grab("memory_limit", r"memory_limit\s*</td>\s*<td[^>]*>\s*([^<]+)")
grab("post_max_size", r"post_max_size\s*</td>\s*<td[^>]*>\s*([^<]+)")
grab("max_input_vars", r"max_input_vars\s*</td>\s*<td[^>]*>\s*([^<]+)")
grab("disable_functions", r"disable_functions\s*</td>\s*<td[^>]*>\s*([^<]+)")
# plain-text phpinfo (CLI) fallbacks
if "sapi" not in out:
grab("sapi", r"Server API\s*=>\s*(.+)")
if "build_date" not in out:
grab("build_date", r"Build Date\s*=>\s*(.+)")
return out
def assess_confidence(r):
"""
Grade how trustworthy the version-based verdict is, and attach caveats.
Pure reasoning over already-collected passive signals — no new requests.
"""
notes = []
conf = "LOW"
src = r.version_source or ""
if r.version:
if src.startswith("phpinfo"):
conf = "HIGH"
notes.append("version from exposed phpinfo() (authoritative)")
elif "errorpage" in src:
conf = "HIGH"
notes.append("version from PHP error page (authoritative)")
elif src.startswith("origin:"):
conf = "HIGH"
notes.append("version read directly from the origin (CDN/WAF bypassed)")
elif src.startswith(("header:", "banner:")):
conf = "MEDIUM"
notes.append("version from HTTP banner (expose_php=On)")
elif src.startswith(("shodan:", "censys:")):
conf = "MEDIUM"
notes.append("version from %s scan data (intel — may be stale, re-verify live)" % src.split(":")[0])
elif src.startswith("egg:"):
conf = "MEDIUM"
notes.append("version from PHP easter-egg credits page")
else:
notes.append("no version disclosed — verdict is inference-only")
# distro backport caveat (big false-positive source)
if r.distro_build:
notes.append("distro-packaged build (%s): fix may be BACKPORTED without a version bump — verify the package changelog, not just the number" % r.distro_build)
if conf == "HIGH":
conf = "MEDIUM"
elif conf == "MEDIUM":
conf = "LOW"
# proxy/CDN caveat (banner may be the edge, not the origin)
if r.proxy:
notes.append("%s in front: banner may reflect the proxy, not the PHP origin" % r.proxy)
if r.version and src.startswith(("header:", "banner:")) and conf != "LOW":
conf = "LOW"
# SAPI relevance to CVE-2026-109619
if r.worker_persistent is True:
notes.append("persistent worker (%s): exposed to CVE-2026-109619 stale-state reuse" % (r.sapi or "?"))
elif r.worker_persistent is False:
notes.append("per-request SAPI (%s): reduced exposure to CVE-2026-109619" % (r.sapi or "cgi"))
# OOM surface from phpinfo (CVE-2026-109618)
pi = r.phpinfo or {}
if pi.get("post_max_size") or pi.get("max_input_vars"):
notes.append("OOM surface: post_max_size=%s max_input_vars=%s memory_limit=%s" % (
pi.get("post_max_size", "?"), pi.get("max_input_vars", "?"), pi.get("memory_limit", "?")))
if pi.get("disable_functions") and pi["disable_functions"] not in ("no value", "", "none"):
notes.append("disable_functions set (post-exploit mitigation present)")
r.confidence = conf
r.notes = notes
return r
def detect_php_presence(opener, base):
"""Heuristics for PHP presence without version disclosure."""
signals = []
res = http_get(opener, base + "/")
if res.get("status") is None:
return signals, res
hdrs = {k.lower(): v for k, v in res.get("headers", {}).items()}
cookie = hdrs.get("set-cookie", "")
if "PHPSESSID" in cookie:
signals.append("cookie:PHPSESSID")
if "x-powered-by" in hdrs and "php" in hdrs["x-powered-by"].lower():
signals.append("header:X-Powered-By")
body = res.get("body", "")
if ".php" in body:
signals.append("body:.php refs")
# redirect to index.php is a classic PHP-app tell
loc = hdrs.get("location", "")
if loc.endswith(".php"):
signals.append("redirect:%s" % loc)
# 404 page of WordPress/Drupal etc.
if "wp-content" in body:
signals.append("body:wp-content")
return signals, res
# ---------------------------------------------------------------------------
# Robust PHP banner grabbing
# ---------------------------------------------------------------------------
# Headers that may carry a PHP version string.
PHP_HINT_HEADERS = (
"server", "x-powered-by", "x-php-version",
"x-generator", "x-drupal-cache", "x-redirect-by",
)
# Only these headers count as a "PHP present" signal when they mention php
# (avoids false positives from a 'php' substring inside a URL, e.g. Link).
PHP_SIGNAL_HEADERS = ("server", "x-powered-by", "x-php-version")
# Error strings PHP/SAPI stacks tend to emit on malformed input.
PHP_ERROR_MARKERS = [
re.compile(r"\bPHP (?:Notice|Warning|Fatal error|Parse error|Deprecated)\b", re.I),
re.compile(r"Call Stack", re.I),
re.compile(r"on line \d+", re.I),
re.compile(r"Xdebug", re.I),
re.compile(r"\.php on line", re.I),
]
def _raw_http(host, port, use_tls, request_line, extra_headers, insecure, timeout=8, read_bytes=65536):
"""
Single raw-socket HTTP exchange. Returns (status_line, headers_dict,
body_text, error). Keeps the full raw header block so odd casing /
duplicate headers survive (urllib folds those).
"""
raw_headers = {}
sock = None
try:
sock = socket.create_connection((host, port), timeout=timeout)
if use_tls:
ctx = ssl.create_default_context()
if insecure:
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
sock = ctx.wrap_socket(sock, server_hostname=host)
hdr_lines = ["%s HTTP/1.1" % request_line,
"Host: %s" % host,
"User-Agent: %s" % UA,
"Accept: */*",
"Connection: close"]
hdr_lines += list(extra_headers)
payload = ("\r\n".join(hdr_lines) + "\r\n\r\n").encode()
sock.sendall(payload)
chunks = []
got = 0
while got < read_bytes:
data = sock.recv(8192)
if not data:
break
chunks.append(data)
got += len(data)
raw = b"".join(chunks)
except Exception as e:
return None, {}, "", str(e)
finally:
try:
if sock:
sock.close()
except Exception:
pass
text = raw.decode("iso-8859-1", "replace")
head, _, body = text.partition("\r\n\r\n")
lines = head.split("\r\n")
status_line = lines[0] if lines else ""
for line in lines[1:]:
if ":" in line:
k, _, v = line.partition(":")
k = k.strip().lower()
v = v.strip()
# keep multiple Set-Cookie etc.
if k in raw_headers:
raw_headers[k] += "; " + v
else:
raw_headers[k] = v
return status_line, raw_headers, body, None
def banner_grab(host, insecure=False, timeout=8):
"""
Robust multi-probe banner grab. Tries https:443 and http:80, with
HEAD / GET / OPTIONS and a deliberately malformed request, to surface:
- Server / X-Powered-By version banners (even when urllib hides them),
- PHPSESSID and other PHP-tell headers,
- PHP error disclosure on malformed input.
Returns a dict: {version, version_source, php_signals, probes:[...]}.
Non-destructive: tiny requests only.
"""
result = {"version": None, "version_source": None, "php_signals": [], "probes": []}
schemes = [("https", 443, True), ("http", 80, False)]
# request_line, extra_headers, label
probes = [
("HEAD / HTTP/1.1".replace(" HTTP/1.1", ""), [], "HEAD /"),
("GET / HTTP/1.1".replace(" HTTP/1.1", ""), [], "GET /"),
("OPTIONS / HTTP/1.1".replace(" HTTP/1.1", ""), [], "OPTIONS /"),
# malformed path to coax an error page from the SAPI
("GET /%ff%fe/..%00.php HTTP/1.1".replace(" HTTP/1.1", ""),
["X-Probe: malformed"], "GET malformed"),
]
for scheme, port, use_tls in schemes:
reachable = False
for request_line, extra, label in probes:
status, hdrs, body, err = _raw_http(
host, port, use_tls, request_line, extra, insecure, timeout=timeout)
probe_rec = {"scheme": scheme, "probe": label, "status": None, "error": err}
if err:
result["probes"].append(probe_rec)
continue
reachable = True
probe_rec["status"] = status
# header-based version
for h in PHP_HINT_HEADERS:
if h in hdrs:
val = hdrs[h]
for pat in VER_PATTERNS:
m = pat.search(val)
if m and not result["version"]:
result["version"] = m.group(1)
result["version_source"] = "banner:%s:%s" % (scheme, h)
if h in PHP_SIGNAL_HEADERS and "php" in val.lower():
sig = "header:%s=%s" % (h, val[:80])
if sig not in result["php_signals"]:
result["php_signals"].append(sig)
if "set-cookie" in hdrs and "PHPSESSID" in hdrs["set-cookie"]:
if "cookie:PHPSESSID" not in result["php_signals"]:
result["php_signals"].append("cookie:PHPSESSID")
# error-page disclosure
if body:
for pat in PHP_ERROR_MARKERS:
m = pat.search(body)
if m:
snip = "error:%s" % m.group(0)
if snip not in result["php_signals"]:
result["php_signals"].append(snip)
# grab a version from the error page if present
if not result["version"]:
vm = re.search(r"PHP/?(\d+\.\d+\.\d+)", body)
if vm:
result["version"] = vm.group(1)
result["version_source"] = "banner:%s:errorpage" % scheme
break
probe_rec["server"] = hdrs.get("server")
probe_rec["x_powered_by"] = hdrs.get("x-powered-by")
# skip duplicate probe records (same scheme/server/x-powered-by)
key = (probe_rec["scheme"], probe_rec.get("server"), probe_rec.get("x_powered_by"))
if key not in {(p["scheme"], p.get("server"), p.get("x_powered_by")) for p in result["probes"]}:
result["probes"].append(probe_rec)
# once we have a version from headers, no need to hammer more probes
if result["version"] and label != "GET malformed":
break
if reachable and result["version"]:
break
return result
# ---------------------------------------------------------------------------
# Subdomain recon via crt.sh (Certificate Transparency)
# ---------------------------------------------------------------------------
def crtsh_subdomains(domain, timeout=25, insecure=False):
"""
Query crt.sh Certificate Transparency logs for subdomains of `domain`.
Returns a sorted list of unique hostnames (wildcards stripped).
Passive recon: no traffic to the target itself.
"""
domain = domain.strip().lower().lstrip(".")
# strip scheme/path if a URL was passed
if "://" in domain:
domain = urllib.parse.urlparse(domain if "//" in domain else "//" + domain).netloc
domain = domain.split("/")[0].split(":")[0]
found = set()
url = "https://crt.sh/?q=%s&output=json" % urllib.parse.quote("%." + domain)
ctx = ssl.create_default_context()
if insecure:
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json"})
data = None
last_err = None
# crt.sh frequently returns 502/timeout under load — retry a few times.
for attempt in range(4):
try:
resp = urllib.request.urlopen(req, timeout=timeout, context=ctx)
data = resp.read()
break
except Exception as e:
last_err = e
time.sleep(2 * (attempt + 1))
if data is None:
return [], "crt.sh error after retries: %s" % last_err
try:
rows = json.loads(data.decode("utf-8", "replace"))
except Exception:
# crt.sh sometimes returns concatenated JSON objects; normalize
txt = data.decode("utf-8", "replace").strip()
try:
rows = json.loads("[" + txt.replace("}\n{", "},{") + "]")
except Exception as e:
return [], "crt.sh parse error: %s" % e
for row in rows:
name = (row.get("name_value") or "") + "\n" + (row.get("common_name") or "")
for n in name.split("\n"):
n = n.strip().lower().lstrip("*.")
if n and n.endswith(domain) and all(ch.isprintable() for ch in n):
found.add(n)
return sorted(found), None
def _normalize_domain(domain):
domain = domain.strip().lower().lstrip(".")
if "://" in domain:
domain = urllib.parse.urlparse(domain if "//" in domain else "//" + domain).netloc
return domain.split("/")[0].split(":")[0]
# Common multi-label public suffixes. Not a full PSL, but covers the cases
# that break a naive "strip one label" (e.g. example.com.br -> com.br).
MULTI_LABEL_SUFFIXES = frozenset((
"com.br", "net.br", "org.br", "gov.br", "edu.br",
"co.uk", "org.uk", "gov.uk", "ac.uk", "me.uk",
"com.au", "net.au", "org.au", "gov.au", "edu.au",
"co.jp", "or.jp", "ne.jp", "go.jp",
"com.mx", "com.ar", "com.co", "com.tr", "com.cn",
"co.in", "co.za", "co.nz", "co.kr", "com.sg", "com.hk",
"com.pt", "com.es", "com.pl", "com.ua", "com.ru",
))
def registrable_domain(host):
"""
Reduce a hostname to the registrable (apex) domain, honoring common
two-label public suffixes. 'www.example.com.br' -> 'example.com.br',
'origin.example.com' -> 'example.com'. Returns host unchanged when it is
already at (or below) the apex. Used only to seed sibling-subdomain origin
discovery for an OWNED domain — never to reach across to unrelated hosts.
"""
host = _normalize_domain(host)
if not host:
return host
labels = host.split(".")
if len(labels) <= 2:
return host
last_two = ".".join(labels[-2:])
if last_two in MULTI_LABEL_SUFFIXES:
# keep three labels: <name>.<second-level>.<tld>
return ".".join(labels[-3:])
return last_two
def subfinder_subdomains(domain, timeout=120):
"""
Fallback enumeration via ProjectDiscovery subfinder (passive).
Returns (sorted_hosts, error). error is set if subfinder is missing or
fails; an empty list with no error means subfinder ran but found none.
"""
domain = _normalize_domain(domain)
if not shutil.which("subfinder"):
return [], "subfinder not installed"
try:
p = subprocess.run(
["subfinder", "-silent", "-all", "-d", domain],
capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
return [], "subfinder timeout"
except Exception as e:
return [], "subfinder error: %s" % e
if p.returncode != 0 and not p.stdout.strip():
return [], "subfinder exit %s: %s" % (p.returncode, (p.stderr or "").strip()[:200])
found = set()
for line in p.stdout.splitlines():
n = line.strip().lower().lstrip("*.")
if n and n.endswith(domain) and all(ch.isprintable() for ch in n):
found.add(n)
return sorted(found), None
def enumerate_subdomains(domain, insecure=False):
"""
Enumerate subdomains: crt.sh first, subfinder as fallback.
If crt.sh succeeds, subfinder still runs and results are merged (union)
when available — broader coverage, fallback-safe when crt.sh is down.
Returns (sorted_hosts, sources_used:list, note:str|None).
"""
hosts = set()
sources = []
note = None
subs, err = crtsh_subdomains(domain, insecure=insecure)
if err:
note = err
else:
sources.append("crt.sh")
hosts.update(subs)
# subfinder: fallback when crt.sh failed, or as a merge source otherwise
sf, sf_err = subfinder_subdomains(domain)
if sf_err:
if note:
note += " | subfinder: %s" % sf_err
else:
sources.append("subfinder")
hosts.update(sf)
return sorted(hosts), sources, note
def resolves(host):
"""True if host resolves to an A/AAAA record."""
try:
socket.getaddrinfo(host, None)
return True
except Exception:
return False
# ---------------------------------------------------------------------------
# Behavior probe (OPT-IN — may cause DoS)
# ---------------------------------------------------------------------------
def build_multipart_payload(n_parts=1500, part_size=4096):
"""
multipart/form-data with many parts -> memory pressure in the parser.
Vector cited in the advisory (CVE-2026-109618): multipart that reaches
OOM within PHP's apparent limits.
"""
boundary = "----php2shellProbe"
lines = []
for i in range(n_parts):
lines.append("--" + boundary)
lines.append('Content-Disposition: form-data; name="field_%d"' % i)
lines.append("Content-Type: text/plain")
lines.append("")
lines.append("A" * part_size)
lines.append("--" + boundary + "--")
lines.append("")
return ("\r\n".join(lines)).encode(), boundary
def probe_request(opener, url, timeout=25):
"""Huge multipart POST; returns (status, elapsed, error)."""
payload, boundary = build_multipart_payload()
req = urllib.request.Request(url, data=payload, headers={
"User-Agent": UA,
"Content-Type": "multipart/form-data; boundary=" + boundary,
"Connection": "close",
"Expect": "",
}, method="POST")
t0 = time.time()
try:
resp = opener.open(req, timeout=timeout)
resp.read(10_000)
return resp.status, time.time() - t0, None
except urllib.error.HTTPError as e:
return e.code, time.time() - t0, None
except Exception as e:
return None, time.time() - t0, str(e)
def run_probe(opener, base, count=5):
"""
Heuristic: baseline GET ok + N large multipart POSTs.
If 5xx/timeouts/refused connections appear that the baseline did not
show, mark SUSPECTED. Does NOT confirm RCE — only flags instability.
"""
results = []
target = base.rstrip("/") + "/"
b = http_get(opener, target)
baseline_ok = b.get("status") is not None and b.get("status") < 500
for i in range(count):
st, el, err = probe_request(opener, target)
results.append({"iter": i + 1, "status": st, "elapsed": round(el, 2), "error": err})
time.sleep(1.0) # rate-limit: 1 req/s
anomalies = [r for r in results if r["status"] is None or (r["status"] and r["status"] >= 500)]
verdict = "NO_ANOMALY"
if baseline_ok and len(anomalies) >= max(1, count // 2):
verdict = "SUSPECTED (instability under multipart load — worker may have restarted)"
elif anomalies:
verdict = "INCONCLUSIVE (%d/%d anomalous responses)" % (len(anomalies), count)
return {"verdict": verdict, "baseline_ok": baseline_ok, "iterations": results}
# ---------------------------------------------------------------------------
# Local scan
# ---------------------------------------------------------------------------
def scan_local(php_bin="php"):
out = {"mode": "local", "php_bin": php_bin}
path = shutil.which(php_bin)
if not path:
out["error"] = "php binary not found in PATH"
return out
try:
v = subprocess.run([php_bin, "-r", "echo PHP_VERSION;"], capture_output=True, text=True, timeout=10)
version = v.stdout.strip()
out["php_version"] = version or None
try:
si = subprocess.run([php_bin, "-r", "echo php_sapi_name().'|'.@(ini_get('memory_limit')).'|'.@(ini_get('post_max_size'));"],
capture_output=True, text=True, timeout=10)
parts = si.stdout.strip().split("|")
if len(parts) == 3:
out["sapi"] = parts[0]
out["memory_limit"] = parts[1]
out["post_max_size"] = parts[2]
except Exception:
pass
except Exception as e:
out["error"] = str(e)
return out
return out
# ---------------------------------------------------------------------------
# Extra PHP version-fingerprinting techniques (passive / non-exploit)
# ---------------------------------------------------------------------------
# Classic PHP "easter egg" query strings. On expose_php=On they return a
# characteristic GIF (or the credits page), confirming PHP and its era.
PHP_EGGS = {
"logo": "PHPE9568F34-D428-11d2-A769-00AA001ACF42", # PHP logo
"zend": "PHPE9568F35-D428-11d2-A769-00AA001ACF42", # Zend logo
"credits": "PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000", # credits page
"egg": "PHPE9568F36-D428-11d2-A769-00AA001ACF42", # easter egg logo
}
# Files that may DECLARE a PHP version constraint (not the live runtime).
VERSION_LEAK_FILES = [
"/composer.json", "/composer.lock", "/vendor/composer/installed.json",
"/.env", "/phpunit.xml", "/phpunit.xml.dist",
]
def probe_php_eggs(opener, base, hostpath="/"):
"""
Request the PHP easter-egg query strings. Returns (confirmed, era) where
confirmed means PHP presence was proven, and era is a coarse version hint.
Non-destructive GETs. Works only when expose_php=On.
"""
target = base.rstrip("/") + (hostpath if hostpath.startswith("/") else "/" + hostpath)
for name, egg in PHP_EGGS.items():
url = "%s?=%s" % (target, egg)
res = http_get(opener, url, max_bytes=40_000)
if res.get("status") != 200:
continue
hdrs = {k.lower(): v for k, v in res.get("headers", {}).items()}
ctype = hdrs.get("content-type", "")
body = res.get("body", "")
# GIF response to a logo egg = PHP with expose_php On
if "image/gif" in ctype or body[:6] in ("GIF87a", "GIF89a"):
return True, "egg:%s (expose_php=On)" % name
# credits page leaks build/version strings
if name == "credits" and ("PHP Credits" in body or "PHP Group" in body):
m = re.search(r"PHP\s*(\d+\.\d+\.\d+)", body)
return True, ("egg:credits %s" % m.group(1)) if m else "egg:credits"
return False, None
def probe_version_files(opener, base):
"""
Fetch files that may declare a required PHP version. Returns (constraint,
source) — a DECLARED requirement (e.g. '>=8.1'), not the live runtime, so
it only narrows the branch, never confirms the patch level.
"""
for p in VERSION_LEAK_FILES:
url = urllib.parse.urljoin(base + "/", p.lstrip("/"))
res = http_get(opener, url, max_bytes=60_000)
if res.get("status") != 200 or not res.get("body"):
continue
body = res["body"]
# composer: "php": ">=8.1" or "require": {"php": "^8.2"}
m = re.search(r'"php"\s*:\s*"([^"]+)"', body)
if m:
return m.group(1), "file:%s" % p
# .env sometimes carries PHP_VERSION=8.3.1
m = re.search(r'PHP_VERSION\s*=\s*["\']?(\d+\.\d+\.\d+)', body)
if m:
return m.group(1), "file:%s" % p
return None, None
# ---------------------------------------------------------------------------
# Origin discovery — reach the PHP origin behind Cloudflare / other WAFs
# ---------------------------------------------------------------------------
# Published Cloudflare IPv4 ranges (https://www.cloudflare.com/ips/).
CLOUDFLARE_CIDRS = [ipaddress.ip_network(c) for c in (
"173.245.48.0/20", "103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22",
"141.101.64.0/18", "108.162.192.0/18", "190.93.240.0/20", "188.114.96.0/20",
"197.234.240.0/22", "198.41.128.0/17", "162.158.0.0/15", "104.16.0.0/13",
"104.24.0.0/14", "172.64.0.0/13", "131.0.72.0/22",
# Cloudflare IPv6 ranges
"2400:cb00::/32", "2606:4700::/32", "2803:f800::/32", "2405:b500::/32",
"2405:8100::/32", "2a06:98c0::/29", "2c0f:f248::/32",
)]
# A few other common edge providers whose IPs are NOT the origin either.
OTHER_EDGE_CIDRS = [ipaddress.ip_network(c) for c in (
"199.83.128.0/21", "198.143.32.0/19", # Imperva/Incapsula
"192.230.64.0/18", # Sucuri
)]
# Subdomain prefixes that commonly point straight at the origin (not proxied).
ORIGIN_HINT_PREFIXES = [
"origin", "direct", "direct-connect", "cpanel", "whm", "webmail", "mail",
"ftp", "sftp", "ssh", "server", "web", "dev", "staging", "stage", "test",
"vpn", "remote", "portal", "admin", "api", "autodiscover", "ns1", "ns2",
"mx", "smtp", "backup", "old", "beta",
]
def _is_edge_ip(ip):
try:
addr = ipaddress.ip_address(ip)
except ValueError:
return False
return any(addr in n for n in CLOUDFLARE_CIDRS) or any(addr in n for n in OTHER_EDGE_CIDRS)
def _a_records(host):
try:
infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
except Exception:
return []
out = []
for fam, _, _, _, sa in infos:
ip = sa[0]
if ip not in out:
out.append(ip)
return out
def discover_origin_ips(domain, extra_hosts=None, insecure=False, max_candidates=12):
"""
Find candidate origin IPs that are NOT behind Cloudflare/WAF edge ranges.
Strategy (passive DNS only):
1. resolve the apex and www,
2. resolve common non-proxied prefixes (origin.*, cpanel.*, mail.*, ...),
3. resolve any extra hosts handed in (e.g. crt.sh/subfinder output),
4. keep only IPs outside known edge CIDRs.
Returns (origin_ips, notes).
"""
domain = _normalize_domain(domain)
notes = []
candidate_hosts = {domain, "www." + domain}
candidate_hosts.update("%s.%s" % (p, domain) for p in ORIGIN_HINT_PREFIXES)
if extra_hosts:
candidate_hosts.update(h for h in extra_hosts if h.endswith(domain))