@profullstack/threatcrush 0.11.10 → 0.12.0

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 CHANGED
@@ -2022,8 +2022,8 @@ var require_toml = __commonJS({
2022
2022
  });
2023
2023
 
2024
2024
  // src/daemon/index.ts
2025
- var import_node_fs18 = require("fs");
2026
- var import_node_path13 = require("path");
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,67 @@ 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
+ };
2537
+ return this.send(client, { id: req.id, ok: true, result: reply });
2538
+ }
2539
+ case "block": {
2540
+ if (!tokensMatch(this.controlToken, req.params?.token)) {
2541
+ return this.send(client, {
2542
+ id: req.id,
2543
+ ok: false,
2544
+ error: "banning requires the daemon control token (run as root, or as the user running threatcrushd)"
2545
+ });
2546
+ }
2547
+ if (!this.remediation) {
2548
+ return this.send(client, { id: req.id, ok: false, error: "remediation is not running" });
2549
+ }
2550
+ const ttl = parseDuration(req.params?.ttl) ?? void 0;
2551
+ const result = await this.remediation.ban(req.params.ip, req.params.reason || "banned by operator", {
2552
+ ttlSeconds: ttl,
2553
+ source: "manual"
2554
+ });
2555
+ if (!result.ok) {
2556
+ return this.send(client, { id: req.id, ok: false, error: result.error || "ban failed" });
2557
+ }
2558
+ return this.send(client, { id: req.id, ok: true, result: result.entry });
2559
+ }
2560
+ case "unblock": {
2561
+ if (!tokensMatch(this.controlToken, req.params?.token)) {
2562
+ return this.send(client, {
2563
+ id: req.id,
2564
+ ok: false,
2565
+ error: "unbanning requires the daemon control token (run as root, or as the user running threatcrushd)"
2566
+ });
2567
+ }
2568
+ if (!this.remediation) {
2569
+ return this.send(client, { id: req.id, ok: false, error: "remediation is not running" });
2570
+ }
2571
+ const result = await this.remediation.unban(req.params.ip, { forget: req.params.forget !== false });
2572
+ if (!result.ok) {
2573
+ return this.send(client, { id: req.id, ok: false, error: result.error || "unban failed" });
2574
+ }
2575
+ return this.send(client, { id: req.id, ok: true, result: { ip: req.params.ip } });
2576
+ }
2464
2577
  case "shutdown":
2465
2578
  if (!tokensMatch(this.controlToken, req.params?.token)) {
2466
2579
  return this.send(client, {
@@ -2620,9 +2733,10 @@ var import_node_fs6 = require("fs");
2620
2733
  var import_node_readline = require("readline");
2621
2734
 
2622
2735
  // src/core/log-parser.ts
2623
- var NGINX_REGEX = /^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) \S+" (\d{3}) (\d+) "[^"]*" "([^"]*)"/;
2624
- var AUTH_REGEX = /^(\w+\s+\d+\s+[\d:]+)\s+\S+\s+(\S+?)(?:\[\d+\])?:\s+(.*)/;
2625
- var SYSLOG_REGEX = /^(\w+\s+\d+\s+[\d:]+)\s+\S+\s+(\S+?)(?:\[\d+\])?:\s+(.*)/;
2736
+ var NGINX_REGEX = /^(?:(\S+) )?(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) \S+" (\d{3}) (\d+) "[^"]*" "([^"]*)"/;
2737
+ var TIMESTAMP = String.raw`(\w{3}\s+\d+\s+[\d:]+|\d{4}-\d{2}-\d{2}T[\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)`;
2738
+ var AUTH_REGEX = new RegExp(`^${TIMESTAMP}\\s+\\S+\\s+(\\S+?)(?:\\[\\d+\\])?:\\s+(.*)`);
2739
+ var SYSLOG_REGEX = new RegExp(`^${TIMESTAMP}\\s+\\S+\\s+(\\S+?)(?:\\[\\d+\\])?:\\s+(.*)`);
2626
2740
  var IP_REGEX = /(?:from|FROM)\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
2627
2741
  var INVALID_USER_REGEX = /(?:for\s+invalid\s+user)\s+(\S+?)(?:\s+from|\s*$)/;
2628
2742
  var USER_REGEX = /(?:for|user)\s+(\S+?)(?:\s+from|\s*$)/;
@@ -2652,26 +2766,37 @@ var ATTACK_PATTERNS = {
2652
2766
  /windows\/system32/i
2653
2767
  ],
2654
2768
  rfi: [
2655
- /(?:https?|ftp):\/\/.*\?/i,
2769
+ // A remote URL pointing at something executable — the actual shape of a
2770
+ // remote file include (`?page=http://evil.tld/shell.txt`).
2771
+ //
2772
+ // This used to be `(?:https?|ftp):\/\/.*\?`, i.e. *any* URL carrying a
2773
+ // query string. A URL inside a query parameter is ordinary web design —
2774
+ // readers, share links, oembed, feed proxies — so on rssamplifier.com every
2775
+ // `/<feed>/read?p=https://…` hit was logged as a CRITICAL attack. With
2776
+ // auto-defence enforcing, that pattern bans readers, which is precisely the
2777
+ // failure PRD 0010 is written to prevent.
2778
+ /(?:https?|ftp):\/\/\S+\.(?:php|phtml|phar|asp|aspx|jsp|txt|sh|pl|py|cgi)(?:[?#%\s]|$)/i,
2656
2779
  /php:\/\/(?:input|filter)/i,
2657
- /data:\/\//i
2780
+ /(?:data|expect|zip|phar):\/\//i
2658
2781
  ]
2659
2782
  };
2660
2783
  function parseNginxLog(line) {
2661
2784
  const match = line.match(NGINX_REGEX);
2662
2785
  if (!match) return null;
2786
+ const fields = {
2787
+ ip: match[2],
2788
+ method: match[4],
2789
+ path: match[5],
2790
+ status: match[6],
2791
+ size: match[7],
2792
+ user_agent: match[8]
2793
+ };
2794
+ if (match[1]) fields.host = match[1];
2663
2795
  return {
2664
- timestamp: parseNginxTimestamp(match[2]),
2796
+ timestamp: parseNginxTimestamp(match[3]),
2665
2797
  raw: line,
2666
2798
  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
- }
2799
+ fields
2675
2800
  };
2676
2801
  }
