@profullstack/threatcrush 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +150 -13
- package/dist/daemon.js +1874 -243
- package/dist/daemon.js.map +1 -1
- package/dist/index.js +2522 -540
- package/dist/index.js.map +1 -1
- package/dist/systemd/threatcrushd.service +6 -2
- package/package.json +1 -1
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
|
|
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
|
|
2044
|
-
var
|
|
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) => (
|
|
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 =
|
|
2077
|
+
exports2.isMap = isMap3;
|
|
2078
2078
|
exports2.isNode = isNode;
|
|
2079
2079
|
exports2.isPair = isPair;
|
|
2080
|
-
exports2.isScalar =
|
|
2081
|
-
exports2.isSeq =
|
|
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
|
|
6190
|
-
const fcName =
|
|
6191
|
-
const NodeClass = tag?.nodeClass ?? (
|
|
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 (!
|
|
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 (!
|
|
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 (!
|
|
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 (
|
|
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 =
|
|
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
|
|
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 =
|
|
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
|
|
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 =
|
|
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
|
|
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 =
|
|
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 =
|
|
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
|
|
9360
|
-
var
|
|
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
|
|
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
|
-
|
|
18002
|
-
|
|
18003
|
-
|
|
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
|
-
|
|
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,53 @@ 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
|
}
|
|
18223
|
+
function redact(message, key) {
|
|
18224
|
+
if (!key) return message;
|
|
18225
|
+
return message.split(key).join("<auth-key>").split(encodeURIComponent(key)).join("<auth-key>");
|
|
18226
|
+
}
|
|
18145
18227
|
async function fetchFeeds(settings, fetchImpl = fetch) {
|
|
18146
18228
|
const sources = [];
|
|
18147
18229
|
const parts = [];
|
|
18148
|
-
const
|
|
18230
|
+
const key = settings.authKey?.trim() || void 0;
|
|
18231
|
+
const ua = { "User-Agent": "threatcrush (+https://threatcrush.com)" };
|
|
18232
|
+
const get2 = async (feed, request2, parse, emptyOk = false) => {
|
|
18233
|
+
if (!request2) {
|
|
18234
|
+
sources.push({ feed, ok: false, count: 0, error: NEEDS_KEY });
|
|
18235
|
+
return;
|
|
18236
|
+
}
|
|
18149
18237
|
try {
|
|
18150
|
-
const
|
|
18238
|
+
const extra = request2.init?.headers ?? {};
|
|
18239
|
+
const res = await fetchImpl(request2.url, { ...request2.init, signal: AbortSignal.timeout(6e4), headers: { ...ua, ...extra } });
|
|
18240
|
+
if (res.status === 401 || res.status === 403) throw new Error(`HTTP ${res.status}: abuse.ch refused the Auth-Key`);
|
|
18151
18241
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
18152
|
-
const
|
|
18242
|
+
const text = await res.text();
|
|
18243
|
+
const type = res.headers.get("content-type") ?? "";
|
|
18244
|
+
if (type.includes("text/html") || /^\s*<(!doctype|html)/i.test(text)) throw new Error(`HTTP ${res.status} but an HTML page, not feed data`);
|
|
18245
|
+
const part = parse(text);
|
|
18246
|
+
const count = (part.ips?.size ?? 0) + (part.domains?.size ?? 0);
|
|
18247
|
+
if (count === 0 && !emptyOk) throw new Error("no entries in the response");
|
|
18153
18248
|
parts.push(part);
|
|
18154
|
-
sources.push({ feed, ok: true, count
|
|
18249
|
+
sources.push({ feed, ok: true, count });
|
|
18155
18250
|
} catch (err) {
|
|
18156
|
-
sources.push({ feed, ok: false, count: 0, error: err.message });
|
|
18251
|
+
sources.push({ feed, ok: false, count: 0, error: redact(err.message, key) });
|
|
18157
18252
|
}
|
|
18158
18253
|
};
|
|
18254
|
+
const threatfoxApi = key ? {
|
|
18255
|
+
url: FEEDS.threatfoxApi,
|
|
18256
|
+
init: {
|
|
18257
|
+
method: "POST",
|
|
18258
|
+
headers: { "Auth-Key": key, "Content-Type": "application/json" },
|
|
18259
|
+
body: JSON.stringify({ query: "get_iocs", days: THREATFOX_DAYS })
|
|
18260
|
+
}
|
|
18261
|
+
} : null;
|
|
18159
18262
|
await Promise.all([
|
|
18160
|
-
get2("threatfox",
|
|
18161
|
-
get2("threatfox-hosts", FEEDS.threatfoxHosts, (t) => ({ domains: parseHostfile(t, "threatfox") })),
|
|
18162
|
-
get2("urlhaus
|
|
18163
|
-
|
|
18263
|
+
get2("threatfox", threatfoxApi, (t) => parseThreatFoxJson(t, settings.minConfidence), true),
|
|
18264
|
+
get2("threatfox-hosts", key ? { url: FEEDS.threatfoxHosts(key) } : null, (t) => ({ domains: parseHostfile(t, "threatfox") })),
|
|
18265
|
+
get2("urlhaus", key ? { url: FEEDS.urlhausOnline(key) } : null, parseUrlhausCsv),
|
|
18266
|
+
// Feodo has been near-empty since 2025; an empty list there is real.
|
|
18267
|
+
get2("feodo", { url: FEEDS.feodoIps }, (t) => ({ ips: parseIpList(t, "feodo") }), true)
|
|
18164
18268
|
]);
|
|
18269
|
+
sources.sort((a, b) => a.feed.localeCompare(b.feed));
|
|
18165
18270
|
return buildFeedSet(parts, settings.allow, sources);
|
|
18166
18271
|
}
|
|
18167
18272
|
function readFeedCache(path) {
|
|
@@ -21552,18 +21657,18 @@ function isComment(line) {
|
|
|
21552
21657
|
}
|
|
21553
21658
|
function proseLines(lines) {
|
|
21554
21659
|
const inside = /* @__PURE__ */ new Set();
|
|
21555
|
-
let
|
|
21660
|
+
let delimiter2 = null;
|
|
21556
21661
|
lines.forEach((line, index) => {
|
|
21557
|
-
if (
|
|
21662
|
+
if (delimiter2) {
|
|
21558
21663
|
inside.add(index);
|
|
21559
|
-
if (line.includes(
|
|
21664
|
+
if (line.includes(delimiter2)) delimiter2 = null;
|
|
21560
21665
|
return;
|
|
21561
21666
|
}
|
|
21562
21667
|
for (const candidate of ['"""', "'''"]) {
|
|
21563
21668
|
const start = line.indexOf(candidate);
|
|
21564
21669
|
if (start === -1) continue;
|
|
21565
21670
|
if (line.indexOf(candidate, start + candidate.length) !== -1) return;
|
|
21566
|
-
|
|
21671
|
+
delimiter2 = candidate;
|
|
21567
21672
|
inside.add(index);
|
|
21568
21673
|
return;
|
|
21569
21674
|
}
|
|
@@ -22617,6 +22722,679 @@ function evaluateWorkflowRules(text) {
|
|
|
22617
22722
|
return matches.sort((a, b) => a.line - b.line);
|
|
22618
22723
|
}
|
|
22619
22724
|
|
|
22725
|
+
// ../../packages/scan/src/deploy-rules.ts
|
|
22726
|
+
var import_yaml2 = __toESM(require_dist(), 1);
|
|
22727
|
+
|
|
22728
|
+
// ../../packages/scan/src/references.ts
|
|
22729
|
+
var ATTACK_VECTORS_BASE = "https://github.com/profullstack/threatcrush/blob/master/attack-vectors/";
|
|
22730
|
+
function attackVector(slug) {
|
|
22731
|
+
return `${ATTACK_VECTORS_BASE}${slug}.md`;
|
|
22732
|
+
}
|
|
22733
|
+
|
|
22734
|
+
// ../../packages/scan/src/deploy-rules.ts
|
|
22735
|
+
var RULE_LIST2 = [
|
|
22736
|
+
{
|
|
22737
|
+
id: "compose-host-root-mount",
|
|
22738
|
+
title: "Compose service bind-mounts the host root, a home, or an .ssh directory",
|
|
22739
|
+
severity: "critical",
|
|
22740
|
+
confidence: "evidence",
|
|
22741
|
+
cwe: "CWE-250",
|
|
22742
|
+
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.",
|
|
22743
|
+
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.",
|
|
22744
|
+
reference: attackVector("ci-forced-command-compose")
|
|
22745
|
+
},
|
|
22746
|
+
{
|
|
22747
|
+
id: "compose-docker-socket",
|
|
22748
|
+
title: "Compose service mounts the Docker socket",
|
|
22749
|
+
severity: "high",
|
|
22750
|
+
confidence: "evidence",
|
|
22751
|
+
cwe: "CWE-250",
|
|
22752
|
+
consequence: "The Docker API is root on the host: the container can start a new privileged container that mounts `/`.",
|
|
22753
|
+
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.",
|
|
22754
|
+
reference: attackVector("ci-forced-command-compose")
|
|
22755
|
+
},
|
|
22756
|
+
{
|
|
22757
|
+
id: "compose-privileged",
|
|
22758
|
+
title: "Compose service runs privileged or with SYS_ADMIN / ALL capabilities",
|
|
22759
|
+
severity: "high",
|
|
22760
|
+
confidence: "evidence",
|
|
22761
|
+
cwe: "CWE-250",
|
|
22762
|
+
consequence: "A privileged container can mount host devices and load kernel modules: escaping it is routine.",
|
|
22763
|
+
fix: "Drop `privileged: true` and add back only the individual capabilities the service needs.",
|
|
22764
|
+
reference: attackVector("ci-forced-command-compose")
|
|
22765
|
+
},
|
|
22766
|
+
{
|
|
22767
|
+
id: "compose-root-user",
|
|
22768
|
+
title: "Compose service explicitly runs as uid 0",
|
|
22769
|
+
severity: "medium",
|
|
22770
|
+
confidence: "evidence",
|
|
22771
|
+
cwe: "CWE-250",
|
|
22772
|
+
consequence: "Root in the container is root on every host path it mounts. Combined with a bind mount it writes host files as root.",
|
|
22773
|
+
fix: 'Run as an unprivileged uid (`user: "1000:1000"`) and give it ownership of only the paths it writes.',
|
|
22774
|
+
reference: attackVector("ci-forced-command-compose")
|
|
22775
|
+
},
|
|
22776
|
+
{
|
|
22777
|
+
id: "deploy-compose-from-synced-repo",
|
|
22778
|
+
title: "docker compose runs a compose file from a repository checkout on the host",
|
|
22779
|
+
severity: "high",
|
|
22780
|
+
confidence: "contextual",
|
|
22781
|
+
cwe: "CWE-94",
|
|
22782
|
+
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.',
|
|
22783
|
+
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.",
|
|
22784
|
+
reference: attackVector("ci-forced-command-compose")
|
|
22785
|
+
},
|
|
22786
|
+
{
|
|
22787
|
+
id: "deploy-remote-exec-uploaded-script",
|
|
22788
|
+
title: "Script from the repository is uploaded to a host and run there",
|
|
22789
|
+
severity: "high",
|
|
22790
|
+
confidence: "contextual",
|
|
22791
|
+
cwe: "CWE-94",
|
|
22792
|
+
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.",
|
|
22793
|
+
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.',
|
|
22794
|
+
reference: attackVector("ci-forced-command-compose")
|
|
22795
|
+
},
|
|
22796
|
+
{
|
|
22797
|
+
id: "github-app-installation-idor",
|
|
22798
|
+
title: "GitHub App setup callback stores an installation_id from the query string without verifying the user owns it",
|
|
22799
|
+
severity: "high",
|
|
22800
|
+
confidence: "contextual",
|
|
22801
|
+
cwe: "CWE-639",
|
|
22802
|
+
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.",
|
|
22803
|
+
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.",
|
|
22804
|
+
reference: attackVector("github-app-installation-idor")
|
|
22805
|
+
},
|
|
22806
|
+
{
|
|
22807
|
+
id: "authorized-keys-unrestricted",
|
|
22808
|
+
title: "authorized_keys entry with no from=, command= or restrict",
|
|
22809
|
+
severity: "medium",
|
|
22810
|
+
confidence: "evidence",
|
|
22811
|
+
cwe: "CWE-284",
|
|
22812
|
+
consequence: "Whoever holds the private half logs in from anywhere and gets a full shell.",
|
|
22813
|
+
fix: 'Prefix the key with `restrict` and, where possible, `from="<addresses>"` and `command="<script>"` scoped to what it is for.',
|
|
22814
|
+
reference: attackVector("planted-authorized-keys")
|
|
22815
|
+
},
|
|
22816
|
+
{
|
|
22817
|
+
id: "authorized-keys-suspicious-comment",
|
|
22818
|
+
title: "authorized_keys entry named like a temporary CI / diagnostic key",
|
|
22819
|
+
severity: "high",
|
|
22820
|
+
confidence: "contextual",
|
|
22821
|
+
cwe: "CWE-506",
|
|
22822
|
+
consequence: "Intruders plant persistence keys with innocuous dated names (`ci-diag-YYYYMMDD`, `ops-recovery-YYYYMMDD`) and add them to both a user and root.",
|
|
22823
|
+
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.",
|
|
22824
|
+
reference: attackVector("planted-authorized-keys")
|
|
22825
|
+
},
|
|
22826
|
+
{
|
|
22827
|
+
id: "authorized-keys-sftp-unjailed",
|
|
22828
|
+
title: "sftp-only key without a chroot can read the whole filesystem",
|
|
22829
|
+
severity: "medium",
|
|
22830
|
+
confidence: "pattern",
|
|
22831
|
+
cwe: "CWE-552",
|
|
22832
|
+
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.',
|
|
22833
|
+
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.",
|
|
22834
|
+
reference: attackVector("sftp-jail-reads-root")
|
|
22835
|
+
},
|
|
22836
|
+
{
|
|
22837
|
+
id: "sshd-sftp-without-chroot",
|
|
22838
|
+
title: "sshd forces sftp without a ChrootDirectory",
|
|
22839
|
+
severity: "medium",
|
|
22840
|
+
confidence: "pattern",
|
|
22841
|
+
cwe: "CWE-552",
|
|
22842
|
+
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.",
|
|
22843
|
+
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.",
|
|
22844
|
+
reference: attackVector("sftp-jail-reads-root")
|
|
22845
|
+
}
|
|
22846
|
+
];
|
|
22847
|
+
var RULE2 = Object.fromEntries(RULE_LIST2.map((r) => [r.id, r]));
|
|
22848
|
+
function baseName(path) {
|
|
22849
|
+
const p = path.replace(/\\/g, "/");
|
|
22850
|
+
return p.slice(p.lastIndexOf("/") + 1);
|
|
22851
|
+
}
|
|
22852
|
+
function isComposePath(relativePath) {
|
|
22853
|
+
return /^(?:docker-)?compose(?:[.-][\w.-]+)?\.ya?ml$/i.test(baseName(relativePath));
|
|
22854
|
+
}
|
|
22855
|
+
function isAuthorizedKeysPath(relativePath) {
|
|
22856
|
+
return /^authorized_keys2?(?:\.[\w.-]+)?$/.test(baseName(relativePath));
|
|
22857
|
+
}
|
|
22858
|
+
function isSshdConfigPath(relativePath) {
|
|
22859
|
+
const p = relativePath.replace(/\\/g, "/");
|
|
22860
|
+
return baseName(p) === "sshd_config" || /(?:^|\/)sshd_config\.d\/[^/]+\.conf$/.test(p);
|
|
22861
|
+
}
|
|
22862
|
+
var SOURCE_LANGUAGES = ["javascript", "typescript", "python", "ruby", "go", "php", "java"];
|
|
22863
|
+
function evaluateDeployRules(relativePath, text, language, isWorkflow = false) {
|
|
22864
|
+
const out = [];
|
|
22865
|
+
const emit = (id, line, message, severity) => {
|
|
22866
|
+
const rule = RULE2[id];
|
|
22867
|
+
if (out.some((m) => m.rule.id === id && m.line === line)) return;
|
|
22868
|
+
out.push({ rule, line, message, severity: severityFor(severity ?? rule.severity, rule.confidence) });
|
|
22869
|
+
};
|
|
22870
|
+
try {
|
|
22871
|
+
if (isComposePath(relativePath)) composeRules(text, emit);
|
|
22872
|
+
if (isAuthorizedKeysPath(relativePath)) authorizedKeysRules(text, emit);
|
|
22873
|
+
if (isSshdConfigPath(relativePath)) sshdRules(text, emit);
|
|
22874
|
+
if (isWorkflow || language === "shell" || /\bSSH_ORIGINAL_COMMAND\b/.test(text)) {
|
|
22875
|
+
remoteDeployRules(text, isWorkflow, emit);
|
|
22876
|
+
}
|
|
22877
|
+
if (SOURCE_LANGUAGES.includes(language)) githubAppCallbackRule(text, emit);
|
|
22878
|
+
} catch {
|
|
22879
|
+
}
|
|
22880
|
+
return out.sort((a, b) => a.line - b.line);
|
|
22881
|
+
}
|
|
22882
|
+
function yamlGet(map, key) {
|
|
22883
|
+
if (!(0, import_yaml2.isMap)(map)) return void 0;
|
|
22884
|
+
for (const pair of map.items) {
|
|
22885
|
+
if ((0, import_yaml2.isScalar)(pair.key) && String(pair.key.value) === key) return pair.value;
|
|
22886
|
+
}
|
|
22887
|
+
return void 0;
|
|
22888
|
+
}
|
|
22889
|
+
function yamlStr(node) {
|
|
22890
|
+
if (!(0, import_yaml2.isScalar)(node)) return void 0;
|
|
22891
|
+
const v = node.value;
|
|
22892
|
+
return v === null || v === void 0 ? void 0 : String(v);
|
|
22893
|
+
}
|
|
22894
|
+
function volumeSource(spec) {
|
|
22895
|
+
let depth = 0;
|
|
22896
|
+
for (let i = 0; i < spec.length; i++) {
|
|
22897
|
+
const ch = spec[i];
|
|
22898
|
+
if (ch === "{") depth++;
|
|
22899
|
+
else if (ch === "}") depth = Math.max(0, depth - 1);
|
|
22900
|
+
else if (ch === ":" && depth === 0) {
|
|
22901
|
+
if (i === 1 && /^[A-Za-z]$/.test(spec[0]) && /[\\/]/.test(spec[2] ?? "")) continue;
|
|
22902
|
+
return spec.slice(0, i);
|
|
22903
|
+
}
|
|
22904
|
+
}
|
|
22905
|
+
return null;
|
|
22906
|
+
}
|
|
22907
|
+
function isDangerousHostPath(source) {
|
|
22908
|
+
const s = source.trim().replace(/^['"]|['"]$/g, "");
|
|
22909
|
+
const norm = s.replace(/\$\{HOME\}|\$HOME/g, "~").replace(/\/+$/, "") || "/";
|
|
22910
|
+
if (norm === "/" || norm === "~") return true;
|
|
22911
|
+
if (/^\/(?:root|etc|boot)(?:\/|$)/.test(norm)) return true;
|
|
22912
|
+
if (norm === "/home" || /^\/home\/[^/]+$/.test(norm)) return true;
|
|
22913
|
+
if (/(?:^|\/)\.ssh(?:\/|$)/.test(norm)) return true;
|
|
22914
|
+
return false;
|
|
22915
|
+
}
|
|
22916
|
+
function isDockerSocket(source) {
|
|
22917
|
+
return /^(?:\/var)?\/run\/docker\.sock$/.test(source.trim().replace(/^['"]|['"]$/g, ""));
|
|
22918
|
+
}
|
|
22919
|
+
function composeRules(text, emit) {
|
|
22920
|
+
const lc = new import_yaml2.LineCounter();
|
|
22921
|
+
const doc = (0, import_yaml2.parseDocument)(text, { lineCounter: lc, uniqueKeys: false, strict: false });
|
|
22922
|
+
if (doc.errors.length > 0 || !(0, import_yaml2.isMap)(doc.contents)) return;
|
|
22923
|
+
const lineOf = (node) => node?.range ? lc.linePos(node.range[0]).line : 1;
|
|
22924
|
+
const services = yamlGet(doc.contents, "services");
|
|
22925
|
+
if (!(0, import_yaml2.isMap)(services)) return;
|
|
22926
|
+
for (const pair of services.items) {
|
|
22927
|
+
const name = (0, import_yaml2.isScalar)(pair.key) ? String(pair.key.value) : "?";
|
|
22928
|
+
const svc = pair.value;
|
|
22929
|
+
if (!(0, import_yaml2.isMap)(svc)) continue;
|
|
22930
|
+
const userNode = yamlGet(svc, "user");
|
|
22931
|
+
const user = yamlStr(userNode);
|
|
22932
|
+
const runsAsRoot = user !== void 0 && /^(?:0|root)(?::.*)?$/.test(user.trim());
|
|
22933
|
+
if (runsAsRoot) emit("compose-root-user", lineOf(userNode), `Service \`${name}\` sets \`user: ${user}\``);
|
|
22934
|
+
const priv = yamlGet(svc, "privileged");
|
|
22935
|
+
if (priv && /^true$/i.test(yamlStr(priv) ?? "")) {
|
|
22936
|
+
emit("compose-privileged", lineOf(priv), `Service \`${name}\` sets \`privileged: true\``);
|
|
22937
|
+
}
|
|
22938
|
+
const caps = yamlGet(svc, "cap_add");
|
|
22939
|
+
if ((0, import_yaml2.isSeq)(caps)) {
|
|
22940
|
+
for (const item of caps.items) {
|
|
22941
|
+
const cap = (yamlStr(item) ?? "").toUpperCase().replace(/^CAP_/, "");
|
|
22942
|
+
if (cap === "SYS_ADMIN" || cap === "ALL") {
|
|
22943
|
+
emit("compose-privileged", lineOf(item), `Service \`${name}\` adds capability ${cap}`);
|
|
22944
|
+
}
|
|
22945
|
+
}
|
|
22946
|
+
}
|
|
22947
|
+
const volumes = yamlGet(svc, "volumes");
|
|
22948
|
+
if (!(0, import_yaml2.isSeq)(volumes)) continue;
|
|
22949
|
+
for (const item of volumes.items) {
|
|
22950
|
+
let source;
|
|
22951
|
+
let writable = true;
|
|
22952
|
+
if ((0, import_yaml2.isScalar)(item)) {
|
|
22953
|
+
const spec = yamlStr(item) ?? "";
|
|
22954
|
+
source = volumeSource(spec);
|
|
22955
|
+
writable = !/:ro(?:,|$)/.test(spec.slice((source ?? "").length));
|
|
22956
|
+
} else if ((0, import_yaml2.isMap)(item)) {
|
|
22957
|
+
const type = yamlStr(yamlGet(item, "type"));
|
|
22958
|
+
if (type && type !== "bind") continue;
|
|
22959
|
+
source = yamlStr(yamlGet(item, "source"));
|
|
22960
|
+
writable = !/^true$/i.test(yamlStr(yamlGet(item, "read_only")) ?? "");
|
|
22961
|
+
}
|
|
22962
|
+
if (!source) continue;
|
|
22963
|
+
const line = lineOf(item);
|
|
22964
|
+
if (isDockerSocket(source)) {
|
|
22965
|
+
emit("compose-docker-socket", line, `Service \`${name}\` mounts the Docker socket \`${source}\``);
|
|
22966
|
+
} else if (isDangerousHostPath(source)) {
|
|
22967
|
+
const how = writable ? "writable" : "read-only";
|
|
22968
|
+
const asRoot = runsAsRoot ? ", and the service runs as root" : "";
|
|
22969
|
+
emit("compose-host-root-mount", line, `Service \`${name}\` bind-mounts host path \`${source}\` (${how}${asRoot})`);
|
|
22970
|
+
}
|
|
22971
|
+
}
|
|
22972
|
+
}
|
|
22973
|
+
}
|
|
22974
|
+
var KEY_TYPE = /^(?:ssh-(?:rsa|dss|ed25519)|ecdsa-sha2-nistp\d+|sk-(?:ssh-ed25519|ecdsa-sha2-nistp256)@openssh\.com)$/;
|
|
22975
|
+
function parseAuthorizedKeyLines(text) {
|
|
22976
|
+
const out = [];
|
|
22977
|
+
text.split("\n").forEach((raw, idx) => {
|
|
22978
|
+
const line = raw.replace(/\r$/, "").trim();
|
|
22979
|
+
if (!line || line.startsWith("#")) return;
|
|
22980
|
+
let optionText = "";
|
|
22981
|
+
let rest = line;
|
|
22982
|
+
if (!KEY_TYPE.test(line.split(/\s+/, 1)[0] ?? "")) {
|
|
22983
|
+
let inQuote = false;
|
|
22984
|
+
let cut = -1;
|
|
22985
|
+
for (let i = 0; i < line.length; i++) {
|
|
22986
|
+
const ch = line[i];
|
|
22987
|
+
if (ch === "\\" && inQuote) {
|
|
22988
|
+
i++;
|
|
22989
|
+
continue;
|
|
22990
|
+
}
|
|
22991
|
+
if (ch === '"') inQuote = !inQuote;
|
|
22992
|
+
else if (!inQuote && (ch === " " || ch === " ")) {
|
|
22993
|
+
cut = i;
|
|
22994
|
+
break;
|
|
22995
|
+
}
|
|
22996
|
+
}
|
|
22997
|
+
if (cut === -1) return;
|
|
22998
|
+
optionText = line.slice(0, cut);
|
|
22999
|
+
rest = line.slice(cut).trimStart();
|
|
23000
|
+
}
|
|
23001
|
+
const parts = rest.split(/\s+/);
|
|
23002
|
+
if (!KEY_TYPE.test(parts[0] ?? "") || !parts[1]) return;
|
|
23003
|
+
const options = /* @__PURE__ */ new Map();
|
|
23004
|
+
for (const m of optionText.matchAll(/([A-Za-z-]+)(?:="((?:[^"\\]|\\.)*)")?/g)) {
|
|
23005
|
+
options.set(m[1].toLowerCase(), m[2] ?? null);
|
|
23006
|
+
}
|
|
23007
|
+
out.push({ line: idx + 1, type: parts[0], comment: parts.slice(2).join(" "), options });
|
|
23008
|
+
});
|
|
23009
|
+
return out;
|
|
23010
|
+
}
|
|
23011
|
+
function suspiciousKeyComment(comment) {
|
|
23012
|
+
const c = comment.trim();
|
|
23013
|
+
if (!c || c.includes("@")) return false;
|
|
23014
|
+
const role = /(?:^|[-_.\s])(?:ci|cd|diag|diagnostic|debug|tmp|temp|test|recovery|maint|maintenance|support|backdoor)(?=[-_.\s]|\d|$)/i;
|
|
23015
|
+
const date = /(?:^|\D)(?:20\d{2}[-_.]?[01]\d[-_.]?[0-3]\d|[0-3]\d[01]\d20\d{2})(?:\D|$)/;
|
|
23016
|
+
return role.test(c) && date.test(c);
|
|
23017
|
+
}
|
|
23018
|
+
function authorizedKeysRules(text, emit) {
|
|
23019
|
+
for (const key of parseAuthorizedKeyLines(text)) {
|
|
23020
|
+
const label = key.comment ? `"${key.comment}"` : "(no comment)";
|
|
23021
|
+
const restricted = key.options.has("from") || key.options.has("command") || key.options.has("restrict");
|
|
23022
|
+
if (!restricted) emit("authorized-keys-unrestricted", key.line, `Unrestricted ${key.type} key ${label}`);
|
|
23023
|
+
if (suspiciousKeyComment(key.comment)) {
|
|
23024
|
+
emit(
|
|
23025
|
+
"authorized-keys-suspicious-comment",
|
|
23026
|
+
key.line,
|
|
23027
|
+
`Key ${label} is named like a temporary CI/diagnostic key${restricted ? "" : " and is unrestricted"}`
|
|
23028
|
+
);
|
|
23029
|
+
}
|
|
23030
|
+
const command = key.options.get("command") ?? "";
|
|
23031
|
+
if (/\b(?:internal-sftp|sftp-server)\b/.test(command)) {
|
|
23032
|
+
emit("authorized-keys-sftp-unjailed", key.line, `Key ${label} is sftp-only; sftp alone does not limit reads`);
|
|
23033
|
+
}
|
|
23034
|
+
}
|
|
23035
|
+
}
|
|
23036
|
+
function sshdRules(text, emit) {
|
|
23037
|
+
const blocks = [];
|
|
23038
|
+
let current = { forceLine: 0, chroot: false };
|
|
23039
|
+
let globalChroot = false;
|
|
23040
|
+
let inMatch = false;
|
|
23041
|
+
const flush = () => {
|
|
23042
|
+
if (current.forceLine) blocks.push(current);
|
|
23043
|
+
};
|
|
23044
|
+
text.split("\n").forEach((raw, idx) => {
|
|
23045
|
+
const line = raw.replace(/#.*$/, "").trim();
|
|
23046
|
+
if (!line) return;
|
|
23047
|
+
const [keyword = "", ...rest] = line.split(/\s+/);
|
|
23048
|
+
const kw = keyword.toLowerCase();
|
|
23049
|
+
const value = rest.join(" ");
|
|
23050
|
+
if (kw === "match") {
|
|
23051
|
+
flush();
|
|
23052
|
+
current = { forceLine: 0, chroot: false };
|
|
23053
|
+
inMatch = true;
|
|
23054
|
+
return;
|
|
23055
|
+
}
|
|
23056
|
+
if (kw === "chrootdirectory" && value.toLowerCase() !== "none") {
|
|
23057
|
+
current.chroot = true;
|
|
23058
|
+
if (!inMatch) globalChroot = true;
|
|
23059
|
+
}
|
|
23060
|
+
if (kw === "forcecommand" && /\b(?:internal-sftp|sftp-server)\b/.test(value)) current.forceLine = idx + 1;
|
|
23061
|
+
});
|
|
23062
|
+
flush();
|
|
23063
|
+
for (const block of blocks) {
|
|
23064
|
+
if (block.chroot || globalChroot) continue;
|
|
23065
|
+
emit("sshd-sftp-without-chroot", block.forceLine, "ForceCommand sftp with no ChrootDirectory: reads are not confined");
|
|
23066
|
+
}
|
|
23067
|
+
}
|
|
23068
|
+
function segments(text) {
|
|
23069
|
+
const out = [];
|
|
23070
|
+
let quote = null;
|
|
23071
|
+
let cur = "";
|
|
23072
|
+
for (let i = 0; i < text.length; i++) {
|
|
23073
|
+
const ch = text[i];
|
|
23074
|
+
if (quote) {
|
|
23075
|
+
if (ch === "\\" && quote === '"') {
|
|
23076
|
+
cur += ch + (text[i + 1] ?? "");
|
|
23077
|
+
i++;
|
|
23078
|
+
continue;
|
|
23079
|
+
}
|
|
23080
|
+
if (ch === quote) quote = null;
|
|
23081
|
+
cur += ch;
|
|
23082
|
+
continue;
|
|
23083
|
+
}
|
|
23084
|
+
if (ch === "'" || ch === '"') {
|
|
23085
|
+
quote = ch;
|
|
23086
|
+
cur += ch;
|
|
23087
|
+
continue;
|
|
23088
|
+
}
|
|
23089
|
+
if (ch === ";" || ch === "|" || ch === "&" && text[i + 1] === "&") {
|
|
23090
|
+
out.push(cur);
|
|
23091
|
+
cur = "";
|
|
23092
|
+
if (text[i + 1] === ch) i++;
|
|
23093
|
+
continue;
|
|
23094
|
+
}
|
|
23095
|
+
cur += ch;
|
|
23096
|
+
}
|
|
23097
|
+
out.push(cur);
|
|
23098
|
+
return out.map((s) => s.trim()).filter(Boolean);
|
|
23099
|
+
}
|
|
23100
|
+
function shellWords(text) {
|
|
23101
|
+
const out = [];
|
|
23102
|
+
let quote = null;
|
|
23103
|
+
let cur = "";
|
|
23104
|
+
for (let i = 0; i < text.length; i++) {
|
|
23105
|
+
const ch = text[i];
|
|
23106
|
+
if (quote) {
|
|
23107
|
+
if (ch === quote) quote = null;
|
|
23108
|
+
cur += ch;
|
|
23109
|
+
continue;
|
|
23110
|
+
}
|
|
23111
|
+
if (ch === "'" || ch === '"') {
|
|
23112
|
+
quote = ch;
|
|
23113
|
+
cur += ch;
|
|
23114
|
+
continue;
|
|
23115
|
+
}
|
|
23116
|
+
if (ch === " " || ch === " ") {
|
|
23117
|
+
if (cur) out.push(cur);
|
|
23118
|
+
cur = "";
|
|
23119
|
+
continue;
|
|
23120
|
+
}
|
|
23121
|
+
cur += ch;
|
|
23122
|
+
}
|
|
23123
|
+
if (cur) out.push(cur);
|
|
23124
|
+
return out;
|
|
23125
|
+
}
|
|
23126
|
+
function unquote2(word) {
|
|
23127
|
+
if (word.length >= 2 && (word[0] === '"' || word[0] === "'") && word[word.length - 1] === word[0]) {
|
|
23128
|
+
return word.slice(1, -1);
|
|
23129
|
+
}
|
|
23130
|
+
return word;
|
|
23131
|
+
}
|
|
23132
|
+
var WRAPPERS2 = /* @__PURE__ */ new Set(["sudo", "exec", "command", "nohup", "time", "env", "timeout", "doas"]);
|
|
23133
|
+
function commandOf(segment) {
|
|
23134
|
+
const words3 = shellWords(segment.replace(/^[-\s]*(?:run|script|command):\s*[|>]?[-+]?\s*/, ""));
|
|
23135
|
+
let i = 0;
|
|
23136
|
+
while (i < words3.length) {
|
|
23137
|
+
const w = words3[i];
|
|
23138
|
+
if (/^[A-Za-z_]\w*=/.test(w) || WRAPPERS2.has(w)) {
|
|
23139
|
+
i++;
|
|
23140
|
+
continue;
|
|
23141
|
+
}
|
|
23142
|
+
if (words3[i - 1] === "sudo" && w.startsWith("-")) {
|
|
23143
|
+
i++;
|
|
23144
|
+
continue;
|
|
23145
|
+
}
|
|
23146
|
+
break;
|
|
23147
|
+
}
|
|
23148
|
+
return words3.slice(i);
|
|
23149
|
+
}
|
|
23150
|
+
var SSH_VALUE_OPTS2 = new Set("BbcDEeFIiJLlmOoPpQRSWw".split(""));
|
|
23151
|
+
function sshRemoteCommand(words3) {
|
|
23152
|
+
let i = 1;
|
|
23153
|
+
while (i < words3.length && words3[i].startsWith("-")) {
|
|
23154
|
+
const opt = words3[i];
|
|
23155
|
+
const letter = opt[opt.length - 1];
|
|
23156
|
+
i += opt.length === 2 && SSH_VALUE_OPTS2.has(letter) ? 2 : 1;
|
|
23157
|
+
}
|
|
23158
|
+
i++;
|
|
23159
|
+
if (i >= words3.length) return null;
|
|
23160
|
+
const rest = words3.slice(i).filter((w) => !w.startsWith("<"));
|
|
23161
|
+
if (rest.length === 0) return null;
|
|
23162
|
+
return rest.length === 1 ? unquote2(rest[0]) : rest.map(unquote2).join(" ");
|
|
23163
|
+
}
|
|
23164
|
+
function transferDestination(words3) {
|
|
23165
|
+
for (let i = words3.length - 1; i > 0; i--) {
|
|
23166
|
+
const w = unquote2(words3[i]);
|
|
23167
|
+
if (w.startsWith("-")) continue;
|
|
23168
|
+
const m = /^(?:[\w.${}-]+@)?[\w.${}-]+:(.*)$/.exec(w);
|
|
23169
|
+
if (m && !w.includes("://")) return m[1] || "~";
|
|
23170
|
+
return null;
|
|
23171
|
+
}
|
|
23172
|
+
return null;
|
|
23173
|
+
}
|
|
23174
|
+
function rsyncServerDestination(words3) {
|
|
23175
|
+
if (!words3.includes("--server")) return null;
|
|
23176
|
+
const last = words3[words3.length - 1];
|
|
23177
|
+
return last && !last.startsWith("-") ? unquote2(last) : null;
|
|
23178
|
+
}
|
|
23179
|
+
function normDir(path) {
|
|
23180
|
+
return path.replace(/\/\*+$/, "").replace(/\/+$/, "") || "/";
|
|
23181
|
+
}
|
|
23182
|
+
function joinPath(cwd, path) {
|
|
23183
|
+
if (path.startsWith("/") || path.startsWith("~") || path.startsWith("$")) return path;
|
|
23184
|
+
const clean2 = path.replace(/^\.\//, "");
|
|
23185
|
+
return cwd ? `${normDir(cwd)}/${clean2}` : clean2;
|
|
23186
|
+
}
|
|
23187
|
+
function under(path, dirs) {
|
|
23188
|
+
const p = normDir(path);
|
|
23189
|
+
for (const d of dirs) {
|
|
23190
|
+
const dir = normDir(d);
|
|
23191
|
+
if (dir === "~" || dir === "." || dir === "/") continue;
|
|
23192
|
+
if (p === dir || p.startsWith(`${dir}/`)) return dir;
|
|
23193
|
+
const fixed = dir.split(/[*$]/)[0];
|
|
23194
|
+
if (fixed.length > 1 && fixed !== dir && p.startsWith(fixed)) return dir;
|
|
23195
|
+
}
|
|
23196
|
+
return null;
|
|
23197
|
+
}
|
|
23198
|
+
var COMPOSE = /\bdocker(?:-compose|\s+compose)\b/;
|
|
23199
|
+
var COMPOSE_FILE = /(?:^|\s)(?:-f|--file)(?:=|\s+)['"]?([^\s'";|&]+)/;
|
|
23200
|
+
function remoteSegment(segment, line, state, emit) {
|
|
23201
|
+
const words3 = commandOf(segment);
|
|
23202
|
+
const cmd = words3[0] ?? "";
|
|
23203
|
+
if (cmd === "cd" && words3[1]) {
|
|
23204
|
+
state.cwd = joinPath(state.cwd, unquote2(words3[1]));
|
|
23205
|
+
return;
|
|
23206
|
+
}
|
|
23207
|
+
if (cmd === "git" && /^(?:pull|clone|fetch|checkout|reset)$/.test(words3[1] ?? "")) {
|
|
23208
|
+
if (words3[1] === "clone" && words3.length > 3) state.gitDirs.add(joinPath(state.cwd, unquote2(words3[words3.length - 1])));
|
|
23209
|
+
else if (state.cwd) state.gitDirs.add(state.cwd);
|
|
23210
|
+
return;
|
|
23211
|
+
}
|
|
23212
|
+
if (cmd === "rsync") {
|
|
23213
|
+
const dest = rsyncServerDestination(words3);
|
|
23214
|
+
if (dest) state.uploads.add(dest);
|
|
23215
|
+
return;
|
|
23216
|
+
}
|
|
23217
|
+
if (COMPOSE.test(segment)) {
|
|
23218
|
+
const file = COMPOSE_FILE.exec(segment)?.[1];
|
|
23219
|
+
const target = file ? joinPath(state.cwd, file) : state.cwd;
|
|
23220
|
+
const synced = target ? under(target, state.uploads) : null;
|
|
23221
|
+
const pulled = target ? under(target, state.gitDirs) : null;
|
|
23222
|
+
const forcedWithRsync = state.forced && state.uploads.size > 0 && Boolean(file);
|
|
23223
|
+
if (synced || pulled || forcedWithRsync) {
|
|
23224
|
+
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";
|
|
23225
|
+
const build = /\s--build\b|\sbuild\b/.test(segment) ? " and builds from it" : "";
|
|
23226
|
+
emit(
|
|
23227
|
+
"deploy-compose-from-synced-repo",
|
|
23228
|
+
line,
|
|
23229
|
+
`\`docker compose\` runs ${file ? `\`${file}\`` : "the compose file in the working directory"} ${where}${build}`
|
|
23230
|
+
);
|
|
23231
|
+
}
|
|
23232
|
+
return;
|
|
23233
|
+
}
|
|
23234
|
+
let script;
|
|
23235
|
+
if (/^(?:ba|z|da|k)?sh$|^source$|^\.$/.test(cmd) && words3[1] && !words3[1].startsWith("-")) script = unquote2(words3[1]);
|
|
23236
|
+
else if (/\.(?:sh|bash|py|rb|pl)$/.test(cmd) || cmd.startsWith("./")) script = cmd;
|
|
23237
|
+
if (script) {
|
|
23238
|
+
const path = joinPath(state.cwd, script);
|
|
23239
|
+
const dir = under(path, state.uploads);
|
|
23240
|
+
if (dir) {
|
|
23241
|
+
emit("deploy-remote-exec-uploaded-script", line, `Runs \`${script}\` on the host from \`${dir}\`, which this file uploads to`);
|
|
23242
|
+
}
|
|
23243
|
+
}
|
|
23244
|
+
}
|
|
23245
|
+
function logicalLines2(text) {
|
|
23246
|
+
const raw = text.split("\n");
|
|
23247
|
+
const out = [];
|
|
23248
|
+
for (let i = 0; i < raw.length; i++) {
|
|
23249
|
+
let t = raw[i];
|
|
23250
|
+
const start = i + 1;
|
|
23251
|
+
while (/\\\s*$/.test(t) && i + 1 < raw.length) {
|
|
23252
|
+
t = t.replace(/\\\s*$/, " ") + raw[++i].trim();
|
|
23253
|
+
}
|
|
23254
|
+
out.push({ text: t, line: start });
|
|
23255
|
+
}
|
|
23256
|
+
return out;
|
|
23257
|
+
}
|
|
23258
|
+
function isCommentLine(text) {
|
|
23259
|
+
return /^\s*#/.test(text);
|
|
23260
|
+
}
|
|
23261
|
+
function remoteDeployRules(text, isWorkflow, emit) {
|
|
23262
|
+
const forced = /\bSSH_ORIGINAL_COMMAND\b/.test(text);
|
|
23263
|
+
const lines = logicalLines2(text);
|
|
23264
|
+
const uploads = /* @__PURE__ */ new Set();
|
|
23265
|
+
let sawScpAction = false;
|
|
23266
|
+
for (const { text: t } of lines) {
|
|
23267
|
+
if (isCommentLine(t)) continue;
|
|
23268
|
+
for (const seg of segments(t)) {
|
|
23269
|
+
const words3 = commandOf(seg);
|
|
23270
|
+
if (words3[0] === "rsync" || words3[0] === "scp") {
|
|
23271
|
+
const dest = transferDestination(words3) ?? rsyncServerDestination(words3);
|
|
23272
|
+
if (dest) uploads.add(dest);
|
|
23273
|
+
}
|
|
23274
|
+
}
|
|
23275
|
+
if (isWorkflow) {
|
|
23276
|
+
if (/uses:\s*['"]?appleboy\/scp-action@/.test(t)) sawScpAction = true;
|
|
23277
|
+
const target = /^\s*target:\s*['"]?([^'"\s]+)/.exec(t);
|
|
23278
|
+
if (target && sawScpAction) {
|
|
23279
|
+
uploads.add(target[1]);
|
|
23280
|
+
sawScpAction = false;
|
|
23281
|
+
}
|
|
23282
|
+
}
|
|
23283
|
+
if (forced) {
|
|
23284
|
+
const allowed = /rsync(?:\\?\s)+--server[^)\n]*?\s(\/[^\s)"'*]+)/.exec(t);
|
|
23285
|
+
if (allowed) uploads.add(allowed[1]);
|
|
23286
|
+
}
|
|
23287
|
+
}
|
|
23288
|
+
const fresh = () => ({ cwd: null, uploads, gitDirs: /* @__PURE__ */ new Set(), forced });
|
|
23289
|
+
let heredoc = null;
|
|
23290
|
+
let actionScript = null;
|
|
23291
|
+
let sawSshAction = false;
|
|
23292
|
+
const forcedState = fresh();
|
|
23293
|
+
for (const { text: t, line } of lines) {
|
|
23294
|
+
if (heredoc) {
|
|
23295
|
+
if (t.trim() === heredoc.end) {
|
|
23296
|
+
heredoc = null;
|
|
23297
|
+
continue;
|
|
23298
|
+
}
|
|
23299
|
+
if (!isCommentLine(t)) for (const seg of segments(t)) remoteSegment(seg, line, heredoc.state, emit);
|
|
23300
|
+
continue;
|
|
23301
|
+
}
|
|
23302
|
+
if (actionScript) {
|
|
23303
|
+
const indent = /^\s*/.exec(t)[0].length;
|
|
23304
|
+
if (t.trim() && indent <= actionScript.indent) actionScript = null;
|
|
23305
|
+
else {
|
|
23306
|
+
if (!isCommentLine(t)) for (const seg of segments(t)) remoteSegment(seg, line, actionScript.state, emit);
|
|
23307
|
+
continue;
|
|
23308
|
+
}
|
|
23309
|
+
}
|
|
23310
|
+
if (isCommentLine(t)) continue;
|
|
23311
|
+
if (isWorkflow) {
|
|
23312
|
+
if (/uses:\s*['"]?appleboy\/ssh-action@/.test(t)) sawSshAction = true;
|
|
23313
|
+
const script = /^(\s*)script:\s*[|>]?[-+]?\s*$/.exec(t);
|
|
23314
|
+
if (script && sawSshAction) {
|
|
23315
|
+
actionScript = { indent: script[1].length, state: fresh() };
|
|
23316
|
+
sawSshAction = false;
|
|
23317
|
+
continue;
|
|
23318
|
+
}
|
|
23319
|
+
}
|
|
23320
|
+
if (forced) {
|
|
23321
|
+
const body = t.replace(/^\s*[^()]*\)\s*/, "").replace(/;;\s*$/, "");
|
|
23322
|
+
for (const seg of segments(body)) remoteSegment(seg, line, forcedState, emit);
|
|
23323
|
+
continue;
|
|
23324
|
+
}
|
|
23325
|
+
for (const seg of segments(t)) {
|
|
23326
|
+
const words3 = commandOf(seg);
|
|
23327
|
+
if (words3[0] !== "ssh") continue;
|
|
23328
|
+
const piped = /(?:^|\s)(?:ba|z)?sh\s+-s\b[^<]*<(?!<)\s*['"]?([^\s'"<]+)/.exec(seg);
|
|
23329
|
+
if (piped) {
|
|
23330
|
+
emit("deploy-remote-exec-uploaded-script", line, `Pipes repository script \`${piped[1]}\` into a remote shell`);
|
|
23331
|
+
continue;
|
|
23332
|
+
}
|
|
23333
|
+
const here = /<<-?\s*['"]?(\w+)['"]?/.exec(seg);
|
|
23334
|
+
if (here) {
|
|
23335
|
+
heredoc = { end: here[1], state: fresh() };
|
|
23336
|
+
continue;
|
|
23337
|
+
}
|
|
23338
|
+
const remote = sshRemoteCommand(words3);
|
|
23339
|
+
if (!remote) continue;
|
|
23340
|
+
const state = fresh();
|
|
23341
|
+
for (const inner of segments(remote)) remoteSegment(inner, line, state, emit);
|
|
23342
|
+
}
|
|
23343
|
+
}
|
|
23344
|
+
}
|
|
23345
|
+
var INSTALLATION_FROM_QUERY = new RegExp(
|
|
23346
|
+
[
|
|
23347
|
+
String.raw`searchParams\.get\(\s*['"]installation_id['"]`,
|
|
23348
|
+
String.raw`\b(?:req|request|ctx|context)\.(?:query|params)(?:\.installation_id\b|\[\s*['"]installation_id['"])`,
|
|
23349
|
+
String.raw`\bquery\.installation_id\b`,
|
|
23350
|
+
String.raw`\bquery\[\s*['"]installation_id['"]\s*\]`,
|
|
23351
|
+
String.raw`\breq\.query\(\s*['"]installation_id['"]`,
|
|
23352
|
+
String.raw`request\.(?:args|GET|query_params)(?:\.get\(\s*|\[\s*)['"]installation_id['"]`,
|
|
23353
|
+
String.raw`\bparams\[\s*:installation_id\s*\]`,
|
|
23354
|
+
String.raw`\$_(?:GET|REQUEST)\[\s*['"]installation_id['"]`,
|
|
23355
|
+
String.raw`Query\(\)\.Get\(\s*"installation_id"`,
|
|
23356
|
+
String.raw`getParameter\(\s*"installation_id"`,
|
|
23357
|
+
String.raw`\{[^}]*\binstallation_id\b[^}]*\}\s*=\s*(?:await\s+)?(?:req|request|ctx)\.query\b`
|
|
23358
|
+
].join("|")
|
|
23359
|
+
);
|
|
23360
|
+
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;
|
|
23361
|
+
var VERIFIES_USER = /\/user\/installations|listInstallationsForAuthenticatedUser|(?:verify|check|assert|ensure|validate|confirm)\w*Installation\w*\s*\(|installationBelongsTo\w*\s*\(|userCanAccessInstallation\s*\(/;
|
|
23362
|
+
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/;
|
|
23363
|
+
function githubAppCallbackRule(text, emit) {
|
|
23364
|
+
if (!text.includes("installation_id") || !INSTALLATION_FROM_QUERY.test(text)) return;
|
|
23365
|
+
const lines = text.split("\n");
|
|
23366
|
+
const chunks = [];
|
|
23367
|
+
let start = 0;
|
|
23368
|
+
for (let i = 1; i < lines.length; i++) {
|
|
23369
|
+
if (DECLARATION.test(lines[i])) {
|
|
23370
|
+
chunks.push({ start, end: i });
|
|
23371
|
+
start = i;
|
|
23372
|
+
}
|
|
23373
|
+
}
|
|
23374
|
+
chunks.push({ start, end: lines.length });
|
|
23375
|
+
const verifyingHelpers = /* @__PURE__ */ new Set();
|
|
23376
|
+
for (const c of chunks) {
|
|
23377
|
+
const body = lines.slice(c.start, c.end).join("\n");
|
|
23378
|
+
if (!VERIFIES_USER.test(body)) continue;
|
|
23379
|
+
const name = /(?:function\s+|(?:const|let|var)\s+|def\s+|func\s+)(\w+)/.exec(lines[c.start] ?? "")?.[1];
|
|
23380
|
+
if (name) verifyingHelpers.add(name);
|
|
23381
|
+
}
|
|
23382
|
+
for (const c of chunks) {
|
|
23383
|
+
const chunkLines = lines.slice(c.start, c.end);
|
|
23384
|
+
const body = chunkLines.join("\n");
|
|
23385
|
+
const readAt = chunkLines.findIndex((l) => INSTALLATION_FROM_QUERY.test(l) && !/^\s*(?:\/\/|#|\*)/.test(l));
|
|
23386
|
+
if (readAt === -1) continue;
|
|
23387
|
+
if (!PERSISTS.test(body)) continue;
|
|
23388
|
+
if (VERIFIES_USER.test(body)) continue;
|
|
23389
|
+
if ([...verifyingHelpers].some((name) => new RegExp(`\\b${name}\\s*\\(`).test(body))) continue;
|
|
23390
|
+
emit(
|
|
23391
|
+
"github-app-installation-idor",
|
|
23392
|
+
c.start + readAt + 1,
|
|
23393
|
+
"`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`)"
|
|
23394
|
+
);
|
|
23395
|
+
}
|
|
23396
|
+
}
|
|
23397
|
+
|
|
22620
23398
|
// ../../packages/scan/src/controls.ts
|
|
22621
23399
|
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
23400
|
var SECURITY_CONTROLS = [
|
|
@@ -23016,11 +23794,28 @@ var SECRET_RULES = [
|
|
|
23016
23794
|
{
|
|
23017
23795
|
id: "secret-private-key",
|
|
23018
23796
|
name: "Private Key",
|
|
23019
|
-
pattern: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY(?: BLOCK)?-----/,
|
|
23797
|
+
pattern: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----/,
|
|
23020
23798
|
severity: "critical",
|
|
23021
23799
|
cwe: "CWE-798",
|
|
23022
23800
|
consequence: "Key material, committed. Rotation is the only remediation.",
|
|
23023
|
-
confirm: (lines, index, match) => hasPemBody(lines, index, match)
|
|
23801
|
+
confirm: (lines, index, match) => hasPemBody(lines, index, match),
|
|
23802
|
+
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.",
|
|
23803
|
+
reference: attackVector("unrotated-github-app-keys")
|
|
23804
|
+
},
|
|
23805
|
+
{
|
|
23806
|
+
id: "secret-github-app-private-key",
|
|
23807
|
+
name: "GitHub App Private Key",
|
|
23808
|
+
// The same banner, confirmed by an App id in the same file. That pairing is
|
|
23809
|
+
// everything needed to mint installation tokens for every org the App is
|
|
23810
|
+
// installed in, which is why it outranks a bare private key.
|
|
23811
|
+
pattern: /-----BEGIN (?:RSA |ENCRYPTED )?PRIVATE KEY-----/,
|
|
23812
|
+
severity: "critical",
|
|
23813
|
+
cwe: "CWE-798",
|
|
23814
|
+
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.",
|
|
23815
|
+
confirm: (lines, index, match) => hasPemBody(lines, index, match) && hasGithubAppId(lines),
|
|
23816
|
+
supersedes: ["secret-private-key"],
|
|
23817
|
+
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.",
|
|
23818
|
+
reference: attackVector("unrotated-github-app-keys")
|
|
23024
23819
|
},
|
|
23025
23820
|
{
|
|
23026
23821
|
id: "secret-slack-token",
|
|
@@ -23088,6 +23883,28 @@ var SECRET_RULES = [
|
|
|
23088
23883
|
cwe: "CWE-798",
|
|
23089
23884
|
consequence: "Direct database access, usually bypassing every application-level authorisation check."
|
|
23090
23885
|
},
|
|
23886
|
+
{
|
|
23887
|
+
id: "secret-resend-key",
|
|
23888
|
+
name: "Resend API Key",
|
|
23889
|
+
pattern: /\bre_[A-Za-z0-9]{8}_[A-Za-z0-9]{16,}\b/,
|
|
23890
|
+
severity: "critical",
|
|
23891
|
+
cwe: "CWE-798",
|
|
23892
|
+
consequence: "Send mail as every verified domain on the account."
|
|
23893
|
+
},
|
|
23894
|
+
{
|
|
23895
|
+
id: "secret-supabase-service-role",
|
|
23896
|
+
name: "Supabase service-role key",
|
|
23897
|
+
// A JWT whose payload claims `role: service_role`. Decoded rather than
|
|
23898
|
+
// guessed from the variable name: the anon key has the same shape and is
|
|
23899
|
+
// public by design.
|
|
23900
|
+
pattern: /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{16,}/,
|
|
23901
|
+
severity: "critical",
|
|
23902
|
+
cwe: "CWE-798",
|
|
23903
|
+
consequence: "Bypasses every row-level security policy: full read and write on the project database.",
|
|
23904
|
+
confirm: (_lines, _index, match) => jwtClaimsRole(match[0], "service_role"),
|
|
23905
|
+
supersedes: ["secret-jwt", "secret-generic-high-entropy"],
|
|
23906
|
+
fix: "Rotate the JWT secret (which reissues both keys) and keep the service-role key server-side only."
|
|
23907
|
+
},
|
|
23091
23908
|
{
|
|
23092
23909
|
id: "secret-jwt",
|
|
23093
23910
|
name: "JSON Web Token",
|
|
@@ -23118,6 +23935,26 @@ var SECRET_RULES = [
|
|
|
23118
23935
|
consequence: "A password in source is a password in every clone, fork and CI cache of that source.",
|
|
23119
23936
|
keywordShaped: true
|
|
23120
23937
|
},
|
|
23938
|
+
{
|
|
23939
|
+
id: "secret-generic-high-entropy",
|
|
23940
|
+
name: "High-entropy secret in a *_SECRET / *_PRIVATE_KEY / *_TOKEN variable",
|
|
23941
|
+
// The unquoted `.env` assignment the quoted-only generic rules above leave
|
|
23942
|
+
// alone. Safe to key on the name only because the value must also look
|
|
23943
|
+
// like key material: long, mixed-class and high-entropy (see
|
|
23944
|
+
// `looksLikeKeyMaterial`). An ARN or a parameter-store path fails that,
|
|
23945
|
+
// which is what keeps the header's two counter-examples quiet. All-hex
|
|
23946
|
+
// values belong to `secret-hex-token` and are left to it.
|
|
23947
|
+
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*$/,
|
|
23948
|
+
severity: "high",
|
|
23949
|
+
cwe: "CWE-798",
|
|
23950
|
+
consequence: "Whatever the variable unlocks, in every clone, backup and image layer that carries this file.",
|
|
23951
|
+
keywordShaped: true,
|
|
23952
|
+
yieldsToVendorRules: true,
|
|
23953
|
+
confirm: (_lines, _index, match) => looksLikeKeyMaterial(match[1] ?? ""),
|
|
23954
|
+
supersedes: ["secret-jwt"],
|
|
23955
|
+
fix: "Rotate the value, then load it from a secret manager or the deploy environment instead of a committed file.",
|
|
23956
|
+
reference: attackVector("unrotated-github-app-keys")
|
|
23957
|
+
},
|
|
23121
23958
|
{
|
|
23122
23959
|
id: "secret-hex-token",
|
|
23123
23960
|
name: "High-entropy Hex Token",
|
|
@@ -23181,10 +24018,44 @@ function hasPemBody(lines, index, match) {
|
|
|
23181
24018
|
}
|
|
23182
24019
|
return false;
|
|
23183
24020
|
}
|
|
23184
|
-
|
|
23185
|
-
|
|
23186
|
-
|
|
23187
|
-
|
|
24021
|
+
var GITHUB_APP_ID = /\b(?:GITHUB_APP_ID|GH_APP_ID|APP_ID|app_id|appId)\b['"]?\s*[=:]\s*['"]?\d{2,}/;
|
|
24022
|
+
function hasGithubAppId(lines) {
|
|
24023
|
+
return lines.some((line) => GITHUB_APP_ID.test(line));
|
|
24024
|
+
}
|
|
24025
|
+
function jwtClaimsRole(token, role) {
|
|
24026
|
+
const payload = token.split(".")[1];
|
|
24027
|
+
if (!payload) return false;
|
|
24028
|
+
try {
|
|
24029
|
+
const b64 = payload.replace(/-/g, "+").replace(/_/g, "/");
|
|
24030
|
+
const json = JSON.parse(atob(b64 + "=".repeat((4 - b64.length % 4) % 4)));
|
|
24031
|
+
return json.role === role;
|
|
24032
|
+
} catch {
|
|
24033
|
+
return false;
|
|
24034
|
+
}
|
|
24035
|
+
}
|
|
24036
|
+
function shannonEntropy(value) {
|
|
24037
|
+
if (!value) return 0;
|
|
24038
|
+
const counts = /* @__PURE__ */ new Map();
|
|
24039
|
+
for (const ch of value) counts.set(ch, (counts.get(ch) ?? 0) + 1);
|
|
24040
|
+
let bits = 0;
|
|
24041
|
+
for (const n of counts.values()) {
|
|
24042
|
+
const p = n / value.length;
|
|
24043
|
+
bits -= p * Math.log2(p);
|
|
24044
|
+
}
|
|
24045
|
+
return bits;
|
|
24046
|
+
}
|
|
24047
|
+
function looksLikeKeyMaterial(value) {
|
|
24048
|
+
if (value.length < 20) return false;
|
|
24049
|
+
if (value.startsWith("/") || value.includes("://")) return false;
|
|
24050
|
+
if (/^[0-9a-f]+$/i.test(value)) return false;
|
|
24051
|
+
const classes = [/[a-z]/, /[A-Z]/, /[0-9]/].filter((re) => re.test(value)).length;
|
|
24052
|
+
if (classes < 2) return false;
|
|
24053
|
+
return shannonEntropy(value) >= 3.5;
|
|
24054
|
+
}
|
|
24055
|
+
function isPlaceholderAttribute(line, value) {
|
|
24056
|
+
const at = line.lastIndexOf(value);
|
|
24057
|
+
if (at === -1) return false;
|
|
24058
|
+
return /(?:^|\s)(?:aria-)?placeholder\s*=\s*[{("'`]*$/i.test(line.slice(0, at));
|
|
23188
24059
|
}
|
|
23189
24060
|
function isVariableReference(value) {
|
|
23190
24061
|
const trimmed = value.trim();
|
|
@@ -23243,13 +24114,28 @@ function redactSecret(line) {
|
|
|
23243
24114
|
return `${match.slice(0, 3)}${"*".repeat(Math.min(16, match.length - 3))}`;
|
|
23244
24115
|
});
|
|
23245
24116
|
}
|
|
24117
|
+
function isEnvFileName(filename) {
|
|
24118
|
+
const name = filename.toLowerCase();
|
|
24119
|
+
if (/\.(?:example|sample|template|dist|defaults?)$/.test(name)) return false;
|
|
24120
|
+
return /^\.env(?:\..*)?$/.test(name) || /\.env$/.test(name) || isEnvBackupName(name);
|
|
24121
|
+
}
|
|
24122
|
+
function isEnvBackupName(filename) {
|
|
24123
|
+
return /(?:^|\.)env\.(?:bak|old|orig|save|backup|prev|swp)(?:[.~_-].*)?$/i.test(filename) || /\.env~$/i.test(filename);
|
|
24124
|
+
}
|
|
23246
24125
|
var SENSITIVE_FILES = [
|
|
24126
|
+
{
|
|
24127
|
+
pattern: ".env.bak",
|
|
24128
|
+
test: isEnvBackupName,
|
|
24129
|
+
message: "Backup copy of an environment file committed: backups are never rotated with the original",
|
|
24130
|
+
severity: "critical"
|
|
24131
|
+
},
|
|
23247
24132
|
{ pattern: ".env", message: "Environment file committed \u2014 the usual home of every runtime credential", severity: "high" },
|
|
23248
24133
|
{ pattern: ".env.local", message: "Local environment file committed", severity: "high" },
|
|
23249
24134
|
{ pattern: ".env.production", message: "Production environment file committed", severity: "critical" },
|
|
23250
24135
|
{ pattern: "id_rsa", message: "Private SSH key committed", severity: "critical" },
|
|
23251
24136
|
{ pattern: "id_ed25519", message: "Private SSH key committed", severity: "critical" },
|
|
23252
24137
|
{ pattern: "id_ecdsa", message: "Private SSH key committed", severity: "critical" },
|
|
24138
|
+
{ pattern: "id_dsa", message: "Private SSH key committed", severity: "critical" },
|
|
23253
24139
|
{ pattern: ".pem", message: "PEM certificate or key file committed", severity: "high" },
|
|
23254
24140
|
{ pattern: ".p12", message: "PKCS#12 keystore committed", severity: "high" },
|
|
23255
24141
|
{ pattern: ".pfx", message: "PKCS#12 keystore committed", severity: "high" },
|
|
@@ -23623,11 +24509,19 @@ function scanText(relativePath, text, language = languageOf(relativePath)) {
|
|
|
23623
24509
|
const inDocs = isDocPath(relativePath);
|
|
23624
24510
|
const inlineTests = inlineTestLines(relativePath, lines);
|
|
23625
24511
|
lines.forEach((line, index) => {
|
|
24512
|
+
const lineMatches = [];
|
|
23626
24513
|
for (const rule of SECRET_RULES) {
|
|
23627
24514
|
const match = rule.pattern.exec(line);
|
|
23628
24515
|
if (!match) continue;
|
|
23629
24516
|
if (isKnownPlaceholder(match[0])) continue;
|
|
23630
24517
|
if (rule.confirm && !rule.confirm(lines, index, match)) continue;
|
|
24518
|
+
lineMatches.push({ rule, match });
|
|
24519
|
+
}
|
|
24520
|
+
const superseded = new Set(lineMatches.flatMap(({ rule }) => rule.supersedes ?? []));
|
|
24521
|
+
const vendorMatched = lineMatches.some(({ rule }) => !rule.keywordShaped);
|
|
24522
|
+
for (const { rule, match } of lineMatches) {
|
|
24523
|
+
if (superseded.has(rule.id)) continue;
|
|
24524
|
+
if (rule.yieldsToVendorRules && vendorMatched) continue;
|
|
23631
24525
|
if (isSuppressed(suppressions, index, rule.id)) continue;
|
|
23632
24526
|
const value = match[1] ?? match[0];
|
|
23633
24527
|
if (isVariableReference(value)) continue;
|
|
@@ -23653,6 +24547,8 @@ function scanText(relativePath, text, language = languageOf(relativePath)) {
|
|
|
23653
24547
|
confidence: "evidence",
|
|
23654
24548
|
message: soft ? `Possible ${rule.name} detected ${SECRET_SOFTENING[soft]}` : `Possible ${rule.name} detected`,
|
|
23655
24549
|
consequence: rule.consequence,
|
|
24550
|
+
...rule.fix ? { fix: rule.fix } : {},
|
|
24551
|
+
...rule.reference ? { reference: rule.reference } : {},
|
|
23656
24552
|
cwe: rule.cwe,
|
|
23657
24553
|
excerpt: redactSecret(line.trim()).slice(0, 200),
|
|
23658
24554
|
sensitive: true,
|
|
@@ -23710,7 +24606,8 @@ function scanText(relativePath, text, language = languageOf(relativePath)) {
|
|
|
23710
24606
|
category: "code"
|
|
23711
24607
|
});
|
|
23712
24608
|
}
|
|
23713
|
-
|
|
24609
|
+
const isWorkflow = isWorkflowPath(relativePath, text);
|
|
24610
|
+
if (isWorkflow) {
|
|
23714
24611
|
for (const match of evaluateWorkflowRules(text)) {
|
|
23715
24612
|
const index = match.line - 1;
|
|
23716
24613
|
if (isSuppressed(suppressions, index, match.rule.id)) continue;
|
|
@@ -23735,6 +24632,30 @@ function scanText(relativePath, text, language = languageOf(relativePath)) {
|
|
|
23735
24632
|
});
|
|
23736
24633
|
}
|
|
23737
24634
|
}
|
|
24635
|
+
for (const match of evaluateDeployRules(relativePath, text, language, isWorkflow)) {
|
|
24636
|
+
const index = match.line - 1;
|
|
24637
|
+
if (isSuppressed(suppressions, index, match.rule.id)) continue;
|
|
24638
|
+
const soft = softening({
|
|
24639
|
+
test: inTests,
|
|
24640
|
+
docs: inDocs,
|
|
24641
|
+
suppressed: foreignSecurityMark(lines[index] ?? "")
|
|
24642
|
+
});
|
|
24643
|
+
findings.push({
|
|
24644
|
+
ruleId: match.rule.id,
|
|
24645
|
+
title: match.rule.title,
|
|
24646
|
+
file: relativePath,
|
|
24647
|
+
line: match.line,
|
|
24648
|
+
severity: soft ? "low" : match.severity,
|
|
24649
|
+
confidence: match.rule.confidence,
|
|
24650
|
+
message: soft ? `${match.message} (${CODE_SOFTENING[soft]})` : match.message,
|
|
24651
|
+
consequence: match.rule.consequence,
|
|
24652
|
+
fix: match.rule.fix,
|
|
24653
|
+
reference: match.rule.reference,
|
|
24654
|
+
cwe: match.rule.cwe,
|
|
24655
|
+
excerpt: (lines[index] ?? "").trim().slice(0, 200),
|
|
24656
|
+
category: "code"
|
|
24657
|
+
});
|
|
24658
|
+
}
|
|
23738
24659
|
return findings;
|
|
23739
24660
|
}
|
|
23740
24661
|
function scanManifest(relativePath, filename, text) {
|
|
@@ -23854,7 +24775,7 @@ function scanPath(targetPath, options = {}) {
|
|
|
23854
24775
|
const relativePath = toRelative(walkRoot, fullPath);
|
|
23855
24776
|
const extension = (0, import_node_path11.extname)(filename).toLowerCase();
|
|
23856
24777
|
const isManifest = filename === "package.json" || filename === "requirements.txt";
|
|
23857
|
-
const scannable = SCAN_EXTENSIONS.has(extension) || filename.startsWith(".env");
|
|
24778
|
+
const scannable = SCAN_EXTENSIONS.has(extension) || filename.startsWith(".env") || isEnvFileName(filename) || isAuthorizedKeysPath(filename);
|
|
23858
24779
|
const mayDeclareInterpreter = !scannable && !isManifest && extension === "";
|
|
23859
24780
|
if (!scannable && !isManifest && !mayDeclareInterpreter) {
|
|
23860
24781
|
recordSensitiveFile(filename, relativePath, findings, []);
|
|
@@ -23875,7 +24796,10 @@ function scanPath(targetPath, options = {}) {
|
|
|
23875
24796
|
const prefix = Buffer.alloc(128);
|
|
23876
24797
|
const read = (0, import_node_fs17.readSync)(handle, prefix, 0, prefix.length, 0);
|
|
23877
24798
|
declared = languageOfShebang(prefix.subarray(0, read).toString("utf-8").split("\n", 1)[0] ?? "");
|
|
23878
|
-
if (!declared)
|
|
24799
|
+
if (!declared) {
|
|
24800
|
+
recordSensitiveFile(filename, relativePath, findings, []);
|
|
24801
|
+
return;
|
|
24802
|
+
}
|
|
23879
24803
|
}
|
|
23880
24804
|
text = (0, import_node_fs17.readFileSync)(handle, "utf-8");
|
|
23881
24805
|
} catch {
|
|
@@ -23943,7 +24867,7 @@ function scanPath(targetPath, options = {}) {
|
|
|
23943
24867
|
function recordSensitiveFile(filename, relativePath, sink, fileFindings) {
|
|
23944
24868
|
if (fileFindings.length > 0) return;
|
|
23945
24869
|
for (const sensitive of SENSITIVE_FILES) {
|
|
23946
|
-
const matches = filename === sensitive.pattern || filename.endsWith(sensitive.pattern);
|
|
24870
|
+
const matches = sensitive.test ? sensitive.test(filename) : filename === sensitive.pattern || filename.endsWith(sensitive.pattern);
|
|
23947
24871
|
if (!matches) continue;
|
|
23948
24872
|
sink.push({
|
|
23949
24873
|
ruleId: "sensitive-file-committed",
|
|
@@ -23954,6 +24878,8 @@ function recordSensitiveFile(filename, relativePath, sink, fileFindings) {
|
|
|
23954
24878
|
confidence: "evidence",
|
|
23955
24879
|
message: sensitive.message,
|
|
23956
24880
|
consequence: "Anything in this file is in every clone, fork and CI cache of the repository.",
|
|
24881
|
+
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.",
|
|
24882
|
+
reference: attackVector("unrotated-github-app-keys"),
|
|
23957
24883
|
cwe: "CWE-538",
|
|
23958
24884
|
excerpt: "",
|
|
23959
24885
|
sensitive: true,
|
|
@@ -25853,7 +26779,7 @@ var EGRESS_TABLE = "threatcrush_egress";
|
|
|
25853
26779
|
var DEFAULT_REFRESH_MS = 36e5;
|
|
25854
26780
|
var POLL_MS = 15e3;
|
|
25855
26781
|
var REALERT_MS = 36e5;
|
|
25856
|
-
function threatFeedSettings(section) {
|
|
26782
|
+
function threatFeedSettings(section, env2 = process.env) {
|
|
25857
26783
|
const refresh = parseDuration(section?.refresh);
|
|
25858
26784
|
return {
|
|
25859
26785
|
enabled: section?.enabled !== false,
|
|
@@ -25862,9 +26788,21 @@ function threatFeedSettings(section) {
|
|
|
25862
26788
|
// abuse.ch asks for no more than one fetch per 5 minutes; hourly is plenty.
|
|
25863
26789
|
refreshMs: refresh ? Math.max(900, refresh) * 1e3 : DEFAULT_REFRESH_MS,
|
|
25864
26790
|
minConfidence: typeof section?.min_confidence === "number" ? section.min_confidence : 75,
|
|
25865
|
-
allow: Array.isArray(section?.allow) ? section.allow.map(String) : []
|
|
26791
|
+
allow: Array.isArray(section?.allow) ? section.allow.map(String) : [],
|
|
26792
|
+
authKey: abusechAuthKey(section, env2)
|
|
25866
26793
|
};
|
|
25867
26794
|
}
|
|
26795
|
+
function abusechAuthKey(section, env2 = process.env) {
|
|
26796
|
+
if (section?.auth_key_file) {
|
|
26797
|
+
try {
|
|
26798
|
+
const key2 = (0, import_node_fs24.readFileSync)(section.auth_key_file, "utf-8").trim();
|
|
26799
|
+
if (key2) return key2;
|
|
26800
|
+
} catch {
|
|
26801
|
+
}
|
|
26802
|
+
}
|
|
26803
|
+
const key = (section?.auth_key ?? env2.ABUSECH_AUTH_KEY ?? "").trim();
|
|
26804
|
+
return key || void 0;
|
|
26805
|
+
}
|
|
25868
26806
|
function egressRuleset(ips) {
|
|
25869
26807
|
const v4 = ips.filter((ip) => (0, import_node_net10.isIP)(ip) === 4);
|
|
25870
26808
|
const v6 = ips.filter((ip) => (0, import_node_net10.isIP)(ip) === 6);
|
|
@@ -26001,7 +26939,9 @@ var ThreatFeeds = class {
|
|
|
26001
26939
|
this.blocking = ok;
|
|
26002
26940
|
mode = ok ? "blocking egress" : "detecting (nft load failed)";
|
|
26003
26941
|
}
|
|
26004
|
-
const
|
|
26942
|
+
const failed = (set.sources ?? []).filter((s) => !s.ok).map((s) => s.feed);
|
|
26943
|
+
const failing = failed.length ? `; ${failed.length}/${set.sources.length} feeds failing (${failed.join(", ")}), see \`threatcrush feeds\`` : "";
|
|
26944
|
+
const detail = `${ips.length} IPs, ${domains} domains, ${mode}${this.writeResolverFiles(set)}${failing}`;
|
|
26005
26945
|
this.opts.log(`[threat-feeds] ${from === "cache" ? "loaded cached" : "refreshed"} list: ${detail} (${set.skipped_shared} shared/protected entries skipped)`);
|
|
26006
26946
|
this.opts.bus.announceModule("threat-feeds", "running", detail);
|
|
26007
26947
|
}
|
|
@@ -26946,9 +27886,247 @@ var CommandHistoryWatcher = class {
|
|
|
26946
27886
|
|
|
26947
27887
|
// src/daemon/workers/file-integrity.ts
|
|
26948
27888
|
var import_node_fs27 = require("fs");
|
|
26949
|
-
var
|
|
27889
|
+
var import_promises4 = require("fs/promises");
|
|
26950
27890
|
var import_node_crypto8 = require("crypto");
|
|
27891
|
+
var import_node_path23 = require("path");
|
|
27892
|
+
|
|
27893
|
+
// src/daemon/workers/writer-containment.ts
|
|
27894
|
+
var import_promises3 = require("fs/promises");
|
|
26951
27895
|
var import_node_path22 = require("path");
|
|
27896
|
+
var realWriterProcFs = {
|
|
27897
|
+
async pids() {
|
|
27898
|
+
try {
|
|
27899
|
+
return (await (0, import_promises3.readdir)("/proc")).filter((name) => /^\d+$/.test(name)).map(Number);
|
|
27900
|
+
} catch {
|
|
27901
|
+
return [];
|
|
27902
|
+
}
|
|
27903
|
+
},
|
|
27904
|
+
async stat(pid) {
|
|
27905
|
+
try {
|
|
27906
|
+
return await (0, import_promises3.readFile)(`/proc/${pid}/stat`, "utf8");
|
|
27907
|
+
} catch {
|
|
27908
|
+
return null;
|
|
27909
|
+
}
|
|
27910
|
+
},
|
|
27911
|
+
async exe(pid) {
|
|
27912
|
+
try {
|
|
27913
|
+
return await (0, import_promises3.readlink)(`/proc/${pid}/exe`);
|
|
27914
|
+
} catch {
|
|
27915
|
+
return null;
|
|
27916
|
+
}
|
|
27917
|
+
},
|
|
27918
|
+
async fds(pid) {
|
|
27919
|
+
try {
|
|
27920
|
+
return await (0, import_promises3.readdir)(`/proc/${pid}/fd`);
|
|
27921
|
+
} catch {
|
|
27922
|
+
return null;
|
|
27923
|
+
}
|
|
27924
|
+
},
|
|
27925
|
+
async fdTarget(pid, fd) {
|
|
27926
|
+
try {
|
|
27927
|
+
return await (0, import_promises3.readlink)(`/proc/${pid}/fd/${fd}`);
|
|
27928
|
+
} catch {
|
|
27929
|
+
return null;
|
|
27930
|
+
}
|
|
27931
|
+
},
|
|
27932
|
+
async fdFlags(pid, fd) {
|
|
27933
|
+
try {
|
|
27934
|
+
const match = /^flags:\s*([0-7]+)$/m.exec(await (0, import_promises3.readFile)(`/proc/${pid}/fdinfo/${fd}`, "utf8"));
|
|
27935
|
+
return match ? Number.parseInt(match[1], 8) : null;
|
|
27936
|
+
} catch {
|
|
27937
|
+
return null;
|
|
27938
|
+
}
|
|
27939
|
+
},
|
|
27940
|
+
kill(pid, signal) {
|
|
27941
|
+
process.kill(pid, signal);
|
|
27942
|
+
}
|
|
27943
|
+
};
|
|
27944
|
+
var CONTAIN_DEFAULT_MAX_PROCESSES = 3;
|
|
27945
|
+
var MAX_PIDS = 8192;
|
|
27946
|
+
var MAX_FDS_PER_PROCESS = 4096;
|
|
27947
|
+
var MAX_MATCH_FILES = 1e3;
|
|
27948
|
+
var MAX_MATCH_DIRECTORIES = 64;
|
|
27949
|
+
var MAX_REPORTED_FILES = 10;
|
|
27950
|
+
var DEFAULT_BUDGET_MS = 1500;
|
|
27951
|
+
var O_ACCMODE = 3;
|
|
27952
|
+
function containWriterSettings(section) {
|
|
27953
|
+
const raw = section?.contain_writer;
|
|
27954
|
+
const mode = raw === "stop" || raw === "kill" ? raw : "off";
|
|
27955
|
+
const max = section?.contain_max_processes;
|
|
27956
|
+
const maxProcesses = typeof max === "number" && Number.isFinite(max) ? Math.max(1, Math.min(20, Math.floor(max))) : CONTAIN_DEFAULT_MAX_PROCESSES;
|
|
27957
|
+
const neverContain = Array.isArray(section?.never_contain) ? section.never_contain.filter((value) => typeof value === "string" && value.startsWith("/")) : [];
|
|
27958
|
+
return { mode, maxProcesses, neverContain };
|
|
27959
|
+
}
|
|
27960
|
+
function parseStat(text) {
|
|
27961
|
+
const open2 = text.indexOf("(");
|
|
27962
|
+
const close = text.lastIndexOf(")");
|
|
27963
|
+
if (open2 < 0 || close < open2) return null;
|
|
27964
|
+
const pid = Number(text.slice(0, open2).trim());
|
|
27965
|
+
const rest = text.slice(close + 2).split(" ");
|
|
27966
|
+
const ppid = Number(rest[1]);
|
|
27967
|
+
const starttime = Number(rest[19]);
|
|
27968
|
+
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) return null;
|
|
27969
|
+
return { pid, ppid, comm: text.slice(open2 + 1, close), starttime: Number.isFinite(starttime) ? starttime : 0 };
|
|
27970
|
+
}
|
|
27971
|
+
var stripDeleted = (path) => path.replace(/ \(deleted\)$/, "");
|
|
27972
|
+
var WriterContainment = class {
|
|
27973
|
+
constructor(opts) {
|
|
27974
|
+
this.opts = opts;
|
|
27975
|
+
this.fs = opts.procfs ?? realWriterProcFs;
|
|
27976
|
+
this.selfPid = opts.selfPid ?? process.pid;
|
|
27977
|
+
this.parentPid = opts.parentPid ?? process.ppid;
|
|
27978
|
+
this.nowMs = opts.nowMs ?? Date.now;
|
|
27979
|
+
}
|
|
27980
|
+
opts;
|
|
27981
|
+
fs;
|
|
27982
|
+
selfPid;
|
|
27983
|
+
parentPid;
|
|
27984
|
+
nowMs;
|
|
27985
|
+
get enabled() {
|
|
27986
|
+
return this.opts.settings.mode !== "off" && (this.opts.platform ?? process.platform) === "linux";
|
|
27987
|
+
}
|
|
27988
|
+
/** A process that must never be signalled, whatever it wrote. */
|
|
27989
|
+
isProtected(info, exe) {
|
|
27990
|
+
if (info.pid <= 2 || info.ppid === 2) return true;
|
|
27991
|
+
if (info.pid === this.selfPid || info.pid === this.parentPid) return true;
|
|
27992
|
+
const path = stripDeleted(exe);
|
|
27993
|
+
const names = [info.comm, (0, import_node_path22.basename)(path)];
|
|
27994
|
+
if (names.some((name) => name === "sshd" || name.startsWith("sshd-") || name.startsWith("systemd"))) return true;
|
|
27995
|
+
return this.opts.settings.neverContain.some((entry) => entry.endsWith("/") ? path.startsWith(entry) : path === entry);
|
|
27996
|
+
}
|
|
27997
|
+
/**
|
|
27998
|
+
* Find who holds `files` (or files under their directories) open for writing,
|
|
27999
|
+
* and signal them when attribution is unambiguous.
|
|
28000
|
+
*/
|
|
28001
|
+
async contain(files, extraDirectories = []) {
|
|
28002
|
+
const { mode, maxProcesses } = this.opts.settings;
|
|
28003
|
+
const report = { mode, action: "no-writer", processes: [], protected_writers: [], incomplete: false };
|
|
28004
|
+
if (!this.enabled) {
|
|
28005
|
+
report.action = "alert-only";
|
|
28006
|
+
report.reason = mode === "off" ? "contain_writer is off" : "writer containment needs Linux /proc";
|
|
28007
|
+
return report;
|
|
28008
|
+
}
|
|
28009
|
+
const exact = new Set(files.slice(0, MAX_MATCH_FILES));
|
|
28010
|
+
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}/`);
|
|
28011
|
+
if (files.length > MAX_MATCH_FILES) report.incomplete = true;
|
|
28012
|
+
const deadline = this.nowMs() + (this.opts.budgetMs ?? DEFAULT_BUDGET_MS);
|
|
28013
|
+
const exactHits = /* @__PURE__ */ new Map();
|
|
28014
|
+
const dirHits = /* @__PURE__ */ new Map();
|
|
28015
|
+
let pids = await this.fs.pids();
|
|
28016
|
+
if (pids.length > MAX_PIDS) {
|
|
28017
|
+
report.incomplete = true;
|
|
28018
|
+
pids = pids.slice(0, MAX_PIDS);
|
|
28019
|
+
}
|
|
28020
|
+
for (const pid of pids) {
|
|
28021
|
+
if (this.nowMs() > deadline) {
|
|
28022
|
+
report.incomplete = true;
|
|
28023
|
+
break;
|
|
28024
|
+
}
|
|
28025
|
+
const fds = await this.fs.fds(pid);
|
|
28026
|
+
if (!fds || fds.length === 0) continue;
|
|
28027
|
+
let exactFiles = [];
|
|
28028
|
+
let dirFiles = [];
|
|
28029
|
+
for (const fd of fds.slice(0, MAX_FDS_PER_PROCESS)) {
|
|
28030
|
+
const raw = await this.fs.fdTarget(pid, fd);
|
|
28031
|
+
if (!raw || !raw.startsWith("/")) continue;
|
|
28032
|
+
const target = stripDeleted(raw);
|
|
28033
|
+
const isExact = exact.has(target);
|
|
28034
|
+
const inDir = !isExact && directories.some((dir) => target.startsWith(dir));
|
|
28035
|
+
if (!isExact && !inDir) continue;
|
|
28036
|
+
const flags = await this.fs.fdFlags(pid, fd);
|
|
28037
|
+
if (flags === null || (flags & O_ACCMODE) === 0) continue;
|
|
28038
|
+
if (isExact) exactFiles.push(target);
|
|
28039
|
+
else dirFiles.push(target);
|
|
28040
|
+
}
|
|
28041
|
+
if (fds.length > MAX_FDS_PER_PROCESS) report.incomplete = true;
|
|
28042
|
+
if (exactFiles.length === 0 && dirFiles.length === 0) continue;
|
|
28043
|
+
const statText = await this.fs.stat(pid);
|
|
28044
|
+
const info = statText ? parseStat(statText) : null;
|
|
28045
|
+
if (!info) continue;
|
|
28046
|
+
const exe = await this.fs.exe(pid) ?? "";
|
|
28047
|
+
exactFiles = [...new Set(exactFiles)];
|
|
28048
|
+
dirFiles = [...new Set(dirFiles)];
|
|
28049
|
+
if (!exe || this.isProtected(info, exe)) {
|
|
28050
|
+
report.protected_writers.push({ pid, comm: info.comm, exe: exe || "[kernel]" });
|
|
28051
|
+
continue;
|
|
28052
|
+
}
|
|
28053
|
+
if (exactFiles.length) exactHits.set(pid, { info, exe, files: [...exactFiles, ...dirFiles] });
|
|
28054
|
+
else dirHits.set(pid, { info, exe, files: dirFiles });
|
|
28055
|
+
}
|
|
28056
|
+
const chosen = exactHits.size ? exactHits : dirHits;
|
|
28057
|
+
report.match = exactHits.size ? "exact" : dirHits.size ? "directory" : void 0;
|
|
28058
|
+
report.processes = [...chosen.values()].map(({ info, exe, files: held }) => ({
|
|
28059
|
+
pid: info.pid,
|
|
28060
|
+
comm: info.comm,
|
|
28061
|
+
exe: stripDeleted(exe),
|
|
28062
|
+
files: held.slice(0, MAX_REPORTED_FILES)
|
|
28063
|
+
}));
|
|
28064
|
+
if (report.processes.length === 0) {
|
|
28065
|
+
report.action = "no-writer";
|
|
28066
|
+
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";
|
|
28067
|
+
if (!report.match) delete report.match;
|
|
28068
|
+
return report;
|
|
28069
|
+
}
|
|
28070
|
+
if (report.incomplete) {
|
|
28071
|
+
report.action = "alert-only";
|
|
28072
|
+
report.reason = "the /proc walk hit a limit, so attribution may be incomplete";
|
|
28073
|
+
return report;
|
|
28074
|
+
}
|
|
28075
|
+
if (report.processes.length > maxProcesses) {
|
|
28076
|
+
report.action = "alert-only";
|
|
28077
|
+
report.reason = `${report.processes.length} candidate writers exceeds contain_max_processes (${maxProcesses})`;
|
|
28078
|
+
return report;
|
|
28079
|
+
}
|
|
28080
|
+
const signal = mode === "kill" ? "SIGKILL" : "SIGSTOP";
|
|
28081
|
+
const dryRun = this.opts.dryRun?.() === true;
|
|
28082
|
+
let sent = 0;
|
|
28083
|
+
for (const proc of report.processes) {
|
|
28084
|
+
proc.signal = signal;
|
|
28085
|
+
const before = chosen.get(proc.pid).info;
|
|
28086
|
+
const fresh = await this.fs.stat(proc.pid);
|
|
28087
|
+
const now = fresh ? parseStat(fresh) : null;
|
|
28088
|
+
if (!now || now.starttime !== before.starttime) {
|
|
28089
|
+
proc.result = "gone";
|
|
28090
|
+
continue;
|
|
28091
|
+
}
|
|
28092
|
+
if (dryRun) {
|
|
28093
|
+
proc.result = "dry-run";
|
|
28094
|
+
continue;
|
|
28095
|
+
}
|
|
28096
|
+
try {
|
|
28097
|
+
this.fs.kill(proc.pid, signal);
|
|
28098
|
+
proc.result = "sent";
|
|
28099
|
+
sent++;
|
|
28100
|
+
} catch (error) {
|
|
28101
|
+
proc.result = "failed";
|
|
28102
|
+
proc.error = error.message.split("\n")[0].slice(0, 200);
|
|
28103
|
+
}
|
|
28104
|
+
}
|
|
28105
|
+
report.action = dryRun ? "dry-run" : sent === report.processes.length ? "contained" : sent > 0 ? "partial" : "alert-only";
|
|
28106
|
+
if (report.action === "alert-only") report.reason = "signal not delivered";
|
|
28107
|
+
for (const proc of report.processes) {
|
|
28108
|
+
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}` : ""}`);
|
|
28109
|
+
}
|
|
28110
|
+
return report;
|
|
28111
|
+
}
|
|
28112
|
+
};
|
|
28113
|
+
function summarizeContainment(report) {
|
|
28114
|
+
const procs = report.processes.map((p) => `pid ${p.pid} (${(0, import_node_path22.basename)(p.exe) || p.comm})`).join(", ");
|
|
28115
|
+
switch (report.action) {
|
|
28116
|
+
case "contained":
|
|
28117
|
+
return `writer ${procs} ${report.mode === "kill" ? "killed (SIGKILL)" : "stopped (SIGSTOP)"}`;
|
|
28118
|
+
case "partial":
|
|
28119
|
+
return `writer containment partial: ${report.processes.map((p) => `pid ${p.pid} ${p.result}`).join(", ")}`;
|
|
28120
|
+
case "dry-run":
|
|
28121
|
+
return `dry_run: would ${report.mode === "kill" ? "SIGKILL" : "SIGSTOP"} ${procs}`;
|
|
28122
|
+
case "alert-only":
|
|
28123
|
+
return procs ? `writer ${procs} not contained: ${report.reason}` : `writer not contained: ${report.reason}`;
|
|
28124
|
+
case "no-writer":
|
|
28125
|
+
return "writer not identified";
|
|
28126
|
+
}
|
|
28127
|
+
}
|
|
28128
|
+
|
|
28129
|
+
// src/daemon/workers/file-integrity.ts
|
|
26952
28130
|
var DEFAULT_POLL_MS = 15 * 6e4;
|
|
26953
28131
|
var MAX_FILES = 5e4;
|
|
26954
28132
|
var MAX_FILE_BYTES = 64 * 1024 * 1024;
|
|
@@ -26963,8 +28141,8 @@ var READ_CHUNK_BYTES = 64 * 1024;
|
|
|
26963
28141
|
var CANARY_CONTENT = "ThreatCrush file integrity canary v1\n";
|
|
26964
28142
|
function fileIntegritySettings(section) {
|
|
26965
28143
|
const safePath = (value) => {
|
|
26966
|
-
if (typeof value !== "string" || !(0,
|
|
26967
|
-
const path = (0,
|
|
28144
|
+
if (typeof value !== "string" || !(0, import_node_path23.isAbsolute)(value) || value.split(import_node_path23.sep).includes("..")) return null;
|
|
28145
|
+
const path = (0, import_node_path23.normalize)(value);
|
|
26968
28146
|
return path === "/" ? null : path;
|
|
26969
28147
|
};
|
|
26970
28148
|
const strings = (values) => Array.isArray(values) ? [...new Set(values.map(safePath).filter((path) => path !== null))] : [];
|
|
@@ -26977,7 +28155,8 @@ function fileIntegritySettings(section) {
|
|
|
26977
28155
|
paths: strings(section?.paths),
|
|
26978
28156
|
canaries: strings(section?.canaries),
|
|
26979
28157
|
canaryDirectories: strings(section?.canary_directories),
|
|
26980
|
-
pollMs
|
|
28158
|
+
pollMs,
|
|
28159
|
+
containment: containWriterSettings(section)
|
|
26981
28160
|
};
|
|
26982
28161
|
}
|
|
26983
28162
|
function signature(value) {
|
|
@@ -26985,7 +28164,7 @@ function signature(value) {
|
|
|
26985
28164
|
}
|
|
26986
28165
|
async function readState(path) {
|
|
26987
28166
|
try {
|
|
26988
|
-
const parsed = JSON.parse(await (0,
|
|
28167
|
+
const parsed = JSON.parse(await (0, import_promises4.readFile)(path, "utf8"));
|
|
26989
28168
|
if (parsed.schema !== 1 || !Array.isArray(parsed.targets) || !parsed.files || typeof parsed.files !== "object") return null;
|
|
26990
28169
|
return parsed;
|
|
26991
28170
|
} catch {
|
|
@@ -26993,10 +28172,10 @@ async function readState(path) {
|
|
|
26993
28172
|
}
|
|
26994
28173
|
}
|
|
26995
28174
|
async function writeState(path, state) {
|
|
26996
|
-
await (0,
|
|
28175
|
+
await (0, import_promises4.mkdir)((0, import_node_path23.dirname)(path), { recursive: true, mode: 448 });
|
|
26997
28176
|
const temp = `${path}.${process.pid}.${(0, import_node_crypto8.randomUUID)()}.tmp`;
|
|
26998
|
-
await (0,
|
|
26999
|
-
await (0,
|
|
28177
|
+
await (0, import_promises4.writeFile)(temp, JSON.stringify(state), { mode: 384 });
|
|
28178
|
+
await (0, import_promises4.rename)(temp, path);
|
|
27000
28179
|
}
|
|
27001
28180
|
async function hashFile(path, handle, size) {
|
|
27002
28181
|
const hash = (0, import_node_crypto8.createHash)("sha256");
|
|
@@ -27019,19 +28198,19 @@ async function hashFile(path, handle, size) {
|
|
|
27019
28198
|
}
|
|
27020
28199
|
return { sha256: hash.digest("hex"), entropy };
|
|
27021
28200
|
}
|
|
27022
|
-
var OPEN_FILE_FLAGS =
|
|
27023
|
-
var OPEN_DIR_FLAGS = OPEN_FILE_FLAGS |
|
|
27024
|
-
var CREATE_FILE_FLAGS =
|
|
28201
|
+
var OPEN_FILE_FLAGS = import_promises4.constants.O_RDONLY | import_promises4.constants.O_NONBLOCK | (import_promises4.constants.O_NOFOLLOW ?? 0);
|
|
28202
|
+
var OPEN_DIR_FLAGS = OPEN_FILE_FLAGS | import_promises4.constants.O_DIRECTORY;
|
|
28203
|
+
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
28204
|
function autoCanaryPath(directory) {
|
|
27026
|
-
return (0,
|
|
28205
|
+
return (0, import_node_path23.join)(directory, ".threatcrush-canary");
|
|
27027
28206
|
}
|
|
27028
28207
|
async function openAbsoluteDirectory(path) {
|
|
27029
|
-
const parts = path.split(
|
|
28208
|
+
const parts = path.split(import_node_path23.sep).filter((part) => part && part !== ".");
|
|
27030
28209
|
if (parts.includes("..")) throw new Error("invalid canary directory");
|
|
27031
|
-
let directory = await (0,
|
|
28210
|
+
let directory = await (0, import_promises4.open)("/", OPEN_DIR_FLAGS);
|
|
27032
28211
|
try {
|
|
27033
28212
|
for (const part of parts) {
|
|
27034
|
-
const next = await (0,
|
|
28213
|
+
const next = await (0, import_promises4.open)(`/proc/self/fd/${directory.fd}/${part}`, OPEN_DIR_FLAGS);
|
|
27035
28214
|
await directory.close();
|
|
27036
28215
|
directory = next;
|
|
27037
28216
|
}
|
|
@@ -27049,9 +28228,9 @@ async function createAutoCanary(path) {
|
|
|
27049
28228
|
} catch (error) {
|
|
27050
28229
|
if (error.code !== "ENOENT") return false;
|
|
27051
28230
|
}
|
|
27052
|
-
const directory = await openAbsoluteDirectory((0,
|
|
28231
|
+
const directory = await openAbsoluteDirectory((0, import_node_path23.dirname)(path));
|
|
27053
28232
|
try {
|
|
27054
|
-
const file = await (0,
|
|
28233
|
+
const file = await (0, import_promises4.open)(`/proc/self/fd/${directory.fd}/${(0, import_node_path23.basename)(path)}`, CREATE_FILE_FLAGS, 438);
|
|
27055
28234
|
try {
|
|
27056
28235
|
await file.chmod(438);
|
|
27057
28236
|
await file.writeFile(CANARY_CONTENT);
|
|
@@ -27068,16 +28247,16 @@ async function createAutoCanary(path) {
|
|
|
27068
28247
|
}
|
|
27069
28248
|
}
|
|
27070
28249
|
async function openAbsoluteTarget(path) {
|
|
27071
|
-
const parts = path.split(
|
|
28250
|
+
const parts = path.split(import_node_path23.sep).filter((part) => part && part !== ".");
|
|
27072
28251
|
if (parts.length === 0 || parts.includes("..")) throw new Error("invalid file integrity path");
|
|
27073
|
-
let directory = await (0,
|
|
28252
|
+
let directory = await (0, import_promises4.open)("/", OPEN_DIR_FLAGS);
|
|
27074
28253
|
try {
|
|
27075
28254
|
for (const part of parts.slice(0, -1)) {
|
|
27076
|
-
const next = await (0,
|
|
28255
|
+
const next = await (0, import_promises4.open)(`/proc/self/fd/${directory.fd}/${part}`, OPEN_DIR_FLAGS);
|
|
27077
28256
|
await directory.close();
|
|
27078
28257
|
directory = next;
|
|
27079
28258
|
}
|
|
27080
|
-
const target = await (0,
|
|
28259
|
+
const target = await (0, import_promises4.open)(`/proc/self/fd/${directory.fd}/${parts.at(-1)}`, OPEN_FILE_FLAGS);
|
|
27081
28260
|
await directory.close();
|
|
27082
28261
|
return target;
|
|
27083
28262
|
} catch (error) {
|
|
@@ -27103,7 +28282,7 @@ async function scanTargets(targets, canaries) {
|
|
|
27103
28282
|
}
|
|
27104
28283
|
let handle;
|
|
27105
28284
|
try {
|
|
27106
|
-
handle = parent ? await (0,
|
|
28285
|
+
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
28286
|
const stat = await handle.stat();
|
|
27108
28287
|
if (stat.isDirectory()) {
|
|
27109
28288
|
directories.push(path);
|
|
@@ -27114,14 +28293,14 @@ async function scanTargets(targets, canaries) {
|
|
|
27114
28293
|
}
|
|
27115
28294
|
let entries2;
|
|
27116
28295
|
try {
|
|
27117
|
-
entries2 = await (0,
|
|
28296
|
+
entries2 = await (0, import_promises4.readdir)(`/proc/self/fd/${handle.fd}`, { withFileTypes: true });
|
|
27118
28297
|
} catch {
|
|
27119
28298
|
complete = false;
|
|
27120
28299
|
errors.add(path);
|
|
27121
28300
|
return;
|
|
27122
28301
|
}
|
|
27123
28302
|
for (const entry of entries2) {
|
|
27124
|
-
await walk((0,
|
|
28303
|
+
await walk((0, import_node_path23.join)(path, entry.name), handle);
|
|
27125
28304
|
if (!complete) return;
|
|
27126
28305
|
}
|
|
27127
28306
|
return;
|
|
@@ -27194,6 +28373,12 @@ var FileIntegrityWatch = class {
|
|
|
27194
28373
|
constructor(opts) {
|
|
27195
28374
|
this.opts = opts;
|
|
27196
28375
|
this.now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
28376
|
+
this.containment = new WriterContainment({
|
|
28377
|
+
settings: opts.settings.containment ?? containWriterSettings(void 0),
|
|
28378
|
+
log: opts.log,
|
|
28379
|
+
dryRun: opts.dryRun,
|
|
28380
|
+
procfs: opts.procfs
|
|
28381
|
+
});
|
|
27197
28382
|
this.canaries = /* @__PURE__ */ new Set([
|
|
27198
28383
|
...opts.settings.canaries,
|
|
27199
28384
|
...opts.settings.canaryDirectories.map(autoCanaryPath)
|
|
@@ -27209,6 +28394,7 @@ var FileIntegrityWatch = class {
|
|
|
27209
28394
|
eventFirstAt = 0;
|
|
27210
28395
|
eventScanPending = false;
|
|
27211
28396
|
watcherLimitLogged = false;
|
|
28397
|
+
containment;
|
|
27212
28398
|
get autoCanaries() {
|
|
27213
28399
|
return this.opts.settings.canaryDirectories.map(autoCanaryPath);
|
|
27214
28400
|
}
|
|
@@ -27233,6 +28419,9 @@ var FileIntegrityWatch = class {
|
|
|
27233
28419
|
return;
|
|
27234
28420
|
}
|
|
27235
28421
|
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`);
|
|
28422
|
+
if (this.containment.enabled) {
|
|
28423
|
+
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`);
|
|
28424
|
+
}
|
|
27236
28425
|
void this.scanOnce();
|
|
27237
28426
|
this.timer = setInterval(() => {
|
|
27238
28427
|
void this.scanOnce();
|
|
@@ -27315,7 +28504,7 @@ var FileIntegrityWatch = class {
|
|
|
27315
28504
|
let baselineFilePresent = false;
|
|
27316
28505
|
if (!baseline) {
|
|
27317
28506
|
try {
|
|
27318
|
-
await (0,
|
|
28507
|
+
await (0, import_promises4.lstat)(this.opts.baselinePath);
|
|
27319
28508
|
baselineFilePresent = true;
|
|
27320
28509
|
} catch (error) {
|
|
27321
28510
|
baselineFilePresent = error.code !== "ENOENT";
|
|
@@ -27331,7 +28520,7 @@ var FileIntegrityWatch = class {
|
|
|
27331
28520
|
if (current.complete) {
|
|
27332
28521
|
const directories = new Set(current.directories);
|
|
27333
28522
|
for (const path of Object.keys(current.files)) {
|
|
27334
|
-
if (!directories.has(path)) directories.add((0,
|
|
28523
|
+
if (!directories.has(path)) directories.add((0, import_node_path23.dirname)(path));
|
|
27335
28524
|
}
|
|
27336
28525
|
this.refreshWatchers([...directories]);
|
|
27337
28526
|
}
|
|
@@ -27367,7 +28556,8 @@ var FileIntegrityWatch = class {
|
|
|
27367
28556
|
if (!sameTargets(baseline.targets, targets)) {
|
|
27368
28557
|
const removedCanaries = changedPaths(observed.files, current.files).filter((change) => this.canaries.has(change.path) && observed.targets.includes(change.path));
|
|
27369
28558
|
if (removedCanaries.length) {
|
|
27370
|
-
|
|
28559
|
+
const containment2 = await this.containWriters(removedCanaries.map((change) => change.path));
|
|
28560
|
+
this.emit("critical", "A file integrity canary changed or disappeared", "file-integrity-canary", removedCanaries, containment2);
|
|
27371
28561
|
}
|
|
27372
28562
|
if (!sameTargets(observed.targets, targets)) {
|
|
27373
28563
|
this.emit(
|
|
@@ -27382,17 +28572,19 @@ var FileIntegrityWatch = class {
|
|
|
27382
28572
|
}
|
|
27383
28573
|
const changes = changedPaths(observed.files, current.files);
|
|
27384
28574
|
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
28575
|
const ordinary = changes.filter((change) => !this.canaries.has(change.path));
|
|
27389
28576
|
const paths = ordinary.map((change) => change.path);
|
|
27390
28577
|
const beforeEntropy = meanEntropy(paths, observed.files);
|
|
27391
28578
|
const afterEntropy = meanEntropy(paths, current.files);
|
|
27392
28579
|
const entropyRose = beforeEntropy !== null && afterEntropy !== null && afterEntropy - beforeEntropy >= MASS_CHANGE_ENTROPY_RISE_BITS;
|
|
27393
|
-
|
|
28580
|
+
const massChange = ordinary.length >= MASS_CHANGE_COUNT || ordinary.length >= 10 && entropyRose;
|
|
28581
|
+
const containment = canaryChanges.length || massChange ? await this.containWriters([...canaryChanges.map((change) => change.path), ...massChange ? paths : []]) : void 0;
|
|
28582
|
+
if (canaryChanges.length) {
|
|
28583
|
+
this.emit("critical", "A file integrity canary changed or disappeared", "file-integrity-canary", canaryChanges, containment);
|
|
28584
|
+
}
|
|
28585
|
+
if (massChange) {
|
|
27394
28586
|
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);
|
|
28587
|
+
this.emit("critical", `${ordinary.length} monitored files changed in one scan${entropyDetail}`, "file-integrity-mass-change", ordinary, containment);
|
|
27396
28588
|
} else {
|
|
27397
28589
|
for (const change of ordinary) {
|
|
27398
28590
|
const expected = baseline.files[change.path] ?? "missing";
|
|
@@ -27414,13 +28606,25 @@ var FileIntegrityWatch = class {
|
|
|
27414
28606
|
if (this.eventScanPending && !this.eventTimer) this.scheduleEventScan();
|
|
27415
28607
|
}
|
|
27416
28608
|
}
|
|
27417
|
-
|
|
28609
|
+
/** Opt-in: find and stop (or kill) the writer. Undefined when contain_writer is off. */
|
|
28610
|
+
async containWriters(paths) {
|
|
28611
|
+
if (!this.containment.enabled) return void 0;
|
|
28612
|
+
try {
|
|
28613
|
+
return await this.containment.contain(paths);
|
|
28614
|
+
} catch (error) {
|
|
28615
|
+
this.opts.log(`[file-integrity] writer containment failed: ${error.message.split("\n")[0]}`);
|
|
28616
|
+
return void 0;
|
|
28617
|
+
}
|
|
28618
|
+
}
|
|
28619
|
+
emit(severity, message, ruleId, changes, containment) {
|
|
28620
|
+
const fullMessage = containment ? `${message}; ${summarizeContainment(containment)}` : message;
|
|
28621
|
+
if (containment) this.opts.log(`[file-integrity] ${fullMessage}`);
|
|
27418
28622
|
const event = {
|
|
27419
28623
|
timestamp: this.now(),
|
|
27420
28624
|
module: "file-integrity",
|
|
27421
28625
|
category: "system",
|
|
27422
28626
|
severity,
|
|
27423
|
-
message:
|
|
28627
|
+
message: fullMessage.replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 500),
|
|
27424
28628
|
details: {
|
|
27425
28629
|
rule_id: ruleId,
|
|
27426
28630
|
change_count: changes.length,
|
|
@@ -27428,7 +28632,8 @@ var FileIntegrityWatch = class {
|
|
|
27428
28632
|
path,
|
|
27429
28633
|
state: state === "missing" ? "missing" : "present"
|
|
27430
28634
|
})),
|
|
27431
|
-
truncated: changes.length > MAX_CHANGES_PER_EVENT
|
|
28635
|
+
truncated: changes.length > MAX_CHANGES_PER_EVENT,
|
|
28636
|
+
...containment ? { containment } : {}
|
|
27432
28637
|
}
|
|
27433
28638
|
};
|
|
27434
28639
|
try {
|
|
@@ -27440,9 +28645,308 @@ var FileIntegrityWatch = class {
|
|
|
27440
28645
|
};
|
|
27441
28646
|
|
|
27442
28647
|
// src/daemon/workers/edr.ts
|
|
27443
|
-
var
|
|
27444
|
-
var
|
|
28648
|
+
var import_node_fs29 = require("fs");
|
|
28649
|
+
var import_node_path25 = require("path");
|
|
28650
|
+
var import_node_child_process10 = require("child_process");
|
|
28651
|
+
|
|
28652
|
+
// src/daemon/workers/edr-ebpf.ts
|
|
27445
28653
|
var import_node_child_process9 = require("child_process");
|
|
28654
|
+
var import_node_fs28 = require("fs");
|
|
28655
|
+
var import_node_path24 = require("path");
|
|
28656
|
+
var BPFTRACE_RECORD_TAG = "TC1";
|
|
28657
|
+
var BTF_VMLINUX_PATH = "/sys/kernel/btf/vmlinux";
|
|
28658
|
+
var TCP_SYN_SENT = 2;
|
|
28659
|
+
var TCP_LISTEN = 10;
|
|
28660
|
+
var IPPROTO_TCP = 6;
|
|
28661
|
+
function bpftraceScript(opts) {
|
|
28662
|
+
const prefix = `"${BPFTRACE_RECORD_TAG}\\t%s\\t%d\\t%d\\t%d\\t%s\\n"`;
|
|
28663
|
+
const lines = [
|
|
28664
|
+
"tracepoint:sched:sched_process_exec",
|
|
28665
|
+
"{",
|
|
28666
|
+
` printf(${prefix}, "exec", pid, curtask->real_parent->tgid, curtask->cred->euid.val, str(args.filename));`,
|
|
28667
|
+
"}"
|
|
28668
|
+
];
|
|
28669
|
+
if (opts.network) {
|
|
28670
|
+
lines.push(
|
|
28671
|
+
"tracepoint:sock:inet_sock_set_state",
|
|
28672
|
+
`/args.protocol == ${IPPROTO_TCP} && args.newstate == ${TCP_SYN_SENT}/`,
|
|
28673
|
+
"{",
|
|
28674
|
+
` printf(${prefix}, "connect", pid, curtask->real_parent->tgid, curtask->cred->euid.val, comm);`,
|
|
28675
|
+
"}",
|
|
28676
|
+
"tracepoint:sock:inet_sock_set_state",
|
|
28677
|
+
`/args.protocol == ${IPPROTO_TCP} && args.newstate == ${TCP_LISTEN}/`,
|
|
28678
|
+
"{",
|
|
28679
|
+
` printf(${prefix}, "listen", pid, curtask->real_parent->tgid, curtask->cred->euid.val, comm);`,
|
|
28680
|
+
"}"
|
|
28681
|
+
);
|
|
28682
|
+
}
|
|
28683
|
+
return `${lines.join("\n")}
|
|
28684
|
+
`;
|
|
28685
|
+
}
|
|
28686
|
+
function bpftraceArgs(opts) {
|
|
28687
|
+
return ["-q", "-B", "line", "-f", "json", "-e", bpftraceScript(opts)];
|
|
28688
|
+
}
|
|
28689
|
+
var MAX_FIELD = 4096;
|
|
28690
|
+
function parseRecordText(text) {
|
|
28691
|
+
const body = text.endsWith("\n") ? text.slice(0, -1) : text;
|
|
28692
|
+
const parts = [];
|
|
28693
|
+
let rest = body;
|
|
28694
|
+
for (let i = 0; i < 5; i++) {
|
|
28695
|
+
const at = rest.indexOf(" ");
|
|
28696
|
+
if (at < 0) return null;
|
|
28697
|
+
parts.push(rest.slice(0, at));
|
|
28698
|
+
rest = rest.slice(at + 1);
|
|
28699
|
+
}
|
|
28700
|
+
const [tag, kind, pidText, ppidText, euidText] = parts;
|
|
28701
|
+
if (tag !== BPFTRACE_RECORD_TAG) return null;
|
|
28702
|
+
if (kind !== "exec" && kind !== "connect" && kind !== "listen") return null;
|
|
28703
|
+
const pid = Number(pidText);
|
|
28704
|
+
const ppid = Number(ppidText);
|
|
28705
|
+
const euid = Number(euidText);
|
|
28706
|
+
if (!/^\d+$/.test(pidText) || !/^\d+$/.test(ppidText) || !/^\d+$/.test(euidText)) return null;
|
|
28707
|
+
if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isSafeInteger(ppid) || !Number.isSafeInteger(euid)) return null;
|
|
28708
|
+
const value = rest.slice(0, MAX_FIELD);
|
|
28709
|
+
if (!value) return null;
|
|
28710
|
+
if (kind === "exec") {
|
|
28711
|
+
const base = value.slice(value.lastIndexOf("/") + 1).slice(0, 15);
|
|
28712
|
+
return { kind, pid, ppid, euid, filename: value, comm: base || value.slice(0, 15) };
|
|
28713
|
+
}
|
|
28714
|
+
return { kind, pid, ppid, euid, comm: value.slice(0, 64) };
|
|
28715
|
+
}
|
|
28716
|
+
function parseBpftraceLine(line) {
|
|
28717
|
+
const trimmed = line.replace(/\r$/, "");
|
|
28718
|
+
if (!trimmed) return null;
|
|
28719
|
+
if (trimmed.startsWith("{")) {
|
|
28720
|
+
let parsed;
|
|
28721
|
+
try {
|
|
28722
|
+
parsed = JSON.parse(trimmed);
|
|
28723
|
+
} catch {
|
|
28724
|
+
return null;
|
|
28725
|
+
}
|
|
28726
|
+
if (!parsed || typeof parsed !== "object") return null;
|
|
28727
|
+
const { type, data } = parsed;
|
|
28728
|
+
if (type === "printf" && typeof data === "string") {
|
|
28729
|
+
const event2 = parseRecordText(data);
|
|
28730
|
+
return event2 ? { type: "event", event: event2 } : null;
|
|
28731
|
+
}
|
|
28732
|
+
if (type === "attached_probes") {
|
|
28733
|
+
const probes = Number(data?.probes);
|
|
28734
|
+
return { type: "attached", probes: Number.isFinite(probes) ? probes : 0 };
|
|
28735
|
+
}
|
|
28736
|
+
if (type === "lost_events") {
|
|
28737
|
+
const count = Number(data?.events);
|
|
28738
|
+
return { type: "lost", count: Number.isFinite(count) ? count : 0 };
|
|
28739
|
+
}
|
|
28740
|
+
if (type === "error" || type === "warning") {
|
|
28741
|
+
return { type: "error", message: typeof data === "string" ? data.slice(0, 400) : JSON.stringify(data).slice(0, 400) };
|
|
28742
|
+
}
|
|
28743
|
+
return null;
|
|
28744
|
+
}
|
|
28745
|
+
const event = parseRecordText(trimmed);
|
|
28746
|
+
return event ? { type: "event", event } : null;
|
|
28747
|
+
}
|
|
28748
|
+
function selectEdrSource(probe) {
|
|
28749
|
+
if (probe.configured === "auditd") return { source: "auditd", degraded: false, reason: 'source = "auditd" configured' };
|
|
28750
|
+
const missing = [];
|
|
28751
|
+
if ((probe.platform ?? "linux") !== "linux") missing.push("not Linux");
|
|
28752
|
+
if (!probe.bpftracePath) missing.push("bpftrace not installed");
|
|
28753
|
+
if (!probe.btfPresent) missing.push(`kernel BTF (${BTF_VMLINUX_PATH}) missing`);
|
|
28754
|
+
if (!probe.isRoot) missing.push("daemon not running as root");
|
|
28755
|
+
if (missing.length === 0) {
|
|
28756
|
+
return { source: "ebpf", degraded: false, reason: `bpftrace at ${probe.bpftracePath} with kernel BTF, running as root` };
|
|
28757
|
+
}
|
|
28758
|
+
return {
|
|
28759
|
+
source: "auditd",
|
|
28760
|
+
degraded: probe.configured === "ebpf",
|
|
28761
|
+
reason: `eBPF unavailable (${missing.join("; ")}); using auditd`
|
|
28762
|
+
};
|
|
28763
|
+
}
|
|
28764
|
+
var BPFTRACE_DIRS = ["/usr/sbin", "/usr/bin", "/sbin", "/bin", "/usr/local/sbin", "/usr/local/bin", "/snap/bin"];
|
|
28765
|
+
function findBpftrace(env2 = process.env) {
|
|
28766
|
+
const dirs = [...BPFTRACE_DIRS, ...(env2.PATH ?? "").split(import_node_path24.delimiter).filter((dir) => dir.startsWith("/"))];
|
|
28767
|
+
for (const dir of new Set(dirs)) {
|
|
28768
|
+
const candidate = (0, import_node_path24.join)(dir, "bpftrace");
|
|
28769
|
+
try {
|
|
28770
|
+
(0, import_node_fs28.accessSync)(candidate, import_node_fs28.constants.X_OK);
|
|
28771
|
+
return candidate;
|
|
28772
|
+
} catch {
|
|
28773
|
+
}
|
|
28774
|
+
}
|
|
28775
|
+
return null;
|
|
28776
|
+
}
|
|
28777
|
+
function probeHost(configured) {
|
|
28778
|
+
return {
|
|
28779
|
+
configured,
|
|
28780
|
+
bpftracePath: configured === "auditd" ? null : findBpftrace(),
|
|
28781
|
+
btfPresent: (0, import_node_fs28.existsSync)(BTF_VMLINUX_PATH),
|
|
28782
|
+
isRoot: typeof process.getuid === "function" && process.getuid() === 0,
|
|
28783
|
+
platform: process.platform
|
|
28784
|
+
};
|
|
28785
|
+
}
|
|
28786
|
+
var STDERR_TAIL = 2048;
|
|
28787
|
+
var HEALTHY_AFTER_MS = 3e4;
|
|
28788
|
+
var KILL_GRACE_MS = 3e3;
|
|
28789
|
+
var BpftraceSource = class {
|
|
28790
|
+
constructor(opts) {
|
|
28791
|
+
this.opts = opts;
|
|
28792
|
+
this.spawnFn = opts.spawn ?? import_node_child_process9.spawn;
|
|
28793
|
+
this.minBackoffMs = opts.minBackoffMs ?? 1e3;
|
|
28794
|
+
this.maxBackoffMs = opts.maxBackoffMs ?? 6e4;
|
|
28795
|
+
this.maxFailedStarts = opts.maxFailedStarts ?? 3;
|
|
28796
|
+
this.maxLineBytes = opts.maxLineBytes ?? 64 * 1024;
|
|
28797
|
+
this.backoffMs = this.minBackoffMs;
|
|
28798
|
+
}
|
|
28799
|
+
opts;
|
|
28800
|
+
child = null;
|
|
28801
|
+
restartTimer = null;
|
|
28802
|
+
healthyTimer = null;
|
|
28803
|
+
stopped = true;
|
|
28804
|
+
healthy = false;
|
|
28805
|
+
failedStarts = 0;
|
|
28806
|
+
backoffMs;
|
|
28807
|
+
buffer = "";
|
|
28808
|
+
stderrTail = "";
|
|
28809
|
+
overflowLogged = false;
|
|
28810
|
+
spawnFn;
|
|
28811
|
+
minBackoffMs;
|
|
28812
|
+
maxBackoffMs;
|
|
28813
|
+
maxFailedStarts;
|
|
28814
|
+
maxLineBytes;
|
|
28815
|
+
get running() {
|
|
28816
|
+
return this.child !== null;
|
|
28817
|
+
}
|
|
28818
|
+
start() {
|
|
28819
|
+
if (!this.stopped) return;
|
|
28820
|
+
this.stopped = false;
|
|
28821
|
+
this.launch();
|
|
28822
|
+
}
|
|
28823
|
+
stop() {
|
|
28824
|
+
this.stopped = true;
|
|
28825
|
+
if (this.restartTimer) clearTimeout(this.restartTimer);
|
|
28826
|
+
if (this.healthyTimer) clearTimeout(this.healthyTimer);
|
|
28827
|
+
this.restartTimer = null;
|
|
28828
|
+
this.healthyTimer = null;
|
|
28829
|
+
const child = this.child;
|
|
28830
|
+
this.child = null;
|
|
28831
|
+
if (child && child.exitCode === null && child.signalCode === null) {
|
|
28832
|
+
try {
|
|
28833
|
+
child.kill("SIGTERM");
|
|
28834
|
+
} catch {
|
|
28835
|
+
}
|
|
28836
|
+
const killer = setTimeout(() => {
|
|
28837
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
28838
|
+
try {
|
|
28839
|
+
child.kill("SIGKILL");
|
|
28840
|
+
} catch {
|
|
28841
|
+
}
|
|
28842
|
+
}
|
|
28843
|
+
}, KILL_GRACE_MS);
|
|
28844
|
+
killer.unref?.();
|
|
28845
|
+
}
|
|
28846
|
+
this.buffer = "";
|
|
28847
|
+
}
|
|
28848
|
+
/** Feed raw stdout; exposed for tests. */
|
|
28849
|
+
ingest(chunk) {
|
|
28850
|
+
this.buffer += chunk;
|
|
28851
|
+
let newline = this.buffer.indexOf("\n");
|
|
28852
|
+
while (newline >= 0) {
|
|
28853
|
+
const line = this.buffer.slice(0, newline);
|
|
28854
|
+
this.buffer = this.buffer.slice(newline + 1);
|
|
28855
|
+
this.handleLine(line);
|
|
28856
|
+
newline = this.buffer.indexOf("\n");
|
|
28857
|
+
}
|
|
28858
|
+
if (this.buffer.length > this.maxLineBytes) {
|
|
28859
|
+
if (!this.overflowLogged) this.opts.log(`[edr] discarded an oversized bpftrace output line (>${this.maxLineBytes} bytes)`);
|
|
28860
|
+
this.overflowLogged = true;
|
|
28861
|
+
this.buffer = "";
|
|
28862
|
+
}
|
|
28863
|
+
}
|
|
28864
|
+
handleLine(line) {
|
|
28865
|
+
if (line.length > this.maxLineBytes) return;
|
|
28866
|
+
const parsed = parseBpftraceLine(line);
|
|
28867
|
+
if (!parsed) return;
|
|
28868
|
+
if (parsed.type === "event") {
|
|
28869
|
+
this.markHealthy();
|
|
28870
|
+
this.opts.onEvent(parsed.event);
|
|
28871
|
+
} else if (parsed.type === "attached") {
|
|
28872
|
+
this.markHealthy();
|
|
28873
|
+
this.opts.log(`[edr] bpftrace attached ${parsed.probes} probe(s)`);
|
|
28874
|
+
} else if (parsed.type === "lost") {
|
|
28875
|
+
this.opts.log(`[edr] bpftrace dropped ${parsed.count} event(s) (perf buffer full)`);
|
|
28876
|
+
} else if (parsed.type === "error") {
|
|
28877
|
+
this.opts.log(`[edr] bpftrace: ${parsed.message}`);
|
|
28878
|
+
}
|
|
28879
|
+
}
|
|
28880
|
+
markHealthy() {
|
|
28881
|
+
if (this.healthy) return;
|
|
28882
|
+
this.healthy = true;
|
|
28883
|
+
this.failedStarts = 0;
|
|
28884
|
+
this.backoffMs = this.minBackoffMs;
|
|
28885
|
+
}
|
|
28886
|
+
launch() {
|
|
28887
|
+
if (this.stopped) return;
|
|
28888
|
+
this.healthy = false;
|
|
28889
|
+
this.buffer = "";
|
|
28890
|
+
this.stderrTail = "";
|
|
28891
|
+
let child;
|
|
28892
|
+
try {
|
|
28893
|
+
child = this.spawnFn(this.opts.bpftracePath, bpftraceArgs({ network: this.opts.network }), {
|
|
28894
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
28895
|
+
shell: false,
|
|
28896
|
+
env: { PATH: "/usr/sbin:/usr/bin:/sbin:/bin", LANG: "C" }
|
|
28897
|
+
});
|
|
28898
|
+
} catch (error) {
|
|
28899
|
+
this.onExit(null, null, error.message);
|
|
28900
|
+
return;
|
|
28901
|
+
}
|
|
28902
|
+
this.child = child;
|
|
28903
|
+
child.stdout?.setEncoding("utf8");
|
|
28904
|
+
child.stderr?.setEncoding("utf8");
|
|
28905
|
+
child.stdout?.on("data", (chunk) => {
|
|
28906
|
+
if (this.child === child) this.ingest(chunk);
|
|
28907
|
+
});
|
|
28908
|
+
child.stderr?.on("data", (chunk) => {
|
|
28909
|
+
this.stderrTail = (this.stderrTail + chunk).slice(-STDERR_TAIL);
|
|
28910
|
+
});
|
|
28911
|
+
let finished = false;
|
|
28912
|
+
const finish = (code, signal, error) => {
|
|
28913
|
+
if (finished) return;
|
|
28914
|
+
finished = true;
|
|
28915
|
+
if (this.child !== child) return;
|
|
28916
|
+
this.child = null;
|
|
28917
|
+
this.onExit(code, signal, error);
|
|
28918
|
+
};
|
|
28919
|
+
child.on("error", (error) => finish(null, null, error.message));
|
|
28920
|
+
child.on("exit", (code, signal) => finish(code, signal));
|
|
28921
|
+
if (this.healthyTimer) clearTimeout(this.healthyTimer);
|
|
28922
|
+
this.healthyTimer = setTimeout(() => {
|
|
28923
|
+
if (this.child === child) this.markHealthy();
|
|
28924
|
+
}, HEALTHY_AFTER_MS);
|
|
28925
|
+
this.healthyTimer.unref?.();
|
|
28926
|
+
}
|
|
28927
|
+
onExit(code, signal, error) {
|
|
28928
|
+
if (this.healthyTimer) clearTimeout(this.healthyTimer);
|
|
28929
|
+
this.healthyTimer = null;
|
|
28930
|
+
if (this.stopped) return;
|
|
28931
|
+
const detail = error ?? (this.stderrTail.trim().split("\n").slice(-1)[0] || `exit ${code ?? signal ?? "unknown"}`);
|
|
28932
|
+
if (!this.healthy) this.failedStarts++;
|
|
28933
|
+
if (!this.healthy && this.failedStarts >= this.maxFailedStarts) {
|
|
28934
|
+
this.stopped = true;
|
|
28935
|
+
this.opts.onFatal(`bpftrace failed to start ${this.failedStarts} time(s): ${detail.slice(0, 300)}`);
|
|
28936
|
+
return;
|
|
28937
|
+
}
|
|
28938
|
+
const delay = this.backoffMs;
|
|
28939
|
+
this.backoffMs = Math.min(this.maxBackoffMs, this.backoffMs * 2);
|
|
28940
|
+
this.opts.log(`[edr] bpftrace exited (${detail.slice(0, 300)}); restarting in ${Math.round(delay / 1e3)}s`);
|
|
28941
|
+
this.restartTimer = setTimeout(() => {
|
|
28942
|
+
this.restartTimer = null;
|
|
28943
|
+
this.launch();
|
|
28944
|
+
}, delay);
|
|
28945
|
+
this.restartTimer.unref?.();
|
|
28946
|
+
}
|
|
28947
|
+
};
|
|
28948
|
+
|
|
28949
|
+
// src/daemon/workers/edr.ts
|
|
27446
28950
|
var DEFAULT_AUDIT_LOG = "/var/log/audit/audit.log";
|
|
27447
28951
|
var DEFAULT_WEB_USERS = ["www-data", "nginx", "apache", "httpd", "caddy", "node"];
|
|
27448
28952
|
var DEFAULT_TEMP_PATHS = ["/tmp", "/var/tmp", "/dev/shm"];
|
|
@@ -27459,8 +28963,8 @@ var SHELLS2 = /* @__PURE__ */ new Set(["sh", "bash", "dash", "zsh", "ksh", "fish
|
|
|
27459
28963
|
var DOWNLOADERS = /* @__PURE__ */ new Set(["curl", "wget"]);
|
|
27460
28964
|
var MINERS = /* @__PURE__ */ new Set(["xmrig", "minerd", "cpuminer", "cpuminer-multi", "kdevtmpfsi", "kinsing", "cryptonight"]);
|
|
27461
28965
|
function safeAbsolutePath(value) {
|
|
27462
|
-
if (typeof value !== "string" || !(0,
|
|
27463
|
-
const path = (0,
|
|
28966
|
+
if (typeof value !== "string" || !(0, import_node_path25.isAbsolute)(value) || value.split(import_node_path25.sep).includes("..")) return null;
|
|
28967
|
+
const path = (0, import_node_path25.normalize)(value);
|
|
27464
28968
|
return path === "/" ? null : path;
|
|
27465
28969
|
}
|
|
27466
28970
|
function edrSettings(section) {
|
|
@@ -27470,8 +28974,10 @@ function edrSettings(section) {
|
|
|
27470
28974
|
const seconds = section?.poll_interval_seconds;
|
|
27471
28975
|
const pollMs = typeof seconds === "number" && Number.isFinite(seconds) ? Math.max(1, Math.min(60, Math.floor(seconds))) * 1e3 : 2e3;
|
|
27472
28976
|
const baselineSeconds = section?.network_baseline_seconds;
|
|
28977
|
+
const source = section?.source === "auto" || section?.source === "ebpf" ? section.source : "auditd";
|
|
27473
28978
|
return {
|
|
27474
28979
|
enabled: section?.enabled === true,
|
|
28980
|
+
source,
|
|
27475
28981
|
auditLogPath: configuredLog,
|
|
27476
28982
|
webServiceUsers: configuredUsers,
|
|
27477
28983
|
tempExecPaths: configuredPaths,
|
|
@@ -27506,7 +29012,7 @@ function parseAuditRecord(line) {
|
|
|
27506
29012
|
serial: header[2],
|
|
27507
29013
|
key: fields.key,
|
|
27508
29014
|
executable,
|
|
27509
|
-
comm: fields.comm ?? (0,
|
|
29015
|
+
comm: fields.comm ?? (0, import_node_path25.basename)(executable),
|
|
27510
29016
|
euid,
|
|
27511
29017
|
...Number.isInteger(pid) && pid > 0 ? { pid } : {},
|
|
27512
29018
|
...Number.isInteger(ppid) && ppid > 0 ? { ppid } : {}
|
|
@@ -27515,10 +29021,10 @@ function parseAuditRecord(line) {
|
|
|
27515
29021
|
function accountNames2() {
|
|
27516
29022
|
let raw = "";
|
|
27517
29023
|
try {
|
|
27518
|
-
raw = (0,
|
|
29024
|
+
raw = (0, import_node_child_process10.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
|
|
27519
29025
|
} catch {
|
|
27520
29026
|
try {
|
|
27521
|
-
raw = (0,
|
|
29027
|
+
raw = (0, import_node_fs29.readFileSync)("/etc/passwd", "utf8");
|
|
27522
29028
|
} catch {
|
|
27523
29029
|
return /* @__PURE__ */ new Map();
|
|
27524
29030
|
}
|
|
@@ -27536,7 +29042,7 @@ function pathWithin(path, root) {
|
|
|
27536
29042
|
}
|
|
27537
29043
|
function executableInWorldWritableDirectory(executable) {
|
|
27538
29044
|
try {
|
|
27539
|
-
return ((0,
|
|
29045
|
+
return ((0, import_node_fs29.statSync)((0, import_node_path25.dirname)(executable)).mode & 2) !== 0;
|
|
27540
29046
|
} catch {
|
|
27541
29047
|
return false;
|
|
27542
29048
|
}
|
|
@@ -27544,6 +29050,26 @@ function executableInWorldWritableDirectory(executable) {
|
|
|
27544
29050
|
function clean(value) {
|
|
27545
29051
|
return value.replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 400);
|
|
27546
29052
|
}
|
|
29053
|
+
var EXEC_KEYS = [MINER_KEY, WEB_KEY, TEMP_KEY];
|
|
29054
|
+
var MAX_EBPF_EXE_CACHE = 4096;
|
|
29055
|
+
function ebpfEventToRecords(event, resolveExe, now = /* @__PURE__ */ new Date(), serial = "ebpf") {
|
|
29056
|
+
let executable = resolveExe(event.pid);
|
|
29057
|
+
if (!executable && event.kind === "exec" && event.filename?.startsWith("/")) executable = event.filename;
|
|
29058
|
+
if (!executable || !executable.startsWith("/")) return [];
|
|
29059
|
+
const base = {
|
|
29060
|
+
timestamp: now,
|
|
29061
|
+
source: "ebpf",
|
|
29062
|
+
serial,
|
|
29063
|
+
executable,
|
|
29064
|
+
comm: event.comm || (0, import_node_path25.basename)(executable),
|
|
29065
|
+
euid: event.euid,
|
|
29066
|
+
pid: event.pid,
|
|
29067
|
+
...event.ppid > 0 ? { ppid: event.ppid } : {}
|
|
29068
|
+
};
|
|
29069
|
+
if (event.kind === "connect") return [{ ...base, key: CONNECT_KEY }];
|
|
29070
|
+
if (event.kind === "listen") return [{ ...base, key: LISTEN_KEY }];
|
|
29071
|
+
return EXEC_KEYS.map((key) => ({ ...base, key }));
|
|
29072
|
+
}
|
|
27547
29073
|
var EdrWatch = class {
|
|
27548
29074
|
constructor(opts) {
|
|
27549
29075
|
this.opts = opts;
|
|
@@ -27554,6 +29080,10 @@ var EdrWatch = class {
|
|
|
27554
29080
|
}
|
|
27555
29081
|
opts;
|
|
27556
29082
|
tail = null;
|
|
29083
|
+
bpftrace = null;
|
|
29084
|
+
ebpfSerial = 0;
|
|
29085
|
+
ebpfExeCache = /* @__PURE__ */ new Map();
|
|
29086
|
+
activeSource = "none";
|
|
27557
29087
|
timer = null;
|
|
27558
29088
|
cpuTimer = null;
|
|
27559
29089
|
usersById;
|
|
@@ -27570,18 +29100,13 @@ var EdrWatch = class {
|
|
|
27570
29100
|
this.opts.log("[edr] disabled; set [edr] enabled = true after installing the generated audit rules");
|
|
27571
29101
|
return;
|
|
27572
29102
|
}
|
|
27573
|
-
|
|
27574
|
-
|
|
29103
|
+
const probe = this.probe();
|
|
29104
|
+
const selection = selectEdrSource(probe);
|
|
29105
|
+
if (selection.source === "ebpf" && probe.bpftracePath) {
|
|
29106
|
+
this.startEbpf(probe.bpftracePath, selection.reason);
|
|
27575
29107
|
} else {
|
|
27576
|
-
|
|
27577
|
-
|
|
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
|
-
}
|
|
29108
|
+
if (selection.degraded) this.opts.log(`[edr] source = "ebpf" requested but ${selection.reason}`);
|
|
29109
|
+
this.startAuditd(selection.reason);
|
|
27585
29110
|
}
|
|
27586
29111
|
if (this.opts.settings.watchUnknownTempCpu) {
|
|
27587
29112
|
this.cpuTimer = setInterval(() => this.sampleTemporaryProcesses(), CPU_SAMPLE_MS);
|
|
@@ -27590,7 +29115,109 @@ var EdrWatch = class {
|
|
|
27590
29115
|
this.opts.log(`[edr] watching temporary-path processes for sustained CPU use (${CPU_THRESHOLD_PERCENT}% for ${CPU_SUSTAIN_MS / 1e3}s)`);
|
|
27591
29116
|
}
|
|
27592
29117
|
}
|
|
29118
|
+
/** The event source currently feeding detections. */
|
|
29119
|
+
get source() {
|
|
29120
|
+
return this.activeSource;
|
|
29121
|
+
}
|
|
29122
|
+
probe() {
|
|
29123
|
+
const configured = this.opts.settings.source;
|
|
29124
|
+
if (configured === "auditd") return { configured, bpftracePath: null, btfPresent: false, isRoot: false };
|
|
29125
|
+
return (this.opts.probeHost ?? probeHost)(configured);
|
|
29126
|
+
}
|
|
29127
|
+
startEbpf(bpftracePath, reason) {
|
|
29128
|
+
const options = {
|
|
29129
|
+
bpftracePath,
|
|
29130
|
+
network: this.opts.settings.watchNetworkSyscalls,
|
|
29131
|
+
onEvent: (event) => {
|
|
29132
|
+
this.handleEbpfEvent(event);
|
|
29133
|
+
},
|
|
29134
|
+
onFatal: (failure) => {
|
|
29135
|
+
this.bpftrace = null;
|
|
29136
|
+
this.opts.log(`[edr] ${failure}; falling back to auditd`);
|
|
29137
|
+
this.startAuditd(`eBPF failed: ${failure}`);
|
|
29138
|
+
},
|
|
29139
|
+
log: this.opts.log
|
|
29140
|
+
};
|
|
29141
|
+
this.bpftrace = this.opts.createBpftrace ? this.opts.createBpftrace(options) : new BpftraceSource(options);
|
|
29142
|
+
this.setSource("ebpf", reason);
|
|
29143
|
+
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`);
|
|
29144
|
+
this.bpftrace.start();
|
|
29145
|
+
}
|
|
29146
|
+
startAuditd(reason) {
|
|
29147
|
+
if (!(0, import_node_fs29.existsSync)(this.opts.settings.auditLogPath)) {
|
|
29148
|
+
this.opts.log(`[edr] audit log not found at ${this.opts.settings.auditLogPath}; auditd detections are unavailable`);
|
|
29149
|
+
this.setSource("none", `${reason}; audit log not found at ${this.opts.settings.auditLogPath}`);
|
|
29150
|
+
return;
|
|
29151
|
+
}
|
|
29152
|
+
try {
|
|
29153
|
+
(0, import_node_fs29.accessSync)(this.opts.settings.auditLogPath, import_node_fs29.constants.R_OK);
|
|
29154
|
+
this.tail = new LogTail(this.opts.settings.auditLogPath);
|
|
29155
|
+
this.timer = setInterval(() => this.poll(), this.opts.settings.pollMs);
|
|
29156
|
+
this.timer.unref?.();
|
|
29157
|
+
this.setSource("auditd", reason);
|
|
29158
|
+
this.opts.log(`[edr] event source: auditd; watching selected events in ${this.opts.settings.auditLogPath}; command arguments and remote addresses are discarded`);
|
|
29159
|
+
} catch {
|
|
29160
|
+
this.opts.log(`[edr] cannot read ${this.opts.settings.auditLogPath}; run the daemon with permission to read the audit log`);
|
|
29161
|
+
this.setSource("none", `${reason}; cannot read ${this.opts.settings.auditLogPath}`);
|
|
29162
|
+
}
|
|
29163
|
+
}
|
|
29164
|
+
setSource(active2, reason) {
|
|
29165
|
+
this.activeSource = active2;
|
|
29166
|
+
const path = this.opts.sourceStatusPath;
|
|
29167
|
+
if (!path) return;
|
|
29168
|
+
const status = {
|
|
29169
|
+
configured: this.opts.settings.source,
|
|
29170
|
+
active: active2,
|
|
29171
|
+
reason,
|
|
29172
|
+
updated_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
29173
|
+
pid: process.pid
|
|
29174
|
+
};
|
|
29175
|
+
try {
|
|
29176
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
29177
|
+
(0, import_node_fs29.writeFileSync)(temp, `${JSON.stringify(status)}
|
|
29178
|
+
`, { mode: 420 });
|
|
29179
|
+
(0, import_node_fs29.renameSync)(temp, path);
|
|
29180
|
+
} catch {
|
|
29181
|
+
}
|
|
29182
|
+
}
|
|
29183
|
+
resolveEbpfExe(event) {
|
|
29184
|
+
let exe = null;
|
|
29185
|
+
try {
|
|
29186
|
+
exe = (0, import_node_fs29.readlinkSync)(`/proc/${event.pid}/exe`).replace(/ \(deleted\)$/, "");
|
|
29187
|
+
} catch {
|
|
29188
|
+
}
|
|
29189
|
+
if (!exe && event.kind !== "exec") exe = this.ebpfExeCache.get(event.pid) ?? null;
|
|
29190
|
+
if (!exe && event.kind === "exec" && event.filename?.startsWith("/")) exe = event.filename;
|
|
29191
|
+
if (exe && event.kind === "exec") {
|
|
29192
|
+
this.ebpfExeCache.delete(event.pid);
|
|
29193
|
+
this.ebpfExeCache.set(event.pid, exe);
|
|
29194
|
+
if (this.ebpfExeCache.size > MAX_EBPF_EXE_CACHE) this.ebpfExeCache.delete(this.ebpfExeCache.keys().next().value);
|
|
29195
|
+
}
|
|
29196
|
+
return exe;
|
|
29197
|
+
}
|
|
29198
|
+
/** Classify one eBPF event through the same rules as auditd records. Returns the event published, if any. */
|
|
29199
|
+
handleEbpfEvent(event, resolveExe) {
|
|
29200
|
+
if ((event.kind === "connect" || event.kind === "listen") && !this.opts.settings.watchNetworkSyscalls) return null;
|
|
29201
|
+
this.ebpfSerial = (this.ebpfSerial + 1) % Number.MAX_SAFE_INTEGER;
|
|
29202
|
+
const resolver = resolveExe ?? (() => this.resolveEbpfExe(event));
|
|
29203
|
+
const records = ebpfEventToRecords(event, resolver, /* @__PURE__ */ new Date(), `ebpf-${this.ebpfSerial}`);
|
|
29204
|
+
for (const record of records) {
|
|
29205
|
+
const threat = this.classify(record);
|
|
29206
|
+
if (threat) {
|
|
29207
|
+
this.publish(threat);
|
|
29208
|
+
return threat;
|
|
29209
|
+
}
|
|
29210
|
+
}
|
|
29211
|
+
return null;
|
|
29212
|
+
}
|
|
27593
29213
|
stop() {
|
|
29214
|
+
try {
|
|
29215
|
+
this.bpftrace?.stop();
|
|
29216
|
+
} catch {
|
|
29217
|
+
}
|
|
29218
|
+
this.bpftrace = null;
|
|
29219
|
+
this.ebpfExeCache.clear();
|
|
29220
|
+
this.activeSource = "none";
|
|
27594
29221
|
if (this.timer) clearInterval(this.timer);
|
|
27595
29222
|
if (this.cpuTimer) clearInterval(this.cpuTimer);
|
|
27596
29223
|
this.timer = null;
|
|
@@ -27622,7 +29249,7 @@ var EdrWatch = class {
|
|
|
27622
29249
|
this.opts.bus.publish(event);
|
|
27623
29250
|
}
|
|
27624
29251
|
classify(execution) {
|
|
27625
|
-
const name = (0,
|
|
29252
|
+
const name = (0, import_node_path25.basename)(execution.executable).toLowerCase();
|
|
27626
29253
|
const account = this.usersById.get(execution.euid) ?? String(execution.euid);
|
|
27627
29254
|
let severity;
|
|
27628
29255
|
let ruleId;
|
|
@@ -27677,7 +29304,8 @@ var EdrWatch = class {
|
|
|
27677
29304
|
euid: execution.euid,
|
|
27678
29305
|
...execution.pid ? { pid: execution.pid } : {},
|
|
27679
29306
|
...execution.ppid ? { ppid: execution.ppid } : {},
|
|
27680
|
-
|
|
29307
|
+
event_source: execution.source ?? "auditd",
|
|
29308
|
+
...execution.source === "ebpf" ? {} : { audit_serial: execution.serial }
|
|
27681
29309
|
}
|
|
27682
29310
|
};
|
|
27683
29311
|
}
|
|
@@ -27685,7 +29313,7 @@ var EdrWatch = class {
|
|
|
27685
29313
|
const path = this.opts.networkBaselinePath;
|
|
27686
29314
|
if (!path) return;
|
|
27687
29315
|
try {
|
|
27688
|
-
const parsed = JSON.parse((0,
|
|
29316
|
+
const parsed = JSON.parse((0, import_node_fs29.readFileSync)(path, "utf8"));
|
|
27689
29317
|
if (Array.isArray(parsed)) {
|
|
27690
29318
|
for (const value of parsed.slice(0, 1e4)) {
|
|
27691
29319
|
if (typeof value === "string" && value.startsWith("/")) this.outboundExecutables.add(value);
|
|
@@ -27702,9 +29330,9 @@ var EdrWatch = class {
|
|
|
27702
29330
|
if (!path) return;
|
|
27703
29331
|
try {
|
|
27704
29332
|
const temp = `${path}.${process.pid}.tmp`;
|
|
27705
|
-
(0,
|
|
29333
|
+
(0, import_node_fs29.writeFileSync)(temp, `${JSON.stringify([...this.outboundExecutables])}
|
|
27706
29334
|
`, { mode: 384 });
|
|
27707
|
-
(0,
|
|
29335
|
+
(0, import_node_fs29.renameSync)(temp, path);
|
|
27708
29336
|
this.baselineWriteFailed = false;
|
|
27709
29337
|
} catch (error) {
|
|
27710
29338
|
if (!this.baselineWriteFailed) this.opts.log(`[edr] could not persist outbound executable baseline: ${error.message.split("\n")[0]}`);
|
|
@@ -27713,7 +29341,7 @@ var EdrWatch = class {
|
|
|
27713
29341
|
}
|
|
27714
29342
|
readTicksPerSecond() {
|
|
27715
29343
|
try {
|
|
27716
|
-
const value = Number((0,
|
|
29344
|
+
const value = Number((0, import_node_child_process10.execFileSync)("getconf", ["CLK_TCK"], { encoding: "utf8", timeout: 2e3, stdio: ["ignore", "pipe", "ignore"] }).trim());
|
|
27717
29345
|
if (Number.isFinite(value) && value > 0) return value;
|
|
27718
29346
|
} catch {
|
|
27719
29347
|
}
|
|
@@ -27725,7 +29353,7 @@ var EdrWatch = class {
|
|
|
27725
29353
|
const current = /* @__PURE__ */ new Map();
|
|
27726
29354
|
let pids;
|
|
27727
29355
|
try {
|
|
27728
|
-
pids = (0,
|
|
29356
|
+
pids = (0, import_node_fs29.readdirSync)("/proc");
|
|
27729
29357
|
} catch {
|
|
27730
29358
|
return;
|
|
27731
29359
|
}
|
|
@@ -27733,7 +29361,7 @@ var EdrWatch = class {
|
|
|
27733
29361
|
if (!/^\d+$/.test(pid)) continue;
|
|
27734
29362
|
const proc = `/proc/${pid}`;
|
|
27735
29363
|
try {
|
|
27736
|
-
const raw = (0,
|
|
29364
|
+
const raw = (0, import_node_fs29.readFileSync)(`${proc}/stat`, "utf8");
|
|
27737
29365
|
const end = raw.lastIndexOf(")");
|
|
27738
29366
|
if (end < 0) continue;
|
|
27739
29367
|
const fields = raw.slice(end + 1).trim().split(/\s+/);
|
|
@@ -27741,10 +29369,10 @@ var EdrWatch = class {
|
|
|
27741
29369
|
const systemTicks = Number(fields[12]);
|
|
27742
29370
|
const startTicks = fields[19];
|
|
27743
29371
|
if (!Number.isFinite(userTicks) || !Number.isFinite(systemTicks) || !startTicks) continue;
|
|
27744
|
-
let executable = (0,
|
|
29372
|
+
let executable = (0, import_node_fs29.readlinkSync)(`${proc}/exe`);
|
|
27745
29373
|
executable = executable.replace(/ \(deleted\)$/, "");
|
|
27746
29374
|
if (!this.opts.settings.tempExecPaths.some((path) => pathWithin(executable, path))) continue;
|
|
27747
|
-
const name = (0,
|
|
29375
|
+
const name = (0, import_node_path25.basename)(executable).toLowerCase();
|
|
27748
29376
|
if (MINERS.has(name)) continue;
|
|
27749
29377
|
const key = `${pid}:${startTicks}`;
|
|
27750
29378
|
const ticks = userTicks + systemTicks;
|
|
@@ -27780,9 +29408,9 @@ var EdrWatch = class {
|
|
|
27780
29408
|
};
|
|
27781
29409
|
|
|
27782
29410
|
// src/daemon/workers/ssh-intrusion.ts
|
|
27783
|
-
var
|
|
27784
|
-
var
|
|
27785
|
-
var
|
|
29411
|
+
var import_node_fs30 = require("fs");
|
|
29412
|
+
var import_node_path26 = require("path");
|
|
29413
|
+
var import_node_child_process11 = require("child_process");
|
|
27786
29414
|
|
|
27787
29415
|
// src/core/asn.ts
|
|
27788
29416
|
var import_node_dns = require("dns");
|
|
@@ -27975,35 +29603,35 @@ function parseKeyLoginsByFingerprint(text) {
|
|
|
27975
29603
|
}
|
|
27976
29604
|
function readJson2(path) {
|
|
27977
29605
|
try {
|
|
27978
|
-
return JSON.parse((0,
|
|
29606
|
+
return JSON.parse((0, import_node_fs30.readFileSync)(path, "utf-8"));
|
|
27979
29607
|
} catch {
|
|
27980
29608
|
return null;
|
|
27981
29609
|
}
|
|
27982
29610
|
}
|
|
27983
29611
|
function writeJson2(path, value) {
|
|
27984
|
-
(0,
|
|
27985
|
-
(0,
|
|
27986
|
-
(0,
|
|
29612
|
+
(0, import_node_fs30.mkdirSync)((0, import_node_path26.dirname)(path), { recursive: true });
|
|
29613
|
+
(0, import_node_fs30.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
|
|
29614
|
+
(0, import_node_fs30.renameSync)(`${path}.tmp`, path);
|
|
27987
29615
|
}
|
|
27988
29616
|
var fsIO2 = {
|
|
27989
29617
|
readFile: (p) => {
|
|
27990
29618
|
try {
|
|
27991
|
-
return (0,
|
|
29619
|
+
return (0, import_node_fs30.readFileSync)(p, "utf-8");
|
|
27992
29620
|
} catch {
|
|
27993
29621
|
return null;
|
|
27994
29622
|
}
|
|
27995
29623
|
},
|
|
27996
29624
|
readDir: (p) => {
|
|
27997
29625
|
try {
|
|
27998
|
-
return (0,
|
|
29626
|
+
return (0, import_node_fs30.readdirSync)(p);
|
|
27999
29627
|
} catch {
|
|
28000
29628
|
return null;
|
|
28001
29629
|
}
|
|
28002
29630
|
},
|
|
28003
|
-
exists: (p) => (0,
|
|
29631
|
+
exists: (p) => (0, import_node_fs30.existsSync)(p)
|
|
28004
29632
|
};
|
|
28005
29633
|
function defaultRun4(cmd, args) {
|
|
28006
|
-
const res = (0,
|
|
29634
|
+
const res = (0, import_node_child_process11.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
|
|
28007
29635
|
return res.status === 0 ? res.stdout : null;
|
|
28008
29636
|
}
|
|
28009
29637
|
var SshIntrusionWatch = class {
|
|
@@ -28201,23 +29829,23 @@ var SshIntrusionWatch = class {
|
|
|
28201
29829
|
};
|
|
28202
29830
|
|
|
28203
29831
|
// src/daemon/key-directory.ts
|
|
28204
|
-
var
|
|
29832
|
+
var import_node_fs31 = require("fs");
|
|
28205
29833
|
var fsIO3 = {
|
|
28206
29834
|
readFile: (p) => {
|
|
28207
29835
|
try {
|
|
28208
|
-
return (0,
|
|
29836
|
+
return (0, import_node_fs31.readFileSync)(p, "utf-8");
|
|
28209
29837
|
} catch {
|
|
28210
29838
|
return null;
|
|
28211
29839
|
}
|
|
28212
29840
|
},
|
|
28213
29841
|
readDir: (p) => {
|
|
28214
29842
|
try {
|
|
28215
|
-
return (0,
|
|
29843
|
+
return (0, import_node_fs31.readdirSync)(p);
|
|
28216
29844
|
} catch {
|
|
28217
29845
|
return null;
|
|
28218
29846
|
}
|
|
28219
29847
|
},
|
|
28220
|
-
exists: (p) => (0,
|
|
29848
|
+
exists: (p) => (0, import_node_fs31.existsSync)(p)
|
|
28221
29849
|
};
|
|
28222
29850
|
var KeyDirectory = class {
|
|
28223
29851
|
constructor(io = fsIO3, now = Date.now, ttlMs = 3e5) {
|
|
@@ -28261,7 +29889,7 @@ function enrichLoginEvent(event, keys) {
|
|
|
28261
29889
|
}
|
|
28262
29890
|
|
|
28263
29891
|
// src/daemon/workers/lightning-watch.ts
|
|
28264
|
-
var
|
|
29892
|
+
var import_node_fs32 = require("fs");
|
|
28265
29893
|
var DEFAULT_CLN_LOGS = [
|
|
28266
29894
|
"/home/lightning/.lightning/cln.log",
|
|
28267
29895
|
"/root/.lightning/cln.log",
|
|
@@ -28317,9 +29945,9 @@ var LightningWatch = class {
|
|
|
28317
29945
|
if (this.opts.enabled === false) return [];
|
|
28318
29946
|
const found = [];
|
|
28319
29947
|
for (const path of this.opts.paths?.length ? this.opts.paths : DEFAULT_CLN_LOGS) {
|
|
28320
|
-
if (!(0,
|
|
29948
|
+
if (!(0, import_node_fs32.existsSync)(path)) continue;
|
|
28321
29949
|
try {
|
|
28322
|
-
(0,
|
|
29950
|
+
(0, import_node_fs32.accessSync)(path, import_node_fs32.constants.R_OK);
|
|
28323
29951
|
} catch {
|
|
28324
29952
|
continue;
|
|
28325
29953
|
}
|
|
@@ -28354,12 +29982,12 @@ var LightningWatch = class {
|
|
|
28354
29982
|
};
|
|
28355
29983
|
|
|
28356
29984
|
// src/daemon/workers/docker-logs.ts
|
|
28357
|
-
var
|
|
29985
|
+
var import_node_fs34 = require("fs");
|
|
28358
29986
|
var import_node_http = require("http");
|
|
28359
29987
|
var import_node_net12 = require("net");
|
|
28360
29988
|
|
|
28361
29989
|
// src/daemon/workers/postgres-shell.ts
|
|
28362
|
-
var
|
|
29990
|
+
var import_node_fs33 = require("fs");
|
|
28363
29991
|
var DEFAULT_ALLOW_CMDLINE = [
|
|
28364
29992
|
// Supabase's pgsodium reads its root key by running this script at startup.
|
|
28365
29993
|
String.raw`^(?:\S*/)?(?:ba|da)?sh (?:-c )?(?:\S*/)?pgsodium_getkey(?:\.sh)?$`,
|
|
@@ -28503,28 +30131,28 @@ function shellLogDetector(cooldownMs = 6e4, now = Date.now) {
|
|
|
28503
30131
|
var realProcFs = {
|
|
28504
30132
|
pids: () => {
|
|
28505
30133
|
try {
|
|
28506
|
-
return (0,
|
|
30134
|
+
return (0, import_node_fs33.readdirSync)("/proc").filter((n) => /^\d+$/.test(n)).map(Number);
|
|
28507
30135
|
} catch {
|
|
28508
30136
|
return [];
|
|
28509
30137
|
}
|
|
28510
30138
|
},
|
|
28511
30139
|
stat: (pid) => {
|
|
28512
30140
|
try {
|
|
28513
|
-
return (0,
|
|
30141
|
+
return (0, import_node_fs33.readFileSync)(`/proc/${pid}/stat`, "utf-8");
|
|
28514
30142
|
} catch {
|
|
28515
30143
|
return null;
|
|
28516
30144
|
}
|
|
28517
30145
|
},
|
|
28518
30146
|
cmdline: (pid) => {
|
|
28519
30147
|
try {
|
|
28520
|
-
return (0,
|
|
30148
|
+
return (0, import_node_fs33.readFileSync)(`/proc/${pid}/cmdline`, "utf-8").replace(/\0+$/, "").replace(/\0/g, " ");
|
|
28521
30149
|
} catch {
|
|
28522
30150
|
return null;
|
|
28523
30151
|
}
|
|
28524
30152
|
},
|
|
28525
30153
|
cgroup: (pid) => {
|
|
28526
30154
|
try {
|
|
28527
|
-
return (0,
|
|
30155
|
+
return (0, import_node_fs33.readFileSync)(`/proc/${pid}/cgroup`, "utf-8");
|
|
28528
30156
|
} catch {
|
|
28529
30157
|
return null;
|
|
28530
30158
|
}
|
|
@@ -28883,7 +30511,7 @@ var DockerLogsWatch = class {
|
|
|
28883
30511
|
start() {
|
|
28884
30512
|
const { settings } = this.opts;
|
|
28885
30513
|
if (!settings.enabled) return false;
|
|
28886
|
-
if (!this.opts.deps && !(0,
|
|
30514
|
+
if (!this.opts.deps && !(0, import_node_fs34.existsSync)(settings.socket)) return false;
|
|
28887
30515
|
this.opts.log(`[docker-logs] following containers named /${settings.namePattern.source}/ or with image /${settings.imagePattern.source}/ for Postgres auth failures`);
|
|
28888
30516
|
void this.poll();
|
|
28889
30517
|
this.timer = setInterval(() => {
|
|
@@ -28989,8 +30617,8 @@ var DockerLogsWatch = class {
|
|
|
28989
30617
|
};
|
|
28990
30618
|
|
|
28991
30619
|
// src/daemon/workers/login-watch.ts
|
|
28992
|
-
var
|
|
28993
|
-
var
|
|
30620
|
+
var import_node_fs35 = require("fs");
|
|
30621
|
+
var import_node_child_process12 = require("child_process");
|
|
28994
30622
|
var import_node_net13 = require("net");
|
|
28995
30623
|
var DEFAULT_SENSITIVE_GROUPS = ["sudo", "admin", "wheel", "docker"];
|
|
28996
30624
|
function stringList(value, fallback) {
|
|
@@ -29100,12 +30728,12 @@ function sshdPidsForPeer(ssOutput, ip) {
|
|
|
29100
30728
|
}
|
|
29101
30729
|
var realKillDeps = {
|
|
29102
30730
|
run: (cmd, args) => {
|
|
29103
|
-
const res = (0,
|
|
30731
|
+
const res = (0, import_node_child_process12.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 1e4, stdio: ["ignore", "pipe", "pipe"] });
|
|
29104
30732
|
return res.status === 0 ? res.stdout : null;
|
|
29105
30733
|
},
|
|
29106
30734
|
cmdline: (pid) => {
|
|
29107
30735
|
try {
|
|
29108
|
-
return (0,
|
|
30736
|
+
return (0, import_node_fs35.readFileSync)(`/proc/${pid}/cmdline`, "utf-8").replace(/\0+$/, "").replace(/\0/g, " ");
|
|
29109
30737
|
} catch {
|
|
29110
30738
|
return null;
|
|
29111
30739
|
}
|
|
@@ -29163,14 +30791,14 @@ function forcedCommandKeys(text) {
|
|
|
29163
30791
|
var realKeyFileIO = {
|
|
29164
30792
|
mtime: (p) => {
|
|
29165
30793
|
try {
|
|
29166
|
-
return (0,
|
|
30794
|
+
return (0, import_node_fs35.statSync)(p).mtimeMs;
|
|
29167
30795
|
} catch {
|
|
29168
30796
|
return null;
|
|
29169
30797
|
}
|
|
29170
30798
|
},
|
|
29171
30799
|
read: (p) => {
|
|
29172
30800
|
try {
|
|
29173
|
-
return (0,
|
|
30801
|
+
return (0, import_node_fs35.readFileSync)(p, "utf-8");
|
|
29174
30802
|
} catch {
|
|
29175
30803
|
return null;
|
|
29176
30804
|
}
|
|
@@ -29224,8 +30852,8 @@ var LoginWatch = class {
|
|
|
29224
30852
|
const users = new Set(this.opts.settings.sensitiveUsers);
|
|
29225
30853
|
try {
|
|
29226
30854
|
const { group, passwd } = this.opts.readAccounts?.() ?? {
|
|
29227
|
-
group: (0,
|
|
29228
|
-
passwd: (0,
|
|
30855
|
+
group: (0, import_node_fs35.readFileSync)("/etc/group", "utf-8"),
|
|
30856
|
+
passwd: (0, import_node_fs35.readFileSync)("/etc/passwd", "utf-8")
|
|
29229
30857
|
};
|
|
29230
30858
|
for (const u of groupMembers(group, passwd, this.opts.settings.sensitiveGroups)) users.add(u);
|
|
29231
30859
|
} catch {
|
|
@@ -29240,7 +30868,7 @@ var LoginWatch = class {
|
|
|
29240
30868
|
return;
|
|
29241
30869
|
}
|
|
29242
30870
|
const run = this.opts.run ?? ((cmd, args) => {
|
|
29243
|
-
const res = (0,
|
|
30871
|
+
const res = (0, import_node_child_process12.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
|
|
29244
30872
|
return res.status === 0 ? res.stdout : null;
|
|
29245
30873
|
});
|
|
29246
30874
|
const out = run("journalctl", ["_COMM=sshd", "_COMM=sshd-session", "--since=-30d", "-o", "short-unix", "--no-pager", "--grep", "Accepted "]);
|
|
@@ -29261,7 +30889,7 @@ var LoginWatch = class {
|
|
|
29261
30889
|
}
|
|
29262
30890
|
passwdText() {
|
|
29263
30891
|
try {
|
|
29264
|
-
return this.opts.readAccounts ? this.opts.readAccounts().passwd : (0,
|
|
30892
|
+
return this.opts.readAccounts ? this.opts.readAccounts().passwd : (0, import_node_fs35.readFileSync)("/etc/passwd", "utf-8");
|
|
29265
30893
|
} catch {
|
|
29266
30894
|
return "";
|
|
29267
30895
|
}
|
|
@@ -29387,8 +31015,8 @@ var LoginWatch = class {
|
|
|
29387
31015
|
};
|
|
29388
31016
|
|
|
29389
31017
|
// src/core/tor-exits.ts
|
|
29390
|
-
var
|
|
29391
|
-
var
|
|
31018
|
+
var import_node_fs36 = require("fs");
|
|
31019
|
+
var import_node_path27 = require("path");
|
|
29392
31020
|
var import_node_net14 = require("net");
|
|
29393
31021
|
var TOR_BULK_EXIT_LIST_URL = "https://check.torproject.org/torbulkexitlist";
|
|
29394
31022
|
function parseTorExitList(text) {
|
|
@@ -29460,10 +31088,10 @@ var TorExitList = class _TorExitList {
|
|
|
29460
31088
|
}
|
|
29461
31089
|
loadCache() {
|
|
29462
31090
|
try {
|
|
29463
|
-
if (!(0,
|
|
29464
|
-
const parsed = parseTorExitList((0,
|
|
31091
|
+
if (!(0, import_node_fs36.existsSync)(this.opts.cachePath)) return false;
|
|
31092
|
+
const parsed = parseTorExitList((0, import_node_fs36.readFileSync)(this.opts.cachePath, "utf-8"));
|
|
29465
31093
|
if (parsed.size === 0) return false;
|
|
29466
|
-
this.load(parsed, (0,
|
|
31094
|
+
this.load(parsed, (0, import_node_fs36.statSync)(this.opts.cachePath).mtimeMs);
|
|
29467
31095
|
this.log(`[tor] loaded ${parsed.size} Tor exit addresses from cache (${new Date(this.updatedAt).toISOString()})`);
|
|
29468
31096
|
return true;
|
|
29469
31097
|
} catch (err) {
|
|
@@ -29495,9 +31123,9 @@ var TorExitList = class _TorExitList {
|
|
|
29495
31123
|
const before = this.exits.size;
|
|
29496
31124
|
this.load(parsed);
|
|
29497
31125
|
try {
|
|
29498
|
-
(0,
|
|
29499
|
-
(0,
|
|
29500
|
-
(0,
|
|
31126
|
+
(0, import_node_fs36.mkdirSync)((0, import_node_path27.dirname)(this.opts.cachePath), { recursive: true });
|
|
31127
|
+
(0, import_node_fs36.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
|
|
31128
|
+
(0, import_node_fs36.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
|
|
29501
31129
|
} catch (err) {
|
|
29502
31130
|
this.log(`[tor] could not save the exit list cache: ${err.message}`);
|
|
29503
31131
|
}
|
|
@@ -29507,12 +31135,12 @@ var TorExitList = class _TorExitList {
|
|
|
29507
31135
|
};
|
|
29508
31136
|
|
|
29509
31137
|
// src/daemon/firewall/tor-block.ts
|
|
29510
|
-
var
|
|
31138
|
+
var import_node_child_process13 = require("child_process");
|
|
29511
31139
|
var import_node_net15 = require("net");
|
|
29512
31140
|
var TOR_NFT_TABLE = "threatcrush-tor";
|
|
29513
31141
|
function defaultNftRunner() {
|
|
29514
31142
|
return (args, stdin) => new Promise((resolve4, reject) => {
|
|
29515
|
-
const child = (0,
|
|
31143
|
+
const child = (0, import_node_child_process13.execFile)(
|
|
29516
31144
|
"nft",
|
|
29517
31145
|
args,
|
|
29518
31146
|
{ maxBuffer: 16 * 1024 * 1024 },
|
|
@@ -29808,8 +31436,8 @@ var RuleEngine = class {
|
|
|
29808
31436
|
};
|
|
29809
31437
|
|
|
29810
31438
|
// src/daemon/rules/loader.ts
|
|
29811
|
-
var
|
|
29812
|
-
var
|
|
31439
|
+
var import_node_fs37 = require("fs");
|
|
31440
|
+
var import_node_path28 = require("path");
|
|
29813
31441
|
|
|
29814
31442
|
// src/daemon/rules/default-rules.ts
|
|
29815
31443
|
var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
|
|
@@ -30481,16 +32109,16 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
|
|
|
30481
32109
|
function loadAllRules(customDir) {
|
|
30482
32110
|
const rules = [...DEFAULT_RULES];
|
|
30483
32111
|
const dir = customDir || RULES_DIR;
|
|
30484
|
-
if ((0,
|
|
32112
|
+
if ((0, import_node_fs37.existsSync)(dir)) {
|
|
30485
32113
|
let files = [];
|
|
30486
32114
|
try {
|
|
30487
|
-
files = (0,
|
|
32115
|
+
files = (0, import_node_fs37.readdirSync)(dir).filter((f) => f.endsWith(".json"));
|
|
30488
32116
|
} catch (err) {
|
|
30489
32117
|
console.warn(`[rules] cannot read ${dir}: ${err.message}; custom rules not loaded`);
|
|
30490
32118
|
}
|
|
30491
32119
|
for (const file of files) {
|
|
30492
32120
|
try {
|
|
30493
|
-
const raw = (0,
|
|
32121
|
+
const raw = (0, import_node_fs37.readFileSync)((0, import_node_path28.join)(dir, file), "utf-8");
|
|
30494
32122
|
const parsed = JSON.parse(raw);
|
|
30495
32123
|
const customRules = Array.isArray(parsed) ? parsed : [parsed];
|
|
30496
32124
|
for (const rule of customRules) {
|
|
@@ -30521,9 +32149,9 @@ function loadAllRules(customDir) {
|
|
|
30521
32149
|
}
|
|
30522
32150
|
|
|
30523
32151
|
// src/daemon/firewall/adapters.ts
|
|
30524
|
-
var
|
|
30525
|
-
var
|
|
30526
|
-
var
|
|
32152
|
+
var import_node_child_process14 = require("child_process");
|
|
32153
|
+
var import_node_fs38 = require("fs");
|
|
32154
|
+
var import_node_path29 = require("path");
|
|
30527
32155
|
var import_node_net16 = require("net");
|
|
30528
32156
|
function assertValidFirewallIp(ip) {
|
|
30529
32157
|
if ((0, import_node_net16.isIP)(ip) !== 4) {
|
|
@@ -30536,9 +32164,9 @@ function assertBannableIp(ip) {
|
|
|
30536
32164
|
}
|
|
30537
32165
|
}
|
|
30538
32166
|
function writeIfAbsent(path, contents) {
|
|
30539
|
-
(0,
|
|
32167
|
+
(0, import_node_fs38.mkdirSync)((0, import_node_path29.dirname)(path), { recursive: true });
|
|
30540
32168
|
try {
|
|
30541
|
-
(0,
|
|
32169
|
+
(0, import_node_fs38.writeFileSync)(path, contents, { flag: "wx" });
|
|
30542
32170
|
} catch (err) {
|
|
30543
32171
|
if (err.code !== "EEXIST") throw err;
|
|
30544
32172
|
}
|
|
@@ -30557,11 +32185,11 @@ var Fail2banAdapter = class {
|
|
|
30557
32185
|
enforces = true;
|
|
30558
32186
|
jailReady = false;
|
|
30559
32187
|
isAvailable() {
|
|
30560
|
-
const result = (0,
|
|
32188
|
+
const result = (0, import_node_child_process14.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
|
|
30561
32189
|
return result.status === 0;
|
|
30562
32190
|
}
|
|
30563
32191
|
client(args) {
|
|
30564
|
-
return (0,
|
|
32192
|
+
return (0, import_node_child_process14.execFileSync)("fail2ban-client", args, {
|
|
30565
32193
|
encoding: "utf-8",
|
|
30566
32194
|
stdio: ["ignore", "pipe", "pipe"]
|
|
30567
32195
|
});
|
|
@@ -30657,35 +32285,35 @@ var NftablesAdapter = class {
|
|
|
30657
32285
|
table = "threatcrush";
|
|
30658
32286
|
set = "blocklist";
|
|
30659
32287
|
isAvailable() {
|
|
30660
|
-
const result = (0,
|
|
32288
|
+
const result = (0, import_node_child_process14.spawnSync)("nft", ["--version"], { stdio: "pipe" });
|
|
30661
32289
|
return result.status === 0;
|
|
30662
32290
|
}
|
|
30663
32291
|
ensureSetup() {
|
|
30664
32292
|
try {
|
|
30665
|
-
(0,
|
|
32293
|
+
(0, import_node_child_process14.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
|
|
30666
32294
|
} catch {
|
|
30667
|
-
(0,
|
|
30668
|
-
(0,
|
|
30669
|
-
(0,
|
|
30670
|
-
(0,
|
|
32295
|
+
(0, import_node_child_process14.execSync)(`nft add table inet ${this.table}`);
|
|
32296
|
+
(0, import_node_child_process14.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
|
|
32297
|
+
(0, import_node_child_process14.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
|
|
32298
|
+
(0, import_node_child_process14.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
|
|
30671
32299
|
}
|
|
30672
32300
|
}
|
|
30673
32301
|
async block(ip) {
|
|
30674
32302
|
assertValidFirewallIp(ip);
|
|
30675
32303
|
this.ensureSetup();
|
|
30676
|
-
(0,
|
|
32304
|
+
(0, import_node_child_process14.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
|
|
30677
32305
|
}
|
|
30678
32306
|
async unblock(ip) {
|
|
30679
32307
|
assertValidFirewallIp(ip);
|
|
30680
32308
|
try {
|
|
30681
|
-
(0,
|
|
32309
|
+
(0, import_node_child_process14.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
|
|
30682
32310
|
} catch {
|
|
30683
32311
|
}
|
|
30684
32312
|
}
|
|
30685
32313
|
async isBlocked(ip) {
|
|
30686
32314
|
assertValidFirewallIp(ip);
|
|
30687
32315
|
try {
|
|
30688
|
-
const output = (0,
|
|
32316
|
+
const output = (0, import_node_child_process14.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
|
|
30689
32317
|
return output.includes(ip);
|
|
30690
32318
|
} catch {
|
|
30691
32319
|
return false;
|
|
@@ -30693,7 +32321,7 @@ var NftablesAdapter = class {
|
|
|
30693
32321
|
}
|
|
30694
32322
|
async listBlocked() {
|
|
30695
32323
|
try {
|
|
30696
|
-
const output = (0,
|
|
32324
|
+
const output = (0, import_node_child_process14.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
|
|
30697
32325
|
const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
|
|
30698
32326
|
if (!match) return [];
|
|
30699
32327
|
return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
|
|
@@ -30706,34 +32334,34 @@ var IptablesAdapter = class {
|
|
|
30706
32334
|
name = "iptables";
|
|
30707
32335
|
chain = "THREATCRUSH";
|
|
30708
32336
|
isAvailable() {
|
|
30709
|
-
const result = (0,
|
|
32337
|
+
const result = (0, import_node_child_process14.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
|
|
30710
32338
|
return result.status === 0;
|
|
30711
32339
|
}
|
|
30712
32340
|
ensureChain() {
|
|
30713
32341
|
try {
|
|
30714
|
-
(0,
|
|
32342
|
+
(0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
|
|
30715
32343
|
} catch {
|
|
30716
|
-
(0,
|
|
30717
|
-
(0,
|
|
32344
|
+
(0, import_node_child_process14.execSync)(`iptables -N ${this.chain}`);
|
|
32345
|
+
(0, import_node_child_process14.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
|
|
30718
32346
|
}
|
|
30719
32347
|
}
|
|
30720
32348
|
async block(ip) {
|
|
30721
32349
|
assertValidFirewallIp(ip);
|
|
30722
32350
|
this.ensureChain();
|
|
30723
32351
|
if (await this.isBlocked(ip)) return;
|
|
30724
|
-
(0,
|
|
32352
|
+
(0, import_node_child_process14.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
|
|
30725
32353
|
}
|
|
30726
32354
|
async unblock(ip) {
|
|
30727
32355
|
assertValidFirewallIp(ip);
|
|
30728
32356
|
try {
|
|
30729
|
-
(0,
|
|
32357
|
+
(0, import_node_child_process14.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
|
|
30730
32358
|
} catch {
|
|
30731
32359
|
}
|
|
30732
32360
|
}
|
|
30733
32361
|
async isBlocked(ip) {
|
|
30734
32362
|
assertValidFirewallIp(ip);
|
|
30735
32363
|
try {
|
|
30736
|
-
const output = (0,
|
|
32364
|
+
const output = (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
|
|
30737
32365
|
return output.includes(ip);
|
|
30738
32366
|
} catch {
|
|
30739
32367
|
return false;
|
|
@@ -30741,7 +32369,7 @@ var IptablesAdapter = class {
|
|
|
30741
32369
|
}
|
|
30742
32370
|
async listBlocked() {
|
|
30743
32371
|
try {
|
|
30744
|
-
const output = (0,
|
|
32372
|
+
const output = (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
|
|
30745
32373
|
const ips = [];
|
|
30746
32374
|
for (const line of output.split("\n")) {
|
|
30747
32375
|
const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
|
|
@@ -30797,8 +32425,8 @@ function detectFirewallAdapter(backend = "auto") {
|
|
|
30797
32425
|
}
|
|
30798
32426
|
|
|
30799
32427
|
// src/daemon/firewall/remediation.ts
|
|
30800
|
-
var
|
|
30801
|
-
var
|
|
32428
|
+
var import_node_fs39 = require("fs");
|
|
32429
|
+
var import_node_child_process15 = require("child_process");
|
|
30802
32430
|
var import_node_net17 = require("net");
|
|
30803
32431
|
|
|
30804
32432
|
// src/daemon/firewall/crawlers.ts
|
|
@@ -30867,19 +32495,19 @@ var defaultDiscovery = {
|
|
|
30867
32495
|
const snapshot = takeSnapshot({
|
|
30868
32496
|
readFile: (p) => {
|
|
30869
32497
|
try {
|
|
30870
|
-
return (0,
|
|
32498
|
+
return (0, import_node_fs39.readFileSync)(p, "utf-8");
|
|
30871
32499
|
} catch {
|
|
30872
32500
|
return null;
|
|
30873
32501
|
}
|
|
30874
32502
|
},
|
|
30875
32503
|
readDir: (p) => {
|
|
30876
32504
|
try {
|
|
30877
|
-
return (0,
|
|
32505
|
+
return (0, import_node_fs39.readdirSync)(p);
|
|
30878
32506
|
} catch {
|
|
30879
32507
|
return null;
|
|
30880
32508
|
}
|
|
30881
32509
|
},
|
|
30882
|
-
exists: (p) => (0,
|
|
32510
|
+
exists: (p) => (0, import_node_fs39.existsSync)(p)
|
|
30883
32511
|
});
|
|
30884
32512
|
const out = /* @__PURE__ */ new Set();
|
|
30885
32513
|
for (const keys of Object.values(snapshot.keys)) {
|
|
@@ -30888,7 +32516,7 @@ var defaultDiscovery = {
|
|
|
30888
32516
|
return out;
|
|
30889
32517
|
},
|
|
30890
32518
|
keyLoginJournal: (sinceSeconds) => new Promise((resolve4) => {
|
|
30891
|
-
(0,
|
|
32519
|
+
(0, import_node_child_process15.execFile)(
|
|
30892
32520
|
"journalctl",
|
|
30893
32521
|
["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
|
|
30894
32522
|
{ maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
|
|
@@ -31392,7 +33020,7 @@ var RemediationManager = class {
|
|
|
31392
33020
|
}
|
|
31393
33021
|
logLine(line) {
|
|
31394
33022
|
try {
|
|
31395
|
-
(0,
|
|
33023
|
+
(0, import_node_fs39.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
|
|
31396
33024
|
`);
|
|
31397
33025
|
} catch {
|
|
31398
33026
|
}
|
|
@@ -31432,13 +33060,13 @@ function remediationSettings(section) {
|
|
|
31432
33060
|
}
|
|
31433
33061
|
|
|
31434
33062
|
// src/daemon/watchdog-service.ts
|
|
31435
|
-
var
|
|
31436
|
-
var
|
|
33063
|
+
var import_node_fs41 = require("fs");
|
|
33064
|
+
var import_node_path31 = require("path");
|
|
31437
33065
|
|
|
31438
33066
|
// src/core/watchdog.ts
|
|
31439
|
-
var
|
|
33067
|
+
var import_node_fs40 = require("fs");
|
|
31440
33068
|
var import_node_crypto9 = require("crypto");
|
|
31441
|
-
var
|
|
33069
|
+
var import_node_path30 = require("path");
|
|
31442
33070
|
var WATCHDOG_DIRNAME = "watchdog";
|
|
31443
33071
|
var LOG_FILE2 = "attacks.jsonl";
|
|
31444
33072
|
var ROTATED_FILE = "attacks.1.jsonl";
|
|
@@ -31527,12 +33155,12 @@ var WatchdogLog = class {
|
|
|
31527
33155
|
stats = { logged: 0, answered: 0, errored: 0 };
|
|
31528
33156
|
constructor(dir, options = {}) {
|
|
31529
33157
|
this.dir = dir;
|
|
31530
|
-
this.file = (0,
|
|
33158
|
+
this.file = (0, import_node_path30.join)(dir, LOG_FILE2);
|
|
31531
33159
|
this.shareGid = options.shareGid;
|
|
31532
|
-
(0,
|
|
33160
|
+
(0, import_node_fs40.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
|
|
31533
33161
|
if (this.shareGid !== void 0) {
|
|
31534
|
-
(0,
|
|
31535
|
-
(0,
|
|
33162
|
+
(0, import_node_fs40.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
|
|
33163
|
+
(0, import_node_fs40.chmodSync)(dir, 1528);
|
|
31536
33164
|
}
|
|
31537
33165
|
for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
|
|
31538
33166
|
}
|
|
@@ -31561,16 +33189,16 @@ var WatchdogLog = class {
|
|
|
31561
33189
|
const chunk = this.buffer.join("\n") + "\n";
|
|
31562
33190
|
this.buffer = [];
|
|
31563
33191
|
try {
|
|
31564
|
-
if ((0,
|
|
31565
|
-
(0,
|
|
33192
|
+
if ((0, import_node_fs40.statSync)(this.file).size > ROTATE_BYTES) {
|
|
33193
|
+
(0, import_node_fs40.renameSync)(this.file, (0, import_node_path30.join)(this.dir, ROTATED_FILE));
|
|
31566
33194
|
}
|
|
31567
33195
|
} catch {
|
|
31568
33196
|
}
|
|
31569
|
-
(0,
|
|
33197
|
+
(0, import_node_fs40.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
|
|
31570
33198
|
if (this.shareGid !== void 0) {
|
|
31571
33199
|
try {
|
|
31572
|
-
(0,
|
|
31573
|
-
(0,
|
|
33200
|
+
(0, import_node_fs40.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
|
|
33201
|
+
(0, import_node_fs40.chmodSync)(this.file, 432);
|
|
31574
33202
|
} catch {
|
|
31575
33203
|
}
|
|
31576
33204
|
}
|
|
@@ -31591,21 +33219,21 @@ function parseLines(text) {
|
|
|
31591
33219
|
function readTail(file, bytes) {
|
|
31592
33220
|
let fd;
|
|
31593
33221
|
try {
|
|
31594
|
-
fd = (0,
|
|
33222
|
+
fd = (0, import_node_fs40.openSync)(file, "r");
|
|
31595
33223
|
} catch (err) {
|
|
31596
33224
|
if (err.code === "ENOENT") return [];
|
|
31597
33225
|
throw err;
|
|
31598
33226
|
}
|
|
31599
33227
|
try {
|
|
31600
|
-
const size = (0,
|
|
33228
|
+
const size = (0, import_node_fs40.fstatSync)(fd).size;
|
|
31601
33229
|
const start = Math.max(0, size - bytes);
|
|
31602
33230
|
const buf = Buffer.alloc(size - start);
|
|
31603
|
-
(0,
|
|
33231
|
+
(0, import_node_fs40.readSync)(fd, buf, 0, buf.length, start);
|
|
31604
33232
|
let text = buf.toString("utf8");
|
|
31605
33233
|
if (start > 0) text = text.slice(text.indexOf("\n") + 1);
|
|
31606
33234
|
return parseLines(text);
|
|
31607
33235
|
} finally {
|
|
31608
|
-
(0,
|
|
33236
|
+
(0, import_node_fs40.closeSync)(fd);
|
|
31609
33237
|
}
|
|
31610
33238
|
}
|
|
31611
33239
|
|
|
@@ -31614,13 +33242,13 @@ function defaultShareGid() {
|
|
|
31614
33242
|
const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
|
|
31615
33243
|
if (!isRoot2) return void 0;
|
|
31616
33244
|
try {
|
|
31617
|
-
return (0,
|
|
33245
|
+
return (0, import_node_fs41.statSync)("/var/log/auth.log").gid;
|
|
31618
33246
|
} catch {
|
|
31619
33247
|
return void 0;
|
|
31620
33248
|
}
|
|
31621
33249
|
}
|
|
31622
33250
|
function startWatchdog(opts) {
|
|
31623
|
-
const dir = opts.config?.dir ?? (0,
|
|
33251
|
+
const dir = opts.config?.dir ?? (0, import_node_path31.join)(opts.stateDir, WATCHDOG_DIRNAME);
|
|
31624
33252
|
const base = { dir, logged: 0, answered: 0, errored: 0 };
|
|
31625
33253
|
if (opts.config?.enabled === false) {
|
|
31626
33254
|
opts.log("[watchdog] off ([watchdog] enabled = false)");
|
|
@@ -31711,7 +33339,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
|
|
|
31711
33339
|
}
|
|
31712
33340
|
|
|
31713
33341
|
// src/core/node-runtime.ts
|
|
31714
|
-
var
|
|
33342
|
+
var import_node_child_process16 = require("child_process");
|
|
31715
33343
|
var MIN_DAEMON_NODE_MAJOR = 22;
|
|
31716
33344
|
function nodeMajor(version) {
|
|
31717
33345
|
const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
|
|
@@ -31727,16 +33355,16 @@ function daemonNodeProblem(version) {
|
|
|
31727
33355
|
// src/daemon/index.ts
|
|
31728
33356
|
function readVersion2() {
|
|
31729
33357
|
try {
|
|
31730
|
-
const pkg = JSON.parse((0,
|
|
33358
|
+
const pkg = JSON.parse((0, import_node_fs42.readFileSync)((0, import_node_path32.join)(__dirname, "..", "package.json"), "utf-8"));
|
|
31731
33359
|
return pkg.version || "0.0.0";
|
|
31732
33360
|
} catch {
|
|
31733
33361
|
return "0.0.0";
|
|
31734
33362
|
}
|
|
31735
33363
|
}
|
|
31736
33364
|
async function runHardeningChecks() {
|
|
31737
|
-
const { stdout } = await (0, import_node_util.promisify)(
|
|
33365
|
+
const { stdout } = await (0, import_node_util.promisify)(import_node_child_process17.execFile)(
|
|
31738
33366
|
process.execPath,
|
|
31739
|
-
[(0,
|
|
33367
|
+
[(0, import_node_path32.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
|
|
31740
33368
|
{ timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
|
|
31741
33369
|
);
|
|
31742
33370
|
const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
|
|
@@ -31748,9 +33376,9 @@ async function runHardeningChecks() {
|
|
|
31748
33376
|
return patches ? [...findings, patches] : findings;
|
|
31749
33377
|
}
|
|
31750
33378
|
async function runPatchCheck() {
|
|
31751
|
-
const { stdout } = await (0, import_node_util.promisify)(
|
|
33379
|
+
const { stdout } = await (0, import_node_util.promisify)(import_node_child_process17.execFile)(
|
|
31752
33380
|
process.execPath,
|
|
31753
|
-
[(0,
|
|
33381
|
+
[(0, import_node_path32.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
|
|
31754
33382
|
{ timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
|
|
31755
33383
|
);
|
|
31756
33384
|
const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
|
|
@@ -31758,7 +33386,7 @@ async function runPatchCheck() {
|
|
|
31758
33386
|
}
|
|
31759
33387
|
function logLine(line) {
|
|
31760
33388
|
try {
|
|
31761
|
-
(0,
|
|
33389
|
+
(0, import_node_fs42.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
|
|
31762
33390
|
`);
|
|
31763
33391
|
} catch {
|
|
31764
33392
|
}
|
|
@@ -31783,9 +33411,9 @@ async function runDaemon() {
|
|
|
31783
33411
|
logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
|
|
31784
33412
|
const restartDaemon = () => {
|
|
31785
33413
|
if (PATHS.mode === "system") {
|
|
31786
|
-
(0,
|
|
33414
|
+
(0, import_node_child_process17.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
|
|
31787
33415
|
} else {
|
|
31788
|
-
(0,
|
|
33416
|
+
(0, import_node_child_process17.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
|
|
31789
33417
|
setTimeout(() => process.exit(0), 500).unref();
|
|
31790
33418
|
}
|
|
31791
33419
|
};
|
|
@@ -31800,7 +33428,7 @@ async function runDaemon() {
|
|
|
31800
33428
|
} catch (err) {
|
|
31801
33429
|
logLine(`[daemon] state db unavailable: ${err.message}`);
|
|
31802
33430
|
}
|
|
31803
|
-
const loaded = loadDaemonConfig(PATHS.configFile, (0,
|
|
33431
|
+
const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path32.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
|
|
31804
33432
|
const config = loaded.config;
|
|
31805
33433
|
if (loaded.error) {
|
|
31806
33434
|
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 +33499,7 @@ async function runDaemon() {
|
|
|
31871
33499
|
const threatFeeds = new ThreatFeeds({
|
|
31872
33500
|
settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
|
|
31873
33501
|
enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
|
|
31874
|
-
cachePath: (0,
|
|
33502
|
+
cachePath: (0, import_node_path32.join)(PATHS.stateDir, "threat-feeds.json"),
|
|
31875
33503
|
bus,
|
|
31876
33504
|
log: logLine
|
|
31877
33505
|
});
|
|
@@ -31879,9 +33507,9 @@ async function runDaemon() {
|
|
|
31879
33507
|
const privilegeWatch = new PrivilegeWatch({
|
|
31880
33508
|
settings: privilegeSettings(config.privileged),
|
|
31881
33509
|
bus,
|
|
31882
|
-
snapshotPath: (0,
|
|
31883
|
-
loginsPath: (0,
|
|
31884
|
-
cursorPath: (0,
|
|
33510
|
+
snapshotPath: (0, import_node_path32.join)(PATHS.stateDir, "privileges.json"),
|
|
33511
|
+
loginsPath: (0, import_node_path32.join)(PATHS.stateDir, "login-countries.json"),
|
|
33512
|
+
cursorPath: (0, import_node_path32.join)(PATHS.stateDir, "sudo-cursor.json"),
|
|
31885
33513
|
log: logLine
|
|
31886
33514
|
});
|
|
31887
33515
|
privilegeWatch.start();
|
|
@@ -31895,20 +33523,23 @@ async function runDaemon() {
|
|
|
31895
33523
|
const fileIntegrity = new FileIntegrityWatch({
|
|
31896
33524
|
bus,
|
|
31897
33525
|
settings: fileIntegritySettings(config.file_integrity),
|
|
31898
|
-
baselinePath: (0,
|
|
31899
|
-
observedPath: (0,
|
|
33526
|
+
baselinePath: (0, import_node_path32.join)(PATHS.stateDir, "file-integrity-baseline.json"),
|
|
33527
|
+
observedPath: (0, import_node_path32.join)(PATHS.stateDir, "file-integrity-observed.json"),
|
|
33528
|
+
// `[remediation] dry_run` also covers the opt-in contain_writer response.
|
|
33529
|
+
dryRun: () => remediation.status().dry_run,
|
|
31900
33530
|
log: logLine
|
|
31901
33531
|
});
|
|
31902
33532
|
fileIntegrity.start();
|
|
31903
33533
|
const edr = new EdrWatch({
|
|
31904
33534
|
bus,
|
|
31905
33535
|
settings: edrSettings(config.edr),
|
|
31906
|
-
networkBaselinePath: (0,
|
|
33536
|
+
networkBaselinePath: (0, import_node_path32.join)(PATHS.stateDir, "edr-outbound-executables.json"),
|
|
33537
|
+
sourceStatusPath: (0, import_node_path32.join)(PATHS.stateDir, "edr-source.json"),
|
|
31907
33538
|
log: logLine
|
|
31908
33539
|
});
|
|
31909
33540
|
edr.start();
|
|
31910
33541
|
const torExits = new TorExitList({
|
|
31911
|
-
cachePath: (0,
|
|
33542
|
+
cachePath: (0, import_node_path32.join)(PATHS.stateDir, "tor-exits.txt"),
|
|
31912
33543
|
url: config.remediation?.tor_exit_list_url,
|
|
31913
33544
|
log: logLine
|
|
31914
33545
|
});
|
|
@@ -31916,7 +33547,7 @@ async function runDaemon() {
|
|
|
31916
33547
|
bus,
|
|
31917
33548
|
manager: remediation,
|
|
31918
33549
|
tor: torExits,
|
|
31919
|
-
historyPath: (0,
|
|
33550
|
+
historyPath: (0, import_node_path32.join)(PATHS.stateDir, "key-logins.json"),
|
|
31920
33551
|
keyLoginWatch: config.privileged?.key_login_watch !== false,
|
|
31921
33552
|
log: logLine
|
|
31922
33553
|
});
|
|
@@ -31991,7 +33622,7 @@ async function runDaemon() {
|
|
|
31991
33622
|
version,
|
|
31992
33623
|
hostname: (0, import_node_os6.hostname)(),
|
|
31993
33624
|
minSeverity,
|
|
31994
|
-
spoolPath: (0,
|
|
33625
|
+
spoolPath: (0, import_node_path32.join)(PATHS.stateDir, "cloud-spool.jsonl"),
|
|
31995
33626
|
log: logLine,
|
|
31996
33627
|
ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
|
|
31997
33628
|
runHardening: runHardeningChecks
|
|
@@ -32025,8 +33656,8 @@ async function runDaemon() {
|
|
|
32025
33656
|
const autoUpdate = autoUpdateRef = new AutoUpdate({
|
|
32026
33657
|
version,
|
|
32027
33658
|
settings: updateSettings(config.update),
|
|
32028
|
-
pkgRoot: (0,
|
|
32029
|
-
statePath: (0,
|
|
33659
|
+
pkgRoot: (0, import_node_path32.join)(__dirname, ".."),
|
|
33660
|
+
statePath: (0, import_node_path32.join)(PATHS.stateDir, "auto-update.json"),
|
|
32030
33661
|
bus,
|
|
32031
33662
|
log: logLine,
|
|
32032
33663
|
restartDaemon
|