@profullstack/threatcrush 0.11.11 → 0.12.1
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/daemon.js +635 -88
- package/dist/daemon.js.map +1 -1
- package/dist/index.js +1133 -222
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/daemon.js
CHANGED
|
@@ -2022,8 +2022,8 @@ var require_toml = __commonJS({
|
|
|
2022
2022
|
});
|
|
2023
2023
|
|
|
2024
2024
|
// src/daemon/index.ts
|
|
2025
|
-
var
|
|
2026
|
-
var
|
|
2025
|
+
var import_node_fs19 = require("fs");
|
|
2026
|
+
var import_node_path14 = require("path");
|
|
2027
2027
|
|
|
2028
2028
|
// src/daemon/paths.ts
|
|
2029
2029
|
var import_node_fs = require("fs");
|
|
@@ -2301,11 +2301,62 @@ function closeDB() {
|
|
|
2301
2301
|
}
|
|
2302
2302
|
}
|
|
2303
2303
|
|
|
2304
|
+
// src/daemon/firewall/backoff.ts
|
|
2305
|
+
function fibonacciMinutes(strike) {
|
|
2306
|
+
const n = Math.max(1, Math.floor(strike));
|
|
2307
|
+
let prev = 1;
|
|
2308
|
+
let curr = 1;
|
|
2309
|
+
for (let i = 1; i < n; i++) {
|
|
2310
|
+
const next = prev + curr;
|
|
2311
|
+
prev = curr;
|
|
2312
|
+
curr = next;
|
|
2313
|
+
}
|
|
2314
|
+
return curr;
|
|
2315
|
+
}
|
|
2316
|
+
function banSeconds(strike, maxSeconds) {
|
|
2317
|
+
const seconds = fibonacciMinutes(strike) * 60;
|
|
2318
|
+
return Math.min(seconds, Math.max(60, maxSeconds));
|
|
2319
|
+
}
|
|
2320
|
+
function recordStrike(strikes, ip, now, memorySeconds) {
|
|
2321
|
+
const existing = strikes[ip];
|
|
2322
|
+
const expired = !existing || now - existing.last > memorySeconds * 1e3;
|
|
2323
|
+
const count = expired ? 1 : existing.count + 1;
|
|
2324
|
+
strikes[ip] = { count, last: now };
|
|
2325
|
+
return count;
|
|
2326
|
+
}
|
|
2327
|
+
function pruneStrikes(strikes, now, memorySeconds) {
|
|
2328
|
+
const kept = {};
|
|
2329
|
+
for (const [ip, strike] of Object.entries(strikes)) {
|
|
2330
|
+
if (now - strike.last <= memorySeconds * 1e3) kept[ip] = strike;
|
|
2331
|
+
}
|
|
2332
|
+
return kept;
|
|
2333
|
+
}
|
|
2334
|
+
function parseDuration(value) {
|
|
2335
|
+
if (typeof value === "number") return Number.isFinite(value) && value > 0 ? value : null;
|
|
2336
|
+
if (!value) return null;
|
|
2337
|
+
const match = String(value).trim().match(/^(\d+)\s*(s|m|h|d)?$/i);
|
|
2338
|
+
if (!match) return null;
|
|
2339
|
+
const units = { s: 1, m: 60, h: 3600, d: 86400 };
|
|
2340
|
+
return Number(match[1]) * (units[(match[2] || "s").toLowerCase()] ?? 1);
|
|
2341
|
+
}
|
|
2342
|
+
function formatDuration(seconds) {
|
|
2343
|
+
if (!Number.isFinite(seconds) || seconds <= 0) return "0s";
|
|
2344
|
+
const d = Math.floor(seconds / 86400);
|
|
2345
|
+
const h = Math.floor(seconds % 86400 / 3600);
|
|
2346
|
+
const m = Math.floor(seconds % 3600 / 60);
|
|
2347
|
+
const s = Math.floor(seconds % 60);
|
|
2348
|
+
if (d > 0) return h > 0 ? `${d}d ${h}h` : `${d}d`;
|
|
2349
|
+
if (h > 0) return m > 0 ? `${h}h ${m}m` : `${h}h`;
|
|
2350
|
+
if (m > 0) return s > 0 && m < 10 ? `${m}m ${s}s` : `${m}m`;
|
|
2351
|
+
return `${s}s`;
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2304
2354
|
// src/daemon/ipc-server.ts
|
|
2305
2355
|
var IpcServer = class {
|
|
2306
|
-
constructor(version, moduleHost) {
|
|
2356
|
+
constructor(version, moduleHost, remediation) {
|
|
2307
2357
|
this.version = version;
|
|
2308
2358
|
this.moduleHost = moduleHost;
|
|
2359
|
+
this.remediation = remediation;
|
|
2309
2360
|
bus.on("event", (event) => {
|
|
2310
2361
|
this.counters.events++;
|
|
2311
2362
|
if (event.severity === "medium" || event.severity === "high" || event.severity === "critical") {
|
|
@@ -2322,6 +2373,7 @@ var IpcServer = class {
|
|
|
2322
2373
|
}
|
|
2323
2374
|
version;
|
|
2324
2375
|
moduleHost;
|
|
2376
|
+
remediation;
|
|
2325
2377
|
server = null;
|
|
2326
2378
|
clients = /* @__PURE__ */ new Map();
|
|
2327
2379
|
nextClientId = 1;
|
|
@@ -2461,6 +2513,54 @@ var IpcServer = class {
|
|
|
2461
2513
|
case "subscribe":
|
|
2462
2514
|
for (const ch of req.params.channels) client.subscriptions.add(ch);
|
|
2463
2515
|
return this.send(client, { id: req.id, ok: true, result: { subscribed: [...client.subscriptions] } });
|
|
2516
|
+
case "blocklist": {
|
|
2517
|
+
if (!this.remediation) {
|
|
2518
|
+
return this.send(client, { id: req.id, ok: false, error: "remediation is not running" });
|
|
2519
|
+
}
|
|
2520
|
+
const status = this.remediation.status();
|
|
2521
|
+
const reply = {
|
|
2522
|
+
entries: this.remediation.getBlocklist().map((entry) => ({
|
|
2523
|
+
ip: entry.ip,
|
|
2524
|
+
reason: entry.reason,
|
|
2525
|
+
blocked_at: entry.blocked_at,
|
|
2526
|
+
expires_at: entry.expires_at,
|
|
2527
|
+
strikes: entry.strikes,
|
|
2528
|
+
source: entry.source,
|
|
2529
|
+
dry_run: entry.dry_run
|
|
2530
|
+
})),
|
|
2531
|
+
protected: this.remediation.getProtected(),
|
|
2532
|
+
enabled: status.enabled,
|
|
2533
|
+
dry_run: status.dry_run,
|
|
2534
|
+
backend: status.backend,
|
|
2535
|
+
min_severity: status.min_severity,
|
|
2536
|
+
warning: status.warning
|
|
2537
|
+
};
|
|
2538
|
+
return this.send(client, { id: req.id, ok: true, result: reply });
|
|
2539
|
+
}
|
|
2540
|
+
case "block": {
|
|
2541
|
+
if (!this.remediation) {
|
|
2542
|
+
return this.send(client, { id: req.id, ok: false, error: "remediation is not running" });
|
|
2543
|
+
}
|
|
2544
|
+
const ttl = parseDuration(req.params?.ttl) ?? void 0;
|
|
2545
|
+
const result = await this.remediation.ban(req.params.ip, req.params.reason || "banned by operator", {
|
|
2546
|
+
ttlSeconds: ttl,
|
|
2547
|
+
source: "manual"
|
|
2548
|
+
});
|
|
2549
|
+
if (!result.ok) {
|
|
2550
|
+
return this.send(client, { id: req.id, ok: false, error: result.error || "ban failed" });
|
|
2551
|
+
}
|
|
2552
|
+
return this.send(client, { id: req.id, ok: true, result: result.entry });
|
|
2553
|
+
}
|
|
2554
|
+
case "unblock": {
|
|
2555
|
+
if (!this.remediation) {
|
|
2556
|
+
return this.send(client, { id: req.id, ok: false, error: "remediation is not running" });
|
|
2557
|
+
}
|
|
2558
|
+
const result = await this.remediation.unban(req.params.ip, { forget: req.params.forget !== false });
|
|
2559
|
+
if (!result.ok) {
|
|
2560
|
+
return this.send(client, { id: req.id, ok: false, error: result.error || "unban failed" });
|
|
2561
|
+
}
|
|
2562
|
+
return this.send(client, { id: req.id, ok: true, result: { ip: req.params.ip } });
|
|
2563
|
+
}
|
|
2464
2564
|
case "shutdown":
|
|
2465
2565
|
if (!tokensMatch(this.controlToken, req.params?.token)) {
|
|
2466
2566
|
return this.send(client, {
|
|
@@ -2620,9 +2720,10 @@ var import_node_fs6 = require("fs");
|
|
|
2620
2720
|
var import_node_readline = require("readline");
|
|
2621
2721
|
|
|
2622
2722
|
// src/core/log-parser.ts
|
|
2623
|
-
var NGINX_REGEX = /^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) \S+" (\d{3}) (\d+) "[^"]*" "([^"]*)"/;
|
|
2624
|
-
var
|
|
2625
|
-
var
|
|
2723
|
+
var NGINX_REGEX = /^(?:(\S+) )?(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) \S+" (\d{3}) (\d+) "[^"]*" "([^"]*)"/;
|
|
2724
|
+
var TIMESTAMP = String.raw`(\w{3}\s+\d+\s+[\d:]+|\d{4}-\d{2}-\d{2}T[\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)`;
|
|
2725
|
+
var AUTH_REGEX = new RegExp(`^${TIMESTAMP}\\s+\\S+\\s+(\\S+?)(?:\\[\\d+\\])?:\\s+(.*)`);
|
|
2726
|
+
var SYSLOG_REGEX = new RegExp(`^${TIMESTAMP}\\s+\\S+\\s+(\\S+?)(?:\\[\\d+\\])?:\\s+(.*)`);
|
|
2626
2727
|
var IP_REGEX = /(?:from|FROM)\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
|
|
2627
2728
|
var INVALID_USER_REGEX = /(?:for\s+invalid\s+user)\s+(\S+?)(?:\s+from|\s*$)/;
|
|
2628
2729
|
var USER_REGEX = /(?:for|user)\s+(\S+?)(?:\s+from|\s*$)/;
|
|
@@ -2652,26 +2753,37 @@ var ATTACK_PATTERNS = {
|
|
|
2652
2753
|
/windows\/system32/i
|
|
2653
2754
|
],
|
|
2654
2755
|
rfi: [
|
|
2655
|
-
|
|
2756
|
+
// A remote URL pointing at something executable — the actual shape of a
|
|
2757
|
+
// remote file include (`?page=http://evil.tld/shell.txt`).
|
|
2758
|
+
//
|
|
2759
|
+
// This used to be `(?:https?|ftp):\/\/.*\?`, i.e. *any* URL carrying a
|
|
2760
|
+
// query string. A URL inside a query parameter is ordinary web design —
|
|
2761
|
+
// readers, share links, oembed, feed proxies — so on rssamplifier.com every
|
|
2762
|
+
// `/<feed>/read?p=https://…` hit was logged as a CRITICAL attack. With
|
|
2763
|
+
// auto-defence enforcing, that pattern bans readers, which is precisely the
|
|
2764
|
+
// failure PRD 0010 is written to prevent.
|
|
2765
|
+
/(?:https?|ftp):\/\/\S+\.(?:php|phtml|phar|asp|aspx|jsp|txt|sh|pl|py|cgi)(?:[?#%\s]|$)/i,
|
|
2656
2766
|
/php:\/\/(?:input|filter)/i,
|
|
2657
|
-
/data:\/\//i
|
|
2767
|
+
/(?:data|expect|zip|phar):\/\//i
|
|
2658
2768
|
]
|
|
2659
2769
|
};
|
|
2660
2770
|
function parseNginxLog(line) {
|
|
2661
2771
|
const match = line.match(NGINX_REGEX);
|
|
2662
2772
|
if (!match) return null;
|
|
2773
|
+
const fields = {
|
|
2774
|
+
ip: match[2],
|
|
2775
|
+
method: match[4],
|
|
2776
|
+
path: match[5],
|
|
2777
|
+
status: match[6],
|
|
2778
|
+
size: match[7],
|
|
2779
|
+
user_agent: match[8]
|
|
2780
|
+
};
|
|
2781
|
+
if (match[1]) fields.host = match[1];
|
|
2663
2782
|
return {
|
|
2664
|
-
timestamp: parseNginxTimestamp(match[
|
|
2783
|
+
timestamp: parseNginxTimestamp(match[3]),
|
|
2665
2784
|
raw: line,
|
|
2666
2785
|
source: "nginx",
|
|
2667
|
-
fields
|
|
2668
|
-
ip: match[1],
|
|
2669
|
-
method: match[3],
|
|
2670
|
-
path: match[4],
|
|
2671
|
-
status: match[5],
|
|
2672
|
-
size: match[6],
|
|
2673
|
-
user_agent: match[7]
|
|
2674
|
-
}
|
|
2786
|
+
fields
|
|
2675
2787
|
};
|
|
2676
2788
|
}
|
|
2677
2789
|
function parseAuthLog(line) {
|
|
@@ -2707,17 +2819,23 @@ function parseSyslog(line) {
|
|
|
2707
2819
|
}
|
|
2708
2820
|
function detectAttackPattern(path) {
|
|
2709
2821
|
const candidates = /* @__PURE__ */ new Set([path]);
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2822
|
+
const seeds = [path, path.includes("+") ? path.replace(/\+/g, " ") : null].filter(
|
|
2823
|
+
(s) => s !== null
|
|
2824
|
+
);
|
|
2825
|
+
for (const seed of seeds) {
|
|
2826
|
+
candidates.add(seed);
|
|
2827
|
+
let current = seed;
|
|
2828
|
+
for (let i = 0; i < 2; i++) {
|
|
2829
|
+
let decoded = null;
|
|
2830
|
+
try {
|
|
2831
|
+
decoded = decodeURIComponent(current);
|
|
2832
|
+
} catch {
|
|
2833
|
+
decoded = null;
|
|
2834
|
+
}
|
|
2835
|
+
if (decoded === null || decoded === current) break;
|
|
2836
|
+
candidates.add(decoded);
|
|
2837
|
+
current = decoded;
|
|
2717
2838
|
}
|
|
2718
|
-
if (decoded === null || decoded === current) break;
|
|
2719
|
-
candidates.add(decoded);
|
|
2720
|
-
current = decoded;
|
|
2721
2839
|
}
|
|
2722
2840
|
for (const [type, patterns] of Object.entries(ATTACK_PATTERNS)) {
|
|
2723
2841
|
for (const pattern of patterns) {
|
|
@@ -2743,6 +2861,10 @@ function parseNginxTimestamp(s) {
|
|
|
2743
2861
|
return Number.isNaN(d.getTime()) ? /* @__PURE__ */ new Date() : d;
|
|
2744
2862
|
}
|
|
2745
2863
|
function parseSyslogTimestamp(s) {
|
|
2864
|
+
if (/^\d{4}-\d{2}-\d{2}T/.test(s)) {
|
|
2865
|
+
const iso = new Date(s);
|
|
2866
|
+
return Number.isNaN(iso.getTime()) ? /* @__PURE__ */ new Date() : iso;
|
|
2867
|
+
}
|
|
2746
2868
|
const now = /* @__PURE__ */ new Date();
|
|
2747
2869
|
let d = /* @__PURE__ */ new Date(`${s} ${now.getFullYear()}`);
|
|
2748
2870
|
if (Number.isNaN(d.getTime())) return now;
|
|
@@ -2833,6 +2955,7 @@ var LogWatcher = class {
|
|
|
2833
2955
|
let severity = "info";
|
|
2834
2956
|
let message = line;
|
|
2835
2957
|
let sourceIp;
|
|
2958
|
+
let host;
|
|
2836
2959
|
if (parsed.source === "auth") {
|
|
2837
2960
|
const entry = parseAuthLog(line);
|
|
2838
2961
|
if (!entry) return;
|
|
@@ -2856,6 +2979,7 @@ var LogWatcher = class {
|
|
|
2856
2979
|
sourceIp = entry.fields.ip;
|
|
2857
2980
|
const status = parseInt(entry.fields.status, 10);
|
|
2858
2981
|
const attack = detectAttackPattern(entry.fields.path);
|
|
2982
|
+
host = entry.fields.host;
|
|
2859
2983
|
if (attack) {
|
|
2860
2984
|
severity = "critical";
|
|
2861
2985
|
message = `Attack [${attack.toUpperCase()}]: ${entry.fields.method} ${entry.fields.path}`;
|
|
@@ -2877,7 +3001,8 @@ var LogWatcher = class {
|
|
|
2877
3001
|
category: src.category,
|
|
2878
3002
|
severity,
|
|
2879
3003
|
message,
|
|
2880
|
-
source_ip: sourceIp
|
|
3004
|
+
source_ip: sourceIp,
|
|
3005
|
+
...host ? { details: { host } } : {}
|
|
2881
3006
|
};
|
|
2882
3007
|
try {
|
|
2883
3008
|
insertEvent(event);
|
|
@@ -3432,6 +3557,7 @@ function loadConfig(configPath) {
|
|
|
3432
3557
|
api: { ...DEFAULT_CONFIG.api, ...parsed.api },
|
|
3433
3558
|
alerts: parsed.alerts || {},
|
|
3434
3559
|
modules: { ...DEFAULT_CONFIG.modules, ...parsed.modules },
|
|
3560
|
+
remediation: parsed.remediation,
|
|
3435
3561
|
license: parsed.license
|
|
3436
3562
|
};
|
|
3437
3563
|
} catch {
|
|
@@ -8656,12 +8782,132 @@ function loadAllRules(customDir) {
|
|
|
8656
8782
|
|
|
8657
8783
|
// src/daemon/firewall/adapters.ts
|
|
8658
8784
|
var import_node_child_process3 = require("child_process");
|
|
8785
|
+
var import_node_fs17 = require("fs");
|
|
8786
|
+
var import_node_path13 = require("path");
|
|
8659
8787
|
var import_node_net2 = require("net");
|
|
8660
8788
|
function assertValidFirewallIp(ip) {
|
|
8661
8789
|
if ((0, import_node_net2.isIP)(ip) !== 4) {
|
|
8662
8790
|
throw new Error(`Invalid IPv4 address: ${ip}`);
|
|
8663
8791
|
}
|
|
8664
8792
|
}
|
|
8793
|
+
function assertBannableIp(ip) {
|
|
8794
|
+
if ((0, import_node_net2.isIP)(ip) === 0) {
|
|
8795
|
+
throw new Error(`Invalid IP address: ${ip}`);
|
|
8796
|
+
}
|
|
8797
|
+
}
|
|
8798
|
+
function writeIfAbsent(path, contents) {
|
|
8799
|
+
(0, import_node_fs17.mkdirSync)((0, import_node_path13.dirname)(path), { recursive: true });
|
|
8800
|
+
try {
|
|
8801
|
+
(0, import_node_fs17.writeFileSync)(path, contents, { flag: "wx" });
|
|
8802
|
+
} catch (err) {
|
|
8803
|
+
if (err.code !== "EEXIST") throw err;
|
|
8804
|
+
}
|
|
8805
|
+
}
|
|
8806
|
+
var FAIL2BAN_JAIL = "threatcrush";
|
|
8807
|
+
var FAIL2BAN_FILTER_FILE = "/etc/fail2ban/filter.d/threatcrush.conf";
|
|
8808
|
+
var FAIL2BAN_JAIL_FILE = "/etc/fail2ban/jail.d/threatcrush.conf";
|
|
8809
|
+
var Fail2banAdapter = class {
|
|
8810
|
+
constructor(jail = FAIL2BAN_JAIL, backstopSeconds = 86400) {
|
|
8811
|
+
this.jail = jail;
|
|
8812
|
+
this.backstopSeconds = backstopSeconds;
|
|
8813
|
+
}
|
|
8814
|
+
jail;
|
|
8815
|
+
backstopSeconds;
|
|
8816
|
+
name = "fail2ban";
|
|
8817
|
+
enforces = true;
|
|
8818
|
+
jailReady = false;
|
|
8819
|
+
isAvailable() {
|
|
8820
|
+
const result = (0, import_node_child_process3.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
|
|
8821
|
+
return result.status === 0;
|
|
8822
|
+
}
|
|
8823
|
+
client(args) {
|
|
8824
|
+
return (0, import_node_child_process3.execFileSync)("fail2ban-client", args, {
|
|
8825
|
+
encoding: "utf-8",
|
|
8826
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
8827
|
+
});
|
|
8828
|
+
}
|
|
8829
|
+
/**
|
|
8830
|
+
* Create the jail if it is missing. Writing to /etc/fail2ban needs root; when
|
|
8831
|
+
* we cannot, the error surfaces to the caller instead of a ban that silently
|
|
8832
|
+
* goes nowhere.
|
|
8833
|
+
*/
|
|
8834
|
+
ensureJail() {
|
|
8835
|
+
if (this.jailReady) return;
|
|
8836
|
+
try {
|
|
8837
|
+
this.client(["status", this.jail]);
|
|
8838
|
+
this.jailReady = true;
|
|
8839
|
+
return;
|
|
8840
|
+
} catch {
|
|
8841
|
+
}
|
|
8842
|
+
writeIfAbsent(
|
|
8843
|
+
FAIL2BAN_FILTER_FILE,
|
|
8844
|
+
[
|
|
8845
|
+
"# Installed by ThreatCrush. Intentionally matches nothing:",
|
|
8846
|
+
"# detection happens in threatcrushd, this jail only executes bans.",
|
|
8847
|
+
"[Definition]",
|
|
8848
|
+
"failregex = ^threatcrush-never-matches <HOST>$",
|
|
8849
|
+
"ignoreregex =",
|
|
8850
|
+
""
|
|
8851
|
+
].join("\n")
|
|
8852
|
+
);
|
|
8853
|
+
writeIfAbsent(
|
|
8854
|
+
FAIL2BAN_JAIL_FILE,
|
|
8855
|
+
[
|
|
8856
|
+
"# Installed by ThreatCrush \u2014 bans arrive via `fail2ban-client set threatcrush banip`.",
|
|
8857
|
+
"# bantime is only a backstop; threatcrushd unbans on its own schedule.",
|
|
8858
|
+
`[${this.jail}]`,
|
|
8859
|
+
"enabled = true",
|
|
8860
|
+
"filter = threatcrush",
|
|
8861
|
+
"backend = polling",
|
|
8862
|
+
"logpath = /var/log/threatcrush/threatcrushd.log",
|
|
8863
|
+
"maxretry = 1000000",
|
|
8864
|
+
"findtime = 1",
|
|
8865
|
+
`bantime = ${this.backstopSeconds}`,
|
|
8866
|
+
""
|
|
8867
|
+
].join("\n")
|
|
8868
|
+
);
|
|
8869
|
+
this.client(["reload", this.jail]);
|
|
8870
|
+
this.jailReady = true;
|
|
8871
|
+
}
|
|
8872
|
+
async block(ip) {
|
|
8873
|
+
assertBannableIp(ip);
|
|
8874
|
+
this.ensureJail();
|
|
8875
|
+
this.client(["set", this.jail, "banip", ip]);
|
|
8876
|
+
}
|
|
8877
|
+
async unblock(ip) {
|
|
8878
|
+
assertBannableIp(ip);
|
|
8879
|
+
try {
|
|
8880
|
+
this.client(["set", this.jail, "unbanip", ip]);
|
|
8881
|
+
} catch {
|
|
8882
|
+
}
|
|
8883
|
+
}
|
|
8884
|
+
async isBlocked(ip) {
|
|
8885
|
+
assertBannableIp(ip);
|
|
8886
|
+
return (await this.listBlocked()).includes(ip);
|
|
8887
|
+
}
|
|
8888
|
+
async listBlocked() {
|
|
8889
|
+
try {
|
|
8890
|
+
return parseBannedList(this.client(["get", this.jail, "banned"]));
|
|
8891
|
+
} catch {
|
|
8892
|
+
try {
|
|
8893
|
+
const status = this.client(["status", this.jail]);
|
|
8894
|
+
const line = status.split("\n").find((l) => /Banned IP list:/i.test(l));
|
|
8895
|
+
if (!line) return [];
|
|
8896
|
+
return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net2.isIP)(s) !== 0);
|
|
8897
|
+
} catch {
|
|
8898
|
+
return [];
|
|
8899
|
+
}
|
|
8900
|
+
}
|
|
8901
|
+
}
|
|
8902
|
+
};
|
|
8903
|
+
function parseBannedList(output) {
|
|
8904
|
+
const found = [];
|
|
8905
|
+
for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
|
|
8906
|
+
if ((0, import_node_net2.isIP)(match[1]) !== 0) found.push(match[1]);
|
|
8907
|
+
}
|
|
8908
|
+
if (found.length > 0) return found;
|
|
8909
|
+
return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net2.isIP)(s) !== 0);
|
|
8910
|
+
}
|
|
8665
8911
|
var NftablesAdapter = class {
|
|
8666
8912
|
name = "nftables";
|
|
8667
8913
|
table = "threatcrush";
|
|
@@ -8765,6 +9011,7 @@ var IptablesAdapter = class {
|
|
|
8765
9011
|
};
|
|
8766
9012
|
var DryRunAdapter = class {
|
|
8767
9013
|
name = "dry-run";
|
|
9014
|
+
enforces = false;
|
|
8768
9015
|
blocked = /* @__PURE__ */ new Set();
|
|
8769
9016
|
isAvailable() {
|
|
8770
9017
|
return true;
|
|
@@ -8785,7 +9032,19 @@ var DryRunAdapter = class {
|
|
|
8785
9032
|
return [...this.blocked];
|
|
8786
9033
|
}
|
|
8787
9034
|
};
|
|
8788
|
-
function detectFirewallAdapter() {
|
|
9035
|
+
function detectFirewallAdapter(backend = "auto") {
|
|
9036
|
+
const byName = {
|
|
9037
|
+
fail2ban: () => new Fail2banAdapter(),
|
|
9038
|
+
nftables: () => new NftablesAdapter(),
|
|
9039
|
+
iptables: () => new IptablesAdapter(),
|
|
9040
|
+
"dry-run": () => new DryRunAdapter()
|
|
9041
|
+
};
|
|
9042
|
+
if (backend !== "auto") {
|
|
9043
|
+
const chosen = byName[backend]?.();
|
|
9044
|
+
if (chosen?.isAvailable()) return chosen;
|
|
9045
|
+
}
|
|
9046
|
+
const f2b = new Fail2banAdapter();
|
|
9047
|
+
if (f2b.isAvailable()) return f2b;
|
|
8789
9048
|
const nft = new NftablesAdapter();
|
|
8790
9049
|
if (nft.isAvailable()) return nft;
|
|
8791
9050
|
const ipt = new IptablesAdapter();
|
|
@@ -8794,13 +9053,127 @@ function detectFirewallAdapter() {
|
|
|
8794
9053
|
}
|
|
8795
9054
|
|
|
8796
9055
|
// src/daemon/firewall/remediation.ts
|
|
8797
|
-
var
|
|
9056
|
+
var import_node_fs18 = require("fs");
|
|
9057
|
+
var import_node_net4 = require("net");
|
|
9058
|
+
|
|
9059
|
+
// src/daemon/firewall/protected.ts
|
|
9060
|
+
var import_node_child_process4 = require("child_process");
|
|
9061
|
+
var import_node_net3 = require("net");
|
|
9062
|
+
var DEFAULT_PROTECTED = [
|
|
9063
|
+
"127.0.0.0/8",
|
|
9064
|
+
"::1/128",
|
|
9065
|
+
"10.0.0.0/8",
|
|
9066
|
+
"172.16.0.0/12",
|
|
9067
|
+
"192.168.0.0/16",
|
|
9068
|
+
"169.254.0.0/16",
|
|
9069
|
+
"fc00::/7",
|
|
9070
|
+
"fe80::/10"
|
|
9071
|
+
];
|
|
9072
|
+
function ipToBytes(ip) {
|
|
9073
|
+
const version = (0, import_node_net3.isIP)(ip);
|
|
9074
|
+
if (version === 4) return v4ToBytes(ip);
|
|
9075
|
+
if (version === 6) return v6ToBytes(ip);
|
|
9076
|
+
return null;
|
|
9077
|
+
}
|
|
9078
|
+
function v4ToBytes(ip) {
|
|
9079
|
+
const parts = ip.split(".");
|
|
9080
|
+
if (parts.length !== 4) return null;
|
|
9081
|
+
const bytes = new Uint8Array(4);
|
|
9082
|
+
for (let i = 0; i < 4; i++) {
|
|
9083
|
+
const n = Number(parts[i]);
|
|
9084
|
+
if (!Number.isInteger(n) || n < 0 || n > 255) return null;
|
|
9085
|
+
bytes[i] = n;
|
|
9086
|
+
}
|
|
9087
|
+
return bytes;
|
|
9088
|
+
}
|
|
9089
|
+
function v6ToBytes(ip) {
|
|
9090
|
+
const bare = ip.split("%")[0];
|
|
9091
|
+
const [headText, tailText] = bare.split("::", 2);
|
|
9092
|
+
const head = headText ? headText.split(":") : [];
|
|
9093
|
+
const tail = tailText !== void 0 ? tailText ? tailText.split(":") : [] : null;
|
|
9094
|
+
const groups = [];
|
|
9095
|
+
const pushGroup = (group) => {
|
|
9096
|
+
if (group.includes(".")) {
|
|
9097
|
+
const v4 = v4ToBytes(group);
|
|
9098
|
+
if (!v4) return false;
|
|
9099
|
+
groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
|
|
9100
|
+
return true;
|
|
9101
|
+
}
|
|
9102
|
+
if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return false;
|
|
9103
|
+
groups.push(parseInt(group, 16));
|
|
9104
|
+
return true;
|
|
9105
|
+
};
|
|
9106
|
+
for (const group of head) if (!pushGroup(group)) return null;
|
|
9107
|
+
const headCount = groups.length;
|
|
9108
|
+
if (tail === null) {
|
|
9109
|
+
if (headCount !== 8) return null;
|
|
9110
|
+
} else {
|
|
9111
|
+
const tailGroups = [];
|
|
9112
|
+
const saved = groups.length;
|
|
9113
|
+
for (const group of tail) if (!pushGroup(group)) return null;
|
|
9114
|
+
tailGroups.push(...groups.splice(saved));
|
|
9115
|
+
const zeros = 8 - headCount - tailGroups.length;
|
|
9116
|
+
if (zeros < 0) return null;
|
|
9117
|
+
for (let i = 0; i < zeros; i++) groups.push(0);
|
|
9118
|
+
groups.push(...tailGroups);
|
|
9119
|
+
}
|
|
9120
|
+
if (groups.length !== 8) return null;
|
|
9121
|
+
const bytes = new Uint8Array(16);
|
|
9122
|
+
for (let i = 0; i < 8; i++) {
|
|
9123
|
+
bytes[i * 2] = groups[i] >> 8 & 255;
|
|
9124
|
+
bytes[i * 2 + 1] = groups[i] & 255;
|
|
9125
|
+
}
|
|
9126
|
+
return bytes;
|
|
9127
|
+
}
|
|
9128
|
+
function ipMatches(ip, entry) {
|
|
9129
|
+
const [network, prefixText] = entry.trim().split("/");
|
|
9130
|
+
const target = ipToBytes(ip);
|
|
9131
|
+
const base = ipToBytes(network);
|
|
9132
|
+
if (!target || !base || target.length !== base.length) return false;
|
|
9133
|
+
const bits = prefixText === void 0 ? base.length * 8 : Number(prefixText);
|
|
9134
|
+
if (!Number.isInteger(bits) || bits < 0 || bits > base.length * 8) return false;
|
|
9135
|
+
const wholeBytes = Math.floor(bits / 8);
|
|
9136
|
+
for (let i = 0; i < wholeBytes; i++) {
|
|
9137
|
+
if (target[i] !== base[i]) return false;
|
|
9138
|
+
}
|
|
9139
|
+
const remainder = bits % 8;
|
|
9140
|
+
if (remainder === 0) return true;
|
|
9141
|
+
const mask = 255 << 8 - remainder & 255;
|
|
9142
|
+
return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
|
|
9143
|
+
}
|
|
9144
|
+
function isProtected(ip, list) {
|
|
9145
|
+
return list.some((entry) => ipMatches(ip, entry));
|
|
9146
|
+
}
|
|
9147
|
+
function currentSshClient(env2 = process.env) {
|
|
9148
|
+
const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
|
|
9149
|
+
if (!source) return null;
|
|
9150
|
+
const ip = source.trim().split(/\s+/)[0];
|
|
9151
|
+
return ip && (0, import_node_net3.isIP)(ip) ? ip : null;
|
|
9152
|
+
}
|
|
9153
|
+
function defaultGateways() {
|
|
9154
|
+
const found = /* @__PURE__ */ new Set();
|
|
9155
|
+
for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
|
|
9156
|
+
try {
|
|
9157
|
+
const out = (0, import_node_child_process4.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
|
|
9158
|
+
for (const line of out.split("\n")) {
|
|
9159
|
+
const match = line.match(/\bvia\s+(\S+)/);
|
|
9160
|
+
if (match && (0, import_node_net3.isIP)(match[1])) found.add(match[1]);
|
|
9161
|
+
}
|
|
9162
|
+
} catch {
|
|
9163
|
+
}
|
|
9164
|
+
}
|
|
9165
|
+
return [...found];
|
|
9166
|
+
}
|
|
9167
|
+
|
|
9168
|
+
// src/daemon/firewall/remediation.ts
|
|
8798
9169
|
var DEFAULT_CONFIG2 = {
|
|
8799
9170
|
enabled: true,
|
|
8800
|
-
dry_run:
|
|
8801
|
-
default_ttl_seconds: 3600,
|
|
9171
|
+
dry_run: false,
|
|
8802
9172
|
min_severity: "high",
|
|
8803
|
-
|
|
9173
|
+
max_ban_seconds: 86400,
|
|
9174
|
+
strike_memory_seconds: 86400,
|
|
9175
|
+
allowlist: [],
|
|
9176
|
+
protect_current_ssh_client: true
|
|
8804
9177
|
};
|
|
8805
9178
|
var SEVERITY_RANK4 = {
|
|
8806
9179
|
info: 0,
|
|
@@ -8809,135 +9182,274 @@ var SEVERITY_RANK4 = {
|
|
|
8809
9182
|
high: 3,
|
|
8810
9183
|
critical: 4
|
|
8811
9184
|
};
|
|
9185
|
+
function explainBlockFailure(err, backend) {
|
|
9186
|
+
const raw = err.message || String(err);
|
|
9187
|
+
const denied = /not permitted|EACCES|EPERM|permission denied|must be root/i.test(raw);
|
|
9188
|
+
if (!denied) return `${raw} (backend: ${backend})`;
|
|
9189
|
+
const who = typeof process.getuid === "function" && process.getuid() === 0 ? "as root" : `as uid ${typeof process.getuid === "function" ? process.getuid() : "?"}`;
|
|
9190
|
+
return `threatcrushd is running ${who} and cannot manage ${backend}. A ban is written by the daemon, not by whoever asked for it \u2014 run the daemon as root: sudo threatcrush install-service && sudo systemctl enable --now threatcrushd`;
|
|
9191
|
+
}
|
|
8812
9192
|
var RemediationManager = class {
|
|
8813
9193
|
constructor(adapter, bus2, config) {
|
|
8814
9194
|
this.adapter = adapter;
|
|
8815
9195
|
this.bus = bus2;
|
|
8816
9196
|
this.config = { ...DEFAULT_CONFIG2, ...config };
|
|
9197
|
+
this.protectedList = [...DEFAULT_PROTECTED, ...this.config.allowlist];
|
|
9198
|
+
if (this.config.protect_current_ssh_client) {
|
|
9199
|
+
const ssh = currentSshClient();
|
|
9200
|
+
if (ssh) this.protectedList.push(ssh);
|
|
9201
|
+
}
|
|
9202
|
+
for (const gateway of defaultGateways()) this.protectedList.push(gateway);
|
|
9203
|
+
if (this.adapter.enforces === false) this.config.dry_run = true;
|
|
8817
9204
|
this.loadState();
|
|
9205
|
+
void this.reconcile();
|
|
8818
9206
|
this.startExpiryWorker();
|
|
8819
9207
|
}
|
|
8820
9208
|
adapter;
|
|
8821
9209
|
bus;
|
|
8822
9210
|
config;
|
|
8823
9211
|
blocklist = [];
|
|
9212
|
+
strikes = {};
|
|
9213
|
+
protectedList = [];
|
|
8824
9214
|
expiryTimer = null;
|
|
9215
|
+
/** Every address that can never be blocked, built-ins included. */
|
|
9216
|
+
getProtected() {
|
|
9217
|
+
return [...this.protectedList];
|
|
9218
|
+
}
|
|
9219
|
+
isAllowlisted(ip) {
|
|
9220
|
+
return isProtected(ip, this.protectedList);
|
|
9221
|
+
}
|
|
8825
9222
|
async handleDetection(event) {
|
|
8826
9223
|
if (!this.config.enabled) return;
|
|
8827
9224
|
const eventRank = SEVERITY_RANK4[event.severity] ?? 0;
|
|
8828
9225
|
const minRank = SEVERITY_RANK4[this.config.min_severity] ?? 3;
|
|
8829
9226
|
if (eventRank < minRank) return;
|
|
8830
9227
|
const ip = event.source_ip;
|
|
8831
|
-
if (!ip) return;
|
|
9228
|
+
if (!ip || (0, import_node_net4.isIP)(ip) === 0) return;
|
|
8832
9229
|
if (this.isAllowlisted(ip)) return;
|
|
8833
9230
|
if (this.blocklist.some((b) => b.ip === ip)) return;
|
|
8834
|
-
const ruleRemediation = event.details?.remediation;
|
|
8835
|
-
const ttl = ruleRemediation?.ttl_seconds || this.config.default_ttl_seconds;
|
|
8836
9231
|
const ruleId = event.details?.rule_id;
|
|
8837
|
-
await this.
|
|
8838
|
-
}
|
|
8839
|
-
|
|
8840
|
-
|
|
9232
|
+
await this.ban(ip, event.message, { ruleId, source: "auto" });
|
|
9233
|
+
}
|
|
9234
|
+
/**
|
|
9235
|
+
* Ban `ip`. With no explicit TTL the length comes from the Fibonacci ladder:
|
|
9236
|
+
* 1m, 2m, 3m, 5m, 8m, 13m … for the 1st, 2nd, 3rd offence and so on, clamped
|
|
9237
|
+
* to `max_ban_seconds`.
|
|
9238
|
+
*/
|
|
9239
|
+
async ban(ip, reason, opts = {}) {
|
|
9240
|
+
if ((0, import_node_net4.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
|
|
9241
|
+
if (this.isAllowlisted(ip)) {
|
|
9242
|
+
return { ok: false, error: `${ip} is protected and can never be blocked` };
|
|
9243
|
+
}
|
|
9244
|
+
const now = Date.now();
|
|
9245
|
+
const existing = this.blocklist.find((b) => b.ip === ip);
|
|
9246
|
+
if (existing && !opts.ttlSeconds) {
|
|
9247
|
+
return { ok: false, error: `${ip} is already banned` };
|
|
9248
|
+
}
|
|
9249
|
+
const strike = recordStrike(this.strikes, ip, now, this.config.strike_memory_seconds);
|
|
9250
|
+
const ttl = opts.ttlSeconds ?? banSeconds(strike, this.config.max_ban_seconds);
|
|
8841
9251
|
const entry = {
|
|
8842
9252
|
ip,
|
|
8843
9253
|
reason,
|
|
8844
|
-
rule_id: ruleId,
|
|
8845
|
-
blocked_at:
|
|
8846
|
-
expires_at:
|
|
8847
|
-
dry_run: this.config.dry_run
|
|
9254
|
+
rule_id: opts.ruleId,
|
|
9255
|
+
blocked_at: now,
|
|
9256
|
+
expires_at: now + ttl * 1e3,
|
|
9257
|
+
dry_run: this.config.dry_run,
|
|
9258
|
+
strikes: strike,
|
|
9259
|
+
source: opts.source ?? "manual"
|
|
8848
9260
|
};
|
|
8849
9261
|
if (!this.config.dry_run) {
|
|
8850
9262
|
try {
|
|
8851
9263
|
await this.adapter.block(ip);
|
|
8852
9264
|
} catch (err) {
|
|
8853
|
-
|
|
9265
|
+
const message = explainBlockFailure(err, this.adapter.name);
|
|
9266
|
+
this.logLine(`[firewall] error blocking ${ip}: ${message}`);
|
|
8854
9267
|
this.bus.publish({
|
|
8855
9268
|
timestamp: /* @__PURE__ */ new Date(),
|
|
8856
9269
|
module: "firewall-rules",
|
|
8857
9270
|
category: "system",
|
|
8858
9271
|
severity: "medium",
|
|
8859
|
-
message: `Failed to block ${ip}: ${
|
|
9272
|
+
message: `Failed to block ${ip}: ${message}`,
|
|
9273
|
+
source_ip: ip
|
|
8860
9274
|
});
|
|
8861
|
-
return false;
|
|
9275
|
+
return { ok: false, error: message };
|
|
8862
9276
|
}
|
|
8863
9277
|
}
|
|
9278
|
+
this.blocklist = this.blocklist.filter((b) => b.ip !== ip);
|
|
8864
9279
|
this.blocklist.push(entry);
|
|
8865
9280
|
this.saveState();
|
|
8866
9281
|
const mode = this.config.dry_run ? "[DRY-RUN] " : "";
|
|
8867
|
-
const
|
|
8868
|
-
this.logLine(`[firewall] ${
|
|
9282
|
+
const label = `${mode}Banned ${ip} for ${formatDuration(ttl)} (offence #${strike}): ${reason}`;
|
|
9283
|
+
this.logLine(`[firewall] ${label}`);
|
|
8869
9284
|
this.bus.publish({
|
|
8870
9285
|
timestamp: /* @__PURE__ */ new Date(),
|
|
8871
9286
|
module: "firewall-rules",
|
|
8872
9287
|
category: "system",
|
|
8873
9288
|
severity: "info",
|
|
8874
|
-
message:
|
|
9289
|
+
message: label,
|
|
8875
9290
|
source_ip: ip,
|
|
8876
|
-
details: {
|
|
9291
|
+
details: {
|
|
9292
|
+
action: "block",
|
|
9293
|
+
rule_id: opts.ruleId,
|
|
9294
|
+
dry_run: this.config.dry_run,
|
|
9295
|
+
ttl_seconds: ttl,
|
|
9296
|
+
strikes: strike,
|
|
9297
|
+
source: entry.source,
|
|
9298
|
+
backend: this.adapter.name
|
|
9299
|
+
}
|
|
8877
9300
|
});
|
|
8878
|
-
return true;
|
|
8879
|
-
}
|
|
8880
|
-
|
|
9301
|
+
return { ok: true, entry };
|
|
9302
|
+
}
|
|
9303
|
+
/**
|
|
9304
|
+
* Lift a ban. `forget` also drops the strike ledger entry — an operator
|
|
9305
|
+
* unbanning by hand is overruling the detection, so the next offence should
|
|
9306
|
+
* start at one minute again rather than resuming the ladder.
|
|
9307
|
+
*/
|
|
9308
|
+
async unban(ip, opts = {}) {
|
|
8881
9309
|
const idx = this.blocklist.findIndex((b) => b.ip === ip);
|
|
8882
|
-
|
|
8883
|
-
|
|
8884
|
-
if (!entry.dry_run) {
|
|
9310
|
+
const entry = idx >= 0 ? this.blocklist[idx] : null;
|
|
9311
|
+
if (!entry?.dry_run) {
|
|
8885
9312
|
try {
|
|
8886
9313
|
await this.adapter.unblock(ip);
|
|
8887
9314
|
} catch (err) {
|
|
8888
|
-
|
|
8889
|
-
|
|
9315
|
+
const message = err.message;
|
|
9316
|
+
this.logLine(`[firewall] error unblocking ${ip}: ${message}`);
|
|
9317
|
+
return { ok: false, error: message };
|
|
8890
9318
|
}
|
|
8891
9319
|
}
|
|
8892
|
-
this.blocklist.splice(idx, 1);
|
|
9320
|
+
if (idx >= 0) this.blocklist.splice(idx, 1);
|
|
9321
|
+
if (opts.forget) delete this.strikes[ip];
|
|
8893
9322
|
this.saveState();
|
|
8894
|
-
|
|
9323
|
+
if (idx < 0) return { ok: false, error: `${ip} is not banned` };
|
|
9324
|
+
this.logLine(`[firewall] Unbanned ${ip}${opts.forget ? " (strikes cleared)" : ""}`);
|
|
8895
9325
|
this.bus.publish({
|
|
8896
9326
|
timestamp: /* @__PURE__ */ new Date(),
|
|
8897
9327
|
module: "firewall-rules",
|
|
8898
9328
|
category: "system",
|
|
8899
9329
|
severity: "info",
|
|
8900
|
-
message: `
|
|
9330
|
+
message: `Unbanned ${ip}`,
|
|
8901
9331
|
source_ip: ip,
|
|
8902
|
-
details: { action: "unblock" }
|
|
9332
|
+
details: { action: "unblock", forget: opts.forget === true }
|
|
8903
9333
|
});
|
|
8904
|
-
return true;
|
|
9334
|
+
return { ok: true };
|
|
8905
9335
|
}
|
|
8906
|
-
|
|
8907
|
-
|
|
9336
|
+
/** Lifts every ban this module placed. The "undo it all" of R12. */
|
|
9337
|
+
async flush() {
|
|
9338
|
+
const entries = [...this.blocklist];
|
|
9339
|
+
for (const entry of entries) await this.unban(entry.ip);
|
|
9340
|
+
return entries.length;
|
|
9341
|
+
}
|
|
9342
|
+
getBlocklist() {
|
|
9343
|
+
return [...this.blocklist].sort((a, b) => b.blocked_at - a.blocked_at);
|
|
9344
|
+
}
|
|
9345
|
+
getAllowlist() {
|
|
9346
|
+
return [...this.protectedList];
|
|
9347
|
+
}
|
|
9348
|
+
/** Offence count per address, so the dashboard can show why a ban is long. */
|
|
9349
|
+
getStrikes() {
|
|
9350
|
+
return { ...this.strikes };
|
|
9351
|
+
}
|
|
9352
|
+
status() {
|
|
9353
|
+
return {
|
|
9354
|
+
enabled: this.config.enabled,
|
|
9355
|
+
dry_run: this.config.dry_run,
|
|
9356
|
+
backend: this.adapter.name,
|
|
9357
|
+
min_severity: this.config.min_severity,
|
|
9358
|
+
banned: this.blocklist.length,
|
|
9359
|
+
max_ban_seconds: this.config.max_ban_seconds,
|
|
9360
|
+
warning: this.privilegeWarning()
|
|
9361
|
+
};
|
|
9362
|
+
}
|
|
9363
|
+
/**
|
|
9364
|
+
* Set when the daemon intends to enforce but cannot. `nft --version` succeeds
|
|
9365
|
+
* for anybody, so backend detection alone will happily pick nftables inside
|
|
9366
|
+
* an unprivileged daemon — and then every ban fails at the moment it matters.
|
|
9367
|
+
* Saying so up front beats a dashboard that looks armed and is not.
|
|
9368
|
+
*/
|
|
9369
|
+
privilegeWarning() {
|
|
9370
|
+
if (!this.config.enabled || this.config.dry_run) return void 0;
|
|
9371
|
+
if (this.adapter.enforces === false) return void 0;
|
|
9372
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : 0;
|
|
9373
|
+
if (uid === 0) return void 0;
|
|
9374
|
+
return `daemon runs as uid ${uid} and cannot write ${this.adapter.name} rules \u2014 bans will fail`;
|
|
8908
9375
|
}
|
|
8909
9376
|
addToAllowlist(ip) {
|
|
8910
|
-
if (!this.
|
|
8911
|
-
|
|
8912
|
-
}
|
|
9377
|
+
if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
|
|
9378
|
+
if (!this.config.allowlist.includes(ip)) this.config.allowlist.push(ip);
|
|
8913
9379
|
}
|
|
8914
9380
|
removeFromAllowlist(ip) {
|
|
9381
|
+
if (DEFAULT_PROTECTED.includes(ip)) return;
|
|
9382
|
+
this.protectedList = this.protectedList.filter((a) => a !== ip);
|
|
8915
9383
|
this.config.allowlist = this.config.allowlist.filter((a) => a !== ip);
|
|
8916
9384
|
}
|
|
8917
|
-
getBlocklist() {
|
|
8918
|
-
return [...this.blocklist];
|
|
8919
|
-
}
|
|
8920
|
-
getAllowlist() {
|
|
8921
|
-
return [...this.config.allowlist];
|
|
8922
|
-
}
|
|
8923
9385
|
stop() {
|
|
8924
9386
|
if (this.expiryTimer) clearInterval(this.expiryTimer);
|
|
8925
9387
|
this.expiryTimer = null;
|
|
8926
9388
|
}
|
|
9389
|
+
/**
|
|
9390
|
+
* R5: bans survive a restart, their TTLs do not. Anything that expired while
|
|
9391
|
+
* the daemon was down is dropped, and anything still live is re-applied —
|
|
9392
|
+
* the firewall may have been flushed by a reboot underneath us.
|
|
9393
|
+
*/
|
|
9394
|
+
async reconcile() {
|
|
9395
|
+
const now = Date.now();
|
|
9396
|
+
const live = this.blocklist.filter((b) => b.expires_at > now);
|
|
9397
|
+
const stale = this.blocklist.filter((b) => b.expires_at <= now);
|
|
9398
|
+
for (const entry of stale) {
|
|
9399
|
+
if (!entry.dry_run) {
|
|
9400
|
+
try {
|
|
9401
|
+
await this.adapter.unblock(entry.ip);
|
|
9402
|
+
} catch {
|
|
9403
|
+
}
|
|
9404
|
+
}
|
|
9405
|
+
}
|
|
9406
|
+
this.blocklist = live;
|
|
9407
|
+
this.saveState();
|
|
9408
|
+
if (this.config.dry_run) return;
|
|
9409
|
+
let applied = [];
|
|
9410
|
+
try {
|
|
9411
|
+
applied = await this.adapter.listBlocked();
|
|
9412
|
+
} catch {
|
|
9413
|
+
}
|
|
9414
|
+
for (const entry of live) {
|
|
9415
|
+
if (applied.includes(entry.ip)) continue;
|
|
9416
|
+
try {
|
|
9417
|
+
await this.adapter.block(entry.ip);
|
|
9418
|
+
} catch {
|
|
9419
|
+
}
|
|
9420
|
+
}
|
|
9421
|
+
}
|
|
8927
9422
|
startExpiryWorker() {
|
|
8928
|
-
this.expiryTimer = setInterval(() => void this.processExpiries(),
|
|
9423
|
+
this.expiryTimer = setInterval(() => void this.processExpiries(), 1e4);
|
|
9424
|
+
this.expiryTimer.unref?.();
|
|
8929
9425
|
}
|
|
8930
9426
|
async processExpiries() {
|
|
8931
9427
|
const now = Date.now();
|
|
8932
|
-
const
|
|
8933
|
-
|
|
8934
|
-
|
|
9428
|
+
for (const entry of this.blocklist.filter((b) => b.expires_at <= now)) {
|
|
9429
|
+
await this.unban(entry.ip);
|
|
9430
|
+
}
|
|
9431
|
+
const pruned = pruneStrikes(this.strikes, now, this.config.strike_memory_seconds);
|
|
9432
|
+
if (Object.keys(pruned).length !== Object.keys(this.strikes).length) {
|
|
9433
|
+
this.strikes = pruned;
|
|
9434
|
+
this.saveState();
|
|
8935
9435
|
}
|
|
8936
9436
|
}
|
|
8937
9437
|
loadState() {
|
|
8938
9438
|
try {
|
|
8939
9439
|
const saved = getModuleState("firewall-rules", "blocklist");
|
|
8940
|
-
if (Array.isArray(saved))
|
|
9440
|
+
if (Array.isArray(saved)) {
|
|
9441
|
+
this.blocklist = saved.map((entry) => ({
|
|
9442
|
+
...entry,
|
|
9443
|
+
strikes: entry.strikes ?? 1,
|
|
9444
|
+
source: entry.source ?? "auto",
|
|
9445
|
+
expires_at: entry.expires_at ?? entry.blocked_at + this.config.max_ban_seconds * 1e3
|
|
9446
|
+
}));
|
|
9447
|
+
}
|
|
9448
|
+
} catch {
|
|
9449
|
+
}
|
|
9450
|
+
try {
|
|
9451
|
+
const saved = getModuleState("firewall-rules", "strikes");
|
|
9452
|
+
if (saved && typeof saved === "object") this.strikes = saved;
|
|
8941
9453
|
} catch {
|
|
8942
9454
|
}
|
|
8943
9455
|
}
|
|
@@ -8946,16 +9458,41 @@ var RemediationManager = class {
|
|
|
8946
9458
|
setModuleState("firewall-rules", "blocklist", this.blocklist);
|
|
8947
9459
|
} catch {
|
|
8948
9460
|
}
|
|
9461
|
+
try {
|
|
9462
|
+
setModuleState("firewall-rules", "strikes", this.strikes);
|
|
9463
|
+
} catch {
|
|
9464
|
+
}
|
|
8949
9465
|
}
|
|
8950
9466
|
logLine(line) {
|
|
8951
9467
|
try {
|
|
8952
|
-
(0,
|
|
9468
|
+
(0, import_node_fs18.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
|
|
8953
9469
|
`);
|
|
8954
9470
|
} catch {
|
|
8955
9471
|
}
|
|
8956
9472
|
}
|
|
8957
9473
|
};
|
|
8958
9474
|
|
|
9475
|
+
// src/daemon/firewall/settings.ts
|
|
9476
|
+
function remediationSettings(section) {
|
|
9477
|
+
if (!section) return {};
|
|
9478
|
+
const settings = {};
|
|
9479
|
+
if (typeof section.enabled === "boolean") settings.enabled = section.enabled;
|
|
9480
|
+
if (section.mode === "dry_run") settings.dry_run = true;
|
|
9481
|
+
else if (section.mode === "enforce") settings.dry_run = false;
|
|
9482
|
+
else if (typeof section.dry_run === "boolean") settings.dry_run = section.dry_run;
|
|
9483
|
+
if (section.min_severity) settings.min_severity = section.min_severity;
|
|
9484
|
+
const maxBan = parseDuration(section.max_ban);
|
|
9485
|
+
if (maxBan) settings.max_ban_seconds = maxBan;
|
|
9486
|
+
const memory = parseDuration(section.strike_memory);
|
|
9487
|
+
if (memory) settings.strike_memory_seconds = memory;
|
|
9488
|
+
const allow = [...section.protected ?? [], ...section.allowlist ?? []];
|
|
9489
|
+
if (allow.length > 0) settings.allowlist = allow;
|
|
9490
|
+
if (typeof section.protect_current_ssh_client === "boolean") {
|
|
9491
|
+
settings.protect_current_ssh_client = section.protect_current_ssh_client;
|
|
9492
|
+
}
|
|
9493
|
+
return settings;
|
|
9494
|
+
}
|
|
9495
|
+
|
|
8959
9496
|
// src/core/telemetry.ts
|
|
8960
9497
|
var ready = false;
|
|
8961
9498
|
var sentry = null;
|
|
@@ -9005,7 +9542,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
|
|
|
9005
9542
|
// src/daemon/index.ts
|
|
9006
9543
|
function readVersion2() {
|
|
9007
9544
|
try {
|
|
9008
|
-
const pkg = JSON.parse((0,
|
|
9545
|
+
const pkg = JSON.parse((0, import_node_fs19.readFileSync)((0, import_node_path14.join)(__dirname, "..", "package.json"), "utf-8"));
|
|
9009
9546
|
return pkg.version || "0.0.0";
|
|
9010
9547
|
} catch {
|
|
9011
9548
|
return "0.0.0";
|
|
@@ -9013,7 +9550,7 @@ function readVersion2() {
|
|
|
9013
9550
|
}
|
|
9014
9551
|
function logLine(line) {
|
|
9015
9552
|
try {
|
|
9016
|
-
(0,
|
|
9553
|
+
(0, import_node_fs19.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
|
|
9017
9554
|
`);
|
|
9018
9555
|
} catch {
|
|
9019
9556
|
}
|
|
@@ -9041,7 +9578,7 @@ async function runDaemon() {
|
|
|
9041
9578
|
} catch (err) {
|
|
9042
9579
|
logLine(`[daemon] state db unavailable: ${err.message}`);
|
|
9043
9580
|
}
|
|
9044
|
-
const config = loadConfig((0,
|
|
9581
|
+
const config = loadConfig((0, import_node_fs19.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
|
|
9045
9582
|
bus.on("event", (event) => {
|
|
9046
9583
|
logLine(`[event] ${event.severity} ${event.module} ${event.message}`);
|
|
9047
9584
|
});
|
|
@@ -9069,14 +9606,24 @@ async function runDaemon() {
|
|
|
9069
9606
|
});
|
|
9070
9607
|
logLine(`[daemon] rule engine loaded ${ruleEngine.getRules().length} rules`);
|
|
9071
9608
|
setInterval(() => ruleEngine.cleanup(), 3e5);
|
|
9072
|
-
const
|
|
9073
|
-
const
|
|
9609
|
+
const settings = remediationSettings(config.remediation);
|
|
9610
|
+
const firewallAdapter = detectFirewallAdapter(config.remediation?.backend ?? "auto");
|
|
9611
|
+
const remediation = new RemediationManager(firewallAdapter, bus, settings);
|
|
9074
9612
|
bus.on("event", (event) => {
|
|
9075
9613
|
if (event.module !== "firewall-rules") {
|
|
9076
9614
|
void remediation.handleDetection(event);
|
|
9077
9615
|
}
|
|
9078
9616
|
});
|
|
9079
|
-
|
|
9617
|
+
const remediationStatus = remediation.status();
|
|
9618
|
+
logLine(
|
|
9619
|
+
`[daemon] auto-defence ${remediationStatus.enabled ? "ON" : "OFF"} (backend=${remediationStatus.backend}, mode=${remediationStatus.dry_run ? "dry_run" : "enforce"}, min_severity=${remediationStatus.min_severity}, bans escalate 1m\u21922m\u21923m\u21925m\u21928m\u2026)`
|
|
9620
|
+
);
|
|
9621
|
+
if (remediationStatus.dry_run && firewallAdapter.enforces !== false) {
|
|
9622
|
+
logLine("[daemon] dry_run is set in [remediation] \u2014 detections will be logged, not blocked");
|
|
9623
|
+
}
|
|
9624
|
+
if (firewallAdapter.enforces === false) {
|
|
9625
|
+
logLine("[daemon] no manageable firewall found (need fail2ban, nftables or iptables) \u2014 bans are simulated");
|
|
9626
|
+
}
|
|
9080
9627
|
new AlertDispatcher(bus, config);
|
|
9081
9628
|
const runsWorker = new RunsWorker(bus);
|
|
9082
9629
|
try {
|
|
@@ -9084,7 +9631,7 @@ async function runDaemon() {
|
|
|
9084
9631
|
} catch (err) {
|
|
9085
9632
|
logLine(`[daemon] runs-worker failed to start: ${err.message}`);
|
|
9086
9633
|
}
|
|
9087
|
-
const ipc = new IpcServer(version, moduleHost);
|
|
9634
|
+
const ipc = new IpcServer(version, moduleHost, remediation);
|
|
9088
9635
|
await ipc.start();
|
|
9089
9636
|
logLine(`[daemon] ipc listening on ${PATHS.socket}`);
|
|
9090
9637
|
const shutdown = async (signal) => {
|