Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
393 lines (349 loc) · 13.2 KB
/
Copy pathscript.js
File metadata and controls
393 lines (349 loc) · 13.2 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
const CONFIG = {
endpoints: {
scan: "index.php",
quarantinedFetch: "index.php?fetch=1"
},
statusClasses: {
quarantined: "quarantined",
safe: "safe",
error: "error"
},
statusMessages: {
quarantined: "Email is PHISHING (Quarantined)!",
safe: "Email is SAFE!",
unknown: "Unable to determine email status.",
listError: "Unable to analyze list.",
networkError: "Network error while analyzing list.",
fetchError: "Network error while fetching quarantined emails.",
invalidResponse: "Unexpected response format."
},
listSummaryLabels: {
total: "Total items",
last: "Last item",
secondLast: "Second-to-last item"
},
listStatusOk: "ok",
quarantineFields: ["sender", "recipient", "subject", "body", "received_at"],
emptyDisplayValue: "",
fallbackDisplayValue: "N/A"
};
const ANIMATION_CONFIG = {
initialDelayMs: 200,
idleDelayMs: 5000,
animationName: "idleAnimation",
animationDuration: "6s",
animationTiming: "ease-in-out",
idleSelectors: "a, h1",
idleEvents: ["mousemove", "click", "keydown", "scroll"]
};
const logger = (() => {
const isNode = typeof process !== "undefined" && Boolean(process.stdout);
const stdout = isNode ? process.stdout : null;
const stderr = isNode ? process.stderr : null;
const write = (stream, message) => {
if (stream) {
stream.write(`${message}\n`);
}
};
return {
info: message => write(stdout, message),
error: message => write(stderr, message)
};
})();
/**
* Parse a fetch response as JSON with validation.
* @param {Response} response - The fetch response to parse.
* @returns {Promise<unknown>} Parsed JSON payload.
*/
async function parseJsonResponse(response) {
if (!response.ok) {
throw new Error(CONFIG.statusMessages.invalidResponse);
}
try {
return await response.json();
} catch (error) {
throw new Error(CONFIG.statusMessages.invalidResponse);
}
}
/**
* Ensure a value is a string for rendering.
* @param {unknown} value - Value to validate.
* @returns {string} Sanitized display value.
*/
function toDisplayString(value) {
return typeof value === "string" ? value : CONFIG.emptyDisplayValue;
}
/**
* Ensure a value is a number for rendering.
* @param {unknown} value - Value to validate.
* @returns {number} Sanitized numeric value.
*/
function toDisplayNumber(value) {
return typeof value === "number" && Number.isFinite(value) ? value : 0;
}
/**
* Verify an object shape for list responses.
* @param {unknown} responseData - Parsed payload to validate.
* @returns {boolean} True when the payload matches expected shape.
*/
function isListResponse(responseData) {
return Boolean(responseData && typeof responseData === "object");
}
/**
* Update a result element with status styling and message.
* @param {HTMLElement} element - The DOM element to update.
* @param {string} status - Status value from the server.
* @param {string} message - Message to display.
*/
function applyStatus(element, status, message) {
element.textContent = message;
element.classList.remove(
CONFIG.statusClasses.quarantined,
CONFIG.statusClasses.safe,
CONFIG.statusClasses.error
);
if (status === CONFIG.statusClasses.quarantined) {
element.classList.add(CONFIG.statusClasses.quarantined);
return;
}
if (status === CONFIG.statusClasses.safe) {
element.classList.add(CONFIG.statusClasses.safe);
return;
}
element.classList.add(CONFIG.statusClasses.error);
}
/**
* Apply error styling and message to a list result element.
* @param {HTMLElement} element - The DOM element to update.
* @param {string} message - Error message to display.
*/
function applyListError(element, message) {
element.classList.add(CONFIG.statusClasses.error);
element.textContent = message;
}
/**
* Fetch quarantined email data and update the table.
* @param {HTMLTableSectionElement | null} tableBody - The table body to update.
*/
async function fetchQuarantinedEmails(tableBody) {
if (!tableBody) {
return;
}
try {
// Cet endpoint exige désormais un jeton (X-Quarantine-Token) : il
// renvoyait auparavant le corps complet de tous les courriels en
// quarantaine à quiconque le demandait.
//
// Un navigateur ne peut PAS détenir ce jeton : tout ce qu'il connaît
// est lisible par la personne devant l'écran, et par toute extension
// installée. Le tableau de bord doit donc passer par le serveur de
// l'application, qui détient le secret et vérifie la session — jamais
// porter le secret lui-même.
//
// En attendant ce relais, l'appel reste tel quel et reçoit un 401 : la
// liste ne s'affiche plus, et c'est la bonne défaillance. Une liste qui
// s'affichait pour tout le monde était le défaut, pas la solution.
const response = await fetch(CONFIG.endpoints.quarantinedFetch, {
credentials: "same-origin",
});
if (response.status === 401 || response.status === 503) {
throw new Error(
"Accès à la quarantaine non autorisé : le serveur doit relayer cette " +
"requête avec le jeton, un navigateur ne peut pas le détenir."
);
}
const quarantinedEmails = await parseJsonResponse(response);
if (!Array.isArray(quarantinedEmails)) {
throw new Error(CONFIG.statusMessages.invalidResponse);
}
tableBody.replaceChildren();
quarantinedEmails.forEach(email => {
const row = document.createElement("tr");
CONFIG.quarantineFields.forEach(key => {
const cell = document.createElement("td");
const value = toDisplayString(email?.[key]);
cell.textContent = value;
row.appendChild(cell);
});
tableBody.appendChild(row);
});
} catch (error) {
logger.error(CONFIG.statusMessages.fetchError);
}
}
document.addEventListener("DOMContentLoaded", () => {
const form = document.getElementById("emailForm");
const resultDiv = document.getElementById("result");
const quarantineTable = document.getElementById("quarantineList");
const quarantineBody = quarantineTable?.querySelector("tbody") ?? null;
const listForm = document.getElementById("listForm");
const listResult = document.getElementById("listResult");
if (form && resultDiv) {
form.addEventListener("submit", async event => {
event.preventDefault();
try {
const formData = new FormData(form);
if ([...formData.keys()].length === 0) {
applyStatus(resultDiv, CONFIG.statusClasses.error, CONFIG.statusMessages.unknown);
return;
}
const response = await fetch(CONFIG.endpoints.scan, {
method: "POST",
body: formData
});
const responseData = await parseJsonResponse(response);
const status = typeof responseData?.status === "string" ? responseData.status : "";
const message =
status === CONFIG.statusClasses.quarantined
? CONFIG.statusMessages.quarantined
: status === CONFIG.statusClasses.safe
? CONFIG.statusMessages.safe
: responseData?.message ?? CONFIG.statusMessages.unknown;
applyStatus(resultDiv, status, message);
await fetchQuarantinedEmails(quarantineBody);
} catch (error) {
applyStatus(resultDiv, CONFIG.statusClasses.error, CONFIG.statusMessages.networkError);
}
});
}
if (listForm && listResult) {
listForm.addEventListener("submit", async event => {
event.preventDefault();
try {
const formData = new FormData(listForm);
if ([...formData.keys()].length === 0) {
applyListError(listResult, CONFIG.statusMessages.listError);
return;
}
const response = await fetch(CONFIG.endpoints.scan, {
method: "POST",
body: formData
});
const responseData = await parseJsonResponse(response);
listResult.classList.remove(CONFIG.statusClasses.error);
if (!isListResponse(responseData) || responseData?.status !== CONFIG.listStatusOk) {
applyListError(
listResult,
responseData?.message ?? CONFIG.statusMessages.listError
);
return;
}
const summaryLines = [
`${CONFIG.listSummaryLabels.total}: ${toDisplayNumber(responseData.count)}`,
`${CONFIG.listSummaryLabels.last}: ${responseData.last ?? CONFIG.fallbackDisplayValue}`,
`${CONFIG.listSummaryLabels.secondLast}: ${responseData.second_last ?? CONFIG.fallbackDisplayValue}`
];
listResult.textContent = summaryLines.join("\n");
} catch (error) {
applyListError(listResult, CONFIG.statusMessages.networkError);
}
});
}
fetchQuarantinedEmails(quarantineBody).catch(error => {
logger.error(CONFIG.statusMessages.fetchError);
});
});
if (typeof window === "undefined") {
const fs = require("node:fs");
const path = require("node:path");
const WORDPRESS_DIRECTORY = "/var/www/html/wordpress";
const PHP_EXTENSION = ".php";
const MALWARE_KEYWORDS = [
"eval(",
"base64_decode(",
"file_get_contents(",
"system(",
"exec("
];
/**
* Recursively scan a directory for PHP files.
* @param {string} directoryPath - Directory path to scan.
*/
function scanDirectory(directoryPath) {
let files;
try {
files = fs.readdirSync(directoryPath);
} catch (error) {
logger.error(`Unable to read directory: ${directoryPath}`);
return;
}
files.forEach(file => {
const filePath = path.join(directoryPath, file);
let stat;
try {
stat = fs.statSync(filePath);
} catch (error) {
logger.error(`Unable to read path: ${filePath}`);
return;
}
if (stat.isDirectory()) {
scanDirectory(filePath);
return;
}
if (stat.isFile() && path.extname(file) === PHP_EXTENSION) {
scanFile(filePath);
}
});
}
/**
* Scan a single file for suspicious content.
* @param {string} filePath - Path to the file to scan.
*/
function scanFile(filePath) {
let fileContent;
try {
fileContent = fs.readFileSync(filePath, "utf-8");
} catch (error) {
logger.error(`Unable to read file: ${filePath}`);
return;
}
const malwareFound = checkForMalware(fileContent);
const logMessage = malwareFound
? `⚠️ Malware detected in: ${filePath}`
: `✅ File is clean: ${filePath}`;
logger.info(logMessage);
}
/**
* Check for suspicious keywords inside a file.
* @param {string} fileContent - File contents to analyze.
* @returns {boolean} True if malware patterns are found.
*/
function checkForMalware(fileContent) {
return MALWARE_KEYWORDS.some(keyword => fileContent.includes(keyword));
}
if (fs.existsSync(WORDPRESS_DIRECTORY)) {
scanDirectory(WORDPRESS_DIRECTORY);
} else {
logger.error(`WordPress directory not found: ${WORDPRESS_DIRECTORY}`);
}
}
document.addEventListener("DOMContentLoaded", () => {
const container = document.querySelector(".container");
if (!container) {
return;
}
let idleTimeout;
const animationValue = `${ANIMATION_CONFIG.animationName} ${ANIMATION_CONFIG.animationDuration} infinite ${ANIMATION_CONFIG.animationTiming}`;
const stopIdleAnimations = () => {
clearTimeout(idleTimeout);
container.style.animation = "none";
document.querySelectorAll(ANIMATION_CONFIG.idleSelectors).forEach(element => {
element.style.animation = "none";
});
};
const startIdleAnimations = () => {
idleTimeout = setTimeout(() => {
container.style.animation = animationValue;
document.querySelectorAll(ANIMATION_CONFIG.idleSelectors).forEach(element => {
element.style.animation = animationValue;
});
}, ANIMATION_CONFIG.idleDelayMs);
};
setTimeout(() => {
container.classList.add("visible");
}, ANIMATION_CONFIG.initialDelayMs);
ANIMATION_CONFIG.idleEvents.forEach(eventName => {
document.addEventListener(eventName, stopIdleAnimations);
});
startIdleAnimations();
});