badmfck-api-server 5.0.14 → 5.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/apiServer/APIService.d.ts +2 -0
- package/dist/apiServer/APIService.js +23 -0
- package/dist/apiServer/MonitorService.js +11 -0
- package/dist/apiServer/deployment/Activate.js +1 -1
- package/dist/apiServer/deployment/Backups.js +1 -1
- package/dist/apiServer/deployment/Deploy.js +1 -1
- package/dist/apiServer/deployment/Deployer.js +5 -5
- package/dist/apiServer/deployment/DeployerService.d.ts +12 -0
- package/dist/apiServer/deployment/DeployerService.js +51 -21
- package/dist/apiServer/deployment/HashPassword.d.ts +1 -0
- package/dist/apiServer/deployment/HashPassword.js +91 -0
- package/dist/apiServer/deployment/Restore.js +1 -1
- package/dist/apiServer/deployment/Status.js +1 -1
- package/dist/apiServer/deployment/cli.js +11 -0
- package/dist/apiServer/deployment/cliCommon.d.ts +1 -0
- package/dist/apiServer/deployment/cliCommon.js +4 -0
- package/dist/apiServer/helper/ClientIp.d.ts +2 -0
- package/dist/apiServer/helper/ClientIp.js +28 -0
- package/dist/apiServer/helper/PasswordHash.d.ts +5 -0
- package/dist/apiServer/helper/PasswordHash.js +52 -0
- package/dist/apiServer/monitor/Monitor.d.ts +1 -0
- package/dist/apiServer/monitor/Monitor.js +17 -4
- package/dist/apiServer/monitor/MonitorAuth.d.ts +4 -2
- package/dist/apiServer/monitor/MonitorAuth.js +17 -7
- package/dist/apiServer/monitor/ThreatMonitor.d.ts +65 -0
- package/dist/apiServer/monitor/ThreatMonitor.js +153 -0
- package/dist/apiServer/monitor/index.html +115 -62
- package/dist/apiServer/structures/Interfaces.d.ts +1 -0
- package/monitoring.help.md +46 -0
- package/package.json +1 -1
|
@@ -19,6 +19,7 @@ const SystemInfo_1 = require("./SystemInfo");
|
|
|
19
19
|
const ProcessMonitor_1 = require("./ProcessMonitor");
|
|
20
20
|
const LogFiles_1 = require("./LogFiles");
|
|
21
21
|
const MonitorAuth_1 = require("./MonitorAuth");
|
|
22
|
+
const ThreatMonitor_1 = require("./ThreatMonitor");
|
|
22
23
|
exports.S_MONITOR_REGISTRATE_ACTION = new badmfck_signal_1.Signal();
|
|
23
24
|
exports.S_MONITOR_RESTART_REQUESTED = new badmfck_signal_1.Signal();
|
|
24
25
|
const logMap = {
|
|
@@ -41,6 +42,9 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
|
|
|
41
42
|
super("sm");
|
|
42
43
|
this.apiServiceOptions = options;
|
|
43
44
|
MonitorAuth_1.MonitorAuth.configure({ authFile: options.monitorAuthFile, authDir: options.monitorAuthDir, projectName: options.projectName });
|
|
45
|
+
const plain = MonitorAuth_1.MonitorAuth.plaintextLogins(options.access?.monitor ?? []);
|
|
46
|
+
if (plain.length)
|
|
47
|
+
(0, LogService_1.logError)(`Monitor: password stored as plain text for ${plain.map(l => '"' + l + '"').join(", ")} — these logins are refused; store a hash instead: npx badmfck hash-password`);
|
|
44
48
|
this.registerEndpoints([
|
|
45
49
|
{ ignoreInterceptor: true, endpoint: "html", handler: this.html },
|
|
46
50
|
{ ignoreInterceptor: true, endpoint: "log", handler: this.logs },
|
|
@@ -72,6 +76,10 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
|
|
|
72
76
|
range: "",
|
|
73
77
|
$__range_values: ["week", "day", "hour"]
|
|
74
78
|
} },
|
|
79
|
+
{ ignoreInterceptor: true, endpoint: "threats", handler: this.threats, validationModel: {
|
|
80
|
+
limit: 0,
|
|
81
|
+
$__limit_optional: true
|
|
82
|
+
} },
|
|
75
83
|
{ ignoreInterceptor: true, endpoint: "logfiles", handler: this.logfiles },
|
|
76
84
|
{ ignoreInterceptor: true, endpoint: "logtail", handler: this.logtail, validationModel: {
|
|
77
85
|
source: "",
|
|
@@ -184,9 +192,9 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
|
|
|
184
192
|
const users = await APIService_1.REQ_MONITOR_USERS.request();
|
|
185
193
|
if (!users || users.length === 0)
|
|
186
194
|
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "No users found for monitor access, please set up users first." };
|
|
187
|
-
const { user, error, enrollmentRequired } = MonitorAuth_1.MonitorAuth.authenticate(users, req.data.login, req.data.password, req.data.totp);
|
|
195
|
+
const { user, error, enrollmentRequired } = await MonitorAuth_1.MonitorAuth.authenticate(users, req.data.login, req.data.password, req.data.totp);
|
|
188
196
|
if (!user || error) {
|
|
189
|
-
(0, LogService_1.logWarn)(`Monitor login failed for "${req.data.login}": ${error}`);
|
|
197
|
+
(0, LogService_1.logWarn)(`Monitor login failed for "${req.data.login}" from ${req.ip ?? "unknown"}: ${error}`);
|
|
190
198
|
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: error ?? "Invalid user" };
|
|
191
199
|
}
|
|
192
200
|
if (enrollmentRequired) {
|
|
@@ -202,7 +210,7 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
|
|
|
202
210
|
} };
|
|
203
211
|
}
|
|
204
212
|
const session = MonitorAuth_1.MonitorAuth.createSession(user.login);
|
|
205
|
-
(0, LogService_1.logInfo)(`Monitor login: "${user.login}"`, "Monitor");
|
|
213
|
+
(0, LogService_1.logInfo)(`Monitor login: "${user.login}" from ${req.ip ?? "unknown"}`, "Monitor");
|
|
206
214
|
return { data: {
|
|
207
215
|
token: session.token,
|
|
208
216
|
login: user.login,
|
|
@@ -238,7 +246,7 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
|
|
|
238
246
|
async restart(req) {
|
|
239
247
|
const login = await this.requireAccess(req, "admin");
|
|
240
248
|
const users = await APIService_1.REQ_MONITOR_USERS.request();
|
|
241
|
-
const stepUp = MonitorAuth_1.MonitorAuth.authenticate(users ?? [], login, req.data.password, req.data.totp);
|
|
249
|
+
const stepUp = await MonitorAuth_1.MonitorAuth.authenticate(users ?? [], login, req.data.password, req.data.totp);
|
|
242
250
|
if (!stepUp.user) {
|
|
243
251
|
(0, LogService_1.logWarn)(`Monitor restart re-auth failed for "${login}": ${stepUp.error}`);
|
|
244
252
|
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Re-authentication required: " + (stepUp.error ?? "invalid credentials") };
|
|
@@ -293,6 +301,11 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
|
|
|
293
301
|
const result = await MonitorService_1.REQ_STAT.request(req.data);
|
|
294
302
|
return { data: result };
|
|
295
303
|
}
|
|
304
|
+
async threats(req) {
|
|
305
|
+
await this.requireAccess(req, "logs");
|
|
306
|
+
const limit = Number(req.data.limit) || 50;
|
|
307
|
+
return { data: ThreatMonitor_1.ThreatMonitor.snapshot(limit) };
|
|
308
|
+
}
|
|
296
309
|
async logfiles(req) {
|
|
297
310
|
await this.requireAccess(req, "logs");
|
|
298
311
|
return { data: await (0, LogFiles_1.listLogSources)(this.apiServiceOptions.logFiles) };
|
|
@@ -39,6 +39,8 @@ export declare class MonitorAuth {
|
|
|
39
39
|
static passwordPolicyError(password: string | undefined | null): string | null;
|
|
40
40
|
static compliantUsers(users: IMonitorUser[]): IMonitorUser[];
|
|
41
41
|
static policyReportFor(users: IMonitorUser[]): string[];
|
|
42
|
+
static PLAINTEXT_ERROR: string;
|
|
43
|
+
static plaintextLogins(users: IMonitorUser[]): string[];
|
|
42
44
|
private static base32Decode;
|
|
43
45
|
private static hotp;
|
|
44
46
|
static verifyTotp(login: string, secretBase32: string, code: string): string | null;
|
|
@@ -51,11 +53,11 @@ export declare class MonitorAuth {
|
|
|
51
53
|
private static registerFailure;
|
|
52
54
|
private static clearFailures;
|
|
53
55
|
private static sameSecret;
|
|
54
|
-
static authenticate(users: IMonitorUser[], login: string, password: string, totp?: string): {
|
|
56
|
+
static authenticate(users: IMonitorUser[], login: string, password: string, totp?: string): Promise<{
|
|
55
57
|
user?: IMonitorUser;
|
|
56
58
|
error?: string;
|
|
57
59
|
enrollmentRequired?: boolean;
|
|
58
|
-
}
|
|
60
|
+
}>;
|
|
59
61
|
private static pendingEnrollments;
|
|
60
62
|
static ENROLLMENT_TTL_MS: number;
|
|
61
63
|
static beginEnrollment(login: string, issuer?: string): {
|
|
@@ -8,6 +8,7 @@ const crypto_1 = __importDefault(require("crypto"));
|
|
|
8
8
|
const fs_1 = __importDefault(require("fs"));
|
|
9
9
|
const path_1 = __importDefault(require("path"));
|
|
10
10
|
const LogService_1 = require("../LogService");
|
|
11
|
+
const PasswordHash_1 = require("../helper/PasswordHash");
|
|
11
12
|
class MonitorAuth {
|
|
12
13
|
static ROLE_CAPS = {
|
|
13
14
|
admin: ["dashboard", "logs", "admin"],
|
|
@@ -128,17 +129,23 @@ class MonitorAuth {
|
|
|
128
129
|
}
|
|
129
130
|
static compliantUsers(users) {
|
|
130
131
|
return users.filter(u => u && typeof u.login === "string" && u.login.length > 0
|
|
131
|
-
&&
|
|
132
|
+
&& PasswordHash_1.PasswordHash.isHash(u.password));
|
|
132
133
|
}
|
|
133
134
|
static policyReportFor(users) {
|
|
134
135
|
const out = [];
|
|
135
136
|
for (const u of users || []) {
|
|
136
|
-
const reason = !u?.login ? "login is empty"
|
|
137
|
+
const reason = !u?.login ? "login is empty"
|
|
138
|
+
: PasswordHash_1.PasswordHash.isHash(u.password) ? null
|
|
139
|
+
: MonitorAuth.PLAINTEXT_ERROR;
|
|
137
140
|
if (reason)
|
|
138
141
|
out.push(`${u?.login || "<no login>"}: ${reason}`);
|
|
139
142
|
}
|
|
140
143
|
return out;
|
|
141
144
|
}
|
|
145
|
+
static PLAINTEXT_ERROR = "password is built incorrectly — the config must hold a hash from `npx badmfck hash-password`, not the password itself";
|
|
146
|
+
static plaintextLogins(users) {
|
|
147
|
+
return (users || []).filter(u => u?.login && !PasswordHash_1.PasswordHash.isHash(u.password)).map(u => u.login);
|
|
148
|
+
}
|
|
142
149
|
static base32Decode(input) {
|
|
143
150
|
const A = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
144
151
|
let bits = 0, value = 0;
|
|
@@ -235,7 +242,7 @@ class MonitorAuth {
|
|
|
235
242
|
const x = Buffer.from(String(a), "utf-8"), y = Buffer.from(String(b), "utf-8");
|
|
236
243
|
return x.length === y.length && crypto_1.default.timingSafeEqual(x, y);
|
|
237
244
|
}
|
|
238
|
-
static authenticate(users, login, password, totp) {
|
|
245
|
+
static async authenticate(users, login, password, totp) {
|
|
239
246
|
const locked = MonitorAuth.lockoutRemainingMs(login);
|
|
240
247
|
if (locked > 0)
|
|
241
248
|
return { error: `account locked, try again in ${Math.ceil(locked / 60000)} min` };
|
|
@@ -245,10 +252,13 @@ class MonitorAuth {
|
|
|
245
252
|
MonitorAuth.registerFailure(login);
|
|
246
253
|
return { error: "Invalid user" };
|
|
247
254
|
}
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
255
|
+
if (!PasswordHash_1.PasswordHash.isHash(candidate.password)) {
|
|
256
|
+
const matches = typeof candidate.password === "string" && candidate.password.length > 0
|
|
257
|
+
&& MonitorAuth.sameSecret(candidate.password, password || "");
|
|
258
|
+
MonitorAuth.registerFailure(login);
|
|
259
|
+
return { error: matches ? MonitorAuth.PLAINTEXT_ERROR : "Invalid user" };
|
|
260
|
+
}
|
|
261
|
+
if (!(await PasswordHash_1.PasswordHash.verify(password || "", candidate.password))) {
|
|
252
262
|
MonitorAuth.registerFailure(login);
|
|
253
263
|
return { error: "Invalid user" };
|
|
254
264
|
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
export type TThreatCategory = "scanner" | "injection" | "enumeration" | "auth" | "method" | "not-found";
|
|
2
|
+
export type TThreatLevel = "none" | "suspicious" | "high";
|
|
3
|
+
interface ISample {
|
|
4
|
+
ts: number;
|
|
5
|
+
method: string;
|
|
6
|
+
url: string;
|
|
7
|
+
status: number;
|
|
8
|
+
categories: TThreatCategory[];
|
|
9
|
+
}
|
|
10
|
+
export interface IThreatObservation {
|
|
11
|
+
ip: string;
|
|
12
|
+
method: string;
|
|
13
|
+
url: string;
|
|
14
|
+
status: number;
|
|
15
|
+
ua?: string | null;
|
|
16
|
+
body?: unknown;
|
|
17
|
+
contentLength?: number;
|
|
18
|
+
}
|
|
19
|
+
export declare class ThreatMonitor {
|
|
20
|
+
static HALF_LIFE_MS: number;
|
|
21
|
+
static LEVEL_SUSPICIOUS: number;
|
|
22
|
+
static LEVEL_HIGH: number;
|
|
23
|
+
static ENUM_WINDOW_MS: number;
|
|
24
|
+
static ENUM_DISTINCT_PATHS: number;
|
|
25
|
+
static MAX_IPS: number;
|
|
26
|
+
static MAX_EVENTS: number;
|
|
27
|
+
static MAX_BODY_SCAN: number;
|
|
28
|
+
private static records;
|
|
29
|
+
private static events;
|
|
30
|
+
private static decayed;
|
|
31
|
+
static levelOf(score: number): TThreatLevel;
|
|
32
|
+
private static rank;
|
|
33
|
+
static classify(o: IThreatObservation): TThreatCategory[];
|
|
34
|
+
static observe(o: IThreatObservation): void;
|
|
35
|
+
static snapshot(limit?: number): {
|
|
36
|
+
generatedAt: number;
|
|
37
|
+
settings: {
|
|
38
|
+
halfLifeMinutes: number;
|
|
39
|
+
suspiciousAt: number;
|
|
40
|
+
highAt: number;
|
|
41
|
+
};
|
|
42
|
+
totals: {
|
|
43
|
+
tracked: number;
|
|
44
|
+
suspicious: number;
|
|
45
|
+
high: number;
|
|
46
|
+
};
|
|
47
|
+
offenders: {
|
|
48
|
+
ip: string;
|
|
49
|
+
score: number;
|
|
50
|
+
level: TThreatLevel;
|
|
51
|
+
firstSeen: number;
|
|
52
|
+
lastSeen: number;
|
|
53
|
+
hits: number;
|
|
54
|
+
categories: Partial<Record<TThreatCategory, number>>;
|
|
55
|
+
userAgent: string | null;
|
|
56
|
+
samples: ISample[];
|
|
57
|
+
}[];
|
|
58
|
+
recent: (ISample & {
|
|
59
|
+
ip: string;
|
|
60
|
+
score: number;
|
|
61
|
+
})[];
|
|
62
|
+
};
|
|
63
|
+
static reset(): void;
|
|
64
|
+
}
|
|
65
|
+
export {};
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ThreatMonitor = void 0;
|
|
4
|
+
const LogService_1 = require("../LogService");
|
|
5
|
+
const SCANNER_PATHS = [
|
|
6
|
+
/\/\.(?:env|git|svn|hg|aws|ssh|DS_Store|htaccess|htpasswd|npmrc|dockerenv)(?:[\/.]|$)/i,
|
|
7
|
+
/\/wp-(?:login|admin|content|includes|config|json)/i,
|
|
8
|
+
/\/(?:xmlrpc|phpinfo|phpmyadmin|adminer)\b/i,
|
|
9
|
+
/\/(?:cgi-bin|actuator|server-status|server-info|jmx-console|manager\/html)(?:\/|$)/i,
|
|
10
|
+
/\.(?:php\d?|aspx?|jsp|cgi|pl|cfm)(?:$|\?|\/)/i,
|
|
11
|
+
/(?:etc\/passwd|win\.ini|boot\.ini|id_rsa)/i,
|
|
12
|
+
];
|
|
13
|
+
const INJECTION = [
|
|
14
|
+
/\.\.(?:\/|\\|%2f|%5c)|%2e%2e(?:\/|%2f|%5c)/i,
|
|
15
|
+
/\bunion\b[\s\S]{0,40}\bselect\b|\bor\b\s+['"]?\d+['"]?\s*=\s*['"]?\d+|'\s*(?:or|and)\s+'|;\s*(?:drop|truncate)\s+table/i,
|
|
16
|
+
/<\s*script\b|javascript:|\bon(?:error|load)\s*=/i,
|
|
17
|
+
/\$\{\s*(?:jndi|env|sys|java):/i,
|
|
18
|
+
/(?:;|\|\||&&|\|)\s*(?:cat|wget|curl|bash|nc|whoami)\b|\$\((?:cat|id|whoami|curl|wget)\b/i,
|
|
19
|
+
];
|
|
20
|
+
const ODD_METHODS = new Set(["TRACE", "TRACK", "PROPFIND", "PROPPATCH", "MKCOL", "COPY", "MOVE", "LOCK", "UNLOCK", "CONNECT", "DEBUG", "SEARCH"]);
|
|
21
|
+
const WEIGHT = {
|
|
22
|
+
scanner: 10, injection: 8, enumeration: 10, method: 5, auth: 2, "not-found": 1,
|
|
23
|
+
};
|
|
24
|
+
class ThreatMonitor {
|
|
25
|
+
static HALF_LIFE_MS = 30 * 60 * 1000;
|
|
26
|
+
static LEVEL_SUSPICIOUS = 10;
|
|
27
|
+
static LEVEL_HIGH = 30;
|
|
28
|
+
static ENUM_WINDOW_MS = 5 * 60 * 1000;
|
|
29
|
+
static ENUM_DISTINCT_PATHS = 10;
|
|
30
|
+
static MAX_IPS = 5000;
|
|
31
|
+
static MAX_EVENTS = 500;
|
|
32
|
+
static MAX_BODY_SCAN = 8 * 1024;
|
|
33
|
+
static records = new Map();
|
|
34
|
+
static events = [];
|
|
35
|
+
static decayed(r, now) {
|
|
36
|
+
return r.score * Math.pow(0.5, (now - r.scoreAt) / ThreatMonitor.HALF_LIFE_MS);
|
|
37
|
+
}
|
|
38
|
+
static levelOf(score) {
|
|
39
|
+
return score >= ThreatMonitor.LEVEL_HIGH ? "high" : score >= ThreatMonitor.LEVEL_SUSPICIOUS ? "suspicious" : "none";
|
|
40
|
+
}
|
|
41
|
+
static rank(l) { return l === "high" ? 2 : l === "suspicious" ? 1 : 0; }
|
|
42
|
+
static classify(o) {
|
|
43
|
+
const cats = new Set();
|
|
44
|
+
let target = String(o.url ?? "");
|
|
45
|
+
try {
|
|
46
|
+
target = decodeURIComponent(target);
|
|
47
|
+
}
|
|
48
|
+
catch { }
|
|
49
|
+
if (SCANNER_PATHS.some(r => r.test(target)))
|
|
50
|
+
cats.add("scanner");
|
|
51
|
+
if (INJECTION.some(r => r.test(target)))
|
|
52
|
+
cats.add("injection");
|
|
53
|
+
if (o.status >= 400 && !cats.has("injection") && o.body !== undefined && o.body !== null
|
|
54
|
+
&& !(o.contentLength && o.contentLength > 64 * 1024)) {
|
|
55
|
+
let text = "";
|
|
56
|
+
try {
|
|
57
|
+
text = typeof o.body === "string" ? o.body : JSON.stringify(o.body);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
text = "";
|
|
61
|
+
}
|
|
62
|
+
if (text && INJECTION.some(r => r.test(text.slice(0, ThreatMonitor.MAX_BODY_SCAN))))
|
|
63
|
+
cats.add("injection");
|
|
64
|
+
}
|
|
65
|
+
if (ODD_METHODS.has(String(o.method).toUpperCase()))
|
|
66
|
+
cats.add("method");
|
|
67
|
+
if (o.status === 401 || o.status === 403)
|
|
68
|
+
cats.add("auth");
|
|
69
|
+
if (o.status === 404)
|
|
70
|
+
cats.add("not-found");
|
|
71
|
+
return Array.from(cats);
|
|
72
|
+
}
|
|
73
|
+
static observe(o) {
|
|
74
|
+
if (!o || !o.ip)
|
|
75
|
+
return;
|
|
76
|
+
const cats = ThreatMonitor.classify(o);
|
|
77
|
+
if (cats.length === 0)
|
|
78
|
+
return;
|
|
79
|
+
const now = Date.now();
|
|
80
|
+
let r = ThreatMonitor.records.get(o.ip);
|
|
81
|
+
if (r)
|
|
82
|
+
ThreatMonitor.records.delete(o.ip);
|
|
83
|
+
else
|
|
84
|
+
r = { ip: o.ip, score: 0, scoreAt: now, firstSeen: now, lastSeen: now, hits: 0,
|
|
85
|
+
categories: {}, ua: null, samples: [], notFound: new Map(), enumFlaggedAt: 0 };
|
|
86
|
+
const path = String(o.url ?? "").split("?")[0];
|
|
87
|
+
if (cats.includes("not-found")) {
|
|
88
|
+
r.notFound.set(path, now);
|
|
89
|
+
for (const [p, ts] of r.notFound)
|
|
90
|
+
if (now - ts > ThreatMonitor.ENUM_WINDOW_MS)
|
|
91
|
+
r.notFound.delete(p);
|
|
92
|
+
while (r.notFound.size > 50)
|
|
93
|
+
r.notFound.delete(r.notFound.keys().next().value);
|
|
94
|
+
if (r.notFound.size >= ThreatMonitor.ENUM_DISTINCT_PATHS && now - r.enumFlaggedAt > ThreatMonitor.ENUM_WINDOW_MS) {
|
|
95
|
+
cats.push("enumeration");
|
|
96
|
+
r.enumFlaggedAt = now;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const before = ThreatMonitor.decayed(r, now);
|
|
100
|
+
const add = cats.reduce((sum, c) => sum + WEIGHT[c], 0);
|
|
101
|
+
r.score = before + add;
|
|
102
|
+
r.scoreAt = now;
|
|
103
|
+
r.lastSeen = now;
|
|
104
|
+
r.hits++;
|
|
105
|
+
if (o.ua)
|
|
106
|
+
r.ua = String(o.ua).slice(0, 200);
|
|
107
|
+
for (const c of cats)
|
|
108
|
+
r.categories[c] = (r.categories[c] ?? 0) + 1;
|
|
109
|
+
const sample = { ts: now, method: String(o.method), url: LogService_1.LogService.sanitize(String(o.url ?? "")).slice(0, 200),
|
|
110
|
+
status: o.status, categories: cats };
|
|
111
|
+
r.samples.push(sample);
|
|
112
|
+
if (r.samples.length > 10)
|
|
113
|
+
r.samples.shift();
|
|
114
|
+
ThreatMonitor.records.set(o.ip, r);
|
|
115
|
+
while (ThreatMonitor.records.size > ThreatMonitor.MAX_IPS)
|
|
116
|
+
ThreatMonitor.records.delete(ThreatMonitor.records.keys().next().value);
|
|
117
|
+
if (add >= WEIGHT.auth) {
|
|
118
|
+
ThreatMonitor.events.push({ ...sample, ip: o.ip, score: Math.round(r.score) });
|
|
119
|
+
if (ThreatMonitor.events.length > ThreatMonitor.MAX_EVENTS)
|
|
120
|
+
ThreatMonitor.events.shift();
|
|
121
|
+
}
|
|
122
|
+
const prev = ThreatMonitor.levelOf(before), next = ThreatMonitor.levelOf(r.score);
|
|
123
|
+
if (ThreatMonitor.rank(next) > ThreatMonitor.rank(prev)) {
|
|
124
|
+
const allCats = Object.keys(r.categories).join(",");
|
|
125
|
+
(0, LogService_1.logWarn)(`THREAT ip=${o.ip} level=${next} score=${Math.round(r.score)} categories=${allCats} last=${o.method} ${sample.url}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
static snapshot(limit = 50) {
|
|
129
|
+
const now = Date.now();
|
|
130
|
+
const offenders = Array.from(ThreatMonitor.records.values())
|
|
131
|
+
.map(r => {
|
|
132
|
+
const score = ThreatMonitor.decayed(r, now);
|
|
133
|
+
return { ip: r.ip, score: Math.round(score * 10) / 10, level: ThreatMonitor.levelOf(score),
|
|
134
|
+
firstSeen: r.firstSeen, lastSeen: r.lastSeen, hits: r.hits,
|
|
135
|
+
categories: r.categories, userAgent: r.ua, samples: r.samples.slice().reverse() };
|
|
136
|
+
})
|
|
137
|
+
.filter(o => o.score >= 1)
|
|
138
|
+
.sort((a, b) => b.score - a.score);
|
|
139
|
+
return {
|
|
140
|
+
generatedAt: now,
|
|
141
|
+
settings: { halfLifeMinutes: ThreatMonitor.HALF_LIFE_MS / 60000, suspiciousAt: ThreatMonitor.LEVEL_SUSPICIOUS, highAt: ThreatMonitor.LEVEL_HIGH },
|
|
142
|
+
totals: {
|
|
143
|
+
tracked: offenders.length,
|
|
144
|
+
suspicious: offenders.filter(o => o.level === "suspicious").length,
|
|
145
|
+
high: offenders.filter(o => o.level === "high").length,
|
|
146
|
+
},
|
|
147
|
+
offenders: offenders.slice(0, Math.max(1, Math.min(limit, 500))),
|
|
148
|
+
recent: ThreatMonitor.events.slice(-Math.max(1, Math.min(limit, 500))).reverse(),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
static reset() { ThreatMonitor.records.clear(); ThreatMonitor.events = []; }
|
|
152
|
+
}
|
|
153
|
+
exports.ThreatMonitor = ThreatMonitor;
|