Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
195 lines (176 loc) · 6.93 KB
/
Copy pathindex.js
File metadata and controls
195 lines (176 loc) · 6.93 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
/**
* php2shell-watcher v1.0.0 — Cloudflare Worker (free tier compatible, no KV)
*
* Detects exploitation attempts against PHP session.upload_progress
* (CVE-2026-109618 / CVE-2026-109619) at the edge, blocks the trigger
* request, and reports to a Discord webhook.
*
* Detection signals (multipart POST bodies only; all other traffic passes
* through untouched):
* CRITICAL body contains the PHP_SESSION_UPLOAD_PROGRESS trigger field
* HIGH PHPSESSID sent as a multipart form field (exploit pattern)
* HIGH >= 20 identical t[] fields (heap-spray pattern from public PoCs)
*
* Quickstart:
* 1. Set a random TEST_TOKEN below (or as a secret named TEST_TOKEN).
* 2. wrangler secret put DISCORD_WEBHOOK # your Discord webhook URL
* 3. Edit routes in wrangler.toml for your domain, then: wrangler deploy
* 4. Verify:
* curl -H "x-watcher-test: <TEST_TOKEN>" https://your-site/
* curl -X POST https://your-site/ -F "PHP_SESSION_UPLOAD_PROGRESS=x" -F "f=@/etc/hostname"
* (expect a green self-test embed, then HTTP 403 + a red alert embed)
*
* This is a detection/edge-mitigation layer. It is NOT a substitute for
* patching PHP or setting `session.upload_progress.enabled = Off`.
*/
const CONFIG = {
BLOCK_ON_TRIGGER: true, // 403 any request carrying the actual trigger field
ALERT_ON_SUSPICION: true, // alert (no block) on heuristic-only matches
MAX_BODY_SCAN: 262144, // scan at most 256 KB of any body
ALERT_TTL: 300, // seconds; identical alerts deduped for this long
TEST_TOKEN: "REPLACE-WITH-RANDOM-STRING", // or set secret TEST_TOKEN
};
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
// ---- self-test path: fire one test alert on demand ---------------------
const testToken = env.TEST_TOKEN || CONFIG.TEST_TOKEN;
if (
testToken !== "REPLACE-WITH-RANDOM-STRING" &&
request.headers.get("x-watcher-test") === testToken
) {
await notify(env, ctx, testEmbed(request));
return new Response("test alert sent\n", { status: 200 });
}
// ---- only multipart POSTs can carry the trigger ------------------------
const ct = (request.headers.get("content-type") || "").toLowerCase();
if (request.method !== "POST" || !ct.includes("multipart/form-data")) {
return fetch(request);
}
const body = await readCapped(request.clone(), CONFIG.MAX_BODY_SCAN);
const signals = analyse(body);
if (signals.length === 0) return fetch(request);
const critical = signals.some((s) => s.sev === "CRITICAL");
const action = critical && CONFIG.BLOCK_ON_TRIGGER ? "BLOCKED" : "LOGGED";
if (critical || CONFIG.ALERT_ON_SUSPICION) {
const key = await sha256(
clientIP(request) + signals.map((s) => s.name).join(",") + url.pathname
);
if (!(await dedup(key))) {
ctx.waitUntil(notify(env, ctx, buildEmbed(request, url, signals, action, body)));
}
}
if (action === "BLOCKED") {
return new Response("Forbidden\n", { status: 403 });
}
return fetch(request);
},
};
// ---------------------------------------------------------------- analysis --
function analyse(body) {
const out = [];
if (body.includes("PHP_SESSION_UPLOAD_PROGRESS")) {
out.push({ sev: "CRITICAL", name: "PHP_SESSION_UPLOAD_PROGRESS trigger field present" });
}
if (/name="PHPSESSID"/.test(body)) {
out.push({ sev: "HIGH", name: "PHPSESSID sent as multipart form field (exploit pattern)" });
}
const spray = (body.match(/name="t\[\]"/g) || []).length;
if (spray >= 20) {
out.push({ sev: "HIGH", name: `heap-spray pattern: ${spray} identical t[] fields` });
}
return out;
}
// ------------------------------------------------------------------- embed --
function buildEmbed(request, url, signals, action, body) {
const cf = request.cf || {};
const worst = signals.some((s) => s.sev === "CRITICAL") ? "CRITICAL" : "HIGH";
const excerpt = body
.slice(0, 400)
.replace(/[^\x20-\x7E\n]/g, ".")
.replace(/`/g, "'")
.slice(0, 180);
return {
username: "php2shell-watcher",
embeds: [
{
title: `${worst}: upload_progress exploit ${action}`,
color: worst === "CRITICAL" ? 0xdc2626 : 0xf59e0b,
fields: [
{ name: "Signals", value: signals.map((s) => `• [${s.sev}] ${s.name}`).join("\n") },
{ name: "Client", value: `${clientIP(request)} · ${cf.country || "?"} · AS${cf.asn || "?"} · colo ${cf.colo || "?"}`, inline: true },
{ name: "Target", value: `${request.method} ${url.pathname}`, inline: true },
{ name: "CF Ray", value: request.headers.get("cf-ray") || "n/a", inline: true },
{ name: "User-Agent", value: trunc(request.headers.get("user-agent") || "n/a", 100) },
{ name: "Body excerpt (start)", value: "```" + excerpt + "```" },
],
timestamp: new Date().toISOString(),
},
],
};
}
function testEmbed(request) {
return {
username: "php2shell-watcher",
embeds: [
{
title: "php2shell-watcher online",
description: "Self-test: Discord alerting works. Blocking: " +
(CONFIG.BLOCK_ON_TRIGGER ? "ON" : "OFF"),
color: 0x16a34a,
fields: [{ name: "From colo", value: (request.cf && request.cf.colo) || "?" }],
timestamp: new Date().toISOString(),
},
],
};
}
// ----------------------------------------------------------------- helpers --
async function notify(env, ctx, payload) {
const hook = env.DISCORD_WEBHOOK;
if (!hook) return;
await fetch(hook, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
}).catch(() => {});
}
async function dedup(key) {
const cacheUrl = `https://php2shell-alert-cache.internal/${key}`;
if (await caches.default.match(cacheUrl)) return true;
await caches.default.put(
cacheUrl,
new Response("1", { headers: { "Cache-Control": `max-age=${CONFIG.ALERT_TTL}` } })
);
return false;
}
async function readCapped(request, cap) {
const reader = request.body.getReader();
const chunks = [];
let total = 0;
while (total < cap) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
total += value.byteLength;
if (total >= cap) { reader.cancel().catch(() => {}); break; }
}
const buf = new Uint8Array(Math.min(total, cap));
let off = 0;
for (const c of chunks) {
if (off >= buf.length) break;
const slice = c.subarray(0, buf.length - off);
buf.set(slice, off);
off += slice.byteLength;
}
return new TextDecoder().decode(buf);
}
async function sha256(text) {
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
}
function clientIP(request) {
return request.headers.get("cf-connecting-ip") || "unknown";
}
function trunc(s, n) {
return s.length > n ? s.slice(0, n - 1) + "…" : s;
}