Exploit databaseDownload repository ZIP
GH-7605fec517b50b87a473e14ec462b1c4
leminely/cve-2026-109618-109619
Sources for CVE-2026-109618
412 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files2
leminely/cve-2026-109618-109619Revision d083cabf4936
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
tools/php2shell-check.py
Python · 21,509 bytes#!/usr/bin/env python3
"""
php2shell-check - exposure checker for CVE-2026-109618 / CVE-2026-109619.
Two modes:
--local Audit the PHP runtime on this machine. Reads the real version and the
real directive values, so the verdict is reliable.
--url Triage a remote host. Fingerprints the PHP version from response
headers and, with --probe, tests whether the route accepts a
multipart POST at all. Weaker evidence than --local, and it says so.
What this tool will NOT claim: that it can detect session.upload_progress.enabled
over the network. It cannot, and nor can anything else -- the feature emits no
observable response. Verified against PHP 8.4.26 with the directive on. Use
--local for a real answer on configuration.
Nothing here corrupts memory, sends oversized requests or attempts exploitation.
The remote probe is an ordinary small multipart POST.
Only point --url at systems you own or have written permission to test.
Author: Lemin Ely <[email protected]>
Licence: MIT
"""
from __future__ import annotations
import argparse
import json
import re
import ssl
import subprocess
import sys
import urllib.error
import urllib.request
import uuid
# Fixed releases, 21 October 2026. Both CVEs are fixed in the same release.
FIXED = {
(8, 5): (8, 5, 12),
(8, 4): (8, 4, 27),
(8, 3): (8, 3, 36),
(8, 2): (8, 2, 35),
}
# Branches with no standard upstream release. Minimal source backports exist for
# 7.4, 8.0 and 8.1; a distribution rebuild may also carry the fix while keeping
# the upstream version string, which no version check can see.
BACKPORT_BRANCHES = {(8, 1), (8, 0), (7, 4)}
VULNERABLE = "VULNERABLE"
NEEDS_BACKPORT = "NEEDS_BACKPORT_CHECK"
PATCHED = "PATCHED"
UNKNOWN = "UNKNOWN"
C = {
"red": "\033[31m", "yellow": "\033[33m", "green": "\033[32m",
"blue": "\033[34m", "grey": "\033[90m", "bold": "\033[1m", "off": "\033[0m",
}
def paint(text: str, colour: str, enabled: bool) -> str:
return f"{C[colour]}{text}{C['off']}" if enabled else text
# ---------------------------------------------------------------------------
# Version logic
# ---------------------------------------------------------------------------
def parse_version(raw: str) -> tuple[int, int, int] | None:
"""Pull a major.minor.patch out of a version string or header value."""
match = re.search(r"(\d+)\.(\d+)\.(\d+)", raw)
if not match:
return None
return tuple(int(g) for g in match.groups()) # type: ignore[return-value]
def classify(version: tuple[int, int, int] | None) -> tuple[str, str]:
"""Return (verdict, explanation) for a PHP version."""
if version is None:
return UNKNOWN, "No PHP version could be determined."
major, minor, patch = version
branch = (major, minor)
shown = f"{major}.{minor}.{patch}"
if branch in FIXED:
fixed = FIXED[branch]
if version >= fixed:
return PATCHED, (
f"PHP {shown} is at or above {'.'.join(map(str, fixed))}, "
"the fixed release for this branch."
)
return VULNERABLE, (
f"PHP {shown} is below {'.'.join(map(str, fixed))}, the fixed release "
"for this branch."
)
if branch in BACKPORT_BRANCHES:
return NEEDS_BACKPORT, (
f"PHP {shown} is on an End Of Life branch with no standard upstream "
"release. A source backport exists, and your distribution may have "
"rebuilt the package without changing this version string. Confirm "
"with your package manager, not with the version number."
)
if branch > max(FIXED):
return UNKNOWN, (
f"PHP {shown} is newer than this tool knows about. Check the advisory "
"for your branch."
)
return NEEDS_BACKPORT, (
f"PHP {shown} is on an End Of Life branch with no official backport. "
"Treat the host as affected and plan an upgrade."
)
# ---------------------------------------------------------------------------
# Local audit
# ---------------------------------------------------------------------------
# directive -> (recommended value, which CVE it bears on, note when wrong)
DIRECTIVE_CHECKS = [
(
"session.upload_progress.enabled",
lambda v: v in ("0", "", "Off", "off"),
"0",
"Default-on trigger for the stale-state bug (109619). No session_start() "
"is required by the application.",
),
(
"memory_limit",
lambda v: v == "-1",
"-1",
"A finite limit is the attacker's remote trigger for the OOM bailout "
"(109618). Pair -1 with a process-level memory bound.",
),
(
"fatal_error_backtraces",
lambda v: v in ("0", "", "Off", "off"),
"0",
"PHP 8.5 only. Backtrace state is the confirmed mod_php exploitation path.",
),
]
INFORMATIONAL = [
"post_max_size",
"upload_max_filesize",
"max_input_vars",
"max_input_nesting_level",
"session.upload_progress.name",
]
def php_binary(explicit: str | None) -> str | None:
for candidate in ([explicit] if explicit else ["php", "php8", "php-cli"]):
try:
subprocess.run([candidate, "-v"], capture_output=True, check=True, timeout=15)
return candidate
except (OSError, subprocess.SubprocessError):
continue
return None
def read_runtime(binary: str) -> tuple[tuple[int, int, int] | None, dict[str, str]]:
"""Ask PHP for its own version and directive values."""
wanted = [name for name, _, _, _ in DIRECTIVE_CHECKS] + INFORMATIONAL
script = (
"echo PHP_VERSION, PHP_EOL;"
'echo "sapi=", php_sapi_name(), PHP_EOL;'
'echo "inifile=", (string) php_ini_loaded_file(), PHP_EOL;'
+ "".join(
f'echo {json.dumps(n)}, "=", (string) ini_get({json.dumps(n)}), PHP_EOL;'
for n in wanted
)
)
try:
out = subprocess.run(
[binary, "-r", script], capture_output=True, text=True, timeout=30, check=True
).stdout
except (OSError, subprocess.SubprocessError) as exc:
raise RuntimeError(f"could not query {binary}: {exc}") from exc
lines = out.strip().splitlines()
if not lines:
raise RuntimeError(f"{binary} returned nothing")
values = {}
for line in lines[1:]:
if "=" in line:
key, _, value = line.partition("=")
values[key] = value
return parse_version(lines[0]), values
def audit_local(args) -> dict:
binary = php_binary(args.php)
if binary is None:
return {
"mode": "local",
"verdict": UNKNOWN,
"reason": "No PHP binary found. Pass one with --php /path/to/php.",
"findings": [],
}
version, directives = read_runtime(binary)
verdict, reason = classify(version)
findings = []
for name, ok, want, note in DIRECTIVE_CHECKS:
value = directives.get(name)
if value is None:
continue
# fatal_error_backtraces only exists on 8.5; ini_get returns "" elsewhere.
if name == "fatal_error_backtraces" and value == "" and version and version[:2] < (8, 5):
continue
findings.append({
"directive": name,
"value": value,
"recommended": want,
"ok": bool(ok(value)),
"note": note,
})
sapi = directives.get("sapi", "")
caveat = None
if sapi == "cli":
caveat = (
"These directive values come from the CLI (Command Line Interface) "
"configuration, which is a different php.ini from the one your web "
"SAPI (Server API) uses. Notably, memory_limit defaults to -1 on the "
"CLI, so an 'ok' here proves nothing about your web requests. The "
"version verdict above is still valid. Audit the web configuration "
"directly:\n"
" php-fpm -tt 2>&1 | grep -iE "
"'upload_progress|memory_limit|post_max_size'\n"
" grep -rniE 'upload_progress|memory_limit' /etc/php/*/fpm/ "
"/etc/php-fpm.d/ 2>/dev/null\n"
" apachectl -t -D DUMP_RUN_CFG 2>/dev/null"
)
return {
"mode": "local",
"binary": binary,
"sapi": sapi or None,
"ini_file": directives.get("inifile") or None,
"php_version": ".".join(map(str, version)) if version else None,
"verdict": verdict,
"reason": reason,
"caveat": caveat,
"findings": findings,
"context": {k: directives.get(k) for k in INFORMATIONAL if k in directives},
}
# ---------------------------------------------------------------------------
# Remote triage
# ---------------------------------------------------------------------------
UA = "php2shell-check/1.0 (authorised exposure check)"
def http(url: str, args, method="GET", body=None, content_type=None, cookie=None):
request = urllib.request.Request(url, data=body, method=method)
request.add_header("User-Agent", args.user_agent)
if content_type:
request.add_header("Content-Type", content_type)
if cookie:
request.add_header("Cookie", cookie)
context = None
if url.startswith("https://") and args.insecure:
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
try:
with urllib.request.urlopen(request, timeout=args.timeout, context=context) as resp:
return resp.status, dict(resp.getheaders())
except urllib.error.HTTPError as exc:
# A 4xx/5xx still carries the headers we want.
return exc.code, dict(exc.headers.items())
def session_cookies(headers: dict) -> list[str]:
"""Values of any Set-Cookie naming a PHP session id."""
found = []
for name, value in headers.items():
if name.lower() != "set-cookie":
continue
for match in re.finditer(r"\b(PHPSESSID|PHPSESSIDUPLOAD)=([^;,\s]*)", value):
found.append(match.group(2))
return found
def probe_multipart(url: str, args) -> dict:
"""
Non-destructive reachability probe.
What this does NOT do: test whether session.upload_progress.enabled is set.
That is not observable from outside. The feature writes progress into session
storage and emits no response header, so there is nothing to measure -- the
Set-Cookie seen in published exploitation is forged leaked memory, not normal
behaviour. Measured against PHP 8.4.26 with the directive on: no session cookie
is returned. Any tool claiming to detect the directive remotely is guessing.
What it does test is the attack prerequisite, which IS observable: will this
endpoint accept a multipart/form-data POST at all, and does the progress field
survive to PHP? If multipart is rejected at the edge, mitigation 7 in
docs/hardening.md is in force on this route. If it is accepted, the route is
reachable by the trigger.
The request is a few hundred bytes and approaches no limit.
"""
boundary = uuid.uuid4().hex
field = args.progress_name
body = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="{field}"\r\n\r\n'
f"php2shell-check\r\n"
f"--{boundary}\r\n"
'Content-Disposition: form-data; name="probe"; filename="probe.txt"\r\n'
"Content-Type: text/plain\r\n\r\n"
"exposure check\r\n"
f"--{boundary}--\r\n"
).encode()
try:
status, headers = http(
url, args, method="POST", body=body,
content_type=f"multipart/form-data; boundary={boundary}",
)
except Exception as exc:
return {"ran": False, "reason": f"probe request failed: {exc}"}
if status in (403, 405, 406, 413, 501):
accepted = False
detail = (
f"The multipart POST was rejected with HTTP {status}. Something in front "
"of PHP is refusing multipart on this route, which is mitigation 7 in "
"docs/hardening.md. Confirm it covers every route, not just this one."
)
elif 200 <= status < 400:
accepted = True
detail = (
f"The multipart POST was accepted (HTTP {status}). The trigger path is "
"reachable on this route. That is normal for an application that handles "
"uploads -- it is only a problem while PHP is unpatched."
)
else:
accepted = None
detail = (
f"The multipart POST returned HTTP {status}, which does not clearly "
"indicate acceptance or rejection. A 500 here is worth a look: these "
"CVEs are reached by forcing an early fatal error."
)
return {
"ran": True,
"multipart_accepted": accepted,
"detail": detail,
"probe_status": status,
"field_name_used": field,
"leaked_session_values": session_cookies(headers),
}
def triage_remote(args) -> dict:
url = args.url if "://" in args.url else "http://" + args.url
try:
status, headers = http(url, args)
except Exception as exc:
return {
"mode": "remote", "url": url, "verdict": UNKNOWN,
"reason": f"Request failed: {exc}", "findings": [],
}
banner = " ".join(
headers.get(h, "") for h in ("X-Powered-By", "Server") if headers.get(h)
)
php_part = ""
for header in ("X-Powered-By", "Server"):
value = headers.get(header, "")
if "php" in value.lower():
php_part = value
break
version = parse_version(php_part) if php_part else None
verdict, reason = classify(version)
if version is None:
verdict = UNKNOWN
reason = (
"The host does not advertise a PHP version. expose_php is probably off, "
"or a proxy strips the header -- which is good hygiene and means this "
"mode cannot help. Audit the host directly with --local."
)
result = {
"mode": "remote",
"url": url,
"http_status": status,
"banner": banner or None,
"php_version": ".".join(map(str, version)) if version else None,
"verdict": verdict,
"reason": reason,
"findings": [],
}
if args.probe:
result["probe"] = probe_multipart(url, args)
return result
# ---------------------------------------------------------------------------
# Output
# ---------------------------------------------------------------------------
VERDICT_STYLE = {
VULNERABLE: ("red", "Unpatched PHP"),
NEEDS_BACKPORT: ("yellow", "End Of Life branch, needs a manual check"),
PATCHED: ("green", "Patched release"),
UNKNOWN: ("grey", "Could not determine"),
}
def report(result: dict, colour: bool) -> None:
print()
print(paint("php2shell exposure check", "bold", colour))
print(paint("CVE-2026-109618 / CVE-2026-109619", "grey", colour))
print()
if result["mode"] == "local":
print(f" Target this host ({result.get('binary', 'php')})")
if result.get("sapi"):
print(f" SAPI {result['sapi']}")
if result.get("ini_file"):
print(f" php.ini {result['ini_file']}")
else:
print(f" Target {result['url']}")
if result.get("banner"):
print(f" Banner {result['banner']}")
print(f" PHP version {result.get('php_version') or 'unknown'}")
style, label = VERDICT_STYLE[result["verdict"]]
print(f" Verdict {paint(label, style, colour)}")
print()
print(f" {result['reason']}")
print()
if result.get("caveat"):
print(paint(" Read this before trusting the configuration section", "yellow", colour))
print(paint(f" {result['caveat']}", "grey", colour))
print()
findings = result.get("findings") or []
if findings:
print(paint(" Configuration", "bold", colour))
for item in findings:
mark = paint("ok ", "green", colour) if item["ok"] else paint("warn", "yellow", colour)
print(f" {mark} {item['directive']} = {item['value'] or '(empty)'}"
f" recommended: {item['recommended']}")
if not item["ok"]:
print(paint(f" {item['note']}", "grey", colour))
print()
context = result.get("context") or {}
if context:
print(paint(" For context", "bold", colour))
for key, value in context.items():
print(f" {key} = {value or '(empty)'}")
print()
probe = result.get("probe")
if probe:
print(paint(" Multipart reachability probe", "bold", colour))
if not probe["ran"]:
print(f" did not run: {probe['reason']}")
else:
state = {
True: "multipart ACCEPTED, trigger path reachable",
False: "multipart rejected at the edge",
None: "unclear",
}[probe["multipart_accepted"]]
print(f" Result {state}")
print(f" Status HTTP {probe['probe_status']}")
print(f" Field sent {probe['field_name_used']}")
for value in probe.get("leaked_session_values") or []:
if not re.fullmatch(r"[A-Za-z0-9,-]*", value):
print(paint(" WARNING: the session cookie returned contains "
"unexpected bytes. Investigate as possible memory "
"disclosure.", "red", colour))
print(paint(f" {probe['detail']}", "grey", colour))
print(paint(" This probe cannot tell you whether "
"session.upload_progress.enabled is set -- that is not "
"observable remotely. Use --local on the host.", "grey", colour))
print()
print(paint(" Next", "bold", colour))
if result["verdict"] == VULNERABLE:
print(" Patch to 8.2.35 / 8.3.36 / 8.4.27 / 8.5.12, then RESTART every")
print(" worker -- a reload keeps the stale state alive.")
print(" Cannot patch yet: see docs/hardening.md")
elif result["verdict"] == NEEDS_BACKPORT:
print(" Confirm with your package manager whether the fix was backported:")
print(" apt-get changelog php8.1 | head -40")
print(" rpm -q --changelog php | head -40")
print(" Look for the CVE identifiers. See docs/affected-versions.md")
elif result["verdict"] == PATCHED:
print(" Version looks good. Confirm the workers were restarted, not")
print(" reloaded, and keep the hardening in place as defence in depth.")
else:
print(" Run with --local on the host itself for a reliable answer.")
print()
def main() -> int:
parser = argparse.ArgumentParser(
prog="php2shell-check",
description="Check exposure to CVE-2026-109618 / CVE-2026-109619.",
epilog="Use --url only against systems you own or are authorised to test.",
)
target = parser.add_mutually_exclusive_group(required=True)
target.add_argument("--local", action="store_true",
help="audit the PHP runtime on this machine (most reliable)")
target.add_argument("--url", metavar="URL",
help="triage a remote host by its response headers")
parser.add_argument("--php", metavar="PATH",
help="PHP binary to audit in --local mode")
parser.add_argument("--probe", action="store_true",
help="also send one small multipart POST to test whether the "
"route accepts multipart at all (the attack "
"prerequisite). Cannot detect the upload progress "
"directive -- that is not observable remotely.")
parser.add_argument("--progress-name", default="PHP_SESSION_UPLOAD_PROGRESS",
metavar="NAME",
help="value of session.upload_progress.name on the target "
"(default: %(default)s)")
parser.add_argument("--timeout", type=float, default=15.0, metavar="SECONDS",
help="per-request timeout (default: %(default)s)")
parser.add_argument("--insecure", action="store_true",
help="do not verify TLS certificates")
parser.add_argument("--user-agent", default=UA, metavar="STRING",
help="User-Agent to send")
parser.add_argument("--json", action="store_true",
help="emit JSON instead of a report")
parser.add_argument("--no-colour", action="store_true", help="disable colour")
args = parser.parse_args()
try:
result = audit_local(args) if args.local else triage_remote(args)
except RuntimeError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
if args.json:
print(json.dumps(result, indent=2))
else:
report(result, colour=sys.stdout.isatty() and not args.no_colour)
# 1 if action is needed, 0 if not, 2 if we could not tell.
return {VULNERABLE: 1, NEEDS_BACKPORT: 1, PATCHED: 0, UNKNOWN: 2}[result["verdict"]]
if __name__ == "__main__":
sys.exit(main())