@profullstack/threatcrush 0.13.33 → 0.13.34

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,10 +2022,10 @@ var require_toml = __commonJS({
2022
2022
  });
2023
2023
 
2024
2024
  // src/daemon/index.ts
2025
- var import_node_fs25 = require("fs");
2026
- var import_node_child_process8 = require("child_process");
2025
+ var import_node_fs26 = require("fs");
2026
+ var import_node_child_process9 = require("child_process");
2027
2027
  var import_node_os5 = require("os");
2028
- var import_node_path19 = require("path");
2028
+ var import_node_path20 = require("path");
2029
2029
  var import_node_util = require("util");
2030
2030
 
2031
2031
  // src/daemon/paths.ts
@@ -2674,8 +2674,8 @@ function admGid(readGroup = () => (0, import_node_fs4.readFileSync)("/etc/group"
2674
2674
  }
2675
2675
 
2676
2676
  // src/daemon/module-host.ts
2677
- var import_node_fs12 = require("fs");
2678
- var import_node_path6 = require("path");
2677
+ var import_node_fs13 = require("fs");
2678
+ var import_node_path7 = require("path");
2679
2679
  var import_node_url = require("url");
2680
2680
  var import_toml2 = __toESM(require_toml());
2681
2681
 
@@ -10149,9 +10149,347 @@ var NetworkMonitor = class {
10149
10149
  };
10150
10150
 
10151
10151
  // src/modules/dns-monitor/index.ts
10152
+ var import_node_fs11 = require("fs");
10153
+ var import_node_child_process4 = require("child_process");
10154
+ var import_node_readline = require("readline");
10155
+
10156
+ // src/core/threat-feeds/index.ts
10152
10157
  var import_node_fs10 = require("fs");
10158
+ var import_node_path5 = require("path");
10159
+ var import_node_net3 = require("net");
10160
+
10161
+ // src/daemon/firewall/protected.ts
10153
10162
  var import_node_child_process3 = require("child_process");
10154
- var import_node_readline = require("readline");
10163
+ var import_node_net2 = require("net");
10164
+ var DEFAULT_PROTECTED = [
10165
+ "127.0.0.0/8",
10166
+ "::1/128",
10167
+ "10.0.0.0/8",
10168
+ "172.16.0.0/12",
10169
+ "192.168.0.0/16",
10170
+ "169.254.0.0/16",
10171
+ "fc00::/7",
10172
+ "fe80::/10"
10173
+ ];
10174
+ function ipToBytes(ip) {
10175
+ const version = (0, import_node_net2.isIP)(ip);
10176
+ if (version === 4) return v4ToBytes(ip);
10177
+ if (version === 6) return v6ToBytes(ip);
10178
+ return null;
10179
+ }
10180
+ function v4ToBytes(ip) {
10181
+ const parts = ip.split(".");
10182
+ if (parts.length !== 4) return null;
10183
+ const bytes = new Uint8Array(4);
10184
+ for (let i = 0; i < 4; i++) {
10185
+ const n = Number(parts[i]);
10186
+ if (!Number.isInteger(n) || n < 0 || n > 255) return null;
10187
+ bytes[i] = n;
10188
+ }
10189
+ return bytes;
10190
+ }
10191
+ function v6ToBytes(ip) {
10192
+ const bare = ip.split("%")[0];
10193
+ const [headText, tailText] = bare.split("::", 2);
10194
+ const head = headText ? headText.split(":") : [];
10195
+ const tail = tailText !== void 0 ? tailText ? tailText.split(":") : [] : null;
10196
+ const groups = [];
10197
+ const pushGroup = (group) => {
10198
+ if (group.includes(".")) {
10199
+ const v4 = v4ToBytes(group);
10200
+ if (!v4) return false;
10201
+ groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
10202
+ return true;
10203
+ }
10204
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return false;
10205
+ groups.push(parseInt(group, 16));
10206
+ return true;
10207
+ };
10208
+ for (const group of head) if (!pushGroup(group)) return null;
10209
+ const headCount = groups.length;
10210
+ if (tail === null) {
10211
+ if (headCount !== 8) return null;
10212
+ } else {
10213
+ const tailGroups = [];
10214
+ const saved = groups.length;
10215
+ for (const group of tail) if (!pushGroup(group)) return null;
10216
+ tailGroups.push(...groups.splice(saved));
10217
+ const zeros = 8 - headCount - tailGroups.length;
10218
+ if (zeros < 0) return null;
10219
+ for (let i = 0; i < zeros; i++) groups.push(0);
10220
+ groups.push(...tailGroups);
10221
+ }
10222
+ if (groups.length !== 8) return null;
10223
+ const bytes = new Uint8Array(16);
10224
+ for (let i = 0; i < 8; i++) {
10225
+ bytes[i * 2] = groups[i] >> 8 & 255;
10226
+ bytes[i * 2 + 1] = groups[i] & 255;
10227
+ }
10228
+ return bytes;
10229
+ }
10230
+ function ipMatches(ip, entry) {
10231
+ const [network, prefixText] = entry.trim().split("/");
10232
+ const target = ipToBytes(ip);
10233
+ const base = ipToBytes(network);
10234
+ if (!target || !base || target.length !== base.length) return false;
10235
+ const bits = prefixText === void 0 ? base.length * 8 : Number(prefixText);
10236
+ if (!Number.isInteger(bits) || bits < 0 || bits > base.length * 8) return false;
10237
+ const wholeBytes = Math.floor(bits / 8);
10238
+ for (let i = 0; i < wholeBytes; i++) {
10239
+ if (target[i] !== base[i]) return false;
10240
+ }
10241
+ const remainder = bits % 8;
10242
+ if (remainder === 0) return true;
10243
+ const mask = 255 << 8 - remainder & 255;
10244
+ return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
10245
+ }
10246
+ function isProtected(ip, list) {
10247
+ return list.some((entry) => ipMatches(ip, entry));
10248
+ }
10249
+ function currentSshClient(env2 = process.env) {
10250
+ const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
10251
+ if (!source) return null;
10252
+ const ip = source.trim().split(/\s+/)[0];
10253
+ return ip && (0, import_node_net2.isIP)(ip) ? ip : null;
10254
+ }
10255
+ function establishedSshPeers() {
10256
+ const peers = /* @__PURE__ */ new Set();
10257
+ try {
10258
+ const out = (0, import_node_child_process3.execFileSync)("ss", ["-tnpH"], {
10259
+ encoding: "utf-8",
10260
+ stdio: ["ignore", "pipe", "ignore"],
10261
+ timeout: 3e3
10262
+ });
10263
+ for (const line of out.split("\n")) {
10264
+ if (!/users:\(\("sshd/.test(line)) continue;
10265
+ const parts = line.trim().split(/\s+/);
10266
+ const peer = parts[4];
10267
+ if (!peer) continue;
10268
+ const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
10269
+ if (ip && (0, import_node_net2.isIP)(ip)) peers.add(ip);
10270
+ }
10271
+ } catch {
10272
+ }
10273
+ return [...peers];
10274
+ }
10275
+ function defaultGateways() {
10276
+ const found = /* @__PURE__ */ new Set();
10277
+ for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
10278
+ try {
10279
+ const out = (0, import_node_child_process3.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
10280
+ for (const line of out.split("\n")) {
10281
+ const match = line.match(/\bvia\s+(\S+)/);
10282
+ if (match && (0, import_node_net2.isIP)(match[1])) found.add(match[1]);
10283
+ }
10284
+ } catch {
10285
+ }
10286
+ }
10287
+ return [...found];
10288
+ }
10289
+
10290
+ // src/core/threat-feeds/index.ts
10291
+ var FEEDS = {
10292
+ threatfoxRecent: "https://threatfox.abuse.ch/export/json/recent/",
10293
+ threatfoxHosts: "https://threatfox.abuse.ch/downloads/hostfile/",
10294
+ urlhausHosts: "https://urlhaus.abuse.ch/downloads/hostfile/",
10295
+ feodoIps: "https://feodotracker.abuse.ch/downloads/ipblocklist.txt"
10296
+ };
10297
+ var SHARED_RANGES = [
10298
+ "173.245.48.0/20",
10299
+ "103.21.244.0/22",
10300
+ "103.22.200.0/22",
10301
+ "103.31.4.0/22",
10302
+ "141.101.64.0/18",
10303
+ "108.162.192.0/18",
10304
+ "190.93.240.0/20",
10305
+ "188.114.96.0/20",
10306
+ "197.234.240.0/22",
10307
+ "198.41.128.0/17",
10308
+ "162.158.0.0/15",
10309
+ "104.16.0.0/13",
10310
+ "104.24.0.0/14",
10311
+ "172.64.0.0/13",
10312
+ "131.0.72.0/22",
10313
+ "2400:cb00::/32",
10314
+ "2606:4700::/32",
10315
+ "2803:f800::/32",
10316
+ "2405:b500::/32",
10317
+ "2405:8100::/32",
10318
+ "2a06:98c0::/29",
10319
+ "2c0f:f248::/32",
10320
+ "1.1.1.1/32",
10321
+ "1.0.0.1/32",
10322
+ "8.8.8.8/32",
10323
+ "8.8.4.4/32",
10324
+ "9.9.9.9/32",
10325
+ "149.112.112.112/32",
10326
+ "208.67.222.222/32",
10327
+ "208.67.220.220/32"
10328
+ ];
10329
+ var SHARED_DOMAINS = /* @__PURE__ */ new Set([
10330
+ "workers.dev",
10331
+ "pages.dev",
10332
+ "github.io",
10333
+ "githubusercontent.com",
10334
+ "herokuapp.com",
10335
+ "vercel.app",
10336
+ "netlify.app",
10337
+ "azurewebsites.net",
10338
+ "blob.core.windows.net",
10339
+ "amazonaws.com",
10340
+ "cloudfront.net",
10341
+ "googleusercontent.com",
10342
+ "appspot.com",
10343
+ "firebaseapp.com",
10344
+ "web.app",
10345
+ "r2.dev",
10346
+ "ngrok.io",
10347
+ "ngrok-free.app",
10348
+ "duckdns.org",
10349
+ "discord.com",
10350
+ "discordapp.com",
10351
+ "telegram.org",
10352
+ "dropbox.com",
10353
+ "google.com"
10354
+ ]);
10355
+ function parseThreatFoxJson(text, minConfidence) {
10356
+ const ips = /* @__PURE__ */ new Map();
10357
+ const domains = /* @__PURE__ */ new Map();
10358
+ const data = JSON.parse(text);
10359
+ for (const entries of Object.values(data)) {
10360
+ for (const ioc of Array.isArray(entries) ? entries : []) {
10361
+ const confidence = typeof ioc.confidence_level === "number" ? ioc.confidence_level : 0;
10362
+ if (confidence < minConfidence) continue;
10363
+ const value = String(ioc.ioc_value ?? "").trim();
10364
+ const ind = {
10365
+ malware: String(ioc.malware_printable ?? ioc.malware ?? "unknown"),
10366
+ threat: String(ioc.threat_type ?? "unknown"),
10367
+ feed: "threatfox"
10368
+ };
10369
+ if (ioc.ioc_type === "ip:port") {
10370
+ if (ind.threat !== "botnet_cc" && ind.threat !== "payload_delivery") continue;
10371
+ const ip = stripPort(value);
10372
+ if (ip) ips.set(ip, ind);
10373
+ } else if (ioc.ioc_type === "domain") {
10374
+ const domain = normalizeDomain(value);
10375
+ if (domain) domains.set(domain, ind);
10376
+ }
10377
+ }
10378
+ }
10379
+ return { ips, domains };
10380
+ }
10381
+ function parseHostfile(text, feed) {
10382
+ const out = /* @__PURE__ */ new Map();
10383
+ for (const line of text.split("\n")) {
10384
+ const trimmed = line.trim();
10385
+ if (!trimmed || trimmed.startsWith("#")) continue;
10386
+ const domain = normalizeDomain(trimmed.split(/\s+/)[1] ?? "");
10387
+ if (domain) out.set(domain, { malware: "unknown", threat: "malware_host", feed });
10388
+ }
10389
+ return out;
10390
+ }
10391
+ function parseIpList(text, feed) {
10392
+ const out = /* @__PURE__ */ new Map();
10393
+ for (const line of text.split("\n")) {
10394
+ const ip = line.trim();
10395
+ if (ip && !ip.startsWith("#") && (0, import_node_net3.isIP)(ip)) out.set(ip, { malware: "unknown", threat: "botnet_cc", feed });
10396
+ }
10397
+ return out;
10398
+ }
10399
+ function stripPort(value) {
10400
+ const v6 = /^\[([^\]]+)\]:\d+$/.exec(value);
10401
+ const ip = v6 ? v6[1] : value.replace(/:\d+$/, "");
10402
+ return (0, import_node_net3.isIP)(ip) ? ip : null;
10403
+ }
10404
+ function normalizeDomain(value) {
10405
+ const d = value.trim().toLowerCase().replace(/\.$/, "");
10406
+ if (!d || d === "localhost" || (0, import_node_net3.isIP)(d) || !/^[a-z0-9_.-]+\.[a-z0-9-]{2,}$/.test(d)) return null;
10407
+ return d;
10408
+ }
10409
+ function allowedDomain(domain, allow) {
10410
+ return allow.some((a) => domain === a || domain.endsWith(`.${a}`));
10411
+ }
10412
+ function buildFeedSet(parts, allow, sources, now = /* @__PURE__ */ new Date()) {
10413
+ const neverIps = [...DEFAULT_PROTECTED, ...SHARED_RANGES, ...allow.filter((a) => (0, import_node_net3.isIP)(a.split("/")[0]))];
10414
+ const allowDomains = allow.filter((a) => !(0, import_node_net3.isIP)(a.split("/")[0])).map((a) => a.toLowerCase());
10415
+ const ips = {};
10416
+ const domains = {};
10417
+ let skipped = 0;
10418
+ for (const part of parts) {
10419
+ for (const [ip, ind] of part.ips ?? []) {
10420
+ if (isProtected(ip, neverIps)) {
10421
+ skipped++;
10422
+ continue;
10423
+ }
10424
+ ips[ip] ??= ind;
10425
+ }
10426
+ for (const [domain, ind] of part.domains ?? []) {
10427
+ if (SHARED_DOMAINS.has(domain) || allowedDomain(domain, allowDomains)) {
10428
+ skipped++;
10429
+ continue;
10430
+ }
10431
+ domains[domain] ??= ind;
10432
+ }
10433
+ }
10434
+ return { fetched_at: now.toISOString(), ips, domains, sources, skipped_shared: skipped };
10435
+ }
10436
+ async function fetchFeeds(settings, fetchImpl = fetch) {
10437
+ const sources = [];
10438
+ const parts = [];
10439
+ const get = async (feed, url, parse) => {
10440
+ try {
10441
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(6e4), headers: { "User-Agent": "threatcrush (+https://threatcrush.com)" } });
10442
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
10443
+ const part = parse(await res.text());
10444
+ parts.push(part);
10445
+ sources.push({ feed, ok: true, count: (part.ips?.size ?? 0) + (part.domains?.size ?? 0) });
10446
+ } catch (err) {
10447
+ sources.push({ feed, ok: false, count: 0, error: err.message });
10448
+ }
10449
+ };
10450
+ await Promise.all([
10451
+ get("threatfox", FEEDS.threatfoxRecent, (t) => parseThreatFoxJson(t, settings.minConfidence)),
10452
+ get("threatfox-hosts", FEEDS.threatfoxHosts, (t) => ({ domains: parseHostfile(t, "threatfox") })),
10453
+ get("urlhaus-hosts", FEEDS.urlhausHosts, (t) => ({ domains: parseHostfile(t, "urlhaus") })),
10454
+ get("feodo", FEEDS.feodoIps, (t) => ({ ips: parseIpList(t, "feodo") }))
10455
+ ]);
10456
+ return buildFeedSet(parts, settings.allow, sources);
10457
+ }
10458
+ function readFeedCache(path) {
10459
+ try {
10460
+ const set = JSON.parse((0, import_node_fs10.readFileSync)(path, "utf-8"));
10461
+ return set && typeof set.ips === "object" && typeof set.domains === "object" ? set : null;
10462
+ } catch {
10463
+ return null;
10464
+ }
10465
+ }
10466
+ function writeFeedCache(path, set) {
10467
+ (0, import_node_fs10.mkdirSync)((0, import_node_path5.dirname)(path), { recursive: true });
10468
+ const tmp = `${path}.tmp`;
10469
+ (0, import_node_fs10.writeFileSync)(tmp, JSON.stringify(set));
10470
+ (0, import_node_fs10.renameSync)(tmp, path);
10471
+ }
10472
+ var active = null;
10473
+ function setActiveFeeds(set) {
10474
+ active = set;
10475
+ }
10476
+ function matchIp(ip, set = active) {
10477
+ if (!set) return null;
10478
+ const bare = ip.replace(/^::ffff:/i, "");
10479
+ return set.ips[bare] ?? null;
10480
+ }
10481
+ function matchDomain(name, set = active) {
10482
+ if (!set) return null;
10483
+ const labels = (normalizeDomain(name) ?? "").split(".");
10484
+ for (let i = 0; i < labels.length - 1; i++) {
10485
+ const candidate = labels.slice(i).join(".");
10486
+ const hit = set.domains[candidate];
10487
+ if (hit) return { domain: candidate, indicator: hit };
10488
+ }
10489
+ return null;
10490
+ }
10491
+
10492
+ // src/modules/dns-monitor/index.ts
10155
10493
  var DNS_LOG_SOURCES = [
10156
10494
  "/var/log/syslog",
10157
10495
  // systemd-resolved logs here
@@ -10196,6 +10534,8 @@ var DnsMonitor = class {
10196
10534
  // Tracking windows
10197
10535
  txtQueryCounts = /* @__PURE__ */ new Map();
10198
10536
  domainBuffer = [];
10537
+ /** Last threat-feed alert per domain and client. */
10538
+ feedAlerts = /* @__PURE__ */ new Map();
10199
10539
  // Config
10200
10540
  txtRateThreshold = 20;
10201
10541
  // TXT queries per source per window
@@ -10219,7 +10559,7 @@ var DnsMonitor = class {
10219
10559
  /** True if a systemd unit is loaded on this host (so we do not tail nothing). */
10220
10560
  unitExists(unit) {
10221
10561
  try {
10222
- const r = (0, import_node_child_process3.spawnSync)("systemctl", ["show", unit, "--property=LoadState", "--value"], {
10562
+ const r = (0, import_node_child_process4.spawnSync)("systemctl", ["show", unit, "--property=LoadState", "--value"], {
10223
10563
  encoding: "utf-8",
10224
10564
  stdio: ["ignore", "pipe", "ignore"],
10225
10565
  timeout: 3e3
@@ -10231,9 +10571,9 @@ var DnsMonitor = class {
10231
10571
  }
10232
10572
  start() {
10233
10573
  const sources = [...DNS_LOG_SOURCES, ...this.extraPaths].filter((p) => {
10234
- if (!(0, import_node_fs10.existsSync)(p)) return false;
10574
+ if (!(0, import_node_fs11.existsSync)(p)) return false;
10235
10575
  try {
10236
- (0, import_node_fs10.accessSync)(p, import_node_fs10.constants.R_OK);
10576
+ (0, import_node_fs11.accessSync)(p, import_node_fs11.constants.R_OK);
10237
10577
  return true;
10238
10578
  } catch {
10239
10579
  return false;
@@ -10292,7 +10632,7 @@ var DnsMonitor = class {
10292
10632
  /** Follow one systemd unit's journal, feeding its lines to the same parser. */
10293
10633
  tailJournalUnit(unit) {
10294
10634
  try {
10295
- const child = (0, import_node_child_process3.spawn)("journalctl", ["-u", unit, "-f", "-n", "0", "--output=cat"], {
10635
+ const child = (0, import_node_child_process4.spawn)("journalctl", ["-u", unit, "-f", "-n", "0", "--output=cat"], {
10296
10636
  stdio: ["ignore", "pipe", "ignore"]
10297
10637
  });
10298
10638
  if (!child.stdout) return;
@@ -10433,6 +10773,30 @@ var DnsMonitor = class {
10433
10773
  record(q) {
10434
10774
  this.domainBuffer.push(q);
10435
10775
  this.observed++;
10776
+ this.checkFeeds(q);
10777
+ }
10778
+ /**
10779
+ * A lookup of a domain on the abuse.ch lists (`threat-feeds`). The client
10780
+ * goes in details, never `source_ip`: it is whoever asked, and on a public
10781
+ * resolver that is an outside user auto-defence must not ban. Only a lookup
10782
+ * from this box or a private-range client (a container) is about us.
10783
+ */
10784
+ checkFeeds(q) {
10785
+ const hit = matchDomain(q.domain);
10786
+ if (!hit) return;
10787
+ const now = Date.now();
10788
+ const key = `${hit.domain}|${q.source_ip ?? ""}`;
10789
+ if (now - (this.feedAlerts.get(key) ?? 0) < 36e5) return;
10790
+ this.feedAlerts.set(key, now);
10791
+ if (this.feedAlerts.size > 1e4) this.feedAlerts.clear();
10792
+ const local = !q.source_ip || isProtected(q.source_ip, DEFAULT_PROTECTED);
10793
+ const { malware, threat, feed } = hit.indicator;
10794
+ this.emitEvent(
10795
+ local ? "critical" : "low",
10796
+ `DNS lookup of known ${malware === "unknown" ? "malware" : malware} ${threat === "botnet_cc" ? "C2" : "host"} ${q.domain}${q.source_ip ? ` by ${q.source_ip}` : ""}`,
10797
+ void 0,
10798
+ { rule_id: "threat-feed-dns", domain: q.domain, listed: hit.domain, client_ip: q.source_ip, qtype: q.type, malware, threat, feed }
10799
+ );
10436
10800
  }
10437
10801
  emitEvent(severity, message, sourceIp, details) {
10438
10802
  const event = {
@@ -10453,8 +10817,8 @@ var DnsMonitor = class {
10453
10817
  };
10454
10818
 
10455
10819
  // src/core/config.ts
10456
- var import_node_fs11 = require("fs");
10457
- var import_node_path5 = require("path");
10820
+ var import_node_fs12 = require("fs");
10821
+ var import_node_path6 = require("path");
10458
10822
  var import_toml = __toESM(require_toml());
10459
10823
  var DEFAULT_CONFIG_PATH = "/etc/threatcrush/threatcrushd.conf";
10460
10824
  var DEFAULT_CONFDIR = "/etc/threatcrush/threatcrushd.conf.d";
@@ -10480,11 +10844,11 @@ var DEFAULT_CONFIG = {
10480
10844
  };
10481
10845
  function loadConfig(configPath) {
10482
10846
  const path = configPath || DEFAULT_CONFIG_PATH;
10483
- if (!(0, import_node_fs11.existsSync)(path)) {
10847
+ if (!(0, import_node_fs12.existsSync)(path)) {
10484
10848
  return { ...DEFAULT_CONFIG };
10485
10849
  }
10486
10850
  try {
10487
- const raw = (0, import_node_fs11.readFileSync)(path, "utf-8");
10851
+ const raw = (0, import_node_fs12.readFileSync)(path, "utf-8");
10488
10852
  const parsed = import_toml.default.parse(raw);
10489
10853
  return {
10490
10854
  daemon: { ...DEFAULT_CONFIG.daemon, ...parsed.daemon },
@@ -10496,6 +10860,7 @@ function loadConfig(configPath) {
10496
10860
  cloud: parsed.cloud,
10497
10861
  watchdog: parsed.watchdog,
10498
10862
  update: parsed.update,
10863
+ threat_feeds: parsed.threat_feeds,
10499
10864
  storage: parsed.storage,
10500
10865
  license: parsed.license
10501
10866
  };
@@ -10506,13 +10871,13 @@ function loadConfig(configPath) {
10506
10871
  function loadModuleConfigs(confDir) {
10507
10872
  const dir = confDir || DEFAULT_CONFDIR;
10508
10873
  const configs = /* @__PURE__ */ new Map();
10509
- if (!(0, import_node_fs11.existsSync)(dir)) {
10874
+ if (!(0, import_node_fs12.existsSync)(dir)) {
10510
10875
  return configs;
10511
10876
  }
10512
- const files = (0, import_node_fs11.readdirSync)(dir).filter((f) => f.endsWith(".conf"));
10877
+ const files = (0, import_node_fs12.readdirSync)(dir).filter((f) => f.endsWith(".conf"));
10513
10878
  for (const file of files) {
10514
10879
  try {
10515
- const raw = (0, import_node_fs11.readFileSync)((0, import_node_path5.join)(dir, file), "utf-8");
10880
+ const raw = (0, import_node_fs12.readFileSync)((0, import_node_path6.join)(dir, file), "utf-8");
10516
10881
  const parsed = import_toml.default.parse(raw);
10517
10882
  for (const [name, config] of Object.entries(parsed)) {
10518
10883
  configs.set(name, config);
@@ -10646,15 +11011,15 @@ var ModuleHost = class {
10646
11011
  }
10647
11012
  }
10648
11013
  async discoverAndStartInstalled() {
10649
- if (!(0, import_node_fs12.existsSync)(PATHS.moduleDir)) return;
11014
+ if (!(0, import_node_fs13.existsSync)(PATHS.moduleDir)) return;
10650
11015
  const configs = loadModuleConfigs(PATHS.confD);
10651
- const entries = (0, import_node_fs12.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
11016
+ const entries = (0, import_node_fs13.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
10652
11017
  for (const entry of entries) {
10653
11018
  if (!entry.isDirectory()) continue;
10654
- const manifestPath = (0, import_node_path6.join)(PATHS.moduleDir, entry.name, "mod.toml");
10655
- if (!(0, import_node_fs12.existsSync)(manifestPath)) continue;
11019
+ const manifestPath = (0, import_node_path7.join)(PATHS.moduleDir, entry.name, "mod.toml");
11020
+ if (!(0, import_node_fs13.existsSync)(manifestPath)) continue;
10656
11021
  try {
10657
- const manifest = import_toml2.default.parse((0, import_node_fs12.readFileSync)(manifestPath, "utf-8"));
11022
+ const manifest = import_toml2.default.parse((0, import_node_fs13.readFileSync)(manifestPath, "utf-8"));
10658
11023
  const name = manifest.module?.name || entry.name;
10659
11024
  const defaults = manifest.module?.config?.defaults || {};
10660
11025
  const config = {
@@ -10668,7 +11033,7 @@ var ModuleHost = class {
10668
11033
  source: "installed",
10669
11034
  status: config.enabled === false ? "disabled" : "loaded",
10670
11035
  events: 0,
10671
- path: (0, import_node_path6.join)(PATHS.moduleDir, entry.name),
11036
+ path: (0, import_node_path7.join)(PATHS.moduleDir, entry.name),
10672
11037
  config
10673
11038
  };
10674
11039
  this.modules.set(name, hosted);
@@ -10683,7 +11048,7 @@ var ModuleHost = class {
10683
11048
  status: "error",
10684
11049
  events: 0,
10685
11050
  detail: `manifest load failed: ${String(err.message || err)}`,
10686
- path: (0, import_node_path6.join)(PATHS.moduleDir, entry.name)
11051
+ path: (0, import_node_path7.join)(PATHS.moduleDir, entry.name)
10687
11052
  });
10688
11053
  }
10689
11054
  }
@@ -10722,17 +11087,17 @@ var ModuleHost = class {
10722
11087
  }
10723
11088
  }
10724
11089
  installedEntrypoint(modulePath) {
10725
- const packageJson = (0, import_node_path6.join)(modulePath, "package.json");
11090
+ const packageJson = (0, import_node_path7.join)(modulePath, "package.json");
10726
11091
  const candidates = [];
10727
- if ((0, import_node_fs12.existsSync)(packageJson)) {
11092
+ if ((0, import_node_fs13.existsSync)(packageJson)) {
10728
11093
  try {
10729
- const pkg = JSON.parse((0, import_node_fs12.readFileSync)(packageJson, "utf-8"));
10730
- if (pkg.main) candidates.push((0, import_node_path6.join)(modulePath, pkg.main));
11094
+ const pkg = JSON.parse((0, import_node_fs13.readFileSync)(packageJson, "utf-8"));
11095
+ if (pkg.main) candidates.push((0, import_node_path7.join)(modulePath, pkg.main));
10731
11096
  } catch {
10732
11097
  }
10733
11098
  }
10734
- candidates.push((0, import_node_path6.join)(modulePath, "dist", "index.js"), (0, import_node_path6.join)(modulePath, "index.js"));
10735
- return candidates.find((candidate) => (0, import_node_fs12.existsSync)(candidate)) || null;
11099
+ candidates.push((0, import_node_path7.join)(modulePath, "dist", "index.js"), (0, import_node_path7.join)(modulePath, "index.js"));
11100
+ return candidates.find((candidate) => (0, import_node_fs13.existsSync)(candidate)) || null;
10736
11101
  }
10737
11102
  isThreatCrushModule(value) {
10738
11103
  return Boolean(
@@ -11004,26 +11369,26 @@ function slackChannel(webhookUrl) {
11004
11369
  }
11005
11370
 
11006
11371
  // src/core/cli-config.ts
11007
- var import_node_fs13 = require("fs");
11008
- var import_node_path7 = require("path");
11372
+ var import_node_fs14 = require("fs");
11373
+ var import_node_path8 = require("path");
11009
11374
  var import_node_os2 = require("os");
11010
- var CLI_CONFIG_DIR = (0, import_node_path7.join)((0, import_node_os2.homedir)(), ".threatcrush");
11011
- var CLI_CONFIG_PATH = (0, import_node_path7.join)(CLI_CONFIG_DIR, "config.json");
11375
+ var CLI_CONFIG_DIR = (0, import_node_path8.join)((0, import_node_os2.homedir)(), ".threatcrush");
11376
+ var CLI_CONFIG_PATH = (0, import_node_path8.join)(CLI_CONFIG_DIR, "config.json");
11012
11377
  function apiUrl() {
11013
11378
  return process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
11014
11379
  }
11015
11380
  function readCliConfig() {
11016
11381
  try {
11017
- return JSON.parse((0, import_node_fs13.readFileSync)(CLI_CONFIG_PATH, "utf-8"));
11382
+ return JSON.parse((0, import_node_fs14.readFileSync)(CLI_CONFIG_PATH, "utf-8"));
11018
11383
  } catch {
11019
11384
  return {};
11020
11385
  }
11021
11386
  }
11022
11387
  function writeCliConfig(config) {
11023
- if (!(0, import_node_fs13.existsSync)(CLI_CONFIG_DIR)) (0, import_node_fs13.mkdirSync)(CLI_CONFIG_DIR, { recursive: true });
11024
- (0, import_node_fs13.writeFileSync)(CLI_CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
11388
+ if (!(0, import_node_fs14.existsSync)(CLI_CONFIG_DIR)) (0, import_node_fs14.mkdirSync)(CLI_CONFIG_DIR, { recursive: true });
11389
+ (0, import_node_fs14.writeFileSync)(CLI_CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
11025
11390
  try {
11026
- (0, import_node_fs13.chmodSync)(CLI_CONFIG_PATH, 384);
11391
+ (0, import_node_fs14.chmodSync)(CLI_CONFIG_PATH, 384);
11027
11392
  } catch {
11028
11393
  }
11029
11394
  }
@@ -11099,8 +11464,8 @@ async function cloudFetch(path, init = {}) {
11099
11464
  }
11100
11465
 
11101
11466
  // src/commands/scan.ts
11102
- var import_node_fs17 = require("fs");
11103
- var import_node_path12 = require("path");
11467
+ var import_node_fs18 = require("fs");
11468
+ var import_node_path13 = require("path");
11104
11469
 
11105
11470
  // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
11106
11471
  var ANSI_BACKGROUND_OFFSET = 10;
@@ -11598,13 +11963,13 @@ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
11598
11963
  var source_default = chalk;
11599
11964
 
11600
11965
  // src/core/version.ts
11601
- var import_node_fs14 = require("fs");
11602
- var import_node_path8 = require("path");
11966
+ var import_node_fs15 = require("fs");
11967
+ var import_node_path9 = require("path");
11603
11968
  var FALLBACK_VERSION = "0.0.0";
11604
11969
  function readPackageVersion() {
11605
11970
  try {
11606
11971
  const pkg = JSON.parse(
11607
- (0, import_node_fs14.readFileSync)((0, import_node_path8.join)(__dirname, "..", "package.json"), "utf-8")
11972
+ (0, import_node_fs15.readFileSync)((0, import_node_path9.join)(__dirname, "..", "package.json"), "utf-8")
11608
11973
  );
11609
11974
  return pkg.version || FALLBACK_VERSION;
11610
11975
  } catch {
@@ -14634,8 +14999,8 @@ function scanManifest(relativePath, filename, text) {
14634
14999
  }
14635
15000
 
14636
15001
  // ../../packages/scan/src/node/walk.ts
14637
- var import_node_fs15 = require("fs");
14638
- var import_node_path9 = require("path");
15002
+ var import_node_fs16 = require("fs");
15003
+ var import_node_path10 = require("path");
14639
15004
  function compileExcludes(patterns) {
14640
15005
  const matchers = patterns.map((p) => p.trim()).filter((p) => p.length > 0 && !p.startsWith("#")).map(compilePattern);
14641
15006
  if (matchers.length === 0) return () => false;
@@ -14706,7 +15071,7 @@ function matchPrefix(parts, segs) {
14706
15071
  }
14707
15072
  function readIgnoreFile(root) {
14708
15073
  try {
14709
- return (0, import_node_fs15.readFileSync)((0, import_node_path9.join)(root, ".threatcrushignore"), "utf-8").split("\n");
15074
+ return (0, import_node_fs16.readFileSync)((0, import_node_path10.join)(root, ".threatcrushignore"), "utf-8").split("\n");
14710
15075
  } catch {
14711
15076
  return [];
14712
15077
  }
@@ -14722,16 +15087,16 @@ function scanPath(targetPath, options = {}) {
14722
15087
  let excluded = 0;
14723
15088
  const rootIsDirectory = (() => {
14724
15089
  try {
14725
- return (0, import_node_fs15.statSync)(targetPath).isDirectory();
15090
+ return (0, import_node_fs16.statSync)(targetPath).isDirectory();
14726
15091
  } catch {
14727
15092
  return true;
14728
15093
  }
14729
15094
  })();
14730
- const walkRoot = rootIsDirectory ? targetPath : (0, import_node_path9.dirname)(targetPath);
15095
+ const walkRoot = rootIsDirectory ? targetPath : (0, import_node_path10.dirname)(targetPath);
14731
15096
  const isExcluded = compileExcludes([...options.exclude ?? [], ...readIgnoreFile(walkRoot)]);
14732
15097
  const scanFile = (fullPath, filename) => {
14733
15098
  const relativePath = toRelative(walkRoot, fullPath);
14734
- const extension = (0, import_node_path9.extname)(filename).toLowerCase();
15099
+ const extension = (0, import_node_path10.extname)(filename).toLowerCase();
14735
15100
  const isManifest = filename === "package.json" || filename === "requirements.txt";
14736
15101
  const scannable = SCAN_EXTENSIONS.has(extension) || filename.startsWith(".env");
14737
15102
  const mayDeclareInterpreter = !scannable && !isManifest && extension === "";
@@ -14743,26 +15108,26 @@ function scanPath(targetPath, options = {}) {
14743
15108
  let handle;
14744
15109
  let declared = null;
14745
15110
  try {
14746
- handle = (0, import_node_fs15.openSync)(fullPath, "r");
15111
+ handle = (0, import_node_fs16.openSync)(fullPath, "r");
14747
15112
  } catch {
14748
15113
  unreadable.push(relativePath);
14749
15114
  return;
14750
15115
  }
14751
15116
  try {
14752
- if ((0, import_node_fs15.fstatSync)(handle).size > maxFileBytes) return;
15117
+ if ((0, import_node_fs16.fstatSync)(handle).size > maxFileBytes) return;
14753
15118
  if (mayDeclareInterpreter) {
14754
15119
  const prefix = Buffer.alloc(128);
14755
- const read = (0, import_node_fs15.readSync)(handle, prefix, 0, prefix.length, 0);
15120
+ const read = (0, import_node_fs16.readSync)(handle, prefix, 0, prefix.length, 0);
14756
15121
  declared = languageOfShebang(prefix.subarray(0, read).toString("utf-8").split("\n", 1)[0] ?? "");
14757
15122
  if (!declared) return;
14758
15123
  }
14759
- text = (0, import_node_fs15.readFileSync)(handle, "utf-8");
15124
+ text = (0, import_node_fs16.readFileSync)(handle, "utf-8");
14760
15125
  } catch {
14761
15126
  unreadable.push(relativePath);
14762
15127
  return;
14763
15128
  } finally {
14764
15129
  try {
14765
- (0, import_node_fs15.closeSync)(handle);
15130
+ (0, import_node_fs16.closeSync)(handle);
14766
15131
  } catch {
14767
15132
  }
14768
15133
  }
@@ -14780,13 +15145,13 @@ function scanPath(targetPath, options = {}) {
14780
15145
  const walk = (currentPath) => {
14781
15146
  let entries;
14782
15147
  try {
14783
- entries = (0, import_node_fs15.readdirSync)(currentPath, { withFileTypes: true });
15148
+ entries = (0, import_node_fs16.readdirSync)(currentPath, { withFileTypes: true });
14784
15149
  } catch {
14785
15150
  unreadable.push(toRelative(walkRoot, currentPath));
14786
15151
  return;
14787
15152
  }
14788
15153
  for (const entry of entries) {
14789
- const fullPath = (0, import_node_path9.join)(currentPath, entry.name);
15154
+ const fullPath = (0, import_node_path10.join)(currentPath, entry.name);
14790
15155
  const relativePath = toRelative(walkRoot, fullPath);
14791
15156
  if (entry.isDirectory()) {
14792
15157
  if (SKIP_DIRS.has(entry.name)) continue;
@@ -14810,7 +15175,7 @@ function scanPath(targetPath, options = {}) {
14810
15175
  } else if (isExcluded(toRelative(walkRoot, targetPath))) {
14811
15176
  excluded += 1;
14812
15177
  } else {
14813
- scanFile(targetPath, (0, import_node_path9.basename)(targetPath));
15178
+ scanFile(targetPath, (0, import_node_path10.basename)(targetPath));
14814
15179
  }
14815
15180
  if (options.missingControls) findings.push(...controls.findings());
14816
15181
  const filtered = allowed ? findings.filter((f) => allowed.has(f.category)) : findings;
@@ -14842,22 +15207,22 @@ function recordSensitiveFile(filename, relativePath, sink, fileFindings) {
14842
15207
  }
14843
15208
  }
14844
15209
  function toRelative(base, target) {
14845
- const rel = (0, import_node_path9.relative)(base, target);
14846
- return (rel === "" ? target : rel).split(import_node_path9.sep).join("/");
15210
+ const rel = (0, import_node_path10.relative)(base, target);
15211
+ return (rel === "" ? target : rel).split(import_node_path10.sep).join("/");
14847
15212
  }
14848
15213
 
14849
15214
  // ../../packages/scan/src/node/dependencies.ts
14850
- var import_node_fs16 = require("fs");
14851
- var import_node_path10 = require("path");
15215
+ var import_node_fs17 = require("fs");
15216
+ var import_node_path11 = require("path");
14852
15217
  var MAX_DEPS_PER_LOCKFILE = 50;
14853
15218
  async function scanDependencies(targetPath) {
14854
15219
  const findings = [];
14855
15220
  for (const { file, ecosystem, parse } of LOCKFILES) {
14856
- const lockPath = (0, import_node_path10.join)(targetPath, file);
14857
- if (!(0, import_node_fs16.existsSync)(lockPath)) continue;
15221
+ const lockPath = (0, import_node_path11.join)(targetPath, file);
15222
+ if (!(0, import_node_fs17.existsSync)(lockPath)) continue;
14858
15223
  let deps;
14859
15224
  try {
14860
- deps = dedupe(parse((0, import_node_fs16.readFileSync)(lockPath, "utf-8")));
15225
+ deps = dedupe(parse((0, import_node_fs17.readFileSync)(lockPath, "utf-8")));
14861
15226
  } catch {
14862
15227
  continue;
14863
15228
  }
@@ -15072,16 +15437,16 @@ async function queryOsv(name, version, ecosystem) {
15072
15437
 
15073
15438
  // ../../packages/scan/src/node/sarif.ts
15074
15439
  var import_node_crypto3 = require("crypto");
15075
- var import_node_path11 = require("path");
15440
+ var import_node_path12 = require("path");
15076
15441
 
15077
15442
  // src/commands/scan.ts
15078
15443
  function readVersion() {
15079
15444
  for (const candidate of [
15080
- (0, import_node_path12.join)(__dirname, "..", "package.json"),
15081
- (0, import_node_path12.join)(__dirname, "..", "..", "package.json")
15445
+ (0, import_node_path13.join)(__dirname, "..", "package.json"),
15446
+ (0, import_node_path13.join)(__dirname, "..", "..", "package.json")
15082
15447
  ]) {
15083
15448
  try {
15084
- return JSON.parse((0, import_node_fs17.readFileSync)(candidate, "utf-8")).version ?? "0.0.0";
15449
+ return JSON.parse((0, import_node_fs18.readFileSync)(candidate, "utf-8")).version ?? "0.0.0";
15085
15450
  } catch {
15086
15451
  }
15087
15452
  }
@@ -15426,7 +15791,7 @@ var RunsWorker = class {
15426
15791
 
15427
15792
  // src/core/cloud-events.ts
15428
15793
  var import_node_crypto4 = require("crypto");
15429
- var import_node_net2 = require("net");
15794
+ var import_node_net4 = require("net");
15430
15795
  function currentLink() {
15431
15796
  if (!hasSession()) return null;
15432
15797
  const cfg = readCliConfig();
@@ -15483,7 +15848,7 @@ function detectionEvent(serverId, event) {
15483
15848
  title: title.slice(0, MAX_TITLE_CHARS) || event.module,
15484
15849
  rule_id: str(rule_id) ?? event.module,
15485
15850
  description: str(description),
15486
- source_ip: event.source_ip && (0, import_node_net2.isIP)(event.source_ip) ? event.source_ip : void 0,
15851
+ source_ip: event.source_ip && (0, import_node_net4.isIP)(event.source_ip) ? event.source_ip : void 0,
15487
15852
  username: str(username) ?? str(user),
15488
15853
  raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
15489
15854
  detected_at: event.timestamp.toISOString()
@@ -15525,16 +15890,16 @@ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date(
15525
15890
  }
15526
15891
 
15527
15892
  // src/daemon/workers/cloud-spool.ts
15528
- var import_node_fs18 = require("fs");
15893
+ var import_node_fs19 = require("fs");
15529
15894
  var import_promises = require("fs/promises");
15530
- var import_node_path13 = require("path");
15895
+ var import_node_path14 = require("path");
15531
15896
  var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
15532
15897
  var CloudSpool = class {
15533
15898
  constructor(path, limits = DEFAULT_SPOOL_LIMITS) {
15534
15899
  this.path = path;
15535
15900
  this.limits = limits;
15536
15901
  try {
15537
- (0, import_node_fs18.mkdirSync)((0, import_node_path13.dirname)(path), { recursive: true });
15902
+ (0, import_node_fs19.mkdirSync)((0, import_node_path14.dirname)(path), { recursive: true });
15538
15903
  } catch {
15539
15904
  }
15540
15905
  this.load();
@@ -15603,7 +15968,7 @@ var CloudSpool = class {
15603
15968
  load() {
15604
15969
  let raw;
15605
15970
  try {
15606
- raw = (0, import_node_fs18.readFileSync)(this.path, "utf-8");
15971
+ raw = (0, import_node_fs19.readFileSync)(this.path, "utf-8");
15607
15972
  } catch {
15608
15973
  return;
15609
15974
  }
@@ -15841,142 +16206,13 @@ var CloudSync = class {
15841
16206
  };
15842
16207
 
15843
16208
  // src/daemon/workers/remediation-consumer.ts
15844
- var import_node_net5 = require("net");
15845
-
15846
- // src/daemon/firewall/protected.ts
15847
- var import_node_child_process4 = require("child_process");
15848
- var import_node_net3 = require("net");
15849
- var DEFAULT_PROTECTED = [
15850
- "127.0.0.0/8",
15851
- "::1/128",
15852
- "10.0.0.0/8",
15853
- "172.16.0.0/12",
15854
- "192.168.0.0/16",
15855
- "169.254.0.0/16",
15856
- "fc00::/7",
15857
- "fe80::/10"
15858
- ];
15859
- function ipToBytes(ip) {
15860
- const version = (0, import_node_net3.isIP)(ip);
15861
- if (version === 4) return v4ToBytes(ip);
15862
- if (version === 6) return v6ToBytes(ip);
15863
- return null;
15864
- }
15865
- function v4ToBytes(ip) {
15866
- const parts = ip.split(".");
15867
- if (parts.length !== 4) return null;
15868
- const bytes = new Uint8Array(4);
15869
- for (let i = 0; i < 4; i++) {
15870
- const n = Number(parts[i]);
15871
- if (!Number.isInteger(n) || n < 0 || n > 255) return null;
15872
- bytes[i] = n;
15873
- }
15874
- return bytes;
15875
- }
15876
- function v6ToBytes(ip) {
15877
- const bare = ip.split("%")[0];
15878
- const [headText, tailText] = bare.split("::", 2);
15879
- const head = headText ? headText.split(":") : [];
15880
- const tail = tailText !== void 0 ? tailText ? tailText.split(":") : [] : null;
15881
- const groups = [];
15882
- const pushGroup = (group) => {
15883
- if (group.includes(".")) {
15884
- const v4 = v4ToBytes(group);
15885
- if (!v4) return false;
15886
- groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
15887
- return true;
15888
- }
15889
- if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return false;
15890
- groups.push(parseInt(group, 16));
15891
- return true;
15892
- };
15893
- for (const group of head) if (!pushGroup(group)) return null;
15894
- const headCount = groups.length;
15895
- if (tail === null) {
15896
- if (headCount !== 8) return null;
15897
- } else {
15898
- const tailGroups = [];
15899
- const saved = groups.length;
15900
- for (const group of tail) if (!pushGroup(group)) return null;
15901
- tailGroups.push(...groups.splice(saved));
15902
- const zeros = 8 - headCount - tailGroups.length;
15903
- if (zeros < 0) return null;
15904
- for (let i = 0; i < zeros; i++) groups.push(0);
15905
- groups.push(...tailGroups);
15906
- }
15907
- if (groups.length !== 8) return null;
15908
- const bytes = new Uint8Array(16);
15909
- for (let i = 0; i < 8; i++) {
15910
- bytes[i * 2] = groups[i] >> 8 & 255;
15911
- bytes[i * 2 + 1] = groups[i] & 255;
15912
- }
15913
- return bytes;
15914
- }
15915
- function ipMatches(ip, entry) {
15916
- const [network, prefixText] = entry.trim().split("/");
15917
- const target = ipToBytes(ip);
15918
- const base = ipToBytes(network);
15919
- if (!target || !base || target.length !== base.length) return false;
15920
- const bits = prefixText === void 0 ? base.length * 8 : Number(prefixText);
15921
- if (!Number.isInteger(bits) || bits < 0 || bits > base.length * 8) return false;
15922
- const wholeBytes = Math.floor(bits / 8);
15923
- for (let i = 0; i < wholeBytes; i++) {
15924
- if (target[i] !== base[i]) return false;
15925
- }
15926
- const remainder = bits % 8;
15927
- if (remainder === 0) return true;
15928
- const mask = 255 << 8 - remainder & 255;
15929
- return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
15930
- }
15931
- function isProtected(ip, list) {
15932
- return list.some((entry) => ipMatches(ip, entry));
15933
- }
15934
- function currentSshClient(env2 = process.env) {
15935
- const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
15936
- if (!source) return null;
15937
- const ip = source.trim().split(/\s+/)[0];
15938
- return ip && (0, import_node_net3.isIP)(ip) ? ip : null;
15939
- }
15940
- function establishedSshPeers() {
15941
- const peers = /* @__PURE__ */ new Set();
15942
- try {
15943
- const out = (0, import_node_child_process4.execFileSync)("ss", ["-tnpH"], {
15944
- encoding: "utf-8",
15945
- stdio: ["ignore", "pipe", "ignore"],
15946
- timeout: 3e3
15947
- });
15948
- for (const line of out.split("\n")) {
15949
- if (!/users:\(\("sshd/.test(line)) continue;
15950
- const parts = line.trim().split(/\s+/);
15951
- const peer = parts[4];
15952
- if (!peer) continue;
15953
- const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
15954
- if (ip && (0, import_node_net3.isIP)(ip)) peers.add(ip);
15955
- }
15956
- } catch {
15957
- }
15958
- return [...peers];
15959
- }
15960
- function defaultGateways() {
15961
- const found = /* @__PURE__ */ new Set();
15962
- for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
15963
- try {
15964
- const out = (0, import_node_child_process4.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
15965
- for (const line of out.split("\n")) {
15966
- const match = line.match(/\bvia\s+(\S+)/);
15967
- if (match && (0, import_node_net3.isIP)(match[1])) found.add(match[1]);
15968
- }
15969
- } catch {
15970
- }
15971
- }
15972
- return [...found];
15973
- }
16209
+ var import_node_net6 = require("net");
15974
16210
 
15975
16211
  // src/daemon/workers/allowlist-sync.ts
15976
- var import_node_net4 = require("net");
16212
+ var import_node_net5 = require("net");
15977
16213
  function isAddressOrCidr(value) {
15978
16214
  const [network, prefix, extra] = value.split("/");
15979
- const family = (0, import_node_net4.isIP)(network);
16215
+ const family = (0, import_node_net5.isIP)(network);
15980
16216
  if (family === 0 || extra !== void 0) return false;
15981
16217
  if (prefix === void 0) return true;
15982
16218
  if (!/^\d{1,3}$/.test(prefix)) return false;
@@ -16125,7 +16361,7 @@ var RemediationConsumer = class {
16125
16361
  try {
16126
16362
  switch (action.action_type) {
16127
16363
  case "block": {
16128
- if ((0, import_node_net5.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
16364
+ if ((0, import_node_net6.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
16129
16365
  let ttlSeconds = this.manager.status().max_ban_seconds;
16130
16366
  if (action.expires_at) {
16131
16367
  const until = Date.parse(action.expires_at);
@@ -16144,7 +16380,7 @@ var RemediationConsumer = class {
16144
16380
  return { status: "executed", dry_run: result.entry?.dry_run === true, executed_at };
16145
16381
  }
16146
16382
  case "unblock": {
16147
- if ((0, import_node_net5.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
16383
+ if ((0, import_node_net6.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
16148
16384
  const wasBanned = this.manager.getBlocklist().some((b) => b.ip === target);
16149
16385
  const result = await this.manager.unban(target, {
16150
16386
  forget: true,
@@ -16189,8 +16425,8 @@ var RemediationConsumer = class {
16189
16425
 
16190
16426
  // src/daemon/workers/auto-update.ts
16191
16427
  var import_node_child_process5 = require("child_process");
16192
- var import_node_fs19 = require("fs");
16193
- var import_node_path14 = require("path");
16428
+ var import_node_fs20 = require("fs");
16429
+ var import_node_path15 = require("path");
16194
16430
  var PKG_NAME = "@profullstack/threatcrush";
16195
16431
  var REGISTRY = `https://registry.npmjs.org/${PKG_NAME}`;
16196
16432
  var DEFAULT_INTERVAL_MS = 6 * 36e5;
@@ -16227,12 +16463,12 @@ function pickUpdate(doc, current, opts) {
16227
16463
  return { version: latest };
16228
16464
  }
16229
16465
  function installPlan(opts) {
16230
- const expected = `${import_node_path14.sep}lib${import_node_path14.sep}node_modules${import_node_path14.sep}@profullstack${import_node_path14.sep}threatcrush`;
16466
+ const expected = `${import_node_path15.sep}lib${import_node_path15.sep}node_modules${import_node_path15.sep}@profullstack${import_node_path15.sep}threatcrush`;
16231
16467
  if (!opts.pkgRoot.endsWith(expected)) {
16232
16468
  return { kind: "unsupported", reason: `not an npm global install (${opts.pkgRoot}); run \`threatcrush update\`` };
16233
16469
  }
16234
- const nodeBin = (0, import_node_path14.dirname)(opts.execPath);
16235
- const npm = (0, import_node_path14.join)(nodeBin, "npm");
16470
+ const nodeBin = (0, import_node_path15.dirname)(opts.execPath);
16471
+ const npm = (0, import_node_path15.join)(nodeBin, "npm");
16236
16472
  if (!opts.npmExists(npm)) return { kind: "unsupported", reason: `no npm beside ${opts.execPath}` };
16237
16473
  if (!opts.owner) return { kind: "unsupported", reason: `cannot tell who owns ${opts.pkgRoot}` };
16238
16474
  const npmArgs = [npm, "i", "-g", `${PKG_NAME}@${opts.version}`, "--no-fund", "--no-audit"];
@@ -16264,10 +16500,10 @@ function installPlan(opts) {
16264
16500
  }
16265
16501
  function ownerOf(path, passwd = "/etc/passwd") {
16266
16502
  try {
16267
- const st = (0, import_node_fs19.statSync)(path);
16503
+ const st = (0, import_node_fs20.statSync)(path);
16268
16504
  let home = st.uid === 0 ? "/root" : "";
16269
16505
  try {
16270
- for (const line of (0, import_node_fs19.readFileSync)(passwd, "utf8").split("\n")) {
16506
+ for (const line of (0, import_node_fs20.readFileSync)(passwd, "utf8").split("\n")) {
16271
16507
  const f = line.split(":");
16272
16508
  if (Number(f[2]) === st.uid && f[5]) home = f[5];
16273
16509
  }
@@ -16372,7 +16608,7 @@ var AutoUpdate = class {
16372
16608
  uid: process.getuid?.() ?? -1,
16373
16609
  owner: ownerOf(this.opts.pkgRoot),
16374
16610
  underSystemd: this.opts.underSystemd ?? Boolean(process.env.INVOCATION_ID),
16375
- npmExists: import_node_fs19.existsSync
16611
+ npmExists: import_node_fs20.existsSync
16376
16612
  });
16377
16613
  if (plan.kind === "unsupported") return this.note(`${target} is available but cannot self-install: ${plan.reason}`);
16378
16614
  this.recordAttempt(target);
@@ -16407,7 +16643,7 @@ var AutoUpdate = class {
16407
16643
  }
16408
16644
  lastAttempt() {
16409
16645
  try {
16410
- const v = JSON.parse((0, import_node_fs19.readFileSync)(this.opts.statePath, "utf8"));
16646
+ const v = JSON.parse((0, import_node_fs20.readFileSync)(this.opts.statePath, "utf8"));
16411
16647
  return v.version && typeof v.at === "number" ? { version: v.version, at: v.at } : null;
16412
16648
  } catch {
16413
16649
  return null;
@@ -16415,13 +16651,219 @@ var AutoUpdate = class {
16415
16651
  }
16416
16652
  recordAttempt(version) {
16417
16653
  try {
16418
- (0, import_node_fs19.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
16654
+ (0, import_node_fs20.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
16419
16655
  } catch (err) {
16420
16656
  this.opts.log(`[update] could not record attempt: ${err.message}`);
16421
16657
  }
16422
16658
  }
16423
16659
  };
16424
16660
 
16661
+ // src/daemon/workers/threat-feeds.ts
16662
+ var import_node_child_process6 = require("child_process");
16663
+ var import_node_net7 = require("net");
16664
+ var EGRESS_TABLE = "threatcrush_egress";
16665
+ var DEFAULT_REFRESH_MS = 36e5;
16666
+ var POLL_MS = 15e3;
16667
+ var REALERT_MS = 36e5;
16668
+ function threatFeedSettings(section) {
16669
+ const refresh = parseDuration(section?.refresh);
16670
+ return {
16671
+ enabled: section?.enabled !== false,
16672
+ block: section?.block === true,
16673
+ // abuse.ch asks for no more than one fetch per 5 minutes; hourly is plenty.
16674
+ refreshMs: refresh ? Math.max(900, refresh) * 1e3 : DEFAULT_REFRESH_MS,
16675
+ minConfidence: typeof section?.min_confidence === "number" ? section.min_confidence : 75,
16676
+ allow: Array.isArray(section?.allow) ? section.allow.map(String) : []
16677
+ };
16678
+ }
16679
+ function egressRuleset(ips) {
16680
+ const v4 = ips.filter((ip) => (0, import_node_net7.isIP)(ip) === 4);
16681
+ const v6 = ips.filter((ip) => (0, import_node_net7.isIP)(ip) === 6);
16682
+ const set = (name, type, items) => ` set ${name} { type ${type};${items.length ? ` elements = { ${items.join(", ")} }` : ""} }`;
16683
+ const chain = (name, hook) => [
16684
+ ` chain ${name} {`,
16685
+ ` type filter hook ${hook} priority -1; policy accept;`,
16686
+ ` ip daddr @c2_v4 counter drop`,
16687
+ ` ip6 daddr @c2_v6 counter drop`,
16688
+ ` }`
16689
+ ].join("\n");
16690
+ return [
16691
+ `table inet ${EGRESS_TABLE}`,
16692
+ `delete table inet ${EGRESS_TABLE}`,
16693
+ `table inet ${EGRESS_TABLE} {`,
16694
+ set("c2_v4", "ipv4_addr", v4),
16695
+ set("c2_v6", "ipv6_addr", v6),
16696
+ chain("output", "output"),
16697
+ chain("forward", "forward"),
16698
+ `}`,
16699
+ ""
16700
+ ].join("\n");
16701
+ }
16702
+ function splitAddr(addr) {
16703
+ const m = /^\[?(.+?)\]?:(\d+|\*)$/.exec(addr);
16704
+ if (!m) return null;
16705
+ const ip = m[1].replace(/%.*$/, "").replace(/^::ffff:/i, "");
16706
+ return (0, import_node_net7.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
16707
+ }
16708
+ function parseSs(text) {
16709
+ const out = [];
16710
+ for (const line of text.split("\n")) {
16711
+ const cols = line.trim().split(/\s+/);
16712
+ if (cols.length < 5) continue;
16713
+ const local = splitAddr(cols[3]);
16714
+ const peer = splitAddr(cols[4]);
16715
+ if (!local || !peer) continue;
16716
+ const proc = /users:\(\("([^"]+)",pid=(\d+)/.exec(line);
16717
+ out.push({
16718
+ state: cols[0],
16719
+ localPort: local.port,
16720
+ peerIp: peer.ip,
16721
+ peerPort: peer.port,
16722
+ process: proc?.[1] ?? null,
16723
+ pid: proc ? Number(proc[2]) : null
16724
+ });
16725
+ }
16726
+ return out;
16727
+ }
16728
+ function parseListeningPorts(text) {
16729
+ const ports = /* @__PURE__ */ new Set();
16730
+ for (const line of text.split("\n")) {
16731
+ const cols = line.trim().split(/\s+/);
16732
+ const local = cols.length >= 4 ? splitAddr(cols[3]) : null;
16733
+ if (local) ports.add(local.port);
16734
+ }
16735
+ return ports;
16736
+ }
16737
+ function defaultRun2(cmd, args, input) {
16738
+ const res = (0, import_node_child_process6.spawnSync)(cmd, args, { encoding: "utf-8", input, timeout: 15e3, stdio: ["pipe", "pipe", "pipe"] });
16739
+ return res.status === 0 ? res.stdout : null;
16740
+ }
16741
+ var ThreatFeeds = class {
16742
+ constructor(opts) {
16743
+ this.opts = opts;
16744
+ this.run = opts.run ?? defaultRun2;
16745
+ this.now = opts.now ?? Date.now;
16746
+ }
16747
+ opts;
16748
+ timers = [];
16749
+ set = null;
16750
+ alerted = /* @__PURE__ */ new Map();
16751
+ blocking = false;
16752
+ run;
16753
+ now;
16754
+ get wantsBlock() {
16755
+ return this.opts.settings.block && this.opts.enforcing;
16756
+ }
16757
+ start() {
16758
+ const { settings } = this.opts;
16759
+ if (!settings.enabled) {
16760
+ this.opts.log("[threat-feeds] disabled by [threat_feeds] enabled = false");
16761
+ this.removeBlocking();
16762
+ return;
16763
+ }
16764
+ if (settings.block && !this.opts.enforcing) {
16765
+ this.opts.log("[threat-feeds] block = true but remediation is in dry_run (or has no firewall): detecting only");
16766
+ }
16767
+ const cached = readFeedCache(this.opts.cachePath);
16768
+ if (cached) this.apply(cached, "cache");
16769
+ if (!this.wantsBlock) this.removeBlocking();
16770
+ const stale = !cached || this.now() - Date.parse(cached.fetched_at) > settings.refreshMs;
16771
+ const first = setTimeout(() => void this.refresh(), stale ? 1e4 : settings.refreshMs);
16772
+ first.unref?.();
16773
+ const every = setInterval(() => void this.refresh(), settings.refreshMs);
16774
+ every.unref?.();
16775
+ const poll = setInterval(() => this.pollConnections(), POLL_MS);
16776
+ poll.unref?.();
16777
+ this.timers.push(first, every, poll);
16778
+ }
16779
+ stop() {
16780
+ for (const t of this.timers) clearInterval(t);
16781
+ this.timers = [];
16782
+ }
16783
+ async refresh() {
16784
+ try {
16785
+ const set = await fetchFeeds(this.opts.settings, this.opts.fetchImpl);
16786
+ const failed = set.sources.filter((s) => !s.ok);
16787
+ if (failed.length === set.sources.length) {
16788
+ this.opts.log(`[threat-feeds] refresh failed, keeping previous list: ${failed.map((s) => `${s.feed}: ${s.error}`).join("; ")}`);
16789
+ return;
16790
+ }
16791
+ for (const f of failed) this.opts.log(`[threat-feeds] ${f.feed} unavailable: ${f.error}`);
16792
+ try {
16793
+ writeFeedCache(this.opts.cachePath, set);
16794
+ } catch (err) {
16795
+ this.opts.log(`[threat-feeds] could not write cache: ${err.message}`);
16796
+ }
16797
+ this.apply(set, "refresh");
16798
+ } catch (err) {
16799
+ this.opts.log(`[threat-feeds] refresh failed: ${err.message}`);
16800
+ }
16801
+ }
16802
+ apply(set, from) {
16803
+ this.set = set;
16804
+ setActiveFeeds(set);
16805
+ const ips = Object.keys(set.ips);
16806
+ const domains = Object.keys(set.domains).length;
16807
+ let mode = "detecting";
16808
+ if (this.wantsBlock) {
16809
+ const ok = this.run("nft", ["-f", "-"], egressRuleset(ips)) !== null;
16810
+ this.blocking = ok;
16811
+ mode = ok ? "blocking egress" : "detecting (nft load failed)";
16812
+ }
16813
+ const detail = `${ips.length} IPs, ${domains} domains, ${mode}`;
16814
+ this.opts.log(`[threat-feeds] ${from === "cache" ? "loaded cached" : "refreshed"} list: ${detail} (${set.skipped_shared} shared/protected entries skipped)`);
16815
+ this.opts.bus.announceModule("threat-feeds", "running", detail);
16816
+ }
16817
+ removeBlocking() {
16818
+ if (this.run("nft", ["list", "table", "inet", EGRESS_TABLE]) !== null) {
16819
+ this.run("nft", ["delete", "table", "inet", EGRESS_TABLE]);
16820
+ this.opts.log(`[threat-feeds] removed egress table ${EGRESS_TABLE} (blocking is off)`);
16821
+ }
16822
+ this.blocking = false;
16823
+ }
16824
+ /** Outbound connections to listed IPs, one alert per IP and process per hour. */
16825
+ pollConnections() {
16826
+ if (!this.set || Object.keys(this.set.ips).length === 0) return;
16827
+ const conns = this.run("ss", ["-tnpH"]);
16828
+ if (conns === null) return;
16829
+ const listening = parseListeningPorts(this.run("ss", ["-ltnH"]) ?? "");
16830
+ const now = this.now();
16831
+ for (const c of parseSs(conns)) {
16832
+ if (listening.has(c.localPort)) continue;
16833
+ const ind = matchIp(c.peerIp, this.set);
16834
+ if (!ind) continue;
16835
+ const key = `${c.peerIp}|${c.process ?? "?"}`;
16836
+ if (now - (this.alerted.get(key) ?? 0) < REALERT_MS) continue;
16837
+ this.alerted.set(key, now);
16838
+ const who = c.process ? `${c.process} (pid ${c.pid})` : "an unknown process";
16839
+ const blocked = this.blocking ? " \u2014 blocked" : "";
16840
+ this.opts.bus.publish({
16841
+ timestamp: new Date(now),
16842
+ module: "threat-feeds",
16843
+ category: "network",
16844
+ severity: "critical",
16845
+ message: `Outbound connection to known ${ind.malware} ${ind.threat === "botnet_cc" ? "C2" : "malware host"} ${c.peerIp}:${c.peerPort} by ${who}${blocked}`,
16846
+ // No source_ip on purpose: the remote end is not an attacker to ban
16847
+ // inbound, so remediation has nothing to act on and the egress table
16848
+ // stays the only enforcement.
16849
+ details: {
16850
+ rule_id: "threat-feed-outbound",
16851
+ destination_ip: c.peerIp,
16852
+ destination_port: c.peerPort,
16853
+ state: c.state,
16854
+ process: c.process,
16855
+ pid: c.pid,
16856
+ malware: ind.malware,
16857
+ threat: ind.threat,
16858
+ feed: ind.feed,
16859
+ blocked: this.blocking
16860
+ }
16861
+ });
16862
+ }
16863
+ for (const [key, at] of this.alerted) if (now - at > REALERT_MS) this.alerted.delete(key);
16864
+ }
16865
+ };
16866
+
16425
16867
  // src/daemon/rules/engine.ts
16426
16868
  var MAX_WINDOW_ENTRIES = 1e3;
16427
16869
  function live(window) {
@@ -16583,8 +17025,8 @@ var RuleEngine = class {
16583
17025
  };
16584
17026
 
16585
17027
  // src/daemon/rules/loader.ts
16586
- var import_node_fs20 = require("fs");
16587
- var import_node_path15 = require("path");
17028
+ var import_node_fs21 = require("fs");
17029
+ var import_node_path16 = require("path");
16588
17030
 
16589
17031
  // src/daemon/rules/default-rules.ts
16590
17032
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -16985,11 +17427,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
16985
17427
  function loadAllRules(customDir) {
16986
17428
  const rules = [...DEFAULT_RULES];
16987
17429
  const dir = customDir || RULES_DIR;
16988
- if ((0, import_node_fs20.existsSync)(dir)) {
16989
- const files = (0, import_node_fs20.readdirSync)(dir).filter((f) => f.endsWith(".json"));
17430
+ if ((0, import_node_fs21.existsSync)(dir)) {
17431
+ const files = (0, import_node_fs21.readdirSync)(dir).filter((f) => f.endsWith(".json"));
16990
17432
  for (const file of files) {
16991
17433
  try {
16992
- const raw = (0, import_node_fs20.readFileSync)((0, import_node_path15.join)(dir, file), "utf-8");
17434
+ const raw = (0, import_node_fs21.readFileSync)((0, import_node_path16.join)(dir, file), "utf-8");
16993
17435
  const parsed = JSON.parse(raw);
16994
17436
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
16995
17437
  for (const rule of customRules) {
@@ -17020,24 +17462,24 @@ function loadAllRules(customDir) {
17020
17462
  }
17021
17463
 
17022
17464
  // src/daemon/firewall/adapters.ts
17023
- var import_node_child_process6 = require("child_process");
17024
- var import_node_fs21 = require("fs");
17025
- var import_node_path16 = require("path");
17026
- var import_node_net6 = require("net");
17465
+ var import_node_child_process7 = require("child_process");
17466
+ var import_node_fs22 = require("fs");
17467
+ var import_node_path17 = require("path");
17468
+ var import_node_net8 = require("net");
17027
17469
  function assertValidFirewallIp(ip) {
17028
- if ((0, import_node_net6.isIP)(ip) !== 4) {
17470
+ if ((0, import_node_net8.isIP)(ip) !== 4) {
17029
17471
  throw new Error(`Invalid IPv4 address: ${ip}`);
17030
17472
  }
17031
17473
  }
17032
17474
  function assertBannableIp(ip) {
17033
- if ((0, import_node_net6.isIP)(ip) === 0) {
17475
+ if ((0, import_node_net8.isIP)(ip) === 0) {
17034
17476
  throw new Error(`Invalid IP address: ${ip}`);
17035
17477
  }
17036
17478
  }
17037
17479
  function writeIfAbsent(path, contents) {
17038
- (0, import_node_fs21.mkdirSync)((0, import_node_path16.dirname)(path), { recursive: true });
17480
+ (0, import_node_fs22.mkdirSync)((0, import_node_path17.dirname)(path), { recursive: true });
17039
17481
  try {
17040
- (0, import_node_fs21.writeFileSync)(path, contents, { flag: "wx" });
17482
+ (0, import_node_fs22.writeFileSync)(path, contents, { flag: "wx" });
17041
17483
  } catch (err) {
17042
17484
  if (err.code !== "EEXIST") throw err;
17043
17485
  }
@@ -17056,11 +17498,11 @@ var Fail2banAdapter = class {
17056
17498
  enforces = true;
17057
17499
  jailReady = false;
17058
17500
  isAvailable() {
17059
- const result = (0, import_node_child_process6.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
17501
+ const result = (0, import_node_child_process7.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
17060
17502
  return result.status === 0;
17061
17503
  }
17062
17504
  client(args) {
17063
- return (0, import_node_child_process6.execFileSync)("fail2ban-client", args, {
17505
+ return (0, import_node_child_process7.execFileSync)("fail2ban-client", args, {
17064
17506
  encoding: "utf-8",
17065
17507
  stdio: ["ignore", "pipe", "pipe"]
17066
17508
  });
@@ -17136,7 +17578,7 @@ var Fail2banAdapter = class {
17136
17578
  const status = this.client(["status", this.jail]);
17137
17579
  const line = status.split("\n").find((l) => /Banned IP list:/i.test(l));
17138
17580
  if (!line) return [];
17139
- return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net6.isIP)(s) !== 0);
17581
+ return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net8.isIP)(s) !== 0);
17140
17582
  } catch {
17141
17583
  return [];
17142
17584
  }
@@ -17146,45 +17588,45 @@ var Fail2banAdapter = class {
17146
17588
  function parseBannedList(output) {
17147
17589
  const found = [];
17148
17590
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
17149
- if ((0, import_node_net6.isIP)(match[1]) !== 0) found.push(match[1]);
17591
+ if ((0, import_node_net8.isIP)(match[1]) !== 0) found.push(match[1]);
17150
17592
  }
17151
17593
  if (found.length > 0) return found;
17152
- return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net6.isIP)(s) !== 0);
17594
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net8.isIP)(s) !== 0);
17153
17595
  }
17154
17596
  var NftablesAdapter = class {
17155
17597
  name = "nftables";
17156
17598
  table = "threatcrush";
17157
17599
  set = "blocklist";
17158
17600
  isAvailable() {
17159
- const result = (0, import_node_child_process6.spawnSync)("nft", ["--version"], { stdio: "pipe" });
17601
+ const result = (0, import_node_child_process7.spawnSync)("nft", ["--version"], { stdio: "pipe" });
17160
17602
  return result.status === 0;
17161
17603
  }
17162
17604
  ensureSetup() {
17163
17605
  try {
17164
- (0, import_node_child_process6.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
17606
+ (0, import_node_child_process7.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
17165
17607
  } catch {
17166
- (0, import_node_child_process6.execSync)(`nft add table inet ${this.table}`);
17167
- (0, import_node_child_process6.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
17168
- (0, import_node_child_process6.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
17169
- (0, import_node_child_process6.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
17608
+ (0, import_node_child_process7.execSync)(`nft add table inet ${this.table}`);
17609
+ (0, import_node_child_process7.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
17610
+ (0, import_node_child_process7.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
17611
+ (0, import_node_child_process7.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
17170
17612
  }
17171
17613
  }
17172
17614
  async block(ip) {
17173
17615
  assertValidFirewallIp(ip);
17174
17616
  this.ensureSetup();
17175
- (0, import_node_child_process6.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
17617
+ (0, import_node_child_process7.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
17176
17618
  }
17177
17619
  async unblock(ip) {
17178
17620
  assertValidFirewallIp(ip);
17179
17621
  try {
17180
- (0, import_node_child_process6.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
17622
+ (0, import_node_child_process7.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
17181
17623
  } catch {
17182
17624
  }
17183
17625
  }
17184
17626
  async isBlocked(ip) {
17185
17627
  assertValidFirewallIp(ip);
17186
17628
  try {
17187
- const output = (0, import_node_child_process6.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
17629
+ const output = (0, import_node_child_process7.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
17188
17630
  return output.includes(ip);
17189
17631
  } catch {
17190
17632
  return false;
@@ -17192,7 +17634,7 @@ var NftablesAdapter = class {
17192
17634
  }
17193
17635
  async listBlocked() {
17194
17636
  try {
17195
- const output = (0, import_node_child_process6.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
17637
+ const output = (0, import_node_child_process7.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
17196
17638
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
17197
17639
  if (!match) return [];
17198
17640
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -17205,34 +17647,34 @@ var IptablesAdapter = class {
17205
17647
  name = "iptables";
17206
17648
  chain = "THREATCRUSH";
17207
17649
  isAvailable() {
17208
- const result = (0, import_node_child_process6.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
17650
+ const result = (0, import_node_child_process7.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
17209
17651
  return result.status === 0;
17210
17652
  }
17211
17653
  ensureChain() {
17212
17654
  try {
17213
- (0, import_node_child_process6.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
17655
+ (0, import_node_child_process7.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
17214
17656
  } catch {
17215
- (0, import_node_child_process6.execSync)(`iptables -N ${this.chain}`);
17216
- (0, import_node_child_process6.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
17657
+ (0, import_node_child_process7.execSync)(`iptables -N ${this.chain}`);
17658
+ (0, import_node_child_process7.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
17217
17659
  }
17218
17660
  }
17219
17661
  async block(ip) {
17220
17662
  assertValidFirewallIp(ip);
17221
17663
  this.ensureChain();
17222
17664
  if (await this.isBlocked(ip)) return;
17223
- (0, import_node_child_process6.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
17665
+ (0, import_node_child_process7.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
17224
17666
  }
17225
17667
  async unblock(ip) {
17226
17668
  assertValidFirewallIp(ip);
17227
17669
  try {
17228
- (0, import_node_child_process6.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
17670
+ (0, import_node_child_process7.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
17229
17671
  } catch {
17230
17672
  }
17231
17673
  }
17232
17674
  async isBlocked(ip) {
17233
17675
  assertValidFirewallIp(ip);
17234
17676
  try {
17235
- const output = (0, import_node_child_process6.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
17677
+ const output = (0, import_node_child_process7.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
17236
17678
  return output.includes(ip);
17237
17679
  } catch {
17238
17680
  return false;
@@ -17240,7 +17682,7 @@ var IptablesAdapter = class {
17240
17682
  }
17241
17683
  async listBlocked() {
17242
17684
  try {
17243
- const output = (0, import_node_child_process6.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
17685
+ const output = (0, import_node_child_process7.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
17244
17686
  const ips = [];
17245
17687
  for (const line of output.split("\n")) {
17246
17688
  const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -17296,8 +17738,8 @@ function detectFirewallAdapter(backend = "auto") {
17296
17738
  }
17297
17739
 
17298
17740
  // src/daemon/firewall/remediation.ts
17299
- var import_node_fs22 = require("fs");
17300
- var import_node_net7 = require("net");
17741
+ var import_node_fs23 = require("fs");
17742
+ var import_node_net9 = require("net");
17301
17743
 
17302
17744
  // src/daemon/firewall/crawlers.ts
17303
17745
  var import_node_dns = require("dns");
@@ -17432,7 +17874,7 @@ var RemediationManager = class {
17432
17874
  if (remediation?.action !== "block") return;
17433
17875
  }
17434
17876
  const ip = event.source_ip;
17435
- if (!ip || (0, import_node_net7.isIP)(ip) === 0) return;
17877
+ if (!ip || (0, import_node_net9.isIP)(ip) === 0) return;
17436
17878
  if (this.isAllowlisted(ip)) return;
17437
17879
  if (this.blocklist.some((b) => b.ip === ip)) return;
17438
17880
  if (this.config.spare_verified_crawlers) {
@@ -17451,7 +17893,7 @@ var RemediationManager = class {
17451
17893
  * 4th offence and so on, clamped to `max_ban_seconds`.
17452
17894
  */
17453
17895
  async ban(ip, reason, opts = {}) {
17454
- if ((0, import_node_net7.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
17896
+ if ((0, import_node_net9.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
17455
17897
  if (this.isAllowlisted(ip)) {
17456
17898
  return { ok: false, error: `${ip} is protected and can never be blocked` };
17457
17899
  }
@@ -17708,7 +18150,7 @@ var RemediationManager = class {
17708
18150
  }
17709
18151
  logLine(line) {
17710
18152
  try {
17711
- (0, import_node_fs22.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18153
+ (0, import_node_fs23.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17712
18154
  `);
17713
18155
  } catch {
17714
18156
  }
@@ -17742,13 +18184,13 @@ function remediationSettings(section) {
17742
18184
  }
17743
18185
 
17744
18186
  // src/daemon/watchdog-service.ts
17745
- var import_node_fs24 = require("fs");
17746
- var import_node_path18 = require("path");
18187
+ var import_node_fs25 = require("fs");
18188
+ var import_node_path19 = require("path");
17747
18189
 
17748
18190
  // src/core/watchdog.ts
17749
- var import_node_fs23 = require("fs");
18191
+ var import_node_fs24 = require("fs");
17750
18192
  var import_node_crypto5 = require("crypto");
17751
- var import_node_path17 = require("path");
18193
+ var import_node_path18 = require("path");
17752
18194
  var WATCHDOG_DIRNAME = "watchdog";
17753
18195
  var LOG_FILE = "attacks.jsonl";
17754
18196
  var ROTATED_FILE = "attacks.1.jsonl";
@@ -17837,12 +18279,12 @@ var WatchdogLog = class {
17837
18279
  stats = { logged: 0, answered: 0, errored: 0 };
17838
18280
  constructor(dir, options = {}) {
17839
18281
  this.dir = dir;
17840
- this.file = (0, import_node_path17.join)(dir, LOG_FILE);
18282
+ this.file = (0, import_node_path18.join)(dir, LOG_FILE);
17841
18283
  this.shareGid = options.shareGid;
17842
- (0, import_node_fs23.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
18284
+ (0, import_node_fs24.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
17843
18285
  if (this.shareGid !== void 0) {
17844
- (0, import_node_fs23.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
17845
- (0, import_node_fs23.chmodSync)(dir, 1528);
18286
+ (0, import_node_fs24.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
18287
+ (0, import_node_fs24.chmodSync)(dir, 1528);
17846
18288
  }
17847
18289
  for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
17848
18290
  }
@@ -17871,16 +18313,16 @@ var WatchdogLog = class {
17871
18313
  const chunk = this.buffer.join("\n") + "\n";
17872
18314
  this.buffer = [];
17873
18315
  try {
17874
- if ((0, import_node_fs23.statSync)(this.file).size > ROTATE_BYTES) {
17875
- (0, import_node_fs23.renameSync)(this.file, (0, import_node_path17.join)(this.dir, ROTATED_FILE));
18316
+ if ((0, import_node_fs24.statSync)(this.file).size > ROTATE_BYTES) {
18317
+ (0, import_node_fs24.renameSync)(this.file, (0, import_node_path18.join)(this.dir, ROTATED_FILE));
17876
18318
  }
17877
18319
  } catch {
17878
18320
  }
17879
- (0, import_node_fs23.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
18321
+ (0, import_node_fs24.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
17880
18322
  if (this.shareGid !== void 0) {
17881
18323
  try {
17882
- (0, import_node_fs23.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
17883
- (0, import_node_fs23.chmodSync)(this.file, 432);
18324
+ (0, import_node_fs24.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
18325
+ (0, import_node_fs24.chmodSync)(this.file, 432);
17884
18326
  } catch {
17885
18327
  }
17886
18328
  }
@@ -17901,21 +18343,21 @@ function parseLines(text) {
17901
18343
  function readTail(file, bytes) {
17902
18344
  let fd;
17903
18345
  try {
17904
- fd = (0, import_node_fs23.openSync)(file, "r");
18346
+ fd = (0, import_node_fs24.openSync)(file, "r");
17905
18347
  } catch (err) {
17906
18348
  if (err.code === "ENOENT") return [];
17907
18349
  throw err;
17908
18350
  }
17909
18351
  try {
17910
- const size = (0, import_node_fs23.fstatSync)(fd).size;
18352
+ const size = (0, import_node_fs24.fstatSync)(fd).size;
17911
18353
  const start = Math.max(0, size - bytes);
17912
18354
  const buf = Buffer.alloc(size - start);
17913
- (0, import_node_fs23.readSync)(fd, buf, 0, buf.length, start);
18355
+ (0, import_node_fs24.readSync)(fd, buf, 0, buf.length, start);
17914
18356
  let text = buf.toString("utf8");
17915
18357
  if (start > 0) text = text.slice(text.indexOf("\n") + 1);
17916
18358
  return parseLines(text);
17917
18359
  } finally {
17918
- (0, import_node_fs23.closeSync)(fd);
18360
+ (0, import_node_fs24.closeSync)(fd);
17919
18361
  }
17920
18362
  }
17921
18363
 
@@ -17924,13 +18366,13 @@ function defaultShareGid() {
17924
18366
  const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
17925
18367
  if (!isRoot2) return void 0;
17926
18368
  try {
17927
- return (0, import_node_fs24.statSync)("/var/log/auth.log").gid;
18369
+ return (0, import_node_fs25.statSync)("/var/log/auth.log").gid;
17928
18370
  } catch {
17929
18371
  return void 0;
17930
18372
  }
17931
18373
  }
17932
18374
  function startWatchdog(opts) {
17933
- const dir = opts.config?.dir ?? (0, import_node_path18.join)(opts.stateDir, WATCHDOG_DIRNAME);
18375
+ const dir = opts.config?.dir ?? (0, import_node_path19.join)(opts.stateDir, WATCHDOG_DIRNAME);
17934
18376
  const base = { dir, logged: 0, answered: 0, errored: 0 };
17935
18377
  if (opts.config?.enabled === false) {
17936
18378
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -18021,7 +18463,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
18021
18463
  }
18022
18464
 
18023
18465
  // src/core/node-runtime.ts
18024
- var import_node_child_process7 = require("child_process");
18466
+ var import_node_child_process8 = require("child_process");
18025
18467
  var MIN_DAEMON_NODE_MAJOR = 22;
18026
18468
  function nodeMajor(version) {
18027
18469
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -18037,16 +18479,16 @@ function daemonNodeProblem(version) {
18037
18479
  // src/daemon/index.ts
18038
18480
  function readVersion2() {
18039
18481
  try {
18040
- const pkg = JSON.parse((0, import_node_fs25.readFileSync)((0, import_node_path19.join)(__dirname, "..", "package.json"), "utf-8"));
18482
+ const pkg = JSON.parse((0, import_node_fs26.readFileSync)((0, import_node_path20.join)(__dirname, "..", "package.json"), "utf-8"));
18041
18483
  return pkg.version || "0.0.0";
18042
18484
  } catch {
18043
18485
  return "0.0.0";
18044
18486
  }
18045
18487
  }
18046
18488
  async function runHardeningChecks() {
18047
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process8.execFile)(
18489
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process9.execFile)(
18048
18490
  process.execPath,
18049
- [(0, import_node_path19.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
18491
+ [(0, import_node_path20.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
18050
18492
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
18051
18493
  );
18052
18494
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -18058,9 +18500,9 @@ async function runHardeningChecks() {
18058
18500
  return patches ? [...findings, patches] : findings;
18059
18501
  }
18060
18502
  async function runPatchCheck() {
18061
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process8.execFile)(
18503
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process9.execFile)(
18062
18504
  process.execPath,
18063
- [(0, import_node_path19.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
18505
+ [(0, import_node_path20.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
18064
18506
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
18065
18507
  );
18066
18508
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -18068,7 +18510,7 @@ async function runPatchCheck() {
18068
18510
  }
18069
18511
  function logLine(line) {
18070
18512
  try {
18071
- (0, import_node_fs25.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18513
+ (0, import_node_fs26.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18072
18514
  `);
18073
18515
  } catch {
18074
18516
  }
@@ -18093,9 +18535,9 @@ async function runDaemon() {
18093
18535
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
18094
18536
  const restartDaemon = () => {
18095
18537
  if (PATHS.mode === "system") {
18096
- (0, import_node_child_process8.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
18538
+ (0, import_node_child_process9.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
18097
18539
  } else {
18098
- (0, import_node_child_process8.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
18540
+ (0, import_node_child_process9.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
18099
18541
  setTimeout(() => process.exit(0), 500).unref();
18100
18542
  }
18101
18543
  };
@@ -18110,7 +18552,7 @@ async function runDaemon() {
18110
18552
  } catch (err) {
18111
18553
  logLine(`[daemon] state db unavailable: ${err.message}`);
18112
18554
  }
18113
- const config = loadConfig((0, import_node_fs25.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
18555
+ const config = loadConfig((0, import_node_fs26.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
18114
18556
  configureAttackDetection(config.detection);
18115
18557
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
18116
18558
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -18170,6 +18612,15 @@ async function runDaemon() {
18170
18612
  if (firewallAdapter.enforces === false) {
18171
18613
  logLine("[daemon] no manageable firewall found (need fail2ban, nftables or iptables) \u2014 bans are simulated");
18172
18614
  }
18615
+ const feedSettings = threatFeedSettings(config.threat_feeds);
18616
+ const threatFeeds = new ThreatFeeds({
18617
+ settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
18618
+ enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
18619
+ cachePath: (0, import_node_path20.join)(PATHS.stateDir, "threat-feeds.json"),
18620
+ bus,
18621
+ log: logLine
18622
+ });
18623
+ threatFeeds.start();
18173
18624
  new AlertDispatcher(bus, config);
18174
18625
  const runsWorker = new RunsWorker(bus);
18175
18626
  try {
@@ -18189,7 +18640,7 @@ async function runDaemon() {
18189
18640
  version,
18190
18641
  hostname: (0, import_node_os5.hostname)(),
18191
18642
  minSeverity,
18192
- spoolPath: (0, import_node_path19.join)(PATHS.stateDir, "cloud-spool.jsonl"),
18643
+ spoolPath: (0, import_node_path20.join)(PATHS.stateDir, "cloud-spool.jsonl"),
18193
18644
  log: logLine,
18194
18645
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
18195
18646
  runHardening: runHardeningChecks
@@ -18206,8 +18657,8 @@ async function runDaemon() {
18206
18657
  const autoUpdate = new AutoUpdate({
18207
18658
  version,
18208
18659
  settings: updateSettings(config.update),
18209
- pkgRoot: (0, import_node_path19.join)(__dirname, ".."),
18210
- statePath: (0, import_node_path19.join)(PATHS.stateDir, "auto-update.json"),
18660
+ pkgRoot: (0, import_node_path20.join)(__dirname, ".."),
18661
+ statePath: (0, import_node_path20.join)(PATHS.stateDir, "auto-update.json"),
18211
18662
  bus,
18212
18663
  log: logLine,
18213
18664
  restartDaemon
@@ -18250,6 +18701,10 @@ async function runDaemon() {
18250
18701
  autoUpdate.stop();
18251
18702
  } catch {
18252
18703
  }
18704
+ try {
18705
+ threatFeeds.stop();
18706
+ } catch {
18707
+ }
18253
18708
  try {
18254
18709
  await ipc.stop();
18255
18710
  } catch {