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