@profullstack/threatcrush 0.13.33 → 0.13.35

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_fs27 = require("fs");
2026
+ var import_node_child_process10 = require("child_process");
2027
2027
  var import_node_os5 = require("os");
2028
- var import_node_path19 = require("path");
2028
+ var import_node_path21 = 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,8 @@ function loadConfig(configPath) {
10496
10860
  cloud: parsed.cloud,
10497
10861
  watchdog: parsed.watchdog,
10498
10862
  update: parsed.update,
10863
+ threat_feeds: parsed.threat_feeds,
10864
+ privileged: parsed.privileged,
10499
10865
  storage: parsed.storage,
10500
10866
  license: parsed.license
10501
10867
  };
@@ -10506,13 +10872,13 @@ function loadConfig(configPath) {
10506
10872
  function loadModuleConfigs(confDir) {
10507
10873
  const dir = confDir || DEFAULT_CONFDIR;
10508
10874
  const configs = /* @__PURE__ */ new Map();
10509
- if (!(0, import_node_fs11.existsSync)(dir)) {
10875
+ if (!(0, import_node_fs12.existsSync)(dir)) {
10510
10876
  return configs;
10511
10877
  }
10512
- const files = (0, import_node_fs11.readdirSync)(dir).filter((f) => f.endsWith(".conf"));
10878
+ const files = (0, import_node_fs12.readdirSync)(dir).filter((f) => f.endsWith(".conf"));
10513
10879
  for (const file of files) {
10514
10880
  try {
10515
- const raw = (0, import_node_fs11.readFileSync)((0, import_node_path5.join)(dir, file), "utf-8");
10881
+ const raw = (0, import_node_fs12.readFileSync)((0, import_node_path6.join)(dir, file), "utf-8");
10516
10882
  const parsed = import_toml.default.parse(raw);
10517
10883
  for (const [name, config] of Object.entries(parsed)) {
10518
10884
  configs.set(name, config);
@@ -10646,15 +11012,15 @@ var ModuleHost = class {
10646
11012
  }
10647
11013
  }
10648
11014
  async discoverAndStartInstalled() {
10649
- if (!(0, import_node_fs12.existsSync)(PATHS.moduleDir)) return;
11015
+ if (!(0, import_node_fs13.existsSync)(PATHS.moduleDir)) return;
10650
11016
  const configs = loadModuleConfigs(PATHS.confD);
10651
- const entries = (0, import_node_fs12.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
11017
+ const entries = (0, import_node_fs13.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
10652
11018
  for (const entry of entries) {
10653
11019
  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;
11020
+ const manifestPath = (0, import_node_path7.join)(PATHS.moduleDir, entry.name, "mod.toml");
11021
+ if (!(0, import_node_fs13.existsSync)(manifestPath)) continue;
10656
11022
  try {
10657
- const manifest = import_toml2.default.parse((0, import_node_fs12.readFileSync)(manifestPath, "utf-8"));
11023
+ const manifest = import_toml2.default.parse((0, import_node_fs13.readFileSync)(manifestPath, "utf-8"));
10658
11024
  const name = manifest.module?.name || entry.name;
10659
11025
  const defaults = manifest.module?.config?.defaults || {};
10660
11026
  const config = {
@@ -10668,7 +11034,7 @@ var ModuleHost = class {
10668
11034
  source: "installed",
10669
11035
  status: config.enabled === false ? "disabled" : "loaded",
10670
11036
  events: 0,
10671
- path: (0, import_node_path6.join)(PATHS.moduleDir, entry.name),
11037
+ path: (0, import_node_path7.join)(PATHS.moduleDir, entry.name),
10672
11038
  config
10673
11039
  };
10674
11040
  this.modules.set(name, hosted);
@@ -10683,7 +11049,7 @@ var ModuleHost = class {
10683
11049
  status: "error",
10684
11050
  events: 0,
10685
11051
  detail: `manifest load failed: ${String(err.message || err)}`,
10686
- path: (0, import_node_path6.join)(PATHS.moduleDir, entry.name)
11052
+ path: (0, import_node_path7.join)(PATHS.moduleDir, entry.name)
10687
11053
  });
10688
11054
  }
10689
11055
  }
@@ -10722,17 +11088,17 @@ var ModuleHost = class {
10722
11088
  }
10723
11089
  }
10724
11090
  installedEntrypoint(modulePath) {
10725
- const packageJson = (0, import_node_path6.join)(modulePath, "package.json");
11091
+ const packageJson = (0, import_node_path7.join)(modulePath, "package.json");
10726
11092
  const candidates = [];
10727
- if ((0, import_node_fs12.existsSync)(packageJson)) {
11093
+ if ((0, import_node_fs13.existsSync)(packageJson)) {
10728
11094
  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));
11095
+ const pkg = JSON.parse((0, import_node_fs13.readFileSync)(packageJson, "utf-8"));
11096
+ if (pkg.main) candidates.push((0, import_node_path7.join)(modulePath, pkg.main));
10731
11097
  } catch {
10732
11098
  }
10733
11099
  }
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;
11100
+ candidates.push((0, import_node_path7.join)(modulePath, "dist", "index.js"), (0, import_node_path7.join)(modulePath, "index.js"));
11101
+ return candidates.find((candidate) => (0, import_node_fs13.existsSync)(candidate)) || null;
10736
11102
  }
10737
11103
  isThreatCrushModule(value) {
10738
11104
  return Boolean(
@@ -11004,26 +11370,26 @@ function slackChannel(webhookUrl) {
11004
11370
  }
11005
11371
 
11006
11372
  // src/core/cli-config.ts
11007
- var import_node_fs13 = require("fs");
11008
- var import_node_path7 = require("path");
11373
+ var import_node_fs14 = require("fs");
11374
+ var import_node_path8 = require("path");
11009
11375
  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");
11376
+ var CLI_CONFIG_DIR = (0, import_node_path8.join)((0, import_node_os2.homedir)(), ".threatcrush");
11377
+ var CLI_CONFIG_PATH = (0, import_node_path8.join)(CLI_CONFIG_DIR, "config.json");
11012
11378
  function apiUrl() {
11013
11379
  return process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
11014
11380
  }
11015
11381
  function readCliConfig() {
11016
11382
  try {
11017
- return JSON.parse((0, import_node_fs13.readFileSync)(CLI_CONFIG_PATH, "utf-8"));
11383
+ return JSON.parse((0, import_node_fs14.readFileSync)(CLI_CONFIG_PATH, "utf-8"));
11018
11384
  } catch {
11019
11385
  return {};
11020
11386
  }
11021
11387
  }
11022
11388
  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");
11389
+ if (!(0, import_node_fs14.existsSync)(CLI_CONFIG_DIR)) (0, import_node_fs14.mkdirSync)(CLI_CONFIG_DIR, { recursive: true });
11390
+ (0, import_node_fs14.writeFileSync)(CLI_CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
11025
11391
  try {
11026
- (0, import_node_fs13.chmodSync)(CLI_CONFIG_PATH, 384);
11392
+ (0, import_node_fs14.chmodSync)(CLI_CONFIG_PATH, 384);
11027
11393
  } catch {
11028
11394
  }
11029
11395
  }
@@ -11099,8 +11465,8 @@ async function cloudFetch(path, init = {}) {
11099
11465
  }
11100
11466
 
11101
11467
  // src/commands/scan.ts
11102
- var import_node_fs17 = require("fs");
11103
- var import_node_path12 = require("path");
11468
+ var import_node_fs18 = require("fs");
11469
+ var import_node_path13 = require("path");
11104
11470
 
11105
11471
  // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
11106
11472
  var ANSI_BACKGROUND_OFFSET = 10;
@@ -11598,13 +11964,13 @@ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
11598
11964
  var source_default = chalk;
11599
11965
 
11600
11966
  // src/core/version.ts
11601
- var import_node_fs14 = require("fs");
11602
- var import_node_path8 = require("path");
11967
+ var import_node_fs15 = require("fs");
11968
+ var import_node_path9 = require("path");
11603
11969
  var FALLBACK_VERSION = "0.0.0";
11604
11970
  function readPackageVersion() {
11605
11971
  try {
11606
11972
  const pkg = JSON.parse(
11607
- (0, import_node_fs14.readFileSync)((0, import_node_path8.join)(__dirname, "..", "package.json"), "utf-8")
11973
+ (0, import_node_fs15.readFileSync)((0, import_node_path9.join)(__dirname, "..", "package.json"), "utf-8")
11608
11974
  );
11609
11975
  return pkg.version || FALLBACK_VERSION;
11610
11976
  } catch {
@@ -14634,8 +15000,8 @@ function scanManifest(relativePath, filename, text) {
14634
15000
  }
14635
15001
 
14636
15002
  // ../../packages/scan/src/node/walk.ts
14637
- var import_node_fs15 = require("fs");
14638
- var import_node_path9 = require("path");
15003
+ var import_node_fs16 = require("fs");
15004
+ var import_node_path10 = require("path");
14639
15005
  function compileExcludes(patterns) {
14640
15006
  const matchers = patterns.map((p) => p.trim()).filter((p) => p.length > 0 && !p.startsWith("#")).map(compilePattern);
14641
15007
  if (matchers.length === 0) return () => false;
@@ -14706,7 +15072,7 @@ function matchPrefix(parts, segs) {
14706
15072
  }
14707
15073
  function readIgnoreFile(root) {
14708
15074
  try {
14709
- return (0, import_node_fs15.readFileSync)((0, import_node_path9.join)(root, ".threatcrushignore"), "utf-8").split("\n");
15075
+ return (0, import_node_fs16.readFileSync)((0, import_node_path10.join)(root, ".threatcrushignore"), "utf-8").split("\n");
14710
15076
  } catch {
14711
15077
  return [];
14712
15078
  }
@@ -14722,16 +15088,16 @@ function scanPath(targetPath, options = {}) {
14722
15088
  let excluded = 0;
14723
15089
  const rootIsDirectory = (() => {
14724
15090
  try {
14725
- return (0, import_node_fs15.statSync)(targetPath).isDirectory();
15091
+ return (0, import_node_fs16.statSync)(targetPath).isDirectory();
14726
15092
  } catch {
14727
15093
  return true;
14728
15094
  }
14729
15095
  })();
14730
- const walkRoot = rootIsDirectory ? targetPath : (0, import_node_path9.dirname)(targetPath);
15096
+ const walkRoot = rootIsDirectory ? targetPath : (0, import_node_path10.dirname)(targetPath);
14731
15097
  const isExcluded = compileExcludes([...options.exclude ?? [], ...readIgnoreFile(walkRoot)]);
14732
15098
  const scanFile = (fullPath, filename) => {
14733
15099
  const relativePath = toRelative(walkRoot, fullPath);
14734
- const extension = (0, import_node_path9.extname)(filename).toLowerCase();
15100
+ const extension = (0, import_node_path10.extname)(filename).toLowerCase();
14735
15101
  const isManifest = filename === "package.json" || filename === "requirements.txt";
14736
15102
  const scannable = SCAN_EXTENSIONS.has(extension) || filename.startsWith(".env");
14737
15103
  const mayDeclareInterpreter = !scannable && !isManifest && extension === "";
@@ -14743,26 +15109,26 @@ function scanPath(targetPath, options = {}) {
14743
15109
  let handle;
14744
15110
  let declared = null;
14745
15111
  try {
14746
- handle = (0, import_node_fs15.openSync)(fullPath, "r");
15112
+ handle = (0, import_node_fs16.openSync)(fullPath, "r");
14747
15113
  } catch {
14748
15114
  unreadable.push(relativePath);
14749
15115
  return;
14750
15116
  }
14751
15117
  try {
14752
- if ((0, import_node_fs15.fstatSync)(handle).size > maxFileBytes) return;
15118
+ if ((0, import_node_fs16.fstatSync)(handle).size > maxFileBytes) return;
14753
15119
  if (mayDeclareInterpreter) {
14754
15120
  const prefix = Buffer.alloc(128);
14755
- const read = (0, import_node_fs15.readSync)(handle, prefix, 0, prefix.length, 0);
15121
+ const read = (0, import_node_fs16.readSync)(handle, prefix, 0, prefix.length, 0);
14756
15122
  declared = languageOfShebang(prefix.subarray(0, read).toString("utf-8").split("\n", 1)[0] ?? "");
14757
15123
  if (!declared) return;
14758
15124
  }
14759
- text = (0, import_node_fs15.readFileSync)(handle, "utf-8");
15125
+ text = (0, import_node_fs16.readFileSync)(handle, "utf-8");
14760
15126
  } catch {
14761
15127
  unreadable.push(relativePath);
14762
15128
  return;
14763
15129
  } finally {
14764
15130
  try {
14765
- (0, import_node_fs15.closeSync)(handle);
15131
+ (0, import_node_fs16.closeSync)(handle);
14766
15132
  } catch {
14767
15133
  }
14768
15134
  }
@@ -14780,13 +15146,13 @@ function scanPath(targetPath, options = {}) {
14780
15146
  const walk = (currentPath) => {
14781
15147
  let entries;
14782
15148
  try {
14783
- entries = (0, import_node_fs15.readdirSync)(currentPath, { withFileTypes: true });
15149
+ entries = (0, import_node_fs16.readdirSync)(currentPath, { withFileTypes: true });
14784
15150
  } catch {
14785
15151
  unreadable.push(toRelative(walkRoot, currentPath));
14786
15152
  return;
14787
15153
  }
14788
15154
  for (const entry of entries) {
14789
- const fullPath = (0, import_node_path9.join)(currentPath, entry.name);
15155
+ const fullPath = (0, import_node_path10.join)(currentPath, entry.name);
14790
15156
  const relativePath = toRelative(walkRoot, fullPath);
14791
15157
  if (entry.isDirectory()) {
14792
15158
  if (SKIP_DIRS.has(entry.name)) continue;
@@ -14810,7 +15176,7 @@ function scanPath(targetPath, options = {}) {
14810
15176
  } else if (isExcluded(toRelative(walkRoot, targetPath))) {
14811
15177
  excluded += 1;
14812
15178
  } else {
14813
- scanFile(targetPath, (0, import_node_path9.basename)(targetPath));
15179
+ scanFile(targetPath, (0, import_node_path10.basename)(targetPath));
14814
15180
  }
14815
15181
  if (options.missingControls) findings.push(...controls.findings());
14816
15182
  const filtered = allowed ? findings.filter((f) => allowed.has(f.category)) : findings;
@@ -14842,22 +15208,22 @@ function recordSensitiveFile(filename, relativePath, sink, fileFindings) {
14842
15208
  }
14843
15209
  }
14844
15210
  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("/");
15211
+ const rel = (0, import_node_path10.relative)(base, target);
15212
+ return (rel === "" ? target : rel).split(import_node_path10.sep).join("/");
14847
15213
  }
14848
15214
 
14849
15215
  // ../../packages/scan/src/node/dependencies.ts
14850
- var import_node_fs16 = require("fs");
14851
- var import_node_path10 = require("path");
15216
+ var import_node_fs17 = require("fs");
15217
+ var import_node_path11 = require("path");
14852
15218
  var MAX_DEPS_PER_LOCKFILE = 50;
14853
15219
  async function scanDependencies(targetPath) {
14854
15220
  const findings = [];
14855
15221
  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;
15222
+ const lockPath = (0, import_node_path11.join)(targetPath, file);
15223
+ if (!(0, import_node_fs17.existsSync)(lockPath)) continue;
14858
15224
  let deps;
14859
15225
  try {
14860
- deps = dedupe(parse((0, import_node_fs16.readFileSync)(lockPath, "utf-8")));
15226
+ deps = dedupe(parse((0, import_node_fs17.readFileSync)(lockPath, "utf-8")));
14861
15227
  } catch {
14862
15228
  continue;
14863
15229
  }
@@ -15072,16 +15438,16 @@ async function queryOsv(name, version, ecosystem) {
15072
15438
 
15073
15439
  // ../../packages/scan/src/node/sarif.ts
15074
15440
  var import_node_crypto3 = require("crypto");
15075
- var import_node_path11 = require("path");
15441
+ var import_node_path12 = require("path");
15076
15442
 
15077
15443
  // src/commands/scan.ts
15078
15444
  function readVersion() {
15079
15445
  for (const candidate of [
15080
- (0, import_node_path12.join)(__dirname, "..", "package.json"),
15081
- (0, import_node_path12.join)(__dirname, "..", "..", "package.json")
15446
+ (0, import_node_path13.join)(__dirname, "..", "package.json"),
15447
+ (0, import_node_path13.join)(__dirname, "..", "..", "package.json")
15082
15448
  ]) {
15083
15449
  try {
15084
- return JSON.parse((0, import_node_fs17.readFileSync)(candidate, "utf-8")).version ?? "0.0.0";
15450
+ return JSON.parse((0, import_node_fs18.readFileSync)(candidate, "utf-8")).version ?? "0.0.0";
15085
15451
  } catch {
15086
15452
  }
15087
15453
  }
@@ -15426,7 +15792,7 @@ var RunsWorker = class {
15426
15792
 
15427
15793
  // src/core/cloud-events.ts
15428
15794
  var import_node_crypto4 = require("crypto");
15429
- var import_node_net2 = require("net");
15795
+ var import_node_net4 = require("net");
15430
15796
  function currentLink() {
15431
15797
  if (!hasSession()) return null;
15432
15798
  const cfg = readCliConfig();
@@ -15483,7 +15849,7 @@ function detectionEvent(serverId, event) {
15483
15849
  title: title.slice(0, MAX_TITLE_CHARS) || event.module,
15484
15850
  rule_id: str(rule_id) ?? event.module,
15485
15851
  description: str(description),
15486
- source_ip: event.source_ip && (0, import_node_net2.isIP)(event.source_ip) ? event.source_ip : void 0,
15852
+ source_ip: event.source_ip && (0, import_node_net4.isIP)(event.source_ip) ? event.source_ip : void 0,
15487
15853
  username: str(username) ?? str(user),
15488
15854
  raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
15489
15855
  detected_at: event.timestamp.toISOString()
@@ -15525,16 +15891,16 @@ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date(
15525
15891
  }
15526
15892
 
15527
15893
  // src/daemon/workers/cloud-spool.ts
15528
- var import_node_fs18 = require("fs");
15894
+ var import_node_fs19 = require("fs");
15529
15895
  var import_promises = require("fs/promises");
15530
- var import_node_path13 = require("path");
15896
+ var import_node_path14 = require("path");
15531
15897
  var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
15532
15898
  var CloudSpool = class {
15533
15899
  constructor(path, limits = DEFAULT_SPOOL_LIMITS) {
15534
15900
  this.path = path;
15535
15901
  this.limits = limits;
15536
15902
  try {
15537
- (0, import_node_fs18.mkdirSync)((0, import_node_path13.dirname)(path), { recursive: true });
15903
+ (0, import_node_fs19.mkdirSync)((0, import_node_path14.dirname)(path), { recursive: true });
15538
15904
  } catch {
15539
15905
  }
15540
15906
  this.load();
@@ -15603,7 +15969,7 @@ var CloudSpool = class {
15603
15969
  load() {
15604
15970
  let raw;
15605
15971
  try {
15606
- raw = (0, import_node_fs18.readFileSync)(this.path, "utf-8");
15972
+ raw = (0, import_node_fs19.readFileSync)(this.path, "utf-8");
15607
15973
  } catch {
15608
15974
  return;
15609
15975
  }
@@ -15841,146 +16207,17 @@ var CloudSync = class {
15841
16207
  };
15842
16208
 
15843
16209
  // src/daemon/workers/remediation-consumer.ts
15844
- var import_node_net5 = require("net");
16210
+ var import_node_net6 = require("net");
15845
16211
 
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
- }
15974
-
15975
- // src/daemon/workers/allowlist-sync.ts
15976
- var import_node_net4 = require("net");
15977
- function isAddressOrCidr(value) {
15978
- const [network, prefix, extra] = value.split("/");
15979
- const family = (0, import_node_net4.isIP)(network);
15980
- if (family === 0 || extra !== void 0) return false;
15981
- if (prefix === void 0) return true;
15982
- if (!/^\d{1,3}$/.test(prefix)) return false;
15983
- return Number(prefix) <= (family === 4 ? 32 : 128);
16212
+ // src/daemon/workers/allowlist-sync.ts
16213
+ var import_node_net5 = require("net");
16214
+ function isAddressOrCidr(value) {
16215
+ const [network, prefix, extra] = value.split("/");
16216
+ const family = (0, import_node_net5.isIP)(network);
16217
+ if (family === 0 || extra !== void 0) return false;
16218
+ if (prefix === void 0) return true;
16219
+ if (!/^\d{1,3}$/.test(prefix)) return false;
16220
+ return Number(prefix) <= (family === 4 ? 32 : 128);
15984
16221
  }
15985
16222
  var AllowlistSync = class {
15986
16223
  constructor(manager, opts) {
@@ -16019,13 +16256,13 @@ var AllowlistSync = class {
16019
16256
  const value = String(entry.value ?? "").trim();
16020
16257
  if (isAddressOrCidr(value)) wanted.add(value);
16021
16258
  }
16022
- const added = [];
16259
+ const added2 = [];
16023
16260
  const protectedNow = new Set(this.manager.getProtected());
16024
16261
  for (const value of wanted) {
16025
16262
  if (this.owned.has(value) || protectedNow.has(value)) continue;
16026
16263
  this.manager.addToAllowlist(value);
16027
16264
  this.owned.add(value);
16028
- added.push(value);
16265
+ added2.push(value);
16029
16266
  }
16030
16267
  const removed = [];
16031
16268
  for (const value of this.owned) {
@@ -16034,9 +16271,9 @@ var AllowlistSync = class {
16034
16271
  this.owned.delete(value);
16035
16272
  removed.push(value);
16036
16273
  }
16037
- if (added.length > 0 || removed.length > 0) {
16274
+ if (added2.length > 0 || removed.length > 0) {
16038
16275
  this.opts.log(
16039
- `[cloud] org allowlist: +${added.length} -${removed.length} (${[...added.map((v) => `+${v}`), ...removed.map((v) => `-${v}`)].slice(0, 10).join(" ")})`
16276
+ `[cloud] org allowlist: +${added2.length} -${removed.length} (${[...added2.map((v) => `+${v}`), ...removed.map((v) => `-${v}`)].slice(0, 10).join(" ")})`
16040
16277
  );
16041
16278
  }
16042
16279
  }
@@ -16125,7 +16362,7 @@ var RemediationConsumer = class {
16125
16362
  try {
16126
16363
  switch (action.action_type) {
16127
16364
  case "block": {
16128
- if ((0, import_node_net5.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
16365
+ if ((0, import_node_net6.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
16129
16366
  let ttlSeconds = this.manager.status().max_ban_seconds;
16130
16367
  if (action.expires_at) {
16131
16368
  const until = Date.parse(action.expires_at);
@@ -16144,7 +16381,7 @@ var RemediationConsumer = class {
16144
16381
  return { status: "executed", dry_run: result.entry?.dry_run === true, executed_at };
16145
16382
  }
16146
16383
  case "unblock": {
16147
- if ((0, import_node_net5.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
16384
+ if ((0, import_node_net6.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
16148
16385
  const wasBanned = this.manager.getBlocklist().some((b) => b.ip === target);
16149
16386
  const result = await this.manager.unban(target, {
16150
16387
  forget: true,
@@ -16189,8 +16426,8 @@ var RemediationConsumer = class {
16189
16426
 
16190
16427
  // src/daemon/workers/auto-update.ts
16191
16428
  var import_node_child_process5 = require("child_process");
16192
- var import_node_fs19 = require("fs");
16193
- var import_node_path14 = require("path");
16429
+ var import_node_fs20 = require("fs");
16430
+ var import_node_path15 = require("path");
16194
16431
  var PKG_NAME = "@profullstack/threatcrush";
16195
16432
  var REGISTRY = `https://registry.npmjs.org/${PKG_NAME}`;
16196
16433
  var DEFAULT_INTERVAL_MS = 6 * 36e5;
@@ -16227,12 +16464,12 @@ function pickUpdate(doc, current, opts) {
16227
16464
  return { version: latest };
16228
16465
  }
16229
16466
  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`;
16467
+ const expected = `${import_node_path15.sep}lib${import_node_path15.sep}node_modules${import_node_path15.sep}@profullstack${import_node_path15.sep}threatcrush`;
16231
16468
  if (!opts.pkgRoot.endsWith(expected)) {
16232
16469
  return { kind: "unsupported", reason: `not an npm global install (${opts.pkgRoot}); run \`threatcrush update\`` };
16233
16470
  }
16234
- const nodeBin = (0, import_node_path14.dirname)(opts.execPath);
16235
- const npm = (0, import_node_path14.join)(nodeBin, "npm");
16471
+ const nodeBin = (0, import_node_path15.dirname)(opts.execPath);
16472
+ const npm = (0, import_node_path15.join)(nodeBin, "npm");
16236
16473
  if (!opts.npmExists(npm)) return { kind: "unsupported", reason: `no npm beside ${opts.execPath}` };
16237
16474
  if (!opts.owner) return { kind: "unsupported", reason: `cannot tell who owns ${opts.pkgRoot}` };
16238
16475
  const npmArgs = [npm, "i", "-g", `${PKG_NAME}@${opts.version}`, "--no-fund", "--no-audit"];
@@ -16264,10 +16501,10 @@ function installPlan(opts) {
16264
16501
  }
16265
16502
  function ownerOf(path, passwd = "/etc/passwd") {
16266
16503
  try {
16267
- const st = (0, import_node_fs19.statSync)(path);
16504
+ const st = (0, import_node_fs20.statSync)(path);
16268
16505
  let home = st.uid === 0 ? "/root" : "";
16269
16506
  try {
16270
- for (const line of (0, import_node_fs19.readFileSync)(passwd, "utf8").split("\n")) {
16507
+ for (const line of (0, import_node_fs20.readFileSync)(passwd, "utf8").split("\n")) {
16271
16508
  const f = line.split(":");
16272
16509
  if (Number(f[2]) === st.uid && f[5]) home = f[5];
16273
16510
  }
@@ -16372,7 +16609,7 @@ var AutoUpdate = class {
16372
16609
  uid: process.getuid?.() ?? -1,
16373
16610
  owner: ownerOf(this.opts.pkgRoot),
16374
16611
  underSystemd: this.opts.underSystemd ?? Boolean(process.env.INVOCATION_ID),
16375
- npmExists: import_node_fs19.existsSync
16612
+ npmExists: import_node_fs20.existsSync
16376
16613
  });
16377
16614
  if (plan.kind === "unsupported") return this.note(`${target} is available but cannot self-install: ${plan.reason}`);
16378
16615
  this.recordAttempt(target);
@@ -16407,7 +16644,7 @@ var AutoUpdate = class {
16407
16644
  }
16408
16645
  lastAttempt() {
16409
16646
  try {
16410
- const v = JSON.parse((0, import_node_fs19.readFileSync)(this.opts.statePath, "utf8"));
16647
+ const v = JSON.parse((0, import_node_fs20.readFileSync)(this.opts.statePath, "utf8"));
16411
16648
  return v.version && typeof v.at === "number" ? { version: v.version, at: v.at } : null;
16412
16649
  } catch {
16413
16650
  return null;
@@ -16415,13 +16652,587 @@ var AutoUpdate = class {
16415
16652
  }
16416
16653
  recordAttempt(version) {
16417
16654
  try {
16418
- (0, import_node_fs19.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
16655
+ (0, import_node_fs20.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
16419
16656
  } catch (err) {
16420
16657
  this.opts.log(`[update] could not record attempt: ${err.message}`);
16421
16658
  }
16422
16659
  }
16423
16660
  };
16424
16661
 
16662
+ // src/daemon/workers/threat-feeds.ts
16663
+ var import_node_child_process6 = require("child_process");
16664
+ var import_node_net7 = require("net");
16665
+ var EGRESS_TABLE = "threatcrush_egress";
16666
+ var DEFAULT_REFRESH_MS = 36e5;
16667
+ var POLL_MS = 15e3;
16668
+ var REALERT_MS = 36e5;
16669
+ function threatFeedSettings(section) {
16670
+ const refresh = parseDuration(section?.refresh);
16671
+ return {
16672
+ enabled: section?.enabled !== false,
16673
+ block: section?.block === true,
16674
+ // abuse.ch asks for no more than one fetch per 5 minutes; hourly is plenty.
16675
+ refreshMs: refresh ? Math.max(900, refresh) * 1e3 : DEFAULT_REFRESH_MS,
16676
+ minConfidence: typeof section?.min_confidence === "number" ? section.min_confidence : 75,
16677
+ allow: Array.isArray(section?.allow) ? section.allow.map(String) : []
16678
+ };
16679
+ }
16680
+ function egressRuleset(ips) {
16681
+ const v4 = ips.filter((ip) => (0, import_node_net7.isIP)(ip) === 4);
16682
+ const v6 = ips.filter((ip) => (0, import_node_net7.isIP)(ip) === 6);
16683
+ const set = (name, type, items) => ` set ${name} { type ${type};${items.length ? ` elements = { ${items.join(", ")} }` : ""} }`;
16684
+ const chain = (name, hook) => [
16685
+ ` chain ${name} {`,
16686
+ ` type filter hook ${hook} priority -1; policy accept;`,
16687
+ ` ip daddr @c2_v4 counter drop`,
16688
+ ` ip6 daddr @c2_v6 counter drop`,
16689
+ ` }`
16690
+ ].join("\n");
16691
+ return [
16692
+ `table inet ${EGRESS_TABLE}`,
16693
+ `delete table inet ${EGRESS_TABLE}`,
16694
+ `table inet ${EGRESS_TABLE} {`,
16695
+ set("c2_v4", "ipv4_addr", v4),
16696
+ set("c2_v6", "ipv6_addr", v6),
16697
+ chain("output", "output"),
16698
+ chain("forward", "forward"),
16699
+ `}`,
16700
+ ""
16701
+ ].join("\n");
16702
+ }
16703
+ function splitAddr(addr) {
16704
+ const m = /^\[?(.+?)\]?:(\d+|\*)$/.exec(addr);
16705
+ if (!m) return null;
16706
+ const ip = m[1].replace(/%.*$/, "").replace(/^::ffff:/i, "");
16707
+ return (0, import_node_net7.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
16708
+ }
16709
+ function parseSs(text) {
16710
+ const out = [];
16711
+ for (const line of text.split("\n")) {
16712
+ const cols = line.trim().split(/\s+/);
16713
+ if (cols.length < 5) continue;
16714
+ const local = splitAddr(cols[3]);
16715
+ const peer = splitAddr(cols[4]);
16716
+ if (!local || !peer) continue;
16717
+ const proc = /users:\(\("([^"]+)",pid=(\d+)/.exec(line);
16718
+ out.push({
16719
+ state: cols[0],
16720
+ localPort: local.port,
16721
+ peerIp: peer.ip,
16722
+ peerPort: peer.port,
16723
+ process: proc?.[1] ?? null,
16724
+ pid: proc ? Number(proc[2]) : null
16725
+ });
16726
+ }
16727
+ return out;
16728
+ }
16729
+ function parseListeningPorts(text) {
16730
+ const ports = /* @__PURE__ */ new Set();
16731
+ for (const line of text.split("\n")) {
16732
+ const cols = line.trim().split(/\s+/);
16733
+ const local = cols.length >= 4 ? splitAddr(cols[3]) : null;
16734
+ if (local) ports.add(local.port);
16735
+ }
16736
+ return ports;
16737
+ }
16738
+ function defaultRun2(cmd, args, input) {
16739
+ const res = (0, import_node_child_process6.spawnSync)(cmd, args, { encoding: "utf-8", input, timeout: 15e3, stdio: ["pipe", "pipe", "pipe"] });
16740
+ return res.status === 0 ? res.stdout : null;
16741
+ }
16742
+ var ThreatFeeds = class {
16743
+ constructor(opts) {
16744
+ this.opts = opts;
16745
+ this.run = opts.run ?? defaultRun2;
16746
+ this.now = opts.now ?? Date.now;
16747
+ }
16748
+ opts;
16749
+ timers = [];
16750
+ set = null;
16751
+ alerted = /* @__PURE__ */ new Map();
16752
+ blocking = false;
16753
+ run;
16754
+ now;
16755
+ get wantsBlock() {
16756
+ return this.opts.settings.block && this.opts.enforcing;
16757
+ }
16758
+ start() {
16759
+ const { settings } = this.opts;
16760
+ if (!settings.enabled) {
16761
+ this.opts.log("[threat-feeds] disabled by [threat_feeds] enabled = false");
16762
+ this.removeBlocking();
16763
+ return;
16764
+ }
16765
+ if (settings.block && !this.opts.enforcing) {
16766
+ this.opts.log("[threat-feeds] block = true but remediation is in dry_run (or has no firewall): detecting only");
16767
+ }
16768
+ const cached = readFeedCache(this.opts.cachePath);
16769
+ if (cached) this.apply(cached, "cache");
16770
+ if (!this.wantsBlock) this.removeBlocking();
16771
+ const stale = !cached || this.now() - Date.parse(cached.fetched_at) > settings.refreshMs;
16772
+ const first = setTimeout(() => void this.refresh(), stale ? 1e4 : settings.refreshMs);
16773
+ first.unref?.();
16774
+ const every = setInterval(() => void this.refresh(), settings.refreshMs);
16775
+ every.unref?.();
16776
+ const poll = setInterval(() => this.pollConnections(), POLL_MS);
16777
+ poll.unref?.();
16778
+ this.timers.push(first, every, poll);
16779
+ }
16780
+ stop() {
16781
+ for (const t of this.timers) clearInterval(t);
16782
+ this.timers = [];
16783
+ }
16784
+ async refresh() {
16785
+ try {
16786
+ const set = await fetchFeeds(this.opts.settings, this.opts.fetchImpl);
16787
+ const failed = set.sources.filter((s) => !s.ok);
16788
+ if (failed.length === set.sources.length) {
16789
+ this.opts.log(`[threat-feeds] refresh failed, keeping previous list: ${failed.map((s) => `${s.feed}: ${s.error}`).join("; ")}`);
16790
+ return;
16791
+ }
16792
+ for (const f of failed) this.opts.log(`[threat-feeds] ${f.feed} unavailable: ${f.error}`);
16793
+ try {
16794
+ writeFeedCache(this.opts.cachePath, set);
16795
+ } catch (err) {
16796
+ this.opts.log(`[threat-feeds] could not write cache: ${err.message}`);
16797
+ }
16798
+ this.apply(set, "refresh");
16799
+ } catch (err) {
16800
+ this.opts.log(`[threat-feeds] refresh failed: ${err.message}`);
16801
+ }
16802
+ }
16803
+ apply(set, from) {
16804
+ this.set = set;
16805
+ setActiveFeeds(set);
16806
+ const ips = Object.keys(set.ips);
16807
+ const domains = Object.keys(set.domains).length;
16808
+ let mode = "detecting";
16809
+ if (this.wantsBlock) {
16810
+ const ok = this.run("nft", ["-f", "-"], egressRuleset(ips)) !== null;
16811
+ this.blocking = ok;
16812
+ mode = ok ? "blocking egress" : "detecting (nft load failed)";
16813
+ }
16814
+ const detail = `${ips.length} IPs, ${domains} domains, ${mode}`;
16815
+ this.opts.log(`[threat-feeds] ${from === "cache" ? "loaded cached" : "refreshed"} list: ${detail} (${set.skipped_shared} shared/protected entries skipped)`);
16816
+ this.opts.bus.announceModule("threat-feeds", "running", detail);
16817
+ }
16818
+ removeBlocking() {
16819
+ if (this.run("nft", ["list", "table", "inet", EGRESS_TABLE]) !== null) {
16820
+ this.run("nft", ["delete", "table", "inet", EGRESS_TABLE]);
16821
+ this.opts.log(`[threat-feeds] removed egress table ${EGRESS_TABLE} (blocking is off)`);
16822
+ }
16823
+ this.blocking = false;
16824
+ }
16825
+ /** Outbound connections to listed IPs, one alert per IP and process per hour. */
16826
+ pollConnections() {
16827
+ if (!this.set || Object.keys(this.set.ips).length === 0) return;
16828
+ const conns = this.run("ss", ["-tnpH"]);
16829
+ if (conns === null) return;
16830
+ const listening = parseListeningPorts(this.run("ss", ["-ltnH"]) ?? "");
16831
+ const now = this.now();
16832
+ for (const c of parseSs(conns)) {
16833
+ if (listening.has(c.localPort)) continue;
16834
+ const ind = matchIp(c.peerIp, this.set);
16835
+ if (!ind) continue;
16836
+ const key = `${c.peerIp}|${c.process ?? "?"}`;
16837
+ if (now - (this.alerted.get(key) ?? 0) < REALERT_MS) continue;
16838
+ this.alerted.set(key, now);
16839
+ const who = c.process ? `${c.process} (pid ${c.pid})` : "an unknown process";
16840
+ const blocked = this.blocking ? " \u2014 blocked" : "";
16841
+ this.opts.bus.publish({
16842
+ timestamp: new Date(now),
16843
+ module: "threat-feeds",
16844
+ category: "network",
16845
+ severity: "critical",
16846
+ message: `Outbound connection to known ${ind.malware} ${ind.threat === "botnet_cc" ? "C2" : "malware host"} ${c.peerIp}:${c.peerPort} by ${who}${blocked}`,
16847
+ // No source_ip on purpose: the remote end is not an attacker to ban
16848
+ // inbound, so remediation has nothing to act on and the egress table
16849
+ // stays the only enforcement.
16850
+ details: {
16851
+ rule_id: "threat-feed-outbound",
16852
+ destination_ip: c.peerIp,
16853
+ destination_port: c.peerPort,
16854
+ state: c.state,
16855
+ process: c.process,
16856
+ pid: c.pid,
16857
+ malware: ind.malware,
16858
+ threat: ind.threat,
16859
+ feed: ind.feed,
16860
+ blocked: this.blocking
16861
+ }
16862
+ });
16863
+ }
16864
+ for (const [key, at] of this.alerted) if (now - at > REALERT_MS) this.alerted.delete(key);
16865
+ }
16866
+ };
16867
+
16868
+ // src/daemon/workers/privilege-watch.ts
16869
+ var import_node_fs21 = require("fs");
16870
+ var import_node_path16 = require("path");
16871
+ var import_node_child_process7 = require("child_process");
16872
+
16873
+ // src/core/privileges/index.ts
16874
+ var import_node_crypto5 = require("crypto");
16875
+ var ADMIN_GROUPS = ["sudo", "wheel", "admin"];
16876
+ function parseUsers(text) {
16877
+ const out = [];
16878
+ for (const line of text.split("\n")) {
16879
+ const f = line.split(":");
16880
+ if (f.length < 7 || line.startsWith("#")) continue;
16881
+ const uid = Number(f[2]);
16882
+ if (!f[0] || !Number.isInteger(uid)) continue;
16883
+ out.push({ name: f[0], uid, home: f[5], shell: f[6].trim() });
16884
+ }
16885
+ return out;
16886
+ }
16887
+ function parseAdminGroups(text) {
16888
+ const out = {};
16889
+ for (const line of text.split("\n")) {
16890
+ const f = line.split(":");
16891
+ if (f.length < 4 || !ADMIN_GROUPS.includes(f[0])) continue;
16892
+ out[f[0]] = f[3].trim().split(",").map((m) => m.trim()).filter(Boolean).sort();
16893
+ }
16894
+ return out;
16895
+ }
16896
+ function canLogIn(user) {
16897
+ return !/(nologin|\/false|\/sync|\/shutdown|\/halt)$/.test(user.shell);
16898
+ }
16899
+ function sudoersRules(text) {
16900
+ const joined = text.replace(/\\\n/g, " ");
16901
+ const rules = [];
16902
+ for (const raw of joined.split("\n")) {
16903
+ const line = raw.trim();
16904
+ if (!line) continue;
16905
+ if (line.startsWith("#") && !/^#include(dir)?\s/.test(line)) continue;
16906
+ rules.push(line.replace(/\s+/g, " "));
16907
+ }
16908
+ return rules;
16909
+ }
16910
+ function sudoReadsIncluded(name) {
16911
+ return !name.endsWith("~") && !name.includes(".");
16912
+ }
16913
+ function keyFingerprint(blobBase64) {
16914
+ if (!/^[A-Za-z0-9+/]+=*$/.test(blobBase64)) return null;
16915
+ const digest = (0, import_node_crypto5.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
16916
+ return `SHA256:${digest.replace(/=+$/, "")}`;
16917
+ }
16918
+ function parseAuthorizedKeys(text) {
16919
+ const out = [];
16920
+ for (const raw of text.split("\n")) {
16921
+ const line = raw.trim();
16922
+ if (!line || line.startsWith("#")) continue;
16923
+ const m = /(?:^|\s)((?:ssh|ecdsa|sk)-[\w@.-]+)\s+([A-Za-z0-9+/]+=*)(?:\s+(.*))?$/.exec(line);
16924
+ if (!m) continue;
16925
+ const fingerprint = keyFingerprint(m[2]);
16926
+ if (fingerprint) out.push({ fingerprint, type: m[1], comment: (m[3] ?? "").trim() });
16927
+ }
16928
+ return out;
16929
+ }
16930
+ function takeSnapshot(io, now = /* @__PURE__ */ new Date()) {
16931
+ const unreadable = [];
16932
+ const read = (path) => {
16933
+ const text = io.readFile(path);
16934
+ if (text === null && io.exists(path)) unreadable.push(path);
16935
+ return text;
16936
+ };
16937
+ const users = parseUsers(read("/etc/passwd") ?? "");
16938
+ const snapshot = {
16939
+ taken_at: now.toISOString(),
16940
+ uid0: users.filter((a) => a.uid === 0).map((a) => a.name).sort(),
16941
+ admin_groups: parseAdminGroups(read("/etc/group") ?? ""),
16942
+ sudoers: {},
16943
+ keys: {},
16944
+ unreadable
16945
+ };
16946
+ const sudoersFiles = ["/etc/sudoers"];
16947
+ for (const name of (io.readDir("/etc/sudoers.d") ?? []).sort()) {
16948
+ if (sudoReadsIncluded(name)) sudoersFiles.push(`/etc/sudoers.d/${name}`);
16949
+ }
16950
+ for (const path of sudoersFiles) {
16951
+ const text = read(path);
16952
+ if (text !== null) snapshot.sudoers[path] = sudoersRules(text);
16953
+ }
16954
+ for (const user of users) {
16955
+ if (user.uid !== 0 && (!canLogIn(user) || !user.home || user.home === "/")) continue;
16956
+ const keys = {};
16957
+ for (const file of ["authorized_keys", "authorized_keys2"]) {
16958
+ const text = read(`${user.home.replace(/\/$/, "")}/.ssh/${file}`);
16959
+ for (const k of parseAuthorizedKeys(text ?? "")) keys[k.fingerprint] = { type: k.type, comment: k.comment };
16960
+ }
16961
+ if (Object.keys(keys).length > 0) snapshot.keys[user.name] = keys;
16962
+ }
16963
+ return snapshot;
16964
+ }
16965
+ var added = (before, after) => after.filter((x) => !before.includes(x));
16966
+ function diffSnapshots(prev, next) {
16967
+ const changes = [];
16968
+ for (const name of added(prev.uid0, next.uid0)) {
16969
+ changes.push({ severity: "critical", message: `New uid 0 account: ${name}`, details: { rule_id: "priv-uid0-added", account: name } });
16970
+ }
16971
+ for (const name of added(next.uid0, prev.uid0)) {
16972
+ changes.push({ severity: "low", message: `uid 0 account removed: ${name}`, details: { rule_id: "priv-uid0-removed", account: name } });
16973
+ }
16974
+ for (const group of /* @__PURE__ */ new Set([...Object.keys(prev.admin_groups), ...Object.keys(next.admin_groups)])) {
16975
+ const before = prev.admin_groups[group] ?? [];
16976
+ const after = next.admin_groups[group] ?? [];
16977
+ for (const m of added(before, after)) {
16978
+ changes.push({ severity: "high", message: `${m} added to the ${group} group (can run anything as root)`, details: { rule_id: "priv-admin-group-added", group, account: m } });
16979
+ }
16980
+ for (const m of added(after, before)) {
16981
+ changes.push({ severity: "low", message: `${m} removed from the ${group} group`, details: { rule_id: "priv-admin-group-removed", group, account: m } });
16982
+ }
16983
+ }
16984
+ for (const path of /* @__PURE__ */ new Set([...Object.keys(prev.sudoers), ...Object.keys(next.sudoers)])) {
16985
+ if (next.unreadable.includes(path) || prev.unreadable.includes(path)) continue;
16986
+ const before = prev.sudoers[path];
16987
+ const after = next.sudoers[path];
16988
+ if (!before && after) {
16989
+ changes.push({ severity: "high", message: `New sudoers file ${path}${after.length ? `: ${after.slice(0, 3).join(" | ")}` : ""}`, details: { rule_id: "priv-sudoers-added", path, rules: after.slice(0, 20) } });
16990
+ continue;
16991
+ }
16992
+ if (before && !after) {
16993
+ changes.push({ severity: "low", message: `Sudoers file removed: ${path}`, details: { rule_id: "priv-sudoers-removed", path } });
16994
+ continue;
16995
+ }
16996
+ const plus = added(before ?? [], after ?? []);
16997
+ const minus = added(after ?? [], before ?? []);
16998
+ if (plus.length) {
16999
+ changes.push({ severity: "high", message: `Sudoers rule added in ${path}: ${plus.slice(0, 3).join(" | ")}`, details: { rule_id: "priv-sudoers-changed", path, added: plus.slice(0, 20), removed: minus.slice(0, 20) } });
17000
+ } else if (minus.length) {
17001
+ changes.push({ severity: "low", message: `Sudoers rule removed in ${path}: ${minus.slice(0, 3).join(" | ")}`, details: { rule_id: "priv-sudoers-changed", path, removed: minus.slice(0, 20) } });
17002
+ }
17003
+ }
17004
+ for (const user of /* @__PURE__ */ new Set([...Object.keys(prev.keys), ...Object.keys(next.keys)])) {
17005
+ const before = prev.keys[user] ?? {};
17006
+ const after = next.keys[user] ?? {};
17007
+ for (const fp of Object.keys(after)) {
17008
+ if (before[fp]) continue;
17009
+ const { type, comment } = after[fp];
17010
+ changes.push({
17011
+ severity: "high",
17012
+ message: `New SSH key for ${user}: ${type} ${fp}${comment ? ` (${comment})` : ""}`,
17013
+ details: { rule_id: "priv-authorized-key-added", account: user, fingerprint: fp, key_type: type, comment }
17014
+ });
17015
+ }
17016
+ for (const fp of Object.keys(before)) {
17017
+ if (after[fp]) continue;
17018
+ changes.push({ severity: "low", message: `SSH key removed for ${user}: ${fp}`, details: { rule_id: "priv-authorized-key-removed", account: user, fingerprint: fp } });
17019
+ }
17020
+ }
17021
+ const rank = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
17022
+ return changes.sort((a, b) => rank[b.severity] - rank[a.severity]);
17023
+ }
17024
+ function parseSudoMessage(message) {
17025
+ const m = /^\s*(\S+)\s+:\s+(.*)$/.exec(message);
17026
+ if (!m) return null;
17027
+ const fields = {};
17028
+ let reason = "";
17029
+ for (const part of m[2].split(" ; ")) {
17030
+ const kv = /^([A-Z]+)=(.*)$/.exec(part.trim());
17031
+ if (kv) fields[kv[1]] = kv[2];
17032
+ else if (!reason) reason = part.trim();
17033
+ }
17034
+ if (!fields.COMMAND) return null;
17035
+ if (/incorrect password|authentication failure/i.test(reason)) return null;
17036
+ return {
17037
+ user: m[1],
17038
+ runas: fields.USER ?? "root",
17039
+ command: fields.COMMAND,
17040
+ tty: fields.TTY,
17041
+ pwd: fields.PWD,
17042
+ denied: /not allowed|not in the sudoers|NOT in sudoers|command not allowed/i.test(reason)
17043
+ };
17044
+ }
17045
+
17046
+ // src/daemon/workers/privilege-watch.ts
17047
+ function privilegeSettings(section) {
17048
+ return { enabled: section?.enabled !== false, geo: section?.geo !== false, pollMs: 6e4 };
17049
+ }
17050
+ var COUNTRY_NAMES = new Intl.DisplayNames(["en"], { type: "region" });
17051
+ function countryName(code) {
17052
+ try {
17053
+ return COUNTRY_NAMES.of(code) ?? code;
17054
+ } catch {
17055
+ return code;
17056
+ }
17057
+ }
17058
+ var fsIO = {
17059
+ readFile: (p) => {
17060
+ try {
17061
+ return (0, import_node_fs21.readFileSync)(p, "utf-8");
17062
+ } catch {
17063
+ return null;
17064
+ }
17065
+ },
17066
+ readDir: (p) => {
17067
+ try {
17068
+ return (0, import_node_fs21.readdirSync)(p);
17069
+ } catch {
17070
+ return null;
17071
+ }
17072
+ },
17073
+ exists: (p) => (0, import_node_fs21.existsSync)(p)
17074
+ };
17075
+ function readJson(path) {
17076
+ try {
17077
+ return JSON.parse((0, import_node_fs21.readFileSync)(path, "utf-8"));
17078
+ } catch {
17079
+ return null;
17080
+ }
17081
+ }
17082
+ function writeJson(path, value) {
17083
+ (0, import_node_fs21.mkdirSync)((0, import_node_path16.dirname)(path), { recursive: true });
17084
+ (0, import_node_fs21.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
17085
+ (0, import_node_fs21.renameSync)(`${path}.tmp`, path);
17086
+ }
17087
+ function defaultRun3(cmd, args) {
17088
+ const res = (0, import_node_child_process7.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 2e4, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
17089
+ return res.status === 0 ? res.stdout : null;
17090
+ }
17091
+ async function geolocateViaThreatcrush(ip, fetchImpl = fetch) {
17092
+ const res = await fetchImpl("https://threatcrush.com/api/geo", {
17093
+ method: "POST",
17094
+ headers: { "Content-Type": "application/json" },
17095
+ body: JSON.stringify({ ips: [ip] }),
17096
+ signal: AbortSignal.timeout(8e3)
17097
+ });
17098
+ if (!res.ok) return null;
17099
+ const body = await res.json();
17100
+ const code = body.results?.[ip]?.countryCode;
17101
+ return typeof code === "string" && /^[A-Z]{2}$/.test(code) ? { countryCode: code } : null;
17102
+ }
17103
+ var PrivilegeWatch = class {
17104
+ constructor(opts) {
17105
+ this.opts = opts;
17106
+ this.io = opts.io ?? fsIO;
17107
+ this.run = opts.run ?? defaultRun3;
17108
+ this.now = opts.now ?? (() => /* @__PURE__ */ new Date());
17109
+ }
17110
+ opts;
17111
+ timers = [];
17112
+ io;
17113
+ run;
17114
+ now;
17115
+ warnedUnreadable = false;
17116
+ onEvent = (event) => {
17117
+ void this.checkLogin(event);
17118
+ };
17119
+ start() {
17120
+ if (!this.opts.settings.enabled) {
17121
+ this.opts.log("[privileged] disabled by [privileged] enabled = false");
17122
+ return;
17123
+ }
17124
+ this.checkSnapshot();
17125
+ this.readSudoLedger();
17126
+ if (this.opts.settings.geo) this.opts.bus.on("event", this.onEvent);
17127
+ const timer = setInterval(() => {
17128
+ this.checkSnapshot();
17129
+ this.readSudoLedger();
17130
+ }, this.opts.settings.pollMs);
17131
+ timer.unref?.();
17132
+ this.timers.push(timer);
17133
+ }
17134
+ stop() {
17135
+ for (const t of this.timers) clearInterval(t);
17136
+ this.timers = [];
17137
+ this.opts.bus.off("event", this.onEvent);
17138
+ }
17139
+ emit(severity, message, details) {
17140
+ const event = { timestamp: this.now(), module: "privileged-access", category: "auth", severity, message, details };
17141
+ try {
17142
+ insertEvent(event);
17143
+ } catch {
17144
+ }
17145
+ this.opts.bus.publish(event);
17146
+ }
17147
+ checkSnapshot() {
17148
+ const next = takeSnapshot(this.io, this.now());
17149
+ if (next.unreadable.length && !this.warnedUnreadable) {
17150
+ this.warnedUnreadable = true;
17151
+ this.opts.log(`[privileged] cannot read ${next.unreadable.join(", ")}; run the daemon as root to watch them`);
17152
+ }
17153
+ const prev = readJson(this.opts.snapshotPath);
17154
+ if (!prev) {
17155
+ const keys = Object.values(next.keys).reduce((n, k) => n + Object.keys(k).length, 0);
17156
+ this.opts.log(`[privileged] baseline recorded: uid0 [${next.uid0.join(", ")}], ${Object.values(next.admin_groups).flat().length} admin-group member(s), ${Object.keys(next.sudoers).length} sudoers file(s), ${keys} authorized key(s)`);
17157
+ } else {
17158
+ for (const change of diffSnapshots(prev, next)) this.emit(change.severity, change.message, change.details);
17159
+ }
17160
+ try {
17161
+ writeJson(this.opts.snapshotPath, next);
17162
+ } catch (err) {
17163
+ this.opts.log(`[privileged] could not save snapshot: ${err.message}`);
17164
+ }
17165
+ }
17166
+ /**
17167
+ * New sudo records since the saved journal cursor. The first run only finds
17168
+ * the current end of the journal, so history from before the daemon is not
17169
+ * replayed as if it had just happened.
17170
+ */
17171
+ readSudoLedger() {
17172
+ const cursor = readJson(this.opts.cursorPath)?.cursor;
17173
+ const args = cursor ? ["-t", "sudo", "-o", "json", "--no-pager", `--after-cursor=${cursor}`] : ["-o", "json", "--no-pager", "-n", "0", "--show-cursor"];
17174
+ const out = this.run("journalctl", args);
17175
+ if (out === null) return;
17176
+ let last = cursor ?? /^-- cursor: (\S+)/m.exec(out)?.[1];
17177
+ for (const line of cursor ? out.split("\n") : []) {
17178
+ if (!line.trim()) continue;
17179
+ let rec;
17180
+ try {
17181
+ rec = JSON.parse(line);
17182
+ } catch {
17183
+ continue;
17184
+ }
17185
+ if (typeof rec.__CURSOR === "string") last = rec.__CURSOR;
17186
+ const entry = typeof rec.MESSAGE === "string" ? parseSudoMessage(rec.MESSAGE) : null;
17187
+ if (!entry) continue;
17188
+ this.emit(
17189
+ entry.denied ? "medium" : "info",
17190
+ entry.denied ? `sudo denied: ${entry.user} tried ${entry.command} as ${entry.runas}` : `sudo: ${entry.user} ran ${entry.command} as ${entry.runas}`,
17191
+ { rule_id: entry.denied ? "priv-sudo-denied" : "priv-sudo-command", account: entry.user, runas: entry.runas, command: entry.command, tty: entry.tty, pwd: entry.pwd }
17192
+ );
17193
+ }
17194
+ if (last && last !== cursor) {
17195
+ try {
17196
+ writeJson(this.opts.cursorPath, { cursor: last });
17197
+ } catch {
17198
+ }
17199
+ }
17200
+ }
17201
+ /** An accepted SSH login from a country new for that user. */
17202
+ async checkLogin(event) {
17203
+ if (event.module !== "ssh-guard" || !event.source_ip) return;
17204
+ const user = /SSH login accepted for (\S+)/.exec(event.message)?.[1];
17205
+ if (!user || user === "unknown" || isProtected(event.source_ip, DEFAULT_PROTECTED)) return;
17206
+ let geo = null;
17207
+ try {
17208
+ geo = await (this.opts.geolocate ?? geolocateViaThreatcrush)(event.source_ip);
17209
+ } catch (err) {
17210
+ this.opts.log(`[privileged] geolocation failed for ${event.source_ip}: ${err.message}`);
17211
+ }
17212
+ const country = geo?.countryCode;
17213
+ if (!country || !/^[A-Z]{2}$/.test(country)) return;
17214
+ const history = readJson(this.opts.loginsPath) ?? {};
17215
+ const seen = history[user] ?? {};
17216
+ const at = this.now().toISOString();
17217
+ const known = Object.keys(seen);
17218
+ if (known.length > 0 && !seen[country]) {
17219
+ this.emit("high", `SSH login for ${user} from a new country: ${countryName(country)}, ${event.source_ip}; seen before from ${known.join(", ")}`, {
17220
+ rule_id: "priv-login-new-country",
17221
+ account: user,
17222
+ login_ip: event.source_ip,
17223
+ country,
17224
+ known_countries: known
17225
+ });
17226
+ }
17227
+ seen[country] = { first: seen[country]?.first ?? at, last: at };
17228
+ history[user] = seen;
17229
+ try {
17230
+ writeJson(this.opts.loginsPath, history);
17231
+ } catch {
17232
+ }
17233
+ }
17234
+ };
17235
+
16425
17236
  // src/daemon/rules/engine.ts
16426
17237
  var MAX_WINDOW_ENTRIES = 1e3;
16427
17238
  function live(window) {
@@ -16583,8 +17394,8 @@ var RuleEngine = class {
16583
17394
  };
16584
17395
 
16585
17396
  // src/daemon/rules/loader.ts
16586
- var import_node_fs20 = require("fs");
16587
- var import_node_path15 = require("path");
17397
+ var import_node_fs22 = require("fs");
17398
+ var import_node_path17 = require("path");
16588
17399
 
16589
17400
  // src/daemon/rules/default-rules.ts
16590
17401
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -16985,11 +17796,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
16985
17796
  function loadAllRules(customDir) {
16986
17797
  const rules = [...DEFAULT_RULES];
16987
17798
  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"));
17799
+ if ((0, import_node_fs22.existsSync)(dir)) {
17800
+ const files = (0, import_node_fs22.readdirSync)(dir).filter((f) => f.endsWith(".json"));
16990
17801
  for (const file of files) {
16991
17802
  try {
16992
- const raw = (0, import_node_fs20.readFileSync)((0, import_node_path15.join)(dir, file), "utf-8");
17803
+ const raw = (0, import_node_fs22.readFileSync)((0, import_node_path17.join)(dir, file), "utf-8");
16993
17804
  const parsed = JSON.parse(raw);
16994
17805
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
16995
17806
  for (const rule of customRules) {
@@ -17020,24 +17831,24 @@ function loadAllRules(customDir) {
17020
17831
  }
17021
17832
 
17022
17833
  // 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");
17834
+ var import_node_child_process8 = require("child_process");
17835
+ var import_node_fs23 = require("fs");
17836
+ var import_node_path18 = require("path");
17837
+ var import_node_net8 = require("net");
17027
17838
  function assertValidFirewallIp(ip) {
17028
- if ((0, import_node_net6.isIP)(ip) !== 4) {
17839
+ if ((0, import_node_net8.isIP)(ip) !== 4) {
17029
17840
  throw new Error(`Invalid IPv4 address: ${ip}`);
17030
17841
  }
17031
17842
  }
17032
17843
  function assertBannableIp(ip) {
17033
- if ((0, import_node_net6.isIP)(ip) === 0) {
17844
+ if ((0, import_node_net8.isIP)(ip) === 0) {
17034
17845
  throw new Error(`Invalid IP address: ${ip}`);
17035
17846
  }
17036
17847
  }
17037
17848
  function writeIfAbsent(path, contents) {
17038
- (0, import_node_fs21.mkdirSync)((0, import_node_path16.dirname)(path), { recursive: true });
17849
+ (0, import_node_fs23.mkdirSync)((0, import_node_path18.dirname)(path), { recursive: true });
17039
17850
  try {
17040
- (0, import_node_fs21.writeFileSync)(path, contents, { flag: "wx" });
17851
+ (0, import_node_fs23.writeFileSync)(path, contents, { flag: "wx" });
17041
17852
  } catch (err) {
17042
17853
  if (err.code !== "EEXIST") throw err;
17043
17854
  }
@@ -17056,11 +17867,11 @@ var Fail2banAdapter = class {
17056
17867
  enforces = true;
17057
17868
  jailReady = false;
17058
17869
  isAvailable() {
17059
- const result = (0, import_node_child_process6.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
17870
+ const result = (0, import_node_child_process8.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
17060
17871
  return result.status === 0;
17061
17872
  }
17062
17873
  client(args) {
17063
- return (0, import_node_child_process6.execFileSync)("fail2ban-client", args, {
17874
+ return (0, import_node_child_process8.execFileSync)("fail2ban-client", args, {
17064
17875
  encoding: "utf-8",
17065
17876
  stdio: ["ignore", "pipe", "pipe"]
17066
17877
  });
@@ -17136,7 +17947,7 @@ var Fail2banAdapter = class {
17136
17947
  const status = this.client(["status", this.jail]);
17137
17948
  const line = status.split("\n").find((l) => /Banned IP list:/i.test(l));
17138
17949
  if (!line) return [];
17139
- return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net6.isIP)(s) !== 0);
17950
+ return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net8.isIP)(s) !== 0);
17140
17951
  } catch {
17141
17952
  return [];
17142
17953
  }
@@ -17146,45 +17957,45 @@ var Fail2banAdapter = class {
17146
17957
  function parseBannedList(output) {
17147
17958
  const found = [];
17148
17959
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
17149
- if ((0, import_node_net6.isIP)(match[1]) !== 0) found.push(match[1]);
17960
+ if ((0, import_node_net8.isIP)(match[1]) !== 0) found.push(match[1]);
17150
17961
  }
17151
17962
  if (found.length > 0) return found;
17152
- return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net6.isIP)(s) !== 0);
17963
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net8.isIP)(s) !== 0);
17153
17964
  }
17154
17965
  var NftablesAdapter = class {
17155
17966
  name = "nftables";
17156
17967
  table = "threatcrush";
17157
17968
  set = "blocklist";
17158
17969
  isAvailable() {
17159
- const result = (0, import_node_child_process6.spawnSync)("nft", ["--version"], { stdio: "pipe" });
17970
+ const result = (0, import_node_child_process8.spawnSync)("nft", ["--version"], { stdio: "pipe" });
17160
17971
  return result.status === 0;
17161
17972
  }
17162
17973
  ensureSetup() {
17163
17974
  try {
17164
- (0, import_node_child_process6.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
17975
+ (0, import_node_child_process8.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
17165
17976
  } 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`);
17977
+ (0, import_node_child_process8.execSync)(`nft add table inet ${this.table}`);
17978
+ (0, import_node_child_process8.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
17979
+ (0, import_node_child_process8.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
17980
+ (0, import_node_child_process8.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
17170
17981
  }
17171
17982
  }
17172
17983
  async block(ip) {
17173
17984
  assertValidFirewallIp(ip);
17174
17985
  this.ensureSetup();
17175
- (0, import_node_child_process6.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
17986
+ (0, import_node_child_process8.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
17176
17987
  }
17177
17988
  async unblock(ip) {
17178
17989
  assertValidFirewallIp(ip);
17179
17990
  try {
17180
- (0, import_node_child_process6.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
17991
+ (0, import_node_child_process8.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
17181
17992
  } catch {
17182
17993
  }
17183
17994
  }
17184
17995
  async isBlocked(ip) {
17185
17996
  assertValidFirewallIp(ip);
17186
17997
  try {
17187
- const output = (0, import_node_child_process6.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
17998
+ const output = (0, import_node_child_process8.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
17188
17999
  return output.includes(ip);
17189
18000
  } catch {
17190
18001
  return false;
@@ -17192,7 +18003,7 @@ var NftablesAdapter = class {
17192
18003
  }
17193
18004
  async listBlocked() {
17194
18005
  try {
17195
- const output = (0, import_node_child_process6.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
18006
+ const output = (0, import_node_child_process8.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
17196
18007
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
17197
18008
  if (!match) return [];
17198
18009
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -17205,34 +18016,34 @@ var IptablesAdapter = class {
17205
18016
  name = "iptables";
17206
18017
  chain = "THREATCRUSH";
17207
18018
  isAvailable() {
17208
- const result = (0, import_node_child_process6.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
18019
+ const result = (0, import_node_child_process8.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
17209
18020
  return result.status === 0;
17210
18021
  }
17211
18022
  ensureChain() {
17212
18023
  try {
17213
- (0, import_node_child_process6.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
18024
+ (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
17214
18025
  } 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}`);
18026
+ (0, import_node_child_process8.execSync)(`iptables -N ${this.chain}`);
18027
+ (0, import_node_child_process8.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
17217
18028
  }
17218
18029
  }
17219
18030
  async block(ip) {
17220
18031
  assertValidFirewallIp(ip);
17221
18032
  this.ensureChain();
17222
18033
  if (await this.isBlocked(ip)) return;
17223
- (0, import_node_child_process6.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
18034
+ (0, import_node_child_process8.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
17224
18035
  }
17225
18036
  async unblock(ip) {
17226
18037
  assertValidFirewallIp(ip);
17227
18038
  try {
17228
- (0, import_node_child_process6.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
18039
+ (0, import_node_child_process8.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
17229
18040
  } catch {
17230
18041
  }
17231
18042
  }
17232
18043
  async isBlocked(ip) {
17233
18044
  assertValidFirewallIp(ip);
17234
18045
  try {
17235
- const output = (0, import_node_child_process6.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
18046
+ const output = (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
17236
18047
  return output.includes(ip);
17237
18048
  } catch {
17238
18049
  return false;
@@ -17240,7 +18051,7 @@ var IptablesAdapter = class {
17240
18051
  }
17241
18052
  async listBlocked() {
17242
18053
  try {
17243
- const output = (0, import_node_child_process6.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
18054
+ const output = (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
17244
18055
  const ips = [];
17245
18056
  for (const line of output.split("\n")) {
17246
18057
  const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -17296,8 +18107,8 @@ function detectFirewallAdapter(backend = "auto") {
17296
18107
  }
17297
18108
 
17298
18109
  // src/daemon/firewall/remediation.ts
17299
- var import_node_fs22 = require("fs");
17300
- var import_node_net7 = require("net");
18110
+ var import_node_fs24 = require("fs");
18111
+ var import_node_net9 = require("net");
17301
18112
 
17302
18113
  // src/daemon/firewall/crawlers.ts
17303
18114
  var import_node_dns = require("dns");
@@ -17432,7 +18243,7 @@ var RemediationManager = class {
17432
18243
  if (remediation?.action !== "block") return;
17433
18244
  }
17434
18245
  const ip = event.source_ip;
17435
- if (!ip || (0, import_node_net7.isIP)(ip) === 0) return;
18246
+ if (!ip || (0, import_node_net9.isIP)(ip) === 0) return;
17436
18247
  if (this.isAllowlisted(ip)) return;
17437
18248
  if (this.blocklist.some((b) => b.ip === ip)) return;
17438
18249
  if (this.config.spare_verified_crawlers) {
@@ -17451,7 +18262,7 @@ var RemediationManager = class {
17451
18262
  * 4th offence and so on, clamped to `max_ban_seconds`.
17452
18263
  */
17453
18264
  async ban(ip, reason, opts = {}) {
17454
- if ((0, import_node_net7.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
18265
+ if ((0, import_node_net9.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
17455
18266
  if (this.isAllowlisted(ip)) {
17456
18267
  return { ok: false, error: `${ip} is protected and can never be blocked` };
17457
18268
  }
@@ -17708,7 +18519,7 @@ var RemediationManager = class {
17708
18519
  }
17709
18520
  logLine(line) {
17710
18521
  try {
17711
- (0, import_node_fs22.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18522
+ (0, import_node_fs24.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
17712
18523
  `);
17713
18524
  } catch {
17714
18525
  }
@@ -17742,13 +18553,13 @@ function remediationSettings(section) {
17742
18553
  }
17743
18554
 
17744
18555
  // src/daemon/watchdog-service.ts
17745
- var import_node_fs24 = require("fs");
17746
- var import_node_path18 = require("path");
18556
+ var import_node_fs26 = require("fs");
18557
+ var import_node_path20 = require("path");
17747
18558
 
17748
18559
  // src/core/watchdog.ts
17749
- var import_node_fs23 = require("fs");
17750
- var import_node_crypto5 = require("crypto");
17751
- var import_node_path17 = require("path");
18560
+ var import_node_fs25 = require("fs");
18561
+ var import_node_crypto6 = require("crypto");
18562
+ var import_node_path19 = require("path");
17752
18563
  var WATCHDOG_DIRNAME = "watchdog";
17753
18564
  var LOG_FILE = "attacks.jsonl";
17754
18565
  var ROTATED_FILE = "attacks.1.jsonl";
@@ -17788,7 +18599,7 @@ function signatureOf(r) {
17788
18599
  return ["msg", r.module, shape].join("|");
17789
18600
  }
17790
18601
  function findingId(signature) {
17791
- return (0, import_node_crypto5.createHash)("sha1").update(signature).digest("hex").slice(0, 10);
18602
+ return (0, import_node_crypto6.createHash)("sha1").update(signature).digest("hex").slice(0, 10);
17792
18603
  }
17793
18604
  function toRecord(event) {
17794
18605
  const d = event.details ?? {};
@@ -17837,12 +18648,12 @@ var WatchdogLog = class {
17837
18648
  stats = { logged: 0, answered: 0, errored: 0 };
17838
18649
  constructor(dir, options = {}) {
17839
18650
  this.dir = dir;
17840
- this.file = (0, import_node_path17.join)(dir, LOG_FILE);
18651
+ this.file = (0, import_node_path19.join)(dir, LOG_FILE);
17841
18652
  this.shareGid = options.shareGid;
17842
- (0, import_node_fs23.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
18653
+ (0, import_node_fs25.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
17843
18654
  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);
18655
+ (0, import_node_fs25.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
18656
+ (0, import_node_fs25.chmodSync)(dir, 1528);
17846
18657
  }
17847
18658
  for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
17848
18659
  }
@@ -17871,16 +18682,16 @@ var WatchdogLog = class {
17871
18682
  const chunk = this.buffer.join("\n") + "\n";
17872
18683
  this.buffer = [];
17873
18684
  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));
18685
+ if ((0, import_node_fs25.statSync)(this.file).size > ROTATE_BYTES) {
18686
+ (0, import_node_fs25.renameSync)(this.file, (0, import_node_path19.join)(this.dir, ROTATED_FILE));
17876
18687
  }
17877
18688
  } catch {
17878
18689
  }
17879
- (0, import_node_fs23.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
18690
+ (0, import_node_fs25.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
17880
18691
  if (this.shareGid !== void 0) {
17881
18692
  try {
17882
- (0, import_node_fs23.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
17883
- (0, import_node_fs23.chmodSync)(this.file, 432);
18693
+ (0, import_node_fs25.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
18694
+ (0, import_node_fs25.chmodSync)(this.file, 432);
17884
18695
  } catch {
17885
18696
  }
17886
18697
  }
@@ -17901,21 +18712,21 @@ function parseLines(text) {
17901
18712
  function readTail(file, bytes) {
17902
18713
  let fd;
17903
18714
  try {
17904
- fd = (0, import_node_fs23.openSync)(file, "r");
18715
+ fd = (0, import_node_fs25.openSync)(file, "r");
17905
18716
  } catch (err) {
17906
18717
  if (err.code === "ENOENT") return [];
17907
18718
  throw err;
17908
18719
  }
17909
18720
  try {
17910
- const size = (0, import_node_fs23.fstatSync)(fd).size;
18721
+ const size = (0, import_node_fs25.fstatSync)(fd).size;
17911
18722
  const start = Math.max(0, size - bytes);
17912
18723
  const buf = Buffer.alloc(size - start);
17913
- (0, import_node_fs23.readSync)(fd, buf, 0, buf.length, start);
18724
+ (0, import_node_fs25.readSync)(fd, buf, 0, buf.length, start);
17914
18725
  let text = buf.toString("utf8");
17915
18726
  if (start > 0) text = text.slice(text.indexOf("\n") + 1);
17916
18727
  return parseLines(text);
17917
18728
  } finally {
17918
- (0, import_node_fs23.closeSync)(fd);
18729
+ (0, import_node_fs25.closeSync)(fd);
17919
18730
  }
17920
18731
  }
17921
18732
 
@@ -17924,13 +18735,13 @@ function defaultShareGid() {
17924
18735
  const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
17925
18736
  if (!isRoot2) return void 0;
17926
18737
  try {
17927
- return (0, import_node_fs24.statSync)("/var/log/auth.log").gid;
18738
+ return (0, import_node_fs26.statSync)("/var/log/auth.log").gid;
17928
18739
  } catch {
17929
18740
  return void 0;
17930
18741
  }
17931
18742
  }
17932
18743
  function startWatchdog(opts) {
17933
- const dir = opts.config?.dir ?? (0, import_node_path18.join)(opts.stateDir, WATCHDOG_DIRNAME);
18744
+ const dir = opts.config?.dir ?? (0, import_node_path20.join)(opts.stateDir, WATCHDOG_DIRNAME);
17934
18745
  const base = { dir, logged: 0, answered: 0, errored: 0 };
17935
18746
  if (opts.config?.enabled === false) {
17936
18747
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -18021,7 +18832,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
18021
18832
  }
18022
18833
 
18023
18834
  // src/core/node-runtime.ts
18024
- var import_node_child_process7 = require("child_process");
18835
+ var import_node_child_process9 = require("child_process");
18025
18836
  var MIN_DAEMON_NODE_MAJOR = 22;
18026
18837
  function nodeMajor(version) {
18027
18838
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -18037,16 +18848,16 @@ function daemonNodeProblem(version) {
18037
18848
  // src/daemon/index.ts
18038
18849
  function readVersion2() {
18039
18850
  try {
18040
- const pkg = JSON.parse((0, import_node_fs25.readFileSync)((0, import_node_path19.join)(__dirname, "..", "package.json"), "utf-8"));
18851
+ const pkg = JSON.parse((0, import_node_fs27.readFileSync)((0, import_node_path21.join)(__dirname, "..", "package.json"), "utf-8"));
18041
18852
  return pkg.version || "0.0.0";
18042
18853
  } catch {
18043
18854
  return "0.0.0";
18044
18855
  }
18045
18856
  }
18046
18857
  async function runHardeningChecks() {
18047
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process8.execFile)(
18858
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process10.execFile)(
18048
18859
  process.execPath,
18049
- [(0, import_node_path19.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
18860
+ [(0, import_node_path21.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
18050
18861
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
18051
18862
  );
18052
18863
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -18058,9 +18869,9 @@ async function runHardeningChecks() {
18058
18869
  return patches ? [...findings, patches] : findings;
18059
18870
  }
18060
18871
  async function runPatchCheck() {
18061
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process8.execFile)(
18872
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process10.execFile)(
18062
18873
  process.execPath,
18063
- [(0, import_node_path19.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
18874
+ [(0, import_node_path21.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
18064
18875
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
18065
18876
  );
18066
18877
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -18068,7 +18879,7 @@ async function runPatchCheck() {
18068
18879
  }
18069
18880
  function logLine(line) {
18070
18881
  try {
18071
- (0, import_node_fs25.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18882
+ (0, import_node_fs27.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18072
18883
  `);
18073
18884
  } catch {
18074
18885
  }
@@ -18093,9 +18904,9 @@ async function runDaemon() {
18093
18904
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
18094
18905
  const restartDaemon = () => {
18095
18906
  if (PATHS.mode === "system") {
18096
- (0, import_node_child_process8.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
18907
+ (0, import_node_child_process10.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
18097
18908
  } else {
18098
- (0, import_node_child_process8.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
18909
+ (0, import_node_child_process10.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
18099
18910
  setTimeout(() => process.exit(0), 500).unref();
18100
18911
  }
18101
18912
  };
@@ -18110,7 +18921,7 @@ async function runDaemon() {
18110
18921
  } catch (err) {
18111
18922
  logLine(`[daemon] state db unavailable: ${err.message}`);
18112
18923
  }
18113
- const config = loadConfig((0, import_node_fs25.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
18924
+ const config = loadConfig((0, import_node_fs27.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
18114
18925
  configureAttackDetection(config.detection);
18115
18926
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
18116
18927
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -18170,6 +18981,24 @@ async function runDaemon() {
18170
18981
  if (firewallAdapter.enforces === false) {
18171
18982
  logLine("[daemon] no manageable firewall found (need fail2ban, nftables or iptables) \u2014 bans are simulated");
18172
18983
  }
18984
+ const feedSettings = threatFeedSettings(config.threat_feeds);
18985
+ const threatFeeds = new ThreatFeeds({
18986
+ settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
18987
+ enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
18988
+ cachePath: (0, import_node_path21.join)(PATHS.stateDir, "threat-feeds.json"),
18989
+ bus,
18990
+ log: logLine
18991
+ });
18992
+ threatFeeds.start();
18993
+ const privilegeWatch = new PrivilegeWatch({
18994
+ settings: privilegeSettings(config.privileged),
18995
+ bus,
18996
+ snapshotPath: (0, import_node_path21.join)(PATHS.stateDir, "privileges.json"),
18997
+ loginsPath: (0, import_node_path21.join)(PATHS.stateDir, "login-countries.json"),
18998
+ cursorPath: (0, import_node_path21.join)(PATHS.stateDir, "sudo-cursor.json"),
18999
+ log: logLine
19000
+ });
19001
+ privilegeWatch.start();
18173
19002
  new AlertDispatcher(bus, config);
18174
19003
  const runsWorker = new RunsWorker(bus);
18175
19004
  try {
@@ -18189,7 +19018,7 @@ async function runDaemon() {
18189
19018
  version,
18190
19019
  hostname: (0, import_node_os5.hostname)(),
18191
19020
  minSeverity,
18192
- spoolPath: (0, import_node_path19.join)(PATHS.stateDir, "cloud-spool.jsonl"),
19021
+ spoolPath: (0, import_node_path21.join)(PATHS.stateDir, "cloud-spool.jsonl"),
18193
19022
  log: logLine,
18194
19023
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
18195
19024
  runHardening: runHardeningChecks
@@ -18206,8 +19035,8 @@ async function runDaemon() {
18206
19035
  const autoUpdate = new AutoUpdate({
18207
19036
  version,
18208
19037
  settings: updateSettings(config.update),
18209
- pkgRoot: (0, import_node_path19.join)(__dirname, ".."),
18210
- statePath: (0, import_node_path19.join)(PATHS.stateDir, "auto-update.json"),
19038
+ pkgRoot: (0, import_node_path21.join)(__dirname, ".."),
19039
+ statePath: (0, import_node_path21.join)(PATHS.stateDir, "auto-update.json"),
18211
19040
  bus,
18212
19041
  log: logLine,
18213
19042
  restartDaemon
@@ -18250,6 +19079,14 @@ async function runDaemon() {
18250
19079
  autoUpdate.stop();
18251
19080
  } catch {
18252
19081
  }
19082
+ try {
19083
+ threatFeeds.stop();
19084
+ } catch {
19085
+ }
19086
+ try {
19087
+ privilegeWatch.stop();
19088
+ } catch {
19089
+ }
18253
19090
  try {
18254
19091
  await ipc.stop();
18255
19092
  } catch {