@profullstack/threatcrush 0.13.61 → 0.13.62
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 +1107 -161
- package/dist/daemon.js.map +1 -1
- package/dist/index.js +1308 -298
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/daemon.js
CHANGED
|
@@ -2026,10 +2026,10 @@ var require_toml = __commonJS({
|
|
|
2026
2026
|
});
|
|
2027
2027
|
|
|
2028
2028
|
// src/daemon/index.ts
|
|
2029
|
-
var
|
|
2030
|
-
var
|
|
2031
|
-
var
|
|
2032
|
-
var
|
|
2029
|
+
var import_node_fs34 = require("fs");
|
|
2030
|
+
var import_node_child_process12 = require("child_process");
|
|
2031
|
+
var import_node_os6 = require("os");
|
|
2032
|
+
var import_node_path26 = require("path");
|
|
2033
2033
|
var import_node_util = require("util");
|
|
2034
2034
|
|
|
2035
2035
|
// src/daemon/paths.ts
|
|
@@ -2161,6 +2161,10 @@ var EventBus = class extends import_node_events.EventEmitter {
|
|
|
2161
2161
|
this.emit("alert", event);
|
|
2162
2162
|
}
|
|
2163
2163
|
}
|
|
2164
|
+
/** A raw sshd line with a peer address; not an event, nothing is stored or uploaded. */
|
|
2165
|
+
sshdLine(line) {
|
|
2166
|
+
this.emit("sshd", line);
|
|
2167
|
+
}
|
|
2164
2168
|
announceModule(name, status, detail) {
|
|
2165
2169
|
this.emit("module", { name, status, detail });
|
|
2166
2170
|
}
|
|
@@ -2886,6 +2890,9 @@ var LogTail = class {
|
|
|
2886
2890
|
}
|
|
2887
2891
|
};
|
|
2888
2892
|
|
|
2893
|
+
// src/core/log-parser.ts
|
|
2894
|
+
var import_node_net2 = require("net");
|
|
2895
|
+
|
|
2889
2896
|
// src/core/crs/rules.generated.ts
|
|
2890
2897
|
var CRS_RULES = [
|
|
2891
2898
|
{
|
|
@@ -9577,6 +9584,29 @@ function parseAuthMessage(process3, message, timestamp, raw = message) {
|
|
|
9577
9584
|
}
|
|
9578
9585
|
};
|
|
9579
9586
|
}
|
|
9587
|
+
var ACCEPTED_REGEX = /Accepted (\S+) for (\S+) from (\S+) port (\d+)(?: [^\s:]+:\s+(\S+)\s+(SHA256:[A-Za-z0-9+/=]+))?/;
|
|
9588
|
+
function parseAcceptedLogin(message) {
|
|
9589
|
+
const m = ACCEPTED_REGEX.exec(message);
|
|
9590
|
+
if (!m) return null;
|
|
9591
|
+
return {
|
|
9592
|
+
method: m[1],
|
|
9593
|
+
user: m[2],
|
|
9594
|
+
ip: m[3],
|
|
9595
|
+
port: Number(m[4]),
|
|
9596
|
+
...m[5] ? { key_type: m[5] } : {},
|
|
9597
|
+
...m[6] ? { fingerprint: m[6] } : {}
|
|
9598
|
+
};
|
|
9599
|
+
}
|
|
9600
|
+
var SSHD_PROCESS = /^sshd(?:-session|-auth)?$/;
|
|
9601
|
+
function isSshdProcess(process3) {
|
|
9602
|
+
return !!process3 && SSHD_PROCESS.test(process3);
|
|
9603
|
+
}
|
|
9604
|
+
function sshdPeerIp(message) {
|
|
9605
|
+
const v4 = /(?<![\d.])(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?![\d.])/.exec(message);
|
|
9606
|
+
const v6 = /(?:from|by|user \S+|for connection from)\s+\[?([0-9a-fA-F]*:[0-9a-fA-F:]+)\]?/.exec(message);
|
|
9607
|
+
const cand = [v4 && { at: v4.index, ip: v4[1] }, v6 && { at: v6.index, ip: v6[1] }].filter((c) => !!c && (0, import_node_net2.isIP)(c.ip) !== 0).sort((a, b) => a.at - b.at);
|
|
9608
|
+
return cand[0]?.ip ?? null;
|
|
9609
|
+
}
|
|
9580
9610
|
function classifySshAuth(entry) {
|
|
9581
9611
|
const { ip, user, message } = entry.fields;
|
|
9582
9612
|
if (/failed password/i.test(message)) {
|
|
@@ -9586,7 +9616,14 @@ function classifySshAuth(entry) {
|
|
|
9586
9616
|
return { severity: "high", message: `Invalid SSH user: ${user || "unknown"} from ${ip || "unknown"}`, source_ip: ip };
|
|
9587
9617
|
}
|
|
9588
9618
|
if (/accepted/i.test(message)) {
|
|
9589
|
-
|
|
9619
|
+
const login = parseAcceptedLogin(message);
|
|
9620
|
+
const sourceIp = ip ?? (login && (0, import_node_net2.isIP)(login.ip) ? login.ip : void 0);
|
|
9621
|
+
return {
|
|
9622
|
+
severity: "info",
|
|
9623
|
+
message: `SSH login accepted for ${login?.user || user || "unknown"}`,
|
|
9624
|
+
source_ip: sourceIp,
|
|
9625
|
+
...login ? { details: { ssh_user: login.user, auth_method: login.method, port: login.port, ...login.key_type ? { key_type: login.key_type } : {}, ...login.fingerprint ? { fingerprint: login.fingerprint } : {} } } : {}
|
|
9626
|
+
};
|
|
9590
9627
|
}
|
|
9591
9628
|
return null;
|
|
9592
9629
|
}
|
|
@@ -9743,9 +9780,14 @@ var LogWatcher = class {
|
|
|
9743
9780
|
if (parsed.source === "auth") {
|
|
9744
9781
|
const entry = parseAuthLog(line);
|
|
9745
9782
|
if (!entry) return;
|
|
9783
|
+
if (isSshdProcess(entry.fields.process)) {
|
|
9784
|
+
const peer = sshdPeerIp(entry.fields.message);
|
|
9785
|
+
if (peer) this.bus.sshdLine?.({ timestamp: entry.timestamp, message: entry.fields.message, ip: peer, raw: line });
|
|
9786
|
+
}
|
|
9746
9787
|
const verdict = classifySshAuth(entry);
|
|
9747
9788
|
if (!verdict) return;
|
|
9748
9789
|
({ severity, message, source_ip: sourceIp } = verdict);
|
|
9790
|
+
if (verdict.details) Object.assign(details, verdict.details);
|
|
9749
9791
|
} else if (parsed.source === "nginx") {
|
|
9750
9792
|
const entry = parseNginxLog(line);
|
|
9751
9793
|
if (!entry) return;
|
|
@@ -9821,9 +9863,17 @@ function sshEventFromJournal(entry) {
|
|
|
9821
9863
|
category: "auth",
|
|
9822
9864
|
severity: verdict.severity,
|
|
9823
9865
|
message: verdict.message,
|
|
9824
|
-
source_ip: verdict.source_ip
|
|
9866
|
+
source_ip: verdict.source_ip,
|
|
9867
|
+
...verdict.details ? { details: verdict.details } : {}
|
|
9825
9868
|
};
|
|
9826
9869
|
}
|
|
9870
|
+
function sshdLineFromJournal(entry) {
|
|
9871
|
+
if (!isSshdRecord(entry) || typeof entry.MESSAGE !== "string") return null;
|
|
9872
|
+
const ip = sshdPeerIp(entry.MESSAGE);
|
|
9873
|
+
if (!ip) return null;
|
|
9874
|
+
const timestamp = realtimeToDate(entry.__REALTIME_TIMESTAMP) || /* @__PURE__ */ new Date();
|
|
9875
|
+
return { timestamp, message: entry.MESSAGE, ip, raw: entry.MESSAGE };
|
|
9876
|
+
}
|
|
9827
9877
|
var JournalWatcher = class _JournalWatcher {
|
|
9828
9878
|
constructor(bus2) {
|
|
9829
9879
|
this.bus = bus2;
|
|
@@ -9890,6 +9940,8 @@ var JournalWatcher = class _JournalWatcher {
|
|
|
9890
9940
|
child.stdout.setEncoding("utf-8");
|
|
9891
9941
|
child.stdout.on("data", (chunk) => {
|
|
9892
9942
|
this.sshdBuffer = this.drain(this.sshdBuffer + chunk, (entry) => {
|
|
9943
|
+
const line = sshdLineFromJournal(entry);
|
|
9944
|
+
if (line) this.bus.sshdLine?.(line);
|
|
9893
9945
|
const event = sshEventFromJournal(entry);
|
|
9894
9946
|
if (event) this.emit(event);
|
|
9895
9947
|
});
|
|
@@ -10244,12 +10296,12 @@ var import_node_readline = require("readline");
|
|
|
10244
10296
|
// src/core/threat-feeds/index.ts
|
|
10245
10297
|
var import_node_fs11 = require("fs");
|
|
10246
10298
|
var import_node_path5 = require("path");
|
|
10247
|
-
var
|
|
10299
|
+
var import_node_net4 = require("net");
|
|
10248
10300
|
|
|
10249
10301
|
// src/daemon/firewall/protected.ts
|
|
10250
10302
|
var import_node_child_process3 = require("child_process");
|
|
10251
10303
|
var import_node_fs10 = require("fs");
|
|
10252
|
-
var
|
|
10304
|
+
var import_node_net3 = require("net");
|
|
10253
10305
|
var DEFAULT_PROTECTED = [
|
|
10254
10306
|
"127.0.0.0/8",
|
|
10255
10307
|
"::1/128",
|
|
@@ -10293,7 +10345,7 @@ var SHARED_INFRASTRUCTURE = [
|
|
|
10293
10345
|
"208.67.220.220/32"
|
|
10294
10346
|
];
|
|
10295
10347
|
function ipToBytes(ip) {
|
|
10296
|
-
const version = (0,
|
|
10348
|
+
const version = (0, import_node_net3.isIP)(ip);
|
|
10297
10349
|
if (version === 4) return v4ToBytes(ip);
|
|
10298
10350
|
if (version === 6) return v6ToBytes(ip);
|
|
10299
10351
|
return null;
|
|
@@ -10371,7 +10423,7 @@ function currentSshClient(env2 = process.env) {
|
|
|
10371
10423
|
const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
|
|
10372
10424
|
if (!source) return null;
|
|
10373
10425
|
const ip = source.trim().split(/\s+/)[0];
|
|
10374
|
-
return ip && (0,
|
|
10426
|
+
return ip && (0, import_node_net3.isIP)(ip) ? ip : null;
|
|
10375
10427
|
}
|
|
10376
10428
|
function establishedSshPeers() {
|
|
10377
10429
|
const peers = /* @__PURE__ */ new Set();
|
|
@@ -10387,7 +10439,7 @@ function establishedSshPeers() {
|
|
|
10387
10439
|
const peer = parts[4];
|
|
10388
10440
|
if (!peer) continue;
|
|
10389
10441
|
const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
|
|
10390
|
-
if (ip && (0,
|
|
10442
|
+
if (ip && (0, import_node_net3.isIP)(ip)) peers.add(ip);
|
|
10391
10443
|
}
|
|
10392
10444
|
} catch {
|
|
10393
10445
|
}
|
|
@@ -10396,7 +10448,7 @@ function establishedSshPeers() {
|
|
|
10396
10448
|
function sshClientFromEnviron(environ) {
|
|
10397
10449
|
for (const entry of environ.split("\0")) {
|
|
10398
10450
|
const m = /^SSH_(?:CONNECTION|CLIENT)=(\S+)/.exec(entry);
|
|
10399
|
-
if (m && (0,
|
|
10451
|
+
if (m && (0, import_node_net3.isIP)(m[1])) return m[1];
|
|
10400
10452
|
}
|
|
10401
10453
|
return null;
|
|
10402
10454
|
}
|
|
@@ -10422,7 +10474,7 @@ function parseKeyLogins(text, skip = () => false) {
|
|
|
10422
10474
|
const out = /* @__PURE__ */ new Map();
|
|
10423
10475
|
for (const line of text.split("\n")) {
|
|
10424
10476
|
const m = /^(\d+(?:\.\d+)?)\s.*Accepted publickey for \S+ from (\S+) port \d+ [^\s:]+(?:: \S+ (SHA256:\S+))?/.exec(line);
|
|
10425
|
-
if (!m || !(0,
|
|
10477
|
+
if (!m || !(0, import_node_net3.isIP)(m[2])) continue;
|
|
10426
10478
|
if (m[3] && skip(m[3])) continue;
|
|
10427
10479
|
const at = Math.round(Number(m[1]) * 1e3);
|
|
10428
10480
|
if (at > (out.get(m[2]) ?? 0)) out.set(m[2], at);
|
|
@@ -10439,7 +10491,7 @@ function defaultGateways() {
|
|
|
10439
10491
|
const out = (0, import_node_child_process3.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
|
|
10440
10492
|
for (const line of out.split("\n")) {
|
|
10441
10493
|
const match = line.match(/\bvia\s+(\S+)/);
|
|
10442
|
-
if (match && (0,
|
|
10494
|
+
if (match && (0, import_node_net3.isIP)(match[1])) found.add(match[1]);
|
|
10443
10495
|
}
|
|
10444
10496
|
} catch {
|
|
10445
10497
|
}
|
|
@@ -10552,26 +10604,26 @@ function parseIpList(text, feed) {
|
|
|
10552
10604
|
const out = /* @__PURE__ */ new Map();
|
|
10553
10605
|
for (const line of text.split("\n")) {
|
|
10554
10606
|
const ip = line.trim();
|
|
10555
|
-
if (ip && !ip.startsWith("#") && (0,
|
|
10607
|
+
if (ip && !ip.startsWith("#") && (0, import_node_net4.isIP)(ip)) out.set(ip, { malware: "unknown", threat: "botnet_cc", feed });
|
|
10556
10608
|
}
|
|
10557
10609
|
return out;
|
|
10558
10610
|
}
|
|
10559
10611
|
function stripPort(value) {
|
|
10560
10612
|
const v6 = /^\[([^\]]+)\]:\d+$/.exec(value);
|
|
10561
10613
|
const ip = v6 ? v6[1] : value.replace(/:\d+$/, "");
|
|
10562
|
-
return (0,
|
|
10614
|
+
return (0, import_node_net4.isIP)(ip) ? ip : null;
|
|
10563
10615
|
}
|
|
10564
10616
|
function normalizeDomain(value) {
|
|
10565
10617
|
const d = value.trim().toLowerCase().replace(/\.$/, "");
|
|
10566
|
-
if (!d || d === "localhost" || (0,
|
|
10618
|
+
if (!d || d === "localhost" || (0, import_node_net4.isIP)(d) || !/^[a-z0-9_.-]+\.[a-z0-9-]{2,}$/.test(d)) return null;
|
|
10567
10619
|
return d;
|
|
10568
10620
|
}
|
|
10569
10621
|
function allowedDomain(domain, allow) {
|
|
10570
10622
|
return allow.some((a) => domain === a || domain.endsWith(`.${a}`));
|
|
10571
10623
|
}
|
|
10572
10624
|
function buildFeedSet(parts, allow, sources, now = /* @__PURE__ */ new Date()) {
|
|
10573
|
-
const neverIps = [...DEFAULT_PROTECTED, ...SHARED_RANGES, ...allow.filter((a) => (0,
|
|
10574
|
-
const allowDomains = allow.filter((a) => !(0,
|
|
10625
|
+
const neverIps = [...DEFAULT_PROTECTED, ...SHARED_RANGES, ...allow.filter((a) => (0, import_node_net4.isIP)(a.split("/")[0]))];
|
|
10626
|
+
const allowDomains = allow.filter((a) => !(0, import_node_net4.isIP)(a.split("/")[0])).map((a) => a.toLowerCase());
|
|
10575
10627
|
const ips = {};
|
|
10576
10628
|
const domains = {};
|
|
10577
10629
|
let skipped = 0;
|
|
@@ -11043,6 +11095,7 @@ function loadConfig(configPath) {
|
|
|
11043
11095
|
update: parsed.update,
|
|
11044
11096
|
threat_feeds: parsed.threat_feeds,
|
|
11045
11097
|
privileged: parsed.privileged,
|
|
11098
|
+
lightning: parsed.lightning,
|
|
11046
11099
|
storage: parsed.storage,
|
|
11047
11100
|
// TOML's `[abuse-reporter]` parses to a hyphenated key; expose it under
|
|
11048
11101
|
// the JS-friendly name the rest of the daemon reads.
|
|
@@ -11478,11 +11531,55 @@ function pagerdutyChannel(config) {
|
|
|
11478
11531
|
};
|
|
11479
11532
|
}
|
|
11480
11533
|
|
|
11534
|
+
// src/daemon/alerts/smshub.ts
|
|
11535
|
+
var import_node_os2 = require("os");
|
|
11536
|
+
var SEVERITY_RANK4 = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
|
|
11537
|
+
var DEDUPE_MS = 10 * 6e4;
|
|
11538
|
+
var MAX_PER_HOUR = 6;
|
|
11539
|
+
function smshubText(event, host = (0, import_node_os2.hostname)()) {
|
|
11540
|
+
const evidence = event.details?.evidence?.message;
|
|
11541
|
+
const text = `ThreatCrush ${event.severity.toUpperCase()} on ${host}: ${event.message}${evidence && !event.message.includes(evidence) ? ` | ${evidence}` : ""}`;
|
|
11542
|
+
return text.replace(/\s+/g, " ").slice(0, 600);
|
|
11543
|
+
}
|
|
11544
|
+
function smshubChannel(config, opts = {}) {
|
|
11545
|
+
const sent = /* @__PURE__ */ new Map();
|
|
11546
|
+
const recent = [];
|
|
11547
|
+
const now = opts.now ?? Date.now;
|
|
11548
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
11549
|
+
return async (event) => {
|
|
11550
|
+
const key = config.api_key || (config.api_key_env ? process.env[config.api_key_env] : void 0) || process.env.SMSHUB_ALERT_API_KEY;
|
|
11551
|
+
if (!key) return;
|
|
11552
|
+
if ((SEVERITY_RANK4[event.severity] ?? 0) < (SEVERITY_RANK4[config.min_severity ?? "critical"] ?? 4)) return;
|
|
11553
|
+
if (config.fallback_only !== false && opts.cloudHealthy?.()) return;
|
|
11554
|
+
const message = smshubText(event);
|
|
11555
|
+
const at = now();
|
|
11556
|
+
const dedupe2 = `${event.details?.rule_id ?? event.module}|${event.source_ip ?? ""}|${event.details?.fingerprint ?? ""}`;
|
|
11557
|
+
if (at - (sent.get(dedupe2) ?? 0) < DEDUPE_MS) return;
|
|
11558
|
+
while (recent.length && recent[0] < at - 36e5) recent.shift();
|
|
11559
|
+
if (recent.length >= MAX_PER_HOUR) return;
|
|
11560
|
+
sent.set(dedupe2, at);
|
|
11561
|
+
recent.push(at);
|
|
11562
|
+
const base = (config.url || "https://smshub.dev").replace(/\/$/, "");
|
|
11563
|
+
try {
|
|
11564
|
+
const res = await doFetch(`${base}/api/v1/alerts`, {
|
|
11565
|
+
method: "POST",
|
|
11566
|
+
headers: { "X-API-Key": key, "Content-Type": "application/json", "User-Agent": "threatcrush-daemon" },
|
|
11567
|
+
body: JSON.stringify({ message, severity: event.severity === "critical" ? "critical" : "warning", ...config.to ? { to: config.to } : {} }),
|
|
11568
|
+
signal: AbortSignal.timeout(15e3)
|
|
11569
|
+
});
|
|
11570
|
+
opts.log?.(`[alerts] smshub ${res.ok ? "paged" : `failed HTTP ${res.status}`}: ${message.slice(0, 160)}`);
|
|
11571
|
+
} catch (err) {
|
|
11572
|
+
opts.log?.(`[alerts] smshub failed: ${err.message}`);
|
|
11573
|
+
}
|
|
11574
|
+
};
|
|
11575
|
+
}
|
|
11576
|
+
|
|
11481
11577
|
// src/daemon/alerts/index.ts
|
|
11482
11578
|
var AlertDispatcher = class {
|
|
11483
|
-
constructor(bus2, config) {
|
|
11579
|
+
constructor(bus2, config, hooks = {}) {
|
|
11484
11580
|
this.bus = bus2;
|
|
11485
11581
|
this.config = config;
|
|
11582
|
+
this.hooks = hooks;
|
|
11486
11583
|
this.bindChannels();
|
|
11487
11584
|
bus2.on("alert", (event) => {
|
|
11488
11585
|
void this.dispatch(event);
|
|
@@ -11490,6 +11587,7 @@ var AlertDispatcher = class {
|
|
|
11490
11587
|
}
|
|
11491
11588
|
bus;
|
|
11492
11589
|
config;
|
|
11590
|
+
hooks;
|
|
11493
11591
|
channels = [];
|
|
11494
11592
|
rateLimits = /* @__PURE__ */ new Map();
|
|
11495
11593
|
bindChannels() {
|
|
@@ -11509,6 +11607,9 @@ var AlertDispatcher = class {
|
|
|
11509
11607
|
if (name === "discord" && typeof cfg.webhook_url === "string") {
|
|
11510
11608
|
this.channels.push(discordChannel(cfg));
|
|
11511
11609
|
}
|
|
11610
|
+
if (name === "smshub") {
|
|
11611
|
+
this.channels.push(smshubChannel(cfg, this.hooks));
|
|
11612
|
+
}
|
|
11512
11613
|
if (name === "pagerduty" && typeof cfg.routing_key === "string") {
|
|
11513
11614
|
this.channels.push(pagerdutyChannel(cfg));
|
|
11514
11615
|
}
|
|
@@ -11556,14 +11657,14 @@ function slackChannel(webhookUrl) {
|
|
|
11556
11657
|
// src/daemon/workers/runs-worker.ts
|
|
11557
11658
|
var import_promises = require("dns/promises");
|
|
11558
11659
|
var import_node_fs20 = require("fs");
|
|
11559
|
-
var
|
|
11660
|
+
var import_node_net6 = require("net");
|
|
11560
11661
|
var import_node_path14 = require("path");
|
|
11561
11662
|
|
|
11562
11663
|
// src/core/cli-config.ts
|
|
11563
11664
|
var import_node_fs15 = require("fs");
|
|
11564
11665
|
var import_node_path8 = require("path");
|
|
11565
|
-
var
|
|
11566
|
-
var CLI_CONFIG_DIR = (0, import_node_path8.join)((0,
|
|
11666
|
+
var import_node_os3 = require("os");
|
|
11667
|
+
var CLI_CONFIG_DIR = (0, import_node_path8.join)((0, import_node_os3.homedir)(), ".threatcrush");
|
|
11567
11668
|
var CLI_CONFIG_PATH = (0, import_node_path8.join)(CLI_CONFIG_DIR, "config.json");
|
|
11568
11669
|
function apiUrl() {
|
|
11569
11670
|
return process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
|
|
@@ -11656,14 +11757,14 @@ async function cloudFetch(path, init = {}) {
|
|
|
11656
11757
|
|
|
11657
11758
|
// src/core/cloud-events.ts
|
|
11658
11759
|
var import_node_crypto3 = require("crypto");
|
|
11659
|
-
var
|
|
11760
|
+
var import_node_net5 = require("net");
|
|
11660
11761
|
function currentLink() {
|
|
11661
11762
|
if (!hasSession()) return null;
|
|
11662
11763
|
const cfg = readCliConfig();
|
|
11663
11764
|
if (!cfg.server_id || !cfg.server_org_id) return null;
|
|
11664
11765
|
return { serverId: cfg.server_id, orgId: cfg.server_org_id };
|
|
11665
11766
|
}
|
|
11666
|
-
var
|
|
11767
|
+
var SEVERITY_RANK5 = {
|
|
11667
11768
|
info: 0,
|
|
11668
11769
|
low: 1,
|
|
11669
11770
|
medium: 2,
|
|
@@ -11723,7 +11824,7 @@ function detectionEvent(serverId, event) {
|
|
|
11723
11824
|
title: title.slice(0, MAX_TITLE_CHARS) || event.module,
|
|
11724
11825
|
rule_id: str(rule_id) ?? event.module,
|
|
11725
11826
|
description: str(description),
|
|
11726
|
-
source_ip: event.source_ip && (0,
|
|
11827
|
+
source_ip: event.source_ip && (0, import_node_net5.isIP)(event.source_ip) ? event.source_ip : void 0,
|
|
11727
11828
|
username: str(username) ?? str(user),
|
|
11728
11829
|
raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
|
|
11729
11830
|
detected_at: event.timestamp.toISOString()
|
|
@@ -12022,7 +12123,7 @@ var ansi_styles_default = ansiStyles;
|
|
|
12022
12123
|
|
|
12023
12124
|
// ../../node_modules/.pnpm/chalk@6.0.1/node_modules/chalk/source/vendor/supports-color/index.js
|
|
12024
12125
|
var import_node_process = __toESM(require("process"), 1);
|
|
12025
|
-
var
|
|
12126
|
+
var import_node_os4 = __toESM(require("os"), 1);
|
|
12026
12127
|
var import_node_tty = __toESM(require("tty"), 1);
|
|
12027
12128
|
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
|
|
12028
12129
|
const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
|
|
@@ -12097,7 +12198,7 @@ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
|
|
|
12097
12198
|
return min;
|
|
12098
12199
|
}
|
|
12099
12200
|
if (import_node_process.default.platform === "win32") {
|
|
12100
|
-
const osRelease =
|
|
12201
|
+
const osRelease = import_node_os4.default.release().split(".");
|
|
12101
12202
|
if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
|
|
12102
12203
|
return Number(osRelease[2]) >= 14931 ? 3 : 2;
|
|
12103
12204
|
}
|
|
@@ -12362,7 +12463,7 @@ var LEVEL_COLORS = {
|
|
|
12362
12463
|
};
|
|
12363
12464
|
|
|
12364
12465
|
// src/core/run-result.ts
|
|
12365
|
-
var
|
|
12466
|
+
var import_node_os5 = __toESM(require("os"));
|
|
12366
12467
|
function emptyCounts() {
|
|
12367
12468
|
return { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
|
|
12368
12469
|
}
|
|
@@ -12372,7 +12473,7 @@ function summarize(findings) {
|
|
|
12372
12473
|
return counts;
|
|
12373
12474
|
}
|
|
12374
12475
|
function workerId() {
|
|
12375
|
-
return `${
|
|
12476
|
+
return `${import_node_os5.default.hostname()}/${process.pid}`;
|
|
12376
12477
|
}
|
|
12377
12478
|
|
|
12378
12479
|
// ../../packages/scan/src/node-rules.ts
|
|
@@ -16078,7 +16179,7 @@ var NOT_PUBLIC = [
|
|
|
16078
16179
|
"ff00::/8"
|
|
16079
16180
|
];
|
|
16080
16181
|
function isPublicTarget(ip) {
|
|
16081
|
-
return (0,
|
|
16182
|
+
return (0, import_node_net6.isIP)(ip) !== 0 && !isProtected(ip, NOT_PUBLIC);
|
|
16082
16183
|
}
|
|
16083
16184
|
async function pentestTargetError(rawUrl, resolveHost = async (h) => (await (0, import_promises.lookup)(h, { all: true })).map((a) => a.address)) {
|
|
16084
16185
|
let url;
|
|
@@ -16091,7 +16192,7 @@ async function pentestTargetError(rawUrl, resolveHost = async (h) => (await (0,
|
|
|
16091
16192
|
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
16092
16193
|
let addresses;
|
|
16093
16194
|
try {
|
|
16094
|
-
addresses = (0,
|
|
16195
|
+
addresses = (0, import_node_net6.isIP)(host) ? [host] : await resolveHost(host);
|
|
16095
16196
|
} catch (err) {
|
|
16096
16197
|
return `cannot resolve ${host}: ${err.message}`;
|
|
16097
16198
|
}
|
|
@@ -16415,6 +16516,7 @@ var CloudSync = class {
|
|
|
16415
16516
|
retryAt = 0;
|
|
16416
16517
|
link = null;
|
|
16417
16518
|
lastProblem = "";
|
|
16519
|
+
lastOkAt = 0;
|
|
16418
16520
|
onEvent = (event) => this.capture(event);
|
|
16419
16521
|
start() {
|
|
16420
16522
|
this.link = currentLink();
|
|
@@ -16447,6 +16549,10 @@ var CloudSync = class {
|
|
|
16447
16549
|
get queued() {
|
|
16448
16550
|
return this.spool.size;
|
|
16449
16551
|
}
|
|
16552
|
+
/** Linked, and the dashboard accepted an upload or heartbeat in the last 3 minutes. */
|
|
16553
|
+
get healthy() {
|
|
16554
|
+
return !!this.link && !this.lastProblem && Date.now() - this.lastOkAt < 18e4;
|
|
16555
|
+
}
|
|
16450
16556
|
/** Queue hardening results for upload (the CLI posts its own directly). */
|
|
16451
16557
|
enqueueFindings(results) {
|
|
16452
16558
|
const link = this.refreshLink();
|
|
@@ -16471,7 +16577,7 @@ var CloudSync = class {
|
|
|
16471
16577
|
let out = null;
|
|
16472
16578
|
if (event.module === "firewall-rules") {
|
|
16473
16579
|
out = remediationEvent(link.serverId, event);
|
|
16474
|
-
} else if ((event.module === "rule-engine" || !this.opts.ruleModules.has(event.module)) && event.details?.heartbeat !== true &&
|
|
16580
|
+
} 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]) {
|
|
16475
16581
|
out = detectionEvent(link.serverId, event);
|
|
16476
16582
|
}
|
|
16477
16583
|
if (!out) return;
|
|
@@ -16519,6 +16625,7 @@ var CloudSync = class {
|
|
|
16519
16625
|
this.backoffMs = 0;
|
|
16520
16626
|
this.retryAt = 0;
|
|
16521
16627
|
this.lastProblem = "";
|
|
16628
|
+
this.lastOkAt = Date.now();
|
|
16522
16629
|
return "sent";
|
|
16523
16630
|
}
|
|
16524
16631
|
if (res.status === 401) {
|
|
@@ -16563,6 +16670,7 @@ var CloudSync = class {
|
|
|
16563
16670
|
};
|
|
16564
16671
|
try {
|
|
16565
16672
|
const res = await cloudFetch("/api/ingest", { method: "POST", body: JSON.stringify({ events: [event] }) });
|
|
16673
|
+
if (res.ok) this.lastOkAt = Date.now();
|
|
16566
16674
|
if (res.ok && this.retryAt > 0) {
|
|
16567
16675
|
this.retryAt = 0;
|
|
16568
16676
|
void this.flush();
|
|
@@ -16586,7 +16694,7 @@ var CloudSync = class {
|
|
|
16586
16694
|
var import_node_crypto5 = require("crypto");
|
|
16587
16695
|
|
|
16588
16696
|
// src/daemon/workers/abuse-evidence.ts
|
|
16589
|
-
var
|
|
16697
|
+
var import_node_net7 = require("net");
|
|
16590
16698
|
var NEVER_REPORT_RANGES = [
|
|
16591
16699
|
...DEFAULT_PROTECTED,
|
|
16592
16700
|
"100.64.0.0/10",
|
|
@@ -16662,7 +16770,7 @@ function summarizeEvidence(events) {
|
|
|
16662
16770
|
};
|
|
16663
16771
|
}
|
|
16664
16772
|
function isReportable(ip, evidence, config, now = Date.now()) {
|
|
16665
|
-
if ((0,
|
|
16773
|
+
if ((0, import_node_net7.isIP)(ip) === 0) return { reportable: false, reason: "not an IP address" };
|
|
16666
16774
|
if (isProtected(ip, config.neverReport)) {
|
|
16667
16775
|
return { reportable: false, reason: "address is in a never-report range (private/CGNAT/reserved/allowlisted)" };
|
|
16668
16776
|
}
|
|
@@ -16993,13 +17101,13 @@ var AbuseReporter = class {
|
|
|
16993
17101
|
};
|
|
16994
17102
|
|
|
16995
17103
|
// src/daemon/workers/remediation-consumer.ts
|
|
16996
|
-
var
|
|
17104
|
+
var import_node_net9 = require("net");
|
|
16997
17105
|
|
|
16998
17106
|
// src/daemon/workers/allowlist-sync.ts
|
|
16999
|
-
var
|
|
17107
|
+
var import_node_net8 = require("net");
|
|
17000
17108
|
function isAddressOrCidr(value) {
|
|
17001
17109
|
const [network, prefix, extra] = value.split("/");
|
|
17002
|
-
const family = (0,
|
|
17110
|
+
const family = (0, import_node_net8.isIP)(network);
|
|
17003
17111
|
if (family === 0 || extra !== void 0) return false;
|
|
17004
17112
|
if (prefix === void 0) return true;
|
|
17005
17113
|
if (!/^\d{1,3}$/.test(prefix)) return false;
|
|
@@ -17010,7 +17118,7 @@ function isCloudAllowEntry(value) {
|
|
|
17010
17118
|
if (!isAddressOrCidr(value)) return false;
|
|
17011
17119
|
const [network, prefix] = value.split("/");
|
|
17012
17120
|
if (prefix === void 0) return true;
|
|
17013
|
-
return Number(prefix) >= CLOUD_MIN_PREFIX[(0,
|
|
17121
|
+
return Number(prefix) >= CLOUD_MIN_PREFIX[(0, import_node_net8.isIP)(network)];
|
|
17014
17122
|
}
|
|
17015
17123
|
var AllowlistSync = class {
|
|
17016
17124
|
constructor(manager, opts) {
|
|
@@ -17033,6 +17141,17 @@ var AllowlistSync = class {
|
|
|
17033
17141
|
async sync() {
|
|
17034
17142
|
const link = currentLink();
|
|
17035
17143
|
if (!link) return;
|
|
17144
|
+
if (this.opts.onOrgSettings) {
|
|
17145
|
+
try {
|
|
17146
|
+
const res = await cloudFetch(`/api/orgs/${link.orgId}`);
|
|
17147
|
+
if (res.ok) {
|
|
17148
|
+
const data = await res.json();
|
|
17149
|
+
const v = data.organization?.block_tor_ssh;
|
|
17150
|
+
if (typeof v === "boolean") this.opts.onOrgSettings({ block_tor_ssh: v });
|
|
17151
|
+
}
|
|
17152
|
+
} catch {
|
|
17153
|
+
}
|
|
17154
|
+
}
|
|
17036
17155
|
let entries;
|
|
17037
17156
|
try {
|
|
17038
17157
|
const res = await cloudFetch(`/api/orgs/${link.orgId}/allowlists`);
|
|
@@ -17048,7 +17167,7 @@ var AllowlistSync = class {
|
|
|
17048
17167
|
if (entry.type !== "ip" && entry.type !== "cidr") continue;
|
|
17049
17168
|
const value = String(entry.value ?? "").trim();
|
|
17050
17169
|
if (isCloudAllowEntry(value)) wanted.add(value);
|
|
17051
|
-
else if (isAddressOrCidr(value)) this.opts.log(`[cloud] org allowlist: ignoring ${value} (wider than /${CLOUD_MIN_PREFIX[(0,
|
|
17170
|
+
else if (isAddressOrCidr(value)) this.opts.log(`[cloud] org allowlist: ignoring ${value} (wider than /${CLOUD_MIN_PREFIX[(0, import_node_net8.isIP)(value.split("/")[0])]})`);
|
|
17052
17171
|
}
|
|
17053
17172
|
const added2 = [];
|
|
17054
17173
|
const protectedNow = new Set(this.manager.getProtected());
|
|
@@ -17156,7 +17275,7 @@ var RemediationConsumer = class {
|
|
|
17156
17275
|
try {
|
|
17157
17276
|
switch (action.action_type) {
|
|
17158
17277
|
case "block": {
|
|
17159
|
-
if ((0,
|
|
17278
|
+
if ((0, import_node_net9.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
|
|
17160
17279
|
let ttlSeconds = this.manager.status().max_ban_seconds;
|
|
17161
17280
|
if (action.expires_at) {
|
|
17162
17281
|
const until = Date.parse(action.expires_at);
|
|
@@ -17175,7 +17294,7 @@ var RemediationConsumer = class {
|
|
|
17175
17294
|
return { status: "executed", dry_run: result.entry?.dry_run === true, executed_at };
|
|
17176
17295
|
}
|
|
17177
17296
|
case "unblock": {
|
|
17178
|
-
if ((0,
|
|
17297
|
+
if ((0, import_node_net9.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
|
|
17179
17298
|
const wasBanned = this.manager.getBlocklist().some((b) => b.ip === target);
|
|
17180
17299
|
const result = await this.manager.unban(target, {
|
|
17181
17300
|
forget: true,
|
|
@@ -17479,7 +17598,7 @@ var AutoUpdate = class {
|
|
|
17479
17598
|
var import_node_child_process6 = require("child_process");
|
|
17480
17599
|
var import_node_fs24 = require("fs");
|
|
17481
17600
|
var import_node_path18 = require("path");
|
|
17482
|
-
var
|
|
17601
|
+
var import_node_net10 = require("net");
|
|
17483
17602
|
var EGRESS_TABLE = "threatcrush_egress";
|
|
17484
17603
|
var DEFAULT_REFRESH_MS = 36e5;
|
|
17485
17604
|
var POLL_MS = 15e3;
|
|
@@ -17497,8 +17616,8 @@ function threatFeedSettings(section) {
|
|
|
17497
17616
|
};
|
|
17498
17617
|
}
|
|
17499
17618
|
function egressRuleset(ips) {
|
|
17500
|
-
const v4 = ips.filter((ip) => (0,
|
|
17501
|
-
const v6 = ips.filter((ip) => (0,
|
|
17619
|
+
const v4 = ips.filter((ip) => (0, import_node_net10.isIP)(ip) === 4);
|
|
17620
|
+
const v6 = ips.filter((ip) => (0, import_node_net10.isIP)(ip) === 6);
|
|
17502
17621
|
const set = (name, type, items) => ` set ${name} { type ${type};${items.length ? ` elements = { ${items.join(", ")} }` : ""} }`;
|
|
17503
17622
|
const chain = (name, hook) => [
|
|
17504
17623
|
` chain ${name} {`,
|
|
@@ -17523,7 +17642,7 @@ function splitAddr(addr) {
|
|
|
17523
17642
|
const m = /^\[?(.+?)\]?:(\d+|\*)$/.exec(addr);
|
|
17524
17643
|
if (!m) return null;
|
|
17525
17644
|
const ip = m[1].replace(/%.*$/, "").replace(/^::ffff:/i, "");
|
|
17526
|
-
return (0,
|
|
17645
|
+
return (0, import_node_net10.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
|
|
17527
17646
|
}
|
|
17528
17647
|
function parseSs(text) {
|
|
17529
17648
|
const out = [];
|
|
@@ -17911,7 +18030,42 @@ function parseSudoMessage(message) {
|
|
|
17911
18030
|
|
|
17912
18031
|
// src/daemon/workers/privilege-watch.ts
|
|
17913
18032
|
function privilegeSettings(section) {
|
|
17914
|
-
return {
|
|
18033
|
+
return {
|
|
18034
|
+
enabled: section?.enabled !== false,
|
|
18035
|
+
geo: section?.geo !== false,
|
|
18036
|
+
pollMs: 6e4,
|
|
18037
|
+
expectedKeys: Array.isArray(section?.expected_keys) ? section.expected_keys.map(String).filter(Boolean) : [],
|
|
18038
|
+
watchFiles: true
|
|
18039
|
+
};
|
|
18040
|
+
}
|
|
18041
|
+
function keyIsExpected(fingerprint, comment, expected) {
|
|
18042
|
+
return expected.some((pattern) => {
|
|
18043
|
+
if (pattern.startsWith("SHA256:")) return pattern === fingerprint;
|
|
18044
|
+
const re = new RegExp(`^${pattern.split("*").map((p) => p.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "i");
|
|
18045
|
+
return re.test(comment);
|
|
18046
|
+
});
|
|
18047
|
+
}
|
|
18048
|
+
var SELFTEST_KEY_COMMENT = "threatcrush-selftest";
|
|
18049
|
+
function classifyKeyAddition(change, expected) {
|
|
18050
|
+
if (change.details.rule_id !== "priv-authorized-key-added") return change;
|
|
18051
|
+
const fp = String(change.details.fingerprint ?? "");
|
|
18052
|
+
const comment = String(change.details.comment ?? "");
|
|
18053
|
+
const account = String(change.details.account ?? "?");
|
|
18054
|
+
if (comment.includes(SELFTEST_KEY_COMMENT)) {
|
|
18055
|
+
return {
|
|
18056
|
+
severity: "critical",
|
|
18057
|
+
message: `[TEST] ThreatCrush self-test: new SSH key for ${account} detected (${fp}, ${comment}). This is a test, nothing is wrong.`,
|
|
18058
|
+
details: { ...change.details, rule_id: "priv-authorized-key-selftest", selftest: true }
|
|
18059
|
+
};
|
|
18060
|
+
}
|
|
18061
|
+
if (keyIsExpected(fp, comment, expected)) {
|
|
18062
|
+
return { ...change, severity: "high", details: { ...change.details, expected: true } };
|
|
18063
|
+
}
|
|
18064
|
+
return {
|
|
18065
|
+
severity: "critical",
|
|
18066
|
+
message: `New SSH key added for ${account}: ${change.details.key_type ?? ""} ${fp}${comment ? ` "${comment}"` : " (no comment)"}, not an expected key; whoever holds it can log in`,
|
|
18067
|
+
details: { ...change.details, expected: false }
|
|
18068
|
+
};
|
|
17915
18069
|
}
|
|
17916
18070
|
var COUNTRY_NAMES = new Intl.DisplayNames(["en"], { type: "region" });
|
|
17917
18071
|
function countryName(code) {
|
|
@@ -18009,6 +18163,8 @@ var PrivilegeWatch = class {
|
|
|
18009
18163
|
run;
|
|
18010
18164
|
now;
|
|
18011
18165
|
warnedUnreadable = false;
|
|
18166
|
+
watchers = /* @__PURE__ */ new Map();
|
|
18167
|
+
debounce = null;
|
|
18012
18168
|
onEvent = (event) => {
|
|
18013
18169
|
void this.checkLogin(event);
|
|
18014
18170
|
};
|
|
@@ -18023,9 +18179,11 @@ var PrivilegeWatch = class {
|
|
|
18023
18179
|
this.opts.bus.on("event", this.onEvent);
|
|
18024
18180
|
void this.backfillLogins();
|
|
18025
18181
|
}
|
|
18182
|
+
if (this.opts.settings.watchFiles) this.watchKeyDirs();
|
|
18026
18183
|
const timer = setInterval(() => {
|
|
18027
18184
|
this.checkSnapshot();
|
|
18028
18185
|
this.readSudoLedger();
|
|
18186
|
+
if (this.opts.settings.watchFiles) this.watchKeyDirs();
|
|
18029
18187
|
}, this.opts.settings.pollMs);
|
|
18030
18188
|
timer.unref?.();
|
|
18031
18189
|
this.timers.push(timer);
|
|
@@ -18033,8 +18191,55 @@ var PrivilegeWatch = class {
|
|
|
18033
18191
|
stop() {
|
|
18034
18192
|
for (const t of this.timers) clearInterval(t);
|
|
18035
18193
|
this.timers = [];
|
|
18194
|
+
for (const w of this.watchers.values()) {
|
|
18195
|
+
try {
|
|
18196
|
+
w.close();
|
|
18197
|
+
} catch {
|
|
18198
|
+
}
|
|
18199
|
+
}
|
|
18200
|
+
this.watchers.clear();
|
|
18201
|
+
if (this.debounce) clearTimeout(this.debounce);
|
|
18036
18202
|
this.opts.bus.off("event", this.onEvent);
|
|
18037
18203
|
}
|
|
18204
|
+
/**
|
|
18205
|
+
* inotify on every login account's ~/.ssh (and /root/.ssh): a write there
|
|
18206
|
+
* re-checks the snapshot within a second, not at the next minute's poll.
|
|
18207
|
+
* Re-run each poll so a directory created later is picked up.
|
|
18208
|
+
*/
|
|
18209
|
+
watchKeyDirs() {
|
|
18210
|
+
const dirs = /* @__PURE__ */ new Set();
|
|
18211
|
+
for (const line of (this.io.readFile("/etc/passwd") ?? "").split("\n")) {
|
|
18212
|
+
const f = line.split(":");
|
|
18213
|
+
if (f.length < 7) continue;
|
|
18214
|
+
const uid = Number(f[2]);
|
|
18215
|
+
const home = f[5];
|
|
18216
|
+
if (!home || home === "/" || uid !== 0 && /(nologin|\/false)$/.test(f[6].trim())) continue;
|
|
18217
|
+
dirs.add(`${home.replace(/\/$/, "")}/.ssh`);
|
|
18218
|
+
}
|
|
18219
|
+
for (const dir of dirs) {
|
|
18220
|
+
if (this.watchers.has(dir) || !this.io.exists(dir)) continue;
|
|
18221
|
+
try {
|
|
18222
|
+
const w = (0, import_node_fs25.watch)(dir, { persistent: false }, (_type2, name) => {
|
|
18223
|
+
if (name && !String(name).startsWith("authorized_keys")) return;
|
|
18224
|
+
if (this.debounce) clearTimeout(this.debounce);
|
|
18225
|
+
this.debounce = setTimeout(() => {
|
|
18226
|
+
this.debounce = null;
|
|
18227
|
+
this.checkSnapshot();
|
|
18228
|
+
}, 750);
|
|
18229
|
+
this.debounce.unref?.();
|
|
18230
|
+
});
|
|
18231
|
+
w.on("error", () => {
|
|
18232
|
+
try {
|
|
18233
|
+
w.close();
|
|
18234
|
+
} catch {
|
|
18235
|
+
}
|
|
18236
|
+
this.watchers.delete(dir);
|
|
18237
|
+
});
|
|
18238
|
+
this.watchers.set(dir, w);
|
|
18239
|
+
} catch {
|
|
18240
|
+
}
|
|
18241
|
+
}
|
|
18242
|
+
}
|
|
18038
18243
|
emit(severity, message, details) {
|
|
18039
18244
|
const event = { timestamp: this.now(), module: "privileged-access", category: "auth", severity, message, details };
|
|
18040
18245
|
try {
|
|
@@ -18054,7 +18259,16 @@ var PrivilegeWatch = class {
|
|
|
18054
18259
|
const keys = Object.values(next.keys).reduce((n, k) => n + Object.keys(k).length, 0);
|
|
18055
18260
|
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)`);
|
|
18056
18261
|
} else {
|
|
18057
|
-
for (const
|
|
18262
|
+
for (const raw of diffSnapshots(prev, next)) {
|
|
18263
|
+
const change = classifyKeyAddition(raw, this.opts.settings.expectedKeys ?? []);
|
|
18264
|
+
if (change.details.rule_id === "priv-authorized-key-added" || change.details.rule_id === "priv-authorized-key-selftest") {
|
|
18265
|
+
this.opts.log(`[privileged] ${change.severity.toUpperCase()} ${change.message}`);
|
|
18266
|
+
}
|
|
18267
|
+
this.emit(change.severity, change.message, {
|
|
18268
|
+
...change.details,
|
|
18269
|
+
evidence: { at: this.now().toISOString(), module: "privileged-access", message: change.message.slice(0, 500) }
|
|
18270
|
+
});
|
|
18271
|
+
}
|
|
18058
18272
|
}
|
|
18059
18273
|
try {
|
|
18060
18274
|
writeJson(this.opts.snapshotPath, next);
|
|
@@ -18168,6 +18382,636 @@ var PrivilegeWatch = class {
|
|
|
18168
18382
|
}
|
|
18169
18383
|
};
|
|
18170
18384
|
|
|
18385
|
+
// src/daemon/workers/ssh-intrusion.ts
|
|
18386
|
+
var import_node_fs26 = require("fs");
|
|
18387
|
+
var import_node_path20 = require("path");
|
|
18388
|
+
var import_node_child_process8 = require("child_process");
|
|
18389
|
+
|
|
18390
|
+
// src/core/asn.ts
|
|
18391
|
+
var import_node_dns = require("dns");
|
|
18392
|
+
var import_node_net11 = require("net");
|
|
18393
|
+
var CI_ASNS = /* @__PURE__ */ new Set([8075, 36459, 8068, 8069, 12076]);
|
|
18394
|
+
var HOSTING_ASNS = /* @__PURE__ */ new Set([
|
|
18395
|
+
15169,
|
|
18396
|
+
396982,
|
|
18397
|
+
19527,
|
|
18398
|
+
// Google, Google Cloud
|
|
18399
|
+
16509,
|
|
18400
|
+
14618,
|
|
18401
|
+
// Amazon / AWS
|
|
18402
|
+
16276,
|
|
18403
|
+
// OVH
|
|
18404
|
+
24940,
|
|
18405
|
+
213230,
|
|
18406
|
+
// Hetzner
|
|
18407
|
+
14061,
|
|
18408
|
+
// DigitalOcean
|
|
18409
|
+
63949,
|
|
18410
|
+
// Linode / Akamai
|
|
18411
|
+
20473,
|
|
18412
|
+
// Vultr (Choopa)
|
|
18413
|
+
12876,
|
|
18414
|
+
// Scaleway
|
|
18415
|
+
51167,
|
|
18416
|
+
// Contabo
|
|
18417
|
+
31898,
|
|
18418
|
+
// Oracle Cloud
|
|
18419
|
+
45102,
|
|
18420
|
+
// Alibaba
|
|
18421
|
+
132203,
|
|
18422
|
+
45090,
|
|
18423
|
+
// Tencent
|
|
18424
|
+
36352,
|
|
18425
|
+
// ColoCrossing
|
|
18426
|
+
53667,
|
|
18427
|
+
// FranTech / BuyVM
|
|
18428
|
+
197540,
|
|
18429
|
+
// netcup
|
|
18430
|
+
9009,
|
|
18431
|
+
// M247
|
|
18432
|
+
60068,
|
|
18433
|
+
// Datacamp / CDN77
|
|
18434
|
+
212238,
|
|
18435
|
+
// Datacamp
|
|
18436
|
+
202425,
|
|
18437
|
+
// IP Volume
|
|
18438
|
+
210644,
|
|
18439
|
+
// Aeza
|
|
18440
|
+
49981,
|
|
18441
|
+
// WorldStream
|
|
18442
|
+
62240,
|
|
18443
|
+
// Clouvider
|
|
18444
|
+
136907,
|
|
18445
|
+
// Huawei Cloud
|
|
18446
|
+
8100,
|
|
18447
|
+
// QuadraNet
|
|
18448
|
+
46606,
|
|
18449
|
+
// Unified Layer
|
|
18450
|
+
29802,
|
|
18451
|
+
// HVC
|
|
18452
|
+
40021,
|
|
18453
|
+
// Contabo US / Nubes
|
|
18454
|
+
398324,
|
|
18455
|
+
399629
|
|
18456
|
+
// Censys and friends
|
|
18457
|
+
]);
|
|
18458
|
+
var VPN_ASNS = /* @__PURE__ */ new Set([
|
|
18459
|
+
9009,
|
|
18460
|
+
// M247 (most commercial VPN exits)
|
|
18461
|
+
212238,
|
|
18462
|
+
60068,
|
|
18463
|
+
// Datacamp (NordVPN, Proton, ...)
|
|
18464
|
+
209854,
|
|
18465
|
+
// Surfshark
|
|
18466
|
+
39351,
|
|
18467
|
+
// 31173 Services (Mullvad)
|
|
18468
|
+
136787,
|
|
18469
|
+
// TEFINCOM (NordVPN)
|
|
18470
|
+
147049
|
|
18471
|
+
// PacketHub (NordVPN)
|
|
18472
|
+
]);
|
|
18473
|
+
var HOSTING_NAME = /hosting|server|datacenter|data center|data-center|cloud|colo|vps|dedicated|ovh|hetzner|digitalocean|linode|vultr|choopa|amazon|aws|google|microsoft|azure|oracle|alibaba|tencent|contabo|scaleway|leaseweb|ionos|kamatera|frantech|buyvm|racknerd|quadranet|psychz|m247|datacamp|cdn77|aeza|serverius|worldstream|ipvolume|clouvider|netcup|gcore|g-core|selectel|timeweb|hostinger|godaddy|incapsula|fastly/i;
|
|
18474
|
+
var VPN_NAME = /\bvpn\b|proton|mullvad|nordvpn|surfshark|expressvpn|private internet access|tefincom|packethub|31173 services|anonymi[sz]|privacy|proxy/i;
|
|
18475
|
+
function classifyAsn(info) {
|
|
18476
|
+
if (!info) return "unknown";
|
|
18477
|
+
if (CI_ASNS.has(info.asn)) return "ci";
|
|
18478
|
+
if (VPN_ASNS.has(info.asn) || VPN_NAME.test(info.name)) return "vpn";
|
|
18479
|
+
if (HOSTING_ASNS.has(info.asn) || HOSTING_NAME.test(info.name)) return "hosting";
|
|
18480
|
+
return "unknown";
|
|
18481
|
+
}
|
|
18482
|
+
function cymruOriginName(ip) {
|
|
18483
|
+
const bytes = ipToBytes(ip);
|
|
18484
|
+
if (!bytes) return null;
|
|
18485
|
+
if (bytes.length === 4) return `${[...bytes].reverse().join(".")}.origin.asn.cymru.com`;
|
|
18486
|
+
const nibbles = [];
|
|
18487
|
+
for (const b of bytes) nibbles.push((b >> 4).toString(16), (b & 15).toString(16));
|
|
18488
|
+
return `${nibbles.reverse().join(".")}.origin6.asn.cymru.com`;
|
|
18489
|
+
}
|
|
18490
|
+
function parseCymruOrigin(txt) {
|
|
18491
|
+
const fields = txt.split("|").map((f) => f.trim());
|
|
18492
|
+
const asn = Number(fields[0]?.split(/\s+/)[0]);
|
|
18493
|
+
if (!Number.isInteger(asn) || asn <= 0) return null;
|
|
18494
|
+
return { asn, prefix: fields[1] || void 0, country: /^[A-Z]{2}$/.test(fields[2] ?? "") ? fields[2] : void 0 };
|
|
18495
|
+
}
|
|
18496
|
+
function parseCymruName(txt) {
|
|
18497
|
+
const fields = txt.split("|").map((f) => f.trim());
|
|
18498
|
+
return (fields[4] ?? "").slice(0, 120);
|
|
18499
|
+
}
|
|
18500
|
+
var AsnLookup = class {
|
|
18501
|
+
constructor(resolveTxt = (name) => import_node_dns.promises.resolveTxt(name), ttlMs = 24 * 36e5, now = Date.now) {
|
|
18502
|
+
this.resolveTxt = resolveTxt;
|
|
18503
|
+
this.ttlMs = ttlMs;
|
|
18504
|
+
this.now = now;
|
|
18505
|
+
}
|
|
18506
|
+
resolveTxt;
|
|
18507
|
+
ttlMs;
|
|
18508
|
+
now;
|
|
18509
|
+
cache = /* @__PURE__ */ new Map();
|
|
18510
|
+
async lookup(ip) {
|
|
18511
|
+
if ((0, import_node_net11.isIP)(ip) === 0) return null;
|
|
18512
|
+
const hit = this.cache.get(ip);
|
|
18513
|
+
if (hit && this.now() - hit.at < this.ttlMs) return hit.info;
|
|
18514
|
+
let info = null;
|
|
18515
|
+
try {
|
|
18516
|
+
const origin = cymruOriginName(ip);
|
|
18517
|
+
if (origin) {
|
|
18518
|
+
const rec = await withTimeout(this.resolveTxt(origin), 5e3);
|
|
18519
|
+
const parsed = parseCymruOrigin(rec.map((r) => r.join("")).find(Boolean) ?? "");
|
|
18520
|
+
if (parsed) {
|
|
18521
|
+
let name = "";
|
|
18522
|
+
try {
|
|
18523
|
+
const names = await withTimeout(this.resolveTxt(`AS${parsed.asn}.asn.cymru.com`), 5e3);
|
|
18524
|
+
name = parseCymruName(names.map((r) => r.join("")).find(Boolean) ?? "");
|
|
18525
|
+
} catch {
|
|
18526
|
+
}
|
|
18527
|
+
info = { asn: parsed.asn, name, country: parsed.country, prefix: parsed.prefix };
|
|
18528
|
+
}
|
|
18529
|
+
}
|
|
18530
|
+
} catch {
|
|
18531
|
+
info = null;
|
|
18532
|
+
}
|
|
18533
|
+
if (this.cache.size > 5e3) this.cache.clear();
|
|
18534
|
+
this.cache.set(ip, { at: this.now(), info });
|
|
18535
|
+
return info;
|
|
18536
|
+
}
|
|
18537
|
+
};
|
|
18538
|
+
function withTimeout(p, ms) {
|
|
18539
|
+
return new Promise((resolve4, reject) => {
|
|
18540
|
+
const t = setTimeout(() => reject(new Error("timeout")), ms);
|
|
18541
|
+
p.then((v) => {
|
|
18542
|
+
clearTimeout(t);
|
|
18543
|
+
resolve4(v);
|
|
18544
|
+
}, (e) => {
|
|
18545
|
+
clearTimeout(t);
|
|
18546
|
+
reject(e);
|
|
18547
|
+
});
|
|
18548
|
+
});
|
|
18549
|
+
}
|
|
18550
|
+
function describeNetwork(info, kind) {
|
|
18551
|
+
if (kind === "tor") return info ? `Tor exit, AS${info.asn} ${info.name}`.trim() : "Tor exit";
|
|
18552
|
+
if (!info) return `unknown network (${kind})`;
|
|
18553
|
+
return `AS${info.asn}${info.name ? ` ${info.name}` : ""} (${kind === "unknown" ? "ISP or unclassified" : kind})`;
|
|
18554
|
+
}
|
|
18555
|
+
|
|
18556
|
+
// src/daemon/workers/ssh-intrusion.ts
|
|
18557
|
+
var TOR_REALERT_MS = 10 * 6e4;
|
|
18558
|
+
var HOSTING_REALERT_MS = 24 * 36e5;
|
|
18559
|
+
var TOR_REMEDIATION = {
|
|
18560
|
+
action: "block",
|
|
18561
|
+
description: "Ban the Tor exit at once, for max_ban, even in dry_run and even after a successful login",
|
|
18562
|
+
enforce_in_dry_run: true,
|
|
18563
|
+
ban_on_login: true,
|
|
18564
|
+
override_operator_protection: true,
|
|
18565
|
+
max_ban: true
|
|
18566
|
+
};
|
|
18567
|
+
function parseKeyLoginsByFingerprint(text) {
|
|
18568
|
+
const out = /* @__PURE__ */ new Map();
|
|
18569
|
+
for (const line of text.split("\n")) {
|
|
18570
|
+
const m = /^(\d+(?:\.\d+)?)\s.*Accepted publickey for \S+ from (\S+) port \d+ \S+?:\s+\S+\s+(SHA256:[A-Za-z0-9+/=]+)/.exec(line);
|
|
18571
|
+
if (!m) continue;
|
|
18572
|
+
const at = Math.round(Number(m[1]) * 1e3);
|
|
18573
|
+
const ips = out.get(m[3]) ?? /* @__PURE__ */ new Map();
|
|
18574
|
+
if (at > (ips.get(m[2]) ?? 0)) ips.set(m[2], at);
|
|
18575
|
+
out.set(m[3], ips);
|
|
18576
|
+
}
|
|
18577
|
+
return out;
|
|
18578
|
+
}
|
|
18579
|
+
function readJson2(path) {
|
|
18580
|
+
try {
|
|
18581
|
+
return JSON.parse((0, import_node_fs26.readFileSync)(path, "utf-8"));
|
|
18582
|
+
} catch {
|
|
18583
|
+
return null;
|
|
18584
|
+
}
|
|
18585
|
+
}
|
|
18586
|
+
function writeJson2(path, value) {
|
|
18587
|
+
(0, import_node_fs26.mkdirSync)((0, import_node_path20.dirname)(path), { recursive: true });
|
|
18588
|
+
(0, import_node_fs26.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
|
|
18589
|
+
(0, import_node_fs26.renameSync)(`${path}.tmp`, path);
|
|
18590
|
+
}
|
|
18591
|
+
var fsIO2 = {
|
|
18592
|
+
readFile: (p) => {
|
|
18593
|
+
try {
|
|
18594
|
+
return (0, import_node_fs26.readFileSync)(p, "utf-8");
|
|
18595
|
+
} catch {
|
|
18596
|
+
return null;
|
|
18597
|
+
}
|
|
18598
|
+
},
|
|
18599
|
+
readDir: (p) => {
|
|
18600
|
+
try {
|
|
18601
|
+
return (0, import_node_fs26.readdirSync)(p);
|
|
18602
|
+
} catch {
|
|
18603
|
+
return null;
|
|
18604
|
+
}
|
|
18605
|
+
},
|
|
18606
|
+
exists: (p) => (0, import_node_fs26.existsSync)(p)
|
|
18607
|
+
};
|
|
18608
|
+
function defaultRun4(cmd, args) {
|
|
18609
|
+
const res = (0, import_node_child_process8.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
|
|
18610
|
+
return res.status === 0 ? res.stdout : null;
|
|
18611
|
+
}
|
|
18612
|
+
var SshIntrusionWatch = class {
|
|
18613
|
+
constructor(opts) {
|
|
18614
|
+
this.opts = opts;
|
|
18615
|
+
this.now = opts.now ?? Date.now;
|
|
18616
|
+
this.asn = opts.asn ?? new AsnLookup();
|
|
18617
|
+
this.io = opts.io ?? fsIO2;
|
|
18618
|
+
this.run = opts.run ?? defaultRun4;
|
|
18619
|
+
}
|
|
18620
|
+
opts;
|
|
18621
|
+
now;
|
|
18622
|
+
asn;
|
|
18623
|
+
io;
|
|
18624
|
+
run;
|
|
18625
|
+
torAlerted = /* @__PURE__ */ new Map();
|
|
18626
|
+
hostingAlerted = /* @__PURE__ */ new Map();
|
|
18627
|
+
history = {};
|
|
18628
|
+
keyComments = { at: 0, byFp: /* @__PURE__ */ new Map() };
|
|
18629
|
+
baselineReady = false;
|
|
18630
|
+
onLine = (line) => {
|
|
18631
|
+
this.checkTorLine(line);
|
|
18632
|
+
};
|
|
18633
|
+
onEvent = (event) => {
|
|
18634
|
+
void this.checkKeyLogin(event);
|
|
18635
|
+
};
|
|
18636
|
+
start() {
|
|
18637
|
+
this.opts.tor.start();
|
|
18638
|
+
this.opts.manager.setTorExitCheck((ip) => this.opts.tor.has(ip));
|
|
18639
|
+
this.opts.bus.on("sshd", this.onLine);
|
|
18640
|
+
if (this.opts.keyLoginWatch !== false) {
|
|
18641
|
+
this.opts.bus.on("event", this.onEvent);
|
|
18642
|
+
this.loadHistory();
|
|
18643
|
+
}
|
|
18644
|
+
this.opts.log(`[ssh-intrusion] Tor SSH ban ${this.opts.manager.blockTorSsh ? "ON (enforced even in dry_run)" : "OFF (alert only)"}; key-login watch ${this.opts.keyLoginWatch === false ? "off" : "on"}`);
|
|
18645
|
+
}
|
|
18646
|
+
stop() {
|
|
18647
|
+
this.opts.tor.stop();
|
|
18648
|
+
this.opts.bus.off("sshd", this.onLine);
|
|
18649
|
+
this.opts.bus.off("event", this.onEvent);
|
|
18650
|
+
}
|
|
18651
|
+
emit(event) {
|
|
18652
|
+
try {
|
|
18653
|
+
insertEvent(event);
|
|
18654
|
+
} catch {
|
|
18655
|
+
}
|
|
18656
|
+
this.opts.bus.publish(event);
|
|
18657
|
+
}
|
|
18658
|
+
/** One sshd line: a Tor exit anywhere in it is an intrusion attempt. */
|
|
18659
|
+
checkTorLine(line) {
|
|
18660
|
+
const ip = line.ip;
|
|
18661
|
+
if (!this.opts.tor.has(ip)) return false;
|
|
18662
|
+
if (isProtected(ip, DEFAULT_PROTECTED) || this.opts.manager.isFleetAddress(ip)) return false;
|
|
18663
|
+
const at = this.now();
|
|
18664
|
+
const last = this.torAlerted.get(ip) ?? 0;
|
|
18665
|
+
const accepted = /Accepted \S+ for /.test(line.message);
|
|
18666
|
+
if (!accepted && at - last < TOR_REALERT_MS) return false;
|
|
18667
|
+
this.torAlerted.set(ip, at);
|
|
18668
|
+
if (this.torAlerted.size > 1e4) this.torAlerted.clear();
|
|
18669
|
+
const ban = this.opts.manager.blockTorSsh;
|
|
18670
|
+
const user = /for (?:invalid user )?(\S+) from/.exec(line.message)?.[1];
|
|
18671
|
+
const what = accepted ? `LOGGED IN${user ? ` as ${user}` : ""}` : "connection attempt";
|
|
18672
|
+
this.emit({
|
|
18673
|
+
timestamp: line.timestamp,
|
|
18674
|
+
module: "ssh-intrusion",
|
|
18675
|
+
category: "auth",
|
|
18676
|
+
severity: accepted || ban ? "critical" : "high",
|
|
18677
|
+
message: `SSH from Tor exit ${ip} (${what})${ban ? ": banned" : ""}`,
|
|
18678
|
+
source_ip: ip,
|
|
18679
|
+
details: {
|
|
18680
|
+
rule_id: "ssh-from-tor",
|
|
18681
|
+
description: "Nobody we operate for uses SSH through Tor. A Tor login means a stolen key or password.",
|
|
18682
|
+
tor_exit: true,
|
|
18683
|
+
accepted,
|
|
18684
|
+
...user ? { ssh_user: user } : {},
|
|
18685
|
+
...ban ? { remediation: TOR_REMEDIATION } : {},
|
|
18686
|
+
evidence: { at: line.timestamp.toISOString(), module: "ssh-guard", message: line.raw.slice(0, 500) }
|
|
18687
|
+
}
|
|
18688
|
+
});
|
|
18689
|
+
return true;
|
|
18690
|
+
}
|
|
18691
|
+
loadHistory() {
|
|
18692
|
+
const saved = readJson2(this.opts.historyPath);
|
|
18693
|
+
if (saved) {
|
|
18694
|
+
this.history = saved;
|
|
18695
|
+
this.baselineReady = true;
|
|
18696
|
+
return;
|
|
18697
|
+
}
|
|
18698
|
+
const out = this.run("journalctl", ["_COMM=sshd", "_COMM=sshd-session", "--since=-30d", "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"]);
|
|
18699
|
+
const iso = (ms) => new Date(ms).toISOString();
|
|
18700
|
+
let pairs = 0;
|
|
18701
|
+
for (const [fp, ips] of parseKeyLoginsByFingerprint(out ?? "")) {
|
|
18702
|
+
for (const [ip, at] of ips) {
|
|
18703
|
+
if (this.opts.tor.has(ip)) continue;
|
|
18704
|
+
(this.history[fp] ??= {})[ip] = { first: iso(at), last: iso(at), count: 1 };
|
|
18705
|
+
pairs++;
|
|
18706
|
+
}
|
|
18707
|
+
}
|
|
18708
|
+
this.save();
|
|
18709
|
+
this.baselineReady = true;
|
|
18710
|
+
this.opts.log(`[ssh-intrusion] key-login baseline from the last 30 days: ${Object.keys(this.history).length} key(s), ${pairs} key/address pair(s)`);
|
|
18711
|
+
}
|
|
18712
|
+
save() {
|
|
18713
|
+
try {
|
|
18714
|
+
writeJson2(this.opts.historyPath, this.history);
|
|
18715
|
+
} catch (err) {
|
|
18716
|
+
this.opts.log(`[ssh-intrusion] could not save key-login history: ${err.message}`);
|
|
18717
|
+
}
|
|
18718
|
+
}
|
|
18719
|
+
/** Which account a key is authorized for, and its comment (cached 5 minutes). */
|
|
18720
|
+
keyInfo(fp) {
|
|
18721
|
+
if (this.now() - this.keyComments.at > 3e5) {
|
|
18722
|
+
const snap = takeSnapshot(this.io);
|
|
18723
|
+
const byFp = /* @__PURE__ */ new Map();
|
|
18724
|
+
for (const [user, keys] of Object.entries(snap.keys)) {
|
|
18725
|
+
for (const [f, k] of Object.entries(keys)) if (!byFp.has(f)) byFp.set(f, { user, comment: k.comment });
|
|
18726
|
+
}
|
|
18727
|
+
this.keyComments = { at: this.now(), byFp };
|
|
18728
|
+
}
|
|
18729
|
+
return this.keyComments.byFp.get(fp) ?? null;
|
|
18730
|
+
}
|
|
18731
|
+
async checkKeyLogin(event) {
|
|
18732
|
+
if (event.module !== "ssh-guard" || !this.baselineReady) return null;
|
|
18733
|
+
const fp = event.details?.fingerprint;
|
|
18734
|
+
const ip = event.source_ip;
|
|
18735
|
+
if (typeof fp !== "string" || !ip || isProtected(ip, DEFAULT_PROTECTED)) return null;
|
|
18736
|
+
const seen = this.history[fp] ?? {};
|
|
18737
|
+
const isNew = !seen[ip];
|
|
18738
|
+
const nowIso = new Date(this.now()).toISOString();
|
|
18739
|
+
seen[ip] = { first: seen[ip]?.first ?? nowIso, last: nowIso, count: (seen[ip]?.count ?? 0) + 1 };
|
|
18740
|
+
this.history[fp] = seen;
|
|
18741
|
+
this.save();
|
|
18742
|
+
const tor = this.opts.tor.has(ip);
|
|
18743
|
+
const fleet = this.opts.manager.isFleetAddress(ip);
|
|
18744
|
+
if (fleet) return null;
|
|
18745
|
+
const key = this.keyInfo(fp);
|
|
18746
|
+
const automation = key ? isAutomationKeyComment(key.comment) : false;
|
|
18747
|
+
let info = null;
|
|
18748
|
+
try {
|
|
18749
|
+
info = await this.asn.lookup(ip);
|
|
18750
|
+
} catch {
|
|
18751
|
+
info = null;
|
|
18752
|
+
}
|
|
18753
|
+
const kind = tor ? "tor" : classifyAsn(info);
|
|
18754
|
+
const network = describeNetwork(info, kind);
|
|
18755
|
+
const user = typeof event.details?.ssh_user === "string" ? event.details.ssh_user : /accepted for (\S+)/i.exec(event.message)?.[1] ?? "unknown";
|
|
18756
|
+
const keyLabel = `${fp}${key?.comment ? ` (${key.comment})` : ""}`;
|
|
18757
|
+
const known = Object.keys(seen).filter((a) => a !== ip).length;
|
|
18758
|
+
const anonymous = kind === "hosting" || kind === "vpn" || kind === "tor";
|
|
18759
|
+
const hostingHit = !automation && anonymous;
|
|
18760
|
+
const pairKey = `${fp}|${ip}`;
|
|
18761
|
+
const hostingDue = hostingHit && this.now() - (this.hostingAlerted.get(pairKey) ?? 0) >= HOSTING_REALERT_MS;
|
|
18762
|
+
if (!isNew && !hostingDue) return null;
|
|
18763
|
+
if (tor && this.opts.manager.blockTorSsh) return null;
|
|
18764
|
+
let ruleId;
|
|
18765
|
+
let severity;
|
|
18766
|
+
let message;
|
|
18767
|
+
if (hostingHit) {
|
|
18768
|
+
this.hostingAlerted.set(pairKey, this.now());
|
|
18769
|
+
ruleId = "ssh-human-key-hosting-login";
|
|
18770
|
+
severity = "high";
|
|
18771
|
+
message = `SSH login as ${user} with a person's key from a ${kind === "vpn" ? "VPN/anonymizer" : kind === "tor" ? "Tor" : "hosting/cloud"} network: ${ip}, ${network}${isNew ? ", first time for this key" : ""}`;
|
|
18772
|
+
} else if (automation && kind === "ci") {
|
|
18773
|
+
ruleId = "ssh-key-new-ip";
|
|
18774
|
+
severity = "info";
|
|
18775
|
+
message = `SSH deploy key logged in as ${user} from a new CI address ${ip} (${network}), expected`;
|
|
18776
|
+
} else {
|
|
18777
|
+
ruleId = "ssh-key-new-ip";
|
|
18778
|
+
severity = "high";
|
|
18779
|
+
message = `SSH key logged in as ${user} from an address it never used: ${ip}, ${network}${known ? `; ${known} address(es) known for this key` : ""}`;
|
|
18780
|
+
}
|
|
18781
|
+
const out = {
|
|
18782
|
+
timestamp: event.timestamp,
|
|
18783
|
+
module: "ssh-intrusion",
|
|
18784
|
+
category: "auth",
|
|
18785
|
+
severity,
|
|
18786
|
+
message,
|
|
18787
|
+
details: {
|
|
18788
|
+
rule_id: ruleId,
|
|
18789
|
+
account: user,
|
|
18790
|
+
login_ip: ip,
|
|
18791
|
+
fingerprint: fp,
|
|
18792
|
+
key_comment: key?.comment ?? null,
|
|
18793
|
+
key_kind: automation ? "automation" : "person",
|
|
18794
|
+
network_kind: kind,
|
|
18795
|
+
...info ? { asn: info.asn, as_name: info.name, as_country: info.country } : {},
|
|
18796
|
+
first_time_for_key: isNew,
|
|
18797
|
+
known_addresses_for_key: known,
|
|
18798
|
+
evidence: { at: event.timestamp.toISOString(), module: "ssh-guard", message: `Accepted publickey for ${user} from ${ip} ${fp}` }
|
|
18799
|
+
}
|
|
18800
|
+
};
|
|
18801
|
+
this.emit(out);
|
|
18802
|
+
return out;
|
|
18803
|
+
}
|
|
18804
|
+
};
|
|
18805
|
+
|
|
18806
|
+
// src/daemon/workers/lightning-watch.ts
|
|
18807
|
+
var import_node_fs27 = require("fs");
|
|
18808
|
+
var DEFAULT_CLN_LOGS = [
|
|
18809
|
+
"/home/lightning/.lightning/cln.log",
|
|
18810
|
+
"/root/.lightning/cln.log",
|
|
18811
|
+
"/var/lib/clightning/cln.log",
|
|
18812
|
+
"/home/lightning/.lightning/bitcoin/cln.log"
|
|
18813
|
+
];
|
|
18814
|
+
var CLOSE_RE = /^(\S+)\s+\S+\s+(\S+?)-chan#(\d+): State changed from CHANNELD_NORMAL to (CHANNELD_SHUTTING_DOWN|AWAITING_UNILATERAL|CLOSINGD_SIGEXCHANGE|CLOSINGD_COMPLETE)/;
|
|
18815
|
+
function parseChannelClose(line) {
|
|
18816
|
+
const m = CLOSE_RE.exec(line);
|
|
18817
|
+
if (!m) return null;
|
|
18818
|
+
const at = new Date(m[1]);
|
|
18819
|
+
return { at: Number.isNaN(at.getTime()) ? /* @__PURE__ */ new Date() : at, peer: m[2], channel: `${m[2].slice(0, 12)}\u2026#${m[3]}`, to: m[4], line: line.slice(0, 500) };
|
|
18820
|
+
}
|
|
18821
|
+
var BURST_WINDOW_MS = 10 * 6e4;
|
|
18822
|
+
var BURST_REALERT_MS = 30 * 6e4;
|
|
18823
|
+
var ChannelCloseDetector = class {
|
|
18824
|
+
recent = [];
|
|
18825
|
+
lastBurst = 0;
|
|
18826
|
+
/** Events for one log line (none, a close, or a close and a burst). */
|
|
18827
|
+
feed(line) {
|
|
18828
|
+
const close = parseChannelClose(line);
|
|
18829
|
+
if (!close) return [];
|
|
18830
|
+
const t = close.at.getTime();
|
|
18831
|
+
this.recent = this.recent.filter((c) => t - c.at.getTime() < BURST_WINDOW_MS && c.channel !== close.channel);
|
|
18832
|
+
this.recent.push(close);
|
|
18833
|
+
const out = [{
|
|
18834
|
+
timestamp: close.at,
|
|
18835
|
+
severity: "high",
|
|
18836
|
+
message: `Lightning channel ${close.channel} closing (${close.to})`,
|
|
18837
|
+
details: { rule_id: "ln-channel-close", peer: close.peer, to_state: close.to, evidence: { at: close.at.toISOString(), module: "lightning", message: close.line } }
|
|
18838
|
+
}];
|
|
18839
|
+
if (this.recent.length >= 2 && t - this.lastBurst >= BURST_REALERT_MS) {
|
|
18840
|
+
this.lastBurst = t;
|
|
18841
|
+
out.push({
|
|
18842
|
+
timestamp: close.at,
|
|
18843
|
+
severity: "critical",
|
|
18844
|
+
message: `Lightning channel-close burst: ${this.recent.length} channels closing within 10 minutes (${this.recent.map((c) => c.channel).join(", ")}). If nobody here did this, the node is being drained.`,
|
|
18845
|
+
details: { rule_id: "ln-channel-close-burst", channels: this.recent.map((c) => c.channel), evidence: { at: close.at.toISOString(), module: "lightning", message: close.line } }
|
|
18846
|
+
});
|
|
18847
|
+
}
|
|
18848
|
+
return out;
|
|
18849
|
+
}
|
|
18850
|
+
};
|
|
18851
|
+
var LightningWatch = class {
|
|
18852
|
+
constructor(opts) {
|
|
18853
|
+
this.opts = opts;
|
|
18854
|
+
}
|
|
18855
|
+
opts;
|
|
18856
|
+
tails = [];
|
|
18857
|
+
timer = null;
|
|
18858
|
+
detector = new ChannelCloseDetector();
|
|
18859
|
+
start() {
|
|
18860
|
+
if (this.opts.enabled === false) return [];
|
|
18861
|
+
const found = [];
|
|
18862
|
+
for (const path of this.opts.paths?.length ? this.opts.paths : DEFAULT_CLN_LOGS) {
|
|
18863
|
+
if (!(0, import_node_fs27.existsSync)(path)) continue;
|
|
18864
|
+
try {
|
|
18865
|
+
(0, import_node_fs27.accessSync)(path, import_node_fs27.constants.R_OK);
|
|
18866
|
+
} catch {
|
|
18867
|
+
continue;
|
|
18868
|
+
}
|
|
18869
|
+
this.tails.push(new LogTail(path));
|
|
18870
|
+
found.push(path);
|
|
18871
|
+
}
|
|
18872
|
+
if (!found.length) return [];
|
|
18873
|
+
this.timer = setInterval(() => this.poll(), 2e3);
|
|
18874
|
+
this.timer.unref?.();
|
|
18875
|
+
this.opts.log(`[lightning] watching channel closes in ${found.join(", ")}`);
|
|
18876
|
+
return found;
|
|
18877
|
+
}
|
|
18878
|
+
stop() {
|
|
18879
|
+
if (this.timer) clearInterval(this.timer);
|
|
18880
|
+
this.timer = null;
|
|
18881
|
+
this.tails = [];
|
|
18882
|
+
}
|
|
18883
|
+
poll() {
|
|
18884
|
+
for (const tail of this.tails) {
|
|
18885
|
+
tail.poll((line) => {
|
|
18886
|
+
for (const e of this.detector.feed(line)) {
|
|
18887
|
+
const event = { module: "lightning", category: "system", ...e };
|
|
18888
|
+
try {
|
|
18889
|
+
insertEvent(event);
|
|
18890
|
+
} catch {
|
|
18891
|
+
}
|
|
18892
|
+
this.opts.bus.publish(event);
|
|
18893
|
+
}
|
|
18894
|
+
});
|
|
18895
|
+
}
|
|
18896
|
+
}
|
|
18897
|
+
};
|
|
18898
|
+
|
|
18899
|
+
// src/core/tor-exits.ts
|
|
18900
|
+
var import_node_fs28 = require("fs");
|
|
18901
|
+
var import_node_path21 = require("path");
|
|
18902
|
+
var import_node_net12 = require("net");
|
|
18903
|
+
var TOR_BULK_EXIT_LIST_URL = "https://check.torproject.org/torbulkexitlist";
|
|
18904
|
+
function parseTorExitList(text) {
|
|
18905
|
+
const out = /* @__PURE__ */ new Set();
|
|
18906
|
+
for (const raw of text.split("\n")) {
|
|
18907
|
+
const line = raw.trim();
|
|
18908
|
+
if (!line || line.startsWith("#")) continue;
|
|
18909
|
+
const ip = line.split(/\s+/)[0];
|
|
18910
|
+
if ((0, import_node_net12.isIP)(ip)) out.add(normalizeIp(ip));
|
|
18911
|
+
}
|
|
18912
|
+
return out;
|
|
18913
|
+
}
|
|
18914
|
+
function normalizeIp(ip) {
|
|
18915
|
+
const bare = ip.trim().replace(/^\[|\]$/g, "").replace(/%.*$/, "");
|
|
18916
|
+
const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(bare);
|
|
18917
|
+
return mapped ? mapped[1] : bare.toLowerCase();
|
|
18918
|
+
}
|
|
18919
|
+
var TorExitList = class _TorExitList {
|
|
18920
|
+
constructor(opts) {
|
|
18921
|
+
this.opts = opts;
|
|
18922
|
+
this.url = opts.url ?? TOR_BULK_EXIT_LIST_URL;
|
|
18923
|
+
this.refreshMs = Math.max(15 * 6e4, opts.refreshMs ?? 36e5);
|
|
18924
|
+
this.fetchImpl = opts.fetchImpl ?? fetch;
|
|
18925
|
+
this.log = opts.log ?? (() => {
|
|
18926
|
+
});
|
|
18927
|
+
this.now = opts.now ?? Date.now;
|
|
18928
|
+
}
|
|
18929
|
+
opts;
|
|
18930
|
+
exits = /* @__PURE__ */ new Set();
|
|
18931
|
+
updatedAt = 0;
|
|
18932
|
+
timer = null;
|
|
18933
|
+
url;
|
|
18934
|
+
refreshMs;
|
|
18935
|
+
fetchImpl;
|
|
18936
|
+
log;
|
|
18937
|
+
now;
|
|
18938
|
+
/** Fewer than this many exits is a broken download, not the Tor network (it has ~1,000+). */
|
|
18939
|
+
static MIN_PLAUSIBLE = 100;
|
|
18940
|
+
/** Load the cache, then refresh now and every `refreshMs`. */
|
|
18941
|
+
start() {
|
|
18942
|
+
this.loadCache();
|
|
18943
|
+
void this.refresh();
|
|
18944
|
+
this.timer = setInterval(() => void this.refresh(), this.refreshMs);
|
|
18945
|
+
this.timer.unref?.();
|
|
18946
|
+
}
|
|
18947
|
+
stop() {
|
|
18948
|
+
if (this.timer) clearInterval(this.timer);
|
|
18949
|
+
this.timer = null;
|
|
18950
|
+
}
|
|
18951
|
+
has(ip) {
|
|
18952
|
+
if (!ip) return false;
|
|
18953
|
+
return this.exits.has(normalizeIp(ip));
|
|
18954
|
+
}
|
|
18955
|
+
get size() {
|
|
18956
|
+
return this.exits.size;
|
|
18957
|
+
}
|
|
18958
|
+
/** When the list in memory was downloaded (ms), 0 if never. */
|
|
18959
|
+
get updated() {
|
|
18960
|
+
return this.updatedAt;
|
|
18961
|
+
}
|
|
18962
|
+
/** Replace the list directly (tests, and the CLI reading the cache). */
|
|
18963
|
+
load(ips, at = this.now()) {
|
|
18964
|
+
this.exits = new Set([...ips].map(normalizeIp));
|
|
18965
|
+
this.updatedAt = at;
|
|
18966
|
+
}
|
|
18967
|
+
loadCache() {
|
|
18968
|
+
try {
|
|
18969
|
+
if (!(0, import_node_fs28.existsSync)(this.opts.cachePath)) return false;
|
|
18970
|
+
const parsed = parseTorExitList((0, import_node_fs28.readFileSync)(this.opts.cachePath, "utf-8"));
|
|
18971
|
+
if (parsed.size === 0) return false;
|
|
18972
|
+
this.load(parsed, (0, import_node_fs28.statSync)(this.opts.cachePath).mtimeMs);
|
|
18973
|
+
this.log(`[tor] loaded ${parsed.size} Tor exit addresses from cache (${new Date(this.updatedAt).toISOString()})`);
|
|
18974
|
+
return true;
|
|
18975
|
+
} catch (err) {
|
|
18976
|
+
this.log(`[tor] could not read the exit list cache: ${err.message}`);
|
|
18977
|
+
return false;
|
|
18978
|
+
}
|
|
18979
|
+
}
|
|
18980
|
+
async refresh() {
|
|
18981
|
+
let text;
|
|
18982
|
+
try {
|
|
18983
|
+
const res = await this.fetchImpl(this.url, {
|
|
18984
|
+
signal: AbortSignal.timeout(3e4),
|
|
18985
|
+
headers: { "User-Agent": "threatcrush-daemon (tor exit list)" }
|
|
18986
|
+
});
|
|
18987
|
+
if (!res.ok) {
|
|
18988
|
+
this.log(`[tor] exit list download failed: HTTP ${res.status}; keeping ${this.exits.size} cached`);
|
|
18989
|
+
return false;
|
|
18990
|
+
}
|
|
18991
|
+
text = await res.text();
|
|
18992
|
+
} catch (err) {
|
|
18993
|
+
this.log(`[tor] exit list download failed: ${err.message}; keeping ${this.exits.size} cached`);
|
|
18994
|
+
return false;
|
|
18995
|
+
}
|
|
18996
|
+
const parsed = parseTorExitList(text);
|
|
18997
|
+
if (parsed.size < _TorExitList.MIN_PLAUSIBLE) {
|
|
18998
|
+
this.log(`[tor] exit list download had only ${parsed.size} addresses; keeping ${this.exits.size} cached`);
|
|
18999
|
+
return false;
|
|
19000
|
+
}
|
|
19001
|
+
const before = this.exits.size;
|
|
19002
|
+
this.load(parsed);
|
|
19003
|
+
try {
|
|
19004
|
+
(0, import_node_fs28.mkdirSync)((0, import_node_path21.dirname)(this.opts.cachePath), { recursive: true });
|
|
19005
|
+
(0, import_node_fs28.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
|
|
19006
|
+
(0, import_node_fs28.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
|
|
19007
|
+
} catch (err) {
|
|
19008
|
+
this.log(`[tor] could not save the exit list cache: ${err.message}`);
|
|
19009
|
+
}
|
|
19010
|
+
if (before !== parsed.size || before === 0) this.log(`[tor] loaded ${parsed.size} Tor exit addresses from ${this.url}`);
|
|
19011
|
+
return true;
|
|
19012
|
+
}
|
|
19013
|
+
};
|
|
19014
|
+
|
|
18171
19015
|
// src/daemon/rules/engine.ts
|
|
18172
19016
|
var MAX_WINDOW_ENTRIES = 1e3;
|
|
18173
19017
|
function live(window) {
|
|
@@ -18349,8 +19193,8 @@ var RuleEngine = class {
|
|
|
18349
19193
|
};
|
|
18350
19194
|
|
|
18351
19195
|
// src/daemon/rules/loader.ts
|
|
18352
|
-
var
|
|
18353
|
-
var
|
|
19196
|
+
var import_node_fs29 = require("fs");
|
|
19197
|
+
var import_node_path22 = require("path");
|
|
18354
19198
|
|
|
18355
19199
|
// src/daemon/rules/default-rules.ts
|
|
18356
19200
|
var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
|
|
@@ -18820,11 +19664,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
|
|
|
18820
19664
|
function loadAllRules(customDir) {
|
|
18821
19665
|
const rules = [...DEFAULT_RULES];
|
|
18822
19666
|
const dir = customDir || RULES_DIR;
|
|
18823
|
-
if ((0,
|
|
18824
|
-
const files = (0,
|
|
19667
|
+
if ((0, import_node_fs29.existsSync)(dir)) {
|
|
19668
|
+
const files = (0, import_node_fs29.readdirSync)(dir).filter((f) => f.endsWith(".json"));
|
|
18825
19669
|
for (const file of files) {
|
|
18826
19670
|
try {
|
|
18827
|
-
const raw = (0,
|
|
19671
|
+
const raw = (0, import_node_fs29.readFileSync)((0, import_node_path22.join)(dir, file), "utf-8");
|
|
18828
19672
|
const parsed = JSON.parse(raw);
|
|
18829
19673
|
const customRules = Array.isArray(parsed) ? parsed : [parsed];
|
|
18830
19674
|
for (const rule of customRules) {
|
|
@@ -18855,24 +19699,24 @@ function loadAllRules(customDir) {
|
|
|
18855
19699
|
}
|
|
18856
19700
|
|
|
18857
19701
|
// src/daemon/firewall/adapters.ts
|
|
18858
|
-
var
|
|
18859
|
-
var
|
|
18860
|
-
var
|
|
18861
|
-
var
|
|
19702
|
+
var import_node_child_process9 = require("child_process");
|
|
19703
|
+
var import_node_fs30 = require("fs");
|
|
19704
|
+
var import_node_path23 = require("path");
|
|
19705
|
+
var import_node_net13 = require("net");
|
|
18862
19706
|
function assertValidFirewallIp(ip) {
|
|
18863
|
-
if ((0,
|
|
19707
|
+
if ((0, import_node_net13.isIP)(ip) !== 4) {
|
|
18864
19708
|
throw new Error(`Invalid IPv4 address: ${ip}`);
|
|
18865
19709
|
}
|
|
18866
19710
|
}
|
|
18867
19711
|
function assertBannableIp(ip) {
|
|
18868
|
-
if ((0,
|
|
19712
|
+
if ((0, import_node_net13.isIP)(ip) === 0) {
|
|
18869
19713
|
throw new Error(`Invalid IP address: ${ip}`);
|
|
18870
19714
|
}
|
|
18871
19715
|
}
|
|
18872
19716
|
function writeIfAbsent(path, contents) {
|
|
18873
|
-
(0,
|
|
19717
|
+
(0, import_node_fs30.mkdirSync)((0, import_node_path23.dirname)(path), { recursive: true });
|
|
18874
19718
|
try {
|
|
18875
|
-
(0,
|
|
19719
|
+
(0, import_node_fs30.writeFileSync)(path, contents, { flag: "wx" });
|
|
18876
19720
|
} catch (err) {
|
|
18877
19721
|
if (err.code !== "EEXIST") throw err;
|
|
18878
19722
|
}
|
|
@@ -18891,11 +19735,11 @@ var Fail2banAdapter = class {
|
|
|
18891
19735
|
enforces = true;
|
|
18892
19736
|
jailReady = false;
|
|
18893
19737
|
isAvailable() {
|
|
18894
|
-
const result = (0,
|
|
19738
|
+
const result = (0, import_node_child_process9.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
|
|
18895
19739
|
return result.status === 0;
|
|
18896
19740
|
}
|
|
18897
19741
|
client(args) {
|
|
18898
|
-
return (0,
|
|
19742
|
+
return (0, import_node_child_process9.execFileSync)("fail2ban-client", args, {
|
|
18899
19743
|
encoding: "utf-8",
|
|
18900
19744
|
stdio: ["ignore", "pipe", "pipe"]
|
|
18901
19745
|
});
|
|
@@ -18971,7 +19815,7 @@ var Fail2banAdapter = class {
|
|
|
18971
19815
|
const status = this.client(["status", this.jail]);
|
|
18972
19816
|
const line = status.split("\n").find((l) => /Banned IP list:/i.test(l));
|
|
18973
19817
|
if (!line) return [];
|
|
18974
|
-
return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0,
|
|
19818
|
+
return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net13.isIP)(s) !== 0);
|
|
18975
19819
|
} catch {
|
|
18976
19820
|
return [];
|
|
18977
19821
|
}
|
|
@@ -18981,45 +19825,45 @@ var Fail2banAdapter = class {
|
|
|
18981
19825
|
function parseBannedList(output) {
|
|
18982
19826
|
const found = [];
|
|
18983
19827
|
for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
|
|
18984
|
-
if ((0,
|
|
19828
|
+
if ((0, import_node_net13.isIP)(match[1]) !== 0) found.push(match[1]);
|
|
18985
19829
|
}
|
|
18986
19830
|
if (found.length > 0) return found;
|
|
18987
|
-
return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0,
|
|
19831
|
+
return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net13.isIP)(s) !== 0);
|
|
18988
19832
|
}
|
|
18989
19833
|
var NftablesAdapter = class {
|
|
18990
19834
|
name = "nftables";
|
|
18991
19835
|
table = "threatcrush";
|
|
18992
19836
|
set = "blocklist";
|
|
18993
19837
|
isAvailable() {
|
|
18994
|
-
const result = (0,
|
|
19838
|
+
const result = (0, import_node_child_process9.spawnSync)("nft", ["--version"], { stdio: "pipe" });
|
|
18995
19839
|
return result.status === 0;
|
|
18996
19840
|
}
|
|
18997
19841
|
ensureSetup() {
|
|
18998
19842
|
try {
|
|
18999
|
-
(0,
|
|
19843
|
+
(0, import_node_child_process9.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
|
|
19000
19844
|
} catch {
|
|
19001
|
-
(0,
|
|
19002
|
-
(0,
|
|
19003
|
-
(0,
|
|
19004
|
-
(0,
|
|
19845
|
+
(0, import_node_child_process9.execSync)(`nft add table inet ${this.table}`);
|
|
19846
|
+
(0, import_node_child_process9.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
|
|
19847
|
+
(0, import_node_child_process9.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
|
|
19848
|
+
(0, import_node_child_process9.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
|
|
19005
19849
|
}
|
|
19006
19850
|
}
|
|
19007
19851
|
async block(ip) {
|
|
19008
19852
|
assertValidFirewallIp(ip);
|
|
19009
19853
|
this.ensureSetup();
|
|
19010
|
-
(0,
|
|
19854
|
+
(0, import_node_child_process9.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
|
|
19011
19855
|
}
|
|
19012
19856
|
async unblock(ip) {
|
|
19013
19857
|
assertValidFirewallIp(ip);
|
|
19014
19858
|
try {
|
|
19015
|
-
(0,
|
|
19859
|
+
(0, import_node_child_process9.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
|
|
19016
19860
|
} catch {
|
|
19017
19861
|
}
|
|
19018
19862
|
}
|
|
19019
19863
|
async isBlocked(ip) {
|
|
19020
19864
|
assertValidFirewallIp(ip);
|
|
19021
19865
|
try {
|
|
19022
|
-
const output = (0,
|
|
19866
|
+
const output = (0, import_node_child_process9.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
|
|
19023
19867
|
return output.includes(ip);
|
|
19024
19868
|
} catch {
|
|
19025
19869
|
return false;
|
|
@@ -19027,7 +19871,7 @@ var NftablesAdapter = class {
|
|
|
19027
19871
|
}
|
|
19028
19872
|
async listBlocked() {
|
|
19029
19873
|
try {
|
|
19030
|
-
const output = (0,
|
|
19874
|
+
const output = (0, import_node_child_process9.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
|
|
19031
19875
|
const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
|
|
19032
19876
|
if (!match) return [];
|
|
19033
19877
|
return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
|
|
@@ -19040,34 +19884,34 @@ var IptablesAdapter = class {
|
|
|
19040
19884
|
name = "iptables";
|
|
19041
19885
|
chain = "THREATCRUSH";
|
|
19042
19886
|
isAvailable() {
|
|
19043
|
-
const result = (0,
|
|
19887
|
+
const result = (0, import_node_child_process9.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
|
|
19044
19888
|
return result.status === 0;
|
|
19045
19889
|
}
|
|
19046
19890
|
ensureChain() {
|
|
19047
19891
|
try {
|
|
19048
|
-
(0,
|
|
19892
|
+
(0, import_node_child_process9.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
|
|
19049
19893
|
} catch {
|
|
19050
|
-
(0,
|
|
19051
|
-
(0,
|
|
19894
|
+
(0, import_node_child_process9.execSync)(`iptables -N ${this.chain}`);
|
|
19895
|
+
(0, import_node_child_process9.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
|
|
19052
19896
|
}
|
|
19053
19897
|
}
|
|
19054
19898
|
async block(ip) {
|
|
19055
19899
|
assertValidFirewallIp(ip);
|
|
19056
19900
|
this.ensureChain();
|
|
19057
19901
|
if (await this.isBlocked(ip)) return;
|
|
19058
|
-
(0,
|
|
19902
|
+
(0, import_node_child_process9.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
|
|
19059
19903
|
}
|
|
19060
19904
|
async unblock(ip) {
|
|
19061
19905
|
assertValidFirewallIp(ip);
|
|
19062
19906
|
try {
|
|
19063
|
-
(0,
|
|
19907
|
+
(0, import_node_child_process9.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
|
|
19064
19908
|
} catch {
|
|
19065
19909
|
}
|
|
19066
19910
|
}
|
|
19067
19911
|
async isBlocked(ip) {
|
|
19068
19912
|
assertValidFirewallIp(ip);
|
|
19069
19913
|
try {
|
|
19070
|
-
const output = (0,
|
|
19914
|
+
const output = (0, import_node_child_process9.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
|
|
19071
19915
|
return output.includes(ip);
|
|
19072
19916
|
} catch {
|
|
19073
19917
|
return false;
|
|
@@ -19075,7 +19919,7 @@ var IptablesAdapter = class {
|
|
|
19075
19919
|
}
|
|
19076
19920
|
async listBlocked() {
|
|
19077
19921
|
try {
|
|
19078
|
-
const output = (0,
|
|
19922
|
+
const output = (0, import_node_child_process9.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
|
|
19079
19923
|
const ips = [];
|
|
19080
19924
|
for (const line of output.split("\n")) {
|
|
19081
19925
|
const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
|
|
@@ -19131,20 +19975,20 @@ function detectFirewallAdapter(backend = "auto") {
|
|
|
19131
19975
|
}
|
|
19132
19976
|
|
|
19133
19977
|
// src/daemon/firewall/remediation.ts
|
|
19134
|
-
var
|
|
19135
|
-
var
|
|
19136
|
-
var
|
|
19978
|
+
var import_node_fs31 = require("fs");
|
|
19979
|
+
var import_node_child_process10 = require("child_process");
|
|
19980
|
+
var import_node_net14 = require("net");
|
|
19137
19981
|
|
|
19138
19982
|
// src/daemon/firewall/crawlers.ts
|
|
19139
|
-
var
|
|
19983
|
+
var import_node_dns2 = require("dns");
|
|
19140
19984
|
var CRAWLER_DOMAINS = ["googlebot.com", "google.com", "search.msn.com", "applebot.apple.com"];
|
|
19141
19985
|
var systemResolver = {
|
|
19142
|
-
reverse: (ip) =>
|
|
19143
|
-
lookup: async (host) => (await
|
|
19986
|
+
reverse: (ip) => import_node_dns2.promises.reverse(ip),
|
|
19987
|
+
lookup: async (host) => (await import_node_dns2.promises.lookup(host, { all: true })).map((a) => a.address)
|
|
19144
19988
|
};
|
|
19145
19989
|
var TIMEOUT_MS2 = 2e3;
|
|
19146
19990
|
var CACHE_MS = 6 * 36e5;
|
|
19147
|
-
function
|
|
19991
|
+
function withTimeout2(p) {
|
|
19148
19992
|
return Promise.race([
|
|
19149
19993
|
p,
|
|
19150
19994
|
new Promise((_, reject) => setTimeout(() => reject(new Error("dns timeout")), TIMEOUT_MS2).unref())
|
|
@@ -19161,9 +20005,9 @@ function crawlerVerifier(resolver = systemResolver) {
|
|
|
19161
20005
|
if (hit && hit.until > Date.now()) return hit.host;
|
|
19162
20006
|
let host = null;
|
|
19163
20007
|
try {
|
|
19164
|
-
const names = await
|
|
20008
|
+
const names = await withTimeout2(resolver.reverse(ip));
|
|
19165
20009
|
for (const name of names.filter(inCrawlerDomain)) {
|
|
19166
|
-
const addrs = await
|
|
20010
|
+
const addrs = await withTimeout2(resolver.lookup(name));
|
|
19167
20011
|
if (addrs.includes(ip)) {
|
|
19168
20012
|
host = name.replace(/\.$/, "");
|
|
19169
20013
|
break;
|
|
@@ -19191,7 +20035,8 @@ var DEFAULT_CONFIG2 = {
|
|
|
19191
20035
|
protect_current_ssh_client: true,
|
|
19192
20036
|
protect_recent_operators: true,
|
|
19193
20037
|
operator_memory_seconds: 30 * 86400,
|
|
19194
|
-
spare_verified_crawlers: true
|
|
20038
|
+
spare_verified_crawlers: true,
|
|
20039
|
+
block_tor_ssh: true
|
|
19195
20040
|
};
|
|
19196
20041
|
var defaultDiscovery = {
|
|
19197
20042
|
sshPeers: () => [currentSshClient(), ...establishedSshPeers()].filter((ip) => Boolean(ip)),
|
|
@@ -19200,19 +20045,19 @@ var defaultDiscovery = {
|
|
|
19200
20045
|
const snapshot = takeSnapshot({
|
|
19201
20046
|
readFile: (p) => {
|
|
19202
20047
|
try {
|
|
19203
|
-
return (0,
|
|
20048
|
+
return (0, import_node_fs31.readFileSync)(p, "utf-8");
|
|
19204
20049
|
} catch {
|
|
19205
20050
|
return null;
|
|
19206
20051
|
}
|
|
19207
20052
|
},
|
|
19208
20053
|
readDir: (p) => {
|
|
19209
20054
|
try {
|
|
19210
|
-
return (0,
|
|
20055
|
+
return (0, import_node_fs31.readdirSync)(p);
|
|
19211
20056
|
} catch {
|
|
19212
20057
|
return null;
|
|
19213
20058
|
}
|
|
19214
20059
|
},
|
|
19215
|
-
exists: (p) => (0,
|
|
20060
|
+
exists: (p) => (0, import_node_fs31.existsSync)(p)
|
|
19216
20061
|
});
|
|
19217
20062
|
const out = /* @__PURE__ */ new Set();
|
|
19218
20063
|
for (const keys of Object.values(snapshot.keys)) {
|
|
@@ -19221,7 +20066,7 @@ var defaultDiscovery = {
|
|
|
19221
20066
|
return out;
|
|
19222
20067
|
},
|
|
19223
20068
|
keyLoginJournal: (sinceSeconds) => new Promise((resolve4) => {
|
|
19224
|
-
(0,
|
|
20069
|
+
(0, import_node_child_process10.execFile)(
|
|
19225
20070
|
"journalctl",
|
|
19226
20071
|
["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
|
|
19227
20072
|
{ maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
|
|
@@ -19229,7 +20074,7 @@ var defaultDiscovery = {
|
|
|
19229
20074
|
);
|
|
19230
20075
|
})
|
|
19231
20076
|
};
|
|
19232
|
-
var
|
|
20077
|
+
var SEVERITY_RANK6 = {
|
|
19233
20078
|
info: 0,
|
|
19234
20079
|
low: 1,
|
|
19235
20080
|
medium: 2,
|
|
@@ -19286,16 +20131,56 @@ var RemediationManager = class {
|
|
|
19286
20131
|
operators = {};
|
|
19287
20132
|
expiryTimer = null;
|
|
19288
20133
|
operatorTimer = null;
|
|
20134
|
+
/** True for a Tor exit address; such an address is never an operator. */
|
|
20135
|
+
isTorExit = () => false;
|
|
19289
20136
|
/** Remembered operator addresses and when each was last seen. */
|
|
19290
20137
|
getOperators() {
|
|
19291
20138
|
return { ...this.operators };
|
|
19292
20139
|
}
|
|
20140
|
+
/**
|
|
20141
|
+
* Teach the manager which addresses are Tor exits. They are never
|
|
20142
|
+
* remembered as operators and never protected as a live session: on dev2
|
|
20143
|
+
* the 2026-10-27 intruder logged in with a stolen key from Tor, which made
|
|
20144
|
+
* the exit an "operator" that nothing could ban for 30 days.
|
|
20145
|
+
*/
|
|
20146
|
+
setTorExitCheck(check) {
|
|
20147
|
+
this.isTorExit = check;
|
|
20148
|
+
let dropped = 0;
|
|
20149
|
+
this.protectedList = this.protectedList.filter((a) => !(0, import_node_net14.isIP)(a) || !check(a) || this.pinned.has(a) || this.config.allowlist.includes(a));
|
|
20150
|
+
for (const ip of Object.keys(this.operators)) {
|
|
20151
|
+
if (!check(ip)) continue;
|
|
20152
|
+
delete this.operators[ip];
|
|
20153
|
+
this.protectedList = this.protectedList.filter((a) => a !== ip || this.pinned.has(a) || this.config.allowlist.includes(a));
|
|
20154
|
+
dropped++;
|
|
20155
|
+
}
|
|
20156
|
+
if (dropped) {
|
|
20157
|
+
this.logLine(`[firewall] forgot ${dropped} remembered operator address(es) that are Tor exits`);
|
|
20158
|
+
this.saveState();
|
|
20159
|
+
}
|
|
20160
|
+
}
|
|
20161
|
+
/** Tor SSH bans on (setting) — the cloud may change it unless config pinned it. */
|
|
20162
|
+
get blockTorSsh() {
|
|
20163
|
+
return this.config.enabled && this.config.block_tor_ssh;
|
|
20164
|
+
}
|
|
20165
|
+
setBlockTorSsh(on) {
|
|
20166
|
+
this.config.block_tor_ssh = on;
|
|
20167
|
+
}
|
|
20168
|
+
/**
|
|
20169
|
+
* Our own addresses: built-ins, shared infrastructure, gateways, the
|
|
20170
|
+
* operator's `[remediation] protected` and the dashboard's org allowlist
|
|
20171
|
+
* (Known IPs). Not remembered operators or live sessions.
|
|
20172
|
+
*/
|
|
20173
|
+
isFleetAddress(ip) {
|
|
20174
|
+
return isProtected(ip, [...this.pinned, ...this.config.allowlist]);
|
|
20175
|
+
}
|
|
19293
20176
|
/**
|
|
19294
20177
|
* An address an operator really came from: never ban it, remember it, and
|
|
19295
20178
|
* lift a ban that is already on it — the operator is the one who needs in.
|
|
19296
20179
|
*/
|
|
19297
20180
|
noteOperator(ip, at, remember = true) {
|
|
19298
20181
|
if (Date.now() - at > this.config.operator_memory_seconds * 1e3) return;
|
|
20182
|
+
if (this.isTorExit(ip) && !this.isFleetAddress(ip)) return;
|
|
20183
|
+
if (this.blocklist.some((b) => b.ip === ip && b.strict)) return;
|
|
19299
20184
|
if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
|
|
19300
20185
|
if (!remember || !this.config.protect_recent_operators || isProtected(ip, DEFAULT_PROTECTED)) return;
|
|
19301
20186
|
const known = this.operators[ip] ?? 0;
|
|
@@ -19345,17 +20230,21 @@ var RemediationManager = class {
|
|
|
19345
20230
|
}
|
|
19346
20231
|
async handleDetection(event) {
|
|
19347
20232
|
if (!this.config.enabled) return;
|
|
19348
|
-
const eventRank =
|
|
19349
|
-
const minRank =
|
|
20233
|
+
const eventRank = SEVERITY_RANK6[event.severity] ?? 0;
|
|
20234
|
+
const minRank = SEVERITY_RANK6[this.config.min_severity] ?? 3;
|
|
19350
20235
|
if (eventRank < minRank) return;
|
|
19351
|
-
|
|
20236
|
+
const remediation = event.details?.remediation;
|
|
20237
|
+
if (isSuccessfulAuth(event.message) && remediation?.ban_on_login !== true) return;
|
|
19352
20238
|
if (event.details?.rule_id) {
|
|
19353
|
-
const remediation = event.details?.remediation;
|
|
19354
20239
|
if (remediation?.action !== "block") return;
|
|
19355
20240
|
}
|
|
19356
20241
|
const ip = event.source_ip;
|
|
19357
|
-
if (!ip || (0,
|
|
19358
|
-
|
|
20242
|
+
if (!ip || (0, import_node_net14.isIP)(ip) === 0) return;
|
|
20243
|
+
const strict = remediation?.override_operator_protection === true;
|
|
20244
|
+
if (strict ? this.isFleetAddress(ip) : this.isAllowlisted(ip)) {
|
|
20245
|
+
if (strict) this.logLine(`[remediation] not banning ${ip}: it is one of our own addresses (${event.message})`);
|
|
20246
|
+
return;
|
|
20247
|
+
}
|
|
19359
20248
|
if (this.blocklist.some((b) => b.ip === ip)) return;
|
|
19360
20249
|
if (this.config.spare_verified_crawlers) {
|
|
19361
20250
|
const crawler = await this.verifyCrawler(ip);
|
|
@@ -19365,7 +20254,13 @@ var RemediationManager = class {
|
|
|
19365
20254
|
}
|
|
19366
20255
|
}
|
|
19367
20256
|
const ruleId = event.details?.rule_id;
|
|
19368
|
-
await this.ban(ip, event.message, {
|
|
20257
|
+
await this.ban(ip, event.message, {
|
|
20258
|
+
ruleId,
|
|
20259
|
+
source: "auto",
|
|
20260
|
+
enforceInDryRun: remediation?.enforce_in_dry_run === true,
|
|
20261
|
+
strict,
|
|
20262
|
+
...remediation?.max_ban ? { ttlSeconds: this.config.max_ban_seconds } : {}
|
|
20263
|
+
});
|
|
19369
20264
|
}
|
|
19370
20265
|
/**
|
|
19371
20266
|
* Ban `ip`. With no explicit TTL the length comes from the doubling ladder:
|
|
@@ -19373,8 +20268,8 @@ var RemediationManager = class {
|
|
|
19373
20268
|
* 4th offence and so on, clamped to `max_ban_seconds`.
|
|
19374
20269
|
*/
|
|
19375
20270
|
async ban(ip, reason, opts = {}) {
|
|
19376
|
-
if ((0,
|
|
19377
|
-
if (this.isAllowlisted(ip)) {
|
|
20271
|
+
if ((0, import_node_net14.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
|
|
20272
|
+
if (opts.strict ? this.isFleetAddress(ip) : this.isAllowlisted(ip)) {
|
|
19378
20273
|
return { ok: false, error: `${ip} is protected and can never be blocked` };
|
|
19379
20274
|
}
|
|
19380
20275
|
const now = Date.now();
|
|
@@ -19382,7 +20277,8 @@ var RemediationManager = class {
|
|
|
19382
20277
|
if (existing && !opts.ttlSeconds) {
|
|
19383
20278
|
return { ok: false, error: `${ip} is already banned` };
|
|
19384
20279
|
}
|
|
19385
|
-
|
|
20280
|
+
const dryRun = this.config.dry_run && !(opts.enforceInDryRun && this.adapter.enforces !== false);
|
|
20281
|
+
if (!dryRun) {
|
|
19386
20282
|
try {
|
|
19387
20283
|
await this.adapter.block(ip);
|
|
19388
20284
|
} catch (err) {
|
|
@@ -19415,14 +20311,19 @@ var RemediationManager = class {
|
|
|
19415
20311
|
rule_id: opts.ruleId,
|
|
19416
20312
|
blocked_at: now,
|
|
19417
20313
|
expires_at: now + ttl * 1e3,
|
|
19418
|
-
dry_run:
|
|
20314
|
+
dry_run: dryRun,
|
|
19419
20315
|
strikes: strike,
|
|
19420
|
-
source: opts.source ?? "manual"
|
|
20316
|
+
source: opts.source ?? "manual",
|
|
20317
|
+
...opts.strict ? { strict: true } : {}
|
|
19421
20318
|
};
|
|
20319
|
+
if (opts.strict) {
|
|
20320
|
+
delete this.operators[ip];
|
|
20321
|
+
this.protectedList = this.protectedList.filter((a) => a !== ip || this.pinned.has(a) || this.config.allowlist.includes(a));
|
|
20322
|
+
}
|
|
19422
20323
|
this.blocklist = this.blocklist.filter((b) => b.ip !== ip);
|
|
19423
20324
|
this.blocklist.push(entry);
|
|
19424
20325
|
this.saveState();
|
|
19425
|
-
const mode = this.config.dry_run ? "[DRY-RUN] " : "";
|
|
20326
|
+
const mode = dryRun ? "[DRY-RUN] " : this.config.dry_run ? "[ENFORCED IN DRY-RUN] " : "";
|
|
19426
20327
|
const label = `${mode}Banned ${ip} for ${formatDuration(ttl)} (offence #${strike}): ${reason}`;
|
|
19427
20328
|
this.logLine(`[firewall] ${label}`);
|
|
19428
20329
|
this.bus.publish({
|
|
@@ -19437,7 +20338,7 @@ var RemediationManager = class {
|
|
|
19437
20338
|
rule_id: opts.ruleId,
|
|
19438
20339
|
reason,
|
|
19439
20340
|
origin: opts.origin,
|
|
19440
|
-
dry_run:
|
|
20341
|
+
dry_run: dryRun,
|
|
19441
20342
|
ttl_seconds: ttl,
|
|
19442
20343
|
strikes: strike,
|
|
19443
20344
|
source: entry.source,
|
|
@@ -19520,10 +20421,13 @@ var RemediationManager = class {
|
|
|
19520
20421
|
* Saying so up front beats a dashboard that looks armed and is not.
|
|
19521
20422
|
*/
|
|
19522
20423
|
privilegeWarning() {
|
|
19523
|
-
if (!this.config.enabled
|
|
20424
|
+
if (!this.config.enabled) return void 0;
|
|
19524
20425
|
if (this.adapter.enforces === false) return void 0;
|
|
19525
20426
|
const uid = typeof process.getuid === "function" ? process.getuid() : 0;
|
|
19526
20427
|
if (uid === 0) return void 0;
|
|
20428
|
+
if (this.config.dry_run) {
|
|
20429
|
+
return this.config.block_tor_ssh ? `daemon runs as uid ${uid}: the Tor SSH ban (enforced even in dry_run) cannot write ${this.adapter.name} rules` : void 0;
|
|
20430
|
+
}
|
|
19527
20431
|
return `daemon runs as uid ${uid} and cannot write ${this.adapter.name} rules \u2014 bans will fail`;
|
|
19528
20432
|
}
|
|
19529
20433
|
addToAllowlist(ip) {
|
|
@@ -19552,10 +20456,11 @@ var RemediationManager = class {
|
|
|
19552
20456
|
*/
|
|
19553
20457
|
async reconcile() {
|
|
19554
20458
|
const now = Date.now();
|
|
19555
|
-
const
|
|
20459
|
+
const guarded = (b) => b.strict ? this.isFleetAddress(b.ip) : this.isAllowlisted(b.ip);
|
|
20460
|
+
const lifted = this.blocklist.filter(guarded);
|
|
19556
20461
|
for (const entry of lifted) this.logLine(`[firewall] reconcile: lifting ban on protected ${entry.ip}`);
|
|
19557
|
-
const live2 = this.blocklist.filter((b) => b.expires_at > now && !
|
|
19558
|
-
const stale = this.blocklist.filter((b) => b.expires_at <= now ||
|
|
20462
|
+
const live2 = this.blocklist.filter((b) => b.expires_at > now && !guarded(b));
|
|
20463
|
+
const stale = this.blocklist.filter((b) => b.expires_at <= now || guarded(b));
|
|
19559
20464
|
for (const entry of stale) {
|
|
19560
20465
|
if (!entry.dry_run) {
|
|
19561
20466
|
try {
|
|
@@ -19582,8 +20487,8 @@ var RemediationManager = class {
|
|
|
19582
20487
|
}
|
|
19583
20488
|
}
|
|
19584
20489
|
}
|
|
19585
|
-
if (this.config.dry_run) return;
|
|
19586
20490
|
for (const entry of live2) {
|
|
20491
|
+
if (entry.dry_run) continue;
|
|
19587
20492
|
if (applied?.includes(entry.ip)) continue;
|
|
19588
20493
|
try {
|
|
19589
20494
|
await this.adapter.block(entry.ip);
|
|
@@ -19640,7 +20545,8 @@ var RemediationManager = class {
|
|
|
19640
20545
|
if (saved && typeof saved === "object" && this.config.protect_recent_operators) {
|
|
19641
20546
|
const cutoff = Date.now() - this.config.operator_memory_seconds * 1e3;
|
|
19642
20547
|
for (const [ip, at] of Object.entries(saved)) {
|
|
19643
|
-
if (typeof at !== "number" || at < cutoff || !(0,
|
|
20548
|
+
if (typeof at !== "number" || at < cutoff || !(0, import_node_net14.isIP)(ip)) continue;
|
|
20549
|
+
if (this.blocklist.some((b) => b.ip === ip && b.strict)) continue;
|
|
19644
20550
|
this.operators[ip] = at;
|
|
19645
20551
|
if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
|
|
19646
20552
|
}
|
|
@@ -19664,7 +20570,7 @@ var RemediationManager = class {
|
|
|
19664
20570
|
}
|
|
19665
20571
|
logLine(line) {
|
|
19666
20572
|
try {
|
|
19667
|
-
(0,
|
|
20573
|
+
(0, import_node_fs31.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
|
|
19668
20574
|
`);
|
|
19669
20575
|
} catch {
|
|
19670
20576
|
}
|
|
@@ -19696,6 +20602,7 @@ function remediationSettings(section) {
|
|
|
19696
20602
|
}
|
|
19697
20603
|
const operatorMemory = parseDuration(section.operator_memory);
|
|
19698
20604
|
if (operatorMemory) settings.operator_memory_seconds = operatorMemory;
|
|
20605
|
+
if (typeof section.block_tor_ssh === "boolean") settings.block_tor_ssh = section.block_tor_ssh;
|
|
19699
20606
|
if (typeof section.spare_verified_crawlers === "boolean") {
|
|
19700
20607
|
settings.spare_verified_crawlers = section.spare_verified_crawlers;
|
|
19701
20608
|
}
|
|
@@ -19703,19 +20610,19 @@ function remediationSettings(section) {
|
|
|
19703
20610
|
}
|
|
19704
20611
|
|
|
19705
20612
|
// src/daemon/watchdog-service.ts
|
|
19706
|
-
var
|
|
19707
|
-
var
|
|
20613
|
+
var import_node_fs33 = require("fs");
|
|
20614
|
+
var import_node_path25 = require("path");
|
|
19708
20615
|
|
|
19709
20616
|
// src/core/watchdog.ts
|
|
19710
|
-
var
|
|
20617
|
+
var import_node_fs32 = require("fs");
|
|
19711
20618
|
var import_node_crypto7 = require("crypto");
|
|
19712
|
-
var
|
|
20619
|
+
var import_node_path24 = require("path");
|
|
19713
20620
|
var WATCHDOG_DIRNAME = "watchdog";
|
|
19714
20621
|
var LOG_FILE2 = "attacks.jsonl";
|
|
19715
20622
|
var ROTATED_FILE = "attacks.1.jsonl";
|
|
19716
20623
|
var ROTATE_BYTES = 50 * 1024 * 1024;
|
|
19717
20624
|
var SEEN_LIMIT = 5e3;
|
|
19718
|
-
var
|
|
20625
|
+
var SEVERITY_RANK7 = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
|
|
19719
20626
|
function str2(v) {
|
|
19720
20627
|
return typeof v === "string" && v !== "" && v !== "-" ? v : void 0;
|
|
19721
20628
|
}
|
|
@@ -19726,7 +20633,7 @@ function isAttack(event) {
|
|
|
19726
20633
|
const crs = typeof d.crs_score === "number" ? d.crs_score : 0;
|
|
19727
20634
|
if (crs > 0 || str2(d.attack_type)) return true;
|
|
19728
20635
|
if (event.category === "web" && typeof d.status === "number" && !str2(d.rule_id)) return false;
|
|
19729
|
-
return
|
|
20636
|
+
return SEVERITY_RANK7[event.severity] >= SEVERITY_RANK7.medium;
|
|
19730
20637
|
}
|
|
19731
20638
|
function outcomeFor(status) {
|
|
19732
20639
|
if (typeof status !== "number" || !Number.isFinite(status)) return "unknown";
|
|
@@ -19798,12 +20705,12 @@ var WatchdogLog = class {
|
|
|
19798
20705
|
stats = { logged: 0, answered: 0, errored: 0 };
|
|
19799
20706
|
constructor(dir, options = {}) {
|
|
19800
20707
|
this.dir = dir;
|
|
19801
|
-
this.file = (0,
|
|
20708
|
+
this.file = (0, import_node_path24.join)(dir, LOG_FILE2);
|
|
19802
20709
|
this.shareGid = options.shareGid;
|
|
19803
|
-
(0,
|
|
20710
|
+
(0, import_node_fs32.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
|
|
19804
20711
|
if (this.shareGid !== void 0) {
|
|
19805
|
-
(0,
|
|
19806
|
-
(0,
|
|
20712
|
+
(0, import_node_fs32.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
|
|
20713
|
+
(0, import_node_fs32.chmodSync)(dir, 1528);
|
|
19807
20714
|
}
|
|
19808
20715
|
for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
|
|
19809
20716
|
}
|
|
@@ -19832,16 +20739,16 @@ var WatchdogLog = class {
|
|
|
19832
20739
|
const chunk = this.buffer.join("\n") + "\n";
|
|
19833
20740
|
this.buffer = [];
|
|
19834
20741
|
try {
|
|
19835
|
-
if ((0,
|
|
19836
|
-
(0,
|
|
20742
|
+
if ((0, import_node_fs32.statSync)(this.file).size > ROTATE_BYTES) {
|
|
20743
|
+
(0, import_node_fs32.renameSync)(this.file, (0, import_node_path24.join)(this.dir, ROTATED_FILE));
|
|
19837
20744
|
}
|
|
19838
20745
|
} catch {
|
|
19839
20746
|
}
|
|
19840
|
-
(0,
|
|
20747
|
+
(0, import_node_fs32.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
|
|
19841
20748
|
if (this.shareGid !== void 0) {
|
|
19842
20749
|
try {
|
|
19843
|
-
(0,
|
|
19844
|
-
(0,
|
|
20750
|
+
(0, import_node_fs32.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
|
|
20751
|
+
(0, import_node_fs32.chmodSync)(this.file, 432);
|
|
19845
20752
|
} catch {
|
|
19846
20753
|
}
|
|
19847
20754
|
}
|
|
@@ -19862,21 +20769,21 @@ function parseLines(text) {
|
|
|
19862
20769
|
function readTail(file, bytes) {
|
|
19863
20770
|
let fd;
|
|
19864
20771
|
try {
|
|
19865
|
-
fd = (0,
|
|
20772
|
+
fd = (0, import_node_fs32.openSync)(file, "r");
|
|
19866
20773
|
} catch (err) {
|
|
19867
20774
|
if (err.code === "ENOENT") return [];
|
|
19868
20775
|
throw err;
|
|
19869
20776
|
}
|
|
19870
20777
|
try {
|
|
19871
|
-
const size = (0,
|
|
20778
|
+
const size = (0, import_node_fs32.fstatSync)(fd).size;
|
|
19872
20779
|
const start = Math.max(0, size - bytes);
|
|
19873
20780
|
const buf = Buffer.alloc(size - start);
|
|
19874
|
-
(0,
|
|
20781
|
+
(0, import_node_fs32.readSync)(fd, buf, 0, buf.length, start);
|
|
19875
20782
|
let text = buf.toString("utf8");
|
|
19876
20783
|
if (start > 0) text = text.slice(text.indexOf("\n") + 1);
|
|
19877
20784
|
return parseLines(text);
|
|
19878
20785
|
} finally {
|
|
19879
|
-
(0,
|
|
20786
|
+
(0, import_node_fs32.closeSync)(fd);
|
|
19880
20787
|
}
|
|
19881
20788
|
}
|
|
19882
20789
|
|
|
@@ -19885,13 +20792,13 @@ function defaultShareGid() {
|
|
|
19885
20792
|
const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
|
|
19886
20793
|
if (!isRoot2) return void 0;
|
|
19887
20794
|
try {
|
|
19888
|
-
return (0,
|
|
20795
|
+
return (0, import_node_fs33.statSync)("/var/log/auth.log").gid;
|
|
19889
20796
|
} catch {
|
|
19890
20797
|
return void 0;
|
|
19891
20798
|
}
|
|
19892
20799
|
}
|
|
19893
20800
|
function startWatchdog(opts) {
|
|
19894
|
-
const dir = opts.config?.dir ?? (0,
|
|
20801
|
+
const dir = opts.config?.dir ?? (0, import_node_path25.join)(opts.stateDir, WATCHDOG_DIRNAME);
|
|
19895
20802
|
const base = { dir, logged: 0, answered: 0, errored: 0 };
|
|
19896
20803
|
if (opts.config?.enabled === false) {
|
|
19897
20804
|
opts.log("[watchdog] off ([watchdog] enabled = false)");
|
|
@@ -19982,7 +20889,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
|
|
|
19982
20889
|
}
|
|
19983
20890
|
|
|
19984
20891
|
// src/core/node-runtime.ts
|
|
19985
|
-
var
|
|
20892
|
+
var import_node_child_process11 = require("child_process");
|
|
19986
20893
|
var MIN_DAEMON_NODE_MAJOR = 22;
|
|
19987
20894
|
function nodeMajor(version) {
|
|
19988
20895
|
const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
|
|
@@ -19998,16 +20905,16 @@ function daemonNodeProblem(version) {
|
|
|
19998
20905
|
// src/daemon/index.ts
|
|
19999
20906
|
function readVersion2() {
|
|
20000
20907
|
try {
|
|
20001
|
-
const pkg = JSON.parse((0,
|
|
20908
|
+
const pkg = JSON.parse((0, import_node_fs34.readFileSync)((0, import_node_path26.join)(__dirname, "..", "package.json"), "utf-8"));
|
|
20002
20909
|
return pkg.version || "0.0.0";
|
|
20003
20910
|
} catch {
|
|
20004
20911
|
return "0.0.0";
|
|
20005
20912
|
}
|
|
20006
20913
|
}
|
|
20007
20914
|
async function runHardeningChecks() {
|
|
20008
|
-
const { stdout } = await (0, import_node_util.promisify)(
|
|
20915
|
+
const { stdout } = await (0, import_node_util.promisify)(import_node_child_process12.execFile)(
|
|
20009
20916
|
process.execPath,
|
|
20010
|
-
[(0,
|
|
20917
|
+
[(0, import_node_path26.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
|
|
20011
20918
|
{ timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
|
|
20012
20919
|
);
|
|
20013
20920
|
const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
|
|
@@ -20019,9 +20926,9 @@ async function runHardeningChecks() {
|
|
|
20019
20926
|
return patches ? [...findings, patches] : findings;
|
|
20020
20927
|
}
|
|
20021
20928
|
async function runPatchCheck() {
|
|
20022
|
-
const { stdout } = await (0, import_node_util.promisify)(
|
|
20929
|
+
const { stdout } = await (0, import_node_util.promisify)(import_node_child_process12.execFile)(
|
|
20023
20930
|
process.execPath,
|
|
20024
|
-
[(0,
|
|
20931
|
+
[(0, import_node_path26.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
|
|
20025
20932
|
{ timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
|
|
20026
20933
|
);
|
|
20027
20934
|
const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
|
|
@@ -20029,7 +20936,7 @@ async function runPatchCheck() {
|
|
|
20029
20936
|
}
|
|
20030
20937
|
function logLine(line) {
|
|
20031
20938
|
try {
|
|
20032
|
-
(0,
|
|
20939
|
+
(0, import_node_fs34.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
|
|
20033
20940
|
`);
|
|
20034
20941
|
} catch {
|
|
20035
20942
|
}
|
|
@@ -20054,9 +20961,9 @@ async function runDaemon() {
|
|
|
20054
20961
|
logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
|
|
20055
20962
|
const restartDaemon = () => {
|
|
20056
20963
|
if (PATHS.mode === "system") {
|
|
20057
|
-
(0,
|
|
20964
|
+
(0, import_node_child_process12.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
|
|
20058
20965
|
} else {
|
|
20059
|
-
(0,
|
|
20966
|
+
(0, import_node_child_process12.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
|
|
20060
20967
|
setTimeout(() => process.exit(0), 500).unref();
|
|
20061
20968
|
}
|
|
20062
20969
|
};
|
|
@@ -20071,7 +20978,7 @@ async function runDaemon() {
|
|
|
20071
20978
|
} catch (err) {
|
|
20072
20979
|
logLine(`[daemon] state db unavailable: ${err.message}`);
|
|
20073
20980
|
}
|
|
20074
|
-
const config = loadConfig((0,
|
|
20981
|
+
const config = loadConfig((0, import_node_fs34.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
|
|
20075
20982
|
configureAttackDetection(config.detection);
|
|
20076
20983
|
const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
|
|
20077
20984
|
const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
|
|
@@ -20135,7 +21042,7 @@ async function runDaemon() {
|
|
|
20135
21042
|
const threatFeeds = new ThreatFeeds({
|
|
20136
21043
|
settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
|
|
20137
21044
|
enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
|
|
20138
|
-
cachePath: (0,
|
|
21045
|
+
cachePath: (0, import_node_path26.join)(PATHS.stateDir, "threat-feeds.json"),
|
|
20139
21046
|
bus,
|
|
20140
21047
|
log: logLine
|
|
20141
21048
|
});
|
|
@@ -20143,13 +21050,35 @@ async function runDaemon() {
|
|
|
20143
21050
|
const privilegeWatch = new PrivilegeWatch({
|
|
20144
21051
|
settings: privilegeSettings(config.privileged),
|
|
20145
21052
|
bus,
|
|
20146
|
-
snapshotPath: (0,
|
|
20147
|
-
loginsPath: (0,
|
|
20148
|
-
cursorPath: (0,
|
|
21053
|
+
snapshotPath: (0, import_node_path26.join)(PATHS.stateDir, "privileges.json"),
|
|
21054
|
+
loginsPath: (0, import_node_path26.join)(PATHS.stateDir, "login-countries.json"),
|
|
21055
|
+
cursorPath: (0, import_node_path26.join)(PATHS.stateDir, "sudo-cursor.json"),
|
|
20149
21056
|
log: logLine
|
|
20150
21057
|
});
|
|
20151
21058
|
privilegeWatch.start();
|
|
20152
|
-
new
|
|
21059
|
+
const torExits = new TorExitList({
|
|
21060
|
+
cachePath: (0, import_node_path26.join)(PATHS.stateDir, "tor-exits.txt"),
|
|
21061
|
+
url: config.remediation?.tor_exit_list_url,
|
|
21062
|
+
log: logLine
|
|
21063
|
+
});
|
|
21064
|
+
const sshIntrusion = new SshIntrusionWatch({
|
|
21065
|
+
bus,
|
|
21066
|
+
manager: remediation,
|
|
21067
|
+
tor: torExits,
|
|
21068
|
+
historyPath: (0, import_node_path26.join)(PATHS.stateDir, "key-logins.json"),
|
|
21069
|
+
keyLoginWatch: config.privileged?.key_login_watch !== false,
|
|
21070
|
+
log: logLine
|
|
21071
|
+
});
|
|
21072
|
+
sshIntrusion.start();
|
|
21073
|
+
const lightningWatch = new LightningWatch({
|
|
21074
|
+
bus,
|
|
21075
|
+
enabled: config.lightning?.enabled !== false,
|
|
21076
|
+
paths: Array.isArray(config.lightning?.log_paths) ? config.lightning.log_paths.map(String) : void 0,
|
|
21077
|
+
log: logLine
|
|
21078
|
+
});
|
|
21079
|
+
lightningWatch.start();
|
|
21080
|
+
let cloudSyncRef = null;
|
|
21081
|
+
new AlertDispatcher(bus, config, { cloudHealthy: () => cloudSyncRef?.healthy ?? false, log: logLine });
|
|
20153
21082
|
const runsWorker = new RunsWorker(bus, {
|
|
20154
21083
|
enabled: config.cloud?.enabled !== false && config.cloud?.runs === true,
|
|
20155
21084
|
scanRoots: Array.isArray(config.cloud?.run_scan_paths) ? config.cloud.run_scan_paths.filter((p) => typeof p === "string") : [],
|
|
@@ -20171,14 +21100,15 @@ async function runDaemon() {
|
|
|
20171
21100
|
cloudSync = new CloudSync({
|
|
20172
21101
|
bus,
|
|
20173
21102
|
version,
|
|
20174
|
-
hostname: (0,
|
|
21103
|
+
hostname: (0, import_node_os6.hostname)(),
|
|
20175
21104
|
minSeverity,
|
|
20176
|
-
spoolPath: (0,
|
|
21105
|
+
spoolPath: (0, import_node_path26.join)(PATHS.stateDir, "cloud-spool.jsonl"),
|
|
20177
21106
|
log: logLine,
|
|
20178
21107
|
ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
|
|
20179
21108
|
runHardening: runHardeningChecks
|
|
20180
21109
|
});
|
|
20181
21110
|
cloudSync.start();
|
|
21111
|
+
cloudSyncRef = cloudSync;
|
|
20182
21112
|
remediationConsumer = new RemediationConsumer(remediation, {
|
|
20183
21113
|
log: logLine,
|
|
20184
21114
|
restartDaemon,
|
|
@@ -20186,7 +21116,15 @@ async function runDaemon() {
|
|
|
20186
21116
|
updateNow: () => autoUpdateRef ? autoUpdateRef.check({ force: true, restartDelayMs: 3e3 }) : Promise.resolve("updater not started")
|
|
20187
21117
|
});
|
|
20188
21118
|
remediationConsumer.start();
|
|
20189
|
-
|
|
21119
|
+
const torPinned = typeof config.remediation?.block_tor_ssh === "boolean";
|
|
21120
|
+
allowlistSync = new AllowlistSync(remediation, {
|
|
21121
|
+
log: logLine,
|
|
21122
|
+
onOrgSettings: ({ block_tor_ssh }) => {
|
|
21123
|
+
if (torPinned || typeof block_tor_ssh !== "boolean" || block_tor_ssh === remediation.blockTorSsh) return;
|
|
21124
|
+
remediation.setBlockTorSsh(block_tor_ssh);
|
|
21125
|
+
logLine(`[ssh-intrusion] Tor SSH ban ${block_tor_ssh ? "ON" : "OFF"} (org setting from the dashboard)`);
|
|
21126
|
+
}
|
|
21127
|
+
});
|
|
20190
21128
|
allowlistSync.start();
|
|
20191
21129
|
const link = currentLink();
|
|
20192
21130
|
logLine(link ? `[cloud] reporting as server ${link.serverId} (org ${link.orgId}), detections >= ${minSeverity}` : "[cloud] not linked; run `threatcrush login` and `threatcrush servers link` to report to the dashboard");
|
|
@@ -20197,8 +21135,8 @@ async function runDaemon() {
|
|
|
20197
21135
|
const autoUpdate = autoUpdateRef = new AutoUpdate({
|
|
20198
21136
|
version,
|
|
20199
21137
|
settings: updateSettings(config.update),
|
|
20200
|
-
pkgRoot: (0,
|
|
20201
|
-
statePath: (0,
|
|
21138
|
+
pkgRoot: (0, import_node_path26.join)(__dirname, ".."),
|
|
21139
|
+
statePath: (0, import_node_path26.join)(PATHS.stateDir, "auto-update.json"),
|
|
20202
21140
|
bus,
|
|
20203
21141
|
log: logLine,
|
|
20204
21142
|
restartDaemon
|
|
@@ -20253,6 +21191,14 @@ async function runDaemon() {
|
|
|
20253
21191
|
privilegeWatch.stop();
|
|
20254
21192
|
} catch {
|
|
20255
21193
|
}
|
|
21194
|
+
try {
|
|
21195
|
+
sshIntrusion.stop();
|
|
21196
|
+
} catch {
|
|
21197
|
+
}
|
|
21198
|
+
try {
|
|
21199
|
+
lightningWatch.stop();
|
|
21200
|
+
} catch {
|
|
21201
|
+
}
|
|
20256
21202
|
try {
|
|
20257
21203
|
await ipc.stop();
|
|
20258
21204
|
} catch {
|