@profullstack/threatcrush 0.13.66 → 0.13.68
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 +92 -0
- package/dist/daemon.js +1020 -156
- package/dist/daemon.js.map +1 -1
- package/dist/index.js +2220 -479
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/daemon.js
CHANGED
|
@@ -30,9 +30,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
30
30
|
mod
|
|
31
31
|
));
|
|
32
32
|
|
|
33
|
-
//
|
|
33
|
+
// ../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/parser.js
|
|
34
34
|
var require_parser = __commonJS({
|
|
35
|
-
"
|
|
35
|
+
"../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/parser.js"(exports2, module2) {
|
|
36
36
|
"use strict";
|
|
37
37
|
var ParserEND = 1114112;
|
|
38
38
|
var ParserError = class _ParserError extends Error {
|
|
@@ -155,9 +155,9 @@ var require_parser = __commonJS({
|
|
|
155
155
|
}
|
|
156
156
|
});
|
|
157
157
|
|
|
158
|
-
//
|
|
158
|
+
// ../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime.js
|
|
159
159
|
var require_create_datetime = __commonJS({
|
|
160
|
-
"
|
|
160
|
+
"../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime.js"(exports2, module2) {
|
|
161
161
|
"use strict";
|
|
162
162
|
module2.exports = (value) => {
|
|
163
163
|
const date = new Date(value);
|
|
@@ -170,9 +170,9 @@ var require_create_datetime = __commonJS({
|
|
|
170
170
|
}
|
|
171
171
|
});
|
|
172
172
|
|
|
173
|
-
//
|
|
173
|
+
// ../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/format-num.js
|
|
174
174
|
var require_format_num = __commonJS({
|
|
175
|
-
"
|
|
175
|
+
"../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/format-num.js"(exports2, module2) {
|
|
176
176
|
"use strict";
|
|
177
177
|
module2.exports = (d, num) => {
|
|
178
178
|
num = String(num);
|
|
@@ -182,9 +182,9 @@ var require_format_num = __commonJS({
|
|
|
182
182
|
}
|
|
183
183
|
});
|
|
184
184
|
|
|
185
|
-
//
|
|
185
|
+
// ../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime-float.js
|
|
186
186
|
var require_create_datetime_float = __commonJS({
|
|
187
|
-
"
|
|
187
|
+
"../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime-float.js"(exports2, module2) {
|
|
188
188
|
"use strict";
|
|
189
189
|
var f = require_format_num();
|
|
190
190
|
var FloatingDateTime = class extends Date {
|
|
@@ -209,9 +209,9 @@ var require_create_datetime_float = __commonJS({
|
|
|
209
209
|
}
|
|
210
210
|
});
|
|
211
211
|
|
|
212
|
-
//
|
|
212
|
+
// ../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-date.js
|
|
213
213
|
var require_create_date = __commonJS({
|
|
214
|
-
"
|
|
214
|
+
"../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-date.js"(exports2, module2) {
|
|
215
215
|
"use strict";
|
|
216
216
|
var f = require_format_num();
|
|
217
217
|
var DateTime = global.Date;
|
|
@@ -235,9 +235,9 @@ var require_create_date = __commonJS({
|
|
|
235
235
|
}
|
|
236
236
|
});
|
|
237
237
|
|
|
238
|
-
//
|
|
238
|
+
// ../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-time.js
|
|
239
239
|
var require_create_time = __commonJS({
|
|
240
|
-
"
|
|
240
|
+
"../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-time.js"(exports2, module2) {
|
|
241
241
|
"use strict";
|
|
242
242
|
var f = require_format_num();
|
|
243
243
|
var Time = class extends Date {
|
|
@@ -260,9 +260,9 @@ var require_create_time = __commonJS({
|
|
|
260
260
|
}
|
|
261
261
|
});
|
|
262
262
|
|
|
263
|
-
//
|
|
263
|
+
// ../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/toml-parser.js
|
|
264
264
|
var require_toml_parser = __commonJS({
|
|
265
|
-
"
|
|
265
|
+
"../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/toml-parser.js"(exports, module) {
|
|
266
266
|
"use strict";
|
|
267
267
|
module.exports = makeParserClass(require_parser());
|
|
268
268
|
module.exports.makeParserClass = makeParserClass;
|
|
@@ -1573,9 +1573,9 @@ var require_toml_parser = __commonJS({
|
|
|
1573
1573
|
}
|
|
1574
1574
|
});
|
|
1575
1575
|
|
|
1576
|
-
//
|
|
1576
|
+
// ../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-pretty-error.js
|
|
1577
1577
|
var require_parse_pretty_error = __commonJS({
|
|
1578
|
-
"
|
|
1578
|
+
"../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-pretty-error.js"(exports2, module2) {
|
|
1579
1579
|
"use strict";
|
|
1580
1580
|
module2.exports = prettyError;
|
|
1581
1581
|
function prettyError(err, buf) {
|
|
@@ -1609,9 +1609,9 @@ var require_parse_pretty_error = __commonJS({
|
|
|
1609
1609
|
}
|
|
1610
1610
|
});
|
|
1611
1611
|
|
|
1612
|
-
//
|
|
1612
|
+
// ../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-string.js
|
|
1613
1613
|
var require_parse_string = __commonJS({
|
|
1614
|
-
"
|
|
1614
|
+
"../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-string.js"(exports2, module2) {
|
|
1615
1615
|
"use strict";
|
|
1616
1616
|
module2.exports = parseString;
|
|
1617
1617
|
var TOMLParser = require_toml_parser();
|
|
@@ -1631,9 +1631,9 @@ var require_parse_string = __commonJS({
|
|
|
1631
1631
|
}
|
|
1632
1632
|
});
|
|
1633
1633
|
|
|
1634
|
-
//
|
|
1634
|
+
// ../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-async.js
|
|
1635
1635
|
var require_parse_async = __commonJS({
|
|
1636
|
-
"
|
|
1636
|
+
"../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-async.js"(exports2, module2) {
|
|
1637
1637
|
"use strict";
|
|
1638
1638
|
module2.exports = parseAsync;
|
|
1639
1639
|
var TOMLParser = require_toml_parser();
|
|
@@ -1665,9 +1665,9 @@ var require_parse_async = __commonJS({
|
|
|
1665
1665
|
}
|
|
1666
1666
|
});
|
|
1667
1667
|
|
|
1668
|
-
//
|
|
1668
|
+
// ../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-stream.js
|
|
1669
1669
|
var require_parse_stream = __commonJS({
|
|
1670
|
-
"
|
|
1670
|
+
"../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-stream.js"(exports2, module2) {
|
|
1671
1671
|
"use strict";
|
|
1672
1672
|
module2.exports = parseStream;
|
|
1673
1673
|
var stream = require("stream");
|
|
@@ -1744,9 +1744,9 @@ var require_parse_stream = __commonJS({
|
|
|
1744
1744
|
}
|
|
1745
1745
|
});
|
|
1746
1746
|
|
|
1747
|
-
//
|
|
1747
|
+
// ../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse.js
|
|
1748
1748
|
var require_parse = __commonJS({
|
|
1749
|
-
"
|
|
1749
|
+
"../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse.js"(exports2, module2) {
|
|
1750
1750
|
"use strict";
|
|
1751
1751
|
module2.exports = require_parse_string();
|
|
1752
1752
|
module2.exports.async = require_parse_async();
|
|
@@ -1755,9 +1755,9 @@ var require_parse = __commonJS({
|
|
|
1755
1755
|
}
|
|
1756
1756
|
});
|
|
1757
1757
|
|
|
1758
|
-
//
|
|
1758
|
+
// ../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/stringify.js
|
|
1759
1759
|
var require_stringify = __commonJS({
|
|
1760
|
-
"
|
|
1760
|
+
"../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/stringify.js"(exports2, module2) {
|
|
1761
1761
|
"use strict";
|
|
1762
1762
|
module2.exports = stringify;
|
|
1763
1763
|
module2.exports.value = stringifyInline;
|
|
@@ -2016,9 +2016,9 @@ var require_stringify = __commonJS({
|
|
|
2016
2016
|
}
|
|
2017
2017
|
});
|
|
2018
2018
|
|
|
2019
|
-
//
|
|
2019
|
+
// ../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/toml.js
|
|
2020
2020
|
var require_toml = __commonJS({
|
|
2021
|
-
"
|
|
2021
|
+
"../../../../../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/toml.js"(exports2) {
|
|
2022
2022
|
"use strict";
|
|
2023
2023
|
exports2.parse = require_parse();
|
|
2024
2024
|
exports2.stringify = require_stringify();
|
|
@@ -2026,10 +2026,10 @@ var require_toml = __commonJS({
|
|
|
2026
2026
|
});
|
|
2027
2027
|
|
|
2028
2028
|
// src/daemon/index.ts
|
|
2029
|
-
var
|
|
2030
|
-
var
|
|
2029
|
+
var import_node_fs37 = require("fs");
|
|
2030
|
+
var import_node_child_process14 = require("child_process");
|
|
2031
2031
|
var import_node_os6 = require("os");
|
|
2032
|
-
var
|
|
2032
|
+
var import_node_path29 = require("path");
|
|
2033
2033
|
var import_node_util = require("util");
|
|
2034
2034
|
|
|
2035
2035
|
// src/daemon/paths.ts
|
|
@@ -2800,8 +2800,8 @@ function verifyModuleTrust(name, modulePath) {
|
|
|
2800
2800
|
} catch (err) {
|
|
2801
2801
|
return { ok: false, reason: `could not hash module: ${String(err.message || err)}` };
|
|
2802
2802
|
}
|
|
2803
|
-
const
|
|
2804
|
-
if (!
|
|
2803
|
+
const signature2 = verifyModuleSignature(modulePath, digest);
|
|
2804
|
+
if (!signature2.ok) return signature2;
|
|
2805
2805
|
const record = readTrustFile().modules[name];
|
|
2806
2806
|
if (!record) {
|
|
2807
2807
|
return {
|
|
@@ -8983,13 +8983,13 @@ function normalizePathImpl(s, win) {
|
|
|
8983
8983
|
if (src < end && buf[src + 1] === BS) buf[src + 1] = SL;
|
|
8984
8984
|
}
|
|
8985
8985
|
let skipCopy = false;
|
|
8986
|
-
let
|
|
8986
|
+
let normalize3 = true;
|
|
8987
8987
|
if (src === end) {
|
|
8988
8988
|
done = true;
|
|
8989
8989
|
} else if (buf[src + 1] !== SL) {
|
|
8990
|
-
|
|
8990
|
+
normalize3 = false;
|
|
8991
8991
|
}
|
|
8992
|
-
if (
|
|
8992
|
+
if (normalize3) {
|
|
8993
8993
|
if (src !== end && buf[src] === SL) {
|
|
8994
8994
|
} else if (buf[src] === DOT) {
|
|
8995
8995
|
if (dst > 0 && buf[dst - 1] === DOT) {
|
|
@@ -9541,7 +9541,7 @@ var TIMESTAMP = String.raw`(\w{3}\s+\d+\s+[\d:]+|\d{4}-\d{2}-\d{2}T[\d:.]+(?:Z|[
|
|
|
9541
9541
|
var AUTH_REGEX = new RegExp(`^${TIMESTAMP}\\s+\\S+\\s+(\\S+?)(?:\\[\\d+\\])?:\\s+(.*)`);
|
|
9542
9542
|
var SYSLOG_REGEX = new RegExp(`^${TIMESTAMP}\\s+\\S+\\s+(\\S+?)(?:\\[\\d+\\])?:\\s+(.*)`);
|
|
9543
9543
|
var IP_REGEX = /(?:from|FROM)\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/;
|
|
9544
|
-
var INVALID_USER_REGEX =
|
|
9544
|
+
var INVALID_USER_REGEX = /\binvalid\s+user\s+(\S+?)(?:\s+from\s|\s+\[?[0-9a-fA-F:.]+\]?\s+port\b|\s*$)/i;
|
|
9545
9545
|
var USER_REGEX = /(?:for|user)\s+(\S+?)(?:\s+from|\s*$)/;
|
|
9546
9546
|
function parseNginxLog(line) {
|
|
9547
9547
|
const match = line.match(NGINX_REGEX);
|
|
@@ -9605,6 +9605,8 @@ function parseAuthLog(line) {
|
|
|
9605
9605
|
function parseAuthMessage(process3, message, timestamp, raw = message) {
|
|
9606
9606
|
const ipMatch = message.match(IP_REGEX);
|
|
9607
9607
|
const userMatch = message.match(INVALID_USER_REGEX) || message.match(USER_REGEX);
|
|
9608
|
+
const ip = ipMatch?.[1] ?? (isSshdProcess(process3) ? sshdPeerIp(message) ?? void 0 : void 0);
|
|
9609
|
+
const user = userMatch?.[1] && userMatch[1].toLowerCase() !== "from" ? userMatch[1] : void 0;
|
|
9608
9610
|
return {
|
|
9609
9611
|
timestamp,
|
|
9610
9612
|
raw,
|
|
@@ -9612,8 +9614,8 @@ function parseAuthMessage(process3, message, timestamp, raw = message) {
|
|
|
9612
9614
|
fields: {
|
|
9613
9615
|
process: process3,
|
|
9614
9616
|
message,
|
|
9615
|
-
ip
|
|
9616
|
-
user
|
|
9617
|
+
ip,
|
|
9618
|
+
user
|
|
9617
9619
|
}
|
|
9618
9620
|
};
|
|
9619
9621
|
}
|
|
@@ -9650,6 +9652,7 @@ function classifySshAuth(entry) {
|
|
|
9650
9652
|
...user ? { details: { user } } : {}
|
|
9651
9653
|
};
|
|
9652
9654
|
}
|
|
9655
|
+
if (/^(?:Disconnected from|Connection closed by|Received disconnect from)\s+(?:invalid|authenticating)\s+user\b/i.test(message)) return null;
|
|
9653
9656
|
if (/invalid user/i.test(message)) {
|
|
9654
9657
|
return {
|
|
9655
9658
|
severity: "high",
|
|
@@ -11209,6 +11212,8 @@ function parseConfigText(raw) {
|
|
|
11209
11212
|
threat_feeds: parsed.threat_feeds,
|
|
11210
11213
|
privileged: parsed.privileged,
|
|
11211
11214
|
command_history: parsed.command_history,
|
|
11215
|
+
file_integrity: parsed.file_integrity,
|
|
11216
|
+
edr: parsed.edr,
|
|
11212
11217
|
lightning: parsed.lightning,
|
|
11213
11218
|
storage: parsed.storage,
|
|
11214
11219
|
// TOML's `[abuse-reporter]` parses to a hyphenated key; expose it under
|
|
@@ -11672,7 +11677,8 @@ var DEDUPE_MS = 10 * 6e4;
|
|
|
11672
11677
|
var MAX_PER_HOUR = 6;
|
|
11673
11678
|
function smshubText(event, host = (0, import_node_os2.hostname)()) {
|
|
11674
11679
|
const evidence = event.details?.evidence?.message;
|
|
11675
|
-
const
|
|
11680
|
+
const ip = event.source_ip && ![event.message, evidence ?? ""].some((t) => t.includes(event.source_ip)) ? ` from ${event.source_ip}` : "";
|
|
11681
|
+
const text = `ThreatCrush ${event.severity.toUpperCase()} on ${host}: ${event.message}${evidence && !event.message.includes(evidence) ? ` | ${evidence}` : ""}${ip}`;
|
|
11676
11682
|
return text.replace(/\s+/g, " ").slice(0, 600);
|
|
11677
11683
|
}
|
|
11678
11684
|
function smshubChannel(config, opts = {}) {
|
|
@@ -12003,7 +12009,7 @@ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date(
|
|
|
12003
12009
|
var import_node_fs19 = require("fs");
|
|
12004
12010
|
var import_node_path13 = require("path");
|
|
12005
12011
|
|
|
12006
|
-
//
|
|
12012
|
+
// ../../../../../node_modules/.pnpm/chalk@6.0.1/node_modules/chalk/source/utilities.js
|
|
12007
12013
|
function stringReplaceAll(string, substring, postfix) {
|
|
12008
12014
|
let index = string.indexOf(substring);
|
|
12009
12015
|
if (index === -1) {
|
|
@@ -12033,7 +12039,7 @@ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
|
|
|
12033
12039
|
return returnValue;
|
|
12034
12040
|
}
|
|
12035
12041
|
|
|
12036
|
-
//
|
|
12042
|
+
// ../../../../../node_modules/.pnpm/chalk@6.0.1/node_modules/chalk/source/vendor/ansi-styles/index.js
|
|
12037
12043
|
var ANSI_BACKGROUND_OFFSET = 10;
|
|
12038
12044
|
var ANSI_UNDERLINE_OFFSET = 20;
|
|
12039
12045
|
var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
|
|
@@ -12255,7 +12261,7 @@ function assembleStyles() {
|
|
|
12255
12261
|
var ansiStyles = assembleStyles();
|
|
12256
12262
|
var ansi_styles_default = ansiStyles;
|
|
12257
12263
|
|
|
12258
|
-
//
|
|
12264
|
+
// ../../../../../node_modules/.pnpm/chalk@6.0.1/node_modules/chalk/source/vendor/supports-color/index.js
|
|
12259
12265
|
var import_node_process = __toESM(require("process"), 1);
|
|
12260
12266
|
var import_node_os4 = __toESM(require("os"), 1);
|
|
12261
12267
|
var import_node_tty = __toESM(require("tty"), 1);
|
|
@@ -12397,7 +12403,7 @@ var supportsColor = {
|
|
|
12397
12403
|
};
|
|
12398
12404
|
var supports_color_default = supportsColor;
|
|
12399
12405
|
|
|
12400
|
-
//
|
|
12406
|
+
// ../../../../../node_modules/.pnpm/chalk@6.0.1/node_modules/chalk/source/index.js
|
|
12401
12407
|
var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
|
|
12402
12408
|
var GENERATOR = /* @__PURE__ */ Symbol("GENERATOR");
|
|
12403
12409
|
var STYLER = /* @__PURE__ */ Symbol("STYLER");
|
|
@@ -12480,8 +12486,8 @@ for (const model of usedModels) {
|
|
|
12480
12486
|
styles2[styleName] = {
|
|
12481
12487
|
get() {
|
|
12482
12488
|
const styleFunction = function(first, second, third) {
|
|
12483
|
-
const
|
|
12484
|
-
return createBuilder(this, createStyler(
|
|
12489
|
+
const open2 = converters[this.level](first, second, third);
|
|
12490
|
+
return createBuilder(this, createStyler(open2, close, this[STYLER]), this[IS_EMPTY]);
|
|
12485
12491
|
};
|
|
12486
12492
|
Object.defineProperty(this, styleName, { value: styleFunction });
|
|
12487
12493
|
return styleFunction;
|
|
@@ -12505,18 +12511,18 @@ var proto = Object.defineProperties(
|
|
|
12505
12511
|
}
|
|
12506
12512
|
}
|
|
12507
12513
|
);
|
|
12508
|
-
var createStyler = (
|
|
12514
|
+
var createStyler = (open2, close, parent) => {
|
|
12509
12515
|
let openAll;
|
|
12510
12516
|
let closeAll;
|
|
12511
12517
|
if (parent === void 0) {
|
|
12512
|
-
openAll =
|
|
12518
|
+
openAll = open2;
|
|
12513
12519
|
closeAll = close;
|
|
12514
12520
|
} else {
|
|
12515
|
-
openAll = parent.openAll +
|
|
12521
|
+
openAll = parent.openAll + open2;
|
|
12516
12522
|
closeAll = close + parent.closeAll;
|
|
12517
12523
|
}
|
|
12518
12524
|
return {
|
|
12519
|
-
open,
|
|
12525
|
+
open: open2,
|
|
12520
12526
|
close,
|
|
12521
12527
|
openAll,
|
|
12522
12528
|
closeAll,
|
|
@@ -14210,8 +14216,8 @@ function fileTextOf(lines) {
|
|
|
14210
14216
|
function withoutSingleQuoted(text) {
|
|
14211
14217
|
return text.replace(/'[^'\n]*'/g, "''");
|
|
14212
14218
|
}
|
|
14213
|
-
function calleeEndingAt(text,
|
|
14214
|
-
let end =
|
|
14219
|
+
function calleeEndingAt(text, open2) {
|
|
14220
|
+
let end = open2;
|
|
14215
14221
|
while (end > 0 && (text[end - 1] === " " || text[end - 1] === " ")) end -= 1;
|
|
14216
14222
|
let start = end;
|
|
14217
14223
|
while (start > 0 && /[\w$.]/.test(text[start - 1])) start -= 1;
|
|
@@ -14366,19 +14372,19 @@ function bufferFilledBeforeUse(ctx) {
|
|
|
14366
14372
|
}
|
|
14367
14373
|
var HEREDOC_OPENER = /<<(-?)\s*(['"]?)([A-Za-z_][\w]*)\2/;
|
|
14368
14374
|
function insideDisplayedHeredoc(lines, index) {
|
|
14369
|
-
let
|
|
14375
|
+
let open2 = null;
|
|
14370
14376
|
for (let i = 0; i < index; i += 1) {
|
|
14371
14377
|
const line = lines[i] ?? "";
|
|
14372
|
-
if (
|
|
14373
|
-
if (line.trim() ===
|
|
14378
|
+
if (open2) {
|
|
14379
|
+
if (line.trim() === open2.terminator) open2 = null;
|
|
14374
14380
|
continue;
|
|
14375
14381
|
}
|
|
14376
14382
|
if (line.includes("<<<")) continue;
|
|
14377
14383
|
const found = HEREDOC_OPENER.exec(line);
|
|
14378
|
-
if (found)
|
|
14384
|
+
if (found) open2 = { terminator: found[3], opener: line };
|
|
14379
14385
|
}
|
|
14380
|
-
if (!
|
|
14381
|
-
const opener =
|
|
14386
|
+
if (!open2) return false;
|
|
14387
|
+
const opener = open2.opener.replace(/\s[12]?>&2\b/g, " ");
|
|
14382
14388
|
return /^\s*cat\b/.test(opener) && !/>/.test(opener) && !/\|/.test(opener);
|
|
14383
14389
|
}
|
|
14384
14390
|
var DISPLAY_STRING = /(\b(?:echo|printf|say|info|warn|error)\s+(?:-[A-Za-z]+\s+)*)((?:"(?:[^"\\\n]|\\.)*"|'[^'\n]*')(?:\s+(?:"(?:[^"\\\n]|\\.)*"|'[^'\n]*'))*)(?=\s*(?:$|;|&&|\|\||[12]?>&2|>\s*\/dev\/(?:stderr|tty)\b|\)|#))/g;
|
|
@@ -18836,10 +18842,845 @@ var CommandHistoryWatcher = class {
|
|
|
18836
18842
|
}
|
|
18837
18843
|
};
|
|
18838
18844
|
|
|
18839
|
-
// src/daemon/workers/
|
|
18845
|
+
// src/daemon/workers/file-integrity.ts
|
|
18840
18846
|
var import_node_fs27 = require("fs");
|
|
18847
|
+
var import_promises3 = require("fs/promises");
|
|
18848
|
+
var import_node_crypto8 = require("crypto");
|
|
18841
18849
|
var import_node_path21 = require("path");
|
|
18850
|
+
var DEFAULT_POLL_MS = 15 * 6e4;
|
|
18851
|
+
var MAX_FILES = 5e4;
|
|
18852
|
+
var MAX_FILE_BYTES = 64 * 1024 * 1024;
|
|
18853
|
+
var MAX_SCAN_BYTES = 512 * 1024 * 1024;
|
|
18854
|
+
var MAX_CHANGES_PER_EVENT = 100;
|
|
18855
|
+
var MAX_WATCH_DIRECTORIES = 2048;
|
|
18856
|
+
var WATCH_DEBOUNCE_MS = 500;
|
|
18857
|
+
var WATCH_MAX_DELAY_MS = 5e3;
|
|
18858
|
+
var MASS_CHANGE_COUNT = 25;
|
|
18859
|
+
var MASS_CHANGE_ENTROPY_RISE_BITS = 0.5;
|
|
18860
|
+
var READ_CHUNK_BYTES = 64 * 1024;
|
|
18861
|
+
var CANARY_CONTENT = "ThreatCrush file integrity canary v1\n";
|
|
18862
|
+
function fileIntegritySettings(section) {
|
|
18863
|
+
const safePath = (value) => {
|
|
18864
|
+
if (typeof value !== "string" || !(0, import_node_path21.isAbsolute)(value) || value.split(import_node_path21.sep).includes("..")) return null;
|
|
18865
|
+
const path = (0, import_node_path21.normalize)(value);
|
|
18866
|
+
return path === "/" ? null : path;
|
|
18867
|
+
};
|
|
18868
|
+
const strings = (values) => Array.isArray(values) ? [...new Set(values.map(safePath).filter((path) => path !== null))] : [];
|
|
18869
|
+
const configuredSeconds = section?.poll_interval_seconds;
|
|
18870
|
+
const pollMs = typeof configuredSeconds === "number" && Number.isFinite(configuredSeconds) ? Math.max(60, Math.min(86400, Math.floor(configuredSeconds))) * 1e3 : DEFAULT_POLL_MS;
|
|
18871
|
+
return {
|
|
18872
|
+
// File scans read disk contents (only to hash them), so make this explicit
|
|
18873
|
+
// instead of adding an unannounced I/O load to existing installations.
|
|
18874
|
+
enabled: section?.enabled === true,
|
|
18875
|
+
paths: strings(section?.paths),
|
|
18876
|
+
canaries: strings(section?.canaries),
|
|
18877
|
+
canaryDirectories: strings(section?.canary_directories),
|
|
18878
|
+
pollMs
|
|
18879
|
+
};
|
|
18880
|
+
}
|
|
18881
|
+
function signature(value) {
|
|
18882
|
+
return `${value.sha256};size=${value.size};mode=${value.mode.toString(8)};uid=${value.uid};gid=${value.gid};entropy=${value.entropy.toFixed(3)}`;
|
|
18883
|
+
}
|
|
18884
|
+
async function readState(path) {
|
|
18885
|
+
try {
|
|
18886
|
+
const parsed = JSON.parse(await (0, import_promises3.readFile)(path, "utf8"));
|
|
18887
|
+
if (parsed.schema !== 1 || !Array.isArray(parsed.targets) || !parsed.files || typeof parsed.files !== "object") return null;
|
|
18888
|
+
return parsed;
|
|
18889
|
+
} catch {
|
|
18890
|
+
return null;
|
|
18891
|
+
}
|
|
18892
|
+
}
|
|
18893
|
+
async function writeState(path, state) {
|
|
18894
|
+
await (0, import_promises3.mkdir)((0, import_node_path21.dirname)(path), { recursive: true, mode: 448 });
|
|
18895
|
+
const temp = `${path}.${process.pid}.${(0, import_node_crypto8.randomUUID)()}.tmp`;
|
|
18896
|
+
await (0, import_promises3.writeFile)(temp, JSON.stringify(state), { mode: 384 });
|
|
18897
|
+
await (0, import_promises3.rename)(temp, path);
|
|
18898
|
+
}
|
|
18899
|
+
async function hashFile(path, handle, size) {
|
|
18900
|
+
const hash = (0, import_node_crypto8.createHash)("sha256");
|
|
18901
|
+
const buffer = Buffer.alloc(READ_CHUNK_BYTES);
|
|
18902
|
+
const counts = new Uint32Array(256);
|
|
18903
|
+
let position = 0;
|
|
18904
|
+
while (position < size) {
|
|
18905
|
+
const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, size - position), position);
|
|
18906
|
+
if (bytesRead === 0) throw new Error(`file changed while reading: ${path}`);
|
|
18907
|
+
const chunk = buffer.subarray(0, bytesRead);
|
|
18908
|
+
hash.update(chunk);
|
|
18909
|
+
for (const byte of chunk) counts[byte]++;
|
|
18910
|
+
position += bytesRead;
|
|
18911
|
+
}
|
|
18912
|
+
let entropy = 0;
|
|
18913
|
+
if (size > 0) for (const count of counts) {
|
|
18914
|
+
if (count === 0) continue;
|
|
18915
|
+
const probability = count / size;
|
|
18916
|
+
entropy -= probability * Math.log2(probability);
|
|
18917
|
+
}
|
|
18918
|
+
return { sha256: hash.digest("hex"), entropy };
|
|
18919
|
+
}
|
|
18920
|
+
var OPEN_FILE_FLAGS = import_promises3.constants.O_RDONLY | import_promises3.constants.O_NONBLOCK | (import_promises3.constants.O_NOFOLLOW ?? 0);
|
|
18921
|
+
var OPEN_DIR_FLAGS = OPEN_FILE_FLAGS | import_promises3.constants.O_DIRECTORY;
|
|
18922
|
+
var CREATE_FILE_FLAGS = import_promises3.constants.O_WRONLY | import_promises3.constants.O_CREAT | import_promises3.constants.O_EXCL | import_promises3.constants.O_NOFOLLOW;
|
|
18923
|
+
function autoCanaryPath(directory) {
|
|
18924
|
+
return (0, import_node_path21.join)(directory, ".threatcrush-canary");
|
|
18925
|
+
}
|
|
18926
|
+
async function openAbsoluteDirectory(path) {
|
|
18927
|
+
const parts = path.split(import_node_path21.sep).filter((part) => part && part !== ".");
|
|
18928
|
+
if (parts.includes("..")) throw new Error("invalid canary directory");
|
|
18929
|
+
let directory = await (0, import_promises3.open)("/", OPEN_DIR_FLAGS);
|
|
18930
|
+
try {
|
|
18931
|
+
for (const part of parts) {
|
|
18932
|
+
const next = await (0, import_promises3.open)(`/proc/self/fd/${directory.fd}/${part}`, OPEN_DIR_FLAGS);
|
|
18933
|
+
await directory.close();
|
|
18934
|
+
directory = next;
|
|
18935
|
+
}
|
|
18936
|
+
return directory;
|
|
18937
|
+
} catch (error) {
|
|
18938
|
+
await directory.close().catch(() => void 0);
|
|
18939
|
+
throw error;
|
|
18940
|
+
}
|
|
18941
|
+
}
|
|
18942
|
+
async function createAutoCanary(path) {
|
|
18943
|
+
try {
|
|
18944
|
+
const existing = await openAbsoluteTarget(path);
|
|
18945
|
+
await existing.close();
|
|
18946
|
+
return false;
|
|
18947
|
+
} catch (error) {
|
|
18948
|
+
if (error.code !== "ENOENT") return false;
|
|
18949
|
+
}
|
|
18950
|
+
const directory = await openAbsoluteDirectory((0, import_node_path21.dirname)(path));
|
|
18951
|
+
try {
|
|
18952
|
+
const file = await (0, import_promises3.open)(`/proc/self/fd/${directory.fd}/${(0, import_node_path21.basename)(path)}`, CREATE_FILE_FLAGS, 438);
|
|
18953
|
+
try {
|
|
18954
|
+
await file.chmod(438);
|
|
18955
|
+
await file.writeFile(CANARY_CONTENT);
|
|
18956
|
+
await file.sync();
|
|
18957
|
+
} finally {
|
|
18958
|
+
await file.close();
|
|
18959
|
+
}
|
|
18960
|
+
return true;
|
|
18961
|
+
} catch (error) {
|
|
18962
|
+
if (error.code === "EEXIST") return false;
|
|
18963
|
+
throw error;
|
|
18964
|
+
} finally {
|
|
18965
|
+
await directory.close();
|
|
18966
|
+
}
|
|
18967
|
+
}
|
|
18968
|
+
async function openAbsoluteTarget(path) {
|
|
18969
|
+
const parts = path.split(import_node_path21.sep).filter((part) => part && part !== ".");
|
|
18970
|
+
if (parts.length === 0 || parts.includes("..")) throw new Error("invalid file integrity path");
|
|
18971
|
+
let directory = await (0, import_promises3.open)("/", OPEN_DIR_FLAGS);
|
|
18972
|
+
try {
|
|
18973
|
+
for (const part of parts.slice(0, -1)) {
|
|
18974
|
+
const next = await (0, import_promises3.open)(`/proc/self/fd/${directory.fd}/${part}`, OPEN_DIR_FLAGS);
|
|
18975
|
+
await directory.close();
|
|
18976
|
+
directory = next;
|
|
18977
|
+
}
|
|
18978
|
+
const target = await (0, import_promises3.open)(`/proc/self/fd/${directory.fd}/${parts.at(-1)}`, OPEN_FILE_FLAGS);
|
|
18979
|
+
await directory.close();
|
|
18980
|
+
return target;
|
|
18981
|
+
} catch (error) {
|
|
18982
|
+
await directory.close().catch(() => void 0);
|
|
18983
|
+
throw error;
|
|
18984
|
+
}
|
|
18985
|
+
}
|
|
18986
|
+
async function scanTargets(targets, canaries) {
|
|
18987
|
+
const files = {};
|
|
18988
|
+
const directories = [];
|
|
18989
|
+
const visited = /* @__PURE__ */ new Set();
|
|
18990
|
+
const errors = /* @__PURE__ */ new Set();
|
|
18991
|
+
let complete = true;
|
|
18992
|
+
let skipped = 0;
|
|
18993
|
+
let bytes = 0;
|
|
18994
|
+
const walk = async (path, parent) => {
|
|
18995
|
+
if (visited.has(path) || !complete) return;
|
|
18996
|
+
visited.add(path);
|
|
18997
|
+
if (visited.size > MAX_FILES) {
|
|
18998
|
+
complete = false;
|
|
18999
|
+
errors.add(path);
|
|
19000
|
+
return;
|
|
19001
|
+
}
|
|
19002
|
+
let handle;
|
|
19003
|
+
try {
|
|
19004
|
+
handle = parent ? await (0, import_promises3.open)(`/proc/self/fd/${parent.fd}/${path.slice(path.lastIndexOf(import_node_path21.sep) + 1)}`, OPEN_FILE_FLAGS) : await openAbsoluteTarget(path);
|
|
19005
|
+
const stat = await handle.stat();
|
|
19006
|
+
if (stat.isDirectory()) {
|
|
19007
|
+
directories.push(path);
|
|
19008
|
+
if (canaries.has(path)) {
|
|
19009
|
+
complete = false;
|
|
19010
|
+
errors.add(path);
|
|
19011
|
+
return;
|
|
19012
|
+
}
|
|
19013
|
+
let entries;
|
|
19014
|
+
try {
|
|
19015
|
+
entries = await (0, import_promises3.readdir)(`/proc/self/fd/${handle.fd}`, { withFileTypes: true });
|
|
19016
|
+
} catch {
|
|
19017
|
+
complete = false;
|
|
19018
|
+
errors.add(path);
|
|
19019
|
+
return;
|
|
19020
|
+
}
|
|
19021
|
+
for (const entry of entries) {
|
|
19022
|
+
await walk((0, import_node_path21.join)(path, entry.name), handle);
|
|
19023
|
+
if (!complete) return;
|
|
19024
|
+
}
|
|
19025
|
+
return;
|
|
19026
|
+
}
|
|
19027
|
+
if (!stat.isFile()) {
|
|
19028
|
+
skipped++;
|
|
19029
|
+
return;
|
|
19030
|
+
}
|
|
19031
|
+
if (stat.size > MAX_FILE_BYTES || bytes + stat.size > MAX_SCAN_BYTES) {
|
|
19032
|
+
complete = false;
|
|
19033
|
+
errors.add(path);
|
|
19034
|
+
return;
|
|
19035
|
+
}
|
|
19036
|
+
const { sha256, entropy } = await hashFile(path, handle, stat.size);
|
|
19037
|
+
const afterRead = await handle.stat();
|
|
19038
|
+
if (afterRead.size !== stat.size || afterRead.mtimeMs !== stat.mtimeMs || afterRead.ctimeMs !== stat.ctimeMs) {
|
|
19039
|
+
throw new Error("file changed while reading");
|
|
19040
|
+
}
|
|
19041
|
+
bytes += stat.size;
|
|
19042
|
+
files[path] = signature({
|
|
19043
|
+
sha256,
|
|
19044
|
+
entropy,
|
|
19045
|
+
size: stat.size,
|
|
19046
|
+
mode: stat.mode & 4095,
|
|
19047
|
+
uid: stat.uid,
|
|
19048
|
+
gid: stat.gid
|
|
19049
|
+
});
|
|
19050
|
+
} catch (error) {
|
|
19051
|
+
const code = error.code;
|
|
19052
|
+
if (code === "ENOENT" && targets.includes(path)) files[path] = "missing";
|
|
19053
|
+
else if (code === "ELOOP" && !canaries.has(path)) skipped++;
|
|
19054
|
+
else if (code === "ENOENT" || code === "ELOOP") {
|
|
19055
|
+
complete = false;
|
|
19056
|
+
errors.add(path);
|
|
19057
|
+
} else {
|
|
19058
|
+
complete = false;
|
|
19059
|
+
errors.add(path);
|
|
19060
|
+
}
|
|
19061
|
+
} finally {
|
|
19062
|
+
await handle?.close().catch(() => void 0);
|
|
19063
|
+
}
|
|
19064
|
+
};
|
|
19065
|
+
for (const target of targets) {
|
|
19066
|
+
await walk(target);
|
|
19067
|
+
if (!complete) break;
|
|
19068
|
+
}
|
|
19069
|
+
return { files, directories, complete, skipped, bytes, errorPaths: [...errors].slice(0, 20) };
|
|
19070
|
+
}
|
|
19071
|
+
function changedPaths(before, after) {
|
|
19072
|
+
const paths = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)]);
|
|
19073
|
+
const changed = [];
|
|
19074
|
+
for (const path of paths) {
|
|
19075
|
+
const previous = before[path] ?? "missing";
|
|
19076
|
+
const current = after[path] ?? "missing";
|
|
19077
|
+
const normalized = (value) => typeof value === "string" ? value.replace(/;entropy=\d+(?:\.\d+)?$/, "") : value;
|
|
19078
|
+
if (normalized(previous) !== normalized(current)) changed.push({ path, state: current });
|
|
19079
|
+
}
|
|
19080
|
+
return changed;
|
|
19081
|
+
}
|
|
19082
|
+
function meanEntropy(paths, files) {
|
|
19083
|
+
const values = paths.flatMap((path) => {
|
|
19084
|
+
const signature2 = files[path];
|
|
19085
|
+
if (typeof signature2 !== "string") return [];
|
|
19086
|
+
const match = /;entropy=(\d+(?:\.\d+)?)$/.exec(signature2);
|
|
19087
|
+
return match ? [Number(match[1])] : [];
|
|
19088
|
+
});
|
|
19089
|
+
return values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : null;
|
|
19090
|
+
}
|
|
19091
|
+
var FileIntegrityWatch = class {
|
|
19092
|
+
constructor(opts) {
|
|
19093
|
+
this.opts = opts;
|
|
19094
|
+
this.now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
19095
|
+
this.canaries = /* @__PURE__ */ new Set([
|
|
19096
|
+
...opts.settings.canaries,
|
|
19097
|
+
...opts.settings.canaryDirectories.map(autoCanaryPath)
|
|
19098
|
+
]);
|
|
19099
|
+
}
|
|
19100
|
+
opts;
|
|
19101
|
+
timer = null;
|
|
19102
|
+
running = false;
|
|
19103
|
+
now;
|
|
19104
|
+
canaries;
|
|
19105
|
+
watchers = /* @__PURE__ */ new Map();
|
|
19106
|
+
eventTimer = null;
|
|
19107
|
+
eventFirstAt = 0;
|
|
19108
|
+
eventScanPending = false;
|
|
19109
|
+
watcherLimitLogged = false;
|
|
19110
|
+
get autoCanaries() {
|
|
19111
|
+
return this.opts.settings.canaryDirectories.map(autoCanaryPath);
|
|
19112
|
+
}
|
|
19113
|
+
async ensureAutoCanaries(allowed) {
|
|
19114
|
+
for (const path of this.autoCanaries) {
|
|
19115
|
+
if (!allowed.has(path)) continue;
|
|
19116
|
+
try {
|
|
19117
|
+
if (await createAutoCanary(path)) this.opts.log(`[file-integrity] placed a canary at ${path}`);
|
|
19118
|
+
} catch (error) {
|
|
19119
|
+
this.opts.log(`[file-integrity] could not place canary at ${path}: ${error.message.split("\n")[0]}`);
|
|
19120
|
+
}
|
|
19121
|
+
}
|
|
19122
|
+
}
|
|
19123
|
+
start() {
|
|
19124
|
+
if (!this.opts.settings.enabled) {
|
|
19125
|
+
this.opts.log("[file-integrity] disabled; set [file_integrity] enabled = true to monitor configured paths");
|
|
19126
|
+
return;
|
|
19127
|
+
}
|
|
19128
|
+
const targets = [.../* @__PURE__ */ new Set([...this.opts.settings.paths, ...this.opts.settings.canaries, ...this.autoCanaries])];
|
|
19129
|
+
if (targets.length === 0) {
|
|
19130
|
+
this.opts.log("[file-integrity] enabled with no paths; configure [file_integrity] paths or canaries");
|
|
19131
|
+
return;
|
|
19132
|
+
}
|
|
19133
|
+
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`);
|
|
19134
|
+
void this.scanOnce();
|
|
19135
|
+
this.timer = setInterval(() => {
|
|
19136
|
+
void this.scanOnce();
|
|
19137
|
+
}, this.opts.settings.pollMs);
|
|
19138
|
+
this.timer.unref?.();
|
|
19139
|
+
}
|
|
19140
|
+
stop() {
|
|
19141
|
+
if (this.timer) clearInterval(this.timer);
|
|
19142
|
+
this.timer = null;
|
|
19143
|
+
if (this.eventTimer) clearTimeout(this.eventTimer);
|
|
19144
|
+
this.eventTimer = null;
|
|
19145
|
+
this.eventFirstAt = 0;
|
|
19146
|
+
this.eventScanPending = false;
|
|
19147
|
+
for (const watcher of this.watchers.values()) watcher.close();
|
|
19148
|
+
this.watchers.clear();
|
|
19149
|
+
}
|
|
19150
|
+
refreshWatchers(directories) {
|
|
19151
|
+
const wanted = new Set(directories.slice(0, MAX_WATCH_DIRECTORIES));
|
|
19152
|
+
for (const [path, watcher] of this.watchers) {
|
|
19153
|
+
if (wanted.has(path)) continue;
|
|
19154
|
+
watcher.close();
|
|
19155
|
+
this.watchers.delete(path);
|
|
19156
|
+
}
|
|
19157
|
+
for (const path of wanted) {
|
|
19158
|
+
if (this.watchers.has(path)) continue;
|
|
19159
|
+
try {
|
|
19160
|
+
const watcher = (0, import_node_fs27.watch)(path, { persistent: false }, () => {
|
|
19161
|
+
this.scheduleEventScan();
|
|
19162
|
+
});
|
|
19163
|
+
watcher.on("error", (error) => {
|
|
19164
|
+
this.opts.log(`[file-integrity] inotify watch unavailable for ${path}: ${error.message}`);
|
|
19165
|
+
watcher.close();
|
|
19166
|
+
this.watchers.delete(path);
|
|
19167
|
+
});
|
|
19168
|
+
this.watchers.set(path, watcher);
|
|
19169
|
+
} catch (error) {
|
|
19170
|
+
this.opts.log(`[file-integrity] inotify watch unavailable for ${path}: ${error.message.split("\n")[0]}`);
|
|
19171
|
+
}
|
|
19172
|
+
}
|
|
19173
|
+
if (directories.length > MAX_WATCH_DIRECTORIES && !this.watcherLimitLogged) {
|
|
19174
|
+
this.watcherLimitLogged = true;
|
|
19175
|
+
this.opts.log(`[file-integrity] watching the first ${MAX_WATCH_DIRECTORIES} directories; polling remains the fallback for the rest`);
|
|
19176
|
+
}
|
|
19177
|
+
}
|
|
19178
|
+
/** Debounce bursts, but cap the delay so continuous writes still get scanned. */
|
|
19179
|
+
scheduleEventScan() {
|
|
19180
|
+
this.eventScanPending = true;
|
|
19181
|
+
if (this.eventFirstAt === 0) this.eventFirstAt = Date.now();
|
|
19182
|
+
if (this.running) return;
|
|
19183
|
+
if (this.eventTimer) clearTimeout(this.eventTimer);
|
|
19184
|
+
const dueAt = Math.min(Date.now() + WATCH_DEBOUNCE_MS, this.eventFirstAt + WATCH_MAX_DELAY_MS);
|
|
19185
|
+
this.eventTimer = setTimeout(() => {
|
|
19186
|
+
this.eventTimer = null;
|
|
19187
|
+
if (this.running) return;
|
|
19188
|
+
this.eventScanPending = false;
|
|
19189
|
+
this.eventFirstAt = 0;
|
|
19190
|
+
void this.scanOnce();
|
|
19191
|
+
}, Math.max(0, dueAt - Date.now()));
|
|
19192
|
+
this.eventTimer.unref?.();
|
|
19193
|
+
}
|
|
19194
|
+
async rebaseline() {
|
|
19195
|
+
const targets = [.../* @__PURE__ */ new Set([...this.opts.settings.paths, ...this.opts.settings.canaries, ...this.autoCanaries])];
|
|
19196
|
+
if (!this.opts.settings.enabled || targets.length === 0) return { ok: false, files: 0, reason: "file integrity monitoring is disabled or has no configured paths" };
|
|
19197
|
+
await this.ensureAutoCanaries(new Set(this.autoCanaries));
|
|
19198
|
+
const scan = await scanTargets(targets, this.canaries);
|
|
19199
|
+
if (!scan.complete) return { ok: false, files: Object.keys(scan.files).length, reason: `scan incomplete at ${scan.errorPaths.join(", ") || "configured size limit"}` };
|
|
19200
|
+
const missingCanary = [...this.canaries].find((path) => scan.files[path] === "missing");
|
|
19201
|
+
if (missingCanary) return { ok: false, files: Object.keys(scan.files).length, reason: `configured canary does not exist: ${missingCanary}` };
|
|
19202
|
+
const state = { schema: 1, created_at: this.now().toISOString(), targets, files: scan.files };
|
|
19203
|
+
await writeState(this.opts.baselinePath, state);
|
|
19204
|
+
await writeState(this.opts.observedPath, state);
|
|
19205
|
+
return { ok: true, files: Object.keys(scan.files).length };
|
|
19206
|
+
}
|
|
19207
|
+
async scanOnce() {
|
|
19208
|
+
if (this.running) return;
|
|
19209
|
+
this.running = true;
|
|
19210
|
+
try {
|
|
19211
|
+
const baseline = await readState(this.opts.baselinePath);
|
|
19212
|
+
const previousObserved = await readState(this.opts.observedPath);
|
|
19213
|
+
let baselineFilePresent = false;
|
|
19214
|
+
if (!baseline) {
|
|
19215
|
+
try {
|
|
19216
|
+
await (0, import_promises3.lstat)(this.opts.baselinePath);
|
|
19217
|
+
baselineFilePresent = true;
|
|
19218
|
+
} catch (error) {
|
|
19219
|
+
baselineFilePresent = error.code !== "ENOENT";
|
|
19220
|
+
}
|
|
19221
|
+
}
|
|
19222
|
+
const canCreate = this.autoCanaries.filter((path) => {
|
|
19223
|
+
if (!baseline && !baselineFilePresent) return true;
|
|
19224
|
+
return !!baseline && !baseline.targets.includes(path) && !previousObserved?.targets.includes(path);
|
|
19225
|
+
});
|
|
19226
|
+
await this.ensureAutoCanaries(new Set(canCreate));
|
|
19227
|
+
const targets = [.../* @__PURE__ */ new Set([...this.opts.settings.paths, ...this.opts.settings.canaries, ...this.autoCanaries])];
|
|
19228
|
+
const current = await scanTargets(targets, this.canaries);
|
|
19229
|
+
if (current.complete) {
|
|
19230
|
+
const directories = new Set(current.directories);
|
|
19231
|
+
for (const path of Object.keys(current.files)) {
|
|
19232
|
+
if (!directories.has(path)) directories.add((0, import_node_path21.dirname)(path));
|
|
19233
|
+
}
|
|
19234
|
+
this.refreshWatchers([...directories]);
|
|
19235
|
+
}
|
|
19236
|
+
if (!current.complete) {
|
|
19237
|
+
this.opts.log(`[file-integrity] scan incomplete; no baseline or change state updated (${current.errorPaths.join(", ") || "configured scan limits reached"})`);
|
|
19238
|
+
return;
|
|
19239
|
+
}
|
|
19240
|
+
if (!baseline) {
|
|
19241
|
+
if (baselineFilePresent) {
|
|
19242
|
+
this.emit("critical", "File integrity baseline is unreadable; monitoring paused", "file-integrity-baseline-invalid", [
|
|
19243
|
+
{ path: this.opts.baselinePath, state: "unreadable" }
|
|
19244
|
+
]);
|
|
19245
|
+
this.opts.log("[file-integrity] baseline is present but unreadable; it was not replaced");
|
|
19246
|
+
return;
|
|
19247
|
+
}
|
|
19248
|
+
const missingCanary = [...this.canaries].find((path) => current.files[path] === "missing");
|
|
19249
|
+
if (missingCanary) {
|
|
19250
|
+
this.opts.log(`[file-integrity] cannot record baseline; configured canary does not exist: ${missingCanary}`);
|
|
19251
|
+
return;
|
|
19252
|
+
}
|
|
19253
|
+
const created = { schema: 1, created_at: this.now().toISOString(), targets, files: current.files };
|
|
19254
|
+
await writeState(this.opts.baselinePath, created);
|
|
19255
|
+
await writeState(this.opts.observedPath, created);
|
|
19256
|
+
this.opts.log(`[file-integrity] initial baseline recorded for ${Object.keys(current.files).length} file(s)`);
|
|
19257
|
+
return;
|
|
19258
|
+
}
|
|
19259
|
+
const observed = previousObserved ?? baseline;
|
|
19260
|
+
const sameTargets = (left, right) => {
|
|
19261
|
+
const sortedLeft = [...left].sort();
|
|
19262
|
+
const sortedRight = [...right].sort();
|
|
19263
|
+
return sortedLeft.length === sortedRight.length && sortedLeft.every((path, index) => path === sortedRight[index]);
|
|
19264
|
+
};
|
|
19265
|
+
if (!sameTargets(baseline.targets, targets)) {
|
|
19266
|
+
const removedCanaries = changedPaths(observed.files, current.files).filter((change) => this.canaries.has(change.path) && observed.targets.includes(change.path));
|
|
19267
|
+
if (removedCanaries.length) {
|
|
19268
|
+
this.emit("critical", "A file integrity canary changed or disappeared", "file-integrity-canary", removedCanaries);
|
|
19269
|
+
}
|
|
19270
|
+
if (!sameTargets(observed.targets, targets)) {
|
|
19271
|
+
this.emit(
|
|
19272
|
+
"medium",
|
|
19273
|
+
"File integrity monitoring paths changed; review them and rebaseline",
|
|
19274
|
+
"file-integrity-scope-changed",
|
|
19275
|
+
targets.map((path) => ({ path, state: "scope-changed" }))
|
|
19276
|
+
);
|
|
19277
|
+
}
|
|
19278
|
+
await writeState(this.opts.observedPath, { schema: 1, created_at: observed.created_at, targets, files: current.files });
|
|
19279
|
+
return;
|
|
19280
|
+
}
|
|
19281
|
+
const changes = changedPaths(observed.files, current.files);
|
|
19282
|
+
const canaryChanges = changes.filter((change) => this.canaries.has(change.path));
|
|
19283
|
+
if (canaryChanges.length) {
|
|
19284
|
+
this.emit("critical", "A file integrity canary changed or disappeared", "file-integrity-canary", canaryChanges);
|
|
19285
|
+
}
|
|
19286
|
+
const ordinary = changes.filter((change) => !this.canaries.has(change.path));
|
|
19287
|
+
const paths = ordinary.map((change) => change.path);
|
|
19288
|
+
const beforeEntropy = meanEntropy(paths, observed.files);
|
|
19289
|
+
const afterEntropy = meanEntropy(paths, current.files);
|
|
19290
|
+
const entropyRose = beforeEntropy !== null && afterEntropy !== null && afterEntropy - beforeEntropy >= MASS_CHANGE_ENTROPY_RISE_BITS;
|
|
19291
|
+
if (ordinary.length >= MASS_CHANGE_COUNT || ordinary.length >= 10 && entropyRose) {
|
|
19292
|
+
const entropyDetail = entropyRose ? `; mean changed-file entropy rose from ${beforeEntropy?.toFixed(2)} to ${afterEntropy?.toFixed(2)} bits` : "";
|
|
19293
|
+
this.emit("critical", `${ordinary.length} monitored files changed in one scan${entropyDetail}`, "file-integrity-mass-change", ordinary);
|
|
19294
|
+
} else {
|
|
19295
|
+
for (const change of ordinary) {
|
|
19296
|
+
const expected = baseline.files[change.path] ?? "missing";
|
|
19297
|
+
const restored = change.state === expected;
|
|
19298
|
+
this.emit(
|
|
19299
|
+
restored ? "low" : "high",
|
|
19300
|
+
restored ? `Monitored file returned to its baseline: ${change.path}` : `Monitored file changed: ${change.path}`,
|
|
19301
|
+
restored ? "file-integrity-restored" : "file-integrity-changed",
|
|
19302
|
+
[change]
|
|
19303
|
+
);
|
|
19304
|
+
}
|
|
19305
|
+
}
|
|
19306
|
+
const nextObserved = { schema: 1, created_at: observed.created_at, targets, files: current.files };
|
|
19307
|
+
await writeState(this.opts.observedPath, nextObserved);
|
|
19308
|
+
} catch (error) {
|
|
19309
|
+
this.opts.log(`[file-integrity] scan failed: ${error.message.split("\n")[0]}`);
|
|
19310
|
+
} finally {
|
|
19311
|
+
this.running = false;
|
|
19312
|
+
if (this.eventScanPending && !this.eventTimer) this.scheduleEventScan();
|
|
19313
|
+
}
|
|
19314
|
+
}
|
|
19315
|
+
emit(severity, message, ruleId, changes) {
|
|
19316
|
+
const event = {
|
|
19317
|
+
timestamp: this.now(),
|
|
19318
|
+
module: "file-integrity",
|
|
19319
|
+
category: "system",
|
|
19320
|
+
severity,
|
|
19321
|
+
message: message.replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 500),
|
|
19322
|
+
details: {
|
|
19323
|
+
rule_id: ruleId,
|
|
19324
|
+
change_count: changes.length,
|
|
19325
|
+
changes: changes.slice(0, MAX_CHANGES_PER_EVENT).map(({ path, state }) => ({
|
|
19326
|
+
path,
|
|
19327
|
+
state: state === "missing" ? "missing" : "present"
|
|
19328
|
+
})),
|
|
19329
|
+
truncated: changes.length > MAX_CHANGES_PER_EVENT
|
|
19330
|
+
}
|
|
19331
|
+
};
|
|
19332
|
+
try {
|
|
19333
|
+
insertEvent(event);
|
|
19334
|
+
} catch {
|
|
19335
|
+
}
|
|
19336
|
+
this.opts.bus.publish(event);
|
|
19337
|
+
}
|
|
19338
|
+
};
|
|
19339
|
+
|
|
19340
|
+
// src/daemon/workers/edr.ts
|
|
19341
|
+
var import_node_fs28 = require("fs");
|
|
19342
|
+
var import_node_path22 = require("path");
|
|
18842
19343
|
var import_node_child_process9 = require("child_process");
|
|
19344
|
+
var DEFAULT_AUDIT_LOG = "/var/log/audit/audit.log";
|
|
19345
|
+
var DEFAULT_WEB_USERS = ["www-data", "nginx", "apache", "httpd", "caddy", "node"];
|
|
19346
|
+
var DEFAULT_TEMP_PATHS = ["/tmp", "/var/tmp", "/dev/shm"];
|
|
19347
|
+
var MAX_SEEN_EVENTS = 4096;
|
|
19348
|
+
var WEB_KEY = "threatcrush_edr_web";
|
|
19349
|
+
var TEMP_KEY = "threatcrush_edr_temp";
|
|
19350
|
+
var MINER_KEY = "threatcrush_edr_miner";
|
|
19351
|
+
var CONNECT_KEY = "threatcrush_edr_connect";
|
|
19352
|
+
var LISTEN_KEY = "threatcrush_edr_listen";
|
|
19353
|
+
var CPU_SAMPLE_MS = 15e3;
|
|
19354
|
+
var CPU_SUSTAIN_MS = 6e4;
|
|
19355
|
+
var CPU_THRESHOLD_PERCENT = 80;
|
|
19356
|
+
var SHELLS = /* @__PURE__ */ new Set(["sh", "bash", "dash", "zsh", "ksh", "fish"]);
|
|
19357
|
+
var DOWNLOADERS = /* @__PURE__ */ new Set(["curl", "wget"]);
|
|
19358
|
+
var MINERS = /* @__PURE__ */ new Set(["xmrig", "minerd", "cpuminer", "cpuminer-multi", "kdevtmpfsi", "kinsing", "cryptonight"]);
|
|
19359
|
+
function safeAbsolutePath(value) {
|
|
19360
|
+
if (typeof value !== "string" || !(0, import_node_path22.isAbsolute)(value) || value.split(import_node_path22.sep).includes("..")) return null;
|
|
19361
|
+
const path = (0, import_node_path22.normalize)(value);
|
|
19362
|
+
return path === "/" ? null : path;
|
|
19363
|
+
}
|
|
19364
|
+
function edrSettings(section) {
|
|
19365
|
+
const configuredLog = safeAbsolutePath(section?.audit_log_path) ?? DEFAULT_AUDIT_LOG;
|
|
19366
|
+
const configuredUsers = Array.isArray(section?.web_service_users) ? [...new Set(section.web_service_users.map((value) => String(value).trim()).filter((value) => /^[a-z_][a-z0-9_-]*\$?$/i.test(value)))] : DEFAULT_WEB_USERS;
|
|
19367
|
+
const configuredPaths = Array.isArray(section?.temp_exec_paths) ? [...new Set(section.temp_exec_paths.map(safeAbsolutePath).filter((path) => path !== null))] : DEFAULT_TEMP_PATHS;
|
|
19368
|
+
const seconds = section?.poll_interval_seconds;
|
|
19369
|
+
const pollMs = typeof seconds === "number" && Number.isFinite(seconds) ? Math.max(1, Math.min(60, Math.floor(seconds))) * 1e3 : 2e3;
|
|
19370
|
+
const baselineSeconds = section?.network_baseline_seconds;
|
|
19371
|
+
return {
|
|
19372
|
+
enabled: section?.enabled === true,
|
|
19373
|
+
auditLogPath: configuredLog,
|
|
19374
|
+
webServiceUsers: configuredUsers,
|
|
19375
|
+
tempExecPaths: configuredPaths,
|
|
19376
|
+
watchNetworkSyscalls: section?.watch_network_syscalls === true,
|
|
19377
|
+
networkBaselineMs: typeof baselineSeconds === "number" && Number.isFinite(baselineSeconds) ? Math.max(0, Math.min(3600, Math.floor(baselineSeconds))) * 1e3 : 6e4,
|
|
19378
|
+
watchUnknownTempCpu: section?.watch_unknown_temp_cpu !== false,
|
|
19379
|
+
pollMs
|
|
19380
|
+
};
|
|
19381
|
+
}
|
|
19382
|
+
function parseAuditFields(line) {
|
|
19383
|
+
const fields = {};
|
|
19384
|
+
const pattern = /(?:^|\s)([A-Za-z0-9_]+)=("(?:\\.|[^"\\])*"|\S+)/g;
|
|
19385
|
+
for (const match of line.matchAll(pattern)) {
|
|
19386
|
+
const raw = match[2];
|
|
19387
|
+
fields[match[1]] = raw.startsWith('"') && raw.endsWith('"') ? raw.slice(1, -1).replace(/\\(["\\])/g, "$1") : raw;
|
|
19388
|
+
}
|
|
19389
|
+
return fields;
|
|
19390
|
+
}
|
|
19391
|
+
function parseAuditRecord(line) {
|
|
19392
|
+
const header = /^type=SYSCALL\b.*?\bmsg=audit\((\d+(?:\.\d+)?):(\d+)\):/.exec(line);
|
|
19393
|
+
if (!header) return null;
|
|
19394
|
+
const fields = parseAuditFields(line);
|
|
19395
|
+
if (fields.success !== "yes" || !fields.key || fields.key === "(null)") return null;
|
|
19396
|
+
const executable = fields.exe ?? "";
|
|
19397
|
+
const euid = Number(fields.euid);
|
|
19398
|
+
const seconds = Number(header[1]);
|
|
19399
|
+
if (!executable.startsWith("/") || !Number.isInteger(euid) || !Number.isFinite(seconds)) return null;
|
|
19400
|
+
const pid = Number(fields.pid);
|
|
19401
|
+
const ppid = Number(fields.ppid);
|
|
19402
|
+
return {
|
|
19403
|
+
timestamp: new Date(seconds * 1e3),
|
|
19404
|
+
serial: header[2],
|
|
19405
|
+
key: fields.key,
|
|
19406
|
+
executable,
|
|
19407
|
+
comm: fields.comm ?? (0, import_node_path22.basename)(executable),
|
|
19408
|
+
euid,
|
|
19409
|
+
...Number.isInteger(pid) && pid > 0 ? { pid } : {},
|
|
19410
|
+
...Number.isInteger(ppid) && ppid > 0 ? { ppid } : {}
|
|
19411
|
+
};
|
|
19412
|
+
}
|
|
19413
|
+
function accountNames2() {
|
|
19414
|
+
let raw = "";
|
|
19415
|
+
try {
|
|
19416
|
+
raw = (0, import_node_child_process9.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
|
|
19417
|
+
} catch {
|
|
19418
|
+
try {
|
|
19419
|
+
raw = (0, import_node_fs28.readFileSync)("/etc/passwd", "utf8");
|
|
19420
|
+
} catch {
|
|
19421
|
+
return /* @__PURE__ */ new Map();
|
|
19422
|
+
}
|
|
19423
|
+
}
|
|
19424
|
+
const out = /* @__PURE__ */ new Map();
|
|
19425
|
+
for (const line of raw.split("\n")) {
|
|
19426
|
+
const fields = line.split(":");
|
|
19427
|
+
const uid = Number(fields[2]);
|
|
19428
|
+
if (fields[0] && Number.isInteger(uid)) out.set(uid, fields[0]);
|
|
19429
|
+
}
|
|
19430
|
+
return out;
|
|
19431
|
+
}
|
|
19432
|
+
function pathWithin(path, root) {
|
|
19433
|
+
return path === root || path.startsWith(`${root.replace(/\/$/, "")}/`);
|
|
19434
|
+
}
|
|
19435
|
+
function executableInWorldWritableDirectory(executable) {
|
|
19436
|
+
try {
|
|
19437
|
+
return ((0, import_node_fs28.statSync)((0, import_node_path22.dirname)(executable)).mode & 2) !== 0;
|
|
19438
|
+
} catch {
|
|
19439
|
+
return false;
|
|
19440
|
+
}
|
|
19441
|
+
}
|
|
19442
|
+
function clean(value) {
|
|
19443
|
+
return value.replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 400);
|
|
19444
|
+
}
|
|
19445
|
+
var EdrWatch = class {
|
|
19446
|
+
constructor(opts) {
|
|
19447
|
+
this.opts = opts;
|
|
19448
|
+
this.usersById = accountNames2();
|
|
19449
|
+
const wanted = new Set(opts.settings.webServiceUsers.map((name) => name.toLowerCase()));
|
|
19450
|
+
this.webIds = new Set([...this.usersById].filter(([, name]) => wanted.has(name.toLowerCase())).map(([uid]) => uid));
|
|
19451
|
+
this.loadNetworkBaseline();
|
|
19452
|
+
}
|
|
19453
|
+
opts;
|
|
19454
|
+
tail = null;
|
|
19455
|
+
timer = null;
|
|
19456
|
+
cpuTimer = null;
|
|
19457
|
+
usersById;
|
|
19458
|
+
webIds;
|
|
19459
|
+
seen = /* @__PURE__ */ new Set();
|
|
19460
|
+
listenersSeen = /* @__PURE__ */ new Set();
|
|
19461
|
+
outboundExecutables = /* @__PURE__ */ new Set();
|
|
19462
|
+
cpuSamples = /* @__PURE__ */ new Map();
|
|
19463
|
+
networkStartedAt = Date.now();
|
|
19464
|
+
ticksPerSecond = this.readTicksPerSecond();
|
|
19465
|
+
baselineWriteFailed = false;
|
|
19466
|
+
start() {
|
|
19467
|
+
if (!this.opts.settings.enabled) {
|
|
19468
|
+
this.opts.log("[edr] disabled; set [edr] enabled = true after installing the generated audit rules");
|
|
19469
|
+
return;
|
|
19470
|
+
}
|
|
19471
|
+
if (!(0, import_node_fs28.existsSync)(this.opts.settings.auditLogPath)) {
|
|
19472
|
+
this.opts.log(`[edr] audit log not found at ${this.opts.settings.auditLogPath}; auditd detections are unavailable`);
|
|
19473
|
+
} else {
|
|
19474
|
+
try {
|
|
19475
|
+
(0, import_node_fs28.accessSync)(this.opts.settings.auditLogPath, import_node_fs28.constants.R_OK);
|
|
19476
|
+
this.tail = new LogTail(this.opts.settings.auditLogPath);
|
|
19477
|
+
this.timer = setInterval(() => this.poll(), this.opts.settings.pollMs);
|
|
19478
|
+
this.timer.unref?.();
|
|
19479
|
+
this.opts.log(`[edr] watching selected auditd events in ${this.opts.settings.auditLogPath}; command arguments and remote addresses are discarded`);
|
|
19480
|
+
} catch {
|
|
19481
|
+
this.opts.log(`[edr] cannot read ${this.opts.settings.auditLogPath}; run the daemon with permission to read the audit log`);
|
|
19482
|
+
}
|
|
19483
|
+
}
|
|
19484
|
+
if (this.opts.settings.watchUnknownTempCpu) {
|
|
19485
|
+
this.cpuTimer = setInterval(() => this.sampleTemporaryProcesses(), CPU_SAMPLE_MS);
|
|
19486
|
+
this.cpuTimer.unref?.();
|
|
19487
|
+
this.sampleTemporaryProcesses();
|
|
19488
|
+
this.opts.log(`[edr] watching temporary-path processes for sustained CPU use (${CPU_THRESHOLD_PERCENT}% for ${CPU_SUSTAIN_MS / 1e3}s)`);
|
|
19489
|
+
}
|
|
19490
|
+
}
|
|
19491
|
+
stop() {
|
|
19492
|
+
if (this.timer) clearInterval(this.timer);
|
|
19493
|
+
if (this.cpuTimer) clearInterval(this.cpuTimer);
|
|
19494
|
+
this.timer = null;
|
|
19495
|
+
this.cpuTimer = null;
|
|
19496
|
+
this.tail = null;
|
|
19497
|
+
this.seen.clear();
|
|
19498
|
+
this.listenersSeen.clear();
|
|
19499
|
+
this.cpuSamples.clear();
|
|
19500
|
+
}
|
|
19501
|
+
poll() {
|
|
19502
|
+
if (!this.tail) return 0;
|
|
19503
|
+
return this.tail.poll((line) => {
|
|
19504
|
+
const record = parseAuditRecord(line);
|
|
19505
|
+
if (!record) return;
|
|
19506
|
+
const dedupeKey2 = `${record.timestamp.getTime()}:${record.serial}:${record.key}`;
|
|
19507
|
+
if (this.seen.has(dedupeKey2)) return;
|
|
19508
|
+
this.seen.add(dedupeKey2);
|
|
19509
|
+
if (this.seen.size > MAX_SEEN_EVENTS) this.seen.delete(this.seen.values().next().value);
|
|
19510
|
+
const event = this.classify(record);
|
|
19511
|
+
if (!event) return;
|
|
19512
|
+
this.publish(event);
|
|
19513
|
+
});
|
|
19514
|
+
}
|
|
19515
|
+
publish(event) {
|
|
19516
|
+
try {
|
|
19517
|
+
insertEvent(event);
|
|
19518
|
+
} catch {
|
|
19519
|
+
}
|
|
19520
|
+
this.opts.bus.publish(event);
|
|
19521
|
+
}
|
|
19522
|
+
classify(execution) {
|
|
19523
|
+
const name = (0, import_node_path22.basename)(execution.executable).toLowerCase();
|
|
19524
|
+
const account = this.usersById.get(execution.euid) ?? String(execution.euid);
|
|
19525
|
+
let severity;
|
|
19526
|
+
let ruleId;
|
|
19527
|
+
let message;
|
|
19528
|
+
if (execution.key === CONNECT_KEY) {
|
|
19529
|
+
const wasKnown = this.outboundExecutables.has(execution.executable);
|
|
19530
|
+
this.rememberOutboundExecutable(execution.executable);
|
|
19531
|
+
if (SHELLS.has(name) || SHELLS.has(execution.comm.toLowerCase())) {
|
|
19532
|
+
severity = "high";
|
|
19533
|
+
ruleId = "edr-shell-network-connect";
|
|
19534
|
+
message = `Possible reverse-shell behavior: shell ${execution.executable} opened an outbound connection`;
|
|
19535
|
+
} else if (!wasKnown && Date.now() - this.networkStartedAt >= this.opts.settings.networkBaselineMs) {
|
|
19536
|
+
severity = "medium";
|
|
19537
|
+
ruleId = "edr-new-outbound-executable";
|
|
19538
|
+
message = `Previously unseen executable opened an outbound connection: ${execution.executable}`;
|
|
19539
|
+
} else {
|
|
19540
|
+
return null;
|
|
19541
|
+
}
|
|
19542
|
+
} else if (execution.key === LISTEN_KEY) {
|
|
19543
|
+
const listenerKey = `${execution.pid ?? execution.serial}:${execution.executable}`;
|
|
19544
|
+
if (this.listenersSeen.has(listenerKey)) return null;
|
|
19545
|
+
this.listenersSeen.add(listenerKey);
|
|
19546
|
+
if (this.listenersSeen.size > MAX_SEEN_EVENTS) this.listenersSeen.delete(this.listenersSeen.values().next().value);
|
|
19547
|
+
severity = "medium";
|
|
19548
|
+
ruleId = "edr-process-listener";
|
|
19549
|
+
message = `Process began listening for inbound connections: ${execution.executable}`;
|
|
19550
|
+
} else if (execution.key === WEB_KEY && this.webIds.has(execution.euid) && (SHELLS.has(name) || DOWNLOADERS.has(name))) {
|
|
19551
|
+
severity = "high";
|
|
19552
|
+
ruleId = "edr-web-service-tool";
|
|
19553
|
+
message = `Web service account ${account} executed ${name}: ${execution.executable}`;
|
|
19554
|
+
} else if (execution.key === TEMP_KEY && (this.opts.settings.tempExecPaths.some((path) => pathWithin(execution.executable, path)) || executableInWorldWritableDirectory(execution.executable))) {
|
|
19555
|
+
severity = "high";
|
|
19556
|
+
ruleId = "edr-writable-path-execution";
|
|
19557
|
+
message = `Executable launched from a temporary or world-writable directory: ${execution.executable}`;
|
|
19558
|
+
} else if (execution.key === MINER_KEY && MINERS.has(name)) {
|
|
19559
|
+
severity = "critical";
|
|
19560
|
+
ruleId = "edr-known-miner-execution";
|
|
19561
|
+
message = `Known cryptocurrency miner executed: ${execution.executable}`;
|
|
19562
|
+
} else {
|
|
19563
|
+
return null;
|
|
19564
|
+
}
|
|
19565
|
+
return {
|
|
19566
|
+
timestamp: execution.timestamp,
|
|
19567
|
+
module: "edr",
|
|
19568
|
+
category: "system",
|
|
19569
|
+
severity,
|
|
19570
|
+
message: clean(message),
|
|
19571
|
+
details: {
|
|
19572
|
+
rule_id: ruleId,
|
|
19573
|
+
executable: clean(execution.executable),
|
|
19574
|
+
account,
|
|
19575
|
+
euid: execution.euid,
|
|
19576
|
+
...execution.pid ? { pid: execution.pid } : {},
|
|
19577
|
+
...execution.ppid ? { ppid: execution.ppid } : {},
|
|
19578
|
+
audit_serial: execution.serial
|
|
19579
|
+
}
|
|
19580
|
+
};
|
|
19581
|
+
}
|
|
19582
|
+
loadNetworkBaseline() {
|
|
19583
|
+
const path = this.opts.networkBaselinePath;
|
|
19584
|
+
if (!path) return;
|
|
19585
|
+
try {
|
|
19586
|
+
const parsed = JSON.parse((0, import_node_fs28.readFileSync)(path, "utf8"));
|
|
19587
|
+
if (Array.isArray(parsed)) {
|
|
19588
|
+
for (const value of parsed.slice(0, 1e4)) {
|
|
19589
|
+
if (typeof value === "string" && value.startsWith("/")) this.outboundExecutables.add(value);
|
|
19590
|
+
}
|
|
19591
|
+
}
|
|
19592
|
+
} catch {
|
|
19593
|
+
}
|
|
19594
|
+
}
|
|
19595
|
+
rememberOutboundExecutable(executable) {
|
|
19596
|
+
if (this.outboundExecutables.has(executable)) return;
|
|
19597
|
+
this.outboundExecutables.add(executable);
|
|
19598
|
+
if (this.outboundExecutables.size > 1e4) this.outboundExecutables.delete(this.outboundExecutables.values().next().value);
|
|
19599
|
+
const path = this.opts.networkBaselinePath;
|
|
19600
|
+
if (!path) return;
|
|
19601
|
+
try {
|
|
19602
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
19603
|
+
(0, import_node_fs28.writeFileSync)(temp, `${JSON.stringify([...this.outboundExecutables])}
|
|
19604
|
+
`, { mode: 384 });
|
|
19605
|
+
(0, import_node_fs28.renameSync)(temp, path);
|
|
19606
|
+
this.baselineWriteFailed = false;
|
|
19607
|
+
} catch (error) {
|
|
19608
|
+
if (!this.baselineWriteFailed) this.opts.log(`[edr] could not persist outbound executable baseline: ${error.message.split("\n")[0]}`);
|
|
19609
|
+
this.baselineWriteFailed = true;
|
|
19610
|
+
}
|
|
19611
|
+
}
|
|
19612
|
+
readTicksPerSecond() {
|
|
19613
|
+
try {
|
|
19614
|
+
const value = Number((0, import_node_child_process9.execFileSync)("getconf", ["CLK_TCK"], { encoding: "utf8", timeout: 2e3, stdio: ["ignore", "pipe", "ignore"] }).trim());
|
|
19615
|
+
if (Number.isFinite(value) && value > 0) return value;
|
|
19616
|
+
} catch {
|
|
19617
|
+
}
|
|
19618
|
+
return 100;
|
|
19619
|
+
}
|
|
19620
|
+
sampleTemporaryProcesses() {
|
|
19621
|
+
if (!this.opts.settings.enabled || !this.opts.settings.watchUnknownTempCpu) return;
|
|
19622
|
+
const now = Date.now();
|
|
19623
|
+
const current = /* @__PURE__ */ new Map();
|
|
19624
|
+
let pids;
|
|
19625
|
+
try {
|
|
19626
|
+
pids = (0, import_node_fs28.readdirSync)("/proc");
|
|
19627
|
+
} catch {
|
|
19628
|
+
return;
|
|
19629
|
+
}
|
|
19630
|
+
for (const pid of pids) {
|
|
19631
|
+
if (!/^\d+$/.test(pid)) continue;
|
|
19632
|
+
const proc = `/proc/${pid}`;
|
|
19633
|
+
try {
|
|
19634
|
+
const raw = (0, import_node_fs28.readFileSync)(`${proc}/stat`, "utf8");
|
|
19635
|
+
const end = raw.lastIndexOf(")");
|
|
19636
|
+
if (end < 0) continue;
|
|
19637
|
+
const fields = raw.slice(end + 1).trim().split(/\s+/);
|
|
19638
|
+
const userTicks = Number(fields[11]);
|
|
19639
|
+
const systemTicks = Number(fields[12]);
|
|
19640
|
+
const startTicks = fields[19];
|
|
19641
|
+
if (!Number.isFinite(userTicks) || !Number.isFinite(systemTicks) || !startTicks) continue;
|
|
19642
|
+
let executable = (0, import_node_fs28.readlinkSync)(`${proc}/exe`);
|
|
19643
|
+
executable = executable.replace(/ \(deleted\)$/, "");
|
|
19644
|
+
if (!this.opts.settings.tempExecPaths.some((path) => pathWithin(executable, path))) continue;
|
|
19645
|
+
const name = (0, import_node_path22.basename)(executable).toLowerCase();
|
|
19646
|
+
if (MINERS.has(name)) continue;
|
|
19647
|
+
const key = `${pid}:${startTicks}`;
|
|
19648
|
+
const ticks = userTicks + systemTicks;
|
|
19649
|
+
const previous = this.cpuSamples.get(key);
|
|
19650
|
+
if (!previous) {
|
|
19651
|
+
current.set(key, { ticks, firstAt: now, accumulatedTicks: 0, alerted: false });
|
|
19652
|
+
continue;
|
|
19653
|
+
}
|
|
19654
|
+
const delta = Math.max(0, ticks - previous.ticks);
|
|
19655
|
+
const accumulatedTicks = previous.accumulatedTicks + delta;
|
|
19656
|
+
const elapsedMs = Math.max(1, now - previous.firstAt);
|
|
19657
|
+
const cpuPercent = accumulatedTicks * 1e5 / (this.ticksPerSecond * elapsedMs);
|
|
19658
|
+
const sample = { ticks, firstAt: previous.firstAt, accumulatedTicks, alerted: previous.alerted };
|
|
19659
|
+
current.set(key, sample);
|
|
19660
|
+
if (!sample.alerted && elapsedMs >= CPU_SUSTAIN_MS && cpuPercent >= CPU_THRESHOLD_PERCENT) {
|
|
19661
|
+
sample.alerted = true;
|
|
19662
|
+
const event = {
|
|
19663
|
+
timestamp: new Date(now),
|
|
19664
|
+
module: "edr",
|
|
19665
|
+
category: "system",
|
|
19666
|
+
severity: "high",
|
|
19667
|
+
message: `Unknown executable in a temporary directory sustained ${cpuPercent.toFixed(0)}% CPU: ${clean(executable)}`,
|
|
19668
|
+
details: { rule_id: "edr-temp-high-cpu", executable: clean(executable), pid: Number(pid), cpu_percent: Number(cpuPercent.toFixed(1)), sustained_seconds: Math.floor(elapsedMs / 1e3) }
|
|
19669
|
+
};
|
|
19670
|
+
this.publish(event);
|
|
19671
|
+
}
|
|
19672
|
+
} catch {
|
|
19673
|
+
}
|
|
19674
|
+
}
|
|
19675
|
+
this.cpuSamples.clear();
|
|
19676
|
+
for (const [key, sample] of current) this.cpuSamples.set(key, sample);
|
|
19677
|
+
}
|
|
19678
|
+
};
|
|
19679
|
+
|
|
19680
|
+
// src/daemon/workers/ssh-intrusion.ts
|
|
19681
|
+
var import_node_fs29 = require("fs");
|
|
19682
|
+
var import_node_path23 = require("path");
|
|
19683
|
+
var import_node_child_process10 = require("child_process");
|
|
18843
19684
|
|
|
18844
19685
|
// src/core/asn.ts
|
|
18845
19686
|
var import_node_dns = require("dns");
|
|
@@ -19032,35 +19873,35 @@ function parseKeyLoginsByFingerprint(text) {
|
|
|
19032
19873
|
}
|
|
19033
19874
|
function readJson2(path) {
|
|
19034
19875
|
try {
|
|
19035
|
-
return JSON.parse((0,
|
|
19876
|
+
return JSON.parse((0, import_node_fs29.readFileSync)(path, "utf-8"));
|
|
19036
19877
|
} catch {
|
|
19037
19878
|
return null;
|
|
19038
19879
|
}
|
|
19039
19880
|
}
|
|
19040
19881
|
function writeJson2(path, value) {
|
|
19041
|
-
(0,
|
|
19042
|
-
(0,
|
|
19043
|
-
(0,
|
|
19882
|
+
(0, import_node_fs29.mkdirSync)((0, import_node_path23.dirname)(path), { recursive: true });
|
|
19883
|
+
(0, import_node_fs29.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
|
|
19884
|
+
(0, import_node_fs29.renameSync)(`${path}.tmp`, path);
|
|
19044
19885
|
}
|
|
19045
19886
|
var fsIO2 = {
|
|
19046
19887
|
readFile: (p) => {
|
|
19047
19888
|
try {
|
|
19048
|
-
return (0,
|
|
19889
|
+
return (0, import_node_fs29.readFileSync)(p, "utf-8");
|
|
19049
19890
|
} catch {
|
|
19050
19891
|
return null;
|
|
19051
19892
|
}
|
|
19052
19893
|
},
|
|
19053
19894
|
readDir: (p) => {
|
|
19054
19895
|
try {
|
|
19055
|
-
return (0,
|
|
19896
|
+
return (0, import_node_fs29.readdirSync)(p);
|
|
19056
19897
|
} catch {
|
|
19057
19898
|
return null;
|
|
19058
19899
|
}
|
|
19059
19900
|
},
|
|
19060
|
-
exists: (p) => (0,
|
|
19901
|
+
exists: (p) => (0, import_node_fs29.existsSync)(p)
|
|
19061
19902
|
};
|
|
19062
19903
|
function defaultRun4(cmd, args) {
|
|
19063
|
-
const res = (0,
|
|
19904
|
+
const res = (0, import_node_child_process10.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
|
|
19064
19905
|
return res.status === 0 ? res.stdout : null;
|
|
19065
19906
|
}
|
|
19066
19907
|
var SshIntrusionWatch = class {
|
|
@@ -19258,7 +20099,7 @@ var SshIntrusionWatch = class {
|
|
|
19258
20099
|
};
|
|
19259
20100
|
|
|
19260
20101
|
// src/daemon/workers/lightning-watch.ts
|
|
19261
|
-
var
|
|
20102
|
+
var import_node_fs30 = require("fs");
|
|
19262
20103
|
var DEFAULT_CLN_LOGS = [
|
|
19263
20104
|
"/home/lightning/.lightning/cln.log",
|
|
19264
20105
|
"/root/.lightning/cln.log",
|
|
@@ -19314,9 +20155,9 @@ var LightningWatch = class {
|
|
|
19314
20155
|
if (this.opts.enabled === false) return [];
|
|
19315
20156
|
const found = [];
|
|
19316
20157
|
for (const path of this.opts.paths?.length ? this.opts.paths : DEFAULT_CLN_LOGS) {
|
|
19317
|
-
if (!(0,
|
|
20158
|
+
if (!(0, import_node_fs30.existsSync)(path)) continue;
|
|
19318
20159
|
try {
|
|
19319
|
-
(0,
|
|
20160
|
+
(0, import_node_fs30.accessSync)(path, import_node_fs30.constants.R_OK);
|
|
19320
20161
|
} catch {
|
|
19321
20162
|
continue;
|
|
19322
20163
|
}
|
|
@@ -19351,8 +20192,8 @@ var LightningWatch = class {
|
|
|
19351
20192
|
};
|
|
19352
20193
|
|
|
19353
20194
|
// src/core/tor-exits.ts
|
|
19354
|
-
var
|
|
19355
|
-
var
|
|
20195
|
+
var import_node_fs31 = require("fs");
|
|
20196
|
+
var import_node_path24 = require("path");
|
|
19356
20197
|
var import_node_net12 = require("net");
|
|
19357
20198
|
var TOR_BULK_EXIT_LIST_URL = "https://check.torproject.org/torbulkexitlist";
|
|
19358
20199
|
function parseTorExitList(text) {
|
|
@@ -19420,10 +20261,10 @@ var TorExitList = class _TorExitList {
|
|
|
19420
20261
|
}
|
|
19421
20262
|
loadCache() {
|
|
19422
20263
|
try {
|
|
19423
|
-
if (!(0,
|
|
19424
|
-
const parsed = parseTorExitList((0,
|
|
20264
|
+
if (!(0, import_node_fs31.existsSync)(this.opts.cachePath)) return false;
|
|
20265
|
+
const parsed = parseTorExitList((0, import_node_fs31.readFileSync)(this.opts.cachePath, "utf-8"));
|
|
19425
20266
|
if (parsed.size === 0) return false;
|
|
19426
|
-
this.load(parsed, (0,
|
|
20267
|
+
this.load(parsed, (0, import_node_fs31.statSync)(this.opts.cachePath).mtimeMs);
|
|
19427
20268
|
this.log(`[tor] loaded ${parsed.size} Tor exit addresses from cache (${new Date(this.updatedAt).toISOString()})`);
|
|
19428
20269
|
return true;
|
|
19429
20270
|
} catch (err) {
|
|
@@ -19455,9 +20296,9 @@ var TorExitList = class _TorExitList {
|
|
|
19455
20296
|
const before = this.exits.size;
|
|
19456
20297
|
this.load(parsed);
|
|
19457
20298
|
try {
|
|
19458
|
-
(0,
|
|
19459
|
-
(0,
|
|
19460
|
-
(0,
|
|
20299
|
+
(0, import_node_fs31.mkdirSync)((0, import_node_path24.dirname)(this.opts.cachePath), { recursive: true });
|
|
20300
|
+
(0, import_node_fs31.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
|
|
20301
|
+
(0, import_node_fs31.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
|
|
19461
20302
|
} catch (err) {
|
|
19462
20303
|
this.log(`[tor] could not save the exit list cache: ${err.message}`);
|
|
19463
20304
|
}
|
|
@@ -19675,8 +20516,8 @@ var RuleEngine = class {
|
|
|
19675
20516
|
};
|
|
19676
20517
|
|
|
19677
20518
|
// src/daemon/rules/loader.ts
|
|
19678
|
-
var
|
|
19679
|
-
var
|
|
20519
|
+
var import_node_fs32 = require("fs");
|
|
20520
|
+
var import_node_path25 = require("path");
|
|
19680
20521
|
|
|
19681
20522
|
// src/daemon/rules/default-rules.ts
|
|
19682
20523
|
var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
|
|
@@ -20267,11 +21108,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
|
|
|
20267
21108
|
function loadAllRules(customDir) {
|
|
20268
21109
|
const rules = [...DEFAULT_RULES];
|
|
20269
21110
|
const dir = customDir || RULES_DIR;
|
|
20270
|
-
if ((0,
|
|
20271
|
-
const files = (0,
|
|
21111
|
+
if ((0, import_node_fs32.existsSync)(dir)) {
|
|
21112
|
+
const files = (0, import_node_fs32.readdirSync)(dir).filter((f) => f.endsWith(".json"));
|
|
20272
21113
|
for (const file of files) {
|
|
20273
21114
|
try {
|
|
20274
|
-
const raw = (0,
|
|
21115
|
+
const raw = (0, import_node_fs32.readFileSync)((0, import_node_path25.join)(dir, file), "utf-8");
|
|
20275
21116
|
const parsed = JSON.parse(raw);
|
|
20276
21117
|
const customRules = Array.isArray(parsed) ? parsed : [parsed];
|
|
20277
21118
|
for (const rule of customRules) {
|
|
@@ -20302,9 +21143,9 @@ function loadAllRules(customDir) {
|
|
|
20302
21143
|
}
|
|
20303
21144
|
|
|
20304
21145
|
// src/daemon/firewall/adapters.ts
|
|
20305
|
-
var
|
|
20306
|
-
var
|
|
20307
|
-
var
|
|
21146
|
+
var import_node_child_process11 = require("child_process");
|
|
21147
|
+
var import_node_fs33 = require("fs");
|
|
21148
|
+
var import_node_path26 = require("path");
|
|
20308
21149
|
var import_node_net13 = require("net");
|
|
20309
21150
|
function assertValidFirewallIp(ip) {
|
|
20310
21151
|
if ((0, import_node_net13.isIP)(ip) !== 4) {
|
|
@@ -20317,9 +21158,9 @@ function assertBannableIp(ip) {
|
|
|
20317
21158
|
}
|
|
20318
21159
|
}
|
|
20319
21160
|
function writeIfAbsent(path, contents) {
|
|
20320
|
-
(0,
|
|
21161
|
+
(0, import_node_fs33.mkdirSync)((0, import_node_path26.dirname)(path), { recursive: true });
|
|
20321
21162
|
try {
|
|
20322
|
-
(0,
|
|
21163
|
+
(0, import_node_fs33.writeFileSync)(path, contents, { flag: "wx" });
|
|
20323
21164
|
} catch (err) {
|
|
20324
21165
|
if (err.code !== "EEXIST") throw err;
|
|
20325
21166
|
}
|
|
@@ -20338,11 +21179,11 @@ var Fail2banAdapter = class {
|
|
|
20338
21179
|
enforces = true;
|
|
20339
21180
|
jailReady = false;
|
|
20340
21181
|
isAvailable() {
|
|
20341
|
-
const result = (0,
|
|
21182
|
+
const result = (0, import_node_child_process11.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
|
|
20342
21183
|
return result.status === 0;
|
|
20343
21184
|
}
|
|
20344
21185
|
client(args) {
|
|
20345
|
-
return (0,
|
|
21186
|
+
return (0, import_node_child_process11.execFileSync)("fail2ban-client", args, {
|
|
20346
21187
|
encoding: "utf-8",
|
|
20347
21188
|
stdio: ["ignore", "pipe", "pipe"]
|
|
20348
21189
|
});
|
|
@@ -20438,35 +21279,35 @@ var NftablesAdapter = class {
|
|
|
20438
21279
|
table = "threatcrush";
|
|
20439
21280
|
set = "blocklist";
|
|
20440
21281
|
isAvailable() {
|
|
20441
|
-
const result = (0,
|
|
21282
|
+
const result = (0, import_node_child_process11.spawnSync)("nft", ["--version"], { stdio: "pipe" });
|
|
20442
21283
|
return result.status === 0;
|
|
20443
21284
|
}
|
|
20444
21285
|
ensureSetup() {
|
|
20445
21286
|
try {
|
|
20446
|
-
(0,
|
|
21287
|
+
(0, import_node_child_process11.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
|
|
20447
21288
|
} catch {
|
|
20448
|
-
(0,
|
|
20449
|
-
(0,
|
|
20450
|
-
(0,
|
|
20451
|
-
(0,
|
|
21289
|
+
(0, import_node_child_process11.execSync)(`nft add table inet ${this.table}`);
|
|
21290
|
+
(0, import_node_child_process11.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
|
|
21291
|
+
(0, import_node_child_process11.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
|
|
21292
|
+
(0, import_node_child_process11.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
|
|
20452
21293
|
}
|
|
20453
21294
|
}
|
|
20454
21295
|
async block(ip) {
|
|
20455
21296
|
assertValidFirewallIp(ip);
|
|
20456
21297
|
this.ensureSetup();
|
|
20457
|
-
(0,
|
|
21298
|
+
(0, import_node_child_process11.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
|
|
20458
21299
|
}
|
|
20459
21300
|
async unblock(ip) {
|
|
20460
21301
|
assertValidFirewallIp(ip);
|
|
20461
21302
|
try {
|
|
20462
|
-
(0,
|
|
21303
|
+
(0, import_node_child_process11.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
|
|
20463
21304
|
} catch {
|
|
20464
21305
|
}
|
|
20465
21306
|
}
|
|
20466
21307
|
async isBlocked(ip) {
|
|
20467
21308
|
assertValidFirewallIp(ip);
|
|
20468
21309
|
try {
|
|
20469
|
-
const output = (0,
|
|
21310
|
+
const output = (0, import_node_child_process11.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
|
|
20470
21311
|
return output.includes(ip);
|
|
20471
21312
|
} catch {
|
|
20472
21313
|
return false;
|
|
@@ -20474,7 +21315,7 @@ var NftablesAdapter = class {
|
|
|
20474
21315
|
}
|
|
20475
21316
|
async listBlocked() {
|
|
20476
21317
|
try {
|
|
20477
|
-
const output = (0,
|
|
21318
|
+
const output = (0, import_node_child_process11.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
|
|
20478
21319
|
const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
|
|
20479
21320
|
if (!match) return [];
|
|
20480
21321
|
return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
|
|
@@ -20487,34 +21328,34 @@ var IptablesAdapter = class {
|
|
|
20487
21328
|
name = "iptables";
|
|
20488
21329
|
chain = "THREATCRUSH";
|
|
20489
21330
|
isAvailable() {
|
|
20490
|
-
const result = (0,
|
|
21331
|
+
const result = (0, import_node_child_process11.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
|
|
20491
21332
|
return result.status === 0;
|
|
20492
21333
|
}
|
|
20493
21334
|
ensureChain() {
|
|
20494
21335
|
try {
|
|
20495
|
-
(0,
|
|
21336
|
+
(0, import_node_child_process11.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
|
|
20496
21337
|
} catch {
|
|
20497
|
-
(0,
|
|
20498
|
-
(0,
|
|
21338
|
+
(0, import_node_child_process11.execSync)(`iptables -N ${this.chain}`);
|
|
21339
|
+
(0, import_node_child_process11.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
|
|
20499
21340
|
}
|
|
20500
21341
|
}
|
|
20501
21342
|
async block(ip) {
|
|
20502
21343
|
assertValidFirewallIp(ip);
|
|
20503
21344
|
this.ensureChain();
|
|
20504
21345
|
if (await this.isBlocked(ip)) return;
|
|
20505
|
-
(0,
|
|
21346
|
+
(0, import_node_child_process11.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
|
|
20506
21347
|
}
|
|
20507
21348
|
async unblock(ip) {
|
|
20508
21349
|
assertValidFirewallIp(ip);
|
|
20509
21350
|
try {
|
|
20510
|
-
(0,
|
|
21351
|
+
(0, import_node_child_process11.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
|
|
20511
21352
|
} catch {
|
|
20512
21353
|
}
|
|
20513
21354
|
}
|
|
20514
21355
|
async isBlocked(ip) {
|
|
20515
21356
|
assertValidFirewallIp(ip);
|
|
20516
21357
|
try {
|
|
20517
|
-
const output = (0,
|
|
21358
|
+
const output = (0, import_node_child_process11.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
|
|
20518
21359
|
return output.includes(ip);
|
|
20519
21360
|
} catch {
|
|
20520
21361
|
return false;
|
|
@@ -20522,7 +21363,7 @@ var IptablesAdapter = class {
|
|
|
20522
21363
|
}
|
|
20523
21364
|
async listBlocked() {
|
|
20524
21365
|
try {
|
|
20525
|
-
const output = (0,
|
|
21366
|
+
const output = (0, import_node_child_process11.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
|
|
20526
21367
|
const ips = [];
|
|
20527
21368
|
for (const line of output.split("\n")) {
|
|
20528
21369
|
const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
|
|
@@ -20578,8 +21419,8 @@ function detectFirewallAdapter(backend = "auto") {
|
|
|
20578
21419
|
}
|
|
20579
21420
|
|
|
20580
21421
|
// src/daemon/firewall/remediation.ts
|
|
20581
|
-
var
|
|
20582
|
-
var
|
|
21422
|
+
var import_node_fs34 = require("fs");
|
|
21423
|
+
var import_node_child_process12 = require("child_process");
|
|
20583
21424
|
var import_node_net14 = require("net");
|
|
20584
21425
|
|
|
20585
21426
|
// src/daemon/firewall/crawlers.ts
|
|
@@ -20648,19 +21489,19 @@ var defaultDiscovery = {
|
|
|
20648
21489
|
const snapshot = takeSnapshot({
|
|
20649
21490
|
readFile: (p) => {
|
|
20650
21491
|
try {
|
|
20651
|
-
return (0,
|
|
21492
|
+
return (0, import_node_fs34.readFileSync)(p, "utf-8");
|
|
20652
21493
|
} catch {
|
|
20653
21494
|
return null;
|
|
20654
21495
|
}
|
|
20655
21496
|
},
|
|
20656
21497
|
readDir: (p) => {
|
|
20657
21498
|
try {
|
|
20658
|
-
return (0,
|
|
21499
|
+
return (0, import_node_fs34.readdirSync)(p);
|
|
20659
21500
|
} catch {
|
|
20660
21501
|
return null;
|
|
20661
21502
|
}
|
|
20662
21503
|
},
|
|
20663
|
-
exists: (p) => (0,
|
|
21504
|
+
exists: (p) => (0, import_node_fs34.existsSync)(p)
|
|
20664
21505
|
});
|
|
20665
21506
|
const out = /* @__PURE__ */ new Set();
|
|
20666
21507
|
for (const keys of Object.values(snapshot.keys)) {
|
|
@@ -20669,7 +21510,7 @@ var defaultDiscovery = {
|
|
|
20669
21510
|
return out;
|
|
20670
21511
|
},
|
|
20671
21512
|
keyLoginJournal: (sinceSeconds) => new Promise((resolve4) => {
|
|
20672
|
-
(0,
|
|
21513
|
+
(0, import_node_child_process12.execFile)(
|
|
20673
21514
|
"journalctl",
|
|
20674
21515
|
["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
|
|
20675
21516
|
{ maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
|
|
@@ -21173,7 +22014,7 @@ var RemediationManager = class {
|
|
|
21173
22014
|
}
|
|
21174
22015
|
logLine(line) {
|
|
21175
22016
|
try {
|
|
21176
|
-
(0,
|
|
22017
|
+
(0, import_node_fs34.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
|
|
21177
22018
|
`);
|
|
21178
22019
|
} catch {
|
|
21179
22020
|
}
|
|
@@ -21213,13 +22054,13 @@ function remediationSettings(section) {
|
|
|
21213
22054
|
}
|
|
21214
22055
|
|
|
21215
22056
|
// src/daemon/watchdog-service.ts
|
|
21216
|
-
var
|
|
21217
|
-
var
|
|
22057
|
+
var import_node_fs36 = require("fs");
|
|
22058
|
+
var import_node_path28 = require("path");
|
|
21218
22059
|
|
|
21219
22060
|
// src/core/watchdog.ts
|
|
21220
|
-
var
|
|
21221
|
-
var
|
|
21222
|
-
var
|
|
22061
|
+
var import_node_fs35 = require("fs");
|
|
22062
|
+
var import_node_crypto9 = require("crypto");
|
|
22063
|
+
var import_node_path27 = require("path");
|
|
21223
22064
|
var WATCHDOG_DIRNAME = "watchdog";
|
|
21224
22065
|
var LOG_FILE2 = "attacks.jsonl";
|
|
21225
22066
|
var ROTATED_FILE = "attacks.1.jsonl";
|
|
@@ -21258,8 +22099,8 @@ function signatureOf(r) {
|
|
|
21258
22099
|
const shape = r.message.replace(/\b\d{1,3}(?:\.\d{1,3}){3}(?:\/\d+)?\b/g, "<ip>").replace(/\b[0-9a-f]*:[0-9a-f:]+\b/gi, "<ip>").replace(/\d+/g, "#");
|
|
21259
22100
|
return ["msg", r.module, shape].join("|");
|
|
21260
22101
|
}
|
|
21261
|
-
function findingId(
|
|
21262
|
-
return (0,
|
|
22102
|
+
function findingId(signature2) {
|
|
22103
|
+
return (0, import_node_crypto9.createHash)("sha1").update(signature2).digest("hex").slice(0, 10);
|
|
21263
22104
|
}
|
|
21264
22105
|
function toRecord(event) {
|
|
21265
22106
|
const d = event.details ?? {};
|
|
@@ -21308,12 +22149,12 @@ var WatchdogLog = class {
|
|
|
21308
22149
|
stats = { logged: 0, answered: 0, errored: 0 };
|
|
21309
22150
|
constructor(dir, options = {}) {
|
|
21310
22151
|
this.dir = dir;
|
|
21311
|
-
this.file = (0,
|
|
22152
|
+
this.file = (0, import_node_path27.join)(dir, LOG_FILE2);
|
|
21312
22153
|
this.shareGid = options.shareGid;
|
|
21313
|
-
(0,
|
|
22154
|
+
(0, import_node_fs35.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
|
|
21314
22155
|
if (this.shareGid !== void 0) {
|
|
21315
|
-
(0,
|
|
21316
|
-
(0,
|
|
22156
|
+
(0, import_node_fs35.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
|
|
22157
|
+
(0, import_node_fs35.chmodSync)(dir, 1528);
|
|
21317
22158
|
}
|
|
21318
22159
|
for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
|
|
21319
22160
|
}
|
|
@@ -21342,16 +22183,16 @@ var WatchdogLog = class {
|
|
|
21342
22183
|
const chunk = this.buffer.join("\n") + "\n";
|
|
21343
22184
|
this.buffer = [];
|
|
21344
22185
|
try {
|
|
21345
|
-
if ((0,
|
|
21346
|
-
(0,
|
|
22186
|
+
if ((0, import_node_fs35.statSync)(this.file).size > ROTATE_BYTES) {
|
|
22187
|
+
(0, import_node_fs35.renameSync)(this.file, (0, import_node_path27.join)(this.dir, ROTATED_FILE));
|
|
21347
22188
|
}
|
|
21348
22189
|
} catch {
|
|
21349
22190
|
}
|
|
21350
|
-
(0,
|
|
22191
|
+
(0, import_node_fs35.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
|
|
21351
22192
|
if (this.shareGid !== void 0) {
|
|
21352
22193
|
try {
|
|
21353
|
-
(0,
|
|
21354
|
-
(0,
|
|
22194
|
+
(0, import_node_fs35.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
|
|
22195
|
+
(0, import_node_fs35.chmodSync)(this.file, 432);
|
|
21355
22196
|
} catch {
|
|
21356
22197
|
}
|
|
21357
22198
|
}
|
|
@@ -21372,21 +22213,21 @@ function parseLines(text) {
|
|
|
21372
22213
|
function readTail(file, bytes) {
|
|
21373
22214
|
let fd;
|
|
21374
22215
|
try {
|
|
21375
|
-
fd = (0,
|
|
22216
|
+
fd = (0, import_node_fs35.openSync)(file, "r");
|
|
21376
22217
|
} catch (err) {
|
|
21377
22218
|
if (err.code === "ENOENT") return [];
|
|
21378
22219
|
throw err;
|
|
21379
22220
|
}
|
|
21380
22221
|
try {
|
|
21381
|
-
const size = (0,
|
|
22222
|
+
const size = (0, import_node_fs35.fstatSync)(fd).size;
|
|
21382
22223
|
const start = Math.max(0, size - bytes);
|
|
21383
22224
|
const buf = Buffer.alloc(size - start);
|
|
21384
|
-
(0,
|
|
22225
|
+
(0, import_node_fs35.readSync)(fd, buf, 0, buf.length, start);
|
|
21385
22226
|
let text = buf.toString("utf8");
|
|
21386
22227
|
if (start > 0) text = text.slice(text.indexOf("\n") + 1);
|
|
21387
22228
|
return parseLines(text);
|
|
21388
22229
|
} finally {
|
|
21389
|
-
(0,
|
|
22230
|
+
(0, import_node_fs35.closeSync)(fd);
|
|
21390
22231
|
}
|
|
21391
22232
|
}
|
|
21392
22233
|
|
|
@@ -21395,13 +22236,13 @@ function defaultShareGid() {
|
|
|
21395
22236
|
const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
|
|
21396
22237
|
if (!isRoot2) return void 0;
|
|
21397
22238
|
try {
|
|
21398
|
-
return (0,
|
|
22239
|
+
return (0, import_node_fs36.statSync)("/var/log/auth.log").gid;
|
|
21399
22240
|
} catch {
|
|
21400
22241
|
return void 0;
|
|
21401
22242
|
}
|
|
21402
22243
|
}
|
|
21403
22244
|
function startWatchdog(opts) {
|
|
21404
|
-
const dir = opts.config?.dir ?? (0,
|
|
22245
|
+
const dir = opts.config?.dir ?? (0, import_node_path28.join)(opts.stateDir, WATCHDOG_DIRNAME);
|
|
21405
22246
|
const base = { dir, logged: 0, answered: 0, errored: 0 };
|
|
21406
22247
|
if (opts.config?.enabled === false) {
|
|
21407
22248
|
opts.log("[watchdog] off ([watchdog] enabled = false)");
|
|
@@ -21492,7 +22333,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
|
|
|
21492
22333
|
}
|
|
21493
22334
|
|
|
21494
22335
|
// src/core/node-runtime.ts
|
|
21495
|
-
var
|
|
22336
|
+
var import_node_child_process13 = require("child_process");
|
|
21496
22337
|
var MIN_DAEMON_NODE_MAJOR = 22;
|
|
21497
22338
|
function nodeMajor(version) {
|
|
21498
22339
|
const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
|
|
@@ -21508,16 +22349,16 @@ function daemonNodeProblem(version) {
|
|
|
21508
22349
|
// src/daemon/index.ts
|
|
21509
22350
|
function readVersion2() {
|
|
21510
22351
|
try {
|
|
21511
|
-
const pkg = JSON.parse((0,
|
|
22352
|
+
const pkg = JSON.parse((0, import_node_fs37.readFileSync)((0, import_node_path29.join)(__dirname, "..", "package.json"), "utf-8"));
|
|
21512
22353
|
return pkg.version || "0.0.0";
|
|
21513
22354
|
} catch {
|
|
21514
22355
|
return "0.0.0";
|
|
21515
22356
|
}
|
|
21516
22357
|
}
|
|
21517
22358
|
async function runHardeningChecks() {
|
|
21518
|
-
const { stdout } = await (0, import_node_util.promisify)(
|
|
22359
|
+
const { stdout } = await (0, import_node_util.promisify)(import_node_child_process14.execFile)(
|
|
21519
22360
|
process.execPath,
|
|
21520
|
-
[(0,
|
|
22361
|
+
[(0, import_node_path29.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
|
|
21521
22362
|
{ timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
|
|
21522
22363
|
);
|
|
21523
22364
|
const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
|
|
@@ -21529,9 +22370,9 @@ async function runHardeningChecks() {
|
|
|
21529
22370
|
return patches ? [...findings, patches] : findings;
|
|
21530
22371
|
}
|
|
21531
22372
|
async function runPatchCheck() {
|
|
21532
|
-
const { stdout } = await (0, import_node_util.promisify)(
|
|
22373
|
+
const { stdout } = await (0, import_node_util.promisify)(import_node_child_process14.execFile)(
|
|
21533
22374
|
process.execPath,
|
|
21534
|
-
[(0,
|
|
22375
|
+
[(0, import_node_path29.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
|
|
21535
22376
|
{ timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
|
|
21536
22377
|
);
|
|
21537
22378
|
const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
|
|
@@ -21539,7 +22380,7 @@ async function runPatchCheck() {
|
|
|
21539
22380
|
}
|
|
21540
22381
|
function logLine(line) {
|
|
21541
22382
|
try {
|
|
21542
|
-
(0,
|
|
22383
|
+
(0, import_node_fs37.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
|
|
21543
22384
|
`);
|
|
21544
22385
|
} catch {
|
|
21545
22386
|
}
|
|
@@ -21564,9 +22405,9 @@ async function runDaemon() {
|
|
|
21564
22405
|
logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
|
|
21565
22406
|
const restartDaemon = () => {
|
|
21566
22407
|
if (PATHS.mode === "system") {
|
|
21567
|
-
(0,
|
|
22408
|
+
(0, import_node_child_process14.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
|
|
21568
22409
|
} else {
|
|
21569
|
-
(0,
|
|
22410
|
+
(0, import_node_child_process14.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
|
|
21570
22411
|
setTimeout(() => process.exit(0), 500).unref();
|
|
21571
22412
|
}
|
|
21572
22413
|
};
|
|
@@ -21581,7 +22422,7 @@ async function runDaemon() {
|
|
|
21581
22422
|
} catch (err) {
|
|
21582
22423
|
logLine(`[daemon] state db unavailable: ${err.message}`);
|
|
21583
22424
|
}
|
|
21584
|
-
const loaded = loadDaemonConfig(PATHS.configFile, (0,
|
|
22425
|
+
const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path29.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
|
|
21585
22426
|
const config = loaded.config;
|
|
21586
22427
|
if (loaded.error) {
|
|
21587
22428
|
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)"}`);
|
|
@@ -21649,7 +22490,7 @@ async function runDaemon() {
|
|
|
21649
22490
|
const threatFeeds = new ThreatFeeds({
|
|
21650
22491
|
settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
|
|
21651
22492
|
enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
|
|
21652
|
-
cachePath: (0,
|
|
22493
|
+
cachePath: (0, import_node_path29.join)(PATHS.stateDir, "threat-feeds.json"),
|
|
21653
22494
|
bus,
|
|
21654
22495
|
log: logLine
|
|
21655
22496
|
});
|
|
@@ -21657,9 +22498,9 @@ async function runDaemon() {
|
|
|
21657
22498
|
const privilegeWatch = new PrivilegeWatch({
|
|
21658
22499
|
settings: privilegeSettings(config.privileged),
|
|
21659
22500
|
bus,
|
|
21660
|
-
snapshotPath: (0,
|
|
21661
|
-
loginsPath: (0,
|
|
21662
|
-
cursorPath: (0,
|
|
22501
|
+
snapshotPath: (0, import_node_path29.join)(PATHS.stateDir, "privileges.json"),
|
|
22502
|
+
loginsPath: (0, import_node_path29.join)(PATHS.stateDir, "login-countries.json"),
|
|
22503
|
+
cursorPath: (0, import_node_path29.join)(PATHS.stateDir, "sudo-cursor.json"),
|
|
21663
22504
|
log: logLine
|
|
21664
22505
|
});
|
|
21665
22506
|
privilegeWatch.start();
|
|
@@ -21670,8 +22511,23 @@ async function runDaemon() {
|
|
|
21670
22511
|
log: logLine
|
|
21671
22512
|
});
|
|
21672
22513
|
commandHistory.start();
|
|
22514
|
+
const fileIntegrity = new FileIntegrityWatch({
|
|
22515
|
+
bus,
|
|
22516
|
+
settings: fileIntegritySettings(config.file_integrity),
|
|
22517
|
+
baselinePath: (0, import_node_path29.join)(PATHS.stateDir, "file-integrity-baseline.json"),
|
|
22518
|
+
observedPath: (0, import_node_path29.join)(PATHS.stateDir, "file-integrity-observed.json"),
|
|
22519
|
+
log: logLine
|
|
22520
|
+
});
|
|
22521
|
+
fileIntegrity.start();
|
|
22522
|
+
const edr = new EdrWatch({
|
|
22523
|
+
bus,
|
|
22524
|
+
settings: edrSettings(config.edr),
|
|
22525
|
+
networkBaselinePath: (0, import_node_path29.join)(PATHS.stateDir, "edr-outbound-executables.json"),
|
|
22526
|
+
log: logLine
|
|
22527
|
+
});
|
|
22528
|
+
edr.start();
|
|
21673
22529
|
const torExits = new TorExitList({
|
|
21674
|
-
cachePath: (0,
|
|
22530
|
+
cachePath: (0, import_node_path29.join)(PATHS.stateDir, "tor-exits.txt"),
|
|
21675
22531
|
url: config.remediation?.tor_exit_list_url,
|
|
21676
22532
|
log: logLine
|
|
21677
22533
|
});
|
|
@@ -21679,7 +22535,7 @@ async function runDaemon() {
|
|
|
21679
22535
|
bus,
|
|
21680
22536
|
manager: remediation,
|
|
21681
22537
|
tor: torExits,
|
|
21682
|
-
historyPath: (0,
|
|
22538
|
+
historyPath: (0, import_node_path29.join)(PATHS.stateDir, "key-logins.json"),
|
|
21683
22539
|
keyLoginWatch: config.privileged?.key_login_watch !== false,
|
|
21684
22540
|
log: logLine
|
|
21685
22541
|
});
|
|
@@ -21726,7 +22582,7 @@ async function runDaemon() {
|
|
|
21726
22582
|
version,
|
|
21727
22583
|
hostname: (0, import_node_os6.hostname)(),
|
|
21728
22584
|
minSeverity,
|
|
21729
|
-
spoolPath: (0,
|
|
22585
|
+
spoolPath: (0, import_node_path29.join)(PATHS.stateDir, "cloud-spool.jsonl"),
|
|
21730
22586
|
log: logLine,
|
|
21731
22587
|
ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
|
|
21732
22588
|
runHardening: runHardeningChecks
|
|
@@ -21759,8 +22615,8 @@ async function runDaemon() {
|
|
|
21759
22615
|
const autoUpdate = autoUpdateRef = new AutoUpdate({
|
|
21760
22616
|
version,
|
|
21761
22617
|
settings: updateSettings(config.update),
|
|
21762
|
-
pkgRoot: (0,
|
|
21763
|
-
statePath: (0,
|
|
22618
|
+
pkgRoot: (0, import_node_path29.join)(__dirname, ".."),
|
|
22619
|
+
statePath: (0, import_node_path29.join)(PATHS.stateDir, "auto-update.json"),
|
|
21764
22620
|
bus,
|
|
21765
22621
|
log: logLine,
|
|
21766
22622
|
restartDaemon
|
|
@@ -21819,6 +22675,14 @@ async function runDaemon() {
|
|
|
21819
22675
|
commandHistory.stop();
|
|
21820
22676
|
} catch {
|
|
21821
22677
|
}
|
|
22678
|
+
try {
|
|
22679
|
+
fileIntegrity.stop();
|
|
22680
|
+
} catch {
|
|
22681
|
+
}
|
|
22682
|
+
try {
|
|
22683
|
+
edr.stop();
|
|
22684
|
+
} catch {
|
|
22685
|
+
}
|
|
21822
22686
|
try {
|
|
21823
22687
|
sshIntrusion.stop();
|
|
21824
22688
|
} catch {
|