@profullstack/threatcrush 0.13.34 → 0.13.36

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/index.js CHANGED
@@ -6241,22 +6241,22 @@ var init_diff = __esm({
6241
6241
  s.fg = DEFAULT_COLOR;
6242
6242
  s.bg = DEFAULT_COLOR;
6243
6243
  }
6244
- const added = attrs & ~s.attrs;
6245
- if (added !== 0) {
6244
+ const added2 = attrs & ~s.attrs;
6245
+ if (added2 !== 0) {
6246
6246
  const codes = [];
6247
- if (added & Attr.Bold)
6247
+ if (added2 & Attr.Bold)
6248
6248
  codes.push(1);
6249
- if (added & Attr.Dim)
6249
+ if (added2 & Attr.Dim)
6250
6250
  codes.push(2);
6251
- if (added & Attr.Italic)
6251
+ if (added2 & Attr.Italic)
6252
6252
  codes.push(3);
6253
- if (added & Attr.Underline)
6253
+ if (added2 & Attr.Underline)
6254
6254
  codes.push(4);
6255
- if (added & Attr.Blink)
6255
+ if (added2 & Attr.Blink)
6256
6256
  codes.push(5);
6257
- if (added & Attr.Reverse)
6257
+ if (added2 & Attr.Reverse)
6258
6258
  codes.push(7);
6259
- if (added & Attr.Strike)
6259
+ if (added2 & Attr.Strike)
6260
6260
  codes.push(9);
6261
6261
  if (codes.length)
6262
6262
  this.parts.push(`${CSI}${codes.join(";")}m`);
@@ -21537,7 +21537,7 @@ var init_map = __esm({
21537
21537
  this.selfAsked = true;
21538
21538
  void this.lookupSelf();
21539
21539
  }
21540
- let added = false;
21540
+ let added2 = false;
21541
21541
  for (const ip of ips) {
21542
21542
  if (this.known.has(ip) || this.queue.has(ip)) continue;
21543
21543
  if (!isPublicAddress(ip)) {
@@ -21545,9 +21545,9 @@ var init_map = __esm({
21545
21545
  continue;
21546
21546
  }
21547
21547
  this.queue.add(ip);
21548
- added = true;
21548
+ added2 = true;
21549
21549
  }
21550
- if (added && !this.timer) {
21550
+ if (added2 && !this.timer) {
21551
21551
  this.timer = setTimeout(() => {
21552
21552
  this.timer = null;
21553
21553
  void this.flush();
@@ -24745,9 +24745,9 @@ var source_default = chalk;
24745
24745
 
24746
24746
  // src/index.ts
24747
24747
  var import_readline = __toESM(require("readline"));
24748
- var import_node_child_process19 = require("child_process");
24749
- var import_node_fs44 = require("fs");
24750
- var import_node_path33 = require("path");
24748
+ var import_node_child_process20 = require("child_process");
24749
+ var import_node_fs46 = require("fs");
24750
+ var import_node_path34 = require("path");
24751
24751
  var import_node_os13 = require("os");
24752
24752
 
24753
24753
  // src/commands/monitor.ts
@@ -31641,6 +31641,7 @@ function loadConfig(configPath) {
31641
31641
  watchdog: parsed.watchdog,
31642
31642
  update: parsed.update,
31643
31643
  threat_feeds: parsed.threat_feeds,
31644
+ privileged: parsed.privileged,
31644
31645
  storage: parsed.storage,
31645
31646
  license: parsed.license
31646
31647
  };
@@ -31779,6 +31780,14 @@ function getRecentEvents(limit = 50) {
31779
31780
  `).all(limit);
31780
31781
  return rows.map(rowToEvent);
31781
31782
  }
31783
+ function getModuleEvents(module2, limit = 50) {
31784
+ const database = tryDb();
31785
+ if (!database) return [];
31786
+ const rows = database.prepare(`
31787
+ SELECT * FROM events WHERE module = ? ORDER BY id DESC LIMIT ?
31788
+ `).all(module2, limit);
31789
+ return rows.map(rowToEvent);
31790
+ }
31782
31791
  var RECENT_WINDOW = 2e5;
31783
31792
  function eventsEverRecorded(database) {
31784
31793
  const row = database.prepare(`SELECT seq FROM sqlite_sequence WHERE name = 'events'`).get();
@@ -39780,16 +39789,16 @@ async function sshConnect(options) {
39780
39789
  }
39781
39790
 
39782
39791
  // src/commands/daemon.ts
39783
- var import_node_child_process14 = require("child_process");
39784
- var import_node_fs37 = require("fs");
39785
- var import_node_path28 = require("path");
39792
+ var import_node_child_process15 = require("child_process");
39786
39793
  var import_node_fs38 = require("fs");
39794
+ var import_node_path29 = require("path");
39795
+ var import_node_fs39 = require("fs");
39787
39796
 
39788
39797
  // src/daemon/index.ts
39789
- var import_node_fs36 = require("fs");
39790
- var import_node_child_process13 = require("child_process");
39798
+ var import_node_fs37 = require("fs");
39799
+ var import_node_child_process14 = require("child_process");
39791
39800
  var import_node_os11 = require("os");
39792
- var import_node_path27 = require("path");
39801
+ var import_node_path28 = require("path");
39793
39802
  var import_node_util = require("util");
39794
39803
  init_paths();
39795
39804
 
@@ -42412,13 +42421,13 @@ var AllowlistSync = class {
42412
42421
  const value = String(entry.value ?? "").trim();
42413
42422
  if (isAddressOrCidr(value)) wanted.add(value);
42414
42423
  }
42415
- const added = [];
42424
+ const added2 = [];
42416
42425
  const protectedNow = new Set(this.manager.getProtected());
42417
42426
  for (const value of wanted) {
42418
42427
  if (this.owned.has(value) || protectedNow.has(value)) continue;
42419
42428
  this.manager.addToAllowlist(value);
42420
42429
  this.owned.add(value);
42421
- added.push(value);
42430
+ added2.push(value);
42422
42431
  }
42423
42432
  const removed = [];
42424
42433
  for (const value of this.owned) {
@@ -42427,9 +42436,9 @@ var AllowlistSync = class {
42427
42436
  this.owned.delete(value);
42428
42437
  removed.push(value);
42429
42438
  }
42430
- if (added.length > 0 || removed.length > 0) {
42439
+ if (added2.length > 0 || removed.length > 0) {
42431
42440
  this.opts.log(
42432
- `[cloud] org allowlist: +${added.length} -${removed.length} (${[...added.map((v) => `+${v}`), ...removed.map((v) => `-${v}`)].slice(0, 10).join(" ")})`
42441
+ `[cloud] org allowlist: +${added2.length} -${removed.length} (${[...added2.map((v) => `+${v}`), ...removed.map((v) => `-${v}`)].slice(0, 10).join(" ")})`
42433
42442
  );
42434
42443
  }
42435
42444
  }
@@ -43023,6 +43032,443 @@ var ThreatFeeds = class {
43023
43032
  }
43024
43033
  };
43025
43034
 
43035
+ // src/daemon/workers/privilege-watch.ts
43036
+ var import_node_fs32 = require("fs");
43037
+ var import_node_path24 = require("path");
43038
+ var import_node_child_process11 = require("child_process");
43039
+
43040
+ // src/core/privileges/index.ts
43041
+ var import_node_crypto7 = require("crypto");
43042
+ var ADMIN_GROUPS = ["sudo", "wheel", "admin"];
43043
+ function parseUsers(text) {
43044
+ const out = [];
43045
+ for (const line2 of text.split("\n")) {
43046
+ const f = line2.split(":");
43047
+ if (f.length < 7 || line2.startsWith("#")) continue;
43048
+ const uid = Number(f[2]);
43049
+ if (!f[0] || !Number.isInteger(uid)) continue;
43050
+ out.push({ name: f[0], uid, home: f[5], shell: f[6].trim() });
43051
+ }
43052
+ return out;
43053
+ }
43054
+ function parseAdminGroups(text) {
43055
+ const out = {};
43056
+ for (const line2 of text.split("\n")) {
43057
+ const f = line2.split(":");
43058
+ if (f.length < 4 || !ADMIN_GROUPS.includes(f[0])) continue;
43059
+ out[f[0]] = f[3].trim().split(",").map((m) => m.trim()).filter(Boolean).sort();
43060
+ }
43061
+ return out;
43062
+ }
43063
+ function canLogIn(user) {
43064
+ return !/(nologin|\/false|\/sync|\/shutdown|\/halt)$/.test(user.shell);
43065
+ }
43066
+ function sudoersRules(text) {
43067
+ const joined = text.replace(/\\\n/g, " ");
43068
+ const rules = [];
43069
+ for (const raw of joined.split("\n")) {
43070
+ const line2 = raw.trim();
43071
+ if (!line2) continue;
43072
+ if (line2.startsWith("#") && !/^#include(dir)?\s/.test(line2)) continue;
43073
+ rules.push(line2.replace(/\s+/g, " "));
43074
+ }
43075
+ return rules;
43076
+ }
43077
+ function sudoReadsIncluded(name) {
43078
+ return !name.endsWith("~") && !name.includes(".");
43079
+ }
43080
+ function keyFingerprint(blobBase64) {
43081
+ if (!/^[A-Za-z0-9+/]+=*$/.test(blobBase64)) return null;
43082
+ const digest = (0, import_node_crypto7.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
43083
+ return `SHA256:${digest.replace(/=+$/, "")}`;
43084
+ }
43085
+ function parseAuthorizedKeys(text) {
43086
+ const out = [];
43087
+ for (const raw of text.split("\n")) {
43088
+ const line2 = raw.trim();
43089
+ if (!line2 || line2.startsWith("#")) continue;
43090
+ const m = /(?:^|\s)((?:ssh|ecdsa|sk)-[\w@.-]+)\s+([A-Za-z0-9+/]+=*)(?:\s+(.*))?$/.exec(line2);
43091
+ if (!m) continue;
43092
+ const fingerprint = keyFingerprint(m[2]);
43093
+ if (fingerprint) out.push({ fingerprint, type: m[1], comment: (m[3] ?? "").trim() });
43094
+ }
43095
+ return out;
43096
+ }
43097
+ function takeSnapshot(io, now = /* @__PURE__ */ new Date()) {
43098
+ const unreadable = [];
43099
+ const read = (path) => {
43100
+ const text = io.readFile(path);
43101
+ if (text === null && io.exists(path)) unreadable.push(path);
43102
+ return text;
43103
+ };
43104
+ const users = parseUsers(read("/etc/passwd") ?? "");
43105
+ const snapshot = {
43106
+ taken_at: now.toISOString(),
43107
+ uid0: users.filter((a) => a.uid === 0).map((a) => a.name).sort(),
43108
+ admin_groups: parseAdminGroups(read("/etc/group") ?? ""),
43109
+ sudoers: {},
43110
+ keys: {},
43111
+ unreadable
43112
+ };
43113
+ const sudoersFiles = ["/etc/sudoers"];
43114
+ for (const name of (io.readDir("/etc/sudoers.d") ?? []).sort()) {
43115
+ if (sudoReadsIncluded(name)) sudoersFiles.push(`/etc/sudoers.d/${name}`);
43116
+ }
43117
+ for (const path of sudoersFiles) {
43118
+ const text = read(path);
43119
+ if (text !== null) snapshot.sudoers[path] = sudoersRules(text);
43120
+ }
43121
+ for (const user of users) {
43122
+ if (user.uid !== 0 && (!canLogIn(user) || !user.home || user.home === "/")) continue;
43123
+ const keys = {};
43124
+ for (const file of ["authorized_keys", "authorized_keys2"]) {
43125
+ const text = read(`${user.home.replace(/\/$/, "")}/.ssh/${file}`);
43126
+ for (const k of parseAuthorizedKeys(text ?? "")) keys[k.fingerprint] = { type: k.type, comment: k.comment };
43127
+ }
43128
+ if (Object.keys(keys).length > 0) snapshot.keys[user.name] = keys;
43129
+ }
43130
+ return snapshot;
43131
+ }
43132
+ var added = (before2, after) => after.filter((x) => !before2.includes(x));
43133
+ function diffSnapshots(prev, next) {
43134
+ const changes = [];
43135
+ for (const name of added(prev.uid0, next.uid0)) {
43136
+ changes.push({ severity: "critical", message: `New uid 0 account: ${name}`, details: { rule_id: "priv-uid0-added", account: name } });
43137
+ }
43138
+ for (const name of added(next.uid0, prev.uid0)) {
43139
+ changes.push({ severity: "low", message: `uid 0 account removed: ${name}`, details: { rule_id: "priv-uid0-removed", account: name } });
43140
+ }
43141
+ for (const group of /* @__PURE__ */ new Set([...Object.keys(prev.admin_groups), ...Object.keys(next.admin_groups)])) {
43142
+ const before2 = prev.admin_groups[group] ?? [];
43143
+ const after = next.admin_groups[group] ?? [];
43144
+ for (const m of added(before2, after)) {
43145
+ 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 } });
43146
+ }
43147
+ for (const m of added(after, before2)) {
43148
+ changes.push({ severity: "low", message: `${m} removed from the ${group} group`, details: { rule_id: "priv-admin-group-removed", group, account: m } });
43149
+ }
43150
+ }
43151
+ for (const path of /* @__PURE__ */ new Set([...Object.keys(prev.sudoers), ...Object.keys(next.sudoers)])) {
43152
+ if (next.unreadable.includes(path) || prev.unreadable.includes(path)) continue;
43153
+ const before2 = prev.sudoers[path];
43154
+ const after = next.sudoers[path];
43155
+ if (!before2 && after) {
43156
+ 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) } });
43157
+ continue;
43158
+ }
43159
+ if (before2 && !after) {
43160
+ changes.push({ severity: "low", message: `Sudoers file removed: ${path}`, details: { rule_id: "priv-sudoers-removed", path } });
43161
+ continue;
43162
+ }
43163
+ const plus = added(before2 ?? [], after ?? []);
43164
+ const minus = added(after ?? [], before2 ?? []);
43165
+ if (plus.length) {
43166
+ 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) } });
43167
+ } else if (minus.length) {
43168
+ 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) } });
43169
+ }
43170
+ }
43171
+ for (const user of /* @__PURE__ */ new Set([...Object.keys(prev.keys), ...Object.keys(next.keys)])) {
43172
+ const before2 = prev.keys[user] ?? {};
43173
+ const after = next.keys[user] ?? {};
43174
+ for (const fp of Object.keys(after)) {
43175
+ if (before2[fp]) continue;
43176
+ const { type, comment } = after[fp];
43177
+ changes.push({
43178
+ severity: "high",
43179
+ message: `New SSH key for ${user}: ${type} ${fp}${comment ? ` (${comment})` : ""}`,
43180
+ details: { rule_id: "priv-authorized-key-added", account: user, fingerprint: fp, key_type: type, comment }
43181
+ });
43182
+ }
43183
+ for (const fp of Object.keys(before2)) {
43184
+ if (after[fp]) continue;
43185
+ changes.push({ severity: "low", message: `SSH key removed for ${user}: ${fp}`, details: { rule_id: "priv-authorized-key-removed", account: user, fingerprint: fp } });
43186
+ }
43187
+ }
43188
+ const rank = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
43189
+ return changes.sort((a, b) => rank[b.severity] - rank[a.severity]);
43190
+ }
43191
+ function parseSudoMessage(message) {
43192
+ const m = /^\s*(\S+)\s+:\s+(.*)$/.exec(message);
43193
+ if (!m) return null;
43194
+ const fields = {};
43195
+ let reason = "";
43196
+ for (const part of m[2].split(" ; ")) {
43197
+ const kv = /^([A-Z]+)=(.*)$/.exec(part.trim());
43198
+ if (kv) fields[kv[1]] = kv[2];
43199
+ else if (!reason) reason = part.trim();
43200
+ }
43201
+ if (!fields.COMMAND) return null;
43202
+ if (/incorrect password|authentication failure/i.test(reason)) return null;
43203
+ return {
43204
+ user: m[1],
43205
+ runas: fields.USER ?? "root",
43206
+ command: fields.COMMAND,
43207
+ tty: fields.TTY,
43208
+ pwd: fields.PWD,
43209
+ denied: /not allowed|not in the sudoers|NOT in sudoers|command not allowed/i.test(reason)
43210
+ };
43211
+ }
43212
+
43213
+ // src/daemon/workers/privilege-watch.ts
43214
+ function privilegeSettings(section) {
43215
+ return { enabled: section?.enabled !== false, geo: section?.geo !== false, pollMs: 6e4 };
43216
+ }
43217
+ var COUNTRY_NAMES = new Intl.DisplayNames(["en"], { type: "region" });
43218
+ function countryName(code) {
43219
+ try {
43220
+ return COUNTRY_NAMES.of(code) ?? code;
43221
+ } catch {
43222
+ return code;
43223
+ }
43224
+ }
43225
+ var fsIO = {
43226
+ readFile: (p) => {
43227
+ try {
43228
+ return (0, import_node_fs32.readFileSync)(p, "utf-8");
43229
+ } catch {
43230
+ return null;
43231
+ }
43232
+ },
43233
+ readDir: (p) => {
43234
+ try {
43235
+ return (0, import_node_fs32.readdirSync)(p);
43236
+ } catch {
43237
+ return null;
43238
+ }
43239
+ },
43240
+ exists: (p) => (0, import_node_fs32.existsSync)(p)
43241
+ };
43242
+ function readJson(path) {
43243
+ try {
43244
+ return JSON.parse((0, import_node_fs32.readFileSync)(path, "utf-8"));
43245
+ } catch {
43246
+ return null;
43247
+ }
43248
+ }
43249
+ function writeJson(path, value) {
43250
+ (0, import_node_fs32.mkdirSync)((0, import_node_path24.dirname)(path), { recursive: true });
43251
+ (0, import_node_fs32.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
43252
+ (0, import_node_fs32.renameSync)(`${path}.tmp`, path);
43253
+ }
43254
+ function defaultRun3(cmd, args) {
43255
+ const res = (0, import_node_child_process11.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 2e4, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
43256
+ return res.status === 0 ? res.stdout : null;
43257
+ }
43258
+ async function geolocateViaThreatcrush(ip, fetchImpl = fetch) {
43259
+ const res = await fetchImpl("https://threatcrush.com/api/geo", {
43260
+ method: "POST",
43261
+ headers: { "Content-Type": "application/json" },
43262
+ body: JSON.stringify({ ips: [ip] }),
43263
+ signal: AbortSignal.timeout(8e3)
43264
+ });
43265
+ if (!res.ok) return null;
43266
+ const body = await res.json();
43267
+ const code = body.results?.[ip]?.countryCode;
43268
+ return typeof code === "string" && /^[A-Z]{2}$/.test(code) ? { countryCode: code } : null;
43269
+ }
43270
+ async function geolocateManyViaThreatcrush(ips, fetchImpl = fetch) {
43271
+ const out = /* @__PURE__ */ new Map();
43272
+ for (let i = 0; i < ips.length; i += 200) {
43273
+ const chunk2 = ips.slice(i, i + 200);
43274
+ const res = await fetchImpl("https://threatcrush.com/api/geo", {
43275
+ method: "POST",
43276
+ headers: { "Content-Type": "application/json" },
43277
+ body: JSON.stringify({ ips: chunk2 }),
43278
+ signal: AbortSignal.timeout(15e3)
43279
+ });
43280
+ if (!res.ok) throw new Error(`geo lookup failed: HTTP ${res.status}`);
43281
+ const body = await res.json();
43282
+ for (const ip of chunk2) {
43283
+ const code = body.results?.[ip]?.countryCode;
43284
+ if (typeof code === "string" && /^[A-Z]{2}$/.test(code)) out.set(ip, code);
43285
+ }
43286
+ }
43287
+ return out;
43288
+ }
43289
+ function parseAcceptedLogins(text) {
43290
+ const out = /* @__PURE__ */ new Map();
43291
+ for (const m of text.matchAll(/Accepted \S+ for (\S+) from (\S+) port/g)) {
43292
+ const [, user, ip] = m;
43293
+ if (isProtected(ip, DEFAULT_PROTECTED)) continue;
43294
+ const ips = out.get(user) ?? /* @__PURE__ */ new Set();
43295
+ ips.add(ip);
43296
+ out.set(user, ips);
43297
+ }
43298
+ return out;
43299
+ }
43300
+ var PrivilegeWatch = class {
43301
+ constructor(opts) {
43302
+ this.opts = opts;
43303
+ this.io = opts.io ?? fsIO;
43304
+ this.run = opts.run ?? defaultRun3;
43305
+ this.now = opts.now ?? (() => /* @__PURE__ */ new Date());
43306
+ }
43307
+ opts;
43308
+ timers = [];
43309
+ io;
43310
+ run;
43311
+ now;
43312
+ warnedUnreadable = false;
43313
+ onEvent = (event) => {
43314
+ void this.checkLogin(event);
43315
+ };
43316
+ start() {
43317
+ if (!this.opts.settings.enabled) {
43318
+ this.opts.log("[privileged] disabled by [privileged] enabled = false");
43319
+ return;
43320
+ }
43321
+ this.checkSnapshot();
43322
+ this.readSudoLedger();
43323
+ if (this.opts.settings.geo) {
43324
+ this.opts.bus.on("event", this.onEvent);
43325
+ void this.backfillLogins();
43326
+ }
43327
+ const timer = setInterval(() => {
43328
+ this.checkSnapshot();
43329
+ this.readSudoLedger();
43330
+ }, this.opts.settings.pollMs);
43331
+ timer.unref?.();
43332
+ this.timers.push(timer);
43333
+ }
43334
+ stop() {
43335
+ for (const t of this.timers) clearInterval(t);
43336
+ this.timers = [];
43337
+ this.opts.bus.off("event", this.onEvent);
43338
+ }
43339
+ emit(severity, message, details) {
43340
+ const event = { timestamp: this.now(), module: "privileged-access", category: "auth", severity, message, details };
43341
+ try {
43342
+ insertEvent(event);
43343
+ } catch {
43344
+ }
43345
+ this.opts.bus.publish(event);
43346
+ }
43347
+ checkSnapshot() {
43348
+ const next = takeSnapshot(this.io, this.now());
43349
+ if (next.unreadable.length && !this.warnedUnreadable) {
43350
+ this.warnedUnreadable = true;
43351
+ this.opts.log(`[privileged] cannot read ${next.unreadable.join(", ")}; run the daemon as root to watch them`);
43352
+ }
43353
+ const prev = readJson(this.opts.snapshotPath);
43354
+ if (!prev) {
43355
+ const keys = Object.values(next.keys).reduce((n, k) => n + Object.keys(k).length, 0);
43356
+ 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)`);
43357
+ } else {
43358
+ for (const change of diffSnapshots(prev, next)) this.emit(change.severity, change.message, change.details);
43359
+ }
43360
+ try {
43361
+ writeJson(this.opts.snapshotPath, next);
43362
+ } catch (err) {
43363
+ this.opts.log(`[privileged] could not save snapshot: ${err.message}`);
43364
+ }
43365
+ }
43366
+ /**
43367
+ * New sudo records since the saved journal cursor. The first run only finds
43368
+ * the current end of the journal, so history from before the daemon is not
43369
+ * replayed as if it had just happened.
43370
+ */
43371
+ readSudoLedger() {
43372
+ const cursor = readJson(this.opts.cursorPath)?.cursor;
43373
+ const args = cursor ? ["-t", "sudo", "-o", "json", "--no-pager", `--after-cursor=${cursor}`] : ["-o", "json", "--no-pager", "-n", "0", "--show-cursor"];
43374
+ const out = this.run("journalctl", args);
43375
+ if (out === null) return;
43376
+ let last = cursor ?? /^-- cursor: (\S+)/m.exec(out)?.[1];
43377
+ for (const line2 of cursor ? out.split("\n") : []) {
43378
+ if (!line2.trim()) continue;
43379
+ let rec;
43380
+ try {
43381
+ rec = JSON.parse(line2);
43382
+ } catch {
43383
+ continue;
43384
+ }
43385
+ if (typeof rec.__CURSOR === "string") last = rec.__CURSOR;
43386
+ const entry = typeof rec.MESSAGE === "string" ? parseSudoMessage(rec.MESSAGE) : null;
43387
+ if (!entry) continue;
43388
+ this.emit(
43389
+ entry.denied ? "medium" : "info",
43390
+ entry.denied ? `sudo denied: ${entry.user} tried ${entry.command} as ${entry.runas}` : `sudo: ${entry.user} ran ${entry.command} as ${entry.runas}`,
43391
+ { 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 }
43392
+ );
43393
+ }
43394
+ if (last && last !== cursor) {
43395
+ try {
43396
+ writeJson(this.opts.cursorPath, { cursor: last });
43397
+ } catch {
43398
+ }
43399
+ }
43400
+ }
43401
+ /**
43402
+ * Seed the login history from the last 30 days of sshd logins, once, when
43403
+ * there is none. Learning only from logins after install meant regular
43404
+ * automation from another country (a backup box pulling every four hours)
43405
+ * raised a "new country" alert on its first run; on dev2 it did, at once.
43406
+ */
43407
+ async backfillLogins() {
43408
+ if ((0, import_node_fs32.existsSync)(this.opts.loginsPath)) return;
43409
+ const out = this.run("journalctl", ["_COMM=sshd", "_COMM=sshd-session", "--since=-30d", "-o", "cat", "--no-pager"]);
43410
+ const byUser = parseAcceptedLogins(out ?? "");
43411
+ const ips = [...new Set([...byUser.values()].flatMap((s) => [...s]))];
43412
+ let codes = /* @__PURE__ */ new Map();
43413
+ if (ips.length > 0) {
43414
+ try {
43415
+ codes = await (this.opts.geolocateMany ?? geolocateManyViaThreatcrush)(ips);
43416
+ } catch (err) {
43417
+ this.opts.log(`[privileged] login backfill geolocation failed: ${err.message}`);
43418
+ return;
43419
+ }
43420
+ }
43421
+ if ((0, import_node_fs32.existsSync)(this.opts.loginsPath)) return;
43422
+ const at = this.now().toISOString();
43423
+ const history = {};
43424
+ for (const [user, userIps] of byUser) {
43425
+ for (const ip of userIps) {
43426
+ const code = codes.get(ip);
43427
+ if (code) (history[user] ??= {})[code] = { first: at, last: at };
43428
+ }
43429
+ }
43430
+ try {
43431
+ writeJson(this.opts.loginsPath, history);
43432
+ } catch {
43433
+ }
43434
+ const summary = Object.entries(history).map(([u, c]) => `${u}: ${Object.keys(c).join("/")}`).join(", ");
43435
+ this.opts.log(`[privileged] login baseline from the last 30 days: ${summary || "no public SSH logins"}`);
43436
+ }
43437
+ /** An accepted SSH login from a country new for that user. */
43438
+ async checkLogin(event) {
43439
+ if (event.module !== "ssh-guard" || !event.source_ip) return;
43440
+ const user = /SSH login accepted for (\S+)/.exec(event.message)?.[1];
43441
+ if (!user || user === "unknown" || isProtected(event.source_ip, DEFAULT_PROTECTED)) return;
43442
+ let geo = null;
43443
+ try {
43444
+ geo = await (this.opts.geolocate ?? geolocateViaThreatcrush)(event.source_ip);
43445
+ } catch (err) {
43446
+ this.opts.log(`[privileged] geolocation failed for ${event.source_ip}: ${err.message}`);
43447
+ }
43448
+ const country = geo?.countryCode;
43449
+ if (!country || !/^[A-Z]{2}$/.test(country)) return;
43450
+ const history = readJson(this.opts.loginsPath) ?? {};
43451
+ const seen = history[user] ?? {};
43452
+ const at = this.now().toISOString();
43453
+ const known = Object.keys(seen);
43454
+ if (known.length > 0 && !seen[country]) {
43455
+ this.emit("high", `SSH login for ${user} from a new country: ${countryName(country)}, ${event.source_ip}; seen before from ${known.join(", ")}`, {
43456
+ rule_id: "priv-login-new-country",
43457
+ account: user,
43458
+ login_ip: event.source_ip,
43459
+ country,
43460
+ known_countries: known
43461
+ });
43462
+ }
43463
+ seen[country] = { first: seen[country]?.first ?? at, last: at };
43464
+ history[user] = seen;
43465
+ try {
43466
+ writeJson(this.opts.loginsPath, history);
43467
+ } catch {
43468
+ }
43469
+ }
43470
+ };
43471
+
43026
43472
  // src/daemon/rules/engine.ts
43027
43473
  var MAX_WINDOW_ENTRIES = 1e3;
43028
43474
  function live(window) {
@@ -43184,8 +43630,8 @@ var RuleEngine = class {
43184
43630
  };
43185
43631
 
43186
43632
  // src/daemon/rules/loader.ts
43187
- var import_node_fs32 = require("fs");
43188
- var import_node_path24 = require("path");
43633
+ var import_node_fs33 = require("fs");
43634
+ var import_node_path25 = require("path");
43189
43635
 
43190
43636
  // src/daemon/rules/default-rules.ts
43191
43637
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -43586,11 +44032,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
43586
44032
  function loadAllRules(customDir) {
43587
44033
  const rules = [...DEFAULT_RULES];
43588
44034
  const dir = customDir || RULES_DIR;
43589
- if ((0, import_node_fs32.existsSync)(dir)) {
43590
- const files = (0, import_node_fs32.readdirSync)(dir).filter((f) => f.endsWith(".json"));
44035
+ if ((0, import_node_fs33.existsSync)(dir)) {
44036
+ const files = (0, import_node_fs33.readdirSync)(dir).filter((f) => f.endsWith(".json"));
43591
44037
  for (const file of files) {
43592
44038
  try {
43593
- const raw = (0, import_node_fs32.readFileSync)((0, import_node_path24.join)(dir, file), "utf-8");
44039
+ const raw = (0, import_node_fs33.readFileSync)((0, import_node_path25.join)(dir, file), "utf-8");
43594
44040
  const parsed = JSON.parse(raw);
43595
44041
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
43596
44042
  for (const rule of customRules) {
@@ -43621,9 +44067,9 @@ function loadAllRules(customDir) {
43621
44067
  }
43622
44068
 
43623
44069
  // src/daemon/firewall/adapters.ts
43624
- var import_node_child_process11 = require("child_process");
43625
- var import_node_fs33 = require("fs");
43626
- var import_node_path25 = require("path");
44070
+ var import_node_child_process12 = require("child_process");
44071
+ var import_node_fs34 = require("fs");
44072
+ var import_node_path26 = require("path");
43627
44073
  var import_node_net10 = require("net");
43628
44074
  function assertValidFirewallIp(ip) {
43629
44075
  if ((0, import_node_net10.isIP)(ip) !== 4) {
@@ -43636,9 +44082,9 @@ function assertBannableIp(ip) {
43636
44082
  }
43637
44083
  }
43638
44084
  function writeIfAbsent(path, contents) {
43639
- (0, import_node_fs33.mkdirSync)((0, import_node_path25.dirname)(path), { recursive: true });
44085
+ (0, import_node_fs34.mkdirSync)((0, import_node_path26.dirname)(path), { recursive: true });
43640
44086
  try {
43641
- (0, import_node_fs33.writeFileSync)(path, contents, { flag: "wx" });
44087
+ (0, import_node_fs34.writeFileSync)(path, contents, { flag: "wx" });
43642
44088
  } catch (err) {
43643
44089
  if (err.code !== "EEXIST") throw err;
43644
44090
  }
@@ -43657,11 +44103,11 @@ var Fail2banAdapter = class {
43657
44103
  enforces = true;
43658
44104
  jailReady = false;
43659
44105
  isAvailable() {
43660
- const result = (0, import_node_child_process11.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
44106
+ const result = (0, import_node_child_process12.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
43661
44107
  return result.status === 0;
43662
44108
  }
43663
44109
  client(args) {
43664
- return (0, import_node_child_process11.execFileSync)("fail2ban-client", args, {
44110
+ return (0, import_node_child_process12.execFileSync)("fail2ban-client", args, {
43665
44111
  encoding: "utf-8",
43666
44112
  stdio: ["ignore", "pipe", "pipe"]
43667
44113
  });
@@ -43757,35 +44203,35 @@ var NftablesAdapter = class {
43757
44203
  table = "threatcrush";
43758
44204
  set = "blocklist";
43759
44205
  isAvailable() {
43760
- const result = (0, import_node_child_process11.spawnSync)("nft", ["--version"], { stdio: "pipe" });
44206
+ const result = (0, import_node_child_process12.spawnSync)("nft", ["--version"], { stdio: "pipe" });
43761
44207
  return result.status === 0;
43762
44208
  }
43763
44209
  ensureSetup() {
43764
44210
  try {
43765
- (0, import_node_child_process11.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
44211
+ (0, import_node_child_process12.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
43766
44212
  } catch {
43767
- (0, import_node_child_process11.execSync)(`nft add table inet ${this.table}`);
43768
- (0, import_node_child_process11.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
43769
- (0, import_node_child_process11.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
43770
- (0, import_node_child_process11.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
44213
+ (0, import_node_child_process12.execSync)(`nft add table inet ${this.table}`);
44214
+ (0, import_node_child_process12.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
44215
+ (0, import_node_child_process12.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
44216
+ (0, import_node_child_process12.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
43771
44217
  }
43772
44218
  }
43773
44219
  async block(ip) {
43774
44220
  assertValidFirewallIp(ip);
43775
44221
  this.ensureSetup();
43776
- (0, import_node_child_process11.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
44222
+ (0, import_node_child_process12.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
43777
44223
  }
43778
44224
  async unblock(ip) {
43779
44225
  assertValidFirewallIp(ip);
43780
44226
  try {
43781
- (0, import_node_child_process11.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
44227
+ (0, import_node_child_process12.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
43782
44228
  } catch {
43783
44229
  }
43784
44230
  }
43785
44231
  async isBlocked(ip) {
43786
44232
  assertValidFirewallIp(ip);
43787
44233
  try {
43788
- const output = (0, import_node_child_process11.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
44234
+ const output = (0, import_node_child_process12.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
43789
44235
  return output.includes(ip);
43790
44236
  } catch {
43791
44237
  return false;
@@ -43793,7 +44239,7 @@ var NftablesAdapter = class {
43793
44239
  }
43794
44240
  async listBlocked() {
43795
44241
  try {
43796
- const output = (0, import_node_child_process11.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
44242
+ const output = (0, import_node_child_process12.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
43797
44243
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
43798
44244
  if (!match) return [];
43799
44245
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -43806,34 +44252,34 @@ var IptablesAdapter = class {
43806
44252
  name = "iptables";
43807
44253
  chain = "THREATCRUSH";
43808
44254
  isAvailable() {
43809
- const result = (0, import_node_child_process11.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
44255
+ const result = (0, import_node_child_process12.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
43810
44256
  return result.status === 0;
43811
44257
  }
43812
44258
  ensureChain() {
43813
44259
  try {
43814
- (0, import_node_child_process11.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
44260
+ (0, import_node_child_process12.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
43815
44261
  } catch {
43816
- (0, import_node_child_process11.execSync)(`iptables -N ${this.chain}`);
43817
- (0, import_node_child_process11.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
44262
+ (0, import_node_child_process12.execSync)(`iptables -N ${this.chain}`);
44263
+ (0, import_node_child_process12.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
43818
44264
  }
43819
44265
  }
43820
44266
  async block(ip) {
43821
44267
  assertValidFirewallIp(ip);
43822
44268
  this.ensureChain();
43823
44269
  if (await this.isBlocked(ip)) return;
43824
- (0, import_node_child_process11.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
44270
+ (0, import_node_child_process12.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
43825
44271
  }
43826
44272
  async unblock(ip) {
43827
44273
  assertValidFirewallIp(ip);
43828
44274
  try {
43829
- (0, import_node_child_process11.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
44275
+ (0, import_node_child_process12.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
43830
44276
  } catch {
43831
44277
  }
43832
44278
  }
43833
44279
  async isBlocked(ip) {
43834
44280
  assertValidFirewallIp(ip);
43835
44281
  try {
43836
- const output = (0, import_node_child_process11.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
44282
+ const output = (0, import_node_child_process12.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
43837
44283
  return output.includes(ip);
43838
44284
  } catch {
43839
44285
  return false;
@@ -43841,7 +44287,7 @@ var IptablesAdapter = class {
43841
44287
  }
43842
44288
  async listBlocked() {
43843
44289
  try {
43844
- const output = (0, import_node_child_process11.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
44290
+ const output = (0, import_node_child_process12.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
43845
44291
  const ips = [];
43846
44292
  for (const line2 of output.split("\n")) {
43847
44293
  const match = line2.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -43897,7 +44343,7 @@ function detectFirewallAdapter(backend = "auto") {
43897
44343
  }
43898
44344
 
43899
44345
  // src/daemon/firewall/remediation.ts
43900
- var import_node_fs34 = require("fs");
44346
+ var import_node_fs35 = require("fs");
43901
44347
  var import_node_net11 = require("net");
43902
44348
  init_paths();
43903
44349
  init_backoff();
@@ -44311,7 +44757,7 @@ var RemediationManager = class {
44311
44757
  }
44312
44758
  logLine(line2) {
44313
44759
  try {
44314
- (0, import_node_fs34.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44760
+ (0, import_node_fs35.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44315
44761
  `);
44316
44762
  } catch {
44317
44763
  }
@@ -44349,19 +44795,19 @@ function remediationSettings(section) {
44349
44795
  init_backoff();
44350
44796
 
44351
44797
  // src/daemon/watchdog-service.ts
44352
- var import_node_fs35 = require("fs");
44353
- var import_node_path26 = require("path");
44798
+ var import_node_fs36 = require("fs");
44799
+ var import_node_path27 = require("path");
44354
44800
  function defaultShareGid() {
44355
44801
  const isRoot4 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
44356
44802
  if (!isRoot4) return void 0;
44357
44803
  try {
44358
- return (0, import_node_fs35.statSync)("/var/log/auth.log").gid;
44804
+ return (0, import_node_fs36.statSync)("/var/log/auth.log").gid;
44359
44805
  } catch {
44360
44806
  return void 0;
44361
44807
  }
44362
44808
  }
44363
44809
  function startWatchdog(opts) {
44364
- const dir = opts.config?.dir ?? (0, import_node_path26.join)(opts.stateDir, WATCHDOG_DIRNAME);
44810
+ const dir = opts.config?.dir ?? (0, import_node_path27.join)(opts.stateDir, WATCHDOG_DIRNAME);
44365
44811
  const base = { dir, logged: 0, answered: 0, errored: 0 };
44366
44812
  if (opts.config?.enabled === false) {
44367
44813
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -44455,7 +44901,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
44455
44901
  }
44456
44902
 
44457
44903
  // src/core/node-runtime.ts
44458
- var import_node_child_process12 = require("child_process");
44904
+ var import_node_child_process13 = require("child_process");
44459
44905
  var MIN_DAEMON_NODE_MAJOR = 22;
44460
44906
  function nodeMajor(version) {
44461
44907
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -44469,23 +44915,23 @@ function daemonNodeProblem(version) {
44469
44915
  }
44470
44916
  function versionOfNode(path) {
44471
44917
  if (path === process.execPath) return process.versions.node;
44472
- const res = (0, import_node_child_process12.spawnSync)(path, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
44918
+ const res = (0, import_node_child_process13.spawnSync)(path, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
44473
44919
  return res.status === 0 ? res.stdout.trim() : null;
44474
44920
  }
44475
44921
 
44476
44922
  // src/daemon/index.ts
44477
44923
  function readVersion2() {
44478
44924
  try {
44479
- const pkg = JSON.parse((0, import_node_fs36.readFileSync)((0, import_node_path27.join)(__dirname, "..", "package.json"), "utf-8"));
44925
+ const pkg = JSON.parse((0, import_node_fs37.readFileSync)((0, import_node_path28.join)(__dirname, "..", "package.json"), "utf-8"));
44480
44926
  return pkg.version || "0.0.0";
44481
44927
  } catch {
44482
44928
  return "0.0.0";
44483
44929
  }
44484
44930
  }
44485
44931
  async function runHardeningChecks() {
44486
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process13.execFile)(
44932
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process14.execFile)(
44487
44933
  process.execPath,
44488
- [(0, import_node_path27.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
44934
+ [(0, import_node_path28.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
44489
44935
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
44490
44936
  );
44491
44937
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -44497,9 +44943,9 @@ async function runHardeningChecks() {
44497
44943
  return patches ? [...findings, patches] : findings;
44498
44944
  }
44499
44945
  async function runPatchCheck() {
44500
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process13.execFile)(
44946
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process14.execFile)(
44501
44947
  process.execPath,
44502
- [(0, import_node_path27.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
44948
+ [(0, import_node_path28.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
44503
44949
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
44504
44950
  );
44505
44951
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -44507,7 +44953,7 @@ async function runPatchCheck() {
44507
44953
  }
44508
44954
  function logLine(line2) {
44509
44955
  try {
44510
- (0, import_node_fs36.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44956
+ (0, import_node_fs37.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
44511
44957
  `);
44512
44958
  } catch {
44513
44959
  }
@@ -44532,9 +44978,9 @@ async function runDaemon() {
44532
44978
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
44533
44979
  const restartDaemon = () => {
44534
44980
  if (PATHS.mode === "system") {
44535
- (0, import_node_child_process13.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
44981
+ (0, import_node_child_process14.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
44536
44982
  } else {
44537
- (0, import_node_child_process13.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
44983
+ (0, import_node_child_process14.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
44538
44984
  setTimeout(() => process.exit(0), 500).unref();
44539
44985
  }
44540
44986
  };
@@ -44549,7 +44995,7 @@ async function runDaemon() {
44549
44995
  } catch (err) {
44550
44996
  logLine(`[daemon] state db unavailable: ${err.message}`);
44551
44997
  }
44552
- const config = loadConfig((0, import_node_fs36.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
44998
+ const config = loadConfig((0, import_node_fs37.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
44553
44999
  configureAttackDetection(config.detection);
44554
45000
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
44555
45001
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -44613,11 +45059,20 @@ async function runDaemon() {
44613
45059
  const threatFeeds = new ThreatFeeds({
44614
45060
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
44615
45061
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
44616
- cachePath: (0, import_node_path27.join)(PATHS.stateDir, "threat-feeds.json"),
45062
+ cachePath: (0, import_node_path28.join)(PATHS.stateDir, "threat-feeds.json"),
44617
45063
  bus,
44618
45064
  log: logLine
44619
45065
  });
44620
45066
  threatFeeds.start();
45067
+ const privilegeWatch = new PrivilegeWatch({
45068
+ settings: privilegeSettings(config.privileged),
45069
+ bus,
45070
+ snapshotPath: (0, import_node_path28.join)(PATHS.stateDir, "privileges.json"),
45071
+ loginsPath: (0, import_node_path28.join)(PATHS.stateDir, "login-countries.json"),
45072
+ cursorPath: (0, import_node_path28.join)(PATHS.stateDir, "sudo-cursor.json"),
45073
+ log: logLine
45074
+ });
45075
+ privilegeWatch.start();
44621
45076
  new AlertDispatcher(bus, config);
44622
45077
  const runsWorker = new RunsWorker(bus);
44623
45078
  try {
@@ -44637,7 +45092,7 @@ async function runDaemon() {
44637
45092
  version,
44638
45093
  hostname: (0, import_node_os11.hostname)(),
44639
45094
  minSeverity,
44640
- spoolPath: (0, import_node_path27.join)(PATHS.stateDir, "cloud-spool.jsonl"),
45095
+ spoolPath: (0, import_node_path28.join)(PATHS.stateDir, "cloud-spool.jsonl"),
44641
45096
  log: logLine,
44642
45097
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
44643
45098
  runHardening: runHardeningChecks
@@ -44654,8 +45109,8 @@ async function runDaemon() {
44654
45109
  const autoUpdate = new AutoUpdate({
44655
45110
  version,
44656
45111
  settings: updateSettings(config.update),
44657
- pkgRoot: (0, import_node_path27.join)(__dirname, ".."),
44658
- statePath: (0, import_node_path27.join)(PATHS.stateDir, "auto-update.json"),
45112
+ pkgRoot: (0, import_node_path28.join)(__dirname, ".."),
45113
+ statePath: (0, import_node_path28.join)(PATHS.stateDir, "auto-update.json"),
44659
45114
  bus,
44660
45115
  log: logLine,
44661
45116
  restartDaemon
@@ -44702,6 +45157,10 @@ async function runDaemon() {
44702
45157
  threatFeeds.stop();
44703
45158
  } catch {
44704
45159
  }
45160
+ try {
45161
+ privilegeWatch.stop();
45162
+ } catch {
45163
+ }
44705
45164
  try {
44706
45165
  await ipc.stop();
44707
45166
  } catch {
@@ -44737,7 +45196,7 @@ var SYSTEM_SOCKET = "/var/run/threatcrush/threatcrushd.sock";
44737
45196
  function isRoot2() {
44738
45197
  return typeof process.getuid === "function" && process.getuid() === 0;
44739
45198
  }
44740
- var DAEMON_ENTRY = (0, import_node_path28.join)(__dirname, "daemon.js");
45199
+ var DAEMON_ENTRY = (0, import_node_path29.join)(__dirname, "daemon.js");
44741
45200
  async function daemonForeground() {
44742
45201
  await runDaemon();
44743
45202
  }
@@ -44758,7 +45217,7 @@ async function daemonStart() {
44758
45217
  return;
44759
45218
  }
44760
45219
  ensureRuntimeDirs();
44761
- if (!(0, import_node_fs37.existsSync)(DAEMON_ENTRY)) {
45220
+ if (!(0, import_node_fs38.existsSync)(DAEMON_ENTRY)) {
44762
45221
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
44763
45222
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
44764
45223
  return;
@@ -44766,8 +45225,8 @@ async function daemonStart() {
44766
45225
  let out;
44767
45226
  let err;
44768
45227
  try {
44769
- out = (0, import_node_fs38.openSync)(PATHS.logFile, "a");
44770
- err = (0, import_node_fs38.openSync)(PATHS.logFile, "a");
45228
+ out = (0, import_node_fs39.openSync)(PATHS.logFile, "a");
45229
+ err = (0, import_node_fs39.openSync)(PATHS.logFile, "a");
44771
45230
  } catch (e) {
44772
45231
  const code = e.code;
44773
45232
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -44780,7 +45239,7 @@ async function daemonStart() {
44780
45239
  }
44781
45240
  return;
44782
45241
  }
44783
- const child = (0, import_node_child_process14.spawn)(process.execPath, [DAEMON_ENTRY], {
45242
+ const child = (0, import_node_child_process15.spawn)(process.execPath, [DAEMON_ENTRY], {
44784
45243
  detached: true,
44785
45244
  stdio: ["ignore", out, err],
44786
45245
  env: { ...process.env, THREATCRUSH_DAEMON: "1" }
@@ -44855,41 +45314,41 @@ async function waitForExit(pid, timeoutMs) {
44855
45314
  }
44856
45315
  async function releaseStaleSocket() {
44857
45316
  const deadline = Date.now() + 2e3;
44858
- while ((0, import_node_fs37.existsSync)(PATHS.socket) && Date.now() < deadline) {
45317
+ while ((0, import_node_fs38.existsSync)(PATHS.socket) && Date.now() < deadline) {
44859
45318
  await new Promise((r) => setTimeout(r, 50));
44860
45319
  }
44861
- if ((0, import_node_fs37.existsSync)(PATHS.socket)) {
45320
+ if ((0, import_node_fs38.existsSync)(PATHS.socket)) {
44862
45321
  try {
44863
- (0, import_node_fs37.unlinkSync)(PATHS.socket);
45322
+ (0, import_node_fs38.unlinkSync)(PATHS.socket);
44864
45323
  } catch {
44865
45324
  }
44866
45325
  }
44867
45326
  }
44868
45327
 
44869
45328
  // src/commands/service.ts
44870
- var import_node_child_process15 = require("child_process");
44871
- var import_node_fs39 = require("fs");
44872
- var import_node_path29 = require("path");
45329
+ var import_node_child_process16 = require("child_process");
45330
+ var import_node_fs40 = require("fs");
45331
+ var import_node_path30 = require("path");
44873
45332
  var import_node_os12 = require("os");
44874
45333
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
44875
45334
  var DAEMON_UNIT_NAME = "threatcrushd.service";
44876
45335
  function resolveTemplate() {
44877
- const templatePath = (0, import_node_path29.join)(__dirname, "systemd", "threatcrushd.service");
44878
- if (!(0, import_node_fs39.existsSync)(templatePath)) {
45336
+ const templatePath = (0, import_node_path30.join)(__dirname, "systemd", "threatcrushd.service");
45337
+ if (!(0, import_node_fs40.existsSync)(templatePath)) {
44879
45338
  throw new Error(`systemd unit template not found at ${templatePath}`);
44880
45339
  }
44881
- return (0, import_node_fs39.readFileSync)(templatePath, "utf-8");
45340
+ return (0, import_node_fs40.readFileSync)(templatePath, "utf-8");
44882
45341
  }
44883
45342
  function stableBinPath(binPath) {
44884
45343
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
44885
45344
  if (stable === binPath) return binPath;
44886
- return (0, import_node_fs39.existsSync)(stable) ? stable : binPath;
45345
+ return (0, import_node_fs40.existsSync)(stable) ? stable : binPath;
44887
45346
  }
44888
45347
  function resolveBinPath() {
44889
45348
  const arg = process.argv[1];
44890
- if (arg && (0, import_node_fs39.existsSync)(arg)) return stableBinPath(arg);
45349
+ if (arg && (0, import_node_fs40.existsSync)(arg)) return stableBinPath(arg);
44891
45350
  try {
44892
- return (0, import_node_child_process15.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
45351
+ return (0, import_node_child_process16.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
44893
45352
  } catch {
44894
45353
  return "threatcrush";
44895
45354
  }
@@ -44897,11 +45356,11 @@ function resolveBinPath() {
44897
45356
  function stableNodePath(execPath) {
44898
45357
  const stable = execPath.replace(/(\/installs\/node\/)[^/]+\//, "$1latest/");
44899
45358
  if (stable === execPath) return execPath;
44900
- return (0, import_node_fs39.existsSync)(stable) ? stable : execPath;
45359
+ return (0, import_node_fs40.existsSync)(stable) ? stable : execPath;
44901
45360
  }
44902
45361
  function looksLikeNodeScript(path) {
44903
45362
  try {
44904
- const head = (0, import_node_fs39.readFileSync)(path, "utf-8").slice(0, 120);
45363
+ const head = (0, import_node_fs40.readFileSync)(path, "utf-8").slice(0, 120);
44905
45364
  return /^#!.*\bnode\b/.test(head);
44906
45365
  } catch {
44907
45366
  return false;
@@ -44928,20 +45387,20 @@ function isRoot3() {
44928
45387
  return typeof process.getuid === "function" && process.getuid() === 0;
44929
45388
  }
44930
45389
  function reexecWithSudo(args) {
44931
- if ((0, import_node_child_process15.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
45390
+ if ((0, import_node_child_process16.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
44932
45391
  console.log(source_default.dim(" This needs root \u2014 sudo will ask for your password.\n"));
44933
45392
  const bin = resolveBinPath();
44934
45393
  const argv = looksLikeNodeScript(bin) ? [stableNodePath(process.execPath), bin, ...args] : [bin, ...args];
44935
- const result = (0, import_node_child_process15.spawnSync)("sudo", argv, { stdio: "inherit" });
45394
+ const result = (0, import_node_child_process16.spawnSync)("sudo", argv, { stdio: "inherit" });
44936
45395
  return result.status === 0;
44937
45396
  }
44938
45397
  function callerHome() {
44939
45398
  const user = process.env.SUDO_USER;
44940
45399
  if (!user) return null;
44941
45400
  try {
44942
- const line2 = (0, import_node_child_process15.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
45401
+ const line2 = (0, import_node_child_process16.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
44943
45402
  const home = line2.split(":")[5];
44944
- return home && (0, import_node_fs39.existsSync)(home) ? home : null;
45403
+ return home && (0, import_node_fs40.existsSync)(home) ? home : null;
44945
45404
  } catch {
44946
45405
  return null;
44947
45406
  }
@@ -44949,13 +45408,13 @@ function callerHome() {
44949
45408
  function stopUserModeDaemon() {
44950
45409
  const home = callerHome();
44951
45410
  if (!home) return;
44952
- const runDir = (0, import_node_path29.join)(home, ".threatcrush", "run");
44953
- const pidFile = (0, import_node_path29.join)(runDir, "threatcrushd.pid");
44954
- const socket = (0, import_node_path29.join)(runDir, "threatcrushd.sock");
44955
- if (!(0, import_node_fs39.existsSync)(pidFile) && !(0, import_node_fs39.existsSync)(socket)) return;
45411
+ const runDir = (0, import_node_path30.join)(home, ".threatcrush", "run");
45412
+ const pidFile = (0, import_node_path30.join)(runDir, "threatcrushd.pid");
45413
+ const socket = (0, import_node_path30.join)(runDir, "threatcrushd.sock");
45414
+ if (!(0, import_node_fs40.existsSync)(pidFile) && !(0, import_node_fs40.existsSync)(socket)) return;
44956
45415
  let pid = null;
44957
45416
  try {
44958
- pid = Number.parseInt((0, import_node_fs39.readFileSync)(pidFile, "utf-8").trim(), 10);
45417
+ pid = Number.parseInt((0, import_node_fs40.readFileSync)(pidFile, "utf-8").trim(), 10);
44959
45418
  } catch {
44960
45419
  pid = null;
44961
45420
  }
@@ -44968,13 +45427,13 @@ function stopUserModeDaemon() {
44968
45427
  }
44969
45428
  for (const path of [socket, pidFile]) {
44970
45429
  try {
44971
- if ((0, import_node_fs39.existsSync)(path)) (0, import_node_fs39.rmSync)(path);
45430
+ if ((0, import_node_fs40.existsSync)(path)) (0, import_node_fs40.rmSync)(path);
44972
45431
  } catch {
44973
45432
  }
44974
45433
  }
44975
45434
  }
44976
45435
  function unitIsActive() {
44977
- const result = (0, import_node_child_process15.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
45436
+ const result = (0, import_node_child_process16.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
44978
45437
  return result.status === 0;
44979
45438
  }
44980
45439
  async function installServiceCommand() {
@@ -44985,8 +45444,8 @@ async function installServiceCommand() {
44985
45444
  return;
44986
45445
  }
44987
45446
  const noSystemd = systemdUnavailableReason({
44988
- hasSystemctl: (0, import_node_child_process15.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
44989
- booted: (0, import_node_fs39.existsSync)("/run/systemd/system")
45447
+ hasSystemctl: (0, import_node_child_process16.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
45448
+ booted: (0, import_node_fs40.existsSync)("/run/systemd/system")
44990
45449
  });
44991
45450
  if (noSystemd) {
44992
45451
  console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
@@ -45008,7 +45467,7 @@ async function installServiceCommand() {
45008
45467
  const isNodeScript = looksLikeNodeScript(binPath);
45009
45468
  let nodePath = stableNodePath(process.execPath);
45010
45469
  if (isNodeScript && nodeVersionDir(binPath)) {
45011
- binPath = (0, import_node_fs39.realpathSync)(binPath);
45470
+ binPath = (0, import_node_fs40.realpathSync)(binPath);
45012
45471
  nodePath = process.execPath;
45013
45472
  }
45014
45473
  if (isNodeScript) {
@@ -45021,9 +45480,9 @@ async function installServiceCommand() {
45021
45480
  }
45022
45481
  }
45023
45482
  const exec = execStartCommand(binPath, nodePath, isNodeScript);
45024
- const configDir = (0, import_node_path29.join)((0, import_node_os12.homedir)(), ".threatcrush");
45483
+ const configDir = (0, import_node_path30.join)((0, import_node_os12.homedir)(), ".threatcrush");
45025
45484
  const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir });
45026
- (0, import_node_fs39.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
45485
+ (0, import_node_fs40.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
45027
45486
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
45028
45487
  console.log(source_default.dim(` ExecStart=${exec}`));
45029
45488
  const nodeDir = nodeVersionDir(nodePath);
@@ -45038,8 +45497,8 @@ async function installServiceCommand() {
45038
45497
  installLogrotate();
45039
45498
  stopUserModeDaemon();
45040
45499
  try {
45041
- (0, import_node_child_process15.execSync)("systemctl daemon-reload", { stdio: "inherit" });
45042
- (0, import_node_child_process15.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
45500
+ (0, import_node_child_process16.execSync)("systemctl daemon-reload", { stdio: "inherit" });
45501
+ (0, import_node_child_process16.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
45043
45502
  } catch (err) {
45044
45503
  console.log(source_default.yellow(` ! systemctl error: ${err.message}`));
45045
45504
  console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -n 50`));
@@ -45076,9 +45535,9 @@ function renderLogrotate(logDir = "/var/log/threatcrush") {
45076
45535
  ].join("\n");
45077
45536
  }
45078
45537
  function installLogrotate() {
45079
- if (!(0, import_node_fs39.existsSync)((0, import_node_path29.dirname)(LOGROTATE_PATH))) return;
45538
+ if (!(0, import_node_fs40.existsSync)((0, import_node_path30.dirname)(LOGROTATE_PATH))) return;
45080
45539
  try {
45081
- (0, import_node_fs39.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
45540
+ (0, import_node_fs40.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
45082
45541
  console.log(source_default.green(` \u2713 Log rotation: ${LOGROTATE_PATH} (daily or 200M, keeps 7)`));
45083
45542
  } catch (err) {
45084
45543
  console.log(source_default.yellow(` ! Could not install log rotation: ${err.message}`));
@@ -45100,20 +45559,20 @@ function ensureSystemDirs(configDir) {
45100
45559
  ];
45101
45560
  let admGid2 = null;
45102
45561
  try {
45103
- admGid2 = (0, import_node_fs39.statSync)("/var/log/auth.log").gid;
45562
+ admGid2 = (0, import_node_fs40.statSync)("/var/log/auth.log").gid;
45104
45563
  } catch {
45105
45564
  }
45106
45565
  for (const { path, groupWritable, sticky } of dirs) {
45107
45566
  try {
45108
- (0, import_node_fs39.mkdirSync)(path, { recursive: true });
45567
+ (0, import_node_fs40.mkdirSync)(path, { recursive: true });
45109
45568
  } catch {
45110
45569
  }
45111
45570
  try {
45112
45571
  if (groupWritable && admGid2 !== null) {
45113
- (0, import_node_fs39.chmodSync)(path, sticky ? 1533 : 509);
45114
- (0, import_node_child_process15.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
45572
+ (0, import_node_fs40.chmodSync)(path, sticky ? 1533 : 509);
45573
+ (0, import_node_child_process16.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
45115
45574
  } else {
45116
- (0, import_node_fs39.chmodSync)(path, 493);
45575
+ (0, import_node_fs40.chmodSync)(path, 493);
45117
45576
  }
45118
45577
  } catch {
45119
45578
  }
@@ -45133,29 +45592,29 @@ async function uninstallServiceCommand() {
45133
45592
  return;
45134
45593
  }
45135
45594
  try {
45136
- (0, import_node_child_process15.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
45595
+ (0, import_node_child_process16.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
45137
45596
  } catch {
45138
45597
  }
45139
45598
  try {
45140
- (0, import_node_child_process15.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
45599
+ (0, import_node_child_process16.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
45141
45600
  } catch {
45142
45601
  }
45143
45602
  try {
45144
- if ((0, import_node_fs39.existsSync)(UNIT_PATH)) {
45145
- (0, import_node_child_process15.execSync)(`rm -f ${UNIT_PATH}`);
45603
+ if ((0, import_node_fs40.existsSync)(UNIT_PATH)) {
45604
+ (0, import_node_child_process16.execSync)(`rm -f ${UNIT_PATH}`);
45146
45605
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
45147
45606
  }
45148
45607
  } catch {
45149
45608
  }
45150
45609
  try {
45151
- (0, import_node_child_process15.execSync)("systemctl daemon-reload", { stdio: "inherit" });
45610
+ (0, import_node_child_process16.execSync)("systemctl daemon-reload", { stdio: "inherit" });
45152
45611
  } catch {
45153
45612
  }
45154
45613
  console.log(source_default.green(" \u2713 threatcrushd service removed."));
45155
45614
  }
45156
45615
 
45157
45616
  // src/commands/save.ts
45158
- var import_node_fs40 = require("fs");
45617
+ var import_node_fs41 = require("fs");
45159
45618
  var import_toml5 = __toESM(require_toml());
45160
45619
  init_cli_config();
45161
45620
  init_paths();
@@ -45194,9 +45653,9 @@ async function saveCommand(opts = {}) {
45194
45653
  }
45195
45654
  const path = opts.config ?? PATHS.configFile;
45196
45655
  let config = {};
45197
- if ((0, import_node_fs40.existsSync)(path)) {
45656
+ if ((0, import_node_fs41.existsSync)(path)) {
45198
45657
  try {
45199
- config = import_toml5.default.parse((0, import_node_fs40.readFileSync)(path, "utf-8"));
45658
+ config = import_toml5.default.parse((0, import_node_fs41.readFileSync)(path, "utf-8"));
45200
45659
  } catch (err) {
45201
45660
  console.log(source_default.red(` \u2717 ${path} is not valid TOML: ${err.message}
45202
45661
  `));
@@ -45309,8 +45768,8 @@ function welcomeCommand() {
45309
45768
  }
45310
45769
 
45311
45770
  // src/commands/properties.ts
45312
- var import_node_fs41 = require("fs");
45313
- var import_node_path30 = require("path");
45771
+ var import_node_fs42 = require("fs");
45772
+ var import_node_path31 = require("path");
45314
45773
  var import_node_readline4 = __toESM(require("readline"));
45315
45774
  init_cli_config();
45316
45775
  var API_URL5 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
@@ -45640,8 +46099,8 @@ async function propertiesRunsCommand(opts) {
45640
46099
  }
45641
46100
  }
45642
46101
  function parseImportFile(path) {
45643
- const ext = (0, import_node_path30.extname)(path).toLowerCase();
45644
- const raw = (0, import_node_fs41.readFileSync)(path, "utf-8");
46102
+ const ext = (0, import_node_path31.extname)(path).toLowerCase();
46103
+ const raw = (0, import_node_fs42.readFileSync)(path, "utf-8");
45645
46104
  if (ext === ".json") {
45646
46105
  const parsed = JSON.parse(raw);
45647
46106
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -45836,19 +46295,19 @@ async function rulesCommand(opts) {
45836
46295
  }
45837
46296
 
45838
46297
  // src/commands/harden.ts
45839
- var import_node_fs42 = require("fs");
45840
- var import_node_child_process16 = require("child_process");
46298
+ var import_node_fs43 = require("fs");
46299
+ var import_node_child_process17 = require("child_process");
45841
46300
  init_cli_config();
45842
46301
  function tryExec(cmd) {
45843
46302
  try {
45844
- return (0, import_node_child_process16.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
46303
+ return (0, import_node_child_process17.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
45845
46304
  } catch {
45846
46305
  return null;
45847
46306
  }
45848
46307
  }
45849
46308
  function tryRead(path) {
45850
46309
  try {
45851
- return (0, import_node_fs42.readFileSync)(path, "utf-8");
46310
+ return (0, import_node_fs43.readFileSync)(path, "utf-8");
45852
46311
  } catch {
45853
46312
  return null;
45854
46313
  }
@@ -45952,8 +46411,8 @@ function checkSshWeakConfig() {
45952
46411
  };
45953
46412
  }
45954
46413
  function checkAutoUpdates() {
45955
- const unattended = (0, import_node_fs42.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs42.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
45956
- const dnfAuto = (0, import_node_fs42.existsSync)("/etc/dnf/automatic.conf");
46414
+ const unattended = (0, import_node_fs43.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs43.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
46415
+ const dnfAuto = (0, import_node_fs43.existsSync)("/etc/dnf/automatic.conf");
45957
46416
  if (unattended || dnfAuto) {
45958
46417
  return {
45959
46418
  key: "auto-updates",
@@ -46079,7 +46538,7 @@ function checkFail2ban() {
46079
46538
  explanation: "fail2ban is installed and running."
46080
46539
  };
46081
46540
  }
46082
- if ((0, import_node_fs42.existsSync)("/etc/fail2ban/fail2ban.conf")) {
46541
+ if ((0, import_node_fs43.existsSync)("/etc/fail2ban/fail2ban.conf")) {
46083
46542
  return {
46084
46543
  key: checkKey,
46085
46544
  status: "warn",
@@ -46265,9 +46724,9 @@ async function hardenCommand(opts) {
46265
46724
  }
46266
46725
 
46267
46726
  // src/core/patches/index.ts
46268
- var import_node_fs43 = require("fs");
46269
- var import_node_path31 = require("path");
46270
- var import_node_child_process17 = require("child_process");
46727
+ var import_node_fs44 = require("fs");
46728
+ var import_node_path32 = require("path");
46729
+ var import_node_child_process18 = require("child_process");
46271
46730
  var import_node_util2 = require("util");
46272
46731
 
46273
46732
  // src/core/patches/dpkg-version.ts
@@ -46327,7 +46786,7 @@ var STALE_AFTER_MS = 2 * 864e5;
46327
46786
  var SEVERITIES2 = ["info", "low", "medium", "high", "critical"];
46328
46787
  var RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
46329
46788
  var defaultExec = async (file, args) => {
46330
- const { stdout } = await (0, import_node_util2.promisify)(import_node_child_process17.execFile)(file, args, {
46789
+ const { stdout } = await (0, import_node_util2.promisify)(import_node_child_process18.execFile)(file, args, {
46331
46790
  timeout: 12e4,
46332
46791
  maxBuffer: 32 * 1024 * 1024,
46333
46792
  env: { ...process.env, LC_ALL: "C" }
@@ -46426,9 +46885,9 @@ async function osvRecords(doFetch, ecosystem, source, version) {
46426
46885
  function newestReleaseMtime(dir) {
46427
46886
  try {
46428
46887
  let newest = 0;
46429
- for (const name of (0, import_node_fs43.readdirSync)(dir)) {
46888
+ for (const name of (0, import_node_fs44.readdirSync)(dir)) {
46430
46889
  if (!/Release$/.test(name)) continue;
46431
- newest = Math.max(newest, (0, import_node_fs43.statSync)((0, import_node_path31.join)(dir, name)).mtimeMs);
46890
+ newest = Math.max(newest, (0, import_node_fs44.statSync)((0, import_node_path32.join)(dir, name)).mtimeMs);
46432
46891
  }
46433
46892
  return newest > 0 ? new Date(newest) : null;
46434
46893
  } catch {
@@ -46445,7 +46904,7 @@ async function checkPatches(opts = {}) {
46445
46904
  let osText = opts.osRelease;
46446
46905
  if (osText === void 0) {
46447
46906
  try {
46448
- osText = (0, import_node_fs43.readFileSync)("/etc/os-release", "utf-8");
46907
+ osText = (0, import_node_fs44.readFileSync)("/etc/os-release", "utf-8");
46449
46908
  } catch {
46450
46909
  osText = "";
46451
46910
  }
@@ -46672,15 +47131,15 @@ async function patchesCommand(opts) {
46672
47131
 
46673
47132
  // src/commands/feeds.ts
46674
47133
  var import_node_net12 = require("net");
46675
- var import_node_path32 = require("path");
47134
+ var import_node_path33 = require("path");
46676
47135
  init_paths();
46677
47136
  async function loadSet() {
46678
47137
  for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
46679
- const path = (0, import_node_path32.join)(dir, "threat-feeds.json");
47138
+ const path = (0, import_node_path33.join)(dir, "threat-feeds.json");
46680
47139
  const set = readFeedCache(path);
46681
47140
  if (set) return { set, from: path };
46682
47141
  }
46683
- const settings = threatFeedSettings(loadConfig((0, import_node_path32.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
47142
+ const settings = threatFeedSettings(loadConfig((0, import_node_path33.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
46684
47143
  return { set: await fetchFeeds(settings), from: "abuse.ch (live; no daemon cache readable)" };
46685
47144
  }
46686
47145
  async function feedsCommand(action, value, opts) {
@@ -46719,6 +47178,73 @@ async function feedsCommand(action, value, opts) {
46719
47178
  console.log(source_default.gray("\n Blocking egress needs [threat_feeds] block = true and [remediation] in enforce mode."));
46720
47179
  }
46721
47180
 
47181
+ // src/commands/privileged.ts
47182
+ var import_node_fs45 = require("fs");
47183
+ init_paths();
47184
+ var SEV2 = {
47185
+ critical: source_default.red.bold,
47186
+ high: source_default.red,
47187
+ medium: source_default.yellow,
47188
+ low: source_default.cyan,
47189
+ info: source_default.gray
47190
+ };
47191
+ async function privilegedCommand(opts) {
47192
+ const snapshot = takeSnapshot({
47193
+ readFile: (p) => {
47194
+ try {
47195
+ return (0, import_node_fs45.readFileSync)(p, "utf-8");
47196
+ } catch {
47197
+ return null;
47198
+ }
47199
+ },
47200
+ readDir: (p) => {
47201
+ try {
47202
+ return (0, import_node_fs45.readdirSync)(p);
47203
+ } catch {
47204
+ return null;
47205
+ }
47206
+ },
47207
+ exists: (p) => (0, import_node_fs45.existsSync)(p)
47208
+ });
47209
+ let events = [];
47210
+ let ledgerNote = "";
47211
+ try {
47212
+ initStateDB(PATHS.stateDb);
47213
+ events = getModuleEvents("privileged-access", Number(opts.limit) || 25);
47214
+ } catch {
47215
+ ledgerNote = `the daemon's state database (${PATHS.stateDb}) is not readable here`;
47216
+ }
47217
+ if (opts.json) {
47218
+ console.log(JSON.stringify({ snapshot, events }, null, 2));
47219
+ return;
47220
+ }
47221
+ console.log(` ${source_default.white.bold("uid 0 accounts:")} ${snapshot.uid0.join(", ") || "\u2014"}`);
47222
+ for (const [group, members] of Object.entries(snapshot.admin_groups)) {
47223
+ console.log(` ${source_default.white.bold(`${group} group:`)} ${members.join(", ") || "\u2014"}`);
47224
+ }
47225
+ const rules = Object.entries(snapshot.sudoers).filter(([, r]) => r.length > 0);
47226
+ console.log(` ${source_default.white.bold("sudoers:")} ${rules.length} file(s) with rules`);
47227
+ for (const [path, r] of rules) {
47228
+ for (const rule of r.filter((x) => !/^Defaults\b/.test(x))) console.log(source_default.gray(` ${path.replace("/etc/", "")}: ${rule}`));
47229
+ }
47230
+ console.log(` ${source_default.white.bold("authorized keys:")}`);
47231
+ for (const [user, keys] of Object.entries(snapshot.keys)) {
47232
+ for (const [fp, k] of Object.entries(keys)) console.log(` ${user.padEnd(12)} ${k.type.padEnd(20)} ${fp} ${source_default.gray(k.comment)}`);
47233
+ }
47234
+ if (snapshot.unreadable.length) {
47235
+ console.log(source_default.yellow(` ! not readable as this user: ${snapshot.unreadable.join(", ")} (run with sudo for the full picture)`));
47236
+ }
47237
+ console.log(`
47238
+ ${source_default.white.bold("Recent changes and sudo commands")}`);
47239
+ if (ledgerNote) console.log(source_default.gray(` ${ledgerNote}`));
47240
+ else if (events.length === 0) console.log(source_default.gray(" none recorded yet (the daemon records them from its first run on)"));
47241
+ for (const e of events) {
47242
+ const at = new Date(e.timestamp).toISOString().replace("T", " ").slice(0, 19);
47243
+ console.log(` ${source_default.gray(at)} ${(SEV2[e.severity] ?? source_default.white)(e.severity.padEnd(8))} ${e.message}`);
47244
+ }
47245
+ console.log();
47246
+ }
47247
+
46722
47248
  // src/commands/firewall.ts
46723
47249
  init_ipc_client();
46724
47250
  init_paths();
@@ -46863,11 +47389,11 @@ async function allowlistCommand(opts) {
46863
47389
  init_paths();
46864
47390
 
46865
47391
  // src/upgrade.ts
46866
- var import_node_child_process18 = require("child_process");
47392
+ var import_node_child_process19 = require("child_process");
46867
47393
  var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
46868
47394
  var defaultRunner = (cmd) => {
46869
47395
  try {
46870
- return (0, import_node_child_process18.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
47396
+ return (0, import_node_child_process19.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
46871
47397
  } catch {
46872
47398
  return null;
46873
47399
  }
@@ -46982,25 +47508,25 @@ ${source_default.dim(" C R U S H")}
46982
47508
  var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
46983
47509
  var PKG_NAME2 = "@profullstack/threatcrush";
46984
47510
  var DESKTOP_PKG_NAME = "@profullstack/threatcrush-desktop";
46985
- var INSTALL_CONFIG_PATH = (0, import_node_path33.join)((0, import_node_os13.homedir)(), ".threatcrush", "install.json");
47511
+ var INSTALL_CONFIG_PATH = (0, import_node_path34.join)((0, import_node_os13.homedir)(), ".threatcrush", "install.json");
46986
47512
  function detectPackageManager() {
46987
47513
  try {
46988
- const npmGlobal = (0, import_node_child_process19.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
47514
+ const npmGlobal = (0, import_node_child_process20.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
46989
47515
  if (npmGlobal.includes(PKG_NAME2)) return "npm";
46990
47516
  } catch {
46991
47517
  }
46992
47518
  try {
46993
- (0, import_node_child_process19.execSync)("pnpm --version", { stdio: "pipe" });
47519
+ (0, import_node_child_process20.execSync)("pnpm --version", { stdio: "pipe" });
46994
47520
  return "pnpm";
46995
47521
  } catch {
46996
47522
  }
46997
47523
  try {
46998
- (0, import_node_child_process19.execSync)("yarn --version", { stdio: "pipe" });
47524
+ (0, import_node_child_process20.execSync)("yarn --version", { stdio: "pipe" });
46999
47525
  return "yarn";
47000
47526
  } catch {
47001
47527
  }
47002
47528
  try {
47003
- (0, import_node_child_process19.execSync)("bun --version", { stdio: "pipe" });
47529
+ (0, import_node_child_process20.execSync)("bun --version", { stdio: "pipe" });
47004
47530
  return "bun";
47005
47531
  } catch {
47006
47532
  }
@@ -47008,14 +47534,14 @@ function detectPackageManager() {
47008
47534
  }
47009
47535
  function readInstallConfig() {
47010
47536
  try {
47011
- return JSON.parse((0, import_node_fs44.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
47537
+ return JSON.parse((0, import_node_fs46.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
47012
47538
  } catch {
47013
47539
  return {};
47014
47540
  }
47015
47541
  }
47016
47542
  function packageLooksInstalled(pm, pkgName) {
47017
47543
  try {
47018
- const output = (0, import_node_child_process19.execSync)(globalListCommand(pm, pkgName), {
47544
+ const output = (0, import_node_child_process20.execSync)(globalListCommand(pm, pkgName), {
47019
47545
  encoding: "utf-8",
47020
47546
  stdio: ["pipe", "pipe", "pipe"]
47021
47547
  });
@@ -47118,14 +47644,14 @@ async function promoteUnprivilegedDaemon() {
47118
47644
  function restartSystemdDaemon() {
47119
47645
  const asRoot = typeof process.getuid === "function" && process.getuid() === 0;
47120
47646
  const argv = asRoot ? ["systemctl", "restart", DAEMON_UNIT] : ["sudo", "systemctl", "restart", DAEMON_UNIT];
47121
- if (!asRoot && (0, import_node_child_process19.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
47647
+ if (!asRoot && (0, import_node_child_process20.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
47122
47648
  const [cmd, ...args] = argv;
47123
- if ((0, import_node_child_process19.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
47124
- return (0, import_node_child_process19.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
47649
+ if ((0, import_node_child_process20.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
47650
+ return (0, import_node_child_process20.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
47125
47651
  }
47126
47652
  function execQuiet(cmd) {
47127
47653
  try {
47128
- return (0, import_node_child_process19.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
47654
+ return (0, import_node_child_process20.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
47129
47655
  } catch {
47130
47656
  return null;
47131
47657
  }
@@ -47281,6 +47807,9 @@ program2.command("patches").description("List OS packages with a security update
47281
47807
  program2.command("feeds [action] [value]").description("Show the abuse.ch C2/malware list the daemon matches; `feeds check <ip|domain>` looks one up (exit 1 when listed)").option("--json", "Output as JSON").action(async (action, value, opts) => {
47282
47808
  await feedsCommand(action, value, opts);
47283
47809
  });
47810
+ program2.command("privileged").description("Who can become root here (uid 0, sudo groups, sudoers, SSH keys) and the daemon's record of changes and sudo commands").option("--json", "Output as JSON").option("--limit <n>", "How many recent events to show", "25").action(async (opts) => {
47811
+ await privilegedCommand(opts);
47812
+ });
47284
47813
  program2.command("block").description("Block an IP address via the firewall").argument("<ip>", "IP address to block").option("--ttl <duration>", "Block duration (e.g. 1h, 30m, 1d)").action(async (ip, opts) => {
47285
47814
  await blockCommand(ip, opts);
47286
47815
  });
@@ -47317,7 +47846,7 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
47317
47846
  program2.command("logs").description("Tail daemon logs").action(async () => {
47318
47847
  console.log(LOGO2);
47319
47848
  const logPath = PATHS.logFile;
47320
- if (!(0, import_node_fs44.existsSync)(logPath)) {
47849
+ if (!(0, import_node_fs46.existsSync)(logPath)) {
47321
47850
  console.log(source_default.yellow(` No log file found at ${logPath}`));
47322
47851
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
47323
47852
  return;
@@ -47325,7 +47854,7 @@ program2.command("logs").description("Tail daemon logs").action(async () => {
47325
47854
  console.log(source_default.green(` Tailing ${logPath}...
47326
47855
  `));
47327
47856
  console.log(source_default.gray(" Press Ctrl+C to stop\n"));
47328
- (0, import_node_child_process19.execSync)(`tail -f ${logPath}`, { stdio: "inherit" });
47857
+ (0, import_node_child_process20.execSync)(`tail -f ${logPath}`, { stdio: "inherit" });
47329
47858
  });
47330
47859
  program2.command("update").description("Update ThreatCrush CLI and installed bundle").option("--cli", "Update CLI only").option("--modules", "Update modules only").option("--desktop", "Update desktop app too").action(async (opts) => {
47331
47860
  console.log(LOGO2);
@@ -47337,7 +47866,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
47337
47866
  for (const cmd of commands2) {
47338
47867
  console.log(source_default.green(` \u2192 ${cmd}
47339
47868
  `));
47340
- (0, import_node_child_process19.execSync)(cmd, { stdio: "inherit" });
47869
+ (0, import_node_child_process20.execSync)(cmd, { stdio: "inherit" });
47341
47870
  }
47342
47871
  console.log(source_default.green("\n \u2713 Modules updated successfully!\n"));
47343
47872
  await reportIfStillStale();
@@ -47362,7 +47891,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
47362
47891
  for (const cmd of commands) {
47363
47892
  console.log(source_default.green(` \u2192 ${cmd}
47364
47893
  `));
47365
- (0, import_node_child_process19.execSync)(cmd, { stdio: "inherit" });
47894
+ (0, import_node_child_process20.execSync)(cmd, { stdio: "inherit" });
47366
47895
  }
47367
47896
  console.log(source_default.green("\n \u2713 ThreatCrush updated successfully!\n"));
47368
47897
  if (installMode === "desktop") {
@@ -47413,7 +47942,7 @@ program2.command("remove").description("Uninstall ThreatCrush and the installed
47413
47942
  for (const cmd of commands) {
47414
47943
  console.log(source_default.green(` \u2192 ${cmd}
47415
47944
  `));
47416
- (0, import_node_child_process19.execSync)(cmd, { stdio: "inherit" });
47945
+ (0, import_node_child_process20.execSync)(cmd, { stdio: "inherit" });
47417
47946
  }
47418
47947
  console.log(source_default.green("\n \u2713 ThreatCrush has been uninstalled.\n"));
47419
47948
  console.log(source_default.dim(" We're sorry to see you go! \u{1F44B}\n"));
@@ -47490,10 +48019,10 @@ storeCmd.command("search <query>").description("Search for modules in the store"
47490
48019
  });
47491
48020
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
47492
48021
  console.log(LOGO2);
47493
- const configPath = (0, import_node_path33.join)((0, import_node_os13.homedir)(), ".threatcrush", "config.json");
48022
+ const configPath = (0, import_node_path34.join)((0, import_node_os13.homedir)(), ".threatcrush", "config.json");
47494
48023
  let email = "";
47495
48024
  try {
47496
- const config = JSON.parse((0, import_node_fs44.readFileSync)(configPath, "utf-8"));
48025
+ const config = JSON.parse((0, import_node_fs46.readFileSync)(configPath, "utf-8"));
47497
48026
  email = config.email || "";
47498
48027
  } catch {
47499
48028
  }
@@ -47510,9 +48039,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
47510
48039
  return;
47511
48040
  }
47512
48041
  try {
47513
- const dir = (0, import_node_path33.join)((0, import_node_os13.homedir)(), ".threatcrush");
47514
- if (!(0, import_node_fs44.existsSync)(dir)) (0, import_node_fs44.mkdirSync)(dir, { recursive: true });
47515
- (0, import_node_fs44.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
48042
+ const dir = (0, import_node_path34.join)((0, import_node_os13.homedir)(), ".threatcrush");
48043
+ if (!(0, import_node_fs46.existsSync)(dir)) (0, import_node_fs46.mkdirSync)(dir, { recursive: true });
48044
+ (0, import_node_fs46.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
47516
48045
  console.log(source_default.dim(` Saved email to ${configPath}`));
47517
48046
  } catch {
47518
48047
  }