@profullstack/threatcrush 0.13.34 → 0.13.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/daemon.js CHANGED
@@ -2022,10 +2022,10 @@ var require_toml = __commonJS({
2022
2022
  });
2023
2023
 
2024
2024
  // src/daemon/index.ts
2025
- var import_node_fs26 = require("fs");
2026
- var import_node_child_process9 = require("child_process");
2025
+ var import_node_fs27 = require("fs");
2026
+ var import_node_child_process10 = require("child_process");
2027
2027
  var import_node_os5 = require("os");
2028
- var import_node_path20 = require("path");
2028
+ var import_node_path21 = require("path");
2029
2029
  var import_node_util = require("util");
2030
2030
 
2031
2031
  // src/daemon/paths.ts
@@ -10861,6 +10861,7 @@ function loadConfig(configPath) {
10861
10861
  watchdog: parsed.watchdog,
10862
10862
  update: parsed.update,
10863
10863
  threat_feeds: parsed.threat_feeds,
10864
+ privileged: parsed.privileged,
10864
10865
  storage: parsed.storage,
10865
10866
  license: parsed.license
10866
10867
  };
@@ -16255,13 +16256,13 @@ var AllowlistSync = class {
16255
16256
  const value = String(entry.value ?? "").trim();
16256
16257
  if (isAddressOrCidr(value)) wanted.add(value);
16257
16258
  }
16258
- const added = [];
16259
+ const added2 = [];
16259
16260
  const protectedNow = new Set(this.manager.getProtected());
16260
16261
  for (const value of wanted) {
16261
16262
  if (this.owned.has(value) || protectedNow.has(value)) continue;
16262
16263
  this.manager.addToAllowlist(value);
16263
16264
  this.owned.add(value);
16264
- added.push(value);
16265
+ added2.push(value);
16265
16266
  }
16266
16267
  const removed = [];
16267
16268
  for (const value of this.owned) {
@@ -16270,9 +16271,9 @@ var AllowlistSync = class {
16270
16271
  this.owned.delete(value);
16271
16272
  removed.push(value);
16272
16273
  }
16273
- if (added.length > 0 || removed.length > 0) {
16274
+ if (added2.length > 0 || removed.length > 0) {
16274
16275
  this.opts.log(
16275
- `[cloud] org allowlist: +${added.length} -${removed.length} (${[...added.map((v) => `+${v}`), ...removed.map((v) => `-${v}`)].slice(0, 10).join(" ")})`
16276
+ `[cloud] org allowlist: +${added2.length} -${removed.length} (${[...added2.map((v) => `+${v}`), ...removed.map((v) => `-${v}`)].slice(0, 10).join(" ")})`
16276
16277
  );
16277
16278
  }
16278
16279
  }
@@ -16864,6 +16865,374 @@ var ThreatFeeds = class {
16864
16865
  }
16865
16866
  };
16866
16867
 
