@profullstack/threatcrush 0.14.0 → 0.15.1

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
@@ -2038,10 +2038,10 @@ var require_identity = __commonJS({
2038
2038
  var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type");
2039
2039
  var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS;
2040
2040
  var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC;
2041
- var isMap2 = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
2041
+ var isMap3 = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
2042
2042
  var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR;
2043
- var isScalar2 = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
2044
- var isSeq2 = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
2043
+ var isScalar3 = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
2044
+ var isSeq3 = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
2045
2045
  function isCollection(node) {
2046
2046
  if (node && typeof node === "object")
2047
2047
  switch (node[NODE_TYPE]) {
@@ -2062,7 +2062,7 @@ var require_identity = __commonJS({
2062
2062
  }
2063
2063
  return false;
2064
2064
  }
2065
- var hasAnchor = (node) => (isScalar2(node) || isCollection(node)) && !!node.anchor;
2065
+ var hasAnchor = (node) => (isScalar3(node) || isCollection(node)) && !!node.anchor;
2066
2066
  exports2.ALIAS = ALIAS;
2067
2067
  exports2.DOC = DOC;
2068
2068
  exports2.MAP = MAP;
@@ -2074,11 +2074,11 @@ var require_identity = __commonJS({
2074
2074
  exports2.isAlias = isAlias;
2075
2075
  exports2.isCollection = isCollection;
2076
2076
  exports2.isDocument = isDocument;
2077
- exports2.isMap = isMap2;
2077
+ exports2.isMap = isMap3;
2078
2078
  exports2.isNode = isNode;
2079
2079
  exports2.isPair = isPair;
2080
- exports2.isScalar = isScalar2;
2081
- exports2.isSeq = isSeq2;
2080
+ exports2.isScalar = isScalar3;
2081
+ exports2.isSeq = isSeq3;
2082
2082
  }
2083
2083
  });
2084
2084
 
@@ -6186,9 +6186,9 @@ var require_resolve_flow_collection = __commonJS({
6186
6186
  var blockMsg = "Block collections are not allowed within flow collections";
6187
6187
  var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq");
6188
6188
  function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {
6189
- const isMap2 = fc.start.source === "{";
6190
- const fcName = isMap2 ? "flow map" : "flow sequence";
6191
- const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq);
6189
+ const isMap3 = fc.start.source === "{";
6190
+ const fcName = isMap3 ? "flow map" : "flow sequence";
6191
+ const NodeClass = tag?.nodeClass ?? (isMap3 ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq);
6192
6192
  const coll = new NodeClass(ctx.schema);
6193
6193
  coll.flow = true;
6194
6194
  const atRoot = ctx.atRoot;
@@ -6224,7 +6224,7 @@ var require_resolve_flow_collection = __commonJS({
6224
6224
  offset = props.end;
6225
6225
  continue;
6226
6226
  }
6227
- if (!isMap2 && ctx.options.strict && utilContainsNewline.containsNewline(key))
6227
+ if (!isMap3 && ctx.options.strict && utilContainsNewline.containsNewline(key))
6228
6228
  onError(
6229
6229
  key,
6230
6230
  // checked by containsNewline()
@@ -6264,7 +6264,7 @@ var require_resolve_flow_collection = __commonJS({
6264
6264
  }
6265
6265
  }
6266
6266
  }
6267
- if (!isMap2 && !sep9 && !props.found) {
6267
+ if (!isMap3 && !sep9 && !props.found) {
6268
6268
  const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep9, null, props, onError);
6269
6269
  coll.items.push(valueNode);
6270
6270
  offset = valueNode.range[2];
@@ -6287,7 +6287,7 @@ var require_resolve_flow_collection = __commonJS({
6287
6287
  startOnNewline: false
6288
6288
  });
6289
6289
  if (valueProps.found) {
6290
- if (!isMap2 && !props.found && ctx.options.strict) {
6290
+ if (!isMap3 && !props.found && ctx.options.strict) {
6291
6291
  if (sep9)
6292
6292
  for (const st of sep9) {
6293
6293
  if (st === valueProps.found)
@@ -6319,7 +6319,7 @@ var require_resolve_flow_collection = __commonJS({
6319
6319
  const pair = new Pair.Pair(keyNode, valueNode);
6320
6320
  if (ctx.options.keepSourceTokens)
6321
6321
  pair.srcToken = collItem;
6322
- if (isMap2) {
6322
+ if (isMap3) {
6323
6323
  const map = coll;
6324
6324
  if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
6325
6325
  onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
@@ -6335,7 +6335,7 @@ var require_resolve_flow_collection = __commonJS({
6335
6335
  offset = valueNode ? valueNode.range[2] : valueProps.end;
6336
6336
  }
6337
6337
  }
6338
- const expectedEnd = isMap2 ? "}" : "]";
6338
+ const expectedEnd = isMap3 ? "}" : "]";
6339
6339
  const [ce, ...ee] = fc.end;
6340
6340
  let cePos = offset;
6341
6341
  if (ce?.source === expectedEnd)
@@ -7622,7 +7622,7 @@ var require_cst = __commonJS({
7622
7622
  var FLOW_END = "";
7623
7623
  var SCALAR = "";
7624
7624
  var isCollection = (token) => !!token && "items" in token;
7625
- var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar");
7625
+ var isScalar3 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar");
7626
7626
  function prettyToken(token) {
7627
7627
  switch (token) {
7628
7628
  case BOM:
@@ -7706,7 +7706,7 @@ var require_cst = __commonJS({
7706
7706
  exports2.FLOW_END = FLOW_END;
7707
7707
  exports2.SCALAR = SCALAR;
7708
7708
  exports2.isCollection = isCollection;
7709
- exports2.isScalar = isScalar2;
7709
+ exports2.isScalar = isScalar3;
7710
7710
  exports2.prettyToken = prettyToken;
7711
7711
  exports2.tokenType = tokenType;
7712
7712
  }
@@ -8305,7 +8305,7 @@ var require_lexer = __commonJS({
8305
8305
  var require_line_counter = __commonJS({
8306
8306
  "../../node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/dist/parse/line-counter.js"(exports2) {
8307
8307
  "use strict";
8308
- var LineCounter2 = class {
8308
+ var LineCounter3 = class {
8309
8309
  constructor() {
8310
8310
  this.lineStarts = [];
8311
8311
  this.addNewLine = (offset) => this.lineStarts.push(offset);
@@ -8328,7 +8328,7 @@ var require_line_counter = __commonJS({
8328
8328
  };
8329
8329
  }
8330
8330
  };
8331
- exports2.LineCounter = LineCounter2;
8331
+ exports2.LineCounter = LineCounter3;
8332
8332
  }
8333
8333
  });
8334
8334
 
@@ -9236,7 +9236,7 @@ var require_public_api = __commonJS({
9236
9236
  return docs;
9237
9237
  return Object.assign([], { empty: true }, composer$1.streamInfo());
9238
9238
  }
9239
- function parseDocument2(source, options = {}) {
9239
+ function parseDocument3(source, options = {}) {
9240
9240
  const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
9241
9241
  const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
9242
9242
  const composer$1 = new composer.Composer(options);
@@ -9262,7 +9262,7 @@ var require_public_api = __commonJS({
9262
9262
  } else if (options === void 0 && reviver && typeof reviver === "object") {
9263
9263
  options = reviver;
9264
9264
  }
9265
- const doc = parseDocument2(src, options);
9265
+ const doc = parseDocument3(src, options);
9266
9266
  if (!doc)
9267
9267
  return null;
9268
9268
  doc.warnings.forEach((warning) => log.warn(doc.options.logLevel, warning));
@@ -9298,7 +9298,7 @@ var require_public_api = __commonJS({
9298
9298
  }
9299
9299
  exports2.parse = parse;
9300
9300
  exports2.parseAllDocuments = parseAllDocuments;
9301
- exports2.parseDocument = parseDocument2;
9301
+ exports2.parseDocument = parseDocument3;
9302
9302
  exports2.stringify = stringify;
9303
9303
  }
9304
9304
  });
@@ -9356,10 +9356,10 @@ var require_dist = __commonJS({
9356
9356
  });
9357
9357
 
9358
9358
  // src/daemon/index.ts
9359
- var import_node_fs41 = require("fs");
9360
- var import_node_child_process16 = require("child_process");
9359
+ var import_node_fs42 = require("fs");
9360
+ var import_node_child_process17 = require("child_process");
9361
9361
  var import_node_os6 = require("os");
9362
- var import_node_path30 = require("path");
9362
+ var import_node_path32 = require("path");
9363
9363
  var import_node_util = require("util");
9364
9364
 
9365
9365
  // src/daemon/paths.ts
@@ -17998,11 +17998,15 @@ function defaultGateways() {
17998
17998
 
17999
17999
  // src/core/threat-feeds/index.ts
18000
18000
  var FEEDS = {
18001
- threatfoxRecent: "https://threatfox.abuse.ch/export/json/recent/",
18002
- threatfoxHosts: "https://threatfox.abuse.ch/downloads/hostfile/",
18003
- urlhausHosts: "https://urlhaus.abuse.ch/downloads/hostfile/",
18001
+ /** POST `{ query: 'get_iocs', days }` with an `Auth-Key` header. */
18002
+ threatfoxApi: "https://threatfox-api.abuse.ch/api/v1/",
18003
+ /** Keyed file exports: the Auth-Key is a path segment. */
18004
+ threatfoxHosts: (key) => `https://threatfox-api.abuse.ch/v2/files/exports/${encodeURIComponent(key)}/hostfile.txt`,
18005
+ urlhausOnline: (key) => `https://urlhaus-api.abuse.ch/v2/files/exports/${encodeURIComponent(key)}/online.csv`,
18004
18006
  feodoIps: "https://feodotracker.abuse.ch/downloads/ipblocklist.txt"
18005
18007
  };
18008
+ var THREATFOX_DAYS = 3;
18009
+ var NEEDS_KEY = "needs an abuse.ch Auth-Key (free at auth.abuse.ch): set [threat_feeds] auth_key_file or ABUSECH_AUTH_KEY";
18006
18010
  var SHARED_RANGES = [
18007
18011
  "173.245.48.0/20",
18008
18012
  "103.21.244.0/22",
@@ -18065,11 +18069,19 @@ function parseThreatFoxJson(text, minConfidence) {
18065
18069
  const ips = /* @__PURE__ */ new Map();
18066
18070
  const domains = /* @__PURE__ */ new Map();
18067
18071
  const data = JSON.parse(text);
18068
- for (const entries2 of Object.values(data)) {
18072
+ let lists;
18073
+ if (typeof data.query_status === "string") {
18074
+ if (data.query_status === "no_result") return { ips, domains };
18075
+ if (data.query_status !== "ok") throw new Error(`ThreatFox API: ${data.query_status}`);
18076
+ lists = [data.data];
18077
+ } else {
18078
+ lists = Object.values(data);
18079
+ }
18080
+ for (const entries2 of lists) {
18069
18081
  for (const ioc of Array.isArray(entries2) ? entries2 : []) {
18070
18082
  const confidence = typeof ioc.confidence_level === "number" ? ioc.confidence_level : 0;
18071
18083
  if (confidence < minConfidence) continue;
18072
- const value = String(ioc.ioc_value ?? "").trim();
18084
+ const value = String(ioc.ioc ?? ioc.ioc_value ?? "").trim();
18073
18085
  const ind = {
18074
18086
  malware: String(ioc.malware_printable ?? ioc.malware ?? "unknown"),
18075
18087
  threat: String(ioc.threat_type ?? "unknown"),
@@ -18087,6 +18099,72 @@ function parseThreatFoxJson(text, minConfidence) {
18087
18099
  }
18088
18100
  return { ips, domains };
18089
18101
  }
18102
+ var URL_HOSTING = [
18103
+ ...SHARED_DOMAINS,
18104
+ "github.com",
18105
+ "gitlab.com",
18106
+ "bitbucket.org",
18107
+ "live.com",
18108
+ "1drv.ms",
18109
+ "sharepoint.com",
18110
+ "mediafire.com",
18111
+ "pastebin.com",
18112
+ "transfer.sh",
18113
+ "catbox.moe",
18114
+ "gofile.io",
18115
+ "archive.org",
18116
+ "yandex.ru",
18117
+ "mega.nz",
18118
+ "sourceforge.net"
18119
+ ];
18120
+ function urlHosting(host) {
18121
+ return URL_HOSTING.some((d) => host === d || host.endsWith(`.${d}`));
18122
+ }
18123
+ function csvRow(line) {
18124
+ const out = [];
18125
+ let cur = "";
18126
+ let quoted = false;
18127
+ for (let i = 0; i < line.length; i++) {
18128
+ const c = line[i];
18129
+ if (quoted) {
18130
+ if (c === '"' && line[i + 1] === '"') {
18131
+ cur += '"';
18132
+ i++;
18133
+ } else if (c === '"') quoted = false;
18134
+ else cur += c;
18135
+ } else if (c === '"') quoted = true;
18136
+ else if (c === ",") {
18137
+ out.push(cur);
18138
+ cur = "";
18139
+ } else cur += c;
18140
+ }
18141
+ out.push(cur);
18142
+ return out;
18143
+ }
18144
+ function parseUrlhausCsv(text) {
18145
+ const ips = /* @__PURE__ */ new Map();
18146
+ const domains = /* @__PURE__ */ new Map();
18147
+ for (const line of text.split("\n")) {
18148
+ const trimmed = line.trim();
18149
+ if (!trimmed || trimmed.startsWith("#")) continue;
18150
+ const cols = csvRow(trimmed);
18151
+ if (cols.length < 6 || cols[3] && cols[3] !== "online") continue;
18152
+ let host;
18153
+ try {
18154
+ host = new URL(cols[2]).hostname.replace(/^\[|\]$/g, "");
18155
+ } catch {
18156
+ continue;
18157
+ }
18158
+ const ind = { malware: cols[6]?.split(",")[0] || "unknown", threat: cols[5] || "malware_download", feed: "urlhaus" };
18159
+ if ((0, import_node_net4.isIP)(host)) {
18160
+ ips.set(host, ind);
18161
+ continue;
18162
+ }
18163
+ const domain = normalizeDomain(host);
18164
+ if (domain && !urlHosting(domain)) domains.set(domain, ind);
18165
+ }
18166
+ return { ips, domains };
18167
+ }
18090
18168
  function parseHostfile(text, feed) {
18091
18169
  const out = /* @__PURE__ */ new Map();
18092
18170
  for (const line of text.split("\n")) {
@@ -18142,26 +18220,67 @@ function buildFeedSet(parts, allow, sources, now = /* @__PURE__ */ new Date()) {
18142
18220
  }
18143
18221
  return { fetched_at: now.toISOString(), ips, domains, sources, skipped_shared: skipped };
18144
18222
  }
18145
- async function fetchFeeds(settings, fetchImpl = fetch) {
18223
+ var FETCH_ATTEMPTS = 3;
18224
+ var FatalFeedError = class extends Error {
18225
+ };
18226
+ function redact(message, key) {
18227
+ if (!key) return message;
18228
+ return message.split(key).join("<auth-key>").split(encodeURIComponent(key)).join("<auth-key>");
18229
+ }
18230
+ async function fetchFeeds(settings, fetchImpl = fetch, retryDelayMs = 5e3) {
18146
18231
  const sources = [];
18147
18232
  const parts = [];
18148
- const get2 = async (feed, url, parse) => {
18233
+ const key = settings.authKey?.trim() || void 0;
18234
+ const ua = { "User-Agent": "threatcrush (+https://threatcrush.com)" };
18235
+ const get2 = async (feed, request2, parse, emptyOk = false) => {
18236
+ if (!request2) {
18237
+ sources.push({ feed, ok: false, count: 0, error: NEEDS_KEY });
18238
+ return;
18239
+ }
18149
18240
  try {
18150
- const res = await fetchImpl(url, { signal: AbortSignal.timeout(6e4), headers: { "User-Agent": "threatcrush (+https://threatcrush.com)" } });
18151
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
18152
- const part = parse(await res.text());
18241
+ const extra = request2.init?.headers ?? {};
18242
+ let part;
18243
+ for (let attempt = 1; ; attempt++) {
18244
+ try {
18245
+ const res = await fetchImpl(request2.url, { ...request2.init, signal: AbortSignal.timeout(6e4), headers: { ...ua, ...extra } });
18246
+ if (res.status === 401 || res.status === 403) throw new FatalFeedError(`HTTP ${res.status}: abuse.ch refused the Auth-Key`);
18247
+ if (res.status >= 400 && res.status < 500) throw new FatalFeedError(`HTTP ${res.status}`);
18248
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
18249
+ const text = await res.text();
18250
+ const type = res.headers.get("content-type") ?? "";
18251
+ if (type.includes("text/html") || /^\s*<(!doctype|html)/i.test(text)) throw new FatalFeedError(`HTTP ${res.status} but an HTML page, not feed data`);
18252
+ part = parse(text);
18253
+ break;
18254
+ } catch (err) {
18255
+ const retryable = !(err instanceof FatalFeedError) && !/^ThreatFox API: /.test(err.message);
18256
+ if (!retryable || attempt >= FETCH_ATTEMPTS) throw err;
18257
+ await new Promise((r) => setTimeout(r, retryDelayMs * attempt));
18258
+ }
18259
+ }
18260
+ const count = (part.ips?.size ?? 0) + (part.domains?.size ?? 0);
18261
+ if (count === 0 && !emptyOk) throw new Error("no entries in the response");
18153
18262
  parts.push(part);
18154
- sources.push({ feed, ok: true, count: (part.ips?.size ?? 0) + (part.domains?.size ?? 0) });
18263
+ sources.push({ feed, ok: true, count });
18155
18264
  } catch (err) {
18156
- sources.push({ feed, ok: false, count: 0, error: err.message });
18265
+ sources.push({ feed, ok: false, count: 0, error: redact(err.message, key) });
18157
18266
  }
18158
18267
  };
18268
+ const threatfoxApi = key ? {
18269
+ url: FEEDS.threatfoxApi,
18270
+ init: {
18271
+ method: "POST",
18272
+ headers: { "Auth-Key": key, "Content-Type": "application/json" },
18273
+ body: JSON.stringify({ query: "get_iocs", days: THREATFOX_DAYS })
18274
+ }
18275
+ } : null;
18159
18276
  await Promise.all([
18160
- get2("threatfox", FEEDS.threatfoxRecent, (t) => parseThreatFoxJson(t, settings.minConfidence)),
18161
- get2("threatfox-hosts", FEEDS.threatfoxHosts, (t) => ({ domains: parseHostfile(t, "threatfox") })),
18162
- get2("urlhaus-hosts", FEEDS.urlhausHosts, (t) => ({ domains: parseHostfile(t, "urlhaus") })),
18163
- get2("feodo", FEEDS.feodoIps, (t) => ({ ips: parseIpList(t, "feodo") }))
18277
+ get2("threatfox", threatfoxApi, (t) => parseThreatFoxJson(t, settings.minConfidence), true),
18278
+ get2("threatfox-hosts", key ? { url: FEEDS.threatfoxHosts(key) } : null, (t) => ({ domains: parseHostfile(t, "threatfox") })),
18279
+ get2("urlhaus", key ? { url: FEEDS.urlhausOnline(key) } : null, parseUrlhausCsv),
18280
+ // Feodo has been near-empty since 2025; an empty list there is real.
18281
+ get2("feodo", { url: FEEDS.feodoIps }, (t) => ({ ips: parseIpList(t, "feodo") }), true)
18164
18282
  ]);
18283
+ sources.sort((a, b) => a.feed.localeCompare(b.feed));
18165
18284
  return buildFeedSet(parts, settings.allow, sources);
18166
18285
  }
18167
18286
  function readFeedCache(path) {
@@ -21552,18 +21671,18 @@ function isComment(line) {
21552
21671
  }
21553
21672
  function proseLines(lines) {
21554
21673
  const inside = /* @__PURE__ */ new Set();
21555
- let delimiter = null;
21674
+ let delimiter2 = null;
21556
21675
  lines.forEach((line, index) => {
21557
- if (delimiter) {
21676
+ if (delimiter2) {
21558
21677
  inside.add(index);
21559
- if (line.includes(delimiter)) delimiter = null;
21678
+ if (line.includes(delimiter2)) delimiter2 = null;
21560
21679
  return;
21561
21680
  }
21562
21681
  for (const candidate of ['"""', "'''"]) {
21563
21682
  const start = line.indexOf(candidate);
21564
21683
  if (start === -1) continue;
21565
21684
  if (line.indexOf(candidate, start + candidate.length) !== -1) return;
21566
- delimiter = candidate;
21685
+ delimiter2 = candidate;
21567
21686
  inside.add(index);
21568
21687
  return;
21569
21688
  }
@@ -22617,6 +22736,679 @@ function evaluateWorkflowRules(text) {
22617
22736
  return matches.sort((a, b) => a.line - b.line);
22618
22737
  }
22619
22738
 
22739
+ // ../../packages/scan/src/deploy-rules.ts
22740
+ var import_yaml2 = __toESM(require_dist(), 1);
22741
+
22742
+ // ../../packages/scan/src/references.ts
22743
+ var ATTACK_VECTORS_BASE = "https://github.com/profullstack/threatcrush/blob/master/attack-vectors/";
22744
+ function attackVector(slug) {
22745
+ return `${ATTACK_VECTORS_BASE}${slug}.md`;
22746
+ }
22747
+
22748
+ // ../../packages/scan/src/deploy-rules.ts
22749
+ var RULE_LIST2 = [
22750
+ {
22751
+ id: "compose-host-root-mount",
22752
+ title: "Compose service bind-mounts the host root, a home, or an .ssh directory",
22753
+ severity: "critical",
22754
+ confidence: "evidence",
22755
+ cwe: "CWE-250",
22756
+ consequence: "The container reads (and with a writable mount, rewrites) host files: every secret under `/`, private keys and `authorized_keys`. Whoever can change this file or what the container runs owns the host.",
22757
+ fix: "Mount only the specific data directory the service needs, read-only where possible. Never mount `/`, `/root`, `/etc`, a whole home directory or any `.ssh` directory.",
22758
+ reference: attackVector("ci-forced-command-compose")
22759
+ },
22760
+ {
22761
+ id: "compose-docker-socket",
22762
+ title: "Compose service mounts the Docker socket",
22763
+ severity: "high",
22764
+ confidence: "evidence",
22765
+ cwe: "CWE-250",
22766
+ consequence: "The Docker API is root on the host: the container can start a new privileged container that mounts `/`.",
22767
+ fix: "Remove the socket mount. If the service really needs the API, put a filtering proxy in front of it that allows only the calls it makes.",
22768
+ reference: attackVector("ci-forced-command-compose")
22769
+ },
22770
+ {
22771
+ id: "compose-privileged",
22772
+ title: "Compose service runs privileged or with SYS_ADMIN / ALL capabilities",
22773
+ severity: "high",
22774
+ confidence: "evidence",
22775
+ cwe: "CWE-250",
22776
+ consequence: "A privileged container can mount host devices and load kernel modules: escaping it is routine.",
22777
+ fix: "Drop `privileged: true` and add back only the individual capabilities the service needs.",
22778
+ reference: attackVector("ci-forced-command-compose")
22779
+ },
22780
+ {
22781
+ id: "compose-root-user",
22782
+ title: "Compose service explicitly runs as uid 0",
22783
+ severity: "medium",
22784
+ confidence: "evidence",
22785
+ cwe: "CWE-250",
22786
+ consequence: "Root in the container is root on every host path it mounts. Combined with a bind mount it writes host files as root.",
22787
+ fix: 'Run as an unprivileged uid (`user: "1000:1000"`) and give it ownership of only the paths it writes.',
22788
+ reference: attackVector("ci-forced-command-compose")
22789
+ },
22790
+ {
22791
+ id: "deploy-compose-from-synced-repo",
22792
+ title: "docker compose runs a compose file from a repository checkout on the host",
22793
+ severity: "high",
22794
+ confidence: "contextual",
22795
+ cwe: "CWE-94",
22796
+ consequence: 'The compose file (and its build context) is whatever the last push contained. A push that adds `user: "0:0"` and a `/:/host` volume gets root on the host, whatever the ssh key or forced command was meant to allow.',
22797
+ fix: "Keep the compose file the host runs outside the synced tree, owned by root and not writable by the deploy user; deploy by pulling a pinned image tag instead of building from pushed sources.",
22798
+ reference: attackVector("ci-forced-command-compose")
22799
+ },
22800
+ {
22801
+ id: "deploy-remote-exec-uploaded-script",
22802
+ title: "Script from the repository is uploaded to a host and run there",
22803
+ severity: "high",
22804
+ confidence: "contextual",
22805
+ cwe: "CWE-94",
22806
+ consequence: "Anything that can change the repository (a merged PR, a stolen App key pushing to the default branch) changes what runs on the host as the deploy user, which a restricted ssh key was supposed to prevent.",
22807
+ fix: 'Install the deploy script on the host out of band (root-owned, not writable by the deploy user) and pin the key to it with `restrict,command="/usr/local/bin/deploy"`; send only data, never code.',
22808
+ reference: attackVector("ci-forced-command-compose")
22809
+ },
22810
+ {
22811
+ id: "github-app-installation-idor",
22812
+ title: "GitHub App setup callback stores an installation_id from the query string without verifying the user owns it",
22813
+ severity: "high",
22814
+ confidence: "contextual",
22815
+ cwe: "CWE-639",
22816
+ consequence: "Any signed-in user can visit the callback with someone else's `installation_id` and bind that organisation's installation to their account, then use the App's write features against repositories they have no access to. An App-JWT lookup of the installation succeeds for every installation, so it proves nothing about the user.",
22817
+ fix: "Exchange the OAuth `code` for a user-to-server token and require the id to appear in `GET /user/installations`; also carry a signed, single-use `state` through the install flow.",
22818
+ reference: attackVector("github-app-installation-idor")
22819
+ },
22820
+ {
22821
+ id: "authorized-keys-unrestricted",
22822
+ title: "authorized_keys entry with no from=, command= or restrict",
22823
+ severity: "medium",
22824
+ confidence: "evidence",
22825
+ cwe: "CWE-284",
22826
+ consequence: "Whoever holds the private half logs in from anywhere and gets a full shell.",
22827
+ fix: 'Prefix the key with `restrict` and, where possible, `from="<addresses>"` and `command="<script>"` scoped to what it is for.',
22828
+ reference: attackVector("planted-authorized-keys")
22829
+ },
22830
+ {
22831
+ id: "authorized-keys-suspicious-comment",
22832
+ title: "authorized_keys entry named like a temporary CI / diagnostic key",
22833
+ severity: "high",
22834
+ confidence: "contextual",
22835
+ cwe: "CWE-506",
22836
+ consequence: "Intruders plant persistence keys with innocuous dated names (`ci-diag-YYYYMMDD`, `ops-recovery-YYYYMMDD`) and add them to both a user and root.",
22837
+ fix: "Confirm who added the key and when. If nobody can, remove it from every account, then look for other persistence and rotate what the box holds.",
22838
+ reference: attackVector("planted-authorized-keys")
22839
+ },
22840
+ {
22841
+ id: "authorized-keys-sftp-unjailed",
22842
+ title: "sftp-only key without a chroot can read the whole filesystem",
22843
+ severity: "medium",
22844
+ confidence: "pattern",
22845
+ cwe: "CWE-552",
22846
+ consequence: '`command="internal-sftp"` limits what the key can run, not what it can read: it downloads every file the account can read, secrets included.',
22847
+ fix: "Give the account a `Match User` block in sshd_config with `ChrootDirectory` (root-owned) and `ForceCommand internal-sftp`, or a jail that restricts reads as well as writes.",
22848
+ reference: attackVector("sftp-jail-reads-root")
22849
+ },
22850
+ {
22851
+ id: "sshd-sftp-without-chroot",
22852
+ title: "sshd forces sftp without a ChrootDirectory",
22853
+ severity: "medium",
22854
+ confidence: "pattern",
22855
+ cwe: "CWE-552",
22856
+ consequence: "An sftp-only jail that confines writes but not reads still serves every readable file on the host, including app env files and private keys, to anyone with the deploy key.",
22857
+ fix: "Add `ChrootDirectory` (a root-owned directory holding only what the account should see) to the same Match block, or confine reads as well as writes in a custom jail.",
22858
+ reference: attackVector("sftp-jail-reads-root")
22859
+ }
22860
+ ];
22861
+ var RULE2 = Object.fromEntries(RULE_LIST2.map((r) => [r.id, r]));
22862
+ function baseName(path) {
22863
+ const p = path.replace(/\\/g, "/");
22864
+ return p.slice(p.lastIndexOf("/") + 1);
22865
+ }
22866
+ function isComposePath(relativePath) {
22867
+ return /^(?:docker-)?compose(?:[.-][\w.-]+)?\.ya?ml$/i.test(baseName(relativePath));
22868
+ }
22869
+ function isAuthorizedKeysPath(relativePath) {
22870
+ return /^authorized_keys2?(?:\.[\w.-]+)?$/.test(baseName(relativePath));
22871
+ }
22872
+ function isSshdConfigPath(relativePath) {
22873
+ const p = relativePath.replace(/\\/g, "/");
22874
+ return baseName(p) === "sshd_config" || /(?:^|\/)sshd_config\.d\/[^/]+\.conf$/.test(p);
22875
+ }
22876
+ var SOURCE_LANGUAGES = ["javascript", "typescript", "python", "ruby", "go", "php", "java"];
22877
+ function evaluateDeployRules(relativePath, text, language, isWorkflow = false) {
22878
+ const out = [];
22879
+ const emit = (id, line, message, severity) => {
22880
+ const rule = RULE2[id];
22881
+ if (out.some((m) => m.rule.id === id && m.line === line)) return;
22882
+ out.push({ rule, line, message, severity: severityFor(severity ?? rule.severity, rule.confidence) });
22883
+ };
22884
+ try {
22885
+ if (isComposePath(relativePath)) composeRules(text, emit);
22886
+ if (isAuthorizedKeysPath(relativePath)) authorizedKeysRules(text, emit);
22887
+ if (isSshdConfigPath(relativePath)) sshdRules(text, emit);
22888
+ if (isWorkflow || language === "shell" || /\bSSH_ORIGINAL_COMMAND\b/.test(text)) {
22889
+ remoteDeployRules(text, isWorkflow, emit);
22890
+ }
22891
+ if (SOURCE_LANGUAGES.includes(language)) githubAppCallbackRule(text, emit);
22892
+ } catch {
22893
+ }
22894
+ return out.sort((a, b) => a.line - b.line);
22895
+ }
22896
+ function yamlGet(map, key) {
22897
+ if (!(0, import_yaml2.isMap)(map)) return void 0;
22898
+ for (const pair of map.items) {
22899
+ if ((0, import_yaml2.isScalar)(pair.key) && String(pair.key.value) === key) return pair.value;
22900
+ }
22901
+ return void 0;
22902
+ }
22903
+ function yamlStr(node) {
22904
+ if (!(0, import_yaml2.isScalar)(node)) return void 0;
22905
+ const v = node.value;
22906
+ return v === null || v === void 0 ? void 0 : String(v);
22907
+ }
22908
+ function volumeSource(spec) {
22909
+ let depth = 0;
22910
+ for (let i = 0; i < spec.length; i++) {
22911
+ const ch = spec[i];
22912
+ if (ch === "{") depth++;
22913
+ else if (ch === "}") depth = Math.max(0, depth - 1);
22914
+ else if (ch === ":" && depth === 0) {
22915
+ if (i === 1 && /^[A-Za-z]$/.test(spec[0]) && /[\\/]/.test(spec[2] ?? "")) continue;
22916
+ return spec.slice(0, i);
22917
+ }
22918
+ }
22919
+ return null;
22920
+ }
22921
+ function isDangerousHostPath(source) {
22922
+ const s = source.trim().replace(/^['"]|['"]$/g, "");
22923
+ const norm = s.replace(/\$\{HOME\}|\$HOME/g, "~").replace(/\/+$/, "") || "/";
22924
+ if (norm === "/" || norm === "~") return true;
22925
+ if (/^\/(?:root|etc|boot)(?:\/|$)/.test(norm)) return true;
22926
+ if (norm === "/home" || /^\/home\/[^/]+$/.test(norm)) return true;
22927
+ if (/(?:^|\/)\.ssh(?:\/|$)/.test(norm)) return true;
22928
+ return false;
22929
+ }
22930
+ function isDockerSocket(source) {
22931
+ return /^(?:\/var)?\/run\/docker\.sock$/.test(source.trim().replace(/^['"]|['"]$/g, ""));
22932
+ }
22933
+ function composeRules(text, emit) {
22934
+ const lc = new import_yaml2.LineCounter();
22935
+ const doc = (0, import_yaml2.parseDocument)(text, { lineCounter: lc, uniqueKeys: false, strict: false });
22936
+ if (doc.errors.length > 0 || !(0, import_yaml2.isMap)(doc.contents)) return;
22937
+ const lineOf = (node) => node?.range ? lc.linePos(node.range[0]).line : 1;
22938
+ const services = yamlGet(doc.contents, "services");
22939
+ if (!(0, import_yaml2.isMap)(services)) return;
22940
+ for (const pair of services.items) {
22941
+ const name = (0, import_yaml2.isScalar)(pair.key) ? String(pair.key.value) : "?";
22942
+ const svc = pair.value;
22943
+ if (!(0, import_yaml2.isMap)(svc)) continue;
22944
+ const userNode = yamlGet(svc, "user");
22945
+ const user = yamlStr(userNode);
22946
+ const runsAsRoot = user !== void 0 && /^(?:0|root)(?::.*)?$/.test(user.trim());
22947
+ if (runsAsRoot) emit("compose-root-user", lineOf(userNode), `Service \`${name}\` sets \`user: ${user}\``);
22948
+ const priv = yamlGet(svc, "privileged");
22949
+ if (priv && /^true$/i.test(yamlStr(priv) ?? "")) {
22950
+ emit("compose-privileged", lineOf(priv), `Service \`${name}\` sets \`privileged: true\``);
22951
+ }
22952
+ const caps = yamlGet(svc, "cap_add");
22953
+ if ((0, import_yaml2.isSeq)(caps)) {
22954
+ for (const item of caps.items) {
22955
+ const cap = (yamlStr(item) ?? "").toUpperCase().replace(/^CAP_/, "");
22956
+ if (cap === "SYS_ADMIN" || cap === "ALL") {
22957
+ emit("compose-privileged", lineOf(item), `Service \`${name}\` adds capability ${cap}`);
22958
+ }
22959
+ }
22960
+ }
22961
+ const volumes = yamlGet(svc, "volumes");
22962
+ if (!(0, import_yaml2.isSeq)(volumes)) continue;
22963
+ for (const item of volumes.items) {
22964
+ let source;
22965
+ let writable = true;
22966
+ if ((0, import_yaml2.isScalar)(item)) {
22967
+ const spec = yamlStr(item) ?? "";
22968
+ source = volumeSource(spec);
22969
+ writable = !/:ro(?:,|$)/.test(spec.slice((source ?? "").length));
22970
+ } else if ((0, import_yaml2.isMap)(item)) {
22971
+ const type = yamlStr(yamlGet(item, "type"));
22972
+ if (type && type !== "bind") continue;
22973
+ source = yamlStr(yamlGet(item, "source"));
22974
+ writable = !/^true$/i.test(yamlStr(yamlGet(item, "read_only")) ?? "");
22975
+ }
22976
+ if (!source) continue;
22977
+ const line = lineOf(item);
22978
+ if (isDockerSocket(source)) {
22979
+ emit("compose-docker-socket", line, `Service \`${name}\` mounts the Docker socket \`${source}\``);
22980
+ } else if (isDangerousHostPath(source)) {
22981
+ const how = writable ? "writable" : "read-only";
22982
+ const asRoot = runsAsRoot ? ", and the service runs as root" : "";
22983
+ emit("compose-host-root-mount", line, `Service \`${name}\` bind-mounts host path \`${source}\` (${how}${asRoot})`);
22984
+ }
22985
+ }
22986
+ }
22987
+ }
22988
+ var KEY_TYPE = /^(?:ssh-(?:rsa|dss|ed25519)|ecdsa-sha2-nistp\d+|sk-(?:ssh-ed25519|ecdsa-sha2-nistp256)@openssh\.com)$/;
22989
+ function parseAuthorizedKeyLines(text) {
22990
+ const out = [];
22991
+ text.split("\n").forEach((raw, idx) => {
22992
+ const line = raw.replace(/\r$/, "").trim();
22993
+ if (!line || line.startsWith("#")) return;
22994
+ let optionText = "";
22995
+ let rest = line;
22996
+ if (!KEY_TYPE.test(line.split(/\s+/, 1)[0] ?? "")) {
22997
+ let inQuote = false;
22998
+ let cut = -1;
22999
+ for (let i = 0; i < line.length; i++) {
23000
+ const ch = line[i];
23001
+ if (ch === "\\" && inQuote) {
23002
+ i++;
23003
+ continue;
23004
+ }
23005
+ if (ch === '"') inQuote = !inQuote;
23006
+ else if (!inQuote && (ch === " " || ch === " ")) {
23007
+ cut = i;
23008
+ break;
23009
+ }
23010
+ }
23011
+ if (cut === -1) return;
23012
+ optionText = line.slice(0, cut);
23013
+ rest = line.slice(cut).trimStart();
23014
+ }
23015
+ const parts = rest.split(/\s+/);
23016
+ if (!KEY_TYPE.test(parts[0] ?? "") || !parts[1]) return;
23017
+ const options = /* @__PURE__ */ new Map();
23018
+ for (const m of optionText.matchAll(/([A-Za-z-]+)(?:="((?:[^"\\]|\\.)*)")?/g)) {
23019
+ options.set(m[1].toLowerCase(), m[2] ?? null);
23020
+ }
23021
+ out.push({ line: idx + 1, type: parts[0], comment: parts.slice(2).join(" "), options });
23022
+ });
23023
+ return out;
23024
+ }
23025
+ function suspiciousKeyComment(comment) {
23026
+ const c = comment.trim();
23027
+ if (!c || c.includes("@")) return false;
23028
+ const role = /(?:^|[-_.\s])(?:ci|cd|diag|diagnostic|debug|tmp|temp|test|recovery|maint|maintenance|support|backdoor)(?=[-_.\s]|\d|$)/i;
23029
+ const date = /(?:^|\D)(?:20\d{2}[-_.]?[01]\d[-_.]?[0-3]\d|[0-3]\d[01]\d20\d{2})(?:\D|$)/;
23030
+ return role.test(c) && date.test(c);
23031
+ }
23032
+ function authorizedKeysRules(text, emit) {
23033
+ for (const key of parseAuthorizedKeyLines(text)) {
23034
+ const label = key.comment ? `"${key.comment}"` : "(no comment)";
23035
+ const restricted = key.options.has("from") || key.options.has("command") || key.options.has("restrict");
23036
+ if (!restricted) emit("authorized-keys-unrestricted", key.line, `Unrestricted ${key.type} key ${label}`);
23037
+ if (suspiciousKeyComment(key.comment)) {
23038
+ emit(
23039
+ "authorized-keys-suspicious-comment",
23040
+ key.line,
23041
+ `Key ${label} is named like a temporary CI/diagnostic key${restricted ? "" : " and is unrestricted"}`
23042
+ );
23043
+ }
23044
+ const command = key.options.get("command") ?? "";
23045
+ if (/\b(?:internal-sftp|sftp-server)\b/.test(command)) {
23046
+ emit("authorized-keys-sftp-unjailed", key.line, `Key ${label} is sftp-only; sftp alone does not limit reads`);
23047
+ }
23048
+ }
23049
+ }
23050
+ function sshdRules(text, emit) {
23051
+ const blocks = [];
23052
+ let current = { forceLine: 0, chroot: false };
23053
+ let globalChroot = false;
23054
+ let inMatch = false;
23055
+ const flush = () => {
23056
+ if (current.forceLine) blocks.push(current);
23057
+ };
23058
+ text.split("\n").forEach((raw, idx) => {
23059
+ const line = raw.replace(/#.*$/, "").trim();
23060
+ if (!line) return;
23061
+ const [keyword = "", ...rest] = line.split(/\s+/);
23062
+ const kw = keyword.toLowerCase();
23063
+ const value = rest.join(" ");
23064
+ if (kw === "match") {
23065
+ flush();
23066
+ current = { forceLine: 0, chroot: false };
23067
+ inMatch = true;
23068
+ return;
23069
+ }
23070
+ if (kw === "chrootdirectory" && value.toLowerCase() !== "none") {
23071
+ current.chroot = true;
23072
+ if (!inMatch) globalChroot = true;
23073
+ }
23074
+ if (kw === "forcecommand" && /\b(?:internal-sftp|sftp-server)\b/.test(value)) current.forceLine = idx + 1;
23075
+ });
23076
+ flush();
23077
+ for (const block of blocks) {
23078
+ if (block.chroot || globalChroot) continue;
23079
+ emit("sshd-sftp-without-chroot", block.forceLine, "ForceCommand sftp with no ChrootDirectory: reads are not confined");
23080
+ }
23081
+ }
23082
+ function segments(text) {
23083
+ const out = [];
23084
+ let quote = null;
23085
+ let cur = "";
23086
+ for (let i = 0; i < text.length; i++) {
23087
+ const ch = text[i];
23088
+ if (quote) {
23089
+ if (ch === "\\" && quote === '"') {
23090
+ cur += ch + (text[i + 1] ?? "");
23091
+ i++;
23092
+ continue;
23093
+ }
23094
+ if (ch === quote) quote = null;
23095
+ cur += ch;
23096
+ continue;
23097
+ }
23098
+ if (ch === "'" || ch === '"') {
23099
+ quote = ch;
23100
+ cur += ch;
23101
+ continue;
23102
+ }
23103
+ if (ch === ";" || ch === "|" || ch === "&" && text[i + 1] === "&") {
23104
+ out.push(cur);
23105
+ cur = "";
23106
+ if (text[i + 1] === ch) i++;
23107
+ continue;
23108
+ }
23109
+ cur += ch;
23110
+ }
23111
+ out.push(cur);
23112
+ return out.map((s) => s.trim()).filter(Boolean);
23113
+ }
23114
+ function shellWords(text) {
23115
+ const out = [];
23116
+ let quote = null;
23117
+ let cur = "";
23118
+ for (let i = 0; i < text.length; i++) {
23119
+ const ch = text[i];
23120
+ if (quote) {
23121
+ if (ch === quote) quote = null;
23122
+ cur += ch;
23123
+ continue;
23124
+ }
23125
+ if (ch === "'" || ch === '"') {
23126
+ quote = ch;
23127
+ cur += ch;
23128
+ continue;
23129
+ }
23130
+ if (ch === " " || ch === " ") {
23131
+ if (cur) out.push(cur);
23132
+ cur = "";
23133
+ continue;
23134
+ }
23135
+ cur += ch;
23136
+ }
23137
+ if (cur) out.push(cur);
23138
+ return out;
23139
+ }
23140
+ function unquote2(word) {
23141
+ if (word.length >= 2 && (word[0] === '"' || word[0] === "'") && word[word.length - 1] === word[0]) {
23142
+ return word.slice(1, -1);
23143
+ }
23144
+ return word;
23145
+ }
23146
+ var WRAPPERS2 = /* @__PURE__ */ new Set(["sudo", "exec", "command", "nohup", "time", "env", "timeout", "doas"]);
23147
+ function commandOf(segment) {
23148
+ const words3 = shellWords(segment.replace(/^[-\s]*(?:run|script|command):\s*[|>]?[-+]?\s*/, ""));
23149
+ let i = 0;
23150
+ while (i < words3.length) {
23151
+ const w = words3[i];
23152
+ if (/^[A-Za-z_]\w*=/.test(w) || WRAPPERS2.has(w)) {
23153
+ i++;
23154
+ continue;
23155
+ }
23156
+ if (words3[i - 1] === "sudo" && w.startsWith("-")) {
23157
+ i++;
23158
+ continue;
23159
+ }
23160
+ break;
23161
+ }
23162
+ return words3.slice(i);
23163
+ }
23164
+ var SSH_VALUE_OPTS2 = new Set("BbcDEeFIiJLlmOoPpQRSWw".split(""));
23165
+ function sshRemoteCommand(words3) {
23166
+ let i = 1;
23167
+ while (i < words3.length && words3[i].startsWith("-")) {
23168
+ const opt = words3[i];
23169
+ const letter = opt[opt.length - 1];
23170
+ i += opt.length === 2 && SSH_VALUE_OPTS2.has(letter) ? 2 : 1;
23171
+ }
23172
+ i++;
23173
+ if (i >= words3.length) return null;
23174
+ const rest = words3.slice(i).filter((w) => !w.startsWith("<"));
23175
+ if (rest.length === 0) return null;
23176
+ return rest.length === 1 ? unquote2(rest[0]) : rest.map(unquote2).join(" ");
23177
+ }
23178
+ function transferDestination(words3) {
23179
+ for (let i = words3.length - 1; i > 0; i--) {
23180
+ const w = unquote2(words3[i]);
23181
+ if (w.startsWith("-")) continue;
23182
+ const m = /^(?:[\w.${}-]+@)?[\w.${}-]+:(.*)$/.exec(w);
23183
+ if (m && !w.includes("://")) return m[1] || "~";
23184
+ return null;
23185
+ }
23186
+ return null;
23187
+ }
23188
+ function rsyncServerDestination(words3) {
23189
+ if (!words3.includes("--server")) return null;
23190
+ const last = words3[words3.length - 1];
23191
+ return last && !last.startsWith("-") ? unquote2(last) : null;
23192
+ }
23193
+ function normDir(path) {
23194
+ return path.replace(/\/\*+$/, "").replace(/\/+$/, "") || "/";
23195
+ }
23196
+ function joinPath(cwd, path) {
23197
+ if (path.startsWith("/") || path.startsWith("~") || path.startsWith("$")) return path;
23198
+ const clean2 = path.replace(/^\.\//, "");
23199
+ return cwd ? `${normDir(cwd)}/${clean2}` : clean2;
23200
+ }
23201
+ function under(path, dirs) {
23202
+ const p = normDir(path);
23203
+ for (const d of dirs) {
23204
+ const dir = normDir(d);
23205
+ if (dir === "~" || dir === "." || dir === "/") continue;
23206
+ if (p === dir || p.startsWith(`${dir}/`)) return dir;
23207
+ const fixed = dir.split(/[*$]/)[0];
23208
+ if (fixed.length > 1 && fixed !== dir && p.startsWith(fixed)) return dir;
23209
+ }
23210
+ return null;
23211
+ }
23212
+ var COMPOSE = /\bdocker(?:-compose|\s+compose)\b/;
23213
+ var COMPOSE_FILE = /(?:^|\s)(?:-f|--file)(?:=|\s+)['"]?([^\s'";|&]+)/;
23214
+ function remoteSegment(segment, line, state, emit) {
23215
+ const words3 = commandOf(segment);
23216
+ const cmd = words3[0] ?? "";
23217
+ if (cmd === "cd" && words3[1]) {
23218
+ state.cwd = joinPath(state.cwd, unquote2(words3[1]));
23219
+ return;
23220
+ }
23221
+ if (cmd === "git" && /^(?:pull|clone|fetch|checkout|reset)$/.test(words3[1] ?? "")) {
23222
+ if (words3[1] === "clone" && words3.length > 3) state.gitDirs.add(joinPath(state.cwd, unquote2(words3[words3.length - 1])));
23223
+ else if (state.cwd) state.gitDirs.add(state.cwd);
23224
+ return;
23225
+ }
23226
+ if (cmd === "rsync") {
23227
+ const dest = rsyncServerDestination(words3);
23228
+ if (dest) state.uploads.add(dest);
23229
+ return;
23230
+ }
23231
+ if (COMPOSE.test(segment)) {
23232
+ const file = COMPOSE_FILE.exec(segment)?.[1];
23233
+ const target = file ? joinPath(state.cwd, file) : state.cwd;
23234
+ const synced = target ? under(target, state.uploads) : null;
23235
+ const pulled = target ? under(target, state.gitDirs) : null;
23236
+ const forcedWithRsync = state.forced && state.uploads.size > 0 && Boolean(file);
23237
+ if (synced || pulled || forcedWithRsync) {
23238
+ const where = synced ? `under \`${synced}\`, which this file uploads to` : pulled ? `in \`${pulled}\`, a git checkout updated on the host` : "in a forced-command allowlist that also accepts rsync uploads";
23239
+ const build = /\s--build\b|\sbuild\b/.test(segment) ? " and builds from it" : "";
23240
+ emit(
23241
+ "deploy-compose-from-synced-repo",
23242
+ line,
23243
+ `\`docker compose\` runs ${file ? `\`${file}\`` : "the compose file in the working directory"} ${where}${build}`
23244
+ );
23245
+ }
23246
+ return;
23247
+ }
23248
+ let script;
23249
+ if (/^(?:ba|z|da|k)?sh$|^source$|^\.$/.test(cmd) && words3[1] && !words3[1].startsWith("-")) script = unquote2(words3[1]);
23250
+ else if (/\.(?:sh|bash|py|rb|pl)$/.test(cmd) || cmd.startsWith("./")) script = cmd;
23251
+ if (script) {
23252
+ const path = joinPath(state.cwd, script);
23253
+ const dir = under(path, state.uploads);
23254
+ if (dir) {
23255
+ emit("deploy-remote-exec-uploaded-script", line, `Runs \`${script}\` on the host from \`${dir}\`, which this file uploads to`);
23256
+ }
23257
+ }
23258
+ }
23259
+ function logicalLines2(text) {
23260
+ const raw = text.split("\n");
23261
+ const out = [];
23262
+ for (let i = 0; i < raw.length; i++) {
23263
+ let t = raw[i];
23264
+ const start = i + 1;
23265
+ while (/\\\s*$/.test(t) && i + 1 < raw.length) {
23266
+ t = t.replace(/\\\s*$/, " ") + raw[++i].trim();
23267
+ }
23268
+ out.push({ text: t, line: start });
23269
+ }
23270
+ return out;
23271
+ }
23272
+ function isCommentLine(text) {
23273
+ return /^\s*#/.test(text);
23274
+ }
23275
+ function remoteDeployRules(text, isWorkflow, emit) {
23276
+ const forced = /\bSSH_ORIGINAL_COMMAND\b/.test(text);
23277
+ const lines = logicalLines2(text);
23278
+ const uploads = /* @__PURE__ */ new Set();
23279
+ let sawScpAction = false;
23280
+ for (const { text: t } of lines) {
23281
+ if (isCommentLine(t)) continue;
23282
+ for (const seg of segments(t)) {
23283
+ const words3 = commandOf(seg);
23284
+ if (words3[0] === "rsync" || words3[0] === "scp") {
23285
+ const dest = transferDestination(words3) ?? rsyncServerDestination(words3);
23286
+ if (dest) uploads.add(dest);
23287
+ }
23288
+ }
23289
+ if (isWorkflow) {
23290
+ if (/uses:\s*['"]?appleboy\/scp-action@/.test(t)) sawScpAction = true;
23291
+ const target = /^\s*target:\s*['"]?([^'"\s]+)/.exec(t);
23292
+ if (target && sawScpAction) {
23293
+ uploads.add(target[1]);
23294
+ sawScpAction = false;
23295
+ }
23296
+ }
23297
+ if (forced) {
23298
+ const allowed = /rsync(?:\\?\s)+--server[^)\n]*?\s(\/[^\s)"'*]+)/.exec(t);
23299
+ if (allowed) uploads.add(allowed[1]);
23300
+ }
23301
+ }
23302
+ const fresh = () => ({ cwd: null, uploads, gitDirs: /* @__PURE__ */ new Set(), forced });
23303
+ let heredoc = null;
23304
+ let actionScript = null;
23305
+ let sawSshAction = false;
23306
+ const forcedState = fresh();
23307
+ for (const { text: t, line } of lines) {
23308
+ if (heredoc) {
23309
+ if (t.trim() === heredoc.end) {
23310
+ heredoc = null;
23311
+ continue;
23312
+ }
23313
+ if (!isCommentLine(t)) for (const seg of segments(t)) remoteSegment(seg, line, heredoc.state, emit);
23314
+ continue;
23315
+ }
23316
+ if (actionScript) {
23317
+ const indent = /^\s*/.exec(t)[0].length;
23318
+ if (t.trim() && indent <= actionScript.indent) actionScript = null;
23319
+ else {
23320
+ if (!isCommentLine(t)) for (const seg of segments(t)) remoteSegment(seg, line, actionScript.state, emit);
23321
+ continue;
23322
+ }
23323
+ }
23324
+ if (isCommentLine(t)) continue;
23325
+ if (isWorkflow) {
23326
+ if (/uses:\s*['"]?appleboy\/ssh-action@/.test(t)) sawSshAction = true;
23327
+ const script = /^(\s*)script:\s*[|>]?[-+]?\s*$/.exec(t);
23328
+ if (script && sawSshAction) {
23329
+ actionScript = { indent: script[1].length, state: fresh() };
23330
+ sawSshAction = false;
23331
+ continue;
23332
+ }
23333
+ }
23334
+ if (forced) {
23335
+ const body = t.replace(/^\s*[^()]*\)\s*/, "").replace(/;;\s*$/, "");
23336
+ for (const seg of segments(body)) remoteSegment(seg, line, forcedState, emit);
23337
+ continue;
23338
+ }
23339
+ for (const seg of segments(t)) {
23340
+ const words3 = commandOf(seg);
23341
+ if (words3[0] !== "ssh") continue;
23342
+ const piped = /(?:^|\s)(?:ba|z)?sh\s+-s\b[^<]*<(?!<)\s*['"]?([^\s'"<]+)/.exec(seg);
23343
+ if (piped) {
23344
+ emit("deploy-remote-exec-uploaded-script", line, `Pipes repository script \`${piped[1]}\` into a remote shell`);
23345
+ continue;
23346
+ }
23347
+ const here = /<<-?\s*['"]?(\w+)['"]?/.exec(seg);
23348
+ if (here) {
23349
+ heredoc = { end: here[1], state: fresh() };
23350
+ continue;
23351
+ }
23352
+ const remote = sshRemoteCommand(words3);
23353
+ if (!remote) continue;
23354
+ const state = fresh();
23355
+ for (const inner of segments(remote)) remoteSegment(inner, line, state, emit);
23356
+ }
23357
+ }
23358
+ }
23359
+ var INSTALLATION_FROM_QUERY = new RegExp(
23360
+ [
23361
+ String.raw`searchParams\.get\(\s*['"]installation_id['"]`,
23362
+ String.raw`\b(?:req|request|ctx|context)\.(?:query|params)(?:\.installation_id\b|\[\s*['"]installation_id['"])`,
23363
+ String.raw`\bquery\.installation_id\b`,
23364
+ String.raw`\bquery\[\s*['"]installation_id['"]\s*\]`,
23365
+ String.raw`\breq\.query\(\s*['"]installation_id['"]`,
23366
+ String.raw`request\.(?:args|GET|query_params)(?:\.get\(\s*|\[\s*)['"]installation_id['"]`,
23367
+ String.raw`\bparams\[\s*:installation_id\s*\]`,
23368
+ String.raw`\$_(?:GET|REQUEST)\[\s*['"]installation_id['"]`,
23369
+ String.raw`Query\(\)\.Get\(\s*"installation_id"`,
23370
+ String.raw`getParameter\(\s*"installation_id"`,
23371
+ String.raw`\{[^}]*\binstallation_id\b[^}]*\}\s*=\s*(?:await\s+)?(?:req|request|ctx)\.query\b`
23372
+ ].join("|")
23373
+ );
23374
+ var PERSISTS = /\.(?:insert|upsert|create|createMany|save|update|updateOne|findOneAndUpdate)\s*\(|\bINSERT\s+INTO\b|\bON\s+CONFLICT\b|\bUPDATE\s+\w+\s+SET\b|\.objects\.(?:create|update_or_create|get_or_create)\b/i;
23375
+ var VERIFIES_USER = /\/user\/installations|listInstallationsForAuthenticatedUser|(?:verify|check|assert|ensure|validate|confirm)\w*Installation\w*\s*\(|installationBelongsTo\w*\s*\(|userCanAccessInstallation\s*\(/;
23376
+ var DECLARATION = /^(?:export\s+(?:default\s+)?)?(?:async\s+)?function\b|^(?:export\s+)?(?:const|let|var)\s+\w+\s*=\s*(?:async\b|function\b|\(|\w+\s*=>)|^(?:async\s+)?def\s|^func\s|^\s{0,4}(?:public\s+|private\s+|protected\s+)?(?:static\s+)?function\s|^(?:app|router|server)\.(?:get|post|put|all|route)\s*\(|^@\w+\.(?:route|get|post)\b|^\s{0,2}def\s/;
23377
+ function githubAppCallbackRule(text, emit) {
23378
+ if (!text.includes("installation_id") || !INSTALLATION_FROM_QUERY.test(text)) return;
23379
+ const lines = text.split("\n");
23380
+ const chunks = [];
23381
+ let start = 0;
23382
+ for (let i = 1; i < lines.length; i++) {
23383
+ if (DECLARATION.test(lines[i])) {
23384
+ chunks.push({ start, end: i });
23385
+ start = i;
23386
+ }
23387
+ }
23388
+ chunks.push({ start, end: lines.length });
23389
+ const verifyingHelpers = /* @__PURE__ */ new Set();
23390
+ for (const c of chunks) {
23391
+ const body = lines.slice(c.start, c.end).join("\n");
23392
+ if (!VERIFIES_USER.test(body)) continue;
23393
+ const name = /(?:function\s+|(?:const|let|var)\s+|def\s+|func\s+)(\w+)/.exec(lines[c.start] ?? "")?.[1];
23394
+ if (name) verifyingHelpers.add(name);
23395
+ }
23396
+ for (const c of chunks) {
23397
+ const chunkLines = lines.slice(c.start, c.end);
23398
+ const body = chunkLines.join("\n");
23399
+ const readAt = chunkLines.findIndex((l) => INSTALLATION_FROM_QUERY.test(l) && !/^\s*(?:\/\/|#|\*)/.test(l));
23400
+ if (readAt === -1) continue;
23401
+ if (!PERSISTS.test(body)) continue;
23402
+ if (VERIFIES_USER.test(body)) continue;
23403
+ if ([...verifyingHelpers].some((name) => new RegExp(`\\b${name}\\s*\\(`).test(body))) continue;
23404
+ emit(
23405
+ "github-app-installation-idor",
23406
+ c.start + readAt + 1,
23407
+ "`installation_id` is read from the query string and stored, with no check that the signed-in user can access that installation (`GET /user/installations`)"
23408
+ );
23409
+ }
23410
+ }
23411
+
22620
23412
  // ../../packages/scan/src/controls.ts
22621
23413
  var SERVER_FRAMEWORK = /\bexpress\s*\(\s*\)|\bnew\s+Koa\s*\(|\bfastify\s*\(|\brequire\s*\(\s*['"](?:express|koa|@hapi\/hapi|restify)['"]\s*\)|\bfrom\s+['"](?:express|koa|@hapi\/hapi|restify)['"]|\bhttp\s*\.\s*createServer\s*\(|\bNestFactory\s*\.\s*create\s*\(/;
22622
23414
  var SECURITY_CONTROLS = [
@@ -23016,11 +23808,28 @@ var SECRET_RULES = [
23016
23808
  {
23017
23809
  id: "secret-private-key",
23018
23810
  name: "Private Key",
23019
- pattern: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY(?: BLOCK)?-----/,
23811
+ pattern: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----/,
23020
23812
  severity: "critical",
23021
23813
  cwe: "CWE-798",
23022
23814
  consequence: "Key material, committed. Rotation is the only remediation.",
23023
- confirm: (lines, index, match) => hasPemBody(lines, index, match)
23815
+ confirm: (lines, index, match) => hasPemBody(lines, index, match),
23816
+ fix: "Regenerate the key at its issuer, delete the old one there, and load the new one from a secret manager. Deleting the file does not help: it is in the history.",
23817
+ reference: attackVector("unrotated-github-app-keys")
23818
+ },
23819
+ {
23820
+ id: "secret-github-app-private-key",
23821
+ name: "GitHub App Private Key",
23822
+ // The same banner, confirmed by an App id in the same file. That pairing is
23823
+ // everything needed to mint installation tokens for every org the App is
23824
+ // installed in, which is why it outranks a bare private key.
23825
+ pattern: /-----BEGIN (?:RSA |ENCRYPTED )?PRIVATE KEY-----/,
23826
+ severity: "critical",
23827
+ cwe: "CWE-798",
23828
+ consequence: "With the App id beside it, anyone holding this file mints installation tokens for every account the App is installed on and pushes, merges or reads as `<app>[bot]`. Suspending the App does not stop it: the key can unsuspend.",
23829
+ confirm: (lines, index, match) => hasPemBody(lines, index, match) && hasGithubAppId(lines),
23830
+ supersedes: ["secret-private-key"],
23831
+ fix: "Generate a new private key in the App settings, delete every old key there, then delete or rotate the installations that matter. Treat every copy on disk (and its `.bak`) as burned.",
23832
+ reference: attackVector("unrotated-github-app-keys")
23024
23833
  },
23025
23834
  {
23026
23835
  id: "secret-slack-token",
@@ -23088,6 +23897,28 @@ var SECRET_RULES = [
23088
23897
  cwe: "CWE-798",
23089
23898
  consequence: "Direct database access, usually bypassing every application-level authorisation check."
23090
23899
  },
23900
+ {
23901
+ id: "secret-resend-key",
23902
+ name: "Resend API Key",
23903
+ pattern: /\bre_[A-Za-z0-9]{8}_[A-Za-z0-9]{16,}\b/,
23904
+ severity: "critical",
23905
+ cwe: "CWE-798",
23906
+ consequence: "Send mail as every verified domain on the account."
23907
+ },
23908
+ {
23909
+ id: "secret-supabase-service-role",
23910
+ name: "Supabase service-role key",
23911
+ // A JWT whose payload claims `role: service_role`. Decoded rather than
23912
+ // guessed from the variable name: the anon key has the same shape and is
23913
+ // public by design.
23914
+ pattern: /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{16,}/,
23915
+ severity: "critical",
23916
+ cwe: "CWE-798",
23917
+ consequence: "Bypasses every row-level security policy: full read and write on the project database.",
23918
+ confirm: (_lines, _index, match) => jwtClaimsRole(match[0], "service_role"),
23919
+ supersedes: ["secret-jwt", "secret-generic-high-entropy"],
23920
+ fix: "Rotate the JWT secret (which reissues both keys) and keep the service-role key server-side only."
23921
+ },
23091
23922
  {
23092
23923
  id: "secret-jwt",
23093
23924
  name: "JSON Web Token",
@@ -23119,8 +23950,28 @@ var SECRET_RULES = [
23119
23950
  keywordShaped: true
23120
23951
  },
23121
23952
  {
23122
- id: "secret-hex-token",
23123
- name: "High-entropy Hex Token",
23953
+ id: "secret-generic-high-entropy",
23954
+ name: "High-entropy secret in a *_SECRET / *_PRIVATE_KEY / *_TOKEN variable",
23955
+ // The unquoted `.env` assignment the quoted-only generic rules above leave
23956
+ // alone. Safe to key on the name only because the value must also look
23957
+ // like key material: long, mixed-class and high-entropy (see
23958
+ // `looksLikeKeyMaterial`). An ARN or a parameter-store path fails that,
23959
+ // which is what keeps the header's two counter-examples quiet. All-hex
23960
+ // values belong to `secret-hex-token` and are left to it.
23961
+ pattern: /^\s*(?:export\s+)?(?![A-Z0-9_]*(?:PUBLIC|ANON|PUBLISHABLE))[A-Z][A-Z0-9_]*(?:SECRET|PRIVATE_KEY|_TOKEN|_API_KEY|_PASSWORD|_PASSWD)[A-Z0-9_]*\s*[=:]\s*([A-Za-z0-9+/_.~-]{20,}={0,2})\s*$/,
23962
+ severity: "high",
23963
+ cwe: "CWE-798",
23964
+ consequence: "Whatever the variable unlocks, in every clone, backup and image layer that carries this file.",
23965
+ keywordShaped: true,
23966
+ yieldsToVendorRules: true,
23967
+ confirm: (_lines, _index, match) => looksLikeKeyMaterial(match[1] ?? ""),
23968
+ supersedes: ["secret-jwt"],
23969
+ fix: "Rotate the value, then load it from a secret manager or the deploy environment instead of a committed file.",
23970
+ reference: attackVector("unrotated-github-app-keys")
23971
+ },
23972
+ {
23973
+ id: "secret-hex-token",
23974
+ name: "High-entropy Hex Token",
23124
23975
  pattern: /(?:token|key|secret|auth|signing)\w*\s*[=:]\s*['"]?([0-9a-f]{32,})['"]?/i,
23125
23976
  severity: "medium",
23126
23977
  cwe: "CWE-798",
@@ -23181,6 +24032,40 @@ function hasPemBody(lines, index, match) {
23181
24032
  }
23182
24033
  return false;
23183
24034
  }
24035
+ var GITHUB_APP_ID = /\b(?:GITHUB_APP_ID|GH_APP_ID|APP_ID|app_id|appId)\b['"]?\s*[=:]\s*['"]?\d{2,}/;
24036
+ function hasGithubAppId(lines) {
24037
+ return lines.some((line) => GITHUB_APP_ID.test(line));
24038
+ }
24039
+ function jwtClaimsRole(token, role) {
24040
+ const payload = token.split(".")[1];
24041
+ if (!payload) return false;
24042
+ try {
24043
+ const b64 = payload.replace(/-/g, "+").replace(/_/g, "/");
24044
+ const json = JSON.parse(atob(b64 + "=".repeat((4 - b64.length % 4) % 4)));
24045
+ return json.role === role;
24046
+ } catch {
24047
+ return false;
24048
+ }
24049
+ }
24050
+ function shannonEntropy(value) {
24051
+ if (!value) return 0;
24052
+ const counts = /* @__PURE__ */ new Map();
24053
+ for (const ch of value) counts.set(ch, (counts.get(ch) ?? 0) + 1);
24054
+ let bits = 0;
24055
+ for (const n of counts.values()) {
24056
+ const p = n / value.length;
24057
+ bits -= p * Math.log2(p);
24058
+ }
24059
+ return bits;
24060
+ }
24061
+ function looksLikeKeyMaterial(value) {
24062
+ if (value.length < 20) return false;
24063
+ if (value.startsWith("/") || value.includes("://")) return false;
24064
+ if (/^[0-9a-f]+$/i.test(value)) return false;
24065
+ const classes = [/[a-z]/, /[A-Z]/, /[0-9]/].filter((re) => re.test(value)).length;
24066
+ if (classes < 2) return false;
24067
+ return shannonEntropy(value) >= 3.5;
24068
+ }
23184
24069
  function isPlaceholderAttribute(line, value) {
23185
24070
  const at = line.lastIndexOf(value);
23186
24071
  if (at === -1) return false;
@@ -23243,13 +24128,28 @@ function redactSecret(line) {
23243
24128
  return `${match.slice(0, 3)}${"*".repeat(Math.min(16, match.length - 3))}`;
23244
24129
  });
23245
24130
  }
24131
+ function isEnvFileName(filename) {
24132
+ const name = filename.toLowerCase();
24133
+ if (/\.(?:example|sample|template|dist|defaults?)$/.test(name)) return false;
24134
+ return /^\.env(?:\..*)?$/.test(name) || /\.env$/.test(name) || isEnvBackupName(name);
24135
+ }
24136
+ function isEnvBackupName(filename) {
24137
+ return /(?:^|\.)env\.(?:bak|old|orig|save|backup|prev|swp)(?:[.~_-].*)?$/i.test(filename) || /\.env~$/i.test(filename);
24138
+ }
23246
24139
  var SENSITIVE_FILES = [
24140
+ {
24141
+ pattern: ".env.bak",
24142
+ test: isEnvBackupName,
24143
+ message: "Backup copy of an environment file committed: backups are never rotated with the original",
24144
+ severity: "critical"
24145
+ },
23247
24146
  { pattern: ".env", message: "Environment file committed \u2014 the usual home of every runtime credential", severity: "high" },
23248
24147
  { pattern: ".env.local", message: "Local environment file committed", severity: "high" },
23249
24148
  { pattern: ".env.production", message: "Production environment file committed", severity: "critical" },
23250
24149
  { pattern: "id_rsa", message: "Private SSH key committed", severity: "critical" },
23251
24150
  { pattern: "id_ed25519", message: "Private SSH key committed", severity: "critical" },
23252
24151
  { pattern: "id_ecdsa", message: "Private SSH key committed", severity: "critical" },
24152
+ { pattern: "id_dsa", message: "Private SSH key committed", severity: "critical" },
23253
24153
  { pattern: ".pem", message: "PEM certificate or key file committed", severity: "high" },
23254
24154
  { pattern: ".p12", message: "PKCS#12 keystore committed", severity: "high" },
23255
24155
  { pattern: ".pfx", message: "PKCS#12 keystore committed", severity: "high" },
@@ -23623,11 +24523,19 @@ function scanText(relativePath, text, language = languageOf(relativePath)) {
23623
24523
  const inDocs = isDocPath(relativePath);
23624
24524
  const inlineTests = inlineTestLines(relativePath, lines);
23625
24525
  lines.forEach((line, index) => {
24526
+ const lineMatches = [];
23626
24527
  for (const rule of SECRET_RULES) {
23627
24528
  const match = rule.pattern.exec(line);
23628
24529
  if (!match) continue;
23629
24530
  if (isKnownPlaceholder(match[0])) continue;
23630
24531
  if (rule.confirm && !rule.confirm(lines, index, match)) continue;
24532
+ lineMatches.push({ rule, match });
24533
+ }
24534
+ const superseded = new Set(lineMatches.flatMap(({ rule }) => rule.supersedes ?? []));
24535
+ const vendorMatched = lineMatches.some(({ rule }) => !rule.keywordShaped);
24536
+ for (const { rule, match } of lineMatches) {
24537
+ if (superseded.has(rule.id)) continue;
24538
+ if (rule.yieldsToVendorRules && vendorMatched) continue;
23631
24539
  if (isSuppressed(suppressions, index, rule.id)) continue;
23632
24540
  const value = match[1] ?? match[0];
23633
24541
  if (isVariableReference(value)) continue;
@@ -23653,6 +24561,8 @@ function scanText(relativePath, text, language = languageOf(relativePath)) {
23653
24561
  confidence: "evidence",
23654
24562
  message: soft ? `Possible ${rule.name} detected ${SECRET_SOFTENING[soft]}` : `Possible ${rule.name} detected`,
23655
24563
  consequence: rule.consequence,
24564
+ ...rule.fix ? { fix: rule.fix } : {},
24565
+ ...rule.reference ? { reference: rule.reference } : {},
23656
24566
  cwe: rule.cwe,
23657
24567
  excerpt: redactSecret(line.trim()).slice(0, 200),
23658
24568
  sensitive: true,
@@ -23710,7 +24620,8 @@ function scanText(relativePath, text, language = languageOf(relativePath)) {
23710
24620
  category: "code"
23711
24621
  });
23712
24622
  }
23713
- if (isWorkflowPath(relativePath, text)) {
24623
+ const isWorkflow = isWorkflowPath(relativePath, text);
24624
+ if (isWorkflow) {
23714
24625
  for (const match of evaluateWorkflowRules(text)) {
23715
24626
  const index = match.line - 1;
23716
24627
  if (isSuppressed(suppressions, index, match.rule.id)) continue;
@@ -23735,6 +24646,30 @@ function scanText(relativePath, text, language = languageOf(relativePath)) {
23735
24646
  });
23736
24647
  }
23737
24648
  }
24649
+ for (const match of evaluateDeployRules(relativePath, text, language, isWorkflow)) {
24650
+ const index = match.line - 1;
24651
+ if (isSuppressed(suppressions, index, match.rule.id)) continue;
24652
+ const soft = softening({
24653
+ test: inTests,
24654
+ docs: inDocs,
24655
+ suppressed: foreignSecurityMark(lines[index] ?? "")
24656
+ });
24657
+ findings.push({
24658
+ ruleId: match.rule.id,
24659
+ title: match.rule.title,
24660
+ file: relativePath,
24661
+ line: match.line,
24662
+ severity: soft ? "low" : match.severity,
24663
+ confidence: match.rule.confidence,
24664
+ message: soft ? `${match.message} (${CODE_SOFTENING[soft]})` : match.message,
24665
+ consequence: match.rule.consequence,
24666
+ fix: match.rule.fix,
24667
+ reference: match.rule.reference,
24668
+ cwe: match.rule.cwe,
24669
+ excerpt: (lines[index] ?? "").trim().slice(0, 200),
24670
+ category: "code"
24671
+ });
24672
+ }
23738
24673
  return findings;
23739
24674
  }
23740
24675
  function scanManifest(relativePath, filename, text) {
@@ -23854,7 +24789,7 @@ function scanPath(targetPath, options = {}) {
23854
24789
  const relativePath = toRelative(walkRoot, fullPath);
23855
24790
  const extension = (0, import_node_path11.extname)(filename).toLowerCase();
23856
24791
  const isManifest = filename === "package.json" || filename === "requirements.txt";
23857
- const scannable = SCAN_EXTENSIONS.has(extension) || filename.startsWith(".env");
24792
+ const scannable = SCAN_EXTENSIONS.has(extension) || filename.startsWith(".env") || isEnvFileName(filename) || isAuthorizedKeysPath(filename);
23858
24793
  const mayDeclareInterpreter = !scannable && !isManifest && extension === "";
23859
24794
  if (!scannable && !isManifest && !mayDeclareInterpreter) {
23860
24795
  recordSensitiveFile(filename, relativePath, findings, []);
@@ -23875,7 +24810,10 @@ function scanPath(targetPath, options = {}) {
23875
24810
  const prefix = Buffer.alloc(128);
23876
24811
  const read = (0, import_node_fs17.readSync)(handle, prefix, 0, prefix.length, 0);
23877
24812
  declared = languageOfShebang(prefix.subarray(0, read).toString("utf-8").split("\n", 1)[0] ?? "");
23878
- if (!declared) return;
24813
+ if (!declared) {
24814
+ recordSensitiveFile(filename, relativePath, findings, []);
24815
+ return;
24816
+ }
23879
24817
  }
23880
24818
  text = (0, import_node_fs17.readFileSync)(handle, "utf-8");
23881
24819
  } catch {
@@ -23943,7 +24881,7 @@ function scanPath(targetPath, options = {}) {
23943
24881
  function recordSensitiveFile(filename, relativePath, sink, fileFindings) {
23944
24882
  if (fileFindings.length > 0) return;
23945
24883
  for (const sensitive of SENSITIVE_FILES) {
23946
- const matches = filename === sensitive.pattern || filename.endsWith(sensitive.pattern);
24884
+ const matches = sensitive.test ? sensitive.test(filename) : filename === sensitive.pattern || filename.endsWith(sensitive.pattern);
23947
24885
  if (!matches) continue;
23948
24886
  sink.push({
23949
24887
  ruleId: "sensitive-file-committed",
@@ -23954,6 +24892,8 @@ function recordSensitiveFile(filename, relativePath, sink, fileFindings) {
23954
24892
  confidence: "evidence",
23955
24893
  message: sensitive.message,
23956
24894
  consequence: "Anything in this file is in every clone, fork and CI cache of the repository.",
24895
+ fix: "Remove it from the repository and its history, add the name to .gitignore, and rotate every credential it held: treat each one as burned.",
24896
+ reference: attackVector("unrotated-github-app-keys"),
23957
24897
  cwe: "CWE-538",
23958
24898
  excerpt: "",
23959
24899
  sensitive: true,
@@ -25853,7 +26793,7 @@ var EGRESS_TABLE = "threatcrush_egress";
25853
26793
  var DEFAULT_REFRESH_MS = 36e5;
25854
26794
  var POLL_MS = 15e3;
25855
26795
  var REALERT_MS = 36e5;
25856
- function threatFeedSettings(section) {
26796
+ function threatFeedSettings(section, env2 = process.env) {
25857
26797
  const refresh = parseDuration(section?.refresh);
25858
26798
  return {
25859
26799
  enabled: section?.enabled !== false,
@@ -25862,9 +26802,21 @@ function threatFeedSettings(section) {
25862
26802
  // abuse.ch asks for no more than one fetch per 5 minutes; hourly is plenty.
25863
26803
  refreshMs: refresh ? Math.max(900, refresh) * 1e3 : DEFAULT_REFRESH_MS,
25864
26804
  minConfidence: typeof section?.min_confidence === "number" ? section.min_confidence : 75,
25865
- allow: Array.isArray(section?.allow) ? section.allow.map(String) : []
26805
+ allow: Array.isArray(section?.allow) ? section.allow.map(String) : [],
26806
+ authKey: abusechAuthKey(section, env2)
25866
26807
  };
25867
26808
  }
26809
+ function abusechAuthKey(section, env2 = process.env) {
26810
+ if (section?.auth_key_file) {
26811
+ try {
26812
+ const key2 = (0, import_node_fs24.readFileSync)(section.auth_key_file, "utf-8").trim();
26813
+ if (key2) return key2;
26814
+ } catch {
26815
+ }
26816
+ }
26817
+ const key = (section?.auth_key ?? env2.ABUSECH_AUTH_KEY ?? "").trim();
26818
+ return key || void 0;
26819
+ }
25868
26820
  function egressRuleset(ips) {
25869
26821
  const v4 = ips.filter((ip) => (0, import_node_net10.isIP)(ip) === 4);
25870
26822
  const v6 = ips.filter((ip) => (0, import_node_net10.isIP)(ip) === 6);
@@ -25973,7 +26925,7 @@ var ThreatFeeds = class {
25973
26925
  }
25974
26926
  async refresh() {
25975
26927
  try {
25976
- const set = await fetchFeeds(this.opts.settings, this.opts.fetchImpl);
26928
+ const set = await fetchFeeds(this.opts.settings, this.opts.fetchImpl, this.opts.retryDelayMs);
25977
26929
  const failed = set.sources.filter((s) => !s.ok);
25978
26930
  if (failed.length === set.sources.length) {
25979
26931
  this.opts.log(`[threat-feeds] refresh failed, keeping previous list: ${failed.map((s) => `${s.feed}: ${s.error}`).join("; ")}`);
@@ -26001,7 +26953,9 @@ var ThreatFeeds = class {
26001
26953
  this.blocking = ok;
26002
26954
  mode = ok ? "blocking egress" : "detecting (nft load failed)";
26003
26955
  }
26004
- const detail = `${ips.length} IPs, ${domains} domains, ${mode}${this.writeResolverFiles(set)}`;
26956
+ const failed = (set.sources ?? []).filter((s) => !s.ok).map((s) => s.feed);
26957
+ const failing = failed.length ? `; ${failed.length}/${set.sources.length} feeds failing (${failed.join(", ")}), see \`threatcrush feeds\`` : "";
26958
+ const detail = `${ips.length} IPs, ${domains} domains, ${mode}${this.writeResolverFiles(set)}${failing}`;
26005
26959
  this.opts.log(`[threat-feeds] ${from === "cache" ? "loaded cached" : "refreshed"} list: ${detail} (${set.skipped_shared} shared/protected entries skipped)`);
26006
26960
  this.opts.bus.announceModule("threat-feeds", "running", detail);
26007
26961
  }
@@ -26946,9 +27900,247 @@ var CommandHistoryWatcher = class {
26946
27900
 
26947
27901
  // src/daemon/workers/file-integrity.ts
26948
27902
  var import_node_fs27 = require("fs");
26949
- var import_promises3 = require("fs/promises");
27903
+ var import_promises4 = require("fs/promises");
26950
27904
  var import_node_crypto8 = require("crypto");
27905
+ var import_node_path23 = require("path");
27906
+
27907
+ // src/daemon/workers/writer-containment.ts
27908
+ var import_promises3 = require("fs/promises");
26951
27909
  var import_node_path22 = require("path");
27910
+ var realWriterProcFs = {
27911
+ async pids() {
27912
+ try {
27913
+ return (await (0, import_promises3.readdir)("/proc")).filter((name) => /^\d+$/.test(name)).map(Number);
27914
+ } catch {
27915
+ return [];
27916
+ }
27917
+ },
27918
+ async stat(pid) {
27919
+ try {
27920
+ return await (0, import_promises3.readFile)(`/proc/${pid}/stat`, "utf8");
27921
+ } catch {
27922
+ return null;
27923
+ }
27924
+ },
27925
+ async exe(pid) {
27926
+ try {
27927
+ return await (0, import_promises3.readlink)(`/proc/${pid}/exe`);
27928
+ } catch {
27929
+ return null;
27930
+ }
27931
+ },
27932
+ async fds(pid) {
27933
+ try {
27934
+ return await (0, import_promises3.readdir)(`/proc/${pid}/fd`);
27935
+ } catch {
27936
+ return null;
27937
+ }
27938
+ },
27939
+ async fdTarget(pid, fd) {
27940
+ try {
27941
+ return await (0, import_promises3.readlink)(`/proc/${pid}/fd/${fd}`);
27942
+ } catch {
27943
+ return null;
27944
+ }
27945
+ },
27946
+ async fdFlags(pid, fd) {
27947
+ try {
27948
+ const match = /^flags:\s*([0-7]+)$/m.exec(await (0, import_promises3.readFile)(`/proc/${pid}/fdinfo/${fd}`, "utf8"));
27949
+ return match ? Number.parseInt(match[1], 8) : null;
27950
+ } catch {
27951
+ return null;
27952
+ }
27953
+ },
27954
+ kill(pid, signal) {
27955
+ process.kill(pid, signal);
27956
+ }
27957
+ };
27958
+ var CONTAIN_DEFAULT_MAX_PROCESSES = 3;
27959
+ var MAX_PIDS = 8192;
27960
+ var MAX_FDS_PER_PROCESS = 4096;
27961
+ var MAX_MATCH_FILES = 1e3;
27962
+ var MAX_MATCH_DIRECTORIES = 64;
27963
+ var MAX_REPORTED_FILES = 10;
27964
+ var DEFAULT_BUDGET_MS = 1500;
27965
+ var O_ACCMODE = 3;
27966
+ function containWriterSettings(section) {
27967
+ const raw = section?.contain_writer;
27968
+ const mode = raw === "stop" || raw === "kill" ? raw : "off";
27969
+ const max = section?.contain_max_processes;
27970
+ const maxProcesses = typeof max === "number" && Number.isFinite(max) ? Math.max(1, Math.min(20, Math.floor(max))) : CONTAIN_DEFAULT_MAX_PROCESSES;
27971
+ const neverContain = Array.isArray(section?.never_contain) ? section.never_contain.filter((value) => typeof value === "string" && value.startsWith("/")) : [];
27972
+ return { mode, maxProcesses, neverContain };
27973
+ }
27974
+ function parseStat(text) {
27975
+ const open2 = text.indexOf("(");
27976
+ const close = text.lastIndexOf(")");
27977
+ if (open2 < 0 || close < open2) return null;
27978
+ const pid = Number(text.slice(0, open2).trim());
27979
+ const rest = text.slice(close + 2).split(" ");
27980
+ const ppid = Number(rest[1]);
27981
+ const starttime = Number(rest[19]);
27982
+ if (!Number.isInteger(pid) || !Number.isInteger(ppid)) return null;
27983
+ return { pid, ppid, comm: text.slice(open2 + 1, close), starttime: Number.isFinite(starttime) ? starttime : 0 };
27984
+ }
27985
+ var stripDeleted = (path) => path.replace(/ \(deleted\)$/, "");
27986
+ var WriterContainment = class {
27987
+ constructor(opts) {
27988
+ this.opts = opts;
27989
+ this.fs = opts.procfs ?? realWriterProcFs;
27990
+ this.selfPid = opts.selfPid ?? process.pid;
27991
+ this.parentPid = opts.parentPid ?? process.ppid;
27992
+ this.nowMs = opts.nowMs ?? Date.now;
27993
+ }
27994
+ opts;
27995
+ fs;
27996
+ selfPid;
27997
+ parentPid;
27998
+ nowMs;
27999
+ get enabled() {
28000
+ return this.opts.settings.mode !== "off" && (this.opts.platform ?? process.platform) === "linux";
28001
+ }
28002
+ /** A process that must never be signalled, whatever it wrote. */
28003
+ isProtected(info, exe) {
28004
+ if (info.pid <= 2 || info.ppid === 2) return true;
28005
+ if (info.pid === this.selfPid || info.pid === this.parentPid) return true;
28006
+ const path = stripDeleted(exe);
28007
+ const names = [info.comm, (0, import_node_path22.basename)(path)];
28008
+ if (names.some((name) => name === "sshd" || name.startsWith("sshd-") || name.startsWith("systemd"))) return true;
28009
+ return this.opts.settings.neverContain.some((entry) => entry.endsWith("/") ? path.startsWith(entry) : path === entry);
28010
+ }
28011
+ /**
28012
+ * Find who holds `files` (or files under their directories) open for writing,
28013
+ * and signal them when attribution is unambiguous.
28014
+ */
28015
+ async contain(files, extraDirectories = []) {
28016
+ const { mode, maxProcesses } = this.opts.settings;
28017
+ const report = { mode, action: "no-writer", processes: [], protected_writers: [], incomplete: false };
28018
+ if (!this.enabled) {
28019
+ report.action = "alert-only";
28020
+ report.reason = mode === "off" ? "contain_writer is off" : "writer containment needs Linux /proc";
28021
+ return report;
28022
+ }
28023
+ const exact = new Set(files.slice(0, MAX_MATCH_FILES));
28024
+ const directories = [.../* @__PURE__ */ new Set([...files.map((file) => (0, import_node_path22.dirname)(file)), ...extraDirectories])].filter((dir) => dir !== "/").slice(0, MAX_MATCH_DIRECTORIES).map((dir) => dir.endsWith("/") ? dir : `${dir}/`);
28025
+ if (files.length > MAX_MATCH_FILES) report.incomplete = true;
28026
+ const deadline = this.nowMs() + (this.opts.budgetMs ?? DEFAULT_BUDGET_MS);
28027
+ const exactHits = /* @__PURE__ */ new Map();
28028
+ const dirHits = /* @__PURE__ */ new Map();
28029
+ let pids = await this.fs.pids();
28030
+ if (pids.length > MAX_PIDS) {
28031
+ report.incomplete = true;
28032
+ pids = pids.slice(0, MAX_PIDS);
28033
+ }
28034
+ for (const pid of pids) {
28035
+ if (this.nowMs() > deadline) {
28036
+ report.incomplete = true;
28037
+ break;
28038
+ }
28039
+ const fds = await this.fs.fds(pid);
28040
+ if (!fds || fds.length === 0) continue;
28041
+ let exactFiles = [];
28042
+ let dirFiles = [];
28043
+ for (const fd of fds.slice(0, MAX_FDS_PER_PROCESS)) {
28044
+ const raw = await this.fs.fdTarget(pid, fd);
28045
+ if (!raw || !raw.startsWith("/")) continue;
28046
+ const target = stripDeleted(raw);
28047
+ const isExact = exact.has(target);
28048
+ const inDir = !isExact && directories.some((dir) => target.startsWith(dir));
28049
+ if (!isExact && !inDir) continue;
28050
+ const flags = await this.fs.fdFlags(pid, fd);
28051
+ if (flags === null || (flags & O_ACCMODE) === 0) continue;
28052
+ if (isExact) exactFiles.push(target);
28053
+ else dirFiles.push(target);
28054
+ }
28055
+ if (fds.length > MAX_FDS_PER_PROCESS) report.incomplete = true;
28056
+ if (exactFiles.length === 0 && dirFiles.length === 0) continue;
28057
+ const statText = await this.fs.stat(pid);
28058
+ const info = statText ? parseStat(statText) : null;
28059
+ if (!info) continue;
28060
+ const exe = await this.fs.exe(pid) ?? "";
28061
+ exactFiles = [...new Set(exactFiles)];
28062
+ dirFiles = [...new Set(dirFiles)];
28063
+ if (!exe || this.isProtected(info, exe)) {
28064
+ report.protected_writers.push({ pid, comm: info.comm, exe: exe || "[kernel]" });
28065
+ continue;
28066
+ }
28067
+ if (exactFiles.length) exactHits.set(pid, { info, exe, files: [...exactFiles, ...dirFiles] });
28068
+ else dirHits.set(pid, { info, exe, files: dirFiles });
28069
+ }
28070
+ const chosen = exactHits.size ? exactHits : dirHits;
28071
+ report.match = exactHits.size ? "exact" : dirHits.size ? "directory" : void 0;
28072
+ report.processes = [...chosen.values()].map(({ info, exe, files: held }) => ({
28073
+ pid: info.pid,
28074
+ comm: info.comm,
28075
+ exe: stripDeleted(exe),
28076
+ files: held.slice(0, MAX_REPORTED_FILES)
28077
+ }));
28078
+ if (report.processes.length === 0) {
28079
+ report.action = "no-writer";
28080
+ report.reason = report.incomplete ? "no writer found before the /proc walk limit; it may have closed its files" : "no process holds the changed files open for writing; it may have closed them";
28081
+ if (!report.match) delete report.match;
28082
+ return report;
28083
+ }
28084
+ if (report.incomplete) {
28085
+ report.action = "alert-only";
28086
+ report.reason = "the /proc walk hit a limit, so attribution may be incomplete";
28087
+ return report;
28088
+ }
28089
+ if (report.processes.length > maxProcesses) {
28090
+ report.action = "alert-only";
28091
+ report.reason = `${report.processes.length} candidate writers exceeds contain_max_processes (${maxProcesses})`;
28092
+ return report;
28093
+ }
28094
+ const signal = mode === "kill" ? "SIGKILL" : "SIGSTOP";
28095
+ const dryRun = this.opts.dryRun?.() === true;
28096
+ let sent = 0;
28097
+ for (const proc of report.processes) {
28098
+ proc.signal = signal;
28099
+ const before = chosen.get(proc.pid).info;
28100
+ const fresh = await this.fs.stat(proc.pid);
28101
+ const now = fresh ? parseStat(fresh) : null;
28102
+ if (!now || now.starttime !== before.starttime) {
28103
+ proc.result = "gone";
28104
+ continue;
28105
+ }
28106
+ if (dryRun) {
28107
+ proc.result = "dry-run";
28108
+ continue;
28109
+ }
28110
+ try {
28111
+ this.fs.kill(proc.pid, signal);
28112
+ proc.result = "sent";
28113
+ sent++;
28114
+ } catch (error) {
28115
+ proc.result = "failed";
28116
+ proc.error = error.message.split("\n")[0].slice(0, 200);
28117
+ }
28118
+ }
28119
+ report.action = dryRun ? "dry-run" : sent === report.processes.length ? "contained" : sent > 0 ? "partial" : "alert-only";
28120
+ if (report.action === "alert-only") report.reason = "signal not delivered";
28121
+ for (const proc of report.processes) {
28122
+ this.opts.log(`[file-integrity] contain_writer=${mode}: ${proc.result} ${signal} to pid ${proc.pid} (${proc.exe}) writing ${proc.files.slice(0, 3).join(", ")}${proc.error ? `: ${proc.error}` : ""}${signal === "SIGSTOP" && proc.result === "sent" ? `; resume with kill -CONT ${proc.pid} or end with kill -KILL ${proc.pid}` : ""}`);
28123
+ }
28124
+ return report;
28125
+ }
28126
+ };
28127
+ function summarizeContainment(report) {
28128
+ const procs = report.processes.map((p) => `pid ${p.pid} (${(0, import_node_path22.basename)(p.exe) || p.comm})`).join(", ");
28129
+ switch (report.action) {
28130
+ case "contained":
28131
+ return `writer ${procs} ${report.mode === "kill" ? "killed (SIGKILL)" : "stopped (SIGSTOP)"}`;
28132
+ case "partial":
28133
+ return `writer containment partial: ${report.processes.map((p) => `pid ${p.pid} ${p.result}`).join(", ")}`;
28134
+ case "dry-run":
28135
+ return `dry_run: would ${report.mode === "kill" ? "SIGKILL" : "SIGSTOP"} ${procs}`;
28136
+ case "alert-only":
28137
+ return procs ? `writer ${procs} not contained: ${report.reason}` : `writer not contained: ${report.reason}`;
28138
+ case "no-writer":
28139
+ return "writer not identified";
28140
+ }
28141
+ }
28142
+
28143
+ // src/daemon/workers/file-integrity.ts
26952
28144
  var DEFAULT_POLL_MS = 15 * 6e4;
26953
28145
  var MAX_FILES = 5e4;
26954
28146
  var MAX_FILE_BYTES = 64 * 1024 * 1024;
@@ -26963,8 +28155,8 @@ var READ_CHUNK_BYTES = 64 * 1024;
26963
28155
  var CANARY_CONTENT = "ThreatCrush file integrity canary v1\n";
26964
28156
  function fileIntegritySettings(section) {
26965
28157
  const safePath = (value) => {
26966
- if (typeof value !== "string" || !(0, import_node_path22.isAbsolute)(value) || value.split(import_node_path22.sep).includes("..")) return null;
26967
- const path = (0, import_node_path22.normalize)(value);
28158
+ if (typeof value !== "string" || !(0, import_node_path23.isAbsolute)(value) || value.split(import_node_path23.sep).includes("..")) return null;
28159
+ const path = (0, import_node_path23.normalize)(value);
26968
28160
  return path === "/" ? null : path;
26969
28161
  };
26970
28162
  const strings = (values) => Array.isArray(values) ? [...new Set(values.map(safePath).filter((path) => path !== null))] : [];
@@ -26977,7 +28169,8 @@ function fileIntegritySettings(section) {
26977
28169
  paths: strings(section?.paths),
26978
28170
  canaries: strings(section?.canaries),
26979
28171
  canaryDirectories: strings(section?.canary_directories),
26980
- pollMs
28172
+ pollMs,
28173
+ containment: containWriterSettings(section)
26981
28174
  };
26982
28175
  }
26983
28176
  function signature(value) {
@@ -26985,7 +28178,7 @@ function signature(value) {
26985
28178
  }
26986
28179
  async function readState(path) {
26987
28180
  try {
26988
- const parsed = JSON.parse(await (0, import_promises3.readFile)(path, "utf8"));
28181
+ const parsed = JSON.parse(await (0, import_promises4.readFile)(path, "utf8"));
26989
28182
  if (parsed.schema !== 1 || !Array.isArray(parsed.targets) || !parsed.files || typeof parsed.files !== "object") return null;
26990
28183
  return parsed;
26991
28184
  } catch {
@@ -26993,10 +28186,10 @@ async function readState(path) {
26993
28186
  }
26994
28187
  }
26995
28188
  async function writeState(path, state) {
26996
- await (0, import_promises3.mkdir)((0, import_node_path22.dirname)(path), { recursive: true, mode: 448 });
28189
+ await (0, import_promises4.mkdir)((0, import_node_path23.dirname)(path), { recursive: true, mode: 448 });
26997
28190
  const temp = `${path}.${process.pid}.${(0, import_node_crypto8.randomUUID)()}.tmp`;
26998
- await (0, import_promises3.writeFile)(temp, JSON.stringify(state), { mode: 384 });
26999
- await (0, import_promises3.rename)(temp, path);
28191
+ await (0, import_promises4.writeFile)(temp, JSON.stringify(state), { mode: 384 });
28192
+ await (0, import_promises4.rename)(temp, path);
27000
28193
  }
27001
28194
  async function hashFile(path, handle, size) {
27002
28195
  const hash = (0, import_node_crypto8.createHash)("sha256");
@@ -27019,19 +28212,19 @@ async function hashFile(path, handle, size) {
27019
28212
  }
27020
28213
  return { sha256: hash.digest("hex"), entropy };
27021
28214
  }
27022
- var OPEN_FILE_FLAGS = import_promises3.constants.O_RDONLY | import_promises3.constants.O_NONBLOCK | (import_promises3.constants.O_NOFOLLOW ?? 0);
27023
- var OPEN_DIR_FLAGS = OPEN_FILE_FLAGS | import_promises3.constants.O_DIRECTORY;
27024
- var CREATE_FILE_FLAGS = import_promises3.constants.O_WRONLY | import_promises3.constants.O_CREAT | import_promises3.constants.O_EXCL | import_promises3.constants.O_NOFOLLOW;
28215
+ var OPEN_FILE_FLAGS = import_promises4.constants.O_RDONLY | import_promises4.constants.O_NONBLOCK | (import_promises4.constants.O_NOFOLLOW ?? 0);
28216
+ var OPEN_DIR_FLAGS = OPEN_FILE_FLAGS | import_promises4.constants.O_DIRECTORY;
28217
+ var CREATE_FILE_FLAGS = import_promises4.constants.O_WRONLY | import_promises4.constants.O_CREAT | import_promises4.constants.O_EXCL | import_promises4.constants.O_NOFOLLOW;
27025
28218
  function autoCanaryPath(directory) {
27026
- return (0, import_node_path22.join)(directory, ".threatcrush-canary");
28219
+ return (0, import_node_path23.join)(directory, ".threatcrush-canary");
27027
28220
  }
27028
28221
  async function openAbsoluteDirectory(path) {
27029
- const parts = path.split(import_node_path22.sep).filter((part) => part && part !== ".");
28222
+ const parts = path.split(import_node_path23.sep).filter((part) => part && part !== ".");
27030
28223
  if (parts.includes("..")) throw new Error("invalid canary directory");
27031
- let directory = await (0, import_promises3.open)("/", OPEN_DIR_FLAGS);
28224
+ let directory = await (0, import_promises4.open)("/", OPEN_DIR_FLAGS);
27032
28225
  try {
27033
28226
  for (const part of parts) {
27034
- const next = await (0, import_promises3.open)(`/proc/self/fd/${directory.fd}/${part}`, OPEN_DIR_FLAGS);
28227
+ const next = await (0, import_promises4.open)(`/proc/self/fd/${directory.fd}/${part}`, OPEN_DIR_FLAGS);
27035
28228
  await directory.close();
27036
28229
  directory = next;
27037
28230
  }
@@ -27049,9 +28242,9 @@ async function createAutoCanary(path) {
27049
28242
  } catch (error) {
27050
28243
  if (error.code !== "ENOENT") return false;
27051
28244
  }
27052
- const directory = await openAbsoluteDirectory((0, import_node_path22.dirname)(path));
28245
+ const directory = await openAbsoluteDirectory((0, import_node_path23.dirname)(path));
27053
28246
  try {
27054
- const file = await (0, import_promises3.open)(`/proc/self/fd/${directory.fd}/${(0, import_node_path22.basename)(path)}`, CREATE_FILE_FLAGS, 438);
28247
+ const file = await (0, import_promises4.open)(`/proc/self/fd/${directory.fd}/${(0, import_node_path23.basename)(path)}`, CREATE_FILE_FLAGS, 438);
27055
28248
  try {
27056
28249
  await file.chmod(438);
27057
28250
  await file.writeFile(CANARY_CONTENT);
@@ -27068,16 +28261,16 @@ async function createAutoCanary(path) {
27068
28261
  }
27069
28262
  }
27070
28263
  async function openAbsoluteTarget(path) {
27071
- const parts = path.split(import_node_path22.sep).filter((part) => part && part !== ".");
28264
+ const parts = path.split(import_node_path23.sep).filter((part) => part && part !== ".");
27072
28265
  if (parts.length === 0 || parts.includes("..")) throw new Error("invalid file integrity path");
27073
- let directory = await (0, import_promises3.open)("/", OPEN_DIR_FLAGS);
28266
+ let directory = await (0, import_promises4.open)("/", OPEN_DIR_FLAGS);
27074
28267
  try {
27075
28268
  for (const part of parts.slice(0, -1)) {
27076
- const next = await (0, import_promises3.open)(`/proc/self/fd/${directory.fd}/${part}`, OPEN_DIR_FLAGS);
28269
+ const next = await (0, import_promises4.open)(`/proc/self/fd/${directory.fd}/${part}`, OPEN_DIR_FLAGS);
27077
28270
  await directory.close();
27078
28271
  directory = next;
27079
28272
  }
27080
- const target = await (0, import_promises3.open)(`/proc/self/fd/${directory.fd}/${parts.at(-1)}`, OPEN_FILE_FLAGS);
28273
+ const target = await (0, import_promises4.open)(`/proc/self/fd/${directory.fd}/${parts.at(-1)}`, OPEN_FILE_FLAGS);
27081
28274
  await directory.close();
27082
28275
  return target;
27083
28276
  } catch (error) {
@@ -27103,7 +28296,7 @@ async function scanTargets(targets, canaries) {
27103
28296
  }
27104
28297
  let handle;
27105
28298
  try {
27106
- handle = parent ? await (0, import_promises3.open)(`/proc/self/fd/${parent.fd}/${path.slice(path.lastIndexOf(import_node_path22.sep) + 1)}`, OPEN_FILE_FLAGS) : await openAbsoluteTarget(path);
28299
+ handle = parent ? await (0, import_promises4.open)(`/proc/self/fd/${parent.fd}/${path.slice(path.lastIndexOf(import_node_path23.sep) + 1)}`, OPEN_FILE_FLAGS) : await openAbsoluteTarget(path);
27107
28300
  const stat = await handle.stat();
27108
28301
  if (stat.isDirectory()) {
27109
28302
  directories.push(path);
@@ -27114,14 +28307,14 @@ async function scanTargets(targets, canaries) {
27114
28307
  }
27115
28308
  let entries2;
27116
28309
  try {
27117
- entries2 = await (0, import_promises3.readdir)(`/proc/self/fd/${handle.fd}`, { withFileTypes: true });
28310
+ entries2 = await (0, import_promises4.readdir)(`/proc/self/fd/${handle.fd}`, { withFileTypes: true });
27118
28311
  } catch {
27119
28312
  complete = false;
27120
28313
  errors.add(path);
27121
28314
  return;
27122
28315
  }
27123
28316
  for (const entry of entries2) {
27124
- await walk((0, import_node_path22.join)(path, entry.name), handle);
28317
+ await walk((0, import_node_path23.join)(path, entry.name), handle);
27125
28318
  if (!complete) return;
27126
28319
  }
27127
28320
  return;
@@ -27194,6 +28387,12 @@ var FileIntegrityWatch = class {
27194
28387
  constructor(opts) {
27195
28388
  this.opts = opts;
27196
28389
  this.now = opts.now ?? (() => /* @__PURE__ */ new Date());
28390
+ this.containment = new WriterContainment({
28391
+ settings: opts.settings.containment ?? containWriterSettings(void 0),
28392
+ log: opts.log,
28393
+ dryRun: opts.dryRun,
28394
+ procfs: opts.procfs
28395
+ });
27197
28396
  this.canaries = /* @__PURE__ */ new Set([
27198
28397
  ...opts.settings.canaries,
27199
28398
  ...opts.settings.canaryDirectories.map(autoCanaryPath)
@@ -27209,6 +28408,7 @@ var FileIntegrityWatch = class {
27209
28408
  eventFirstAt = 0;
27210
28409
  eventScanPending = false;
27211
28410
  watcherLimitLogged = false;
28411
+ containment;
27212
28412
  get autoCanaries() {
27213
28413
  return this.opts.settings.canaryDirectories.map(autoCanaryPath);
27214
28414
  }
@@ -27233,6 +28433,9 @@ var FileIntegrityWatch = class {
27233
28433
  return;
27234
28434
  }
27235
28435
  this.opts.log(`[file-integrity] monitoring ${targets.length} configured path(s), polling every ${Math.round(this.opts.settings.pollMs / 6e4)}m; content is hashed locally`);
28436
+ if (this.containment.enabled) {
28437
+ this.opts.log(`[file-integrity] contain_writer=${this.opts.settings.containment.mode}: canary writes and mass changes ${this.opts.settings.containment.mode === "kill" ? "SIGKILL" : "SIGSTOP"} an unambiguous writer`);
28438
+ }
27236
28439
  void this.scanOnce();
27237
28440
  this.timer = setInterval(() => {
27238
28441
  void this.scanOnce();
@@ -27315,7 +28518,7 @@ var FileIntegrityWatch = class {
27315
28518
  let baselineFilePresent = false;
27316
28519
  if (!baseline) {
27317
28520
  try {
27318
- await (0, import_promises3.lstat)(this.opts.baselinePath);
28521
+ await (0, import_promises4.lstat)(this.opts.baselinePath);
27319
28522
  baselineFilePresent = true;
27320
28523
  } catch (error) {
27321
28524
  baselineFilePresent = error.code !== "ENOENT";
@@ -27331,7 +28534,7 @@ var FileIntegrityWatch = class {
27331
28534
  if (current.complete) {
27332
28535
  const directories = new Set(current.directories);
27333
28536
  for (const path of Object.keys(current.files)) {
27334
- if (!directories.has(path)) directories.add((0, import_node_path22.dirname)(path));
28537
+ if (!directories.has(path)) directories.add((0, import_node_path23.dirname)(path));
27335
28538
  }
27336
28539
  this.refreshWatchers([...directories]);
27337
28540
  }
@@ -27367,7 +28570,8 @@ var FileIntegrityWatch = class {
27367
28570
  if (!sameTargets(baseline.targets, targets)) {
27368
28571
  const removedCanaries = changedPaths(observed.files, current.files).filter((change) => this.canaries.has(change.path) && observed.targets.includes(change.path));
27369
28572
  if (removedCanaries.length) {
27370
- this.emit("critical", "A file integrity canary changed or disappeared", "file-integrity-canary", removedCanaries);
28573
+ const containment2 = await this.containWriters(removedCanaries.map((change) => change.path));
28574
+ this.emit("critical", "A file integrity canary changed or disappeared", "file-integrity-canary", removedCanaries, containment2);
27371
28575
  }
27372
28576
  if (!sameTargets(observed.targets, targets)) {
27373
28577
  this.emit(
@@ -27382,17 +28586,19 @@ var FileIntegrityWatch = class {
27382
28586
  }
27383
28587
  const changes = changedPaths(observed.files, current.files);
27384
28588
  const canaryChanges = changes.filter((change) => this.canaries.has(change.path));
27385
- if (canaryChanges.length) {
27386
- this.emit("critical", "A file integrity canary changed or disappeared", "file-integrity-canary", canaryChanges);
27387
- }
27388
28589
  const ordinary = changes.filter((change) => !this.canaries.has(change.path));
27389
28590
  const paths = ordinary.map((change) => change.path);
27390
28591
  const beforeEntropy = meanEntropy(paths, observed.files);
27391
28592
  const afterEntropy = meanEntropy(paths, current.files);
27392
28593
  const entropyRose = beforeEntropy !== null && afterEntropy !== null && afterEntropy - beforeEntropy >= MASS_CHANGE_ENTROPY_RISE_BITS;
27393
- if (ordinary.length >= MASS_CHANGE_COUNT || ordinary.length >= 10 && entropyRose) {
28594
+ const massChange = ordinary.length >= MASS_CHANGE_COUNT || ordinary.length >= 10 && entropyRose;
28595
+ const containment = canaryChanges.length || massChange ? await this.containWriters([...canaryChanges.map((change) => change.path), ...massChange ? paths : []]) : void 0;
28596
+ if (canaryChanges.length) {
28597
+ this.emit("critical", "A file integrity canary changed or disappeared", "file-integrity-canary", canaryChanges, containment);
28598
+ }
28599
+ if (massChange) {
27394
28600
  const entropyDetail = entropyRose ? `; mean changed-file entropy rose from ${beforeEntropy?.toFixed(2)} to ${afterEntropy?.toFixed(2)} bits` : "";
27395
- this.emit("critical", `${ordinary.length} monitored files changed in one scan${entropyDetail}`, "file-integrity-mass-change", ordinary);
28601
+ this.emit("critical", `${ordinary.length} monitored files changed in one scan${entropyDetail}`, "file-integrity-mass-change", ordinary, containment);
27396
28602
  } else {
27397
28603
  for (const change of ordinary) {
27398
28604
  const expected = baseline.files[change.path] ?? "missing";
@@ -27414,13 +28620,25 @@ var FileIntegrityWatch = class {
27414
28620
  if (this.eventScanPending && !this.eventTimer) this.scheduleEventScan();
27415
28621
  }
27416
28622
  }
27417
- emit(severity, message, ruleId, changes) {
28623
+ /** Opt-in: find and stop (or kill) the writer. Undefined when contain_writer is off. */
28624
+ async containWriters(paths) {
28625
+ if (!this.containment.enabled) return void 0;
28626
+ try {
28627
+ return await this.containment.contain(paths);
28628
+ } catch (error) {
28629
+ this.opts.log(`[file-integrity] writer containment failed: ${error.message.split("\n")[0]}`);
28630
+ return void 0;
28631
+ }
28632
+ }
28633
+ emit(severity, message, ruleId, changes, containment) {
28634
+ const fullMessage = containment ? `${message}; ${summarizeContainment(containment)}` : message;
28635
+ if (containment) this.opts.log(`[file-integrity] ${fullMessage}`);
27418
28636
  const event = {
27419
28637
  timestamp: this.now(),
27420
28638
  module: "file-integrity",
27421
28639
  category: "system",
27422
28640
  severity,
27423
- message: message.replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 500),
28641
+ message: fullMessage.replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 500),
27424
28642
  details: {
27425
28643
  rule_id: ruleId,
27426
28644
  change_count: changes.length,
@@ -27428,7 +28646,8 @@ var FileIntegrityWatch = class {
27428
28646
  path,
27429
28647
  state: state === "missing" ? "missing" : "present"
27430
28648
  })),
27431
- truncated: changes.length > MAX_CHANGES_PER_EVENT
28649
+ truncated: changes.length > MAX_CHANGES_PER_EVENT,
28650
+ ...containment ? { containment } : {}
27432
28651
  }
27433
28652
  };
27434
28653
  try {
@@ -27440,9 +28659,308 @@ var FileIntegrityWatch = class {
27440
28659
  };
27441
28660
 
27442
28661
  // src/daemon/workers/edr.ts
27443
- var import_node_fs28 = require("fs");
27444
- var import_node_path23 = require("path");
28662
+ var import_node_fs29 = require("fs");
28663
+ var import_node_path25 = require("path");
28664
+ var import_node_child_process10 = require("child_process");
28665
+
28666
+ // src/daemon/workers/edr-ebpf.ts
27445
28667
  var import_node_child_process9 = require("child_process");
28668
+ var import_node_fs28 = require("fs");
28669
+ var import_node_path24 = require("path");
28670
+ var BPFTRACE_RECORD_TAG = "TC1";
28671
+ var BTF_VMLINUX_PATH = "/sys/kernel/btf/vmlinux";
28672
+ var TCP_SYN_SENT = 2;
28673
+ var TCP_LISTEN = 10;
28674
+ var IPPROTO_TCP = 6;
28675
+ function bpftraceScript(opts) {
28676
+ const prefix = `"${BPFTRACE_RECORD_TAG}\\t%s\\t%d\\t%d\\t%d\\t%s\\n"`;
28677
+ const lines = [
28678
+ "tracepoint:sched:sched_process_exec",
28679
+ "{",
28680
+ ` printf(${prefix}, "exec", pid, curtask->real_parent->tgid, curtask->cred->euid.val, str(args.filename));`,
28681
+ "}"
28682
+ ];
28683
+ if (opts.network) {
28684
+ lines.push(
28685
+ "tracepoint:sock:inet_sock_set_state",
28686
+ `/args.protocol == ${IPPROTO_TCP} && args.newstate == ${TCP_SYN_SENT}/`,
28687
+ "{",
28688
+ ` printf(${prefix}, "connect", pid, curtask->real_parent->tgid, curtask->cred->euid.val, comm);`,
28689
+ "}",
28690
+ "tracepoint:sock:inet_sock_set_state",
28691
+ `/args.protocol == ${IPPROTO_TCP} && args.newstate == ${TCP_LISTEN}/`,
28692
+ "{",
28693
+ ` printf(${prefix}, "listen", pid, curtask->real_parent->tgid, curtask->cred->euid.val, comm);`,
28694
+ "}"
28695
+ );
28696
+ }
28697
+ return `${lines.join("\n")}
28698
+ `;
28699
+ }
28700
+ function bpftraceArgs(opts) {
28701
+ return ["-q", "-B", "line", "-f", "json", "-e", bpftraceScript(opts)];
28702
+ }
28703
+ var MAX_FIELD = 4096;
28704
+ function parseRecordText(text) {
28705
+ const body = text.endsWith("\n") ? text.slice(0, -1) : text;
28706
+ const parts = [];
28707
+ let rest = body;
28708
+ for (let i = 0; i < 5; i++) {
28709
+ const at = rest.indexOf(" ");
28710
+ if (at < 0) return null;
28711
+ parts.push(rest.slice(0, at));
28712
+ rest = rest.slice(at + 1);
28713
+ }
28714
+ const [tag, kind, pidText, ppidText, euidText] = parts;
28715
+ if (tag !== BPFTRACE_RECORD_TAG) return null;
28716
+ if (kind !== "exec" && kind !== "connect" && kind !== "listen") return null;
28717
+ const pid = Number(pidText);
28718
+ const ppid = Number(ppidText);
28719
+ const euid = Number(euidText);
28720
+ if (!/^\d+$/.test(pidText) || !/^\d+$/.test(ppidText) || !/^\d+$/.test(euidText)) return null;
28721
+ if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isSafeInteger(ppid) || !Number.isSafeInteger(euid)) return null;
28722
+ const value = rest.slice(0, MAX_FIELD);
28723
+ if (!value) return null;
28724
+ if (kind === "exec") {
28725
+ const base = value.slice(value.lastIndexOf("/") + 1).slice(0, 15);
28726
+ return { kind, pid, ppid, euid, filename: value, comm: base || value.slice(0, 15) };
28727
+ }
28728
+ return { kind, pid, ppid, euid, comm: value.slice(0, 64) };
28729
+ }
28730
+ function parseBpftraceLine(line) {
28731
+ const trimmed = line.replace(/\r$/, "");
28732
+ if (!trimmed) return null;
28733
+ if (trimmed.startsWith("{")) {
28734
+ let parsed;
28735
+ try {
28736
+ parsed = JSON.parse(trimmed);
28737
+ } catch {
28738
+ return null;
28739
+ }
28740
+ if (!parsed || typeof parsed !== "object") return null;
28741
+ const { type, data } = parsed;
28742
+ if (type === "printf" && typeof data === "string") {
28743
+ const event2 = parseRecordText(data);
28744
+ return event2 ? { type: "event", event: event2 } : null;
28745
+ }
28746
+ if (type === "attached_probes") {
28747
+ const probes = Number(data?.probes);
28748
+ return { type: "attached", probes: Number.isFinite(probes) ? probes : 0 };
28749
+ }
28750
+ if (type === "lost_events") {
28751
+ const count = Number(data?.events);
28752
+ return { type: "lost", count: Number.isFinite(count) ? count : 0 };
28753
+ }
28754
+ if (type === "error" || type === "warning") {
28755
+ return { type: "error", message: typeof data === "string" ? data.slice(0, 400) : JSON.stringify(data).slice(0, 400) };
28756
+ }
28757
+ return null;
28758
+ }
28759
+ const event = parseRecordText(trimmed);
28760
+ return event ? { type: "event", event } : null;
28761
+ }
28762
+ function selectEdrSource(probe) {
28763
+ if (probe.configured === "auditd") return { source: "auditd", degraded: false, reason: 'source = "auditd" configured' };
28764
+ const missing = [];
28765
+ if ((probe.platform ?? "linux") !== "linux") missing.push("not Linux");
28766
+ if (!probe.bpftracePath) missing.push("bpftrace not installed");
28767
+ if (!probe.btfPresent) missing.push(`kernel BTF (${BTF_VMLINUX_PATH}) missing`);
28768
+ if (!probe.isRoot) missing.push("daemon not running as root");
28769
+ if (missing.length === 0) {
28770
+ return { source: "ebpf", degraded: false, reason: `bpftrace at ${probe.bpftracePath} with kernel BTF, running as root` };
28771
+ }
28772
+ return {
28773
+ source: "auditd",
28774
+ degraded: probe.configured === "ebpf",
28775
+ reason: `eBPF unavailable (${missing.join("; ")}); using auditd`
28776
+ };
28777
+ }
28778
+ var BPFTRACE_DIRS = ["/usr/sbin", "/usr/bin", "/sbin", "/bin", "/usr/local/sbin", "/usr/local/bin", "/snap/bin"];
28779
+ function findBpftrace(env2 = process.env) {
28780
+ const dirs = [...BPFTRACE_DIRS, ...(env2.PATH ?? "").split(import_node_path24.delimiter).filter((dir) => dir.startsWith("/"))];
28781
+ for (const dir of new Set(dirs)) {
28782
+ const candidate = (0, import_node_path24.join)(dir, "bpftrace");
28783
+ try {
28784
+ (0, import_node_fs28.accessSync)(candidate, import_node_fs28.constants.X_OK);
28785
+ return candidate;
28786
+ } catch {
28787
+ }
28788
+ }
28789
+ return null;
28790
+ }
28791
+ function probeHost(configured) {
28792
+ return {
28793
+ configured,
28794
+ bpftracePath: configured === "auditd" ? null : findBpftrace(),
28795
+ btfPresent: (0, import_node_fs28.existsSync)(BTF_VMLINUX_PATH),
28796
+ isRoot: typeof process.getuid === "function" && process.getuid() === 0,
28797
+ platform: process.platform
28798
+ };
28799
+ }
28800
+ var STDERR_TAIL = 2048;
28801
+ var HEALTHY_AFTER_MS = 3e4;
28802
+ var KILL_GRACE_MS = 3e3;
28803
+ var BpftraceSource = class {
28804
+ constructor(opts) {
28805
+ this.opts = opts;
28806
+ this.spawnFn = opts.spawn ?? import_node_child_process9.spawn;
28807
+ this.minBackoffMs = opts.minBackoffMs ?? 1e3;
28808
+ this.maxBackoffMs = opts.maxBackoffMs ?? 6e4;
28809
+ this.maxFailedStarts = opts.maxFailedStarts ?? 3;
28810
+ this.maxLineBytes = opts.maxLineBytes ?? 64 * 1024;
28811
+ this.backoffMs = this.minBackoffMs;
28812
+ }
28813
+ opts;
28814
+ child = null;
28815
+ restartTimer = null;
28816
+ healthyTimer = null;
28817
+ stopped = true;
28818
+ healthy = false;
28819
+ failedStarts = 0;
28820
+ backoffMs;
28821
+ buffer = "";
28822
+ stderrTail = "";
28823
+ overflowLogged = false;
28824
+ spawnFn;
28825
+ minBackoffMs;
28826
+ maxBackoffMs;
28827
+ maxFailedStarts;
28828
+ maxLineBytes;
28829
+ get running() {
28830
+ return this.child !== null;
28831
+ }
28832
+ start() {
28833
+ if (!this.stopped) return;
28834
+ this.stopped = false;
28835
+ this.launch();
28836
+ }
28837
+ stop() {
28838
+ this.stopped = true;
28839
+ if (this.restartTimer) clearTimeout(this.restartTimer);
28840
+ if (this.healthyTimer) clearTimeout(this.healthyTimer);
28841
+ this.restartTimer = null;
28842
+ this.healthyTimer = null;
28843
+ const child = this.child;
28844
+ this.child = null;
28845
+ if (child && child.exitCode === null && child.signalCode === null) {
28846
+ try {
28847
+ child.kill("SIGTERM");
28848
+ } catch {
28849
+ }
28850
+ const killer = setTimeout(() => {
28851
+ if (child.exitCode === null && child.signalCode === null) {
28852
+ try {
28853
+ child.kill("SIGKILL");
28854
+ } catch {
28855
+ }
28856
+ }
28857
+ }, KILL_GRACE_MS);
28858
+ killer.unref?.();
28859
+ }
28860
+ this.buffer = "";
28861
+ }
28862
+ /** Feed raw stdout; exposed for tests. */
28863
+ ingest(chunk) {
28864
+ this.buffer += chunk;
28865
+ let newline = this.buffer.indexOf("\n");
28866
+ while (newline >= 0) {
28867
+ const line = this.buffer.slice(0, newline);
28868
+ this.buffer = this.buffer.slice(newline + 1);
28869
+ this.handleLine(line);
28870
+ newline = this.buffer.indexOf("\n");
28871
+ }
28872
+ if (this.buffer.length > this.maxLineBytes) {
28873
+ if (!this.overflowLogged) this.opts.log(`[edr] discarded an oversized bpftrace output line (>${this.maxLineBytes} bytes)`);
28874
+ this.overflowLogged = true;
28875
+ this.buffer = "";
28876
+ }
28877
+ }
28878
+ handleLine(line) {
28879
+ if (line.length > this.maxLineBytes) return;
28880
+ const parsed = parseBpftraceLine(line);
28881
+ if (!parsed) return;
28882
+ if (parsed.type === "event") {
28883
+ this.markHealthy();
28884
+ this.opts.onEvent(parsed.event);
28885
+ } else if (parsed.type === "attached") {
28886
+ this.markHealthy();
28887
+ this.opts.log(`[edr] bpftrace attached ${parsed.probes} probe(s)`);
28888
+ } else if (parsed.type === "lost") {
28889
+ this.opts.log(`[edr] bpftrace dropped ${parsed.count} event(s) (perf buffer full)`);
28890
+ } else if (parsed.type === "error") {
28891
+ this.opts.log(`[edr] bpftrace: ${parsed.message}`);
28892
+ }
28893
+ }
28894
+ markHealthy() {
28895
+ if (this.healthy) return;
28896
+ this.healthy = true;
28897
+ this.failedStarts = 0;
28898
+ this.backoffMs = this.minBackoffMs;
28899
+ }
28900
+ launch() {
28901
+ if (this.stopped) return;
28902
+ this.healthy = false;
28903
+ this.buffer = "";
28904
+ this.stderrTail = "";
28905
+ let child;
28906
+ try {
28907
+ child = this.spawnFn(this.opts.bpftracePath, bpftraceArgs({ network: this.opts.network }), {
28908
+ stdio: ["ignore", "pipe", "pipe"],
28909
+ shell: false,
28910
+ env: { PATH: "/usr/sbin:/usr/bin:/sbin:/bin", LANG: "C" }
28911
+ });
28912
+ } catch (error) {
28913
+ this.onExit(null, null, error.message);
28914
+ return;
28915
+ }
28916
+ this.child = child;
28917
+ child.stdout?.setEncoding("utf8");
28918
+ child.stderr?.setEncoding("utf8");
28919
+ child.stdout?.on("data", (chunk) => {
28920
+ if (this.child === child) this.ingest(chunk);
28921
+ });
28922
+ child.stderr?.on("data", (chunk) => {
28923
+ this.stderrTail = (this.stderrTail + chunk).slice(-STDERR_TAIL);
28924
+ });
28925
+ let finished = false;
28926
+ const finish = (code, signal, error) => {
28927
+ if (finished) return;
28928
+ finished = true;
28929
+ if (this.child !== child) return;
28930
+ this.child = null;
28931
+ this.onExit(code, signal, error);
28932
+ };
28933
+ child.on("error", (error) => finish(null, null, error.message));
28934
+ child.on("exit", (code, signal) => finish(code, signal));
28935
+ if (this.healthyTimer) clearTimeout(this.healthyTimer);
28936
+ this.healthyTimer = setTimeout(() => {
28937
+ if (this.child === child) this.markHealthy();
28938
+ }, HEALTHY_AFTER_MS);
28939
+ this.healthyTimer.unref?.();
28940
+ }
28941
+ onExit(code, signal, error) {
28942
+ if (this.healthyTimer) clearTimeout(this.healthyTimer);
28943
+ this.healthyTimer = null;
28944
+ if (this.stopped) return;
28945
+ const detail = error ?? (this.stderrTail.trim().split("\n").slice(-1)[0] || `exit ${code ?? signal ?? "unknown"}`);
28946
+ if (!this.healthy) this.failedStarts++;
28947
+ if (!this.healthy && this.failedStarts >= this.maxFailedStarts) {
28948
+ this.stopped = true;
28949
+ this.opts.onFatal(`bpftrace failed to start ${this.failedStarts} time(s): ${detail.slice(0, 300)}`);
28950
+ return;
28951
+ }
28952
+ const delay = this.backoffMs;
28953
+ this.backoffMs = Math.min(this.maxBackoffMs, this.backoffMs * 2);
28954
+ this.opts.log(`[edr] bpftrace exited (${detail.slice(0, 300)}); restarting in ${Math.round(delay / 1e3)}s`);
28955
+ this.restartTimer = setTimeout(() => {
28956
+ this.restartTimer = null;
28957
+ this.launch();
28958
+ }, delay);
28959
+ this.restartTimer.unref?.();
28960
+ }
28961
+ };
28962
+
28963
+ // src/daemon/workers/edr.ts
27446
28964
  var DEFAULT_AUDIT_LOG = "/var/log/audit/audit.log";
27447
28965
  var DEFAULT_WEB_USERS = ["www-data", "nginx", "apache", "httpd", "caddy", "node"];
27448
28966
  var DEFAULT_TEMP_PATHS = ["/tmp", "/var/tmp", "/dev/shm"];
@@ -27459,8 +28977,8 @@ var SHELLS2 = /* @__PURE__ */ new Set(["sh", "bash", "dash", "zsh", "ksh", "fish
27459
28977
  var DOWNLOADERS = /* @__PURE__ */ new Set(["curl", "wget"]);
27460
28978
  var MINERS = /* @__PURE__ */ new Set(["xmrig", "minerd", "cpuminer", "cpuminer-multi", "kdevtmpfsi", "kinsing", "cryptonight"]);
27461
28979
  function safeAbsolutePath(value) {
27462
- if (typeof value !== "string" || !(0, import_node_path23.isAbsolute)(value) || value.split(import_node_path23.sep).includes("..")) return null;
27463
- const path = (0, import_node_path23.normalize)(value);
28980
+ if (typeof value !== "string" || !(0, import_node_path25.isAbsolute)(value) || value.split(import_node_path25.sep).includes("..")) return null;
28981
+ const path = (0, import_node_path25.normalize)(value);
27464
28982
  return path === "/" ? null : path;
27465
28983
  }
27466
28984
  function edrSettings(section) {
@@ -27470,8 +28988,10 @@ function edrSettings(section) {
27470
28988
  const seconds = section?.poll_interval_seconds;
27471
28989
  const pollMs = typeof seconds === "number" && Number.isFinite(seconds) ? Math.max(1, Math.min(60, Math.floor(seconds))) * 1e3 : 2e3;
27472
28990
  const baselineSeconds = section?.network_baseline_seconds;
28991
+ const source = section?.source === "auto" || section?.source === "ebpf" ? section.source : "auditd";
27473
28992
  return {
27474
28993
  enabled: section?.enabled === true,
28994
+ source,
27475
28995
  auditLogPath: configuredLog,
27476
28996
  webServiceUsers: configuredUsers,
27477
28997
  tempExecPaths: configuredPaths,
@@ -27506,7 +29026,7 @@ function parseAuditRecord(line) {
27506
29026
  serial: header[2],
27507
29027
  key: fields.key,
27508
29028
  executable,
27509
- comm: fields.comm ?? (0, import_node_path23.basename)(executable),
29029
+ comm: fields.comm ?? (0, import_node_path25.basename)(executable),
27510
29030
  euid,
27511
29031
  ...Number.isInteger(pid) && pid > 0 ? { pid } : {},
27512
29032
  ...Number.isInteger(ppid) && ppid > 0 ? { ppid } : {}
@@ -27515,10 +29035,10 @@ function parseAuditRecord(line) {
27515
29035
  function accountNames2() {
27516
29036
  let raw = "";
27517
29037
  try {
27518
- raw = (0, import_node_child_process9.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
29038
+ raw = (0, import_node_child_process10.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
27519
29039
  } catch {
27520
29040
  try {
27521
- raw = (0, import_node_fs28.readFileSync)("/etc/passwd", "utf8");
29041
+ raw = (0, import_node_fs29.readFileSync)("/etc/passwd", "utf8");
27522
29042
  } catch {
27523
29043
  return /* @__PURE__ */ new Map();
27524
29044
  }
@@ -27536,7 +29056,7 @@ function pathWithin(path, root) {
27536
29056
  }
27537
29057
  function executableInWorldWritableDirectory(executable) {
27538
29058
  try {
27539
- return ((0, import_node_fs28.statSync)((0, import_node_path23.dirname)(executable)).mode & 2) !== 0;
29059
+ return ((0, import_node_fs29.statSync)((0, import_node_path25.dirname)(executable)).mode & 2) !== 0;
27540
29060
  } catch {
27541
29061
  return false;
27542
29062
  }
@@ -27544,6 +29064,26 @@ function executableInWorldWritableDirectory(executable) {
27544
29064
  function clean(value) {
27545
29065
  return value.replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 400);
27546
29066
  }
29067
+ var EXEC_KEYS = [MINER_KEY, WEB_KEY, TEMP_KEY];
29068
+ var MAX_EBPF_EXE_CACHE = 4096;
29069
+ function ebpfEventToRecords(event, resolveExe, now = /* @__PURE__ */ new Date(), serial = "ebpf") {
29070
+ let executable = resolveExe(event.pid);
29071
+ if (!executable && event.kind === "exec" && event.filename?.startsWith("/")) executable = event.filename;
29072
+ if (!executable || !executable.startsWith("/")) return [];
29073
+ const base = {
29074
+ timestamp: now,
29075
+ source: "ebpf",
29076
+ serial,
29077
+ executable,
29078
+ comm: event.comm || (0, import_node_path25.basename)(executable),
29079
+ euid: event.euid,
29080
+ pid: event.pid,
29081
+ ...event.ppid > 0 ? { ppid: event.ppid } : {}
29082
+ };
29083
+ if (event.kind === "connect") return [{ ...base, key: CONNECT_KEY }];
29084
+ if (event.kind === "listen") return [{ ...base, key: LISTEN_KEY }];
29085
+ return EXEC_KEYS.map((key) => ({ ...base, key }));
29086
+ }
27547
29087
  var EdrWatch = class {
27548
29088
  constructor(opts) {
27549
29089
  this.opts = opts;
@@ -27554,6 +29094,10 @@ var EdrWatch = class {
27554
29094
  }
27555
29095
  opts;
27556
29096
  tail = null;
29097
+ bpftrace = null;
29098
+ ebpfSerial = 0;
29099
+ ebpfExeCache = /* @__PURE__ */ new Map();
29100
+ activeSource = "none";
27557
29101
  timer = null;
27558
29102
  cpuTimer = null;
27559
29103
  usersById;
@@ -27570,18 +29114,13 @@ var EdrWatch = class {
27570
29114
  this.opts.log("[edr] disabled; set [edr] enabled = true after installing the generated audit rules");
27571
29115
  return;
27572
29116
  }
27573
- if (!(0, import_node_fs28.existsSync)(this.opts.settings.auditLogPath)) {
27574
- this.opts.log(`[edr] audit log not found at ${this.opts.settings.auditLogPath}; auditd detections are unavailable`);
29117
+ const probe = this.probe();
29118
+ const selection = selectEdrSource(probe);
29119
+ if (selection.source === "ebpf" && probe.bpftracePath) {
29120
+ this.startEbpf(probe.bpftracePath, selection.reason);
27575
29121
  } else {
27576
- try {
27577
- (0, import_node_fs28.accessSync)(this.opts.settings.auditLogPath, import_node_fs28.constants.R_OK);
27578
- this.tail = new LogTail(this.opts.settings.auditLogPath);
27579
- this.timer = setInterval(() => this.poll(), this.opts.settings.pollMs);
27580
- this.timer.unref?.();
27581
- this.opts.log(`[edr] watching selected auditd events in ${this.opts.settings.auditLogPath}; command arguments and remote addresses are discarded`);
27582
- } catch {
27583
- this.opts.log(`[edr] cannot read ${this.opts.settings.auditLogPath}; run the daemon with permission to read the audit log`);
27584
- }
29122
+ if (selection.degraded) this.opts.log(`[edr] source = "ebpf" requested but ${selection.reason}`);
29123
+ this.startAuditd(selection.reason);
27585
29124
  }
27586
29125
  if (this.opts.settings.watchUnknownTempCpu) {
27587
29126
  this.cpuTimer = setInterval(() => this.sampleTemporaryProcesses(), CPU_SAMPLE_MS);
@@ -27590,7 +29129,109 @@ var EdrWatch = class {
27590
29129
  this.opts.log(`[edr] watching temporary-path processes for sustained CPU use (${CPU_THRESHOLD_PERCENT}% for ${CPU_SUSTAIN_MS / 1e3}s)`);
27591
29130
  }
27592
29131
  }
29132
+ /** The event source currently feeding detections. */
29133
+ get source() {
29134
+ return this.activeSource;
29135
+ }
29136
+ probe() {
29137
+ const configured = this.opts.settings.source;
29138
+ if (configured === "auditd") return { configured, bpftracePath: null, btfPresent: false, isRoot: false };
29139
+ return (this.opts.probeHost ?? probeHost)(configured);
29140
+ }
29141
+ startEbpf(bpftracePath, reason) {
29142
+ const options = {
29143
+ bpftracePath,
29144
+ network: this.opts.settings.watchNetworkSyscalls,
29145
+ onEvent: (event) => {
29146
+ this.handleEbpfEvent(event);
29147
+ },
29148
+ onFatal: (failure) => {
29149
+ this.bpftrace = null;
29150
+ this.opts.log(`[edr] ${failure}; falling back to auditd`);
29151
+ this.startAuditd(`eBPF failed: ${failure}`);
29152
+ },
29153
+ log: this.opts.log
29154
+ };
29155
+ this.bpftrace = this.opts.createBpftrace ? this.opts.createBpftrace(options) : new BpftraceSource(options);
29156
+ this.setSource("ebpf", reason);
29157
+ this.opts.log(`[edr] event source: eBPF via ${bpftracePath} (exec${this.opts.settings.watchNetworkSyscalls ? ", tcp connect/listen" : ""}); command arguments and remote addresses are not collected`);
29158
+ this.bpftrace.start();
29159
+ }
29160
+ startAuditd(reason) {
29161
+ if (!(0, import_node_fs29.existsSync)(this.opts.settings.auditLogPath)) {
29162
+ this.opts.log(`[edr] audit log not found at ${this.opts.settings.auditLogPath}; auditd detections are unavailable`);
29163
+ this.setSource("none", `${reason}; audit log not found at ${this.opts.settings.auditLogPath}`);
29164
+ return;
29165
+ }
29166
+ try {
29167
+ (0, import_node_fs29.accessSync)(this.opts.settings.auditLogPath, import_node_fs29.constants.R_OK);
29168
+ this.tail = new LogTail(this.opts.settings.auditLogPath);
29169
+ this.timer = setInterval(() => this.poll(), this.opts.settings.pollMs);
29170
+ this.timer.unref?.();
29171
+ this.setSource("auditd", reason);
29172
+ this.opts.log(`[edr] event source: auditd; watching selected events in ${this.opts.settings.auditLogPath}; command arguments and remote addresses are discarded`);
29173
+ } catch {
29174
+ this.opts.log(`[edr] cannot read ${this.opts.settings.auditLogPath}; run the daemon with permission to read the audit log`);
29175
+ this.setSource("none", `${reason}; cannot read ${this.opts.settings.auditLogPath}`);
29176
+ }
29177
+ }
29178
+ setSource(active2, reason) {
29179
+ this.activeSource = active2;
29180
+ const path = this.opts.sourceStatusPath;
29181
+ if (!path) return;
29182
+ const status = {
29183
+ configured: this.opts.settings.source,
29184
+ active: active2,
29185
+ reason,
29186
+ updated_at: (/* @__PURE__ */ new Date()).toISOString(),
29187
+ pid: process.pid
29188
+ };
29189
+ try {
29190
+ const temp = `${path}.${process.pid}.tmp`;
29191
+ (0, import_node_fs29.writeFileSync)(temp, `${JSON.stringify(status)}
29192
+ `, { mode: 420 });
29193
+ (0, import_node_fs29.renameSync)(temp, path);
29194
+ } catch {
29195
+ }
29196
+ }
29197
+ resolveEbpfExe(event) {
29198
+ let exe = null;
29199
+ try {
29200
+ exe = (0, import_node_fs29.readlinkSync)(`/proc/${event.pid}/exe`).replace(/ \(deleted\)$/, "");
29201
+ } catch {
29202
+ }
29203
+ if (!exe && event.kind !== "exec") exe = this.ebpfExeCache.get(event.pid) ?? null;
29204
+ if (!exe && event.kind === "exec" && event.filename?.startsWith("/")) exe = event.filename;
29205
+ if (exe && event.kind === "exec") {
29206
+ this.ebpfExeCache.delete(event.pid);
29207
+ this.ebpfExeCache.set(event.pid, exe);
29208
+ if (this.ebpfExeCache.size > MAX_EBPF_EXE_CACHE) this.ebpfExeCache.delete(this.ebpfExeCache.keys().next().value);
29209
+ }
29210
+ return exe;
29211
+ }
29212
+ /** Classify one eBPF event through the same rules as auditd records. Returns the event published, if any. */
29213
+ handleEbpfEvent(event, resolveExe) {
29214
+ if ((event.kind === "connect" || event.kind === "listen") && !this.opts.settings.watchNetworkSyscalls) return null;
29215
+ this.ebpfSerial = (this.ebpfSerial + 1) % Number.MAX_SAFE_INTEGER;
29216
+ const resolver = resolveExe ?? (() => this.resolveEbpfExe(event));
29217
+ const records = ebpfEventToRecords(event, resolver, /* @__PURE__ */ new Date(), `ebpf-${this.ebpfSerial}`);
29218
+ for (const record of records) {
29219
+ const threat = this.classify(record);
29220
+ if (threat) {
29221
+ this.publish(threat);
29222
+ return threat;
29223
+ }
29224
+ }
29225
+ return null;
29226
+ }
27593
29227
  stop() {
29228
+ try {
29229
+ this.bpftrace?.stop();
29230
+ } catch {
29231
+ }
29232
+ this.bpftrace = null;
29233
+ this.ebpfExeCache.clear();
29234
+ this.activeSource = "none";
27594
29235
  if (this.timer) clearInterval(this.timer);
27595
29236
  if (this.cpuTimer) clearInterval(this.cpuTimer);
27596
29237
  this.timer = null;
@@ -27622,7 +29263,7 @@ var EdrWatch = class {
27622
29263
  this.opts.bus.publish(event);
27623
29264
  }
27624
29265
  classify(execution) {
27625
- const name = (0, import_node_path23.basename)(execution.executable).toLowerCase();
29266
+ const name = (0, import_node_path25.basename)(execution.executable).toLowerCase();
27626
29267
  const account = this.usersById.get(execution.euid) ?? String(execution.euid);
27627
29268
  let severity;
27628
29269
  let ruleId;
@@ -27677,7 +29318,8 @@ var EdrWatch = class {
27677
29318
  euid: execution.euid,
27678
29319
  ...execution.pid ? { pid: execution.pid } : {},
27679
29320
  ...execution.ppid ? { ppid: execution.ppid } : {},
27680
- audit_serial: execution.serial
29321
+ event_source: execution.source ?? "auditd",
29322
+ ...execution.source === "ebpf" ? {} : { audit_serial: execution.serial }
27681
29323
  }
27682
29324
  };
27683
29325
  }
@@ -27685,7 +29327,7 @@ var EdrWatch = class {
27685
29327
  const path = this.opts.networkBaselinePath;
27686
29328
  if (!path) return;
27687
29329
  try {
27688
- const parsed = JSON.parse((0, import_node_fs28.readFileSync)(path, "utf8"));
29330
+ const parsed = JSON.parse((0, import_node_fs29.readFileSync)(path, "utf8"));
27689
29331
  if (Array.isArray(parsed)) {
27690
29332
  for (const value of parsed.slice(0, 1e4)) {
27691
29333
  if (typeof value === "string" && value.startsWith("/")) this.outboundExecutables.add(value);
@@ -27702,9 +29344,9 @@ var EdrWatch = class {
27702
29344
  if (!path) return;
27703
29345
  try {
27704
29346
  const temp = `${path}.${process.pid}.tmp`;
27705
- (0, import_node_fs28.writeFileSync)(temp, `${JSON.stringify([...this.outboundExecutables])}
29347
+ (0, import_node_fs29.writeFileSync)(temp, `${JSON.stringify([...this.outboundExecutables])}
27706
29348
  `, { mode: 384 });
27707
- (0, import_node_fs28.renameSync)(temp, path);
29349
+ (0, import_node_fs29.renameSync)(temp, path);
27708
29350
  this.baselineWriteFailed = false;
27709
29351
  } catch (error) {
27710
29352
  if (!this.baselineWriteFailed) this.opts.log(`[edr] could not persist outbound executable baseline: ${error.message.split("\n")[0]}`);
@@ -27713,7 +29355,7 @@ var EdrWatch = class {
27713
29355
  }
27714
29356
  readTicksPerSecond() {
27715
29357
  try {
27716
- const value = Number((0, import_node_child_process9.execFileSync)("getconf", ["CLK_TCK"], { encoding: "utf8", timeout: 2e3, stdio: ["ignore", "pipe", "ignore"] }).trim());
29358
+ const value = Number((0, import_node_child_process10.execFileSync)("getconf", ["CLK_TCK"], { encoding: "utf8", timeout: 2e3, stdio: ["ignore", "pipe", "ignore"] }).trim());
27717
29359
  if (Number.isFinite(value) && value > 0) return value;
27718
29360
  } catch {
27719
29361
  }
@@ -27725,7 +29367,7 @@ var EdrWatch = class {
27725
29367
  const current = /* @__PURE__ */ new Map();
27726
29368
  let pids;
27727
29369
  try {
27728
- pids = (0, import_node_fs28.readdirSync)("/proc");
29370
+ pids = (0, import_node_fs29.readdirSync)("/proc");
27729
29371
  } catch {
27730
29372
  return;
27731
29373
  }
@@ -27733,7 +29375,7 @@ var EdrWatch = class {
27733
29375
  if (!/^\d+$/.test(pid)) continue;
27734
29376
  const proc = `/proc/${pid}`;
27735
29377
  try {
27736
- const raw = (0, import_node_fs28.readFileSync)(`${proc}/stat`, "utf8");
29378
+ const raw = (0, import_node_fs29.readFileSync)(`${proc}/stat`, "utf8");
27737
29379
  const end = raw.lastIndexOf(")");
27738
29380
  if (end < 0) continue;
27739
29381
  const fields = raw.slice(end + 1).trim().split(/\s+/);
@@ -27741,10 +29383,10 @@ var EdrWatch = class {
27741
29383
  const systemTicks = Number(fields[12]);
27742
29384
  const startTicks = fields[19];
27743
29385
  if (!Number.isFinite(userTicks) || !Number.isFinite(systemTicks) || !startTicks) continue;
27744
- let executable = (0, import_node_fs28.readlinkSync)(`${proc}/exe`);
29386
+ let executable = (0, import_node_fs29.readlinkSync)(`${proc}/exe`);
27745
29387
  executable = executable.replace(/ \(deleted\)$/, "");
27746
29388
  if (!this.opts.settings.tempExecPaths.some((path) => pathWithin(executable, path))) continue;
27747
- const name = (0, import_node_path23.basename)(executable).toLowerCase();
29389
+ const name = (0, import_node_path25.basename)(executable).toLowerCase();
27748
29390
  if (MINERS.has(name)) continue;
27749
29391
  const key = `${pid}:${startTicks}`;
27750
29392
  const ticks = userTicks + systemTicks;
@@ -27780,9 +29422,9 @@ var EdrWatch = class {
27780
29422
  };
27781
29423
 
27782
29424
  // src/daemon/workers/ssh-intrusion.ts
27783
- var import_node_fs29 = require("fs");
27784
- var import_node_path24 = require("path");
27785
- var import_node_child_process10 = require("child_process");
29425
+ var import_node_fs30 = require("fs");
29426
+ var import_node_path26 = require("path");
29427
+ var import_node_child_process11 = require("child_process");
27786
29428
 
27787
29429
  // src/core/asn.ts
27788
29430
  var import_node_dns = require("dns");
@@ -27975,35 +29617,35 @@ function parseKeyLoginsByFingerprint(text) {
27975
29617
  }
27976
29618
  function readJson2(path) {
27977
29619
  try {
27978
- return JSON.parse((0, import_node_fs29.readFileSync)(path, "utf-8"));
29620
+ return JSON.parse((0, import_node_fs30.readFileSync)(path, "utf-8"));
27979
29621
  } catch {
27980
29622
  return null;
27981
29623
  }
27982
29624
  }
27983
29625
  function writeJson2(path, value) {
27984
- (0, import_node_fs29.mkdirSync)((0, import_node_path24.dirname)(path), { recursive: true });
27985
- (0, import_node_fs29.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
27986
- (0, import_node_fs29.renameSync)(`${path}.tmp`, path);
29626
+ (0, import_node_fs30.mkdirSync)((0, import_node_path26.dirname)(path), { recursive: true });
29627
+ (0, import_node_fs30.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
29628
+ (0, import_node_fs30.renameSync)(`${path}.tmp`, path);
27987
29629
  }
27988
29630
  var fsIO2 = {
27989
29631
  readFile: (p) => {
27990
29632
  try {
27991
- return (0, import_node_fs29.readFileSync)(p, "utf-8");
29633
+ return (0, import_node_fs30.readFileSync)(p, "utf-8");
27992
29634
  } catch {
27993
29635
  return null;
27994
29636
  }
27995
29637
  },
27996
29638
  readDir: (p) => {
27997
29639
  try {
27998
- return (0, import_node_fs29.readdirSync)(p);
29640
+ return (0, import_node_fs30.readdirSync)(p);
27999
29641
  } catch {
28000
29642
  return null;
28001
29643
  }
28002
29644
  },
28003
- exists: (p) => (0, import_node_fs29.existsSync)(p)
29645
+ exists: (p) => (0, import_node_fs30.existsSync)(p)
28004
29646
  };
28005
29647
  function defaultRun4(cmd, args) {
28006
- const res = (0, import_node_child_process10.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
29648
+ const res = (0, import_node_child_process11.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
28007
29649
  return res.status === 0 ? res.stdout : null;
28008
29650
  }
28009
29651
  var SshIntrusionWatch = class {
@@ -28201,23 +29843,23 @@ var SshIntrusionWatch = class {
28201
29843
  };
28202
29844
 
28203
29845
  // src/daemon/key-directory.ts
28204
- var import_node_fs30 = require("fs");
29846
+ var import_node_fs31 = require("fs");
28205
29847
  var fsIO3 = {
28206
29848
  readFile: (p) => {
28207
29849
  try {
28208
- return (0, import_node_fs30.readFileSync)(p, "utf-8");
29850
+ return (0, import_node_fs31.readFileSync)(p, "utf-8");
28209
29851
  } catch {
28210
29852
  return null;
28211
29853
  }
28212
29854
  },
28213
29855
  readDir: (p) => {
28214
29856
  try {
28215
- return (0, import_node_fs30.readdirSync)(p);
29857
+ return (0, import_node_fs31.readdirSync)(p);
28216
29858
  } catch {
28217
29859
  return null;
28218
29860
  }
28219
29861
  },
28220
- exists: (p) => (0, import_node_fs30.existsSync)(p)
29862
+ exists: (p) => (0, import_node_fs31.existsSync)(p)
28221
29863
  };
28222
29864
  var KeyDirectory = class {
28223
29865
  constructor(io = fsIO3, now = Date.now, ttlMs = 3e5) {
@@ -28261,7 +29903,7 @@ function enrichLoginEvent(event, keys) {
28261
29903
  }
28262
29904
 
28263
29905
  // src/daemon/workers/lightning-watch.ts
28264
- var import_node_fs31 = require("fs");
29906
+ var import_node_fs32 = require("fs");
28265
29907
  var DEFAULT_CLN_LOGS = [
28266
29908
  "/home/lightning/.lightning/cln.log",
28267
29909
  "/root/.lightning/cln.log",
@@ -28317,9 +29959,9 @@ var LightningWatch = class {
28317
29959
  if (this.opts.enabled === false) return [];
28318
29960
  const found = [];
28319
29961
  for (const path of this.opts.paths?.length ? this.opts.paths : DEFAULT_CLN_LOGS) {
28320
- if (!(0, import_node_fs31.existsSync)(path)) continue;
29962
+ if (!(0, import_node_fs32.existsSync)(path)) continue;
28321
29963
  try {
28322
- (0, import_node_fs31.accessSync)(path, import_node_fs31.constants.R_OK);
29964
+ (0, import_node_fs32.accessSync)(path, import_node_fs32.constants.R_OK);
28323
29965
  } catch {
28324
29966
  continue;
28325
29967
  }
@@ -28354,12 +29996,12 @@ var LightningWatch = class {
28354
29996
  };
28355
29997
 
28356
29998
  // src/daemon/workers/docker-logs.ts
28357
- var import_node_fs33 = require("fs");
29999
+ var import_node_fs34 = require("fs");
28358
30000
  var import_node_http = require("http");
28359
30001
  var import_node_net12 = require("net");
28360
30002
 
28361
30003
  // src/daemon/workers/postgres-shell.ts
28362
- var import_node_fs32 = require("fs");
30004
+ var import_node_fs33 = require("fs");
28363
30005
  var DEFAULT_ALLOW_CMDLINE = [
28364
30006
  // Supabase's pgsodium reads its root key by running this script at startup.
28365
30007
  String.raw`^(?:\S*/)?(?:ba|da)?sh (?:-c )?(?:\S*/)?pgsodium_getkey(?:\.sh)?$`,
@@ -28503,28 +30145,28 @@ function shellLogDetector(cooldownMs = 6e4, now = Date.now) {
28503
30145
  var realProcFs = {
28504
30146
  pids: () => {
28505
30147
  try {
28506
- return (0, import_node_fs32.readdirSync)("/proc").filter((n) => /^\d+$/.test(n)).map(Number);
30148
+ return (0, import_node_fs33.readdirSync)("/proc").filter((n) => /^\d+$/.test(n)).map(Number);
28507
30149
  } catch {
28508
30150
  return [];
28509
30151
  }
28510
30152
  },
28511
30153
  stat: (pid) => {
28512
30154
  try {
28513
- return (0, import_node_fs32.readFileSync)(`/proc/${pid}/stat`, "utf-8");
30155
+ return (0, import_node_fs33.readFileSync)(`/proc/${pid}/stat`, "utf-8");
28514
30156
  } catch {
28515
30157
  return null;
28516
30158
  }
28517
30159
  },
28518
30160
  cmdline: (pid) => {
28519
30161
  try {
28520
- return (0, import_node_fs32.readFileSync)(`/proc/${pid}/cmdline`, "utf-8").replace(/\0+$/, "").replace(/\0/g, " ");
30162
+ return (0, import_node_fs33.readFileSync)(`/proc/${pid}/cmdline`, "utf-8").replace(/\0+$/, "").replace(/\0/g, " ");
28521
30163
  } catch {
28522
30164
  return null;
28523
30165
  }
28524
30166
  },
28525
30167
  cgroup: (pid) => {
28526
30168
  try {
28527
- return (0, import_node_fs32.readFileSync)(`/proc/${pid}/cgroup`, "utf-8");
30169
+ return (0, import_node_fs33.readFileSync)(`/proc/${pid}/cgroup`, "utf-8");
28528
30170
  } catch {
28529
30171
  return null;
28530
30172
  }
@@ -28883,7 +30525,7 @@ var DockerLogsWatch = class {
28883
30525
  start() {
28884
30526
  const { settings } = this.opts;
28885
30527
  if (!settings.enabled) return false;
28886
- if (!this.opts.deps && !(0, import_node_fs33.existsSync)(settings.socket)) return false;
30528
+ if (!this.opts.deps && !(0, import_node_fs34.existsSync)(settings.socket)) return false;
28887
30529
  this.opts.log(`[docker-logs] following containers named /${settings.namePattern.source}/ or with image /${settings.imagePattern.source}/ for Postgres auth failures`);
28888
30530
  void this.poll();
28889
30531
  this.timer = setInterval(() => {
@@ -28989,8 +30631,8 @@ var DockerLogsWatch = class {
28989
30631
  };
28990
30632
 
28991
30633
  // src/daemon/workers/login-watch.ts
28992
- var import_node_fs34 = require("fs");
28993
- var import_node_child_process11 = require("child_process");
30634
+ var import_node_fs35 = require("fs");
30635
+ var import_node_child_process12 = require("child_process");
28994
30636
  var import_node_net13 = require("net");
28995
30637
  var DEFAULT_SENSITIVE_GROUPS = ["sudo", "admin", "wheel", "docker"];
28996
30638
  function stringList(value, fallback) {
@@ -29100,12 +30742,12 @@ function sshdPidsForPeer(ssOutput, ip) {
29100
30742
  }
29101
30743
  var realKillDeps = {
29102
30744
  run: (cmd, args) => {
29103
- const res = (0, import_node_child_process11.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 1e4, stdio: ["ignore", "pipe", "pipe"] });
30745
+ const res = (0, import_node_child_process12.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 1e4, stdio: ["ignore", "pipe", "pipe"] });
29104
30746
  return res.status === 0 ? res.stdout : null;
29105
30747
  },
29106
30748
  cmdline: (pid) => {
29107
30749
  try {
29108
- return (0, import_node_fs34.readFileSync)(`/proc/${pid}/cmdline`, "utf-8").replace(/\0+$/, "").replace(/\0/g, " ");
30750
+ return (0, import_node_fs35.readFileSync)(`/proc/${pid}/cmdline`, "utf-8").replace(/\0+$/, "").replace(/\0/g, " ");
29109
30751
  } catch {
29110
30752
  return null;
29111
30753
  }
@@ -29163,14 +30805,14 @@ function forcedCommandKeys(text) {
29163
30805
  var realKeyFileIO = {
29164
30806
  mtime: (p) => {
29165
30807
  try {
29166
- return (0, import_node_fs34.statSync)(p).mtimeMs;
30808
+ return (0, import_node_fs35.statSync)(p).mtimeMs;
29167
30809
  } catch {
29168
30810
  return null;
29169
30811
  }
29170
30812
  },
29171
30813
  read: (p) => {
29172
30814
  try {
29173
- return (0, import_node_fs34.readFileSync)(p, "utf-8");
30815
+ return (0, import_node_fs35.readFileSync)(p, "utf-8");
29174
30816
  } catch {
29175
30817
  return null;
29176
30818
  }
@@ -29224,8 +30866,8 @@ var LoginWatch = class {
29224
30866
  const users = new Set(this.opts.settings.sensitiveUsers);
29225
30867
  try {
29226
30868
  const { group, passwd } = this.opts.readAccounts?.() ?? {
29227
- group: (0, import_node_fs34.readFileSync)("/etc/group", "utf-8"),
29228
- passwd: (0, import_node_fs34.readFileSync)("/etc/passwd", "utf-8")
30869
+ group: (0, import_node_fs35.readFileSync)("/etc/group", "utf-8"),
30870
+ passwd: (0, import_node_fs35.readFileSync)("/etc/passwd", "utf-8")
29229
30871
  };
29230
30872
  for (const u of groupMembers(group, passwd, this.opts.settings.sensitiveGroups)) users.add(u);
29231
30873
  } catch {
@@ -29240,7 +30882,7 @@ var LoginWatch = class {
29240
30882
  return;
29241
30883
  }
29242
30884
  const run = this.opts.run ?? ((cmd, args) => {
29243
- const res = (0, import_node_child_process11.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
30885
+ const res = (0, import_node_child_process12.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
29244
30886
  return res.status === 0 ? res.stdout : null;
29245
30887
  });
29246
30888
  const out = run("journalctl", ["_COMM=sshd", "_COMM=sshd-session", "--since=-30d", "-o", "short-unix", "--no-pager", "--grep", "Accepted "]);
@@ -29261,7 +30903,7 @@ var LoginWatch = class {
29261
30903
  }
29262
30904
  passwdText() {
29263
30905
  try {
29264
- return this.opts.readAccounts ? this.opts.readAccounts().passwd : (0, import_node_fs34.readFileSync)("/etc/passwd", "utf-8");
30906
+ return this.opts.readAccounts ? this.opts.readAccounts().passwd : (0, import_node_fs35.readFileSync)("/etc/passwd", "utf-8");
29265
30907
  } catch {
29266
30908
  return "";
29267
30909
  }
@@ -29387,8 +31029,8 @@ var LoginWatch = class {
29387
31029
  };
29388
31030
 
29389
31031
  // src/core/tor-exits.ts
29390
- var import_node_fs35 = require("fs");
29391
- var import_node_path25 = require("path");
31032
+ var import_node_fs36 = require("fs");
31033
+ var import_node_path27 = require("path");
29392
31034
  var import_node_net14 = require("net");
29393
31035
  var TOR_BULK_EXIT_LIST_URL = "https://check.torproject.org/torbulkexitlist";
29394
31036
  function parseTorExitList(text) {
@@ -29460,10 +31102,10 @@ var TorExitList = class _TorExitList {
29460
31102
  }
29461
31103
  loadCache() {
29462
31104
  try {
29463
- if (!(0, import_node_fs35.existsSync)(this.opts.cachePath)) return false;
29464
- const parsed = parseTorExitList((0, import_node_fs35.readFileSync)(this.opts.cachePath, "utf-8"));
31105
+ if (!(0, import_node_fs36.existsSync)(this.opts.cachePath)) return false;
31106
+ const parsed = parseTorExitList((0, import_node_fs36.readFileSync)(this.opts.cachePath, "utf-8"));
29465
31107
  if (parsed.size === 0) return false;
29466
- this.load(parsed, (0, import_node_fs35.statSync)(this.opts.cachePath).mtimeMs);
31108
+ this.load(parsed, (0, import_node_fs36.statSync)(this.opts.cachePath).mtimeMs);
29467
31109
  this.log(`[tor] loaded ${parsed.size} Tor exit addresses from cache (${new Date(this.updatedAt).toISOString()})`);
29468
31110
  return true;
29469
31111
  } catch (err) {
@@ -29495,9 +31137,9 @@ var TorExitList = class _TorExitList {
29495
31137
  const before = this.exits.size;
29496
31138
  this.load(parsed);
29497
31139
  try {
29498
- (0, import_node_fs35.mkdirSync)((0, import_node_path25.dirname)(this.opts.cachePath), { recursive: true });
29499
- (0, import_node_fs35.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
29500
- (0, import_node_fs35.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
31140
+ (0, import_node_fs36.mkdirSync)((0, import_node_path27.dirname)(this.opts.cachePath), { recursive: true });
31141
+ (0, import_node_fs36.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
31142
+ (0, import_node_fs36.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
29501
31143
  } catch (err) {
29502
31144
  this.log(`[tor] could not save the exit list cache: ${err.message}`);
29503
31145
  }
@@ -29507,12 +31149,12 @@ var TorExitList = class _TorExitList {
29507
31149
  };
29508
31150
 
29509
31151
  // src/daemon/firewall/tor-block.ts
29510
- var import_node_child_process12 = require("child_process");
31152
+ var import_node_child_process13 = require("child_process");
29511
31153
  var import_node_net15 = require("net");
29512
31154
  var TOR_NFT_TABLE = "threatcrush-tor";
29513
31155
  function defaultNftRunner() {
29514
31156
  return (args, stdin) => new Promise((resolve4, reject) => {
29515
- const child = (0, import_node_child_process12.execFile)(
31157
+ const child = (0, import_node_child_process13.execFile)(
29516
31158
  "nft",
29517
31159
  args,
29518
31160
  { maxBuffer: 16 * 1024 * 1024 },
@@ -29808,8 +31450,8 @@ var RuleEngine = class {
29808
31450
  };
29809
31451
 
29810
31452
  // src/daemon/rules/loader.ts
29811
- var import_node_fs36 = require("fs");
29812
- var import_node_path26 = require("path");
31453
+ var import_node_fs37 = require("fs");
31454
+ var import_node_path28 = require("path");
29813
31455
 
29814
31456
  // src/daemon/rules/default-rules.ts
29815
31457
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -30481,16 +32123,16 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
30481
32123
  function loadAllRules(customDir) {
30482
32124
  const rules = [...DEFAULT_RULES];
30483
32125
  const dir = customDir || RULES_DIR;
30484
- if ((0, import_node_fs36.existsSync)(dir)) {
32126
+ if ((0, import_node_fs37.existsSync)(dir)) {
30485
32127
  let files = [];
30486
32128
  try {
30487
- files = (0, import_node_fs36.readdirSync)(dir).filter((f) => f.endsWith(".json"));
32129
+ files = (0, import_node_fs37.readdirSync)(dir).filter((f) => f.endsWith(".json"));
30488
32130
  } catch (err) {
30489
32131
  console.warn(`[rules] cannot read ${dir}: ${err.message}; custom rules not loaded`);
30490
32132
  }
30491
32133
  for (const file of files) {
30492
32134
  try {
30493
- const raw = (0, import_node_fs36.readFileSync)((0, import_node_path26.join)(dir, file), "utf-8");
32135
+ const raw = (0, import_node_fs37.readFileSync)((0, import_node_path28.join)(dir, file), "utf-8");
30494
32136
  const parsed = JSON.parse(raw);
30495
32137
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
30496
32138
  for (const rule of customRules) {
@@ -30521,9 +32163,9 @@ function loadAllRules(customDir) {
30521
32163
  }
30522
32164
 
30523
32165
  // src/daemon/firewall/adapters.ts
30524
- var import_node_child_process13 = require("child_process");
30525
- var import_node_fs37 = require("fs");
30526
- var import_node_path27 = require("path");
32166
+ var import_node_child_process14 = require("child_process");
32167
+ var import_node_fs38 = require("fs");
32168
+ var import_node_path29 = require("path");
30527
32169
  var import_node_net16 = require("net");
30528
32170
  function assertValidFirewallIp(ip) {
30529
32171
  if ((0, import_node_net16.isIP)(ip) !== 4) {
@@ -30536,9 +32178,9 @@ function assertBannableIp(ip) {
30536
32178
  }
30537
32179
  }
30538
32180
  function writeIfAbsent(path, contents) {
30539
- (0, import_node_fs37.mkdirSync)((0, import_node_path27.dirname)(path), { recursive: true });
32181
+ (0, import_node_fs38.mkdirSync)((0, import_node_path29.dirname)(path), { recursive: true });
30540
32182
  try {
30541
- (0, import_node_fs37.writeFileSync)(path, contents, { flag: "wx" });
32183
+ (0, import_node_fs38.writeFileSync)(path, contents, { flag: "wx" });
30542
32184
  } catch (err) {
30543
32185
  if (err.code !== "EEXIST") throw err;
30544
32186
  }
@@ -30557,11 +32199,11 @@ var Fail2banAdapter = class {
30557
32199
  enforces = true;
30558
32200
  jailReady = false;
30559
32201
  isAvailable() {
30560
- const result = (0, import_node_child_process13.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
32202
+ const result = (0, import_node_child_process14.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
30561
32203
  return result.status === 0;
30562
32204
  }
30563
32205
  client(args) {
30564
- return (0, import_node_child_process13.execFileSync)("fail2ban-client", args, {
32206
+ return (0, import_node_child_process14.execFileSync)("fail2ban-client", args, {
30565
32207
  encoding: "utf-8",
30566
32208
  stdio: ["ignore", "pipe", "pipe"]
30567
32209
  });
@@ -30657,35 +32299,35 @@ var NftablesAdapter = class {
30657
32299
  table = "threatcrush";
30658
32300
  set = "blocklist";
30659
32301
  isAvailable() {
30660
- const result = (0, import_node_child_process13.spawnSync)("nft", ["--version"], { stdio: "pipe" });
32302
+ const result = (0, import_node_child_process14.spawnSync)("nft", ["--version"], { stdio: "pipe" });
30661
32303
  return result.status === 0;
30662
32304
  }
30663
32305
  ensureSetup() {
30664
32306
  try {
30665
- (0, import_node_child_process13.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
32307
+ (0, import_node_child_process14.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
30666
32308
  } catch {
30667
- (0, import_node_child_process13.execSync)(`nft add table inet ${this.table}`);
30668
- (0, import_node_child_process13.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
30669
- (0, import_node_child_process13.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
30670
- (0, import_node_child_process13.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
32309
+ (0, import_node_child_process14.execSync)(`nft add table inet ${this.table}`);
32310
+ (0, import_node_child_process14.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
32311
+ (0, import_node_child_process14.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
32312
+ (0, import_node_child_process14.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
30671
32313
  }
30672
32314
  }
30673
32315
  async block(ip) {
30674
32316
  assertValidFirewallIp(ip);
30675
32317
  this.ensureSetup();
30676
- (0, import_node_child_process13.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
32318
+ (0, import_node_child_process14.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
30677
32319
  }
30678
32320
  async unblock(ip) {
30679
32321
  assertValidFirewallIp(ip);
30680
32322
  try {
30681
- (0, import_node_child_process13.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
32323
+ (0, import_node_child_process14.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
30682
32324
  } catch {
30683
32325
  }
30684
32326
  }
30685
32327
  async isBlocked(ip) {
30686
32328
  assertValidFirewallIp(ip);
30687
32329
  try {
30688
- const output = (0, import_node_child_process13.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
32330
+ const output = (0, import_node_child_process14.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
30689
32331
  return output.includes(ip);
30690
32332
  } catch {
30691
32333
  return false;
@@ -30693,7 +32335,7 @@ var NftablesAdapter = class {
30693
32335
  }
30694
32336
  async listBlocked() {
30695
32337
  try {
30696
- const output = (0, import_node_child_process13.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
32338
+ const output = (0, import_node_child_process14.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
30697
32339
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
30698
32340
  if (!match) return [];
30699
32341
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -30706,34 +32348,34 @@ var IptablesAdapter = class {
30706
32348
  name = "iptables";
30707
32349
  chain = "THREATCRUSH";
30708
32350
  isAvailable() {
30709
- const result = (0, import_node_child_process13.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
32351
+ const result = (0, import_node_child_process14.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
30710
32352
  return result.status === 0;
30711
32353
  }
30712
32354
  ensureChain() {
30713
32355
  try {
30714
- (0, import_node_child_process13.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
32356
+ (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
30715
32357
  } catch {
30716
- (0, import_node_child_process13.execSync)(`iptables -N ${this.chain}`);
30717
- (0, import_node_child_process13.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
32358
+ (0, import_node_child_process14.execSync)(`iptables -N ${this.chain}`);
32359
+ (0, import_node_child_process14.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
30718
32360
  }
30719
32361
  }
30720
32362
  async block(ip) {
30721
32363
  assertValidFirewallIp(ip);
30722
32364
  this.ensureChain();
30723
32365
  if (await this.isBlocked(ip)) return;
30724
- (0, import_node_child_process13.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
32366
+ (0, import_node_child_process14.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
30725
32367
  }
30726
32368
  async unblock(ip) {
30727
32369
  assertValidFirewallIp(ip);
30728
32370
  try {
30729
- (0, import_node_child_process13.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
32371
+ (0, import_node_child_process14.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
30730
32372
  } catch {
30731
32373
  }
30732
32374
  }
30733
32375
  async isBlocked(ip) {
30734
32376
  assertValidFirewallIp(ip);
30735
32377
  try {
30736
- const output = (0, import_node_child_process13.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
32378
+ const output = (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
30737
32379
  return output.includes(ip);
30738
32380
  } catch {
30739
32381
  return false;
@@ -30741,7 +32383,7 @@ var IptablesAdapter = class {
30741
32383
  }
30742
32384
  async listBlocked() {
30743
32385
  try {
30744
- const output = (0, import_node_child_process13.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
32386
+ const output = (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
30745
32387
  const ips = [];
30746
32388
  for (const line of output.split("\n")) {
30747
32389
  const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -30797,8 +32439,8 @@ function detectFirewallAdapter(backend = "auto") {
30797
32439
  }
30798
32440
 
30799
32441
  // src/daemon/firewall/remediation.ts
30800
- var import_node_fs38 = require("fs");
30801
- var import_node_child_process14 = require("child_process");
32442
+ var import_node_fs39 = require("fs");
32443
+ var import_node_child_process15 = require("child_process");
30802
32444
  var import_node_net17 = require("net");
30803
32445
 
30804
32446
  // src/daemon/firewall/crawlers.ts
@@ -30867,19 +32509,19 @@ var defaultDiscovery = {
30867
32509
  const snapshot = takeSnapshot({
30868
32510
  readFile: (p) => {
30869
32511
  try {
30870
- return (0, import_node_fs38.readFileSync)(p, "utf-8");
32512
+ return (0, import_node_fs39.readFileSync)(p, "utf-8");
30871
32513
  } catch {
30872
32514
  return null;
30873
32515
  }
30874
32516
  },
30875
32517
  readDir: (p) => {
30876
32518
  try {
30877
- return (0, import_node_fs38.readdirSync)(p);
32519
+ return (0, import_node_fs39.readdirSync)(p);
30878
32520
  } catch {
30879
32521
  return null;
30880
32522
  }
30881
32523
  },
30882
- exists: (p) => (0, import_node_fs38.existsSync)(p)
32524
+ exists: (p) => (0, import_node_fs39.existsSync)(p)
30883
32525
  });
30884
32526
  const out = /* @__PURE__ */ new Set();
30885
32527
  for (const keys of Object.values(snapshot.keys)) {
@@ -30888,7 +32530,7 @@ var defaultDiscovery = {
30888
32530
  return out;
30889
32531
  },
30890
32532
  keyLoginJournal: (sinceSeconds) => new Promise((resolve4) => {
30891
- (0, import_node_child_process14.execFile)(
32533
+ (0, import_node_child_process15.execFile)(
30892
32534
  "journalctl",
30893
32535
  ["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
30894
32536
  { maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
@@ -31392,7 +33034,7 @@ var RemediationManager = class {
31392
33034
  }
31393
33035
  logLine(line) {
31394
33036
  try {
31395
- (0, import_node_fs38.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
33037
+ (0, import_node_fs39.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
31396
33038
  `);
31397
33039
  } catch {
31398
33040
  }
@@ -31432,13 +33074,13 @@ function remediationSettings(section) {
31432
33074
  }
31433
33075
 
31434
33076
  // src/daemon/watchdog-service.ts
31435
- var import_node_fs40 = require("fs");
31436
- var import_node_path29 = require("path");
33077
+ var import_node_fs41 = require("fs");
33078
+ var import_node_path31 = require("path");
31437
33079
 
31438
33080
  // src/core/watchdog.ts
31439
- var import_node_fs39 = require("fs");
33081
+ var import_node_fs40 = require("fs");
31440
33082
  var import_node_crypto9 = require("crypto");
31441
- var import_node_path28 = require("path");
33083
+ var import_node_path30 = require("path");
31442
33084
  var WATCHDOG_DIRNAME = "watchdog";
31443
33085
  var LOG_FILE2 = "attacks.jsonl";
31444
33086
  var ROTATED_FILE = "attacks.1.jsonl";
@@ -31527,12 +33169,12 @@ var WatchdogLog = class {
31527
33169
  stats = { logged: 0, answered: 0, errored: 0 };
31528
33170
  constructor(dir, options = {}) {
31529
33171
  this.dir = dir;
31530
- this.file = (0, import_node_path28.join)(dir, LOG_FILE2);
33172
+ this.file = (0, import_node_path30.join)(dir, LOG_FILE2);
31531
33173
  this.shareGid = options.shareGid;
31532
- (0, import_node_fs39.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
33174
+ (0, import_node_fs40.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
31533
33175
  if (this.shareGid !== void 0) {
31534
- (0, import_node_fs39.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
31535
- (0, import_node_fs39.chmodSync)(dir, 1528);
33176
+ (0, import_node_fs40.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
33177
+ (0, import_node_fs40.chmodSync)(dir, 1528);
31536
33178
  }
31537
33179
  for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
31538
33180
  }
@@ -31561,16 +33203,16 @@ var WatchdogLog = class {
31561
33203
  const chunk = this.buffer.join("\n") + "\n";
31562
33204
  this.buffer = [];
31563
33205
  try {
31564
- if ((0, import_node_fs39.statSync)(this.file).size > ROTATE_BYTES) {
31565
- (0, import_node_fs39.renameSync)(this.file, (0, import_node_path28.join)(this.dir, ROTATED_FILE));
33206
+ if ((0, import_node_fs40.statSync)(this.file).size > ROTATE_BYTES) {
33207
+ (0, import_node_fs40.renameSync)(this.file, (0, import_node_path30.join)(this.dir, ROTATED_FILE));
31566
33208
  }
31567
33209
  } catch {
31568
33210
  }
31569
- (0, import_node_fs39.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
33211
+ (0, import_node_fs40.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
31570
33212
  if (this.shareGid !== void 0) {
31571
33213
  try {
31572
- (0, import_node_fs39.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
31573
- (0, import_node_fs39.chmodSync)(this.file, 432);
33214
+ (0, import_node_fs40.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
33215
+ (0, import_node_fs40.chmodSync)(this.file, 432);
31574
33216
  } catch {
31575
33217
  }
31576
33218
  }
@@ -31591,21 +33233,21 @@ function parseLines(text) {
31591
33233
  function readTail(file, bytes) {
31592
33234
  let fd;
31593
33235
  try {
31594
- fd = (0, import_node_fs39.openSync)(file, "r");
33236
+ fd = (0, import_node_fs40.openSync)(file, "r");
31595
33237
  } catch (err) {
31596
33238
  if (err.code === "ENOENT") return [];
31597
33239
  throw err;
31598
33240
  }
31599
33241
  try {
31600
- const size = (0, import_node_fs39.fstatSync)(fd).size;
33242
+ const size = (0, import_node_fs40.fstatSync)(fd).size;
31601
33243
  const start = Math.max(0, size - bytes);
31602
33244
  const buf = Buffer.alloc(size - start);
31603
- (0, import_node_fs39.readSync)(fd, buf, 0, buf.length, start);
33245
+ (0, import_node_fs40.readSync)(fd, buf, 0, buf.length, start);
31604
33246
  let text = buf.toString("utf8");
31605
33247
  if (start > 0) text = text.slice(text.indexOf("\n") + 1);
31606
33248
  return parseLines(text);
31607
33249
  } finally {
31608
- (0, import_node_fs39.closeSync)(fd);
33250
+ (0, import_node_fs40.closeSync)(fd);
31609
33251
  }
31610
33252
  }
31611
33253
 
@@ -31614,13 +33256,13 @@ function defaultShareGid() {
31614
33256
  const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
31615
33257
  if (!isRoot2) return void 0;
31616
33258
  try {
31617
- return (0, import_node_fs40.statSync)("/var/log/auth.log").gid;
33259
+ return (0, import_node_fs41.statSync)("/var/log/auth.log").gid;
31618
33260
  } catch {
31619
33261
  return void 0;
31620
33262
  }
31621
33263
  }
31622
33264
  function startWatchdog(opts) {
31623
- const dir = opts.config?.dir ?? (0, import_node_path29.join)(opts.stateDir, WATCHDOG_DIRNAME);
33265
+ const dir = opts.config?.dir ?? (0, import_node_path31.join)(opts.stateDir, WATCHDOG_DIRNAME);
31624
33266
  const base = { dir, logged: 0, answered: 0, errored: 0 };
31625
33267
  if (opts.config?.enabled === false) {
31626
33268
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -31711,7 +33353,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
31711
33353
  }
31712
33354
 
31713
33355
  // src/core/node-runtime.ts
31714
- var import_node_child_process15 = require("child_process");
33356
+ var import_node_child_process16 = require("child_process");
31715
33357
  var MIN_DAEMON_NODE_MAJOR = 22;
31716
33358
  function nodeMajor(version) {
31717
33359
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -31727,16 +33369,16 @@ function daemonNodeProblem(version) {
31727
33369
  // src/daemon/index.ts
31728
33370
  function readVersion2() {
31729
33371
  try {
31730
- const pkg = JSON.parse((0, import_node_fs41.readFileSync)((0, import_node_path30.join)(__dirname, "..", "package.json"), "utf-8"));
33372
+ const pkg = JSON.parse((0, import_node_fs42.readFileSync)((0, import_node_path32.join)(__dirname, "..", "package.json"), "utf-8"));
31731
33373
  return pkg.version || "0.0.0";
31732
33374
  } catch {
31733
33375
  return "0.0.0";
31734
33376
  }
31735
33377
  }
31736
33378
  async function runHardeningChecks() {
31737
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process16.execFile)(
33379
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process17.execFile)(
31738
33380
  process.execPath,
31739
- [(0, import_node_path30.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
33381
+ [(0, import_node_path32.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
31740
33382
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
31741
33383
  );
31742
33384
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -31748,9 +33390,9 @@ async function runHardeningChecks() {
31748
33390
  return patches ? [...findings, patches] : findings;
31749
33391
  }
31750
33392
  async function runPatchCheck() {
31751
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process16.execFile)(
33393
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process17.execFile)(
31752
33394
  process.execPath,
31753
- [(0, import_node_path30.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
33395
+ [(0, import_node_path32.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
31754
33396
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
31755
33397
  );
31756
33398
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -31758,7 +33400,7 @@ async function runPatchCheck() {
31758
33400
  }
31759
33401
  function logLine(line) {
31760
33402
  try {
31761
- (0, import_node_fs41.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
33403
+ (0, import_node_fs42.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
31762
33404
  `);
31763
33405
  } catch {
31764
33406
  }
@@ -31783,9 +33425,9 @@ async function runDaemon() {
31783
33425
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
31784
33426
  const restartDaemon = () => {
31785
33427
  if (PATHS.mode === "system") {
31786
- (0, import_node_child_process16.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
33428
+ (0, import_node_child_process17.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
31787
33429
  } else {
31788
- (0, import_node_child_process16.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
33430
+ (0, import_node_child_process17.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
31789
33431
  setTimeout(() => process.exit(0), 500).unref();
31790
33432
  }
31791
33433
  };
@@ -31800,7 +33442,7 @@ async function runDaemon() {
31800
33442
  } catch (err) {
31801
33443
  logLine(`[daemon] state db unavailable: ${err.message}`);
31802
33444
  }
31803
- const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path30.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
33445
+ const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path32.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
31804
33446
  const config = loaded.config;
31805
33447
  if (loaded.error) {
31806
33448
  logLine(`[daemon] CONFIG ERROR: ${loaded.error}; ${loaded.usedLastGood ? "running on the last config that parsed" : "no earlier good copy, running on DEFAULTS (no protected list)"}`);
@@ -31871,7 +33513,7 @@ async function runDaemon() {
31871
33513
  const threatFeeds = new ThreatFeeds({
31872
33514
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
31873
33515
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
31874
- cachePath: (0, import_node_path30.join)(PATHS.stateDir, "threat-feeds.json"),
33516
+ cachePath: (0, import_node_path32.join)(PATHS.stateDir, "threat-feeds.json"),
31875
33517
  bus,
31876
33518
  log: logLine
31877
33519
  });
@@ -31879,9 +33521,9 @@ async function runDaemon() {
31879
33521
  const privilegeWatch = new PrivilegeWatch({
31880
33522
  settings: privilegeSettings(config.privileged),
31881
33523
  bus,
31882
- snapshotPath: (0, import_node_path30.join)(PATHS.stateDir, "privileges.json"),
31883
- loginsPath: (0, import_node_path30.join)(PATHS.stateDir, "login-countries.json"),
31884
- cursorPath: (0, import_node_path30.join)(PATHS.stateDir, "sudo-cursor.json"),
33524
+ snapshotPath: (0, import_node_path32.join)(PATHS.stateDir, "privileges.json"),
33525
+ loginsPath: (0, import_node_path32.join)(PATHS.stateDir, "login-countries.json"),
33526
+ cursorPath: (0, import_node_path32.join)(PATHS.stateDir, "sudo-cursor.json"),
31885
33527
  log: logLine
31886
33528
  });
31887
33529
  privilegeWatch.start();
@@ -31895,20 +33537,23 @@ async function runDaemon() {
31895
33537
  const fileIntegrity = new FileIntegrityWatch({
31896
33538
  bus,
31897
33539
  settings: fileIntegritySettings(config.file_integrity),
31898
- baselinePath: (0, import_node_path30.join)(PATHS.stateDir, "file-integrity-baseline.json"),
31899
- observedPath: (0, import_node_path30.join)(PATHS.stateDir, "file-integrity-observed.json"),
33540
+ baselinePath: (0, import_node_path32.join)(PATHS.stateDir, "file-integrity-baseline.json"),
33541
+ observedPath: (0, import_node_path32.join)(PATHS.stateDir, "file-integrity-observed.json"),
33542
+ // `[remediation] dry_run` also covers the opt-in contain_writer response.
33543
+ dryRun: () => remediation.status().dry_run,
31900
33544
  log: logLine
31901
33545
  });
31902
33546
  fileIntegrity.start();
31903
33547
  const edr = new EdrWatch({
31904
33548
  bus,
31905
33549
  settings: edrSettings(config.edr),
31906
- networkBaselinePath: (0, import_node_path30.join)(PATHS.stateDir, "edr-outbound-executables.json"),
33550
+ networkBaselinePath: (0, import_node_path32.join)(PATHS.stateDir, "edr-outbound-executables.json"),
33551
+ sourceStatusPath: (0, import_node_path32.join)(PATHS.stateDir, "edr-source.json"),
31907
33552
  log: logLine
31908
33553
  });
31909
33554
  edr.start();
31910
33555
  const torExits = new TorExitList({
31911
- cachePath: (0, import_node_path30.join)(PATHS.stateDir, "tor-exits.txt"),
33556
+ cachePath: (0, import_node_path32.join)(PATHS.stateDir, "tor-exits.txt"),
31912
33557
  url: config.remediation?.tor_exit_list_url,
31913
33558
  log: logLine
31914
33559
  });
@@ -31916,7 +33561,7 @@ async function runDaemon() {
31916
33561
  bus,
31917
33562
  manager: remediation,
31918
33563
  tor: torExits,
31919
- historyPath: (0, import_node_path30.join)(PATHS.stateDir, "key-logins.json"),
33564
+ historyPath: (0, import_node_path32.join)(PATHS.stateDir, "key-logins.json"),
31920
33565
  keyLoginWatch: config.privileged?.key_login_watch !== false,
31921
33566
  log: logLine
31922
33567
  });
@@ -31991,7 +33636,7 @@ async function runDaemon() {
31991
33636
  version,
31992
33637
  hostname: (0, import_node_os6.hostname)(),
31993
33638
  minSeverity,
31994
- spoolPath: (0, import_node_path30.join)(PATHS.stateDir, "cloud-spool.jsonl"),
33639
+ spoolPath: (0, import_node_path32.join)(PATHS.stateDir, "cloud-spool.jsonl"),
31995
33640
  log: logLine,
31996
33641
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
31997
33642
  runHardening: runHardeningChecks
@@ -32025,8 +33670,8 @@ async function runDaemon() {
32025
33670
  const autoUpdate = autoUpdateRef = new AutoUpdate({
32026
33671
  version,
32027
33672
  settings: updateSettings(config.update),
32028
- pkgRoot: (0, import_node_path30.join)(__dirname, ".."),
32029
- statePath: (0, import_node_path30.join)(PATHS.stateDir, "auto-update.json"),
33673
+ pkgRoot: (0, import_node_path32.join)(__dirname, ".."),
33674
+ statePath: (0, import_node_path32.join)(PATHS.stateDir, "auto-update.json"),
32030
33675
  bus,
32031
33676
  log: logLine,
32032
33677
  restartDaemon