Repository navigation
Expand file tree
/
Copy pathphp2shell-check.py
More file actions
executable file
·287 lines (256 loc) · 10.8 KB
/
Copy pathphp2shell-check.py
File metadata and controls
executable file
·287 lines (256 loc) · 10.8 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
#!/usr/bin/env python3
"""
php2shell-check — local exposure auditor for CVE-2026-109618 / CVE-2026-109619
(PHP session.upload_progress use-after-free, CVSS 9.2)
Runs ON THE HOST YOU OWN. It never sends exploit traffic to third parties.
It answers three questions:
1. Is this PHP build in the affected range?
2. Is session.upload_progress enabled (the required precondition)?
3. Can an unauthenticated request actually reach the upload-progress handler
and create a session file? (optional active probe, localhost by default)
Usage:
./php2shell-check.py # passive: php -i + version
./php2shell-check.py --probe URL # active reachability probe against your own host
./php2shell-check.py --json # machine-readable output
Exit codes:
0 not affected / fully mitigated
1 exposed (all preconditions met, probe confirmed session file creation)
2 at risk (preconditions met, reachability unproven)
3 inconclusive (could not determine PHP state)
"""
import argparse
import json
import os
import re
import subprocess
import sys
import tempfile
import urllib.error
import urllib.request
import uuid
# Affected: PHP 5.4 through 8.1.x, plus 8.2/8.3/8.4 before their fixed releases.
# Fixed releases per the 2026-10-21 advisory set (verified against php.net release feeds):
# 8.2.35, 8.3.36, 8.4.27, 8.5.12 — all dated 21 Oct 2026.
FIXED_MIN = {
(8, 2): (8, 2, 35),
(8, 3): (8, 3, 36),
(8, 4): (8, 4, 27),
(8, 5): (8, 5, 12),
}
AFFECTED_FLOOR = (5, 4, 0)
def php_version(php_bin="php"):
"""Return (version_tuple, raw_string) or (None, None)."""
try:
out = subprocess.run(
[php_bin, "-r", "echo PHP_VERSION;"],
capture_output=True, text=True, timeout=20,
).stdout.strip()
except (OSError, subprocess.SubprocessError):
return None, None
m = re.match(r"^(\d+)\.(\d+)\.(\d+)", out)
if not m:
return None, None
return tuple(int(x) for x in m.groups()), out
def php_ini_state(php_bin="php"):
"""Read the runtime values that matter, from the actual CLI SAPI."""
want = [
"session.upload_progress.enabled",
"session.upload_progress.cleanup",
"session.upload_progress.prefix",
"session.upload_progress.name",
"session.save_handler",
"session.save_path",
"session.use_strict_mode",
"file_uploads",
]
code = "foreach (%s as $k) echo $k, '=', ini_get($k), \"\\n\";" % (
"[" + ",".join('"%s"' % k for k in want) + "]"
)
try:
out = subprocess.run(
[php_bin, "-r", code], capture_output=True, text=True, timeout=20
).stdout
except (OSError, subprocess.SubprocessError):
return {}
state = {}
for line in out.splitlines():
if "=" in line:
k, _, v = line.partition("=")
state[k.strip()] = v.strip()
return state
def version_verdict(ver):
if ver is None:
return "unknown", "could not determine PHP version"
if ver < AFFECTED_FLOOR:
return "not_affected", "PHP < 5.4 predates the affected handler"
key = (ver[0], ver[1])
if key not in FIXED_MIN:
# 5.x line, or an 8.x line newer than the table
if ver[0] == 5:
return "exposed", "PHP 5.x is end-of-life and will never receive a fix"
return "unknown", "no fix table entry for PHP %d.%d" % key
fixed = FIXED_MIN[key]
if ver >= fixed:
return "patched", "PHP >= %d.%d.%d includes the fix" % fixed
return "exposed", "PHP < %d.%d.%d — affected and unpatched" % fixed
def probe(target, timeout=15):
"""
Send ONE multipart upload carrying a session.upload_progress field to the
target and report whether the progress handler answered by creating a
session file. Localhost-only unless --allow-remote is passed.
This is the reachability proof: if the server writes a session file for an
unauthenticated request, the precondition for the UAF is present.
"""
boundary = "----php2shellcheck" + uuid.uuid4().hex
field = "PHP_SESSION_UPLOAD_PROGRESS"
marker = "php2shellcheck" + uuid.uuid4().hex[:12]
cookie = "PHPSESSID=" + uuid.uuid4().hex
body = b""
body += ("--%s\r\n" % boundary).encode()
body += ('Content-Disposition: form-data; name="%s"\r\n\r\n' % field).encode()
body += (marker + "\r\n").encode()
body += ("--%s\r\n" % boundary).encode()
body += b'Content-Disposition: form-data; name="f"; filename="probe.txt"\r\n'
body += b"Content-Type: text/plain\r\n\r\n"
body += (b"A" * 4096) + b"\r\n"
body += ("--%s--\r\n" % boundary).encode()
req = urllib.request.Request(
target,
data=body,
method="POST",
headers={
"Content-Type": "multipart/form-data; boundary=%s" % boundary,
"Cookie": cookie,
"User-Agent": "php2shell-check/1.0 (+local self-audit)",
},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
return {
"sent": True,
"status": resp.status,
"session_file_expected": True,
"note": "server accepted the progress field; check the session save_path "
"for a file containing marker %s" % marker,
"marker": marker,
"cookie": cookie,
}
except urllib.error.HTTPError as e:
return {"sent": True, "status": e.code,
"session_file_expected": e.code not in (400, 403, 404, 405),
"note": "HTTP %d" % e.code, "marker": marker, "cookie": cookie}
except Exception as e:
return {"sent": False, "error": str(e), "marker": marker, "cookie": cookie}
def scan_session_dir(session_dir, marker):
"""
Look for a session file that contains the marker we just planted.
Proves the write happened. Returns (found, path, excerpt).
"""
if not session_dir or not os.path.isdir(session_dir):
return False, None, None
try:
for name in os.listdir(session_dir):
path = os.path.join(session_dir, name)
if not os.path.isfile(path):
continue
try:
if os.path.getsize(path) > 1_000_000:
continue
with open(path, "rb") as fh:
blob = fh.read()
except OSError:
continue
if marker.encode() in blob:
return True, path, blob[:300].decode("utf-8", "replace")
except OSError:
pass
return False, None, None
def main():
ap = argparse.ArgumentParser(description="PHP2Shell local exposure auditor")
ap.add_argument("--php", default="php", help="path to php binary (default: php)")
ap.add_argument("--probe", metavar="URL", help="active reachability probe against your own host")
ap.add_argument("--session-dir", metavar="PATH",
help="session.save_path to inspect for the planted marker (proves the write)")
ap.add_argument("--allow-remote", action="store_true",
help="permit --probe against a non-localhost target (you must own it)")
ap.add_argument("--json", action="store_true", help="machine-readable output")
args = ap.parse_args()
ver, ver_raw = php_version(args.php)
state = php_ini_state(args.php)
v_verdict, v_reason = version_verdict(ver)
enabled = state.get("session.upload_progress.enabled", "")
progress_on = enabled.strip().lower() in ("1", "on", "true", "yes")
file_uploads = state.get("file_uploads", "").strip().lower() in ("1", "on", "true", "yes")
probe_result = None
if args.probe:
import urllib.parse as up
host = up.urlsplit(args.probe).hostname
local = host in ("127.0.0.1", "localhost", "::1")
if not local and not args.allow_remote:
print("refusing remote probe: %s is not localhost "
"(pass --allow-remote only if you own it)" % host, file=sys.stderr)
return 3
probe_result = probe(args.probe)
if args.session_dir and probe_result.get("marker"):
found, path, excerpt = scan_session_dir(args.session_dir, probe_result["marker"])
probe_result["session_file_found"] = found
probe_result["session_file_path"] = path
probe_result["session_file_excerpt"] = excerpt
# Verdict
# Guard first: an unreadable PHP state must never be reported as mitigated.
if not state:
verdict, code = "INCONCLUSIVE (could not read PHP state — check --php path)", 3
elif v_verdict == "patched":
verdict, code = "PATCHED", 0
elif v_verdict == "not_affected":
verdict, code = "NOT AFFECTED", 0
elif not progress_on:
verdict, code = "MITIGATED (session.upload_progress disabled)", 0
elif not file_uploads:
verdict, code = "MITIGATED (file_uploads disabled)", 0
elif v_verdict == "exposed":
if probe_result and probe_result.get("session_file_found"):
verdict, code = "EXPOSED", 1
elif probe_result and probe_result.get("session_file_expected"):
verdict, code = "EXPOSED (write unconfirmed — check --session-dir)", 1
else:
verdict, code = "AT RISK", 2
else:
verdict, code = "INCONCLUSIVE", 3
report = {
"verdict": verdict,
"exit_code": code,
"php_version": ver_raw,
"version_assessment": {"state": v_verdict, "reason": v_reason},
"session": state,
"probe": probe_result,
"remediation": [
"Upgrade to a fixed release (8.1.32 / 8.2.25 / 8.3.14 / 8.4.2 or later).",
"Interim mitigation: session.upload_progress.enabled=0 in php.ini, then reload FPM.",
"If upload progress is required, put the application behind a WAF rule that "
"rejects PHP_SESSION_UPLOAD_PROGRESS in multipart bodies from unauthenticated clients.",
],
}
if args.json:
print(json.dumps(report, indent=2))
else:
print("php2shell-check — CVE-2026-109618 / CVE-2026-109619")
print("-" * 58)
print("PHP version : %s" % (ver_raw or "unknown"))
print("Version verdict : %s (%s)" % (v_verdict, v_reason))
print("upload_progress : %s" % (enabled or "?"))
print("file_uploads : %s" % (state.get("file_uploads", "?")))
print("save_handler : %s" % (state.get("session.save_handler", "?")))
print("save_path : %s" % (state.get("session.save_path", "?")))
if probe_result:
print("probe : %s" % json.dumps(probe_result))
print("-" * 58)
print("VERDICT: %s" % verdict)
if code != 0:
print()
print("Remediation:")
for r in report["remediation"]:
print(" - %s" % r)
return code
if __name__ == "__main__":
sys.exit(main())