@profullstack/threatcrush 0.13.32 → 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()
@@ -15519,21 +15884,22 @@ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date(
15519
15884
  severity: r.severity,
15520
15885
  title: r.title.slice(0, MAX_TITLE_CHARS),
15521
15886
  recommendation: r.recommendation,
15522
- observed_at: observedAt.toISOString()
15887
+ observed_at: observedAt.toISOString(),
15888
+ ...r.details ? { details: trimMetadata(r.details) } : {}
15523
15889
  }));
15524
15890
  }
15525
15891
 
15526
15892
  // src/daemon/workers/cloud-spool.ts
15527
- var import_node_fs18 = require("fs");
15893
+ var import_node_fs19 = require("fs");
15528
15894
  var import_promises = require("fs/promises");
15529
- var import_node_path13 = require("path");
15895
+ var import_node_path14 = require("path");
15530
15896
  var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
15531
15897
  var CloudSpool = class {
15532
15898
  constructor(path, limits = DEFAULT_SPOOL_LIMITS) {
15533
15899
  this.path = path;
15534
15900
  this.limits = limits;
15535
15901
  try {
15536
- (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 });
15537
15903
  } catch {
15538
15904
  }
15539
15905
  this.load();
@@ -15602,7 +15968,7 @@ var CloudSpool = class {
15602
15968
  load() {
15603
15969
  let raw;
15604
15970
  try {
15605
- raw = (0, import_node_fs18.readFileSync)(this.path, "utf-8");
15971
+ raw = (0, import_node_fs19.readFileSync)(this.path, "utf-8");
15606
15972
  } catch {
15607
15973
  return;
15608
15974
  }
@@ -15840,142 +16206,13 @@ var CloudSync = class {
15840
16206
  };
15841
16207
 
15842
16208
  // src/daemon/workers/remediation-consumer.ts
15843
- var import_node_net5 = require("net");
15844
-
15845
- // src/daemon/firewall/protected.ts
15846
- var import_node_child_process4 = require("child_process");
15847
- var import_node_net3 = require("net");
15848
- var DEFAULT_PROTECTED = [
15849
- "127.0.0.0/8",
15850
- "::1/128",
15851
- "10.0.0.0/8",
15852
- "172.16.0.0/12",
15853
- "192.168.0.0/16",
15854
- "169.254.0.0/16",
15855
- "fc00::/7",
15856
- "fe80::/10"
15857
- ];
15858
- function ipToBytes(ip) {
15859
- const version = (0, import_node_net3.isIP)(ip);
15860
- if (version === 4) return v4ToBytes(ip);
15861
- if (version === 6) return v6ToBytes(ip);
15862
- return null;
15863
- }
15864
- function v4ToBytes(ip) {
15865
- const parts = ip.split(".");
15866
- if (parts.length !== 4) return null;
15867
- const bytes = new Uint8Array(4);
15868
- for (let i = 0; i < 4; i++) {
15869
- const n = Number(parts[i]);
15870
- if (!Number.isInteger(n) || n < 0 || n > 255) return null;
15871
- bytes[i] = n;
15872
- }
15873
- return bytes;
15874
- }
15875
- function v6ToBytes(ip) {
15876
- const bare = ip.split("%")[0];
15877
- const [headText, tailText] = bare.split("::", 2);
15878
- const head = headText ? headText.split(":") : [];
15879
- const tail = tailText !== void 0 ? tailText ? tailText.split(":") : [] : null;
15880
- const groups = [];
15881
- const pushGroup = (group) => {
15882
- if (group.includes(".")) {
15883
- const v4 = v4ToBytes(group);
15884
- if (!v4) return false;
15885
- groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
15886
- return true;
15887
- }
15888
- if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return false;
15889
- groups.push(parseInt(group, 16));
15890
- return true;
15891
- };
15892
- for (const group of head) if (!pushGroup(group)) return null;
15893
- const headCount = groups.length;
15894
- if (tail === null) {
15895
- if (headCount !== 8) return null;
15896
- } else {
15897
- const tailGroups = [];
15898
- const saved = groups.length;
15899
- for (const group of tail) if (!pushGroup(group)) return null;
15900
- tailGroups.push(...groups.splice(saved));
15901
- const zeros = 8 - headCount - tailGroups.length;
15902
- if (zeros < 0) return null;
15903
- for (let i = 0; i < zeros; i++) groups.push(0);
15904
- groups.push(...tailGroups);
15905
- }
15906
- if (groups.length !== 8) return null;
15907
- const bytes = new Uint8Array(16);
15908
- for (let i = 0; i < 8; i++) {
15909
- bytes[i * 2] = groups[i] >> 8 & 255;
15910
- bytes[i * 2 + 1] = groups[i] & 255;
15911
- }
15912
- return bytes;
15913
- }
15914
- function ipMatches(ip, entry) {
15915
- const [network, prefixText] = entry.trim().split("/");
15916
- const target = ipToBytes(ip);
15917
- const base = ipToBytes(network);
15918
- if (!target || !base || target.length !== base.length) return false;
15919
- const bits = prefixText === void 0 ? base.length * 8 : Number(prefixText);
15920
- if (!Number.isInteger(bits) || bits < 0 || bits > base.length * 8) return false;
15921
- const wholeBytes = Math.floor(bits / 8);
15922
- for (let i = 0; i < wholeBytes; i++) {
15923
- if (target[i] !== base[i]) return false;
15924
- }
15925
- const remainder = bits % 8;
15926
- if (remainder === 0) return true;
15927
- const mask = 255 << 8 - remainder & 255;
15928
- return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
15929
- }
15930
- function isProtected(ip, list) {
15931
- return list.some((entry) => ipMatches(ip, entry));
15932
- }
15933
- function currentSshClient(env2 = process.env) {
15934
- const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
15935
- if (!source) return null;
15936
- const ip = source.trim().split(/\s+/)[0];
15937
- return ip && (0, import_node_net3.isIP)(ip) ? ip : null;
15938
- }
15939
- function establishedSshPeers() {
15940
- const peers = /* @__PURE__ */ new Set();
15941
- try {
15942
- const out = (0, import_node_child_process4.execFileSync)("ss", ["-tnpH"], {
15943
- encoding: "utf-8",
15944
- stdio: ["ignore", "pipe", "ignore"],
15945
- timeout: 3e3
15946
- });
15947
- for (const line of out.split("\n")) {
15948
- if (!/users:\(\("sshd/.test(line)) continue;
15949
- const parts = line.trim().split(/\s+/);
15950
- const peer = parts[4];
15951
- if (!peer) continue;
15952
- const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
15953
- if (ip && (0, import_node_net3.isIP)(ip)) peers.add(ip);
15954
- }
15955
- } catch {
15956
- }
15957
- return [...peers];
15958
- }
15959
- function defaultGateways() {
15960
- const found = /* @__PURE__ */ new Set();
15961
- for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
15962
- try {
15963
- const out = (0, import_node_child_process4.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
15964
- for (const line of out.split("\n")) {
15965
- const match = line.match(/\bvia\s+(\S+)/);
15966
- if (match && (0, import_node_net3.isIP)(match[1])) found.add(match[1]);
15967
- }
15968
- } catch {
15969
- }
15970
- }
15971
- return [...found];
15972
- }
16209
+ var import_node_net6 = require("net");
15973
16210
 
15974
16211
  // src/daemon/workers/allowlist-sync.ts
15975
- var import_node_net4 = require("net");
16212
+ var import_node_net5 = require("net");
15976
16213
  function isAddressOrCidr(value) {
15977
16214
  const [network, prefix, extra] = value.split("/");
15978
- const family = (0, import_node_net4.isIP)(network);
16215
+ const family = (0, import_node_net5.isIP)(network);
15979
16216
  if (family === 0 || extra !== void 0) return false;
15980
16217
  if (prefix === void 0) return true;
15981
16218
  if (!/^\d{1,3}$/.test(prefix)) return false;
@@ -16124,7 +16361,7 @@ var RemediationConsumer = class {
16124
16361
  try {
16125
16362
  switch (action.action_type) {
16126
16363
  case "block": {
16127
- 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}`);
16128
16365
  let ttlSeconds = this.manager.status().max_ban_seconds;
16129
16366
  if (action.expires_at) {
16130
16367
  const until = Date.parse(action.expires_at);
@@ -16143,7 +16380,7 @@ var RemediationConsumer = class {
16143
16380
  return { status: "executed", dry_run: result.entry?.dry_run === true, executed_at };
16144
16381
  }
16145
16382
  case "unblock": {
16146
- 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}`);
16147
16384
  const wasBanned = this.manager.getBlocklist().some((b) => b.ip === target);
16148
16385
  const result = await this.manager.unban(target, {
16149
16386
  forget: true,
@@ -16188,8 +16425,8 @@ var RemediationConsumer = class {
16188
16425
 
16189
16426
  // src/daemon/workers/auto-update.ts
16190
16427
  var import_node_child_process5 = require("child_process");
16191
- var import_node_fs19 = require("fs");
16192
- var import_node_path14 = require("path");
16428
+ var import_node_fs20 = require("fs");
16429
+ var import_node_path15 = require("path");
16193
16430
  var PKG_NAME = "@profullstack/threatcrush";
16194
16431
  var REGISTRY = `https://registry.npmjs.org/${PKG_NAME}`;
16195
16432
  var DEFAULT_INTERVAL_MS = 6 * 36e5;
@@ -16226,12 +16463,12 @@ function pickUpdate(doc, current, opts) {
16226
16463
  return { version: latest };
16227
16464
  }
16228
16465
  function installPlan(opts) {
16229
- 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`;
16230
16467
  if (!opts.pkgRoot.endsWith(expected)) {
16231
16468
  return { kind: "unsupported", reason: `not an npm global install (${opts.pkgRoot}); run \`threatcrush update\`` };
16232
16469
  }
16233
- const nodeBin = (0, import_node_path14.dirname)(opts.execPath);
16234
- 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");
16235
16472
  if (!opts.npmExists(npm)) return { kind: "unsupported", reason: `no npm beside ${opts.execPath}` };
16236
16473
  if (!opts.owner) return { kind: "unsupported", reason: `cannot tell who owns ${opts.pkgRoot}` };
16237
16474
  const npmArgs = [npm, "i", "-g", `${PKG_NAME}@${opts.version}`, "--no-fund", "--no-audit"];
@@ -16263,10 +16500,10 @@ function installPlan(opts) {
16263
16500
  }
16264
16501
  function ownerOf(path, passwd = "/etc/passwd") {
16265
16502
  try {
16266
- const st = (0, import_node_fs19.statSync)(path);
16503
+ const st = (0, import_node_fs20.statSync)(path);
16267
16504
  let home = st.uid === 0 ? "/root" : "";
16268
16505
  try {
16269
- 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")) {
16270
16507
  const f = line.split(":");
16271
16508
  if (Number(f[2]) === st.uid && f[5]) home = f[5];
16272
16509
  }
@@ -16371,7 +16608,7 @@ var AutoUpdate = class {
16371
16608
  uid: process.getuid?.() ?? -1,
16372
16609
  owner: ownerOf(this.opts.pkgRoot),
16373
16610
  underSystemd: this.opts.underSystemd ?? Boolean(process.env.INVOCATION_ID),
16374
- npmExists: import_node_fs19.existsSync
16611
+ npmExists: import_node_fs20.existsSync
16375
16612
  });
16376
16613
  if (plan.kind === "unsupported") return this.note(`${target} is available but cannot self-install: ${plan.reason}`);
16377
16614
  this.recordAttempt(target);
@@ -16406,7 +16643,7 @@ var AutoUpdate = class {
16406
16643
  }
16407
16644
  lastAttempt() {
16408
16645
  try {
16409
- 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"));
16410
16647
  return v.version && typeof v.at === "number" ? { version: v.version, at: v.at } : null;
16411
16648
  } catch {
16412
16649
  return null;
@@ -16414,13 +16651,219 @@ var AutoUpdate = class {
16414
16651
  }
16415
16652
  recordAttempt(version) {
16416
16653
  try {
16417
- (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() }));
16418
16655
  } catch (err) {
16419
16656
  this.opts.log(`[update] could not record attempt: ${err.message}`);
16420
16657
  }
16421
16658
  }
16422
16659
  };
16423
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
+
16424
16867
  // src/daemon/rules/engine.ts
16425
16868
  var MAX_WINDOW_ENTRIES = 1e3;
16426
16869
  function live(window) {
@@ -16582,8 +17025,8 @@ var RuleEngine = class {
16582
17025
  };
16583
17026
 
16584
17027
  // src/daemon/rules/loader.ts
16585
- var import_node_fs20 = require("fs");
16586
- var import_node_path15 = require("path");
17028
+ var import_node_fs21 = require("fs");
17029
+ var import_node_path16 = require("path");
16587
17030
 
16588
17031
  // src/daemon/rules/default-rules.ts
16589
17032
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -16984,11 +17427,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
16984
17427
  function loadAllRules(customDir) {
16985
17428
  const rules = [...DEFAULT_RULES];
16986
17429
  const dir = customDir || RULES_DIR;
16987
- if ((0, import_node_fs20.existsSync)(dir)) {
16988
- 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"));
16989
17432
  for (const file of files) {
16990
17433
  try {
16991
- 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");
16992
17435
  const parsed = JSON.parse(raw);
16993
17436
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
16994
17437
  for (const rule of customRules) {
@@ -17019,24 +17462,24 @@ function loadAllRules(customDir) {
17019
17462
  }
17020
17463
 
17021
17464
  // src/daemon/firewall/adapters.ts
17022
- var import_node_child_process6 = require("child_process");
17023
- var import_node_fs21 = require("fs");
17024
- var import_node_path16 = require("path");
17025
- 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");
17026
17469
  function assertValidFirewallIp(ip) {
17027
- if ((0, import_node_net6.isIP)(ip) !== 4) {
17470
+ if ((0, import_node_net8.isIP)(ip) !== 4) {
17028
17471
  throw new Error(`Invalid IPv4 address: ${ip}`);
17029
17472
  }
17030
17473
  }
17031
17474
  function assertBannableIp(ip) {
17032
- if ((0, import_node_net6.isIP)(ip) === 0) {
17475
+ if ((0, import_node_net8.isIP)(ip) === 0) {
17033
17476
  throw new Error(`Invalid IP address: ${ip}`);
17034
17477
  }
17035
17478
  }
17036
17479
  function writeIfAbsent(path, contents) {
17037
- (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 });
17038
17481
  try {
17039
- (0, import_node_fs21.writeFileSync)(path, contents, { flag: "wx" });
17482
+ (0, import_node_fs22.writeFileSync)(path, contents, { flag: "wx" });
17040
17483
  } catch (err) {
17041
17484
  if (err.code !== "EEXIST") throw err;
17042
17485
  }
@@ -17055,11 +17498,11 @@ var Fail2banAdapter = class {
17055
17498
  enforces = true;
17056
17499
  jailReady = false;
17057
17500
  isAvailable() {
17058
- 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" });
17059
17502
  return result.status === 0;
17060
17503
  }
17061
17504
  client(args) {
17062
- return (0, import_node_child_process6.execFileSync)("fail2ban-client", args, {
17505
+ return (0, import_node_child_process7.execFileSync)("fail2ban-client", args, {
17063
17506
  encoding: "utf-8",
17064
17507
  stdio: ["ignore", "pipe", "pipe"]
17065
17508
  });
@@ -17135,7 +17578,7 @@ var Fail2banAdapter = class {
17135
17578
  const status = this.client(["status", this.jail]);
17136
17579
  const line = status.split("\n").find((l) => /Banned IP list:/i.test(l));
17137
17580
  if (!line) return [];
17138
- 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);
17139
17582
  } catch {
17140
17583
  return [];
17141
17584
  }
@@ -17145,45 +17588,45 @@ var Fail2banAdapter = class {
17145
17588
  function parseBannedList(output) {
17146
17589
  const found = [];
17147
17590
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
17148
- 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]);
17149
17592
  }
17150
17593
  if (found.length > 0) return found;
17151
- 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);
17152
17595
  }
17153
17596
  var NftablesAdapter = class {
17154
17597
  name = "nftables";
17155
17598
  table = "threatcrush";
17156
17599
  set = "blocklist";
17157
17600
  isAvailable() {
17158
- 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" });
17159
17602
  return result.status === 0;
17160
17603
  }
17161
17604
  ensureSetup() {
17162
17605
  try {
17163
- (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" });
17164
17607
  } catch {
17165
- (0, import_node_child_process6.execSync)(`nft add table inet ${this.table}`);
17166
- (0, import_node_child_process6.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
17167
- (0, import_node_child_process6.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
17168
- (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`);
17169
17612
  }
17170
17613
  }
17171
17614
  async block(ip) {
17172
17615
  assertValidFirewallIp(ip);
17173
17616
  this.ensureSetup();
17174
- (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} }'`);
17175
17618
  }
17176
17619
  async unblock(ip) {
17177
17620
  assertValidFirewallIp(ip);
17178
17621
  try {
17179
- (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} }'`);
17180
17623
  } catch {
17181
17624
  }
17182
17625
  }
17183
17626
  async isBlocked(ip) {
17184
17627
  assertValidFirewallIp(ip);
17185
17628
  try {
17186
- 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" });
17187
17630
  return output.includes(ip);
17188
17631
  } catch {
17189
17632
  return false;
@@ -17191,7 +17634,7 @@ var NftablesAdapter = class {
17191
17634
  }
17192
17635
  async listBlocked() {
17193
17636
  try {
17194
- 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" });
17195
17638
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
17196
17639
  if (!match) return [];
17197
17640
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -17204,34 +17647,34 @@ var IptablesAdapter = class {
17204
17647
  name = "iptables";
17205
17648
  chain = "THREATCRUSH";
17206
17649
  isAvailable() {
17207
- 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" });
17208
17651
  return result.status === 0;
17209
17652
  }
17210
17653
  ensureChain() {
17211
17654
  try {
17212
- (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" });
17213
17656
  } catch {
17214
- (0, import_node_child_process6.execSync)(`iptables -N ${this.chain}`);
17215
- (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}`);
17216
17659
  }
17217
17660
  }
17218
17661
  async block(ip) {
17219
17662
  assertValidFirewallIp(ip);
17220
17663
  this.ensureChain();
17221
17664
  if (await this.isBlocked(ip)) return;
17222
- (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`);
17223
17666
  }
17224
17667
  async unblock(ip) {
17225
17668
  assertValidFirewallIp(ip);
17226
17669
  try {
17227
- (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`);
17228
17671
  } catch {
17229
17672
  }
17230
17673
  }
17231
17674
  async isBlocked(ip) {
17232
17675
  assertValidFirewallIp(ip);
17233
17676
  try {
17234
- 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" });
17235
17678
  return output.includes(ip);
17236
17679
  } catch {
17237
17680
  return false;
@@ -17239,7 +17682,7 @@ var IptablesAdapter = class {
17239
17682
  }
17240
17683
  async listBlocked() {
17241
17684
  try {
17242
- 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" });
17243
17686
  const ips = [];
17244
17687
  for (const line of output.split("\n")) {
17245
17688
  const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -17295,8 +17738,8 @@ function detectFirewallAdapter(backend = "auto") {
17295
17738
  }
17296
17739
 
17297
17740
  // src/daemon/firewall/remediation.ts
17298
- var import_node_fs22 = require("fs");
17299
- var import_node_net7 = require("net");
17741
+ var import_node_fs23 = require("fs");
17742
+ var import_node_net9 = require("net");
17300
17743
 
17301
17744
  // src/daemon/firewall/crawlers.ts
17302
17745
  var import_node_dns = require("dns");
@@ -17431,7 +17874,7 @@ var RemediationManager = class {
17431
17874
  if (remediation?.action !== "block") return;
17432
17875
  }
17433
17876
  const ip = event.source_ip;
17434
- if (!ip || (0, import_node_net7.isIP)(ip) === 0) return;
17877
+ if (!ip || (0, import_node_net9.isIP)(ip) === 0) return;
17435
17878
  if (this.isAllowlisted(ip)) return;
17436
17879
  if (this.blocklist.some((b) => b.ip === ip)) return;
17437
17880
  if (this.config.spare_verified_crawlers) {
@@ -17450,7 +17893,7 @@ var RemediationManager = class {
17450
17893
  * 4th offence and so on, clamped to `max_ban_seconds`.
17451
17894
  */
17452
17895
  async ban(ip, reason, opts = {}) {
17453
- 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}` };
17454
17897
  if (this.isAllowlisted(ip)) {
17455
17898
  return { ok: false, error: `${ip} is protected and can never be blocked` };
17456
17899
  }
@@ -17707,7 +18150,7 @@ var RemediationManager = class {
17707
18150
  }
17708
18151
  logLine(line) {
17709
18152
  try {
17710
- (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}
17711
18154
  `);
17712
18155
  } catch {
17713
18156
  }
@@ -17741,13 +18184,13 @@ function remediationSettings(section) {
17741
18184
  }
17742
18185
 
17743
18186
  // src/daemon/watchdog-service.ts
17744
- var import_node_fs24 = require("fs");
17745
- var import_node_path18 = require("path");
18187
+ var import_node_fs25 = require("fs");
18188
+ var import_node_path19 = require("path");
17746
18189
 
17747
18190
  // src/core/watchdog.ts
17748
- var import_node_fs23 = require("fs");
18191
+ var import_node_fs24 = require("fs");
17749
18192
  var import_node_crypto5 = require("crypto");
17750
- var import_node_path17 = require("path");
18193
+ var import_node_path18 = require("path");
17751
18194
  var WATCHDOG_DIRNAME = "watchdog";
17752
18195
  var LOG_FILE = "attacks.jsonl";
17753
18196
  var ROTATED_FILE = "attacks.1.jsonl";
@@ -17836,12 +18279,12 @@ var WatchdogLog = class {
17836
18279
  stats = { logged: 0, answered: 0, errored: 0 };
17837
18280
  constructor(dir, options = {}) {
17838
18281
  this.dir = dir;
17839
- this.file = (0, import_node_path17.join)(dir, LOG_FILE);
18282
+ this.file = (0, import_node_path18.join)(dir, LOG_FILE);
17840
18283
  this.shareGid = options.shareGid;
17841
- (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 });
17842
18285
  if (this.shareGid !== void 0) {
17843
- (0, import_node_fs23.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
17844
- (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);
17845
18288
  }
17846
18289
  for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
17847
18290
  }
@@ -17870,16 +18313,16 @@ var WatchdogLog = class {
17870
18313
  const chunk = this.buffer.join("\n") + "\n";
17871
18314
  this.buffer = [];
17872
18315
  try {
17873
- if ((0, import_node_fs23.statSync)(this.file).size > ROTATE_BYTES) {
17874
- (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));
17875
18318
  }
17876
18319
  } catch {
17877
18320
  }
17878
- (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 });
17879
18322
  if (this.shareGid !== void 0) {
17880
18323
  try {
17881
- (0, import_node_fs23.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
17882
- (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);
17883
18326
  } catch {
17884
18327
  }
17885
18328
  }
@@ -17900,21 +18343,21 @@ function parseLines(text) {
17900
18343
  function readTail(file, bytes) {
17901
18344
  let fd;
17902
18345
  try {
17903
- fd = (0, import_node_fs23.openSync)(file, "r");
18346
+ fd = (0, import_node_fs24.openSync)(file, "r");
17904
18347
  } catch (err) {
17905
18348
  if (err.code === "ENOENT") return [];
17906
18349
  throw err;
17907
18350
  }
17908
18351
  try {
17909
- const size = (0, import_node_fs23.fstatSync)(fd).size;
18352
+ const size = (0, import_node_fs24.fstatSync)(fd).size;
17910
18353
  const start = Math.max(0, size - bytes);
17911
18354
  const buf = Buffer.alloc(size - start);
17912
- (0, import_node_fs23.readSync)(fd, buf, 0, buf.length, start);
18355
+ (0, import_node_fs24.readSync)(fd, buf, 0, buf.length, start);
17913
18356
  let text = buf.toString("utf8");
17914
18357
  if (start > 0) text = text.slice(text.indexOf("\n") + 1);
17915
18358
  return parseLines(text);
17916
18359
  } finally {
17917
- (0, import_node_fs23.closeSync)(fd);
18360
+ (0, import_node_fs24.closeSync)(fd);
17918
18361
  }
17919
18362
  }
17920
18363
 
@@ -17923,13 +18366,13 @@ function defaultShareGid() {
17923
18366
  const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
17924
18367
  if (!isRoot2) return void 0;
17925
18368
  try {
17926
- return (0, import_node_fs24.statSync)("/var/log/auth.log").gid;
18369
+ return (0, import_node_fs25.statSync)("/var/log/auth.log").gid;
17927
18370
  } catch {
17928
18371
  return void 0;
17929
18372
  }
17930
18373
  }
17931
18374
  function startWatchdog(opts) {
17932
- 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);
17933
18376
  const base = { dir, logged: 0, answered: 0, errored: 0 };
17934
18377
  if (opts.config?.enabled === false) {
17935
18378
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -18020,7 +18463,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
18020
18463
  }
18021
18464
 
18022
18465
  // src/core/node-runtime.ts
18023
- var import_node_child_process7 = require("child_process");
18466
+ var import_node_child_process8 = require("child_process");
18024
18467
  var MIN_DAEMON_NODE_MAJOR = 22;
18025
18468
  function nodeMajor(version) {
18026
18469
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -18036,24 +18479,38 @@ function daemonNodeProblem(version) {
18036
18479
  // src/daemon/index.ts
18037
18480
  function readVersion2() {
18038
18481
  try {
18039
- 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"));
18040
18483
  return pkg.version || "0.0.0";
18041
18484
  } catch {
18042
18485
  return "0.0.0";
18043
18486
  }
18044
18487
  }
18045
18488
  async function runHardeningChecks() {
18046
- 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)(
18047
18490
  process.execPath,
18048
- [(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"],
18049
18492
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
18050
18493
  );
18051
18494
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
18052
- return Array.isArray(parsed.findings) ? parsed.findings : [];
18495
+ const findings = Array.isArray(parsed.findings) ? parsed.findings : [];
18496
+ const patches = await runPatchCheck().catch((err) => {
18497
+ logLine(`[cloud] patch check failed: ${err.message.split("\n")[0]}`);
18498
+ return null;
18499
+ });
18500
+ return patches ? [...findings, patches] : findings;
18501
+ }
18502
+ async function runPatchCheck() {
18503
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process9.execFile)(
18504
+ process.execPath,
18505
+ [(0, import_node_path20.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
18506
+ { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
18507
+ );
18508
+ const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
18509
+ return parsed.finding ?? null;
18053
18510
  }
18054
18511
  function logLine(line) {
18055
18512
  try {
18056
- (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}
18057
18514
  `);
18058
18515
  } catch {
18059
18516
  }
@@ -18078,9 +18535,9 @@ async function runDaemon() {
18078
18535
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
18079
18536
  const restartDaemon = () => {
18080
18537
  if (PATHS.mode === "system") {
18081
- (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();
18082
18539
  } else {
18083
- (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();
18084
18541
  setTimeout(() => process.exit(0), 500).unref();
18085
18542
  }
18086
18543
  };
@@ -18095,7 +18552,7 @@ async function runDaemon() {
18095
18552
  } catch (err) {
18096
18553
  logLine(`[daemon] state db unavailable: ${err.message}`);
18097
18554
  }
18098
- 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);
18099
18556
  configureAttackDetection(config.detection);
18100
18557
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
18101
18558
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -18155,6 +18612,15 @@ async function runDaemon() {
18155
18612
  if (firewallAdapter.enforces === false) {
18156
18613
  logLine("[daemon] no manageable firewall found (need fail2ban, nftables or iptables) \u2014 bans are simulated");
18157
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();
18158
18624
  new AlertDispatcher(bus, config);
18159
18625
  const runsWorker = new RunsWorker(bus);
18160
18626
  try {
@@ -18174,7 +18640,7 @@ async function runDaemon() {
18174
18640
  version,
18175
18641
  hostname: (0, import_node_os5.hostname)(),
18176
18642
  minSeverity,
18177
- spoolPath: (0, import_node_path19.join)(PATHS.stateDir, "cloud-spool.jsonl"),
18643
+ spoolPath: (0, import_node_path20.join)(PATHS.stateDir, "cloud-spool.jsonl"),
18178
18644
  log: logLine,
18179
18645
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
18180
18646
  runHardening: runHardeningChecks
@@ -18191,8 +18657,8 @@ async function runDaemon() {
18191
18657
  const autoUpdate = new AutoUpdate({
18192
18658
  version,
18193
18659
  settings: updateSettings(config.update),
18194
- pkgRoot: (0, import_node_path19.join)(__dirname, ".."),
18195
- 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"),
18196
18662
  bus,
18197
18663
  log: logLine,
18198
18664
  restartDaemon
@@ -18235,6 +18701,10 @@ async function runDaemon() {
18235
18701
  autoUpdate.stop();
18236
18702
  } catch {
18237
18703
  }
18704
+ try {
18705
+ threatFeeds.stop();
18706
+ } catch {
18707
+ }
18238
18708
  try {
18239
18709
  await ipc.stop();
18240
18710
  } catch {