2677
2802
  function parseAuthLog(line) {
@@ -2707,17 +2832,23 @@ function parseSyslog(line) {
2707
2832
  }
2708
2833
  function detectAttackPattern(path) {
2709
2834
  const candidates = /* @__PURE__ */ new Set([path]);
2710
- let current = path;
2711
- for (let i = 0; i < 2; i++) {
2712
- let decoded = null;
2713
- try {
2714
- decoded = decodeURIComponent(current);
2715
- } catch {
2716
- decoded = null;
2835
+ const seeds = [path, path.includes("+") ? path.replace(/\+/g, " ") : null].filter(
2836
+ (s) => s !== null
2837
+ );
2838
+ for (const seed of seeds) {
2839
+ candidates.add(seed);
2840
+ let current = seed;
2841
+ for (let i = 0; i < 2; i++) {
2842
+ let decoded = null;
2843
+ try {
2844
+ decoded = decodeURIComponent(current);
2845
+ } catch {
2846
+ decoded = null;
2847
+ }
2848
+ if (decoded === null || decoded === current) break;
2849
+ candidates.add(decoded);
2850
+ current = decoded;
2717
2851
  }
2718
- if (decoded === null || decoded === current) break;
2719
- candidates.add(decoded);
2720
- current = decoded;
2721
2852
  }
2722
2853
  for (const [type, patterns] of Object.entries(ATTACK_PATTERNS)) {
2723
2854
  for (const pattern of patterns) {
@@ -2743,6 +2874,10 @@ function parseNginxTimestamp(s) {
2743
2874
  return Number.isNaN(d.getTime()) ? /* @__PURE__ */ new Date() : d;
2744
2875
  }
2745
2876
  function parseSyslogTimestamp(s) {
2877
+ if (/^\d{4}-\d{2}-\d{2}T/.test(s)) {
2878
+ const iso = new Date(s);
2879
+ return Number.isNaN(iso.getTime()) ? /* @__PURE__ */ new Date() : iso;
2880
+ }
2746
2881
  const now = /* @__PURE__ */ new Date();
2747
2882
  let d = /* @__PURE__ */ new Date(`${s} ${now.getFullYear()}`);
2748
2883
  if (Number.isNaN(d.getTime())) return now;
@@ -2833,6 +2968,7 @@ var LogWatcher = class {
2833
2968
  let severity = "info";
2834
2969
  let message = line;
2835
2970
  let sourceIp;
2971
+ let host;
2836
2972
  if (parsed.source === "auth") {
2837
2973
  const entry = parseAuthLog(line);
2838
2974
  if (!entry) return;
@@ -2856,6 +2992,7 @@ var LogWatcher = class {
2856
2992
  sourceIp = entry.fields.ip;
2857
2993
  const status = parseInt(entry.fields.status, 10);
2858
2994
  const attack = detectAttackPattern(entry.fields.path);
2995
+ host = entry.fields.host;
2859
2996
  if (attack) {
2860
2997
  severity = "critical";
2861
2998
  message = `Attack [${attack.toUpperCase()}]: ${entry.fields.method} ${entry.fields.path}`;
@@ -2877,7 +3014,8 @@ var LogWatcher = class {
2877
3014
  category: src.category,
2878
3015
  severity,
2879
3016
  message,
2880
- source_ip: sourceIp
3017
+ source_ip: sourceIp,
3018
+ ...host ? { details: { host } } : {}
2881
3019
  };
2882
3020
  try {
2883
3021
  insertEvent(event);
@@ -3432,6 +3570,7 @@ function loadConfig(configPath) {
3432
3570
  api: { ...DEFAULT_CONFIG.api, ...parsed.api },
3433
3571
  alerts: parsed.alerts || {},
3434
3572
  modules: { ...DEFAULT_CONFIG.modules, ...parsed.modules },
3573
+ remediation: parsed.remediation,
3435
3574
  license: parsed.license
3436
3575
  };
3437
3576
  } catch {
@@ -8656,12 +8795,132 @@ function loadAllRules(customDir) {
8656
8795
 
8657
8796
  // src/daemon/firewall/adapters.ts
8658
8797
  var import_node_child_process3 = require("child_process");
8798
+ var import_node_fs17 = require("fs");
8799
+ var import_node_path13 = require("path");
8659
8800
  var import_node_net2 = require("net");
8660
8801
  function assertValidFirewallIp(ip) {
8661
8802
  if ((0, import_node_net2.isIP)(ip) !== 4) {
8662
8803
  throw new Error(`Invalid IPv4 address: ${ip}`);
8663
8804
  }
8664
8805
  }
8806
+ function assertBannableIp(ip) {
8807
+ if ((0, import_node_net2.isIP)(ip) === 0) {
8808
+ throw new Error(`Invalid IP address: ${ip}`);
8809
+ }
8810
+ }
8811
+ function writeIfAbsent(path, contents) {
8812
+ (0, import_node_fs17.mkdirSync)((0, import_node_path13.dirname)(path), { recursive: true });
8813
+ try {
8814
+ (0, import_node_fs17.writeFileSync)(path, contents, { flag: "wx" });
8815
+ } catch (err) {
8816
+ if (err.code !== "EEXIST") throw err;
8817
+ }
8818
+ }
8819
+ var FAIL2BAN_JAIL = "threatcrush";
8820
+ var FAIL2BAN_FILTER_FILE = "/etc/fail2ban/filter.d/threatcrush.conf";
8821
+ var FAIL2BAN_JAIL_FILE = "/etc/fail2ban/jail.d/threatcrush.conf";
8822
+ var Fail2banAdapter = class {
8823
+ constructor(jail = FAIL2BAN_JAIL, backstopSeconds = 86400) {
8824
+ this.jail = jail;
8825
+ this.backstopSeconds = backstopSeconds;
8826
+ }
8827
+ jail;
8828
+ backstopSeconds;
8829
+ name = "fail2ban";
8830
+ enforces = true;
8831
+ jailReady = false;
8832
+ isAvailable() {
8833
+ const result = (0, import_node_child_process3.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
8834
+ return result.status === 0;
8835
+ }
8836
+ client(args) {
8837
+ return (0, import_node_child_process3.execFileSync)("fail2ban-client", args, {
8838
+ encoding: "utf-8",
8839
+ stdio: ["ignore", "pipe", "pipe"]
8840
+ });
8841
+ }
8842
+ /**
8843
+ * Create the jail if it is missing. Writing to /etc/fail2ban needs root; when
8844
+ * we cannot, the error surfaces to the caller instead of a ban that silently
8845
+ * goes nowhere.
8846
+ */
8847
+ ensureJail() {
8848
+ if (this.jailReady) return;
8849
+ try {
8850
+ this.client(["status", this.jail]);
8851
+ this.jailReady = true;
8852
+ return;
8853
+ } catch {
8854
+ }
8855
+ writeIfAbsent(
8856
+ FAIL2BAN_FILTER_FILE,
8857
+ [
8858
+ "# Installed by ThreatCrush. Intentionally matches nothing:",
8859
+ "# detection happens in threatcrushd, this jail only executes bans.",
8860
+ "[Definition]",
8861
+ "failregex = ^threatcrush-never-matches <HOST>$",
8862
+ "ignoreregex =",
8863
+ ""
8864
+ ].join("\n")
8865
+ );
8866
+ writeIfAbsent(
8867
+ FAIL2BAN_JAIL_FILE,
8868
+ [
8869
+ "# Installed by ThreatCrush \u2014 bans arrive via `fail2ban-client set threatcrush banip`.",
8870
+ "# bantime is only a backstop; threatcrushd unbans on its own schedule.",
8871
+ `[${this.jail}]`,
8872
+ "enabled = true",
8873
+ "filter = threatcrush",
8874
+ "backend = polling",
8875
+ "logpath = /var/log/threatcrush/threatcrushd.log",
8876
+ "maxretry = 1000000",
8877
+ "findtime = 1",
8878
+ `bantime = ${this.backstopSeconds}`,
8879
+ ""
8880
+ ].join("\n")
8881
+ );
8882
+ this.client(["reload", this.jail]);
8883
+ this.jailReady = true;
8884
+ }
8885
+ async block(ip) {
8886
+ assertBannableIp(ip);
8887
+ this.ensureJail();
8888
+ this.client(["set", this.jail, "banip", ip]);
8889
+ }
8890
+ async unblock(ip) {
8891
+ assertBannableIp(ip);
8892
+ try {
8893
+ this.client(["set", this.jail, "unbanip", ip]);
8894
+ } catch {
8895
+ }
8896
+ }
8897
+ async isBlocked(ip) {
8898
+ assertBannableIp(ip);
8899
+ return (await this.listBlocked()).includes(ip);
8900
+ }
8901
+ async listBlocked() {
8902
+ try {
8903
+ return parseBannedList(this.client(["get", this.jail, "banned"]));
8904
+ } catch {
8905
+ try {
8906
+ const status = this.client(["status", this.jail]);
8907
+ const line = status.split("\n").find((l) => /Banned IP list:/i.test(l));
8908
+ if (!line) return [];
8909
+ return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net2.isIP)(s) !== 0);
8910
+ } catch {
8911
+ return [];
8912
+ }
8913
+ }
8914
+ }
8915
+ };
8916
+ function parseBannedList(output) {
8917
+ const found = [];
8918
+ for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
8919
+ if ((0, import_node_net2.isIP)(match[1]) !== 0) found.push(match[1]);
8920
+ }
8921
+ if (found.length > 0) return found;
8922
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net2.isIP)(s) !== 0);
8923
+ }
8665
8924
  var NftablesAdapter = class {
8666
8925
  name = "nftables";
8667
8926
  table = "threatcrush";
@@ -8765,6 +9024,7 @@ var IptablesAdapter = class {
8765
9024
  };
8766
9025
  var DryRunAdapter = class {
8767
9026
  name = "dry-run";
9027
+ enforces = false;
8768
9028
  blocked = /* @__PURE__ */ new Set();
8769
9029
  isAvailable() {
8770
9030
  return true;
@@ -8785,7 +9045,19 @@ var DryRunAdapter = class {
8785
9045
  return [...this.blocked];
8786
9046
  }
8787
9047
  };
8788
- function detectFirewallAdapter() {
9048
+ function detectFirewallAdapter(backend = "auto") {
9049
+ const byName = {
9050
+ fail2ban: () => new Fail2banAdapter(),
9051
+ nftables: () => new NftablesAdapter(),
9052
+ iptables: () => new IptablesAdapter(),
9053
+ "dry-run": () => new DryRunAdapter()
9054
+ };
9055
+ if (backend !== "auto") {
9056
+ const chosen = byName[backend]?.();
9057
+ if (chosen?.isAvailable()) return chosen;
9058
+ }
9059
+ const f2b = new Fail2banAdapter();
9060
+ if (f2b.isAvailable()) return f2b;
8789
9061
  const nft = new NftablesAdapter();
8790
9062
  if (nft.isAvailable()) return nft;
8791
9063
  const ipt = new IptablesAdapter();
@@ -8794,13 +9066,127 @@ function detectFirewallAdapter() {
8794
9066
  }
8795
9067
 
8796
9068
  // src/daemon/firewall/remediation.ts
8797
- var import_node_fs17 = require("fs");
9069
+ var import_node_fs18 = require("fs");
9070
+ var import_node_net4 = require("net");
9071
+
9072
+ // src/daemon/firewall/protected.ts
9073
+ var import_node_child_process4 = require("child_process");
9074
+ var import_node_net3 = require("net");
9075
+ var DEFAULT_PROTECTED = [
9076
+ "127.0.0.0/8",
9077
+ "::1/128",
9078
+ "10.0.0.0/8",
9079
+ "172.16.0.0/12",
9080
+ "192.168.0.0/16",
9081
+ "169.254.0.0/16",
9082
+ "fc00::/7",
9083
+ "fe80::/10"
9084
+ ];
9085
+ function ipToBytes(ip) {
9086
+ const version = (0, import_node_net3.isIP)(ip);
9087
+ if (version === 4) return v4ToBytes(ip);
9088
+ if (version === 6) return v6ToBytes(ip);
9089
+ return null;
9090
+ }
9091
+ function v4ToBytes(ip) {
9092
+ const parts = ip.split(".");
9093
+ if (parts.length !== 4) return null;
9094
+ const bytes = new Uint8Array(4);
9095
+ for (let i = 0; i < 4; i++) {
9096
+ const n = Number(parts[i]);
9097
+ if (!Number.isInteger(n) || n < 0 || n > 255) return null;
9098
+ bytes[i] = n;
9099
+ }
9100
+ return bytes;
9101
+ }
9102
+ function v6ToBytes(ip) {
9103
+ const bare = ip.split("%")[0];
9104
+ const [headText, tailText] = bare.split("::", 2);
9105
+ const head = headText ? headText.split(":") : [];
9106
+ const tail = tailText !== void 0 ? tailText ? tailText.split(":") : [] : null;
9107
+ const groups = [];
9108
+ const pushGroup = (group) => {
9109
+ if (group.includes(".")) {
9110
+ const v4 = v4ToBytes(group);
9111
+ if (!v4) return false;
9112
+ groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
9113
+ return true;
9114
+ }
9115
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return false;
9116
+ groups.push(parseInt(group, 16));
9117
+ return true;
9118
+ };
9119
+ for (const group of head) if (!pushGroup(group)) return null;
9120
+ const headCount = groups.length;
9121
+ if (tail === null) {
9122
+ if (headCount !== 8) return null;
9123
+ } else {
9124
+ const tailGroups = [];
9125
+ const saved = groups.length;
9126
+ for (const group of tail) if (!pushGroup(group)) return null;
9127
+ tailGroups.push(...groups.splice(saved));
9128
+ const zeros = 8 - headCount - tailGroups.length;
9129
+ if (zeros < 0) return null;
9130
+ for (let i = 0; i < zeros; i++) groups.push(0);
9131
+ groups.push(...tailGroups);
9132
+ }
9133
+ if (groups.length !== 8) return null;
9134
+ const bytes = new Uint8Array(16);
9135
+ for (let i = 0; i < 8; i++) {
9136
+ bytes[i * 2] = groups[i] >> 8 & 255;
9137
+ bytes[i * 2 + 1] = groups[i] & 255;
9138
+ }
9139
+ return bytes;
9140
+ }
9141
+ function ipMatches(ip, entry) {
9142
+ const [network, prefixText] = entry.trim().split("/");
9143
+ const target = ipToBytes(ip);
9144
+ const base = ipToBytes(network);
9145
+ if (!target || !base || target.length !== base.length) return false;
9146
+ const bits = prefixText === void 0 ? base.length * 8 : Number(prefixText);
9147
+ if (!Number.isInteger(bits) || bits < 0 || bits > base.length * 8) return false;
9148
+ const wholeBytes = Math.floor(bits / 8);
9149
+ for (let i = 0; i < wholeBytes; i++) {
9150
+ if (target[i] !== base[i]) return false;
9151
+ }
9152
+ const remainder = bits % 8;
9153
+ if (remainder === 0) return true;
9154
+ const mask = 255 << 8 - remainder & 255;
9155
+ return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
9156
+ }
9157
+ function isProtected(ip, list) {
9158
+ return list.some((entry) => ipMatches(ip, entry));
9159
+ }
9160
+ function currentSshClient(env2 = process.env) {
9161
+ const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
9162
+ if (!source) return null;
9163
+ const ip = source.trim().split(/\s+/)[0];
9164
+ return ip && (0, import_node_net3.isIP)(ip) ? ip : null;
9165
+ }
9166
+ function defaultGateways() {
9167
+ const found = /* @__PURE__ */ new Set();
9168
+ for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
9169
+ try {
9170
+ const out = (0, import_node_child_process4.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
9171
+ for (const line of out.split("\n")) {
9172
+ const match = line.match(/\bvia\s+(\S+)/);
9173
+ if (match && (0, import_node_net3.isIP)(match[1])) found.add(match[1]);
9174
+ }
9175
+ } catch {
9176
+ }
9177
+ }
9178
+ return [...found];
9179
+ }
9180
+
9181
+ // src/daemon/firewall/remediation.ts
8798
9182
  var DEFAULT_CONFIG2 = {
8799
9183
  enabled: true,
8800
- dry_run: true,
8801
- default_ttl_seconds: 3600,
9184
+ dry_run: false,
8802
9185
  min_severity: "high",
8803
- allowlist: ["127.0.0.1", "::1"]
9186
+ max_ban_seconds: 86400,
9187
+ strike_memory_seconds: 86400,
9188
+ allowlist: [],
9189
+ protect_current_ssh_client: true
8804
9190
  };
8805
9191
  var SEVERITY_RANK4 = {
8806
9192
  info: 0,
@@ -8814,130 +9200,248 @@ var RemediationManager = class {
8814
9200
  this.adapter = adapter;
8815
9201
  this.bus = bus2;
8816
9202
  this.config = { ...DEFAULT_CONFIG2, ...config };
9203
+ this.protectedList = [...DEFAULT_PROTECTED, ...this.config.allowlist];
9204
+ if (this.config.protect_current_ssh_client) {
9205
+ const ssh = currentSshClient();
9206
+ if (ssh) this.protectedList.push(ssh);
9207
+ }
9208
+ for (const gateway of defaultGateways()) this.protectedList.push(gateway);
9209
+ if (this.adapter.enforces === false) this.config.dry_run = true;
8817
9210
  this.loadState();
9211
+ void this.reconcile();
8818
9212
  this.startExpiryWorker();
8819
9213
  }
8820
9214
  adapter;
8821
9215
  bus;
8822
9216
  config;
8823
9217
  blocklist = [];
9218
+ strikes = {};
9219
+ protectedList = [];
8824
9220
  expiryTimer = null;
9221
+ /** Every address that can never be blocked, built-ins included. */
9222
+ getProtected() {
9223
+ return [...this.protectedList];
9224
+ }
9225
+ isAllowlisted(ip) {
9226
+ return isProtected(ip, this.protectedList);
9227
+ }
8825
9228
  async handleDetection(event) {
8826
9229
  if (!this.config.enabled) return;
8827
9230
  const eventRank = SEVERITY_RANK4[event.severity] ?? 0;
8828
9231
  const minRank = SEVERITY_RANK4[this.config.min_severity] ?? 3;
8829
9232
  if (eventRank < minRank) return;
8830
9233
  const ip = event.source_ip;
8831
- if (!ip) return;
9234
+ if (!ip || (0, import_node_net4.isIP)(ip) === 0) return;
8832
9235
  if (this.isAllowlisted(ip)) return;
8833
9236
  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
9237
  const ruleId = event.details?.rule_id;
8837
- await this.blockIp(ip, event.message, ruleId, ttl);
8838
- }
8839
- async blockIp(ip, reason, ruleId, ttlSeconds) {
8840
- if (this.isAllowlisted(ip)) return false;
9238
+ await this.ban(ip, event.message, { ruleId, source: "auto" });
9239
+ }
9240
+ /**
9241
+ * Ban `ip`. With no explicit TTL the length comes from the Fibonacci ladder:
9242
+ * 1m, 2m, 3m, 5m, 8m, 13m … for the 1st, 2nd, 3rd offence and so on, clamped
9243
+ * to `max_ban_seconds`.
9244
+ */
9245
+ async ban(ip, reason, opts = {}) {
9246
+ if ((0, import_node_net4.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
9247
+ if (this.isAllowlisted(ip)) {
9248
+ return { ok: false, error: `${ip} is protected and can never be blocked` };
9249
+ }
9250
+ const now = Date.now();
9251
+ const existing = this.blocklist.find((b) => b.ip === ip);
9252
+ if (existing && !opts.ttlSeconds) {
9253
+ return { ok: false, error: `${ip} is already banned` };
9254
+ }
9255
+ const strike = recordStrike(this.strikes, ip, now, this.config.strike_memory_seconds);
9256
+ const ttl = opts.ttlSeconds ?? banSeconds(strike, this.config.max_ban_seconds);
8841
9257
  const entry = {
8842
9258
  ip,
8843
9259
  reason,
8844
- rule_id: ruleId,
8845
- blocked_at: Date.now(),
8846
- expires_at: ttlSeconds ? Date.now() + ttlSeconds * 1e3 : void 0,
8847
- dry_run: this.config.dry_run
9260
+ rule_id: opts.ruleId,
9261
+ blocked_at: now,
9262
+ expires_at: now + ttl * 1e3,
9263
+ dry_run: this.config.dry_run,
9264
+ strikes: strike,
9265
+ source: opts.source ?? "manual"
8848
9266
  };
8849
9267
  if (!this.config.dry_run) {
8850
9268
  try {
8851
9269
  await this.adapter.block(ip);
8852
9270
  } catch (err) {
8853
- this.logLine(`[firewall] EACCES or error blocking ${ip}: ${err.message}`);
9271
+ const message = err.message;
9272
+ this.logLine(`[firewall] error blocking ${ip}: ${message}`);
8854
9273
  this.bus.publish({
8855
9274
  timestamp: /* @__PURE__ */ new Date(),
8856
9275
  module: "firewall-rules",
8857
9276
  category: "system",
8858
9277
  severity: "medium",
8859
- message: `Failed to block ${ip}: ${err.message}. Ensure daemon has CAP_NET_ADMIN.`
9278
+ message: `Failed to block ${ip}: ${message}. Ensure the daemon can manage ${this.adapter.name}.`,
9279
+ source_ip: ip
8860
9280
  });
8861
- return false;
9281
+ return { ok: false, error: message };
8862
9282
  }
8863
9283
  }
9284
+ this.blocklist = this.blocklist.filter((b) => b.ip !== ip);
8864
9285
  this.blocklist.push(entry);
8865
9286
  this.saveState();
8866
9287
  const mode = this.config.dry_run ? "[DRY-RUN] " : "";
8867
- const expiryMsg = ttlSeconds ? ` (expires in ${ttlSeconds}s)` : " (permanent)";
8868
- this.logLine(`[firewall] ${mode}Blocked ${ip}: ${reason}${expiryMsg}`);
9288
+ const label = `${mode}Banned ${ip} for ${formatDuration(ttl)} (offence #${strike}): ${reason}`;
9289
+ this.logLine(`[firewall] ${label}`);
8869
9290
  this.bus.publish({
8870
9291
  timestamp: /* @__PURE__ */ new Date(),
8871
9292
  module: "firewall-rules",
8872
9293
  category: "system",
8873
9294
  severity: "info",
8874
- message: `${mode}Blocked ${ip}: ${reason}${expiryMsg}`,
9295
+ message: label,
8875
9296
  source_ip: ip,
8876
- details: { action: "block", rule_id: ruleId, dry_run: this.config.dry_run, ttl_seconds: ttlSeconds }
9297
+ details: {
9298
+ action: "block",
9299
+ rule_id: opts.ruleId,
9300
+ dry_run: this.config.dry_run,
9301
+ ttl_seconds: ttl,
9302
+ strikes: strike,
9303
+ source: entry.source,
9304
+ backend: this.adapter.name
9305
+ }
8877
9306
  });
8878
- return true;
8879
- }
8880
- async unblockIp(ip) {
9307
+ return { ok: true, entry };
9308
+ }
9309
+ /**
9310
+ * Lift a ban. `forget` also drops the strike ledger entry — an operator
9311
+ * unbanning by hand is overruling the detection, so the next offence should
9312
+ * start at one minute again rather than resuming the ladder.
9313
+ */
9314
+ async unban(ip, opts = {}) {
8881
9315
  const idx = this.blocklist.findIndex((b) => b.ip === ip);
8882
- if (idx < 0) return false;
8883
- const entry = this.blocklist[idx];
8884
- if (!entry.dry_run) {
9316
+ const entry = idx >= 0 ? this.blocklist[idx] : null;
9317
+ if (!entry?.dry_run) {
8885
9318
  try {
8886
9319
  await this.adapter.unblock(ip);
8887
9320
  } catch (err) {
8888
- this.logLine(`[firewall] Error unblocking ${ip}: ${err.message}`);
8889
- return false;
9321
+ const message = err.message;
9322
+ this.logLine(`[firewall] error unblocking ${ip}: ${message}`);
9323
+ return { ok: false, error: message };
8890
9324
  }
8891
9325
  }
8892
- this.blocklist.splice(idx, 1);
9326
+ if (idx >= 0) this.blocklist.splice(idx, 1);
9327
+ if (opts.forget) delete this.strikes[ip];
8893
9328
  this.saveState();
8894
- this.logLine(`[firewall] Unblocked ${ip}`);
9329
+ if (idx < 0) return { ok: false, error: `${ip} is not banned` };
9330
+ this.logLine(`[firewall] Unbanned ${ip}${opts.forget ? " (strikes cleared)" : ""}`);
8895
9331
  this.bus.publish({
8896
9332
  timestamp: /* @__PURE__ */ new Date(),
8897
9333
  module: "firewall-rules",
8898
9334
  category: "system",
8899
9335
  severity: "info",
8900
- message: `Unblocked ${ip}`,
9336
+ message: `Unbanned ${ip}`,
8901
9337
  source_ip: ip,
8902
- details: { action: "unblock" }
9338
+ details: { action: "unblock", forget: opts.forget === true }
8903
9339
  });
8904
- return true;
9340
+ return { ok: true };
8905
9341
  }
8906
- isAllowlisted(ip) {
8907
- return this.config.allowlist.includes(ip);
9342
+ /** Lifts every ban this module placed. The "undo it all" of R12. */
9343
+ async flush() {
9344
+ const entries = [...this.blocklist];
9345
+ for (const entry of entries) await this.unban(entry.ip);
9346
+ return entries.length;
9347
+ }
9348
+ getBlocklist() {
9349
+ return [...this.blocklist].sort((a, b) => b.blocked_at - a.blocked_at);
9350
+ }
9351
+ getAllowlist() {
9352
+ return [...this.protectedList];
9353
+ }
9354
+ /** Offence count per address, so the dashboard can show why a ban is long. */
9355
+ getStrikes() {
9356
+ return { ...this.strikes };
9357
+ }
9358
+ status() {
9359
+ return {
9360
+ enabled: this.config.enabled,
9361
+ dry_run: this.config.dry_run,
9362
+ backend: this.adapter.name,
9363
+ min_severity: this.config.min_severity,
9364
+ banned: this.blocklist.length,
9365
+ max_ban_seconds: this.config.max_ban_seconds
9366
+ };
8908
9367
  }
8909
9368
  addToAllowlist(ip) {
8910
- if (!this.config.allowlist.includes(ip)) {
8911
- this.config.allowlist.push(ip);
8912
- }
9369
+ if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
9370
+ if (!this.config.allowlist.includes(ip)) this.config.allowlist.push(ip);
8913
9371
  }
8914
9372
  removeFromAllowlist(ip) {
9373
+ if (DEFAULT_PROTECTED.includes(ip)) return;
9374
+ this.protectedList = this.protectedList.filter((a) => a !== ip);
8915
9375
  this.config.allowlist = this.config.allowlist.filter((a) => a !== ip);
8916
9376
  }
8917
- getBlocklist() {
8918
- return [...this.blocklist];
8919
- }
8920
- getAllowlist() {
8921
- return [...this.config.allowlist];
8922
- }
8923
9377
  stop() {
8924
9378
  if (this.expiryTimer) clearInterval(this.expiryTimer);
8925
9379
  this.expiryTimer = null;
8926
9380
  }
9381
+ /**
9382
+ * R5: bans survive a restart, their TTLs do not. Anything that expired while
9383
+ * the daemon was down is dropped, and anything still live is re-applied —
9384
+ * the firewall may have been flushed by a reboot underneath us.
9385
+ */
9386
+ async reconcile() {
9387
+ const now = Date.now();
9388
+ const live = this.blocklist.filter((b) => b.expires_at > now);
9389
+ const stale = this.blocklist.filter((b) => b.expires_at <= now);
9390
+ for (const entry of stale) {
9391
+ if (!entry.dry_run) {
9392
+ try {
9393
+ await this.adapter.unblock(entry.ip);
9394
+ } catch {
9395
+ }
9396
+ }
9397
+ }
9398
+ this.blocklist = live;
9399
+ this.saveState();
9400
+ if (this.config.dry_run) return;
9401
+ let applied = [];
9402
+ try {
9403
+ applied = await this.adapter.listBlocked();
9404
+ } catch {
9405
+ }
9406
+ for (const entry of live) {
9407
+ if (applied.includes(entry.ip)) continue;
9408
+ try {
9409
+ await this.adapter.block(entry.ip);
9410
+ } catch {
9411
+ }
9412
+ }
9413
+ }
8927
9414
  startExpiryWorker() {
8928
- this.expiryTimer = setInterval(() => void this.processExpiries(), 3e4);
9415
+ this.expiryTimer = setInterval(() => void this.processExpiries(), 1e4);
9416
+ this.expiryTimer.unref?.();
8929
9417
  }
8930
9418
  async processExpiries() {
8931
9419
  const now = Date.now();
8932
- const expired = this.blocklist.filter((b) => b.expires_at && b.expires_at <= now);
8933
- for (const entry of expired) {
8934
- await this.unblockIp(entry.ip);
9420
+ for (const entry of this.blocklist.filter((b) => b.expires_at <= now)) {
9421
+ await this.unban(entry.ip);
9422
+ }
9423
+ const pruned = pruneStrikes(this.strikes, now, this.config.strike_memory_seconds);
9424
+ if (Object.keys(pruned).length !== Object.keys(this.strikes).length) {
9425
+ this.strikes = pruned;
9426
+ this.saveState();
8935
9427
  }
8936
9428
  }
8937
9429
  loadState() {
8938
9430
  try {
8939
9431
  const saved = getModuleState("firewall-rules", "blocklist");
8940
- if (Array.isArray(saved)) this.blocklist = saved;
9432
+ if (Array.isArray(saved)) {
9433
+ this.blocklist = saved.map((entry) => ({
9434
+ ...entry,
9435
+ strikes: entry.strikes ?? 1,
9436
+ source: entry.source ?? "auto",
9437
+ expires_at: entry.expires_at ?? entry.blocked_at + this.config.max_ban_seconds * 1e3
9438
+ }));
9439
+ }
9440
+ } catch {
9441
+ }
9442
+ try {
9443
+ const saved = getModuleState("firewall-rules", "strikes");
9444
+ if (saved && typeof saved === "object") this.strikes = saved;
8941
9445
  } catch {
8942
9446
  }
8943
9447
  }
@@ -8946,16 +9450,41 @@ var RemediationManager = class {
8946
9450
  setModuleState("firewall-rules", "blocklist", this.blocklist);
8947
9451
  } catch {
8948
9452
  }
9453
+ try {
9454
+ setModuleState("firewall-rules", "strikes", this.strikes);
9455
+ } catch {
9456
+ }
8949
9457
  }
8950
9458
  logLine(line) {
8951
9459
  try {
8952
- (0, import_node_fs17.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
9460
+ (0, import_node_fs18.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
8953
9461
  `);
8954
9462
  } catch {
8955
9463
  }
8956
9464
  }
8957
9465
  };
8958
9466
 
9467
+ // src/daemon/firewall/settings.ts
9468
+ function remediationSettings(section) {
9469
+ if (!section) return {};
9470
+ const settings = {};
9471
+ if (typeof section.enabled === "boolean") settings.enabled = section.enabled;
9472
+ if (section.mode === "dry_run") settings.dry_run = true;
9473
+ else if (section.mode === "enforce") settings.dry_run = false;
9474
+ else if (typeof section.dry_run === "boolean") settings.dry_run = section.dry_run;
9475
+ if (section.min_severity) settings.min_severity = section.min_severity;
9476
+ const maxBan = parseDuration(section.max_ban);
9477
+ if (maxBan) settings.max_ban_seconds = maxBan;
9478
+ const memory = parseDuration(section.strike_memory);
9479
+ if (memory) settings.strike_memory_seconds = memory;
9480
+ const allow = [...section.protected ?? [], ...section.allowlist ?? []];
9481
+ if (allow.length > 0) settings.allowlist = allow;
9482
+ if (typeof section.protect_current_ssh_client === "boolean") {
9483
+ settings.protect_current_ssh_client = section.protect_current_ssh_client;
9484
+ }
9485
+ return settings;
9486
+ }
9487
+
8959
9488
  // src/core/telemetry.ts
8960
9489
  var ready = false;
8961
9490
  var sentry = null;
@@ -9005,7 +9534,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
9005
9534
  // src/daemon/index.ts
9006
9535
  function readVersion2() {
9007
9536
  try {
9008
- const pkg = JSON.parse((0, import_node_fs18.readFileSync)((0, import_node_path13.join)(__dirname, "..", "package.json"), "utf-8"));
9537
+ const pkg = JSON.parse((0, import_node_fs19.readFileSync)((0, import_node_path14.join)(__dirname, "..", "package.json"), "utf-8"));
9009
9538
  return pkg.version || "0.0.0";
9010
9539
  } catch {
9011
9540
  return "0.0.0";
@@ -9013,7 +9542,7 @@ function readVersion2() {
9013
9542
  }
9014
9543
  function logLine(line) {
9015
9544
  try {
9016
- (0, import_node_fs18.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
9545
+ (0, import_node_fs19.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
9017
9546
  `);
9018
9547
  } catch {
9019
9548
  }
@@ -9041,7 +9570,7 @@ async function runDaemon() {
9041
9570
  } catch (err) {
9042
9571
  logLine(`[daemon] state db unavailable: ${err.message}`);
9043
9572
  }
9044
- const config = loadConfig((0, import_node_fs18.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
9573
+ const config = loadConfig((0, import_node_fs19.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
9045
9574
  bus.on("event", (event) => {
9046
9575
  logLine(`[event] ${event.severity} ${event.module} ${event.message}`);
9047
9576
  });
@@ -9069,14 +9598,24 @@ async function runDaemon() {
9069
9598
  });
9070
9599
  logLine(`[daemon] rule engine loaded ${ruleEngine.getRules().length} rules`);
9071
9600
  setInterval(() => ruleEngine.cleanup(), 3e5);
9072
- const firewallAdapter = detectFirewallAdapter();
9073
- const remediation = new RemediationManager(firewallAdapter, bus, config.remediation);
9601
+ const settings = remediationSettings(config.remediation);
9602
+ const firewallAdapter = detectFirewallAdapter(config.remediation?.backend ?? "auto");
9603
+ const remediation = new RemediationManager(firewallAdapter, bus, settings);
9074
9604
  bus.on("event", (event) => {
9075
9605
  if (event.module !== "firewall-rules") {
9076
9606
  void remediation.handleDetection(event);
9077
9607
  }
9078
9608
  });
9079
- logLine(`[daemon] firewall remediation active (backend=${firewallAdapter.name}, dry_run=${config.remediation?.dry_run ?? true})`);
9609
+ const remediationStatus = remediation.status();
9610
+ logLine(
9611
+ `[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)`
9612
+ );
9613
+ if (remediationStatus.dry_run && firewallAdapter.enforces !== false) {
9614
+ logLine("[daemon] dry_run is set in [remediation] \u2014 detections will be logged, not blocked");
9615
+ }
9616
+ if (firewallAdapter.enforces === false) {
9617
+ logLine("[daemon] no manageable firewall found (need fail2ban, nftables or iptables) \u2014 bans are simulated");
9618
+ }
9080
9619
  new AlertDispatcher(bus, config);
9081
9620
  const runsWorker = new RunsWorker(bus);
9082
9621
  try {
@@ -9084,7 +9623,7 @@ async function runDaemon() {
9084
9623
  } catch (err) {
9085
9624
  logLine(`[daemon] runs-worker failed to start: ${err.message}`);
9086
9625
  }
9087
- const ipc = new IpcServer(version, moduleHost);
9626
+ const ipc = new IpcServer(version, moduleHost, remediation);
9088
9627
  await ipc.start();
9089
9628
  logLine(`[daemon] ipc listening on ${PATHS.socket}`);
9090
9629
  const shutdown = async (signal) => {