@profullstack/threatcrush 0.15.3 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/daemon.js CHANGED
@@ -8339,15 +8339,15 @@ var require_parser2 = __commonJS({
8339
8339
  var node_process = require("process");
8340
8340
  var cst = require_cst();
8341
8341
  var lexer = require_lexer();
8342
- function includesToken(list, type) {
8343
- for (let i = 0; i < list.length; ++i)
8344
- if (list[i].type === type)
8342
+ function includesToken(list2, type) {
8343
+ for (let i = 0; i < list2.length; ++i)
8344
+ if (list2[i].type === type)
8345
8345
  return true;
8346
8346
  return false;
8347
8347
  }
8348
- function findNonEmptyIndex(list) {
8349
- for (let i = 0; i < list.length; ++i) {
8350
- switch (list[i].type) {
8348
+ function findNonEmptyIndex(list2) {
8349
+ for (let i = 0; i < list2.length; ++i) {
8350
+ switch (list2[i].type) {
8351
8351
  case "space":
8352
8352
  case "comment":
8353
8353
  case "newline":
@@ -9356,10 +9356,10 @@ var require_dist = __commonJS({
9356
9356
  });
9357
9357
 
9358
9358
  // src/daemon/index.ts
9359
- var import_node_fs42 = require("fs");
9360
- var import_node_child_process17 = require("child_process");
9361
- var import_node_os6 = require("os");
9362
- var import_node_path32 = require("path");
9359
+ var import_node_fs44 = require("fs");
9360
+ var import_node_child_process18 = require("child_process");
9361
+ var import_node_os8 = require("os");
9362
+ var import_node_path33 = require("path");
9363
9363
  var import_node_util = require("util");
9364
9364
 
9365
9365
  // src/daemon/paths.ts
@@ -16794,9 +16794,9 @@ var CrsEngine = class {
16794
16794
  continue;
16795
16795
  }
16796
16796
  for (const target of compiled.rule.targets) {
16797
- const list = this.byTarget.get(target) ?? [];
16798
- list.push(compiled);
16799
- this.byTarget.set(target, list);
16797
+ const list2 = this.byTarget.get(target) ?? [];
16798
+ list2.push(compiled);
16799
+ this.byTarget.set(target, list2);
16800
16800
  }
16801
16801
  }
16802
16802
  }
@@ -17913,8 +17913,8 @@ function ipMatches(ip, entry) {
17913
17913
  const mask = 255 << 8 - remainder & 255;
17914
17914
  return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
17915
17915
  }
17916
- function isProtected(ip, list) {
17917
- return list.some((entry) => ipMatches(ip, entry));
17916
+ function isProtected(ip, list2) {
17917
+ return list2.some((entry) => ipMatches(ip, entry));
17918
17918
  }
17919
17919
  function currentSshClient(env2 = process.env) {
17920
17920
  const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
@@ -18733,6 +18733,7 @@ function parseConfigText(raw) {
18733
18733
  docker_logs: parsed.docker_logs,
18734
18734
  postgres_shell: parsed.postgres_shell,
18735
18735
  login_watch: parsed.login_watch,
18736
+ ssh_context: parsed.ssh_context,
18736
18737
  storage: parsed.storage,
18737
18738
  // TOML's `[abuse-reporter]` parses to a hyphenated key; expose it under
18738
18739
  // the JS-friendly name the rest of the daemon reads.
@@ -23013,7 +23014,7 @@ function parseAuthorizedKeyLines(text) {
23013
23014
  text.split("\n").forEach((raw, idx) => {
23014
23015
  const line = raw.replace(/\r$/, "").trim();
23015
23016
  if (!line || line.startsWith("#")) return;
23016
- let optionText = "";
23017
+ let optionText2 = "";
23017
23018
  let rest = line;
23018
23019
  if (!KEY_TYPE.test(line.split(/\s+/, 1)[0] ?? "")) {
23019
23020
  let inQuote = false;
@@ -23031,13 +23032,13 @@ function parseAuthorizedKeyLines(text) {
23031
23032
  }
23032
23033
  }
23033
23034
  if (cut === -1) return;
23034
- optionText = line.slice(0, cut);
23035
+ optionText2 = line.slice(0, cut);
23035
23036
  rest = line.slice(cut).trimStart();
23036
23037
  }
23037
23038
  const parts = rest.split(/\s+/);
23038
23039
  if (!KEY_TYPE.test(parts[0] ?? "") || !parts[1]) return;
23039
23040
  const options = /* @__PURE__ */ new Map();
23040
- for (const m of optionText.matchAll(/([A-Za-z-]+)(?:="((?:[^"\\]|\\.)*)")?/g)) {
23041
+ for (const m of optionText2.matchAll(/([A-Za-z-]+)(?:="((?:[^"\\]|\\.)*)")?/g)) {
23041
23042
  options.set(m[1].toLowerCase(), m[2] ?? null);
23042
23043
  }
23043
23044
  out.push({ line: idx + 1, type: parts[0], comment: parts.slice(2).join(" "), options });
@@ -25705,6 +25706,10 @@ var CloudSpool = class {
25705
25706
 
25706
25707
  // src/daemon/workers/cloud-sync.ts
25707
25708
  var MAX_BATCH_BYTES = 900 * 1024;
25709
+ function uploadSeverity(event) {
25710
+ const rule = event.details?.rule_severity;
25711
+ return typeof rule === "string" && rule in SEVERITY_RANK5 ? rule : event.severity;
25712
+ }
25708
25713
  var CloudSync = class {
25709
25714
  constructor(opts) {
25710
25715
  this.opts = opts;
@@ -25789,7 +25794,7 @@ var CloudSync = class {
25789
25794
  let out = null;
25790
25795
  if (event.module === "firewall-rules") {
25791
25796
  out = remediationEvent(link.serverId, event);
25792
- } else if ((event.module === "rule-engine" || !this.opts.ruleModules.has(event.module)) && event.details?.heartbeat !== true && SEVERITY_RANK5[event.severity] >= SEVERITY_RANK5[this.opts.minSeverity]) {
25797
+ } else if ((event.module === "rule-engine" || !this.opts.ruleModules.has(event.module)) && event.details?.heartbeat !== true && SEVERITY_RANK5[uploadSeverity(event)] >= SEVERITY_RANK5[this.opts.minSeverity]) {
25793
25798
  out = detectionEvent(link.serverId, event);
25794
25799
  }
25795
25800
  if (!out) return;
@@ -26319,11 +26324,11 @@ var import_node_net9 = require("net");
26319
26324
  var import_node_net8 = require("net");
26320
26325
  function isAddressOrCidr(value) {
26321
26326
  const [network, prefix, extra] = value.split("/");
26322
- const family = (0, import_node_net8.isIP)(network);
26323
- if (family === 0 || extra !== void 0) return false;
26327
+ const family2 = (0, import_node_net8.isIP)(network);
26328
+ if (family2 === 0 || extra !== void 0) return false;
26324
26329
  if (prefix === void 0) return true;
26325
26330
  if (!/^\d{1,3}$/.test(prefix)) return false;
26326
- return Number(prefix) <= (family === 4 ? 32 : 128);
26331
+ return Number(prefix) <= (family2 === 4 ? 32 : 128);
26327
26332
  }
26328
26333
  var CLOUD_MIN_PREFIX = { 4: 8, 6: 16 };
26329
26334
  function isCloudAllowEntry(value) {
@@ -30330,9 +30335,9 @@ var PostgresShellWatch = class {
30330
30335
  if (!root) return [];
30331
30336
  const children = /* @__PURE__ */ new Map();
30332
30337
  for (const e of entries2.values()) {
30333
- const list = children.get(e.ppid) ?? [];
30334
- list.push(e.pid);
30335
- children.set(e.ppid, list);
30338
+ const list2 = children.get(e.ppid) ?? [];
30339
+ list2.push(e.pid);
30340
+ children.set(e.ppid, list2);
30336
30341
  }
30337
30342
  const order = [];
30338
30343
  const visit = (pid, depth) => {
@@ -30581,9 +30586,9 @@ var DockerLogsWatch = class {
30581
30586
  if (this.stopped) return;
30582
30587
  const now = Date.now();
30583
30588
  const previous = this.lastPoll;
30584
- let list;
30589
+ let list2;
30585
30590
  try {
30586
- list = await this.deps.getJson("/containers/json");
30591
+ list2 = await this.deps.getJson("/containers/json");
30587
30592
  this.warned = false;
30588
30593
  } catch (err) {
30589
30594
  if (!this.warned) this.opts.log(`[docker-logs] cannot list containers: ${err.message}`);
@@ -30592,7 +30597,7 @@ var DockerLogsWatch = class {
30592
30597
  }
30593
30598
  this.lastPoll = now;
30594
30599
  const running = /* @__PURE__ */ new Set();
30595
- for (const c of Array.isArray(list) ? list : []) {
30600
+ for (const c of Array.isArray(list2) ? list2 : []) {
30596
30601
  if (!c?.Id || !this.matches(c)) continue;
30597
30602
  running.add(c.Id);
30598
30603
  if (this.follows.has(c.Id)) continue;
@@ -31320,6 +31325,8 @@ function evidenceOf(event) {
31320
31325
  const v = details[k];
31321
31326
  if (typeof v === "string" || typeof v === "number") out[k] = String(v).slice(0, EVIDENCE_FIELD_CHARS);
31322
31327
  }
31328
+ const ctx = details.ssh_context;
31329
+ if (ctx && typeof ctx === "object" && !Array.isArray(ctx) && ctx.v === 1) out.ssh_context = ctx;
31323
31330
  return out;
31324
31331
  }
31325
31332
  var RuleEngine = class {
@@ -31471,10 +31478,760 @@ var RuleEngine = class {
31471
31478
  }
31472
31479
  };
31473
31480
 
31474
- // src/daemon/rules/loader.ts
31475
- var import_node_fs37 = require("fs");
31481
+ // src/daemon/ssh-context/index.ts
31482
+ var import_node_os7 = require("os");
31476
31483
  var import_node_path28 = require("path");
31477
31484
 
31485
+ // ../../packages/event-detail/src/verdict.ts
31486
+ var RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
31487
+ function maxSeverity(a, b) {
31488
+ return RANK[a] >= RANK[b] ? a : b;
31489
+ }
31490
+ function severityRank2(s) {
31491
+ return RANK[s ?? "info"] ?? 0;
31492
+ }
31493
+ function describeFailures(f, ip) {
31494
+ if (!f) return null;
31495
+ const mins = Math.max(1, Math.round(f.window_s / 60));
31496
+ if (f.total === 0) {
31497
+ return `No failed SSH attempts in the ${mins} min before this login (the rule fires on every accepted login).`;
31498
+ }
31499
+ const top = (f.ips ?? []).filter((x) => x.ip !== ip).slice(0, 3).map((x) => `${x.ip} x${x.count}`).join(", ");
31500
+ const users = (f.users ?? []).slice(0, 4).map((u) => u.user).join(", ");
31501
+ const span = f.first && f.last ? ` between ${hhmmss(f.first)} and ${hhmmss(f.last)} UTC` : "";
31502
+ if (f.same_ip > 0 && f.other_ips === 0) {
31503
+ return `${f.same_ip} failed attempt${f.same_ip === 1 ? "" : "s"} from this same address${span}${users ? ` (users: ${users})` : ""}, then this login succeeded: a guessed or brute-forced credential is possible.`;
31504
+ }
31505
+ if (f.same_ip === 0) {
31506
+ return `${f.total} failed attempt${f.total === 1 ? "" : "s"} in the ${mins} min before, all from OTHER addresses${top ? ` (${top})` : ""}${users ? `, users: ${users}` : ""}. None came from this address, so this is not a brute force that succeeded.`;
31507
+ }
31508
+ return `${f.total} failed attempt${f.total === 1 ? "" : "s"} in the ${mins} min before: ${f.same_ip} from this address and ${f.other_ips} from others${top ? ` (${top})` : ""}${users ? `, users: ${users}` : ""}.`;
31509
+ }
31510
+ function hhmmss(iso) {
31511
+ const d = new Date(iso);
31512
+ return Number.isNaN(d.getTime()) ? iso : d.toISOString().slice(11, 19);
31513
+ }
31514
+ function computeVerdict(ctx) {
31515
+ const reasons = [];
31516
+ const key = ctx.key;
31517
+ const src = ctx.source;
31518
+ const ci = ctx.session?.ci_deploy;
31519
+ const forced = !!key?.command;
31520
+ const restricted = forced || !!key?.from;
31521
+ const publicSrc = !src || src.kind === "public" || src.kind === "github-actions";
31522
+ const ghActions = src?.kind === "github-actions";
31523
+ let severity = "info";
31524
+ let level = "review";
31525
+ const raise = (s, why) => {
31526
+ severity = maxSeverity(severity, s);
31527
+ reasons.push(why);
31528
+ };
31529
+ if (key?.in_root_and_user) raise("critical", "the same key authorizes root and another account");
31530
+ if (key?.suspicious_comment) raise(restricted ? "high" : "critical", `key comment "${key.comment}" looks like a dated temporary CI/diagnostic key`);
31531
+ if (ctx.failures && ctx.failures.same_ip > 0) raise("critical", `${ctx.failures.same_ip} failed attempt(s) from this same address before it succeeded`);
31532
+ if (ci && /^deny/i.test(ci.decision)) raise("high", `ci-deploy DENIED${ci.repo ? ` ${ci.repo}` : ""}`);
31533
+ if (publicSrc && ctx.auth_method === "password") raise("critical", "password login from a public address");
31534
+ if (publicSrc && !ghActions && key?.found && !restricted && !key.restrict) raise("critical", "unrestricted key (no command=, from= or restrict) from a non-CI address");
31535
+ if (publicSrc && key && !key.found && ctx.auth_method === "publickey") raise("high", "key not found in any readable authorized_keys (another account, or AuthorizedKeysCommand)");
31536
+ if (forced && publicSrc && !ghActions) raise("medium", "forced-command key used from an address outside GitHub Actions");
31537
+ const red = severityRank2(severity) >= RANK.high;
31538
+ if (key?.expected && !red) {
31539
+ level = "expected";
31540
+ severity = "info";
31541
+ reasons.unshift(`key marked as expected CI${key.comment ? ` (${key.comment})` : ""}`);
31542
+ } else if (ghActions && forced && !red) {
31543
+ level = "likely-ci";
31544
+ severity = "low";
31545
+ reasons.unshift("GitHub Actions IP", "forced-command deploy key");
31546
+ if (ci && /^allow/i.test(ci.decision)) reasons.push(`ci-deploy ALLOW ${ci.action || ci.repo || ""}`.trim());
31547
+ } else if (src && ["loopback", "self", "tailscale", "private"].includes(src.kind) && !red) {
31548
+ level = "internal";
31549
+ severity = maxSeverity("low", severity);
31550
+ reasons.unshift(src.kind === "tailscale" ? "Tailscale address" : src.kind === "self" ? "one of this host's own addresses" : src.kind === "loopback" ? "loopback" : "private address");
31551
+ } else if (red) {
31552
+ level = "suspicious";
31553
+ } else {
31554
+ severity = maxSeverity("high", severity);
31555
+ if (!reasons.length) reasons.push(ghActions ? "GitHub Actions address but not a forced-command key" : "login from a public address");
31556
+ }
31557
+ return { level, severity, summary: verdictSummary(level, reasons, ctx), reasons };
31558
+ }
31559
+ function verdictSummary(level, reasons, ctx) {
31560
+ const head = {
31561
+ expected: "Expected CI key",
31562
+ "likely-ci": "Likely CI deploy",
31563
+ internal: "Internal login",
31564
+ review: "Review",
31565
+ suspicious: "Suspicious login"
31566
+ };
31567
+ if (level === "review" && reasons.length === 1 && /public address$/.test(reasons[0])) {
31568
+ const restricted = ctx.key?.command || ctx.key?.from;
31569
+ return `${head.review}: ${restricted ? "restricted" : "unrestricted"} ${ctx.auth_method ?? "login"} from ${ctx.source?.ip ?? "a public address"}`;
31570
+ }
31571
+ return `${head[level]}: ${reasons.join(", ")}`;
31572
+ }
31573
+
31574
+ // src/daemon/ssh-context/auth-history.ts
31575
+ var MAX_ENTRIES = 2e4;
31576
+ var KEEP_MS = 60 * 60 * 1e3;
31577
+ var SAME_ATTEMPT_MS = 1e4;
31578
+ function classifySshdMessage(message) {
31579
+ let m = /^Failed (?:password|publickey|none|keyboard-interactive\/pam|keyboard-interactive|hostbased) for (?:invalid user )?(\S+) from \S+ port (\d+)/.exec(message);
31580
+ if (m) return { kind: "failed", user: m[1], port: Number(m[2]) };
31581
+ m = /^Invalid user (\S*) from \S+(?: port (\d+))?/.exec(message);
31582
+ if (m) return { kind: "invalid", user: m[1] || "(empty)", port: m[2] ? Number(m[2]) : void 0 };
31583
+ m = /^(?:Connection closed by|Disconnected from) (?:authenticating|invalid) user (\S+) \S+ port (\d+)/.exec(message);
31584
+ if (m) return { kind: "preauth-close", user: m[1], port: Number(m[2]) };
31585
+ m = /^Disconnected from user (\S+) \S+ port (\d+)/.exec(message);
31586
+ if (m) return { kind: "close", user: m[1], port: Number(m[2]) };
31587
+ m = /^Received disconnect from \S+ port (\d+):\d+: .*disconnected by user/i.exec(message);
31588
+ if (m && !/\[preauth\]/.test(message)) return { kind: "close", port: Number(m[1]) };
31589
+ return null;
31590
+ }
31591
+ var SshAuthHistory = class {
31592
+ constructor(now = Date.now) {
31593
+ this.now = now;
31594
+ }
31595
+ now;
31596
+ failures = [];
31597
+ closes = [];
31598
+ seen = /* @__PURE__ */ new Map();
31599
+ record(line) {
31600
+ const at = line.timestamp instanceof Date ? line.timestamp.getTime() : Date.now();
31601
+ if (Number.isNaN(at)) return;
31602
+ const key = `${at}|${line.message}`;
31603
+ if (this.seen.has(key)) return;
31604
+ this.seen.set(key, at);
31605
+ const c = classifySshdMessage(line.message);
31606
+ if (!c) return;
31607
+ if (c.kind === "close") {
31608
+ if (c.port) this.closes.push({ at, ip: line.ip, port: c.port, user: c.user });
31609
+ } else {
31610
+ const user = c.user ?? "unknown";
31611
+ const same = [];
31612
+ if (c.port !== void 0) {
31613
+ for (let i = this.failures.length - 1; i >= 0; i--) {
31614
+ const f = this.failures[i];
31615
+ if (f.at < at - SAME_ATTEMPT_MS) break;
31616
+ if (f.ip === line.ip && f.port === c.port) same.push(f);
31617
+ }
31618
+ }
31619
+ if (c.kind === "failed") {
31620
+ const placeholder = same.find((f) => f.kind !== "failed");
31621
+ if (placeholder) {
31622
+ placeholder.kind = "failed";
31623
+ placeholder.user = user;
31624
+ } else this.failures.push({ at, ip: line.ip, user, kind: c.kind, port: c.port });
31625
+ } else if (same.length === 0) {
31626
+ this.failures.push({ at, ip: line.ip, user, kind: c.kind, port: c.port });
31627
+ }
31628
+ }
31629
+ this.prune();
31630
+ }
31631
+ prune() {
31632
+ const cutoff = this.now() - KEEP_MS;
31633
+ if (this.failures.length > MAX_ENTRIES) this.failures.splice(0, this.failures.length - MAX_ENTRIES);
31634
+ if (this.closes.length > MAX_ENTRIES) this.closes.splice(0, this.closes.length - MAX_ENTRIES);
31635
+ while (this.failures.length && this.failures[0].at < cutoff) this.failures.shift();
31636
+ while (this.closes.length && this.closes[0].at < cutoff) this.closes.shift();
31637
+ if (this.seen.size > MAX_ENTRIES) {
31638
+ let drop = this.seen.size - MAX_ENTRIES / 2;
31639
+ for (const k of this.seen.keys()) {
31640
+ if (drop-- <= 0) break;
31641
+ this.seen.delete(k);
31642
+ }
31643
+ }
31644
+ }
31645
+ /** Failures in the `windowS` seconds up to `atMs`, grouped, relative to the address that logged in. */
31646
+ failuresBefore(atMs, ip, windowS = 600) {
31647
+ const from = atMs - windowS * 1e3;
31648
+ const hits = this.failures.filter((f) => f.at >= from && f.at <= atMs + 1e3);
31649
+ const byIp = /* @__PURE__ */ new Map();
31650
+ const byUser = /* @__PURE__ */ new Map();
31651
+ for (const f of hits) {
31652
+ byIp.set(f.ip, (byIp.get(f.ip) ?? 0) + 1);
31653
+ byUser.set(f.user, (byUser.get(f.user) ?? 0) + 1);
31654
+ }
31655
+ const sameIp = byIp.get(ip) ?? 0;
31656
+ const top = (m, k) => [...m.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10).map(([v, count]) => ({ [k]: v, count }));
31657
+ return {
31658
+ window_s: windowS,
31659
+ total: hits.length,
31660
+ same_ip: sameIp,
31661
+ other_ips: hits.length - sameIp,
31662
+ ...hits.length ? {
31663
+ ips: top(byIp, "ip"),
31664
+ users: top(byUser, "user"),
31665
+ first: new Date(Math.min(...hits.map((h) => h.at))).toISOString(),
31666
+ last: new Date(Math.max(...hits.map((h) => h.at))).toISOString()
31667
+ } : {}
31668
+ };
31669
+ }
31670
+ /** When the session from `ip`:`port` closed, if it has. */
31671
+ closeOf(ip, port, afterMs) {
31672
+ if (!port) return null;
31673
+ const c = this.closes.find((x) => x.ip === ip && x.port === port && x.at >= afterMs - 1e3);
31674
+ return c ? c.at : null;
31675
+ }
31676
+ };
31677
+
31678
+ // src/daemon/ssh-context/authorized-keys.ts
31679
+ var import_node_fs37 = require("fs");
31680
+
31681
+ // src/core/host-scan/parsers.ts
31682
+ var import_node_crypto9 = require("crypto");
31683
+ var KEY_TYPE2 = /^(?:ssh-(?:rsa|dss|ed25519|xmss)|ecdsa-sha2-nistp(?:256|384|521)|sk-(?:ssh-ed25519|ecdsa-sha2-nistp256)@openssh\.com)(?:-cert-v0[01]@openssh\.com)?$/;
31684
+ function splitOptionsPrefix(line) {
31685
+ let inQuote = false;
31686
+ for (let i = 0; i < line.length; i++) {
31687
+ const ch = line[i];
31688
+ if (ch === "\\" && inQuote) {
31689
+ i++;
31690
+ continue;
31691
+ }
31692
+ if (ch === '"') {
31693
+ inQuote = !inQuote;
31694
+ continue;
31695
+ }
31696
+ if (!inQuote && (ch === " " || ch === " ")) return { options: line.slice(0, i), rest: line.slice(i).trimStart() };
31697
+ }
31698
+ return { options: line, rest: "" };
31699
+ }
31700
+ function parseOptionList(options) {
31701
+ const out = [];
31702
+ let i = 0;
31703
+ while (i < options.length) {
31704
+ let name = "";
31705
+ while (i < options.length && options[i] !== "=" && options[i] !== ",") name += options[i++];
31706
+ let value = null;
31707
+ if (options[i] === "=") {
31708
+ i++;
31709
+ if (options[i] === '"') {
31710
+ i++;
31711
+ value = "";
31712
+ while (i < options.length && options[i] !== '"') {
31713
+ if (options[i] === "\\" && options[i + 1] === '"') {
31714
+ value += '"';
31715
+ i += 2;
31716
+ continue;
31717
+ }
31718
+ value += options[i++];
31719
+ }
31720
+ i++;
31721
+ } else {
31722
+ value = "";
31723
+ while (i < options.length && options[i] !== ",") value += options[i++];
31724
+ }
31725
+ }
31726
+ if (options[i] === ",") i++;
31727
+ if (name.trim()) out.push({ name: name.trim().toLowerCase(), value });
31728
+ }
31729
+ return out;
31730
+ }
31731
+ function keyFingerprint2(blob) {
31732
+ try {
31733
+ const buf = Buffer.from(blob, "base64");
31734
+ if (!buf.length) return null;
31735
+ return `SHA256:${(0, import_node_crypto9.createHash)("sha256").update(buf).digest("base64").replace(/=+$/, "")}`;
31736
+ } catch {
31737
+ return null;
31738
+ }
31739
+ }
31740
+ function parseAuthorizedKeys2(text, file = "authorized_keys") {
31741
+ const keys = [];
31742
+ text.split("\n").forEach((raw, idx) => {
31743
+ const line = raw.replace(/\r$/, "").trim();
31744
+ if (!line || line.startsWith("#")) return;
31745
+ let optionText2 = "";
31746
+ let rest = line;
31747
+ const first = line.split(/\s+/, 1)[0];
31748
+ if (!KEY_TYPE2.test(first)) {
31749
+ const split = splitOptionsPrefix(line);
31750
+ optionText2 = split.options;
31751
+ rest = split.rest;
31752
+ }
31753
+ const parts = rest.split(/\s+/);
31754
+ const type = parts[0] ?? "";
31755
+ const blob = parts[1] ?? "";
31756
+ if (!KEY_TYPE2.test(type) || !blob) return;
31757
+ const options = optionText2 ? parseOptionList(optionText2) : [];
31758
+ const get2 = (n) => options.find((o) => o.name === n)?.value ?? null;
31759
+ keys.push({
31760
+ file,
31761
+ line: idx + 1,
31762
+ type,
31763
+ blob,
31764
+ comment: parts.slice(2).join(" "),
31765
+ options,
31766
+ command: get2("command"),
31767
+ from: get2("from"),
31768
+ restrict: options.some((o) => o.name === "restrict"),
31769
+ fingerprint: keyFingerprint2(blob)
31770
+ });
31771
+ });
31772
+ return keys;
31773
+ }
31774
+ function parsePasswd(text) {
31775
+ const out = [];
31776
+ for (const raw of text.split("\n")) {
31777
+ const f = raw.trim().split(":");
31778
+ if (f.length < 7 || raw.startsWith("#")) continue;
31779
+ out.push({ name: f[0], uid: Number(f[2]), gid: Number(f[3]), home: f[5], shell: f[6] });
31780
+ }
31781
+ return out;
31782
+ }
31783
+
31784
+ // src/daemon/ssh-context/authorized-keys.ts
31785
+ var realKeyFilesIO = {
31786
+ passwd: () => {
31787
+ try {
31788
+ return (0, import_node_fs37.readFileSync)("/etc/passwd", "utf-8");
31789
+ } catch {
31790
+ return "";
31791
+ }
31792
+ },
31793
+ mtime: (p) => {
31794
+ try {
31795
+ return (0, import_node_fs37.statSync)(p).mtimeMs;
31796
+ } catch {
31797
+ return null;
31798
+ }
31799
+ },
31800
+ read: (p) => {
31801
+ try {
31802
+ return (0, import_node_fs37.readFileSync)(p, "utf-8");
31803
+ } catch {
31804
+ return null;
31805
+ }
31806
+ }
31807
+ };
31808
+ var NOLOGIN = /(?:nologin|false|sync|halt|shutdown)$/;
31809
+ function maskBlob(blob) {
31810
+ return `${blob.slice(0, 8)}\u2026[masked]`;
31811
+ }
31812
+ function optionText(o) {
31813
+ return o.value === null ? o.name : `${o.name}="${o.value.replace(/"/g, '\\"')}"`;
31814
+ }
31815
+ var MAX_OPTION_CHARS = 300;
31816
+ function maskedLine(k) {
31817
+ const opts = k.options.map((o) => optionText(o).slice(0, MAX_OPTION_CHARS)).join(",");
31818
+ return [opts, k.type, maskBlob(k.blob), k.comment].filter(Boolean).join(" ");
31819
+ }
31820
+ var AuthorizedKeysIndex = class {
31821
+ constructor(io = realKeyFilesIO) {
31822
+ this.io = io;
31823
+ }
31824
+ io;
31825
+ files = /* @__PURE__ */ new Map();
31826
+ accounts() {
31827
+ return parsePasswd(this.io.passwd()).filter((p) => p.uid === 0 || p.home && p.home !== "/" && !NOLOGIN.test(p.shell)).map((p) => ({ name: p.name, home: p.home.replace(/\/$/, "") }));
31828
+ }
31829
+ keysIn(path, user) {
31830
+ const mtime = this.io.mtime(path);
31831
+ if (mtime === null) {
31832
+ this.files.delete(path);
31833
+ return [];
31834
+ }
31835
+ const cached = this.files.get(path);
31836
+ if (cached && cached.mtime === mtime) return cached.keys;
31837
+ const keys = parseAuthorizedKeys2(this.io.read(path) ?? "", path).map((k) => ({ ...k, user }));
31838
+ this.files.set(path, { mtime, keys });
31839
+ return keys;
31840
+ }
31841
+ /** Every authorized_keys line carrying `fingerprint`, as login context. */
31842
+ lookup(fingerprint, expected = /* @__PURE__ */ new Set()) {
31843
+ const matches = [];
31844
+ for (const { name, home } of this.accounts()) {
31845
+ for (const f of ["authorized_keys", "authorized_keys2"]) {
31846
+ for (const k2 of this.keysIn(`${home}/.ssh/${f}`, name)) if (k2.fingerprint === fingerprint) matches.push(k2);
31847
+ }
31848
+ }
31849
+ if (!matches.length) return { found: false, fingerprint, ...expected.has(fingerprint) ? { expected: true } : {} };
31850
+ const k = matches.find((m) => !m.command && !m.from && !m.restrict) ?? matches[0];
31851
+ const accounts = [...new Set(matches.map((m) => m.user))];
31852
+ const inRoot = matches.some((m) => m.user === "root" || m.file.startsWith("/root/"));
31853
+ const inOther = matches.some((m) => m.user !== "root" && !m.file.startsWith("/root/"));
31854
+ return {
31855
+ found: true,
31856
+ type: k.type,
31857
+ fingerprint,
31858
+ comment: k.comment.slice(0, 200) || void 0,
31859
+ options: k.options.map((o) => optionText(o).slice(0, MAX_OPTION_CHARS)),
31860
+ command: k.command ? k.command.slice(0, 500) : null,
31861
+ from: k.from ? k.from.slice(0, 300) : null,
31862
+ restrict: k.restrict,
31863
+ files: matches.map((m) => `${m.file}:${m.line}`).slice(0, 10),
31864
+ accounts,
31865
+ line_masked: maskedLine(k).slice(0, 800),
31866
+ in_root_and_user: inRoot && inOther,
31867
+ suspicious_comment: suspiciousKeyComment(k.comment),
31868
+ ...expected.has(fingerprint) ? { expected: true } : {}
31869
+ };
31870
+ }
31871
+ };
31872
+
31873
+ // src/daemon/ssh-context/ip-intel.ts
31874
+ var import_node_net16 = require("net");
31875
+ var import_node_os6 = require("os");
31876
+ var import_node_dns2 = require("dns");
31877
+ var import_node_fs38 = require("fs");
31878
+ function list(entries2) {
31879
+ const b = new import_node_net16.BlockList();
31880
+ for (const [a, p, f] of entries2) b.addSubnet(a, p, f);
31881
+ return b;
31882
+ }
31883
+ var LOOPBACK = list([["127.0.0.0", 8, "ipv4"], ["::1", 128, "ipv6"]]);
31884
+ var TAILSCALE = list([["100.64.0.0", 10, "ipv4"], ["fd7a:115c:a1e0::", 48, "ipv6"]]);
31885
+ var PRIVATE = list([
31886
+ ["10.0.0.0", 8, "ipv4"],
31887
+ ["172.16.0.0", 12, "ipv4"],
31888
+ ["192.168.0.0", 16, "ipv4"],
31889
+ ["169.254.0.0", 16, "ipv4"],
31890
+ ["fc00::", 7, "ipv6"],
31891
+ ["fe80::", 10, "ipv6"]
31892
+ ]);
31893
+ function family(ip) {
31894
+ const f = (0, import_node_net16.isIP)(ip);
31895
+ return f === 4 ? "ipv4" : f === 6 ? "ipv6" : null;
31896
+ }
31897
+ function normalizeIp2(ip) {
31898
+ const m = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(ip);
31899
+ return m ? m[1] : ip;
31900
+ }
31901
+ function ownAddresses() {
31902
+ const out = /* @__PURE__ */ new Set();
31903
+ try {
31904
+ for (const list2 of Object.values((0, import_node_os6.networkInterfaces)())) for (const a of list2 ?? []) out.add(a.address.split("%")[0]);
31905
+ } catch {
31906
+ }
31907
+ return out;
31908
+ }
31909
+ function classifyAddress(raw, c) {
31910
+ const ip = normalizeIp2(raw);
31911
+ const f = family(ip);
31912
+ if (!f) return "public";
31913
+ if (LOOPBACK.check(ip, f)) return "loopback";
31914
+ if (c.own().has(ip)) return "self";
31915
+ if (TAILSCALE.check(ip, f)) return "tailscale";
31916
+ if (PRIVATE.check(ip, f)) return "private";
31917
+ if (c.isGitHubActions(ip)) return "github-actions";
31918
+ return "public";
31919
+ }
31920
+ var META_URL = "https://api.github.com/meta";
31921
+ var DAY_MS = 24 * 60 * 60 * 1e3;
31922
+ var RETRY_MS = 30 * 60 * 1e3;
31923
+ function rangesDeps(cacheFile) {
31924
+ return {
31925
+ fetchJson: async (url) => {
31926
+ const res = await fetch(url, {
31927
+ headers: { accept: "application/vnd.github+json", "user-agent": "threatcrush-agent" },
31928
+ signal: AbortSignal.timeout(15e3)
31929
+ });
31930
+ if (!res.ok) throw new Error(`GitHub meta ${res.status}`);
31931
+ return res.json();
31932
+ },
31933
+ load: () => {
31934
+ try {
31935
+ const v = JSON.parse((0, import_node_fs38.readFileSync)(cacheFile, "utf-8"));
31936
+ return typeof v.at === "number" && Array.isArray(v.cidrs) ? { at: v.at, cidrs: v.cidrs.map(String) } : null;
31937
+ } catch {
31938
+ return null;
31939
+ }
31940
+ },
31941
+ save: (v) => {
31942
+ try {
31943
+ (0, import_node_fs38.writeFileSync)(cacheFile, JSON.stringify(v), { mode: 420 });
31944
+ } catch {
31945
+ }
31946
+ },
31947
+ now: Date.now
31948
+ };
31949
+ }
31950
+ var GitHubActionsRanges = class {
31951
+ constructor(deps, enabled = true) {
31952
+ this.deps = deps;
31953
+ this.enabled = enabled;
31954
+ const saved = enabled ? deps.load() : null;
31955
+ if (saved?.cidrs.length) this.set(saved.cidrs, saved.at);
31956
+ }
31957
+ deps;
31958
+ enabled;
31959
+ list = null;
31960
+ count = 0;
31961
+ at = 0;
31962
+ lastTry = 0;
31963
+ inflight = null;
31964
+ set(cidrs, at) {
31965
+ const b = new import_node_net16.BlockList();
31966
+ let n = 0;
31967
+ for (const c of cidrs) {
31968
+ const [addr, bits] = c.split("/");
31969
+ const f = family(addr);
31970
+ const p = Number(bits);
31971
+ if (!f || !Number.isInteger(p)) continue;
31972
+ try {
31973
+ b.addSubnet(addr, p, f);
31974
+ n++;
31975
+ } catch {
31976
+ }
31977
+ }
31978
+ if (n) {
31979
+ this.list = b;
31980
+ this.count = n;
31981
+ this.at = at;
31982
+ }
31983
+ }
31984
+ size() {
31985
+ return this.count;
31986
+ }
31987
+ /** Refresh when stale; never throws, never blocks a lookup for long. */
31988
+ async refresh() {
31989
+ if (!this.enabled) return;
31990
+ const now = this.deps.now();
31991
+ if (this.list && now - this.at < DAY_MS) return;
31992
+ if (now - this.lastTry < RETRY_MS) return;
31993
+ this.inflight ??= (async () => {
31994
+ this.lastTry = now;
31995
+ try {
31996
+ const body = await this.deps.fetchJson(META_URL);
31997
+ const cidrs = Array.isArray(body?.actions) ? body.actions.filter((c) => typeof c === "string") : [];
31998
+ if (cidrs.length) {
31999
+ this.set(cidrs, now);
32000
+ this.deps.save({ at: now, cidrs });
32001
+ }
32002
+ } catch {
32003
+ }
32004
+ })().finally(() => {
32005
+ this.inflight = null;
32006
+ });
32007
+ return this.inflight;
32008
+ }
32009
+ has(raw) {
32010
+ const ip = normalizeIp2(raw);
32011
+ const f = family(ip);
32012
+ return !!(this.list && f && this.list.check(ip, f));
32013
+ }
32014
+ };
32015
+ var realNetLookup = {
32016
+ reverse: (ip) => import_node_dns2.promises.reverse(ip),
32017
+ txt: (name) => import_node_dns2.promises.resolveTxt(name)
32018
+ };
32019
+ function withTimeout2(p, ms) {
32020
+ return Promise.race([p.catch(() => null), new Promise((r) => setTimeout(() => r(null), ms).unref?.())]);
32021
+ }
32022
+ function cymruOriginName2(raw) {
32023
+ const ip = normalizeIp2(raw);
32024
+ const f = (0, import_node_net16.isIP)(ip);
32025
+ if (f === 4) return `${ip.split(".").reverse().join(".")}.origin.asn.cymru.com`;
32026
+ if (f !== 6) return null;
32027
+ const parts = ip.split("::");
32028
+ const head = parts[0] ? parts[0].split(":") : [];
32029
+ const tail = parts.length > 1 && parts[1] ? parts[1].split(":") : [];
32030
+ const groups = [...head, ...Array(8 - head.length - tail.length).fill("0"), ...tail].map((g) => g.padStart(4, "0"));
32031
+ return `${groups.join("").split("").reverse().join(".")}.origin6.asn.cymru.com`;
32032
+ }
32033
+ function parseCymruOrigin2(txt) {
32034
+ const f = txt.split("|").map((s) => s.trim());
32035
+ const asn = Number((f[0] ?? "").split(/\s+/)[0]);
32036
+ if (!Number.isInteger(asn) || asn <= 0) return null;
32037
+ return { asn, country: f[2] && /^[A-Z]{2}$/.test(f[2]) ? f[2] : null };
32038
+ }
32039
+ function parseCymruAsName(txt) {
32040
+ const f = txt.split("|").map((s) => s.trim());
32041
+ const name = f[4]?.replace(/,\s*[A-Z]{2}$/, "").trim();
32042
+ return name ? name.slice(0, 120) : null;
32043
+ }
32044
+ var NetLookup = class {
32045
+ constructor(deps = realNetLookup, timeoutMs = 2500, now = Date.now) {
32046
+ this.deps = deps;
32047
+ this.timeoutMs = timeoutMs;
32048
+ this.now = now;
32049
+ }
32050
+ deps;
32051
+ timeoutMs;
32052
+ now;
32053
+ cache = /* @__PURE__ */ new Map();
32054
+ async lookup(ip) {
32055
+ const hit = this.cache.get(ip);
32056
+ if (hit && this.now() - hit.at < 6 * 60 * 60 * 1e3) return hit.v;
32057
+ const originName = cymruOriginName2(ip);
32058
+ const [names, origin] = await Promise.all([
32059
+ withTimeout2(this.deps.reverse(normalizeIp2(ip)), this.timeoutMs),
32060
+ originName ? withTimeout2(this.deps.txt(originName), this.timeoutMs) : Promise.resolve(null)
32061
+ ]);
32062
+ const o = origin?.[0] ? parseCymruOrigin2(origin[0].join("")) : null;
32063
+ let asOrg = null;
32064
+ if (o) {
32065
+ const named = await withTimeout2(this.deps.txt(`AS${o.asn}.asn.cymru.com`), this.timeoutMs);
32066
+ asOrg = named?.[0] ? parseCymruAsName(named[0].join("")) : null;
32067
+ }
32068
+ const v = { rdns: names?.[0]?.slice(0, 253) ?? null, asn: o?.asn ?? null, as_org: asOrg, country: o?.country ?? null };
32069
+ if (this.cache.size > 2e3) this.cache.clear();
32070
+ this.cache.set(ip, { at: this.now(), v });
32071
+ return v;
32072
+ }
32073
+ };
32074
+
32075
+ // src/daemon/ssh-context/ci-deploy.ts
32076
+ var import_node_child_process14 = require("child_process");
32077
+ var SECRETISH = /\b([A-Za-z_]*(?:token|secret|password|passwd|apikey|api_key|key|auth)[A-Za-z_]*)=("[^"]*"|'[^']*'|\S+)/gi;
32078
+ function redactCommand(cmd) {
32079
+ return cmd.replace(SECRETISH, "$1=[redacted]").slice(0, 300);
32080
+ }
32081
+ function parseCiDeployMessage(message) {
32082
+ const m = /^\s*(ALLOW|DENY|DENIED|REJECT(?:ED)?)\b\s*(?:\(([^)]*)\))?(.*)$/i.exec(message);
32083
+ if (!m) return null;
32084
+ const rest = m[3] ?? "";
32085
+ const repo = /\brepo=(\S+)/.exec(rest)?.[1];
32086
+ const from = /\bfrom=(\S+)/.exec(rest)?.[1];
32087
+ const cmd = /\bcmd=(.*)$/.exec(rest)?.[1]?.trim();
32088
+ return {
32089
+ decision: m[1].toUpperCase().startsWith("ALLOW") ? "ALLOW" : "DENY",
32090
+ ...m[2] ? { action: m[2].trim().slice(0, 200) } : {},
32091
+ ...repo ? { repo: repo.slice(0, 200) } : {},
32092
+ ...from ? { from } : {},
32093
+ ...cmd ? { command: redactCommand(cmd) } : {}
32094
+ };
32095
+ }
32096
+ function parseCiDeployJournal(text, tag = "ci-deploy") {
32097
+ const out = [];
32098
+ const esc = tag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
32099
+ const re = new RegExp(`^(\\d+(?:\\.\\d+)?)\\s+\\S+\\s+${esc}(?:\\[\\d+\\])?:\\s(.*)$`);
32100
+ for (const line of text.split("\n")) {
32101
+ const m = re.exec(line);
32102
+ if (!m) continue;
32103
+ const parsed = parseCiDeployMessage(m[2]);
32104
+ if (!parsed) continue;
32105
+ const atMs = Math.round(Number(m[1]) * 1e3);
32106
+ out.push({ ...parsed, atMs, at: new Date(atMs).toISOString() });
32107
+ }
32108
+ return out;
32109
+ }
32110
+ function pickCiDeploy(lines, ip, atMs) {
32111
+ const near = lines.filter((l) => l.from === ip && l.atMs !== void 0 && l.atMs >= atMs - 5e3 && l.atMs <= atMs + 6e4).sort((a, b) => Math.abs(a.atMs - atMs) - Math.abs(b.atMs - atMs));
32112
+ if (!near.length) return null;
32113
+ const { from: _from, atMs: _at, ...ctx } = near[0];
32114
+ return ctx;
32115
+ }
32116
+ var realJournal = (args) => new Promise((resolve4) => {
32117
+ (0, import_node_child_process14.execFile)("journalctl", args, { timeout: 4e3, maxBuffer: 1024 * 1024, encoding: "utf-8" }, (err, stdout) => resolve4(err ? null : stdout));
32118
+ });
32119
+ async function findCiDeploy(ip, atMs, tag = "ci-deploy", run = realJournal) {
32120
+ const s = Math.floor(atMs / 1e3);
32121
+ const out = await run(["-t", tag, `--since=@${s - 5}`, `--until=@${s + 60}`, "-o", "short-unix", "--no-pager", "-q"]);
32122
+ return out ? pickCiDeploy(parseCiDeployJournal(out, tag), ip, atMs) : null;
32123
+ }
32124
+
32125
+ // src/daemon/ssh-context/index.ts
32126
+ function sshContextSettings(s) {
32127
+ const settle = Number(s?.settle_ms);
32128
+ const win = Number(s?.failure_window_seconds);
32129
+ return {
32130
+ enabled: s?.enabled !== false,
32131
+ networkLookups: s?.network_lookups !== false,
32132
+ githubRanges: s?.github_actions_ranges !== false,
32133
+ expectedKeys: new Set((Array.isArray(s?.expected_keys) ? s.expected_keys : []).map(String).filter((k) => k.startsWith("SHA256:"))),
32134
+ ciDeployTag: typeof s?.ci_deploy_tag === "string" && /^[\w.-]{1,64}$/.test(s.ci_deploy_tag) ? s.ci_deploy_tag : "ci-deploy",
32135
+ failureWindowS: Number.isFinite(win) && win >= 60 && win <= 86400 ? win : 600,
32136
+ settleMs: Number.isFinite(settle) && settle >= 0 ? Math.min(settle, 2e4) : 5e3
32137
+ };
32138
+ }
32139
+ function isAcceptedLogin(event) {
32140
+ return event.module === "ssh-guard" && /SSH login accepted/.test(event.message) && !!event.source_ip;
32141
+ }
32142
+ var SshLoginEnricher = class {
32143
+ constructor(settings, deps = {}) {
32144
+ this.settings = settings;
32145
+ this.deps = deps;
32146
+ const now = deps.now ?? Date.now;
32147
+ this.history = deps.history ?? new SshAuthHistory(now);
32148
+ this.keys = deps.keys ?? new AuthorizedKeysIndex();
32149
+ this.ranges = deps.ranges ?? new GitHubActionsRanges(rangesDeps((0, import_node_path28.join)(deps.stateDir ?? ".", "github-actions-ranges.json")), settings.githubRanges);
32150
+ this.net = deps.net ?? new NetLookup();
32151
+ this.sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
32152
+ this.host = deps.host ?? (0, import_node_os7.hostname)();
32153
+ const own = deps.own ?? (() => {
32154
+ if (now() - this.ownCache.at > 6e4) this.ownCache = { at: now(), v: ownAddresses() };
32155
+ return this.ownCache.v;
32156
+ });
32157
+ this.classifier = { own, isGitHubActions: (ip) => this.ranges.has(ip) };
32158
+ }
32159
+ settings;
32160
+ deps;
32161
+ history;
32162
+ keys;
32163
+ ranges;
32164
+ net;
32165
+ classifier;
32166
+ sleep;
32167
+ host;
32168
+ ownCache = { at: -Infinity, v: /* @__PURE__ */ new Set() };
32169
+ /** Warm the GitHub ranges at start-up; safe to call any time. */
32170
+ start() {
32171
+ if (this.settings.enabled) void this.ranges.refresh();
32172
+ }
32173
+ recordSshd(line) {
32174
+ if (this.settings.enabled) this.history.record(line);
32175
+ }
32176
+ wants(event) {
32177
+ return this.settings.enabled && isAcceptedLogin(event) && !("ssh_context" in (event.details ?? {}));
32178
+ }
32179
+ /** Adds `details.ssh_context` to the event in place and returns it. Never throws. */
32180
+ async enrich(event) {
32181
+ try {
32182
+ const d = event.details ??= {};
32183
+ const ip = normalizeIp2(event.source_ip ?? "");
32184
+ const atMs = event.timestamp instanceof Date ? event.timestamp.getTime() : Date.now();
32185
+ const user = typeof d.ssh_user === "string" ? d.ssh_user : /SSH login accepted for (\S+)/.exec(event.message)?.[1];
32186
+ const method = typeof d.auth_method === "string" ? d.auth_method : void 0;
32187
+ const fp = typeof d.fingerprint === "string" && d.fingerprint.startsWith("SHA256:") ? d.fingerprint : void 0;
32188
+ const port = typeof d.port === "number" ? d.port : Number(d.port) || void 0;
32189
+ await this.ranges.refresh();
32190
+ const kind = classifyAddress(ip, this.classifier);
32191
+ const key = fp ? this.keys.lookup(fp, this.settings.expectedKeys) : void 0;
32192
+ if (key && !key.type && typeof d.key_type === "string") key.type = d.key_type;
32193
+ const failures = this.history.failuresBefore(atMs, ip, this.settings.failureWindowS);
32194
+ const netP = this.settings.networkLookups && (kind === "public" || kind === "github-actions") ? this.net.lookup(ip).catch(() => null) : Promise.resolve(null);
32195
+ const settle = this.sleep(this.settings.settleMs);
32196
+ const [net] = await Promise.all([netP, settle]);
32197
+ const ci = key?.command ? await findCiDeploy(ip, atMs, this.settings.ciDeployTag, this.deps.journal).catch(() => null) : null;
32198
+ const closed = this.history.closeOf(ip, port, atMs);
32199
+ let tz;
32200
+ try {
32201
+ tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
32202
+ } catch {
32203
+ tz = void 0;
32204
+ }
32205
+ const base = {
32206
+ v: 1,
32207
+ at: new Date(atMs).toISOString(),
32208
+ host: this.host,
32209
+ tz_offset_min: -new Date(atMs).getTimezoneOffset(),
32210
+ ...tz ? { tz } : {},
32211
+ ...user ? { user } : {},
32212
+ ...method ? { auth_method: method } : {},
32213
+ ...port ? { port } : {},
32214
+ ...key ? { key } : {},
32215
+ source: { ip, kind, ...net ?? {} },
32216
+ failures,
32217
+ session: {
32218
+ ...ci ? { ci_deploy: ci } : {},
32219
+ ...closed !== null ? { closed_at: new Date(closed).toISOString(), duration_s: Math.max(0, Math.round((closed - atMs) / 1e3)) } : { open: true }
32220
+ }
32221
+ };
32222
+ const ctx = { ...base, verdict: computeVerdict(base) };
32223
+ d.ssh_context = ctx;
32224
+ return ctx;
32225
+ } catch {
32226
+ return null;
32227
+ }
32228
+ }
32229
+ };
32230
+
32231
+ // src/daemon/rules/loader.ts
32232
+ var import_node_fs39 = require("fs");
32233
+ var import_node_path29 = require("path");
32234
+
31478
32235
  // src/daemon/rules/default-rules.ts
31479
32236
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
31480
32237
  var SSHD_IDENT = String.raw`\[sshd(?:-session|-auth)?\]`;
@@ -31507,12 +32264,16 @@ var DEFAULT_RULES = [
31507
32264
  {
31508
32265
  id: "ssh-success-after-failures",
31509
32266
  title: "SSH Login Accepted",
31510
- // Honest description: this rule does NOT correlate with earlier failures —
31511
- // it matches any accepted login. It is an alert, and it declares no
31512
- // remediation precisely because banning the person who just logged in is
31513
- // never the right response.
32267
+ // Matches every accepted login, not only one after failures (the id is
32268
+ // kept for dashboards and incidents keyed on it). What came before it is
32269
+ // in the login's ssh_context: the failures in the window and whether they
32270
+ // came from the same address. With [ssh_context] on (the default) the
32271
+ // detection's severity is the context's verdict: a GitHub Actions deploy
32272
+ // with a forced-command key is low, an operator-expected CI key is info,
32273
+ // an unrestricted key from the internet stays critical. It declares no
32274
+ // remediation: banning the person who just logged in is never the answer.
31514
32275
  description: "Successful SSH login (alert only \u2014 never grounds for a ban)",
31515
- version: "1.0.0",
32276
+ version: "1.1.0",
31516
32277
  category: "auth",
31517
32278
  severity: "critical",
31518
32279
  source_types: ["ssh-guard", "auth"],
@@ -31524,7 +32285,7 @@ var DEFAULT_RULES = [
31524
32285
  threshold: 1,
31525
32286
  window_seconds: 60,
31526
32287
  cooldown_seconds: 300,
31527
- tags: ["ssh", "compromise-indicator"],
32288
+ tags: ["ssh", "compromise-indicator", "ssh-login-verdict"],
31528
32289
  enabled: true
31529
32290
  },
31530
32291
  {
@@ -32145,16 +32906,16 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
32145
32906
  function loadAllRules(customDir) {
32146
32907
  const rules = [...DEFAULT_RULES];
32147
32908
  const dir = customDir || RULES_DIR;
32148
- if ((0, import_node_fs37.existsSync)(dir)) {
32909
+ if ((0, import_node_fs39.existsSync)(dir)) {
32149
32910
  let files = [];
32150
32911
  try {
32151
- files = (0, import_node_fs37.readdirSync)(dir).filter((f) => f.endsWith(".json"));
32912
+ files = (0, import_node_fs39.readdirSync)(dir).filter((f) => f.endsWith(".json"));
32152
32913
  } catch (err) {
32153
32914
  console.warn(`[rules] cannot read ${dir}: ${err.message}; custom rules not loaded`);
32154
32915
  }
32155
32916
  for (const file of files) {
32156
32917
  try {
32157
- const raw = (0, import_node_fs37.readFileSync)((0, import_node_path28.join)(dir, file), "utf-8");
32918
+ const raw = (0, import_node_fs39.readFileSync)((0, import_node_path29.join)(dir, file), "utf-8");
32158
32919
  const parsed = JSON.parse(raw);
32159
32920
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
32160
32921
  for (const rule of customRules) {
@@ -32185,24 +32946,24 @@ function loadAllRules(customDir) {
32185
32946
  }
32186
32947
 
32187
32948
  // src/daemon/firewall/adapters.ts
32188
- var import_node_child_process14 = require("child_process");
32189
- var import_node_fs38 = require("fs");
32190
- var import_node_path29 = require("path");
32191
- var import_node_net16 = require("net");
32949
+ var import_node_child_process15 = require("child_process");
32950
+ var import_node_fs40 = require("fs");
32951
+ var import_node_path30 = require("path");
32952
+ var import_node_net17 = require("net");
32192
32953
  function assertValidFirewallIp(ip) {
32193
- if ((0, import_node_net16.isIP)(ip) !== 4) {
32954
+ if ((0, import_node_net17.isIP)(ip) !== 4) {
32194
32955
  throw new Error(`Invalid IPv4 address: ${ip}`);
32195
32956
  }
32196
32957
  }
32197
32958
  function assertBannableIp(ip) {
32198
- if ((0, import_node_net16.isIP)(ip) === 0) {
32959
+ if ((0, import_node_net17.isIP)(ip) === 0) {
32199
32960
  throw new Error(`Invalid IP address: ${ip}`);
32200
32961
  }
32201
32962
  }
32202
32963
  function writeIfAbsent(path, contents) {
32203
- (0, import_node_fs38.mkdirSync)((0, import_node_path29.dirname)(path), { recursive: true });
32964
+ (0, import_node_fs40.mkdirSync)((0, import_node_path30.dirname)(path), { recursive: true });
32204
32965
  try {
32205
- (0, import_node_fs38.writeFileSync)(path, contents, { flag: "wx" });
32966
+ (0, import_node_fs40.writeFileSync)(path, contents, { flag: "wx" });
32206
32967
  } catch (err) {
32207
32968
  if (err.code !== "EEXIST") throw err;
32208
32969
  }
@@ -32221,11 +32982,11 @@ var Fail2banAdapter = class {
32221
32982
  enforces = true;
32222
32983
  jailReady = false;
32223
32984
  isAvailable() {
32224
- const result = (0, import_node_child_process14.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
32985
+ const result = (0, import_node_child_process15.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
32225
32986
  return result.status === 0;
32226
32987
  }
32227
32988
  client(args) {
32228
- return (0, import_node_child_process14.execFileSync)("fail2ban-client", args, {
32989
+ return (0, import_node_child_process15.execFileSync)("fail2ban-client", args, {
32229
32990
  encoding: "utf-8",
32230
32991
  stdio: ["ignore", "pipe", "pipe"]
32231
32992
  });
@@ -32301,7 +33062,7 @@ var Fail2banAdapter = class {
32301
33062
  const status = this.client(["status", this.jail]);
32302
33063
  const line = status.split("\n").find((l) => /Banned IP list:/i.test(l));
32303
33064
  if (!line) return [];
32304
- return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net16.isIP)(s) !== 0);
33065
+ return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net17.isIP)(s) !== 0);
32305
33066
  } catch {
32306
33067
  return [];
32307
33068
  }
@@ -32311,45 +33072,45 @@ var Fail2banAdapter = class {
32311
33072
  function parseBannedList(output) {
32312
33073
  const found = [];
32313
33074
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
32314
- if ((0, import_node_net16.isIP)(match[1]) !== 0) found.push(match[1]);
33075
+ if ((0, import_node_net17.isIP)(match[1]) !== 0) found.push(match[1]);
32315
33076
  }
32316
33077
  if (found.length > 0) return found;
32317
- return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net16.isIP)(s) !== 0);
33078
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net17.isIP)(s) !== 0);
32318
33079
  }
32319
33080
  var NftablesAdapter = class {
32320
33081
  name = "nftables";
32321
33082
  table = "threatcrush";
32322
33083
  set = "blocklist";
32323
33084
  isAvailable() {
32324
- const result = (0, import_node_child_process14.spawnSync)("nft", ["--version"], { stdio: "pipe" });
33085
+ const result = (0, import_node_child_process15.spawnSync)("nft", ["--version"], { stdio: "pipe" });
32325
33086
  return result.status === 0;
32326
33087
  }
32327
33088
  ensureSetup() {
32328
33089
  try {
32329
- (0, import_node_child_process14.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
33090
+ (0, import_node_child_process15.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
32330
33091
  } catch {
32331
- (0, import_node_child_process14.execSync)(`nft add table inet ${this.table}`);
32332
- (0, import_node_child_process14.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
32333
- (0, import_node_child_process14.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
32334
- (0, import_node_child_process14.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
33092
+ (0, import_node_child_process15.execSync)(`nft add table inet ${this.table}`);
33093
+ (0, import_node_child_process15.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
33094
+ (0, import_node_child_process15.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
33095
+ (0, import_node_child_process15.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
32335
33096
  }
32336
33097
  }
32337
33098
  async block(ip) {
32338
33099
  assertValidFirewallIp(ip);
32339
33100
  this.ensureSetup();
32340
- (0, import_node_child_process14.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
33101
+ (0, import_node_child_process15.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
32341
33102
  }
32342
33103
  async unblock(ip) {
32343
33104
  assertValidFirewallIp(ip);
32344
33105
  try {
32345
- (0, import_node_child_process14.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
33106
+ (0, import_node_child_process15.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
32346
33107
  } catch {
32347
33108
  }
32348
33109
  }
32349
33110
  async isBlocked(ip) {
32350
33111
  assertValidFirewallIp(ip);
32351
33112
  try {
32352
- const output = (0, import_node_child_process14.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
33113
+ const output = (0, import_node_child_process15.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
32353
33114
  return output.includes(ip);
32354
33115
  } catch {
32355
33116
  return false;
@@ -32357,7 +33118,7 @@ var NftablesAdapter = class {
32357
33118
  }
32358
33119
  async listBlocked() {
32359
33120
  try {
32360
- const output = (0, import_node_child_process14.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
33121
+ const output = (0, import_node_child_process15.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
32361
33122
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
32362
33123
  if (!match) return [];
32363
33124
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -32370,34 +33131,34 @@ var IptablesAdapter = class {
32370
33131
  name = "iptables";
32371
33132
  chain = "THREATCRUSH";
32372
33133
  isAvailable() {
32373
- const result = (0, import_node_child_process14.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
33134
+ const result = (0, import_node_child_process15.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
32374
33135
  return result.status === 0;
32375
33136
  }
32376
33137
  ensureChain() {
32377
33138
  try {
32378
- (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
33139
+ (0, import_node_child_process15.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
32379
33140
  } catch {
32380
- (0, import_node_child_process14.execSync)(`iptables -N ${this.chain}`);
32381
- (0, import_node_child_process14.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
33141
+ (0, import_node_child_process15.execSync)(`iptables -N ${this.chain}`);
33142
+ (0, import_node_child_process15.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
32382
33143
  }
32383
33144
  }
32384
33145
  async block(ip) {
32385
33146
  assertValidFirewallIp(ip);
32386
33147
  this.ensureChain();
32387
33148
  if (await this.isBlocked(ip)) return;
32388
- (0, import_node_child_process14.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
33149
+ (0, import_node_child_process15.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
32389
33150
  }
32390
33151
  async unblock(ip) {
32391
33152
  assertValidFirewallIp(ip);
32392
33153
  try {
32393
- (0, import_node_child_process14.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
33154
+ (0, import_node_child_process15.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
32394
33155
  } catch {
32395
33156
  }
32396
33157
  }
32397
33158
  async isBlocked(ip) {
32398
33159
  assertValidFirewallIp(ip);
32399
33160
  try {
32400
- const output = (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
33161
+ const output = (0, import_node_child_process15.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
32401
33162
  return output.includes(ip);
32402
33163
  } catch {
32403
33164
  return false;
@@ -32405,7 +33166,7 @@ var IptablesAdapter = class {
32405
33166
  }
32406
33167
  async listBlocked() {
32407
33168
  try {
32408
- const output = (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
33169
+ const output = (0, import_node_child_process15.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
32409
33170
  const ips = [];
32410
33171
  for (const line of output.split("\n")) {
32411
33172
  const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -32461,20 +33222,20 @@ function detectFirewallAdapter(backend = "auto") {
32461
33222
  }
32462
33223
 
32463
33224
  // src/daemon/firewall/remediation.ts
32464
- var import_node_fs39 = require("fs");
32465
- var import_node_child_process15 = require("child_process");
32466
- var import_node_net17 = require("net");
33225
+ var import_node_fs41 = require("fs");
33226
+ var import_node_child_process16 = require("child_process");
33227
+ var import_node_net18 = require("net");
32467
33228
 
32468
33229
  // src/daemon/firewall/crawlers.ts
32469
- var import_node_dns2 = require("dns");
33230
+ var import_node_dns3 = require("dns");
32470
33231
  var CRAWLER_DOMAINS = ["googlebot.com", "google.com", "search.msn.com", "applebot.apple.com"];
32471
33232
  var systemResolver = {
32472
- reverse: (ip) => import_node_dns2.promises.reverse(ip),
32473
- lookup: async (host) => (await import_node_dns2.promises.lookup(host, { all: true })).map((a) => a.address)
33233
+ reverse: (ip) => import_node_dns3.promises.reverse(ip),
33234
+ lookup: async (host) => (await import_node_dns3.promises.lookup(host, { all: true })).map((a) => a.address)
32474
33235
  };
32475
33236
  var TIMEOUT_MS2 = 2e3;
32476
33237
  var CACHE_MS = 6 * 36e5;
32477
- function withTimeout2(p) {
33238
+ function withTimeout3(p) {
32478
33239
  return Promise.race([
32479
33240
  p,
32480
33241
  new Promise((_, reject) => setTimeout(() => reject(new Error("dns timeout")), TIMEOUT_MS2).unref())
@@ -32491,9 +33252,9 @@ function crawlerVerifier(resolver = systemResolver) {
32491
33252
  if (hit && hit.until > Date.now()) return hit.host;
32492
33253
  let host = null;
32493
33254
  try {
32494
- const names = await withTimeout2(resolver.reverse(ip));
33255
+ const names = await withTimeout3(resolver.reverse(ip));
32495
33256
  for (const name of names.filter(inCrawlerDomain)) {
32496
- const addrs = await withTimeout2(resolver.lookup(name));
33257
+ const addrs = await withTimeout3(resolver.lookup(name));
32497
33258
  if (addrs.includes(ip)) {
32498
33259
  host = name.replace(/\.$/, "");
32499
33260
  break;
@@ -32531,19 +33292,19 @@ var defaultDiscovery = {
32531
33292
  const snapshot = takeSnapshot({
32532
33293
  readFile: (p) => {
32533
33294
  try {
32534
- return (0, import_node_fs39.readFileSync)(p, "utf-8");
33295
+ return (0, import_node_fs41.readFileSync)(p, "utf-8");
32535
33296
  } catch {
32536
33297
  return null;
32537
33298
  }
32538
33299
  },
32539
33300
  readDir: (p) => {
32540
33301
  try {
32541
- return (0, import_node_fs39.readdirSync)(p);
33302
+ return (0, import_node_fs41.readdirSync)(p);
32542
33303
  } catch {
32543
33304
  return null;
32544
33305
  }
32545
33306
  },
32546
- exists: (p) => (0, import_node_fs39.existsSync)(p)
33307
+ exists: (p) => (0, import_node_fs41.existsSync)(p)
32547
33308
  });
32548
33309
  const out = /* @__PURE__ */ new Set();
32549
33310
  for (const keys of Object.values(snapshot.keys)) {
@@ -32552,7 +33313,7 @@ var defaultDiscovery = {
32552
33313
  return out;
32553
33314
  },
32554
33315
  keyLoginJournal: (sinceSeconds) => new Promise((resolve4) => {
32555
- (0, import_node_child_process15.execFile)(
33316
+ (0, import_node_child_process16.execFile)(
32556
33317
  "journalctl",
32557
33318
  ["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
32558
33319
  { maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
@@ -32632,7 +33393,7 @@ var RemediationManager = class {
32632
33393
  setTorExitCheck(check) {
32633
33394
  this.isTorExit = check;
32634
33395
  let dropped = 0;
32635
- this.protectedList = this.protectedList.filter((a) => !(0, import_node_net17.isIP)(a) || !check(a) || this.pinned.has(a) || this.config.allowlist.includes(a));
33396
+ this.protectedList = this.protectedList.filter((a) => !(0, import_node_net18.isIP)(a) || !check(a) || this.pinned.has(a) || this.config.allowlist.includes(a));
32636
33397
  for (const ip of Object.keys(this.operators)) {
32637
33398
  if (!check(ip)) continue;
32638
33399
  delete this.operators[ip];
@@ -32725,7 +33486,7 @@ var RemediationManager = class {
32725
33486
  if (remediation?.action !== "block") return;
32726
33487
  }
32727
33488
  const ip = event.source_ip;
32728
- if (!ip || (0, import_node_net17.isIP)(ip) === 0) return;
33489
+ if (!ip || (0, import_node_net18.isIP)(ip) === 0) return;
32729
33490
  const strict = remediation?.override_operator_protection === true;
32730
33491
  if (strict ? this.isFleetAddress(ip) : this.isAllowlisted(ip)) {
32731
33492
  if (strict) this.logLine(`[remediation] not banning ${ip}: it is one of our own addresses (${event.message})`);
@@ -32754,7 +33515,7 @@ var RemediationManager = class {
32754
33515
  * 4th offence and so on, clamped to `max_ban_seconds`.
32755
33516
  */
32756
33517
  async ban(ip, reason, opts = {}) {
32757
- if ((0, import_node_net17.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
33518
+ if ((0, import_node_net18.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
32758
33519
  if (opts.strict ? this.isFleetAddress(ip) : this.isAllowlisted(ip)) {
32759
33520
  return { ok: false, error: `${ip} is protected and can never be blocked` };
32760
33521
  }
@@ -33031,7 +33792,7 @@ var RemediationManager = class {
33031
33792
  if (saved && typeof saved === "object" && this.config.protect_recent_operators) {
33032
33793
  const cutoff = Date.now() - this.config.operator_memory_seconds * 1e3;
33033
33794
  for (const [ip, at] of Object.entries(saved)) {
33034
- if (typeof at !== "number" || at < cutoff || !(0, import_node_net17.isIP)(ip)) continue;
33795
+ if (typeof at !== "number" || at < cutoff || !(0, import_node_net18.isIP)(ip)) continue;
33035
33796
  if (this.blocklist.some((b) => b.ip === ip && b.strict)) continue;
33036
33797
  this.operators[ip] = at;
33037
33798
  if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
@@ -33056,7 +33817,7 @@ var RemediationManager = class {
33056
33817
  }
33057
33818
  logLine(line) {
33058
33819
  try {
33059
- (0, import_node_fs39.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
33820
+ (0, import_node_fs41.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
33060
33821
  `);
33061
33822
  } catch {
33062
33823
  }
@@ -33096,13 +33857,13 @@ function remediationSettings(section) {
33096
33857
  }
33097
33858
 
33098
33859
  // src/daemon/watchdog-service.ts
33099
- var import_node_fs41 = require("fs");
33100
- var import_node_path31 = require("path");
33860
+ var import_node_fs43 = require("fs");
33861
+ var import_node_path32 = require("path");
33101
33862
 
33102
33863
  // src/core/watchdog.ts
33103
- var import_node_fs40 = require("fs");
33104
- var import_node_crypto9 = require("crypto");
33105
- var import_node_path30 = require("path");
33864
+ var import_node_fs42 = require("fs");
33865
+ var import_node_crypto10 = require("crypto");
33866
+ var import_node_path31 = require("path");
33106
33867
  var WATCHDOG_DIRNAME = "watchdog";
33107
33868
  var LOG_FILE2 = "attacks.jsonl";
33108
33869
  var ROTATED_FILE = "attacks.1.jsonl";
@@ -33142,7 +33903,7 @@ function signatureOf(r) {
33142
33903
  return ["msg", r.module, shape].join("|");
33143
33904
  }
33144
33905
  function findingId(signature2) {
33145
- return (0, import_node_crypto9.createHash)("sha1").update(signature2).digest("hex").slice(0, 10);
33906
+ return (0, import_node_crypto10.createHash)("sha1").update(signature2).digest("hex").slice(0, 10);
33146
33907
  }
33147
33908
  function toRecord(event) {
33148
33909
  const d = event.details ?? {};
@@ -33191,12 +33952,12 @@ var WatchdogLog = class {
33191
33952
  stats = { logged: 0, answered: 0, errored: 0 };
33192
33953
  constructor(dir, options = {}) {
33193
33954
  this.dir = dir;
33194
- this.file = (0, import_node_path30.join)(dir, LOG_FILE2);
33955
+ this.file = (0, import_node_path31.join)(dir, LOG_FILE2);
33195
33956
  this.shareGid = options.shareGid;
33196
- (0, import_node_fs40.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
33957
+ (0, import_node_fs42.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
33197
33958
  if (this.shareGid !== void 0) {
33198
- (0, import_node_fs40.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
33199
- (0, import_node_fs40.chmodSync)(dir, 1528);
33959
+ (0, import_node_fs42.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
33960
+ (0, import_node_fs42.chmodSync)(dir, 1528);
33200
33961
  }
33201
33962
  for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
33202
33963
  }
@@ -33225,16 +33986,16 @@ var WatchdogLog = class {
33225
33986
  const chunk = this.buffer.join("\n") + "\n";
33226
33987
  this.buffer = [];
33227
33988
  try {
33228
- if ((0, import_node_fs40.statSync)(this.file).size > ROTATE_BYTES) {
33229
- (0, import_node_fs40.renameSync)(this.file, (0, import_node_path30.join)(this.dir, ROTATED_FILE));
33989
+ if ((0, import_node_fs42.statSync)(this.file).size > ROTATE_BYTES) {
33990
+ (0, import_node_fs42.renameSync)(this.file, (0, import_node_path31.join)(this.dir, ROTATED_FILE));
33230
33991
  }
33231
33992
  } catch {
33232
33993
  }
33233
- (0, import_node_fs40.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
33994
+ (0, import_node_fs42.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
33234
33995
  if (this.shareGid !== void 0) {
33235
33996
  try {
33236
- (0, import_node_fs40.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
33237
- (0, import_node_fs40.chmodSync)(this.file, 432);
33997
+ (0, import_node_fs42.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
33998
+ (0, import_node_fs42.chmodSync)(this.file, 432);
33238
33999
  } catch {
33239
34000
  }
33240
34001
  }
@@ -33255,21 +34016,21 @@ function parseLines(text) {
33255
34016
  function readTail(file, bytes) {
33256
34017
  let fd;
33257
34018
  try {
33258
- fd = (0, import_node_fs40.openSync)(file, "r");
34019
+ fd = (0, import_node_fs42.openSync)(file, "r");
33259
34020
  } catch (err) {
33260
34021
  if (err.code === "ENOENT") return [];
33261
34022
  throw err;
33262
34023
  }
33263
34024
  try {
33264
- const size = (0, import_node_fs40.fstatSync)(fd).size;
34025
+ const size = (0, import_node_fs42.fstatSync)(fd).size;
33265
34026
  const start = Math.max(0, size - bytes);
33266
34027
  const buf = Buffer.alloc(size - start);
33267
- (0, import_node_fs40.readSync)(fd, buf, 0, buf.length, start);
34028
+ (0, import_node_fs42.readSync)(fd, buf, 0, buf.length, start);
33268
34029
  let text = buf.toString("utf8");
33269
34030
  if (start > 0) text = text.slice(text.indexOf("\n") + 1);
33270
34031
  return parseLines(text);
33271
34032
  } finally {
33272
- (0, import_node_fs40.closeSync)(fd);
34033
+ (0, import_node_fs42.closeSync)(fd);
33273
34034
  }
33274
34035
  }
33275
34036
 
@@ -33278,13 +34039,13 @@ function defaultShareGid() {
33278
34039
  const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
33279
34040
  if (!isRoot2) return void 0;
33280
34041
  try {
33281
- return (0, import_node_fs41.statSync)("/var/log/auth.log").gid;
34042
+ return (0, import_node_fs43.statSync)("/var/log/auth.log").gid;
33282
34043
  } catch {
33283
34044
  return void 0;
33284
34045
  }
33285
34046
  }
33286
34047
  function startWatchdog(opts) {
33287
- const dir = opts.config?.dir ?? (0, import_node_path31.join)(opts.stateDir, WATCHDOG_DIRNAME);
34048
+ const dir = opts.config?.dir ?? (0, import_node_path32.join)(opts.stateDir, WATCHDOG_DIRNAME);
33288
34049
  const base = { dir, logged: 0, answered: 0, errored: 0 };
33289
34050
  if (opts.config?.enabled === false) {
33290
34051
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -33375,7 +34136,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
33375
34136
  }
33376
34137
 
33377
34138
  // src/core/node-runtime.ts
33378
- var import_node_child_process16 = require("child_process");
34139
+ var import_node_child_process17 = require("child_process");
33379
34140
  var MIN_DAEMON_NODE_MAJOR = 22;
33380
34141
  function nodeMajor(version) {
33381
34142
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -33391,16 +34152,16 @@ function daemonNodeProblem(version) {
33391
34152
  // src/daemon/index.ts
33392
34153
  function readVersion2() {
33393
34154
  try {
33394
- const pkg = JSON.parse((0, import_node_fs42.readFileSync)((0, import_node_path32.join)(__dirname, "..", "package.json"), "utf-8"));
34155
+ const pkg = JSON.parse((0, import_node_fs44.readFileSync)((0, import_node_path33.join)(__dirname, "..", "package.json"), "utf-8"));
33395
34156
  return pkg.version || "0.0.0";
33396
34157
  } catch {
33397
34158
  return "0.0.0";
33398
34159
  }
33399
34160
  }
33400
34161
  async function runHardeningChecks() {
33401
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process17.execFile)(
34162
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process18.execFile)(
33402
34163
  process.execPath,
33403
- [(0, import_node_path32.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
34164
+ [(0, import_node_path33.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
33404
34165
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
33405
34166
  );
33406
34167
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -33412,9 +34173,9 @@ async function runHardeningChecks() {
33412
34173
  return patches ? [...findings, patches] : findings;
33413
34174
  }
33414
34175
  async function runPatchCheck() {
33415
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process17.execFile)(
34176
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process18.execFile)(
33416
34177
  process.execPath,
33417
- [(0, import_node_path32.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
34178
+ [(0, import_node_path33.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
33418
34179
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
33419
34180
  );
33420
34181
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -33422,7 +34183,7 @@ async function runPatchCheck() {
33422
34183
  }
33423
34184
  function logLine(line) {
33424
34185
  try {
33425
- (0, import_node_fs42.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
34186
+ (0, import_node_fs44.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
33426
34187
  `);
33427
34188
  } catch {
33428
34189
  }
@@ -33447,9 +34208,9 @@ async function runDaemon() {
33447
34208
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
33448
34209
  const restartDaemon = () => {
33449
34210
  if (PATHS.mode === "system") {
33450
- (0, import_node_child_process17.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
34211
+ (0, import_node_child_process18.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
33451
34212
  } else {
33452
- (0, import_node_child_process17.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
34213
+ (0, import_node_child_process18.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
33453
34214
  setTimeout(() => process.exit(0), 500).unref();
33454
34215
  }
33455
34216
  };
@@ -33464,7 +34225,7 @@ async function runDaemon() {
33464
34225
  } catch (err) {
33465
34226
  logLine(`[daemon] state db unavailable: ${err.message}`);
33466
34227
  }
33467
- const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path32.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
34228
+ const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path33.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
33468
34229
  const config = loaded.config;
33469
34230
  if (loaded.error) {
33470
34231
  logLine(`[daemon] CONFIG ERROR: ${loaded.error}; ${loaded.usedLastGood ? "running on the last config that parsed" : "no earlier good copy, running on DEFAULTS (no protected list)"}`);
@@ -33488,27 +34249,37 @@ async function runDaemon() {
33488
34249
  const moduleHost = new ModuleHost(bus);
33489
34250
  await moduleHost.start();
33490
34251
  const ruleEngine = new RuleEngine((detection) => {
34252
+ const ctx = detection.raw_metadata?.evidence?.ssh_context;
34253
+ const useVerdict = !!ctx?.verdict && Array.isArray(detection.raw_metadata?.tags) && detection.raw_metadata.tags.includes("ssh-login-verdict");
33491
34254
  const event = {
33492
34255
  timestamp: /* @__PURE__ */ new Date(),
33493
34256
  module: "rule-engine",
33494
34257
  category: detection.raw_metadata?.category || "system",
33495
- severity: detection.severity,
34258
+ severity: useVerdict ? ctx.verdict.severity : detection.severity,
33496
34259
  message: `[DETECTION] ${detection.title}`,
33497
34260
  source_ip: detection.source_ip,
33498
34261
  details: {
33499
34262
  rule_id: detection.rule_id,
33500
- description: detection.description,
34263
+ description: useVerdict ? [ctx.verdict.summary, describeFailures(ctx.failures, ctx.source?.ip)].filter(Boolean).join(". ") : detection.description,
33501
34264
  username: detection.username,
33502
- ...detection.raw_metadata
34265
+ ...detection.raw_metadata,
34266
+ ...useVerdict && ctx.verdict.severity !== detection.severity ? { rule_severity: detection.severity } : {}
33503
34267
  }
33504
34268
  };
33505
34269
  bus.publish(event);
33506
34270
  });
33507
34271
  ruleEngine.loadRules(loadAllRules());
33508
34272
  const keyDirectory = new KeyDirectory();
34273
+ const sshContext = new SshLoginEnricher(sshContextSettings(config.ssh_context), { stateDir: PATHS.stateDir });
34274
+ sshContext.start();
34275
+ bus.on("sshd", (line) => sshContext.recordSshd(line));
33509
34276
  bus.on("event", (event) => {
33510
34277
  if (event.module === "rule-engine") return;
33511
34278
  enrichLoginEvent(event, keyDirectory);
34279
+ if (sshContext.wants(event)) {
34280
+ void sshContext.enrich(event).finally(() => ruleEngine.evaluate(event));
34281
+ return;
34282
+ }
33512
34283
  ruleEngine.evaluate(event);
33513
34284
  });
33514
34285
  logLine(`[daemon] rule engine loaded ${ruleEngine.getRules().length} rules`);
@@ -33535,7 +34306,7 @@ async function runDaemon() {
33535
34306
  const threatFeeds = new ThreatFeeds({
33536
34307
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
33537
34308
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
33538
- cachePath: (0, import_node_path32.join)(PATHS.stateDir, "threat-feeds.json"),
34309
+ cachePath: (0, import_node_path33.join)(PATHS.stateDir, "threat-feeds.json"),
33539
34310
  bus,
33540
34311
  log: logLine
33541
34312
  });
@@ -33543,9 +34314,9 @@ async function runDaemon() {
33543
34314
  const privilegeWatch = new PrivilegeWatch({
33544
34315
  settings: privilegeSettings(config.privileged),
33545
34316
  bus,
33546
- snapshotPath: (0, import_node_path32.join)(PATHS.stateDir, "privileges.json"),
33547
- loginsPath: (0, import_node_path32.join)(PATHS.stateDir, "login-countries.json"),
33548
- cursorPath: (0, import_node_path32.join)(PATHS.stateDir, "sudo-cursor.json"),
34317
+ snapshotPath: (0, import_node_path33.join)(PATHS.stateDir, "privileges.json"),
34318
+ loginsPath: (0, import_node_path33.join)(PATHS.stateDir, "login-countries.json"),
34319
+ cursorPath: (0, import_node_path33.join)(PATHS.stateDir, "sudo-cursor.json"),
33549
34320
  log: logLine
33550
34321
  });
33551
34322
  privilegeWatch.start();
@@ -33559,8 +34330,8 @@ async function runDaemon() {
33559
34330
  const fileIntegrity = new FileIntegrityWatch({
33560
34331
  bus,
33561
34332
  settings: fileIntegritySettings(config.file_integrity),
33562
- baselinePath: (0, import_node_path32.join)(PATHS.stateDir, "file-integrity-baseline.json"),
33563
- observedPath: (0, import_node_path32.join)(PATHS.stateDir, "file-integrity-observed.json"),
34333
+ baselinePath: (0, import_node_path33.join)(PATHS.stateDir, "file-integrity-baseline.json"),
34334
+ observedPath: (0, import_node_path33.join)(PATHS.stateDir, "file-integrity-observed.json"),
33564
34335
  // `[remediation] dry_run` also covers the opt-in contain_writer response.
33565
34336
  dryRun: () => remediation.status().dry_run,
33566
34337
  log: logLine
@@ -33569,13 +34340,13 @@ async function runDaemon() {
33569
34340
  const edr = new EdrWatch({
33570
34341
  bus,
33571
34342
  settings: edrSettings(config.edr),
33572
- networkBaselinePath: (0, import_node_path32.join)(PATHS.stateDir, "edr-outbound-executables.json"),
33573
- sourceStatusPath: (0, import_node_path32.join)(PATHS.stateDir, "edr-source.json"),
34343
+ networkBaselinePath: (0, import_node_path33.join)(PATHS.stateDir, "edr-outbound-executables.json"),
34344
+ sourceStatusPath: (0, import_node_path33.join)(PATHS.stateDir, "edr-source.json"),
33574
34345
  log: logLine
33575
34346
  });
33576
34347
  edr.start();
33577
34348
  const torExits = new TorExitList({
33578
- cachePath: (0, import_node_path32.join)(PATHS.stateDir, "tor-exits.txt"),
34349
+ cachePath: (0, import_node_path33.join)(PATHS.stateDir, "tor-exits.txt"),
33579
34350
  url: config.remediation?.tor_exit_list_url,
33580
34351
  log: logLine
33581
34352
  });
@@ -33583,7 +34354,7 @@ async function runDaemon() {
33583
34354
  bus,
33584
34355
  manager: remediation,
33585
34356
  tor: torExits,
33586
- historyPath: (0, import_node_path32.join)(PATHS.stateDir, "key-logins.json"),
34357
+ historyPath: (0, import_node_path33.join)(PATHS.stateDir, "key-logins.json"),
33587
34358
  keyLoginWatch: config.privileged?.key_login_watch !== false,
33588
34359
  log: logLine
33589
34360
  });
@@ -33656,9 +34427,9 @@ async function runDaemon() {
33656
34427
  cloudSync = new CloudSync({
33657
34428
  bus,
33658
34429
  version,
33659
- hostname: (0, import_node_os6.hostname)(),
34430
+ hostname: (0, import_node_os8.hostname)(),
33660
34431
  minSeverity,
33661
- spoolPath: (0, import_node_path32.join)(PATHS.stateDir, "cloud-spool.jsonl"),
34432
+ spoolPath: (0, import_node_path33.join)(PATHS.stateDir, "cloud-spool.jsonl"),
33662
34433
  log: logLine,
33663
34434
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
33664
34435
  runHardening: runHardeningChecks
@@ -33692,8 +34463,8 @@ async function runDaemon() {
33692
34463
  const autoUpdate = autoUpdateRef = new AutoUpdate({
33693
34464
  version,
33694
34465
  settings: updateSettings(config.update),
33695
- pkgRoot: (0, import_node_path32.join)(__dirname, ".."),
33696
- statePath: (0, import_node_path32.join)(PATHS.stateDir, "auto-update.json"),
34466
+ pkgRoot: (0, import_node_path33.join)(__dirname, ".."),
34467
+ statePath: (0, import_node_path33.join)(PATHS.stateDir, "auto-update.json"),
33697
34468
  bus,
33698
34469
  log: logLine,
33699
34470
  restartDaemon