16868
+ // src/daemon/workers/privilege-watch.ts
16869
+ var import_node_fs21 = require("fs");
16870
+ var import_node_path16 = require("path");
16871
+ var import_node_child_process7 = require("child_process");
16872
+
16873
+ // src/core/privileges/index.ts
16874
+ var import_node_crypto5 = require("crypto");
16875
+ var ADMIN_GROUPS = ["sudo", "wheel", "admin"];
16876
+ function parseUsers(text) {
16877
+ const out = [];
16878
+ for (const line of text.split("\n")) {
16879
+ const f = line.split(":");
16880
+ if (f.length < 7 || line.startsWith("#")) continue;
16881
+ const uid = Number(f[2]);
16882
+ if (!f[0] || !Number.isInteger(uid)) continue;
16883
+ out.push({ name: f[0], uid, home: f[5], shell: f[6].trim() });
16884
+ }
16885
+ return out;
16886
+ }
16887
+ function parseAdminGroups(text) {
16888
+ const out = {};
16889
+ for (const line of text.split("\n")) {
16890
+ const f = line.split(":");
16891
+ if (f.length < 4 || !ADMIN_GROUPS.includes(f[0])) continue;
16892
+ out[f[0]] = f[3].trim().split(",").map((m) => m.trim()).filter(Boolean).sort();
16893
+ }
16894
+ return out;
16895
+ }
16896
+ function canLogIn(user) {
16897
+ return !/(nologin|\/false|\/sync|\/shutdown|\/halt)$/.test(user.shell);
16898
+ }
16899
+ function sudoersRules(text) {
16900
+ const joined = text.replace(/\\\n/g, " ");
16901
+ const rules = [];
16902
+ for (const raw of joined.split("\n")) {
16903
+ const line = raw.trim();
16904
+ if (!line) continue;
16905
+ if (line.startsWith("#") && !/^#include(dir)?\s/.test(line)) continue;
16906
+ rules.push(line.replace(/\s+/g, " "));
16907
+ }
16908
+ return rules;
16909
+ }
16910
+ function sudoReadsIncluded(name) {
16911
+ return !name.endsWith("~") && !name.includes(".");
16912
+ }
16913
+ function keyFingerprint(blobBase64) {
16914
+ if (!/^[A-Za-z0-9+/]+=*$/.test(blobBase64)) return null;
16915
+ const digest = (0, import_node_crypto5.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
16916
+ return `SHA256:${digest.replace(/=+$/, "")}`;
16917
+ }
16918
+ function parseAuthorizedKeys(text) {
16919
+ const out = [];
16920
+ for (const raw of text.split("\n")) {
16921
+ const line = raw.trim();
16922
+ if (!line || line.startsWith("#")) continue;
16923
+ const m = /(?:^|\s)((?:ssh|ecdsa|sk)-[\w@.-]+)\s+([A-Za-z0-9+/]+=*)(?:\s+(.*))?$/.exec(line);
16924
+ if (!m) continue;
16925
+ const fingerprint = keyFingerprint(m[2]);
16926
+ if (fingerprint) out.push({ fingerprint, type: m[1], comment: (m[3] ?? "").trim() });
16927
+ }
16928
+ return out;
16929
+ }
16930
+ function takeSnapshot(io, now = /* @__PURE__ */ new Date()) {
16931
+ const unreadable = [];
16932
+ const read = (path) => {
16933
+ const text = io.readFile(path);
16934
+ if (text === null && io.exists(path)) unreadable.push(path);
16935
+ return text;
16936
+ };
16937
+ const users = parseUsers(read("/etc/passwd") ?? "");
16938
+ const snapshot = {
16939
+ taken_at: now.toISOString(),
16940
+ uid0: users.filter((a) => a.uid === 0).map((a) => a.name).sort(),
16941
+ admin_groups: parseAdminGroups(read("/etc/group") ?? ""),
16942
+ sudoers: {},
16943
+ keys: {},
16944
+ unreadable
16945
+ };
16946
+ const sudoersFiles = ["/etc/sudoers"];
16947
+ for (const name of (io.readDir("/etc/sudoers.d") ?? []).sort()) {
16948
+ if (sudoReadsIncluded(name)) sudoersFiles.push(`/etc/sudoers.d/${name}`);
16949
+ }
16950
+ for (const path of sudoersFiles) {
16951
+ const text = read(path);
16952
+ if (text !== null) snapshot.sudoers[path] = sudoersRules(text);
16953
+ }
16954
+ for (const user of users) {
16955
+ if (user.uid !== 0 && (!canLogIn(user) || !user.home || user.home === "/")) continue;
16956
+ const keys = {};
16957
+ for (const file of ["authorized_keys", "authorized_keys2"]) {
16958
+ const text = read(`${user.home.replace(/\/$/, "")}/.ssh/${file}`);
16959
+ for (const k of parseAuthorizedKeys(text ?? "")) keys[k.fingerprint] = { type: k.type, comment: k.comment };
16960
+ }
16961
+ if (Object.keys(keys).length > 0) snapshot.keys[user.name] = keys;
16962
+ }
16963
+ return snapshot;
16964
+ }
16965
+ var added = (before, after) => after.filter((x) => !before.includes(x));
16966
+ function diffSnapshots(prev, next) {
16967
+ const changes = [];
16968
+ for (const name of added(prev.uid0, next.uid0)) {
16969
+ changes.push({ severity: "critical", message: `New uid 0 account: ${name}`, details: { rule_id: "priv-uid0-added", account: name } });
16970
+ }
16971
+ for (const name of added(next.uid0, prev.uid0)) {
16972
+ changes.push({ severity: "low", message: `uid 0 account removed: ${name}`, details: { rule_id: "priv-uid0-removed", account: name } });
16973
+ }
16974
+ for (const group of /* @__PURE__ */ new Set([...Object.keys(prev.admin_groups), ...Object.keys(next.admin_groups)])) {
16975
+ const before = prev.admin_groups[group] ?? [];
16976
+ const after = next.admin_groups[group] ?? [];
16977
+ for (const m of added(before, after)) {
16978
+ changes.push({ severity: "high", message: `${m} added to the ${group} group (can run anything as root)`, details: { rule_id: "priv-admin-group-added", group, account: m } });
16979
+ }
16980
+ for (const m of added(after, before)) {
16981
+ changes.push({ severity: "low", message: `${m} removed from the ${group} group`, details: { rule_id: "priv-admin-group-removed", group, account: m } });
16982
+ }
16983
+ }
16984
+ for (const path of /* @__PURE__ */ new Set([...Object.keys(prev.sudoers), ...Object.keys(next.sudoers)])) {
16985
+ if (next.unreadable.includes(path) || prev.unreadable.includes(path)) continue;
16986
+ const before = prev.sudoers[path];
16987
+ const after = next.sudoers[path];
16988
+ if (!before && after) {
16989
+ changes.push({ severity: "high", message: `New sudoers file ${path}${after.length ? `: ${after.slice(0, 3).join(" | ")}` : ""}`, details: { rule_id: "priv-sudoers-added", path, rules: after.slice(0, 20) } });
16990
+ continue;
16991
+ }
16992
+ if (before && !after) {
16993
+ changes.push({ severity: "low", message: `Sudoers file removed: ${path}`, details: { rule_id: "priv-sudoers-removed", path } });
16994
+ continue;
16995
+ }
16996
+ const plus = added(before ?? [], after ?? []);
16997
+ const minus = added(after ?? [], before ?? []);
16998
+ if (plus.length) {
16999
+ changes.push({ severity: "high", message: `Sudoers rule added in ${path}: ${plus.slice(0, 3).join(" | ")}`, details: { rule_id: "priv-sudoers-changed", path, added: plus.slice(0, 20), removed: minus.slice(0, 20) } });
17000
+ } else if (minus.length) {
17001
+ changes.push({ severity: "low", message: `Sudoers rule removed in ${path}: ${minus.slice(0, 3).join(" | ")}`, details: { rule_id: "priv-sudoers-changed", path, removed: minus.slice(0, 20) } });
17002
+ }
17003
+ }
17004
+ for (const user of /* @__PURE__ */ new Set([...Object.keys(prev.keys), ...Object.keys(next.keys)])) {
17005
+ const before = prev.keys[user] ?? {};
17006
+ const after = next.keys[user] ?? {};
17007
+ for (const fp of Object.keys(after)) {
17008
+ if (before[fp]) continue;
17009
+ const { type, comment } = after[fp];
17010
+ changes.push({
17011
+ severity: "high",
17012
+ message: `New SSH key for ${user}: ${type} ${fp}${comment ? ` (${comment})` : ""}`,
17013
+ details: { rule_id: "priv-authorized-key-added", account: user, fingerprint: fp, key_type: type, comment }
17014
+ });
17015
+ }
17016
+ for (const fp of Object.keys(before)) {
17017
+ if (after[fp]) continue;
17018
+ changes.push({ severity: "low", message: `SSH key removed for ${user}: ${fp}`, details: { rule_id: "priv-authorized-key-removed", account: user, fingerprint: fp } });
17019
+ }
17020
+ }
17021
+ const rank = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
17022
+ return changes.sort((a, b) => rank[b.severity] - rank[a.severity]);
17023
+ }
17024
+ function parseSudoMessage(message) {
17025
+ const m = /^\s*(\S+)\s+:\s+(.*)$/.exec(message);
17026
+ if (!m) return null;
17027
+ const fields = {};
17028
+ let reason = "";
17029
+ for (const part of m[2].split(" ; ")) {
17030
+ const kv = /^([A-Z]+)=(.*)$/.exec(part.trim());
17031
+ if (kv) fields[kv[1]] = kv[2];
17032
+ else if (!reason) reason = part.trim();
17033
+ }
17034
+ if (!fields.COMMAND) return null;
17035
+ if (/incorrect password|authentication failure/i.test(reason)) return null;
17036
+ return {
17037
+ user: m[1],
17038
+ runas: fields.USER ?? "root",
17039
+ command: fields.COMMAND,
17040
+ tty: fields.TTY,
17041
+ pwd: fields.PWD,
17042
+ denied: /not allowed|not in the sudoers|NOT in sudoers|command not allowed/i.test(reason)
17043
+ };
17044
+ }
17045
+
17046
+ // src/daemon/workers/privilege-watch.ts
17047
+ function privilegeSettings(section) {
17048
+ return { enabled: section?.enabled !== false, geo: section?.geo !== false, pollMs: 6e4 };
17049
+ }
17050
+ var COUNTRY_NAMES = new Intl.DisplayNames(["en"], { type: "region" });
17051
+ function countryName(code) {
17052
+ try {
17053
+ return COUNTRY_NAMES.of(code) ?? code;
17054
+ } catch {
17055
+ return code;
17056
+ }
17057
+ }
17058
+ var fsIO = {
17059
+ readFile: (p) => {
17060
+ try {
17061
+ return (0, import_node_fs21.readFileSync)(p, "utf-8");
17062
+ } catch {
17063
+ return null;
17064
+ }
17065
+ },
17066
+ readDir: (p) => {
17067
+ try {
17068
+ return (0, import_node_fs21.readdirSync)(p);
17069
+ } catch {
17070
+ return null;
17071
+ }
17072
+ },
17073
+ exists: (p) => (0, import_node_fs21.existsSync)(p)
17074
+ };
17075
+ function readJson(path) {
17076
+ try {
17077
+ return JSON.parse((0, import_node_fs21.readFileSync)(path, "utf-8"));
17078
+ } catch {
17079
+ return null;
17080
+ }
17081
+ }
17082
+ function writeJson(path, value) {
17083
+ (0, import_node_fs21.mkdirSync)((0, import_node_path16.dirname)(path), { recursive: true });
17084
+ (0, import_node_fs21.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
17085
+ (0, import_node_fs21.renameSync)(`${path}.tmp`, path);
17086
+ }
17087
+ function defaultRun3(cmd, args) {
17088
+ const res = (0, import_node_child_process7.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 2e4, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
17089
+ return res.status === 0 ? res.stdout : null;
17090
+ }
17091
+ async function geolocateViaThreatcrush(ip, fetchImpl = fetch) {
17092
+ const res = await fetchImpl("https://threatcrush.com/api/geo", {
17093
+ method: "POST",
17094
+ headers: { "Content-Type": "application/json" },
17095
+ body: JSON.stringify({ ips: [ip] }),
17096
+ signal: AbortSignal.timeout(8e3)
17097
+ });
17098
+ if (!res.ok) return null;
17099
+ const body = await res.json();
17100
+ const code = body.results?.[ip]?.countryCode;
17101
+ return typeof code === "string" && /^[A-Z]{2}$/.test(code) ? { countryCode: code } : null;
17102
+ }
17103
+ var PrivilegeWatch = class {
17104
+ constructor(opts) {
17105
+ this.opts = opts;
17106
+ this.io = opts.io ?? fsIO;
17107
+ this.run = opts.run ?? defaultRun3;
17108
+ this.now = opts.now ?? (() => /* @__PURE__ */ new Date());
17109
+ }
17110
+ opts;
17111
+ timers = [];
17112
+ io;
17113
+ run;
17114
+ now;
17115
+ warnedUnreadable = false;
17116
+ onEvent = (event) => {
17117
+ void this.checkLogin(event);
17118
+ };
17119
+ start() {
17120
+ if (!this.opts.settings.enabled) {
17121
+ this.opts.log("[privileged] disabled by [privileged] enabled = false");
17122
+ return;
17123
+ }
17124
+ this.checkSnapshot();
17125
+ this.readSudoLedger();
17126
+ if (this.opts.settings.geo) this.opts.bus.on("event", this.onEvent);
17127
+ const timer = setInterval(() => {
17128
+ this.checkSnapshot();
17129
+ this.readSudoLedger();
17130
+ }, this.opts.settings.pollMs);
17131
+ timer.unref?.();
17132
+ this.timers.push(timer);
17133
+ }
17134
+ stop() {
17135
+ for (const t of this.timers) clearInterval(t);
17136
+ this.timers = [];
17137
+ this.opts.bus.off("event", this.onEvent);
17138
+ }
17139
+ emit(severity, message, details) {
17140
+ const event = { timestamp: this.now(), module: "privileged-access", category: "auth", severity, message, details };
17141
+ try {
17142
+ insertEvent(event);
17143
+ } catch {
17144
+ }
17145
+ this.opts.bus.publish(event);
17146
+ }
17147
+ checkSnapshot() {
17148
+ const next = takeSnapshot(this.io, this.now());
17149
+ if (next.unreadable.length && !this.warnedUnreadable) {
17150
+ this.warnedUnreadable = true;
17151
+ this.opts.log(`[privileged] cannot read ${next.unreadable.join(", ")}; run the daemon as root to watch them`);
17152
+ }
17153
+ const prev = readJson(this.opts.snapshotPath);
17154
+ if (!prev) {
17155
+ const keys = Object.values(next.keys).reduce((n, k) => n + Object.keys(k).length, 0);
17156
+ this.opts.log(`[privileged] baseline recorded: uid0 [${next.uid0.join(", ")}], ${Object.values(next.admin_groups).flat().length} admin-group member(s), ${Object.keys(next.sudoers).length} sudoers file(s), ${keys} authorized key(s)`);
17157
+ } else {
17158
+ for (const change of diffSnapshots(prev, next)) this.emit(change.severity, change.message, change.details);
17159
+ }
17160
+ try {
17161
+ writeJson(this.opts.snapshotPath, next);
17162
+ } catch (err) {
17163
+ this.opts.log(`[privileged] could not save snapshot: ${err.message}`);
17164
+ }
17165
+ }
17166
+ /**
17167
+ * New sudo records since the saved journal cursor. The first run only finds
17168
+ * the current end of the journal, so history from before the daemon is not
17169
+ * replayed as if it had just happened.
17170
+ */
17171
+ readSudoLedger() {
17172
+ const cursor = readJson(this.opts.cursorPath)?.cursor;
17173
+ const args = cursor ? ["-t", "sudo", "-o", "json", "--no-pager", `--after-cursor=${cursor}`] : ["-o", "json", "--no-pager", "-n", "0", "--show-cursor"];
17174
+ const out = this.run("journalctl", args);
17175
+ if (out === null) return;
17176
+ let last = cursor ?? /^-- cursor: (\S+)/m.exec(out)?.[1];
17177
+ for (const line of cursor ? out.split("\n") : []) {
17178
+ if (!line.trim()) continue;
17179
+ let rec;
17180
+ try {
17181
+ rec = JSON.parse(line);
17182
+ } catch {
17183
+ continue;
17184
+ }
17185
+ if (typeof rec.__CURSOR === "string") last = rec.__CURSOR;
17186
+ const entry = typeof rec.MESSAGE === "string" ? parseSudoMessage(rec.MESSAGE) : null;
17187
+ if (!entry) continue;
17188
+ this.emit(
17189
+ entry.denied ? "medium" : "info",
17190
+ entry.denied ? `sudo denied: ${entry.user} tried ${entry.command} as ${entry.runas}` : `sudo: ${entry.user} ran ${entry.command} as ${entry.runas}`,
17191
+ { rule_id: entry.denied ? "priv-sudo-denied" : "priv-sudo-command", account: entry.user, runas: entry.runas, command: entry.command, tty: entry.tty, pwd: entry.pwd }
17192
+ );
17193
+ }
17194
+ if (last && last !== cursor) {
17195
+ try {
17196
+ writeJson(this.opts.cursorPath, { cursor: last });
17197
+ } catch {
17198
+ }
17199
+ }
17200
+ }
17201
+ /** An accepted SSH login from a country new for that user. */
17202
+ async checkLogin(event) {
17203
+ if (event.module !== "ssh-guard" || !event.source_ip) return;
17204
+ const user = /SSH login accepted for (\S+)/.exec(event.message)?.[1];
17205
+ if (!user || user === "unknown" || isProtected(event.source_ip, DEFAULT_PROTECTED)) return;
17206
+ let geo = null;
17207
+ try {
17208
+ geo = await (this.opts.geolocate ?? geolocateViaThreatcrush)(event.source_ip);
17209
+ } catch (err) {
17210
+ this.opts.log(`[privileged] geolocation failed for ${event.source_ip}: ${err.message}`);
17211
+ }
17212
+ const country = geo?.countryCode;
17213
+ if (!country || !/^[A-Z]{2}$/.test(country)) return;
17214
+ const history = readJson(this.opts.loginsPath) ?? {};
17215
+ const seen = history[user] ?? {};
17216
+ const at = this.now().toISOString();
17217
+ const known = Object.keys(seen);
17218
+ if (known.length > 0 && !seen[country]) {
17219
+ this.emit("high", `SSH login for ${user} from a new country: ${countryName(country)}, ${event.source_ip}; seen before from ${known.join(", ")}`, {
17220
+ rule_id: "priv-login-new-country",
17221
+ account: user,
17222
+ login_ip: event.source_ip,
17223
+ country,
17224
+ known_countries: known
17225
+ });
17226
+ }
17227
+ seen[country] = { first: seen[country]?.first ?? at, last: at };
17228
+ history[user] = seen;
17229
+ try {
17230
+ writeJson(this.opts.loginsPath, history);
17231
+ } catch {
17232
+ }
17233
+ }
17234
+ };
17235
+
16867
17236
  // src/daemon/rules/engine.ts
16868
17237
  var MAX_WINDOW_ENTRIES = 1e3;
16869
17238
  function live(window) {
@@ -17025,8 +17394,8 @@ var RuleEngine = class {
17025
17394
  };
17026
17395
 
17027
17396
  // src/daemon/rules/loader.ts
17028
- var import_node_fs21 = require("fs");
17029
- var import_node_path16 = require("path");
17397
+ var import_node_fs22 = require("fs");
17398
+ var import_node_path17 = require("path");
17030
17399
 
17031
17400
  // src/daemon/rules/default-rules.ts
17032
17401
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -17427,11 +17796,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
17427
17796
  function loadAllRules(customDir) {
17428
17797
  const rules = [...DEFAULT_RULES];
17429
17798
  const dir = customDir || RULES_DIR;
17430
- if ((0, import_node_fs21.existsSync)(dir)) {
17431
- const files = (0, import_node_fs21.readdirSync)(dir).filter((f) => f.endsWith(".json"));
17799
+ if ((0, import_node_fs22.existsSync)(dir)) {
17800
+ const files = (0, import_node_fs22.readdirSync)(dir).filter((f) => f.endsWith(".json"));
17432
17801
  for (const file of files) {
17433
17802
  try {
17434
- const raw = (0, import_node_fs21.readFileSync)((0, import_node_path16.join)(dir, file), "utf-8");
17803
+ const raw = (0, import_node_fs22.readFileSync)((0, import_node_path17.join)(dir, file), "utf-8");
17435
17804
  const parsed = JSON.parse(raw);
17436
17805
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
17437
17806
  for (const rule of customRules) {
@@ -17462,9 +17831,9 @@ function loadAllRules(customDir) {
17462
17831
  }
17463
17832
 
17464
17833
  // src/daemon/firewall/adapters.ts
17465
- var import_node_child_process7 = require("child_process");
17466
- var import_node_fs22 = require("fs");
17467
- var import_node_path17 = require("path");
17834
+ var import_node_child_process8 = require("child_process");
17835
+ var import_node_fs23 = require("fs");
17836
+ var import_node_path18 = require("path");
17468
17837
  var import_node_net8 = require("net");
17469
17838
  function assertValidFirewallIp(ip) {
17470
17839
  if ((0, import_node_net8.isIP)(ip) !== 4) {
@@ -17477,9 +17846,9 @@ function assertBannableIp(ip) {
17477
17846
  }
17478
17847
  }
17479
17848
  function writeIfAbsent(path, contents) {
17480
- (0, import_node_fs22.mkdirSync)((0, import_node_path17.dirname)(path), { recursive: true });
17849
+ (0, import_node_fs23.mkdirSync)((0, import_node_path18.dirname)(path), { recursive: true });
17481
17850
  try {
17482
- (0, import_node_fs22.writeFileSync)(path, contents, { flag: "wx" });
17851
+ (0, import_node_fs23.writeFileSync)(path, contents, { flag: "wx" });
17483
17852
  } catch (err) {
17484
17853
  if (err.code !== "EEXIST") throw err;
17485
17854
  }
@@ -17498,11 +17867,11 @@ var Fail2banAdapter = class {
17498
17867
  enforces = true;
17499
17868
  jailReady = false;
17500
17869
  isAvailable() {
17501
- const result = (0, import_node_child_process7.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
17870
+ const result = (0, import_node_child_process8.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
17502
17871
  return result.status === 0;
17503
17872
  }
17504
17873
  client(args) {
17505
- return (0, import_node_child_process7.execFileSync)("fail2ban-client", args, {
17874
+ return (0, import_node_child_process8.execFileSync)("fail2ban-client", args, {
17506
17875
  encoding: "utf-8",
17507
17876
  stdio: ["ignore", "pipe", "pipe"]
17508
17877
  });
@@ -17598,35 +17967,35 @@ var NftablesAdapter = class {
17598
17967
  table = "threatcrush";
17599
17968
  set = "blocklist";
17600
17969
  isAvailable() {
17601
- const result = (0, import_node_child_process7.spawnSync)("nft", ["--version"], { stdio: "pipe" });
17970
+ const result = (0, import_node_child_process8.spawnSync)("nft", ["--version"], { stdio: "pipe" });
17602
17971
  return result.status === 0;
17603
17972
  }
17604
17973
  ensureSetup() {
17605
17974
  try {
17606
- (0, import_node_child_process7.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
17975
+ (0, import_node_child_process8.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
17607
17976
  } catch {
17608
- (0, import_node_child_process7.execSync)(`nft add table inet ${this.table}`);
17609
- (0, import_node_child_process7.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
17610
- (0, import_node_child_process7.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
17611
- (0, import_node_child_process7.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
17977
+ (0, import_node_child_process8.execSync)(`nft add table inet ${this.table}`);
17978
+ (0, import_node_child_process8.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
17979
+ (0, import_node_child_process8.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
17980
+ (0, import_node_child_process8.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
17612
17981
  }
17613
17982
  }
17614
17983
  async block(ip) {
17615
17984
  assertValidFirewallIp(ip);
17616
17985
  this.ensureSetup();
17617
- (0, import_node_child_process7.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
17986
+ (0, import_node_child_process8.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
17618
17987
  }
17619
17988
  async unblock(ip) {
17620
17989
  assertValidFirewallIp(ip);
17621
17990
  try {
17622
- (0, import_node_child_process7.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
17991
+ (0, import_node_child_process8.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
17623
17992
  } catch {
17624
17993
  }
17625
17994
  }
17626
17995
  async isBlocked(ip) {
17627
17996
  assertValidFirewallIp(ip);
17628
17997
  try {
17629
- const output = (0, import_node_child_process7.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
17998
+ const output = (0, import_node_child_process8.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
17630
17999
  return output.includes(ip);
17631
18000
  } catch {
17632
18001
  return false;
@@ -17634,7 +18003,7 @@ var NftablesAdapter = class {
17634
18003
  }
17635
18004
  async listBlocked() {
17636
18005
  try {
17637
- const output = (0, import_node_child_process7.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
18006
+ const output = (0, import_node_child_process8.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
17638
18007
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
17639
18008
  if (!match) return [];
17640
18009
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -17647,34 +18016,34 @@ var IptablesAdapter = class {
17647
18016
  name = "iptables";
17648
18017
  chain = "THREATCRUSH";
17649
18018
  isAvailable() {
17650
- const result = (0, import_node_child_process7.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
18019
+ const result = (0, import_node_child_process8.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
17651
18020
  return result.status === 0;
17652
18021
  }
17653
18022
  ensureChain() {
17654
18023
  try {
17655
- (0, import_node_child_process7.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
18024
+ (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
17656
18025
  } catch {
17657
- (0, import_node_child_process7.execSync)(`iptables -N ${this.chain}`);
17658
- (0, import_node_child_process7.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
18026
+ (0, import_node_child_process8.execSync)(`iptables -N ${this.chain}`);
18027
+ (0, import_node_child_process8.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
17659
18028
  }
17660
18029
  }
17661
18030
  async block(ip) {
17662
18031
  assertValidFirewallIp(ip);
17663
18032
  this.ensureChain();
17664
18033
  if (await this.isBlocked(ip)) return;
17665
- (0, import_node_child_process7.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
18034
+ (0, import_node_child_process8.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
17666
18035
  }
17667
18036
  async unblock(ip) {
17668
18037
  assertValidFirewallIp(ip);
17669
18038
  try {
17670
- (0, import_node_child_process7.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
18039
+ (0, import_node_child_process8.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
17671
18040
  } catch {
17672
18041
  }
17673
18042
  }
17674
18043
  async isBlocked(ip) {
17675
18044
  assertValidFirewallIp(ip);
17676
18045
  try {
17677
- const output = (0, import_node_child_process7.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
18046
+ const output = (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
17678
18047
  return output.includes(ip);
17679
18048
  } catch {
17680
18049
  return false;
@@ -17682,7 +18051,7 @@ var IptablesAdapter = class {
17682
18051
  }
17683
18052
  async listBlocked() {
17684
18053
  try {
17685
- const output = (0, import_node_child_process7.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
18054
+ const output = (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
17686
18055
  const ips = [];
17687
18056
  for (const line of output.split("\n")) {
17688
18057
  const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -17738,7 +18107,7 @@ function detectFirewallAdapter(backend = "auto") {
17738
18107
  }
17739
18108
 
17740
18109
  // src/daemon/firewall/remediation.ts
17741
- var import_node_fs23 = require("fs");
18110
+ var import_node_fs24 = require("fs");
17742
18111
  var import_node_net9 = require("net");
17743
18112
 
17744
18113
  // src/daemon/firewall/crawlers.ts
@@ -18150,7 +18519,7 @@ var RemediationManager = class {
18150
18519
  }
18151
18520
  logLine(line) {
18152
18521
  try {
18153
- (0, import_node_fs23.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18522
+ (0, import_node_fs24.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18154
18523
  `);
18155
18524
  } catch {
18156
18525
  }
@@ -18184,13 +18553,13 @@ function remediationSettings(section) {
18184
18553
  }
18185
18554
 
18186
18555
  // src/daemon/watchdog-service.ts
18187
- var import_node_fs25 = require("fs");
18188
- var import_node_path19 = require("path");
18556
+ var import_node_fs26 = require("fs");
18557
+ var import_node_path20 = require("path");
18189
18558
 
18190
18559
  // src/core/watchdog.ts
18191
- var import_node_fs24 = require("fs");
18192
- var import_node_crypto5 = require("crypto");
18193
- var import_node_path18 = require("path");
18560
+ var import_node_fs25 = require("fs");
18561
+ var import_node_crypto6 = require("crypto");
18562
+ var import_node_path19 = require("path");
18194
18563
  var WATCHDOG_DIRNAME = "watchdog";
18195
18564
  var LOG_FILE = "attacks.jsonl";
18196
18565
  var ROTATED_FILE = "attacks.1.jsonl";
@@ -18230,7 +18599,7 @@ function signatureOf(r) {
18230
18599
  return ["msg", r.module, shape].join("|");
18231
18600
  }
18232
18601
  function findingId(signature) {
18233
- return (0, import_node_crypto5.createHash)("sha1").update(signature).digest("hex").slice(0, 10);
18602
+ return (0, import_node_crypto6.createHash)("sha1").update(signature).digest("hex").slice(0, 10);
18234
18603
  }
18235
18604
  function toRecord(event) {
18236
18605
  const d = event.details ?? {};
@@ -18279,12 +18648,12 @@ var WatchdogLog = class {
18279
18648
  stats = { logged: 0, answered: 0, errored: 0 };
18280
18649
  constructor(dir, options = {}) {
18281
18650
  this.dir = dir;
18282
- this.file = (0, import_node_path18.join)(dir, LOG_FILE);
18651
+ this.file = (0, import_node_path19.join)(dir, LOG_FILE);
18283
18652
  this.shareGid = options.shareGid;
18284
- (0, import_node_fs24.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
18653
+ (0, import_node_fs25.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
18285
18654
  if (this.shareGid !== void 0) {
18286
- (0, import_node_fs24.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
18287
- (0, import_node_fs24.chmodSync)(dir, 1528);
18655
+ (0, import_node_fs25.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
18656
+ (0, import_node_fs25.chmodSync)(dir, 1528);
18288
18657
  }
18289
18658
  for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
18290
18659
  }
@@ -18313,16 +18682,16 @@ var WatchdogLog = class {
18313
18682
  const chunk = this.buffer.join("\n") + "\n";
18314
18683
  this.buffer = [];
18315
18684
  try {
18316
- if ((0, import_node_fs24.statSync)(this.file).size > ROTATE_BYTES) {
18317
- (0, import_node_fs24.renameSync)(this.file, (0, import_node_path18.join)(this.dir, ROTATED_FILE));
18685
+ if ((0, import_node_fs25.statSync)(this.file).size > ROTATE_BYTES) {
18686
+ (0, import_node_fs25.renameSync)(this.file, (0, import_node_path19.join)(this.dir, ROTATED_FILE));
18318
18687
  }
18319
18688
  } catch {
18320
18689
  }
18321
- (0, import_node_fs24.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
18690
+ (0, import_node_fs25.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
18322
18691
  if (this.shareGid !== void 0) {
18323
18692
  try {
18324
- (0, import_node_fs24.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
18325
- (0, import_node_fs24.chmodSync)(this.file, 432);
18693
+ (0, import_node_fs25.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
18694
+ (0, import_node_fs25.chmodSync)(this.file, 432);
18326
18695
  } catch {
18327
18696
  }
18328
18697
  }
@@ -18343,21 +18712,21 @@ function parseLines(text) {
18343
18712
  function readTail(file, bytes) {
18344
18713
  let fd;
18345
18714
  try {
18346
- fd = (0, import_node_fs24.openSync)(file, "r");
18715
+ fd = (0, import_node_fs25.openSync)(file, "r");
18347
18716
  } catch (err) {
18348
18717
  if (err.code === "ENOENT") return [];
18349
18718
  throw err;
18350
18719
  }
18351
18720
  try {
18352
- const size = (0, import_node_fs24.fstatSync)(fd).size;
18721
+ const size = (0, import_node_fs25.fstatSync)(fd).size;
18353
18722
  const start = Math.max(0, size - bytes);
18354
18723
  const buf = Buffer.alloc(size - start);
18355
- (0, import_node_fs24.readSync)(fd, buf, 0, buf.length, start);
18724
+ (0, import_node_fs25.readSync)(fd, buf, 0, buf.length, start);
18356
18725
  let text = buf.toString("utf8");
18357
18726
  if (start > 0) text = text.slice(text.indexOf("\n") + 1);
18358
18727
  return parseLines(text);
18359
18728
  } finally {
18360
- (0, import_node_fs24.closeSync)(fd);
18729
+ (0, import_node_fs25.closeSync)(fd);
18361
18730
  }
18362
18731
  }
18363
18732
 
@@ -18366,13 +18735,13 @@ function defaultShareGid() {
18366
18735
  const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
18367
18736
  if (!isRoot2) return void 0;
18368
18737
  try {
18369
- return (0, import_node_fs25.statSync)("/var/log/auth.log").gid;
18738
+ return (0, import_node_fs26.statSync)("/var/log/auth.log").gid;
18370
18739
  } catch {
18371
18740
  return void 0;
18372
18741
  }
18373
18742
  }
18374
18743
  function startWatchdog(opts) {
18375
- const dir = opts.config?.dir ?? (0, import_node_path19.join)(opts.stateDir, WATCHDOG_DIRNAME);
18744
+ const dir = opts.config?.dir ?? (0, import_node_path20.join)(opts.stateDir, WATCHDOG_DIRNAME);
18376
18745
  const base = { dir, logged: 0, answered: 0, errored: 0 };
18377
18746
  if (opts.config?.enabled === false) {
18378
18747
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -18463,7 +18832,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
18463
18832
  }
18464
18833
 
18465
18834
  // src/core/node-runtime.ts
18466
- var import_node_child_process8 = require("child_process");
18835
+ var import_node_child_process9 = require("child_process");
18467
18836
  var MIN_DAEMON_NODE_MAJOR = 22;
18468
18837
  function nodeMajor(version) {
18469
18838
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -18479,16 +18848,16 @@ function daemonNodeProblem(version) {
18479
18848
  // src/daemon/index.ts
18480
18849
  function readVersion2() {
18481
18850
  try {
18482
- const pkg = JSON.parse((0, import_node_fs26.readFileSync)((0, import_node_path20.join)(__dirname, "..", "package.json"), "utf-8"));
18851
+ const pkg = JSON.parse((0, import_node_fs27.readFileSync)((0, import_node_path21.join)(__dirname, "..", "package.json"), "utf-8"));
18483
18852
  return pkg.version || "0.0.0";
18484
18853
  } catch {
18485
18854
  return "0.0.0";
18486
18855
  }
18487
18856
  }
18488
18857
  async function runHardeningChecks() {
18489
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process9.execFile)(
18858
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process10.execFile)(
18490
18859
  process.execPath,
18491
- [(0, import_node_path20.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
18860
+ [(0, import_node_path21.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
18492
18861
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
18493
18862
  );
18494
18863
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -18500,9 +18869,9 @@ async function runHardeningChecks() {
18500
18869
  return patches ? [...findings, patches] : findings;
18501
18870
  }
18502
18871
  async function runPatchCheck() {
18503
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process9.execFile)(
18872
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process10.execFile)(
18504
18873
  process.execPath,
18505
- [(0, import_node_path20.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
18874
+ [(0, import_node_path21.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
18506
18875
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
18507
18876
  );
18508
18877
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -18510,7 +18879,7 @@ async function runPatchCheck() {
18510
18879
  }
18511
18880
  function logLine(line) {
18512
18881
  try {
18513
- (0, import_node_fs26.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18882
+ (0, import_node_fs27.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
18514
18883
  `);
18515
18884
  } catch {
18516
18885
  }
@@ -18535,9 +18904,9 @@ async function runDaemon() {
18535
18904
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
18536
18905
  const restartDaemon = () => {
18537
18906
  if (PATHS.mode === "system") {
18538
- (0, import_node_child_process9.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
18907
+ (0, import_node_child_process10.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
18539
18908
  } else {
18540
- (0, import_node_child_process9.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
18909
+ (0, import_node_child_process10.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
18541
18910
  setTimeout(() => process.exit(0), 500).unref();
18542
18911
  }
18543
18912
  };
@@ -18552,7 +18921,7 @@ async function runDaemon() {
18552
18921
  } catch (err) {
18553
18922
  logLine(`[daemon] state db unavailable: ${err.message}`);
18554
18923
  }
18555
- const config = loadConfig((0, import_node_fs26.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
18924
+ const config = loadConfig((0, import_node_fs27.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
18556
18925
  configureAttackDetection(config.detection);
18557
18926
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
18558
18927
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -18616,11 +18985,20 @@ async function runDaemon() {
18616
18985
  const threatFeeds = new ThreatFeeds({
18617
18986
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
18618
18987
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
18619
- cachePath: (0, import_node_path20.join)(PATHS.stateDir, "threat-feeds.json"),
18988
+ cachePath: (0, import_node_path21.join)(PATHS.stateDir, "threat-feeds.json"),
18620
18989
  bus,
18621
18990
  log: logLine
18622
18991
  });
18623
18992
  threatFeeds.start();
18993
+ const privilegeWatch = new PrivilegeWatch({
18994
+ settings: privilegeSettings(config.privileged),
18995
+ bus,
18996
+ snapshotPath: (0, import_node_path21.join)(PATHS.stateDir, "privileges.json"),
18997
+ loginsPath: (0, import_node_path21.join)(PATHS.stateDir, "login-countries.json"),
18998
+ cursorPath: (0, import_node_path21.join)(PATHS.stateDir, "sudo-cursor.json"),
18999
+ log: logLine
19000
+ });
19001
+ privilegeWatch.start();
18624
19002
  new AlertDispatcher(bus, config);
18625
19003
  const runsWorker = new RunsWorker(bus);
18626
19004
  try {
@@ -18640,7 +19018,7 @@ async function runDaemon() {
18640
19018
  version,
18641
19019
  hostname: (0, import_node_os5.hostname)(),
18642
19020
  minSeverity,
18643
- spoolPath: (0, import_node_path20.join)(PATHS.stateDir, "cloud-spool.jsonl"),
19021
+ spoolPath: (0, import_node_path21.join)(PATHS.stateDir, "cloud-spool.jsonl"),
18644
19022
  log: logLine,
18645
19023
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
18646
19024
  runHardening: runHardeningChecks
@@ -18657,8 +19035,8 @@ async function runDaemon() {
18657
19035
  const autoUpdate = new AutoUpdate({
18658
19036
  version,
18659
19037
  settings: updateSettings(config.update),
18660
- pkgRoot: (0, import_node_path20.join)(__dirname, ".."),
18661
- statePath: (0, import_node_path20.join)(PATHS.stateDir, "auto-update.json"),
19038
+ pkgRoot: (0, import_node_path21.join)(__dirname, ".."),
19039
+ statePath: (0, import_node_path21.join)(PATHS.stateDir, "auto-update.json"),
18662
19040
  bus,
18663
19041
  log: logLine,
18664
19042
  restartDaemon
@@ -18705,6 +19083,10 @@ async function runDaemon() {
18705
19083
  threatFeeds.stop();
18706
19084
  } catch {
18707
19085
  }
19086
+ try {
19087
+ privilegeWatch.stop();
19088
+ } catch {
19089
+ }
18708
19090
  try {
18709
19091
  await ipc.stop();
18710
19092
  } catch {