sekant-intercept-js 1.0.1 → 1.0.4
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 +4 -3
- package/dist/sekant-intercept.browser.mjs +15 -9
- package/dist/sekant-intercept.node.mjs +15 -9
- package/package.json +1 -1
- package/src/ahocorasickEngine.mjs +209 -104
- package/src/interceptScanner.mjs +487 -18
- package/src/yaraConditionParser.mjs +307 -142
- package/src/yaraConditionsMatch.mjs +72 -16
- package/src/yaraRuleCompiler.mjs +326 -9
- package/src/yaraStringMatch.mjs +419 -79
package/src/interceptScanner.mjs
CHANGED
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
*/
|
|
27
27
|
|
|
28
28
|
import { AhoCorasick } from "./ahocorasickEngine.mjs";
|
|
29
|
-
import { parseYaraRuleGroup } from "./yaraRuleCompiler.mjs";
|
|
29
|
+
import { parseYaraRuleGroup, parseInterceptFilterRuleGroup } from "./yaraRuleCompiler.mjs";
|
|
30
30
|
import { createScanFacts, evaluateCondition } from "./yaraConditionsMatch.mjs";
|
|
31
31
|
import { parseConditionToAST } from "./yaraConditionParser.mjs";
|
|
32
32
|
import { parsePEYara, createPEModule } from "./peModule.mjs";
|
|
@@ -39,6 +39,27 @@ import { createPerformanceTracker } from "./performanceInstrumentation.mjs";
|
|
|
39
39
|
import { MAX_MATCHES } from "./yaraStringMatch.mjs";
|
|
40
40
|
import { isValidModuleName } from "./interceptCustomModules.mjs";
|
|
41
41
|
|
|
42
|
+
/**
|
|
43
|
+
* Longest candidate buffer handed to filter rules. Longer matches keep the candidate and skip
|
|
44
|
+
* filtering, so a filter never decides on a truncated prefix.
|
|
45
|
+
*/
|
|
46
|
+
export const MAX_FILTER_RULE_BUFFER_SIZE = 4096;
|
|
47
|
+
|
|
48
|
+
const FILTER_MODULE_BUILTINS = new Set(["string", "time", "math", "hash"]);
|
|
49
|
+
|
|
50
|
+
function hasRejectFilters(strDef) {
|
|
51
|
+
return Boolean(strDef?.reject?.length || strDef?.rejectCapture?.length);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function hashBytes(bytes) {
|
|
55
|
+
let hash = 0x811c9dc5;
|
|
56
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
57
|
+
hash ^= bytes[i];
|
|
58
|
+
hash = Math.imul(hash, 0x01000193) >>> 0;
|
|
59
|
+
}
|
|
60
|
+
return hash;
|
|
61
|
+
}
|
|
62
|
+
|
|
42
63
|
/**
|
|
43
64
|
* InterceptScanner - A JavaScript implementation of YARA rule scanning engine
|
|
44
65
|
*
|
|
@@ -102,17 +123,29 @@ import { isValidModuleName } from "./interceptCustomModules.mjs";
|
|
|
102
123
|
* @property {boolean} autoParsePE - Automatically parse PE files (default: true)
|
|
103
124
|
* @property {boolean} autoParseELF - Automatically parse ELF files (default: true)
|
|
104
125
|
* @property {number} maxFileSize - Maximum file size for filesize operator (default: 1MB)
|
|
126
|
+
* @property {number} maxMatches - Maximum matches recorded per string (default: 100)
|
|
105
127
|
* @property {Object} modules - Available YARA modules (string, time, pe, elf, math, hash)
|
|
106
128
|
*/
|
|
107
129
|
export class InterceptScanner {
|
|
108
130
|
constructor(options = {}) {
|
|
109
131
|
this.compiledRules = [];
|
|
132
|
+
this.compiledFilterRules = [];
|
|
133
|
+
this.filterIndex = new Map();
|
|
134
|
+
this.filterDiagnostics = [];
|
|
135
|
+
this.filterScanDiagnostics = null;
|
|
136
|
+
this.filterDecisionCache = new Map();
|
|
137
|
+
this.filterModuleCache = new Map();
|
|
110
138
|
this.ac = null;
|
|
139
|
+
this.needsCandidateDedupe = false;
|
|
111
140
|
this.autoParsePE = true; // Automatically parse PE files
|
|
112
141
|
this.autoParseELF = true; // Automatically parse ELF files
|
|
113
142
|
this.maxFileSize = 1024 * 1024; // 1MB default limit for filesize operator
|
|
114
143
|
this.setModules(options.modules);
|
|
115
144
|
this.customModules = options.modules || {};
|
|
145
|
+
this.matchLimits = { maxMatches: options.maxMatches ?? MAX_MATCHES };
|
|
146
|
+
// Opt-in capture-group offsets on regex matches. YARA's match record has no capture data, so
|
|
147
|
+
// the default output stays YARA-shaped.
|
|
148
|
+
this.includeCaptures = options.includeCaptures === true;
|
|
116
149
|
const timingOptions = {
|
|
117
150
|
enabled: options.timing?.enabled ?? options.timing?.enableTiming ?? options.enableTiming ?? false,
|
|
118
151
|
autoPrint: options.timing?.autoPrint ?? options.autoPrint ?? false,
|
|
@@ -129,8 +162,23 @@ export class InterceptScanner {
|
|
|
129
162
|
const tracker = this.timingTracker;
|
|
130
163
|
const timingEnabled = tracker?.isEnabled();
|
|
131
164
|
const start = timingEnabled ? tracker.now() : 0;
|
|
132
|
-
|
|
165
|
+
|
|
166
|
+
const filterGroup = parseInterceptFilterRuleGroup(rulesText, this.compiledFilterRules || [], {
|
|
167
|
+
limits: this.matchLimits,
|
|
168
|
+
availableModules: this.getAvailableModuleNames(),
|
|
169
|
+
includeCaptures: this.includeCaptures,
|
|
170
|
+
});
|
|
171
|
+
this.compiledFilterRules = filterGroup.rules;
|
|
172
|
+
this.filterDiagnostics = filterGroup.diagnostics || [];
|
|
173
|
+
this.compiledRules = parseYaraRuleGroup(rulesText, this.compiledRules || [], {
|
|
174
|
+
limits: this.matchLimits,
|
|
175
|
+
includeCaptures: this.includeCaptures,
|
|
176
|
+
});
|
|
177
|
+
this.validateFilterRegistry();
|
|
178
|
+
this.rebuildFilterIndex();
|
|
179
|
+
|
|
133
180
|
this.ac = null; // Reset AC automaton to force rebuild
|
|
181
|
+
this.needsCandidateDedupe = InterceptScanner.hasMultiPatternStrings(this.compiledRules);
|
|
134
182
|
|
|
135
183
|
if (timingEnabled) {
|
|
136
184
|
tracker.recordCompile(tracker.now() - start);
|
|
@@ -152,7 +200,14 @@ export class InterceptScanner {
|
|
|
152
200
|
*/
|
|
153
201
|
clearRules() {
|
|
154
202
|
this.compiledRules = [];
|
|
203
|
+
this.compiledFilterRules = [];
|
|
204
|
+
this.filterIndex = new Map();
|
|
205
|
+
this.filterDiagnostics = [];
|
|
206
|
+
this.filterScanDiagnostics = null;
|
|
207
|
+
this.filterDecisionCache = new Map();
|
|
208
|
+
this.filterModuleCache = new Map();
|
|
155
209
|
this.ac = null;
|
|
210
|
+
this.needsCandidateDedupe = false;
|
|
156
211
|
}
|
|
157
212
|
|
|
158
213
|
/**
|
|
@@ -191,6 +246,17 @@ export class InterceptScanner {
|
|
|
191
246
|
return Array.from(unique.values());
|
|
192
247
|
}
|
|
193
248
|
|
|
249
|
+
/**
|
|
250
|
+
* Whether a string definition expands into several patterns (ascii + wide, base64 permutations).
|
|
251
|
+
* The Aho-Corasick engine already collapses repeated hits of one pattern, so only multi-pattern
|
|
252
|
+
* strings can report the same offset twice.
|
|
253
|
+
*/
|
|
254
|
+
static hasMultiPatternStrings(rules) {
|
|
255
|
+
return rules.some((rule) =>
|
|
256
|
+
Object.values(rule.strings ?? {}).some((strDef) => (strDef.patterns?.length ?? 0) > 1)
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
|
|
194
260
|
/**
|
|
195
261
|
* Verify candidates with full string matchers
|
|
196
262
|
* @param {Array} candidates - Candidate matches
|
|
@@ -200,17 +266,22 @@ export class InterceptScanner {
|
|
|
200
266
|
*/
|
|
201
267
|
verifyCandidates(candidates, data, rules) {
|
|
202
268
|
const verified = [];
|
|
269
|
+
const rulesById = new Map(rules.map((rule) => [rule.id, rule]));
|
|
203
270
|
|
|
204
271
|
for (const candidate of candidates) {
|
|
205
|
-
const rule =
|
|
272
|
+
const rule = rulesById.get(candidate.id);
|
|
206
273
|
if (!rule) continue;
|
|
207
274
|
|
|
208
275
|
const strDef = rule.strings[candidate.varName];
|
|
209
276
|
if (!strDef || !strDef.matcher) continue;
|
|
210
277
|
|
|
211
|
-
// For text and regex with literal prefix, verify at the candidate offset
|
|
278
|
+
// For text and regex with literal prefix, verify at the candidate offset. `verifyAt` demands
|
|
279
|
+
// a match starting exactly there; a forward scan would also return a neighbouring occurrence,
|
|
280
|
+
// which duplicates that match and loses this candidate's own.
|
|
212
281
|
if (strDef.type === "text" || (strDef.type === "regex" && strDef.literalPrefix)) {
|
|
213
|
-
const matches = strDef.matcher
|
|
282
|
+
const matches = typeof strDef.matcher.verifyAt === "function"
|
|
283
|
+
? strDef.matcher.verifyAt(data, candidate.offset, candidate)
|
|
284
|
+
: strDef.matcher(data, candidate.offset);
|
|
214
285
|
if (matches && matches.length > 0) {
|
|
215
286
|
verified.push({
|
|
216
287
|
...candidate,
|
|
@@ -227,14 +298,17 @@ export class InterceptScanner {
|
|
|
227
298
|
}
|
|
228
299
|
|
|
229
300
|
/**
|
|
230
|
-
* Build string match results per rule
|
|
301
|
+
* Build string match results per rule. Reject filters are applied here, before any facts are
|
|
302
|
+
* produced, so `#a`, `@a`, and `$a at N` only see surviving matches.
|
|
231
303
|
* @param {Array} verifiedCandidates - Verified matches
|
|
232
304
|
* @param {Array} rules - Compiled rules
|
|
233
305
|
* @param {Uint8Array} data - File data
|
|
234
|
-
* @
|
|
306
|
+
* @param {Object} metadata - Scan metadata to pass to custom modules
|
|
307
|
+
* @returns {Promise<Object>} String matches organized by rule
|
|
235
308
|
*/
|
|
236
|
-
buildStringMatches(verifiedCandidates, rules, data) {
|
|
309
|
+
async buildStringMatches(verifiedCandidates, rules, data, metadata = {}) {
|
|
237
310
|
const ruleMatches = {};
|
|
311
|
+
const rulesById = new Map(rules.map((rule) => [rule.id, rule]));
|
|
238
312
|
|
|
239
313
|
// Initialize match structure for each rule
|
|
240
314
|
for (const rule of rules) {
|
|
@@ -268,14 +342,24 @@ export class InterceptScanner {
|
|
|
268
342
|
const lookupKey = ruleMatches[candidate.id][finalKey] ? finalKey : (finalKey.startsWith('$') ? finalKey : `\$${finalKey}`);
|
|
269
343
|
|
|
270
344
|
const matchInfo = ruleMatches[candidate.id][lookupKey];
|
|
345
|
+
const ownerRule = rulesById.get(candidate.id);
|
|
346
|
+
const strDef = ownerRule?.strings?.[candidate.varName];
|
|
271
347
|
|
|
272
348
|
if (candidate.matches && candidate.matches.length > 0) {
|
|
349
|
+
const keptMatches = hasRejectFilters(strDef)
|
|
350
|
+
? await this.filterMatches(strDef, candidate.matches, data, metadata, {
|
|
351
|
+
ruleName: ownerRule?.name,
|
|
352
|
+
varName: candidate.varName,
|
|
353
|
+
})
|
|
354
|
+
: candidate.matches;
|
|
355
|
+
if (keptMatches.length === 0) continue;
|
|
356
|
+
|
|
273
357
|
// Has detailed match information
|
|
274
|
-
const prunedList =
|
|
358
|
+
const prunedList = keptMatches.length > this.maxMatches ? keptMatches.slice(0, this.maxMatches) : keptMatches;
|
|
275
359
|
matchInfo.matched = true;
|
|
276
360
|
matchInfo.count += prunedList.length;
|
|
277
361
|
matchInfo.matches.push(...prunedList);
|
|
278
|
-
matchInfo.offsets.push(...
|
|
362
|
+
matchInfo.offsets.push(...prunedList.map((m) => m.offset));
|
|
279
363
|
// if (prunedList[0].length) {
|
|
280
364
|
// matchInfo.length = prunedList[0].length;
|
|
281
365
|
// }
|
|
@@ -299,6 +383,9 @@ export class InterceptScanner {
|
|
|
299
383
|
for (const rule of rules) {
|
|
300
384
|
for (const [varName, strDef] of Object.entries(rule.strings)) {
|
|
301
385
|
if (strDef.type === "text" || (strDef.type === "regex" && strDef.literalPrefix?.length > 0)) continue; // Should be part of AC verified candidates
|
|
386
|
+
// String definitions that failed to compile carry no matcher; their warning was emitted at
|
|
387
|
+
// compile time, and the string simply never matches.
|
|
388
|
+
if (!strDef.matcher) continue;
|
|
302
389
|
|
|
303
390
|
// Handle key lookup (handle $.anon for anonymous)
|
|
304
391
|
const finalKey = varName.startsWith('.') ? `\$${varName}` : varName;
|
|
@@ -315,8 +402,11 @@ export class InterceptScanner {
|
|
|
315
402
|
|
|
316
403
|
// Run full matcher over entire data (-1 means find ALL matches, not verify at offset 0)
|
|
317
404
|
let matches = strDef.type === "hex" && dataAsHexString !== null ? strDef.matcher(dataAsHexString, -1) : strDef.matcher(data, -1);
|
|
405
|
+
if (hasRejectFilters(strDef) && matches && matches.length > 0) {
|
|
406
|
+
matches = await this.filterMatches(strDef, matches, data, metadata, { ruleName: rule.name, varName });
|
|
407
|
+
}
|
|
318
408
|
if (matches && matches.length > 0) {
|
|
319
|
-
const prunedList = matches.length >
|
|
409
|
+
const prunedList = matches.length > this.maxMatches ? matches.slice(0, this.maxMatches) : matches;
|
|
320
410
|
matchInfo.matched = true;
|
|
321
411
|
matchInfo.count += prunedList.length;
|
|
322
412
|
if (matchInfo.matches.length === 0) {
|
|
@@ -324,7 +414,7 @@ export class InterceptScanner {
|
|
|
324
414
|
} else {
|
|
325
415
|
matchInfo.matches.push(...prunedList);
|
|
326
416
|
}
|
|
327
|
-
matchInfo.offsets.push(...
|
|
417
|
+
matchInfo.offsets.push(...prunedList.map((m) => m.offset));
|
|
328
418
|
// if (prunedList[0].length) {
|
|
329
419
|
// matchInfo.length = prunedList[0].length;
|
|
330
420
|
// }
|
|
@@ -335,6 +425,360 @@ export class InterceptScanner {
|
|
|
335
425
|
return ruleMatches;
|
|
336
426
|
}
|
|
337
427
|
|
|
428
|
+
/**
|
|
429
|
+
* Reject filter registry / gate helpers
|
|
430
|
+
*/
|
|
431
|
+
|
|
432
|
+
validateFilterRegistry() {
|
|
433
|
+
const ruleNames = new Set(this.compiledRules.map((rule) => rule.name));
|
|
434
|
+
for (const filter of this.compiledFilterRules) {
|
|
435
|
+
if (ruleNames.has(filter.name)) {
|
|
436
|
+
throw new Error(`Filter rule "${filter.name}" collides with a rule of the same name`);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
const filterNames = new Set(this.compiledFilterRules.map((filter) => filter.name));
|
|
441
|
+
for (const rule of this.compiledRules) {
|
|
442
|
+
for (const [varName, strDef] of Object.entries(rule.strings || {})) {
|
|
443
|
+
for (const filterName of [...(strDef.reject ?? []), ...(strDef.rejectCapture ?? [])]) {
|
|
444
|
+
if (!filterNames.has(filterName)) {
|
|
445
|
+
this.filterDiagnostics.push({
|
|
446
|
+
code: "unknown-filter-rule",
|
|
447
|
+
severity: "warning",
|
|
448
|
+
message: `String ${varName} in rule "${rule.name}" references unknown filter rule "${filterName}"`,
|
|
449
|
+
rule: rule.name,
|
|
450
|
+
string: varName,
|
|
451
|
+
filter: filterName,
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
rebuildFilterIndex() {
|
|
460
|
+
this.filterIndex = new Map(this.compiledFilterRules.map((rule) => [rule.name, rule]));
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Module keywords available to filter conditions. Custom modules are addressed by the keyword
|
|
465
|
+
* their `getName()` returns, which need not match the key they were registered under.
|
|
466
|
+
*/
|
|
467
|
+
getAvailableModuleNames() {
|
|
468
|
+
const names = new Set(Object.keys(this.modules || {}));
|
|
469
|
+
for (const moduleValue of Object.values(this.modules || {})) {
|
|
470
|
+
if (typeof moduleValue?.getName === "function") {
|
|
471
|
+
names.add(moduleValue.getName());
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return [...names];
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
ensureFilterScanDiagnostics() {
|
|
478
|
+
if (!this.filterScanDiagnostics) {
|
|
479
|
+
this.filterScanDiagnostics = { oversized: new Map(), errors: new Map(), rejections: new Map() };
|
|
480
|
+
}
|
|
481
|
+
return this.filterScanDiagnostics;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
resetFilterScanState() {
|
|
485
|
+
this.filterScanDiagnostics = { oversized: new Map(), errors: new Map(), rejections: new Map() };
|
|
486
|
+
this.filterDecisionCache = new Map();
|
|
487
|
+
this.filterModuleCache = new Map();
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
async filterMatches(strDef, matches, data, metadata, context = {}) {
|
|
491
|
+
if (!hasRejectFilters(strDef)) return matches;
|
|
492
|
+
|
|
493
|
+
const kept = [];
|
|
494
|
+
for (const match of matches) {
|
|
495
|
+
if (await this.isRejectedMatch(strDef, match, data, metadata, context)) continue;
|
|
496
|
+
kept.push(match);
|
|
497
|
+
}
|
|
498
|
+
return kept;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
async isRejectedMatch(strDef, match, data, metadata, { ruleName, varName } = {}) {
|
|
502
|
+
const entries = [
|
|
503
|
+
...(strDef?.reject ?? []).map((name) => ({ name, capture: false })),
|
|
504
|
+
...(strDef?.rejectCapture ?? []).map((name) => ({ name, capture: true })),
|
|
505
|
+
];
|
|
506
|
+
if (entries.length === 0) return false;
|
|
507
|
+
|
|
508
|
+
const length = match?.length ?? 0;
|
|
509
|
+
if (length <= 0) return false;
|
|
510
|
+
|
|
511
|
+
const diagnostics = this.ensureFilterScanDiagnostics();
|
|
512
|
+
|
|
513
|
+
if (length > MAX_FILTER_RULE_BUFFER_SIZE) {
|
|
514
|
+
const key = `${ruleName}:${varName}:${match.offset}:${length}`;
|
|
515
|
+
if (!diagnostics.oversized.has(key)) {
|
|
516
|
+
diagnostics.oversized.set(key, {
|
|
517
|
+
code: "filter-buffer-too-large",
|
|
518
|
+
severity: "warning",
|
|
519
|
+
message: `Candidate for ${varName} in rule "${ruleName}" is ${length} bytes, exceeding MAX_FILTER_RULE_BUFFER_SIZE (${MAX_FILTER_RULE_BUFFER_SIZE}); filters were skipped`,
|
|
520
|
+
rule: ruleName,
|
|
521
|
+
string: varName,
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
return false;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
const fullBuffer = data.subarray(match.offset, match.offset + length);
|
|
528
|
+
|
|
529
|
+
for (const { name: filterName, capture } of entries) {
|
|
530
|
+
const filter = this.filterIndex.get(filterName);
|
|
531
|
+
if (!filter) continue; // Unknown names are ignored (diagnosed at compile time)
|
|
532
|
+
|
|
533
|
+
// `rejectRECapture` passes capture group 1 when the pattern has a participating, non-empty
|
|
534
|
+
// group; every other case falls back to the full match.
|
|
535
|
+
const buffer = capture && typeof match.capture === "string"
|
|
536
|
+
? new TextEncoder().encode(match.capture)
|
|
537
|
+
: fullBuffer;
|
|
538
|
+
|
|
539
|
+
if (await this.getFilterDecision(filter, buffer, metadata)) {
|
|
540
|
+
diagnostics.rejections.set(filterName, (diagnostics.rejections.get(filterName) ?? 0) + 1);
|
|
541
|
+
return true;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
return false;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
async getFilterDecision(filter, buffer, metadata) {
|
|
549
|
+
const cacheKey = `${filter.name}:${buffer.length}:${hashBytes(buffer)}`;
|
|
550
|
+
const cached = this.filterDecisionCache.get(cacheKey);
|
|
551
|
+
if (cached && cached.buffer.length === buffer.length && cached.buffer.every((byte, i) => byte === buffer[i])) {
|
|
552
|
+
return cached.rejected;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
const rejected = await this.evaluateFilterRule(filter, buffer, metadata);
|
|
556
|
+
this.filterDecisionCache.set(cacheKey, { buffer, rejected });
|
|
557
|
+
return rejected;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
async evaluateFilterRule(filter, buffer, metadata = {}) {
|
|
561
|
+
try {
|
|
562
|
+
const stringMatches = this.matchFilterStrings(filter, buffer);
|
|
563
|
+
const modules = await this.createFilterModules(filter, buffer, metadata);
|
|
564
|
+
const scanFacts = createScanFacts(buffer, stringMatches, modules, {
|
|
565
|
+
entrypoint: 0,
|
|
566
|
+
filesize: buffer.length,
|
|
567
|
+
isFileSizeCapped: false,
|
|
568
|
+
maxFileSize: this.maxFileSize,
|
|
569
|
+
matchedRules: {},
|
|
570
|
+
metadata: { ruleName: filter.name },
|
|
571
|
+
});
|
|
572
|
+
|
|
573
|
+
let ast = filter.conditionAST;
|
|
574
|
+
if (!ast) {
|
|
575
|
+
try {
|
|
576
|
+
ast = this.parseSimpleCondition(filter.condition, scanFacts.strings);
|
|
577
|
+
} catch {
|
|
578
|
+
ast = { type: "boolean", value: false };
|
|
579
|
+
}
|
|
580
|
+
filter.conditionAST = ast;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
return (await evaluateCondition(ast, scanFacts)) === true;
|
|
584
|
+
} catch (error) {
|
|
585
|
+
this.recordFilterError(filter.name, error);
|
|
586
|
+
return false;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
matchFilterStrings(filter, buffer) {
|
|
591
|
+
const stringMatches = {};
|
|
592
|
+
|
|
593
|
+
for (const [varName, strDef] of Object.entries(filter.strings || {})) {
|
|
594
|
+
if (typeof strDef.matcher !== "function") {
|
|
595
|
+
stringMatches[varName] = [];
|
|
596
|
+
continue;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
try {
|
|
600
|
+
const matches = strDef.matcher(buffer, -1);
|
|
601
|
+
stringMatches[varName] = Array.isArray(matches) ? matches : [];
|
|
602
|
+
} catch (error) {
|
|
603
|
+
this.recordFilterError(filter.name, error);
|
|
604
|
+
stringMatches[varName] = [];
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
return stringMatches;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
async createFilterModules(filter, buffer, metadata = {}) {
|
|
612
|
+
const modules = {
|
|
613
|
+
string: this.modules.string,
|
|
614
|
+
time: this.modules.time,
|
|
615
|
+
math: createMathModule(buffer),
|
|
616
|
+
hash: createHashModule(buffer),
|
|
617
|
+
};
|
|
618
|
+
|
|
619
|
+
const usedModules = filter.usedModules ?? [];
|
|
620
|
+
if (usedModules.length === 0) return modules;
|
|
621
|
+
|
|
622
|
+
// Custom modules are resolved by their `getName()` keyword, not their registration key.
|
|
623
|
+
const customModules = new Map();
|
|
624
|
+
for (const moduleValue of Object.values(this.modules || {})) {
|
|
625
|
+
if (typeof moduleValue?.getName === "function") {
|
|
626
|
+
customModules.set(moduleValue.getName(), moduleValue);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
for (const moduleName of usedModules) {
|
|
631
|
+
if (FILTER_MODULE_BUILTINS.has(moduleName)) continue;
|
|
632
|
+
|
|
633
|
+
const moduleValue = customModules.get(moduleName);
|
|
634
|
+
if (!moduleValue) continue;
|
|
635
|
+
|
|
636
|
+
const cacheKey = `${moduleName}:${buffer.length}:${hashBytes(buffer)}`;
|
|
637
|
+
if (this.filterModuleCache.has(cacheKey)) {
|
|
638
|
+
modules[moduleName] = this.filterModuleCache.get(cacheKey);
|
|
639
|
+
continue;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
if (typeof moduleValue.isLoaded === "function" && !moduleValue.isLoaded() && typeof moduleValue.load === "function") {
|
|
643
|
+
await moduleValue.load();
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
let moduleObject = moduleValue;
|
|
647
|
+
if (typeof moduleValue.initialize === "function" && typeof moduleValue.createModule === "function") {
|
|
648
|
+
const interimResults = await moduleValue.initialize(buffer, {
|
|
649
|
+
...(metadata || {}),
|
|
650
|
+
filesize: buffer.length,
|
|
651
|
+
hasPE: false,
|
|
652
|
+
hasELF: false,
|
|
653
|
+
timestamp: Date.now(),
|
|
654
|
+
});
|
|
655
|
+
moduleObject = moduleValue.createModule(interimResults);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
this.filterModuleCache.set(cacheKey, moduleObject);
|
|
659
|
+
modules[moduleName] = moduleObject;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
return modules;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
recordFilterError(filterName, error) {
|
|
666
|
+
const diagnostics = this.ensureFilterScanDiagnostics();
|
|
667
|
+
const message = error?.message ?? String(error);
|
|
668
|
+
const key = `${filterName}:${message}`;
|
|
669
|
+
if (diagnostics.errors.has(key)) return;
|
|
670
|
+
|
|
671
|
+
diagnostics.errors.set(key, {
|
|
672
|
+
code: "filter-error",
|
|
673
|
+
severity: "warning",
|
|
674
|
+
message: `Filter rule "${filterName}" failed and was treated as not rejecting: ${message}`,
|
|
675
|
+
filter: filterName,
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
attachResultDiagnostics(results) {
|
|
680
|
+
const diagnostics = [...this.filterDiagnostics];
|
|
681
|
+
|
|
682
|
+
if (this.filterScanDiagnostics) {
|
|
683
|
+
diagnostics.push(...this.filterScanDiagnostics.errors.values());
|
|
684
|
+
diagnostics.push(...this.filterScanDiagnostics.oversized.values());
|
|
685
|
+
for (const [filterName, count] of this.filterScanDiagnostics.rejections) {
|
|
686
|
+
diagnostics.push({
|
|
687
|
+
code: "filter-rejection-count",
|
|
688
|
+
severity: "info",
|
|
689
|
+
message: `Filter rule "${filterName}" rejected ${count} candidate(s)`,
|
|
690
|
+
filter: filterName,
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
Object.defineProperty(results, "diagnostics", {
|
|
696
|
+
value: diagnostics,
|
|
697
|
+
enumerable: false,
|
|
698
|
+
configurable: true,
|
|
699
|
+
});
|
|
700
|
+
|
|
701
|
+
return results;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
/**
|
|
705
|
+
* Evaluate named filter rules against a buffer directly.
|
|
706
|
+
*
|
|
707
|
+
* Result shape matches `scan()` (matched rules only). Unknown names are skipped silently.
|
|
708
|
+
* Custom modules are initialized from the supplied metadata, exactly as `scan()` does.
|
|
709
|
+
*
|
|
710
|
+
* @param {Uint8Array|string} data - Buffer to evaluate
|
|
711
|
+
* @param {Object} metadata - Scan metadata for custom modules
|
|
712
|
+
* @param {string[]} ruleNames - Filter rule names to evaluate
|
|
713
|
+
* @returns {Promise<Array>} Matched filter rules
|
|
714
|
+
*/
|
|
715
|
+
async scanFilterRules(data, metadata = {}, ruleNames = []) {
|
|
716
|
+
if (typeof data === "string") {
|
|
717
|
+
data = new TextEncoder().encode(data);
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
this.resetFilterScanState();
|
|
721
|
+
|
|
722
|
+
const matchedRules = [];
|
|
723
|
+
|
|
724
|
+
for (const filterName of Array.isArray(ruleNames) ? ruleNames : []) {
|
|
725
|
+
const filter = this.filterIndex.get(filterName);
|
|
726
|
+
if (!filter) continue;
|
|
727
|
+
|
|
728
|
+
let scanFacts = null;
|
|
729
|
+
let matched = false;
|
|
730
|
+
|
|
731
|
+
try {
|
|
732
|
+
const stringMatches = this.matchFilterStrings(filter, data);
|
|
733
|
+
const modules = await this.createFilterModules(filter, data, metadata);
|
|
734
|
+
scanFacts = createScanFacts(data, stringMatches, modules, {
|
|
735
|
+
entrypoint: 0,
|
|
736
|
+
filesize: data.length,
|
|
737
|
+
isFileSizeCapped: data.length >= this.maxFileSize,
|
|
738
|
+
maxFileSize: this.maxFileSize,
|
|
739
|
+
matchedRules: {},
|
|
740
|
+
metadata: { ruleName: filter.name },
|
|
741
|
+
});
|
|
742
|
+
|
|
743
|
+
let ast = filter.conditionAST;
|
|
744
|
+
if (!ast) {
|
|
745
|
+
try {
|
|
746
|
+
ast = this.parseSimpleCondition(filter.condition, scanFacts.strings);
|
|
747
|
+
} catch {
|
|
748
|
+
ast = { type: "boolean", value: false };
|
|
749
|
+
}
|
|
750
|
+
filter.conditionAST = ast;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
matched = (await evaluateCondition(ast, scanFacts)) === true;
|
|
754
|
+
} catch (error) {
|
|
755
|
+
this.recordFilterError(filter.name, error);
|
|
756
|
+
matched = false;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
if (matched && scanFacts) {
|
|
760
|
+
const filteredStrings = {};
|
|
761
|
+
for (const [key, value] of Object.entries(scanFacts.strings)) {
|
|
762
|
+
// Anonymous strings surface as `.anon_N` in raw facts; drop them and private strings,
|
|
763
|
+
// matching the normal rule output shape.
|
|
764
|
+
if (key.startsWith(".") || key.startsWith("$.")) continue;
|
|
765
|
+
if (value.private || filter.strings[key]?.private) continue;
|
|
766
|
+
filteredStrings[key] = value;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
matchedRules.push({
|
|
770
|
+
rule: filter.name,
|
|
771
|
+
namespace: "default",
|
|
772
|
+
tags: filter.tags || [],
|
|
773
|
+
metadata: filter.metadata || {},
|
|
774
|
+
strings: filteredStrings,
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
return this.attachResultDiagnostics(matchedRules);
|
|
780
|
+
}
|
|
781
|
+
|
|
338
782
|
/**
|
|
339
783
|
* Evaluate rule conditions
|
|
340
784
|
* @param {Object} ruleMatches - String matches per rule
|
|
@@ -416,6 +860,9 @@ export class InterceptScanner {
|
|
|
416
860
|
|
|
417
861
|
// Initialize custom modules from this.modules
|
|
418
862
|
// Check each module to see if it's a custom module (has getName() method and non-reserved name)
|
|
863
|
+
// `modulesWithBinary` already holds the same instances under their registration keys, so the
|
|
864
|
+
// collision that matters is two *custom* modules claiming one keyword — tracked separately.
|
|
865
|
+
const claimedKeywords = new Set();
|
|
419
866
|
for (const [key, moduleValue] of Object.entries(this.modules)) {
|
|
420
867
|
try {
|
|
421
868
|
// Check if this is a custom module by seeing if it has the custom module interface
|
|
@@ -461,6 +908,14 @@ export class InterceptScanner {
|
|
|
461
908
|
tracker.accumulateModule(modulesTiming, moduleName, tracker.now() - moduleStart);
|
|
462
909
|
}
|
|
463
910
|
|
|
911
|
+
// Conditions reach a custom module by the keyword its `getName()` returns — the key it was
|
|
912
|
+
// registered under is irrelevant. Two instances sharing a name therefore overwrite each
|
|
913
|
+
// other, and the rule silently reads the wrong URL/facts. Say so once per scan.
|
|
914
|
+
if (claimedKeywords.has(moduleName)) {
|
|
915
|
+
console.warn(`InterceptScanner: duplicate custom module name "${moduleName}" - the later instance replaces the earlier one`);
|
|
916
|
+
}
|
|
917
|
+
claimedKeywords.add(moduleName);
|
|
918
|
+
|
|
464
919
|
// Add to modules available for condition evaluation
|
|
465
920
|
modulesWithBinary[moduleName] = moduleObject;
|
|
466
921
|
}
|
|
@@ -701,6 +1156,8 @@ export class InterceptScanner {
|
|
|
701
1156
|
data = encoder.encode(data);
|
|
702
1157
|
}
|
|
703
1158
|
|
|
1159
|
+
this.resetFilterScanState();
|
|
1160
|
+
|
|
704
1161
|
if (!this.compiledRules || this.compiledRules.length === 0) {
|
|
705
1162
|
if (timingEnabled && scanTiming) {
|
|
706
1163
|
scanTiming.total = tracker.now() - totalStart;
|
|
@@ -709,7 +1166,7 @@ export class InterceptScanner {
|
|
|
709
1166
|
} else if (tracker) {
|
|
710
1167
|
tracker.clearScan();
|
|
711
1168
|
}
|
|
712
|
-
return [];
|
|
1169
|
+
return this.attachResultDiagnostics([]);
|
|
713
1170
|
}
|
|
714
1171
|
|
|
715
1172
|
// Phase 1: Fast candidate detection with Aho-Corasick
|
|
@@ -730,7 +1187,9 @@ export class InterceptScanner {
|
|
|
730
1187
|
}
|
|
731
1188
|
|
|
732
1189
|
const dedupeStart = timingEnabled ? tracker.now() : 0;
|
|
733
|
-
const unique = this.
|
|
1190
|
+
const unique = this.needsCandidateDedupe
|
|
1191
|
+
? this.deduplicateCandidates(candidates)
|
|
1192
|
+
: candidates;
|
|
734
1193
|
if (timingEnabled && scanTiming) {
|
|
735
1194
|
tracker.accumulateStep(scanTiming.steps, "deduplicate", tracker.now() - dedupeStart);
|
|
736
1195
|
}
|
|
@@ -742,7 +1201,7 @@ export class InterceptScanner {
|
|
|
742
1201
|
}
|
|
743
1202
|
|
|
744
1203
|
const buildStart = timingEnabled ? tracker.now() : 0;
|
|
745
|
-
const ruleMatches = this.buildStringMatches(verified, this.compiledRules, data);
|
|
1204
|
+
const ruleMatches = await this.buildStringMatches(verified, this.compiledRules, data, metadata);
|
|
746
1205
|
if (timingEnabled && scanTiming) {
|
|
747
1206
|
tracker.accumulateStep(scanTiming.steps, "buildMatches", tracker.now() - buildStart);
|
|
748
1207
|
}
|
|
@@ -775,7 +1234,7 @@ export class InterceptScanner {
|
|
|
775
1234
|
tracker.clearScan();
|
|
776
1235
|
}
|
|
777
1236
|
|
|
778
|
-
return results;
|
|
1237
|
+
return this.attachResultDiagnostics(results);
|
|
779
1238
|
}
|
|
780
1239
|
|
|
781
1240
|
/**
|
|
@@ -786,6 +1245,16 @@ export class InterceptScanner {
|
|
|
786
1245
|
this.maxFileSize = size;
|
|
787
1246
|
}
|
|
788
1247
|
|
|
1248
|
+
// Backed by `matchLimits`, the object shared with compiled string matchers, so changing the
|
|
1249
|
+
// cap takes effect for rules that were already compiled.
|
|
1250
|
+
get maxMatches() {
|
|
1251
|
+
return this.matchLimits.maxMatches;
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
set maxMatches(value) {
|
|
1255
|
+
this.matchLimits.maxMatches = value;
|
|
1256
|
+
}
|
|
1257
|
+
|
|
789
1258
|
/**
|
|
790
1259
|
* Get statistics about loaded rules
|
|
791
1260
|
* @returns {Object} Rule statistics
|
|
@@ -793,6 +1262,7 @@ export class InterceptScanner {
|
|
|
793
1262
|
getStats() {
|
|
794
1263
|
return {
|
|
795
1264
|
totalRules: this.compiledRules.length,
|
|
1265
|
+
totalFilterRules: this.compiledFilterRules.length,
|
|
796
1266
|
ruleNames: this.compiledRules.map((r) => r.name),
|
|
797
1267
|
rulesWithStrings: this.compiledRules.filter((r) => Object.keys(r.strings).length > 0).length,
|
|
798
1268
|
totalStrings: this.compiledRules.reduce((sum, r) => sum + Object.keys(r.strings).length, 0),
|
|
@@ -813,8 +1283,7 @@ export class InterceptScanner {
|
|
|
813
1283
|
* Clear all loaded rules
|
|
814
1284
|
*/
|
|
815
1285
|
clear() {
|
|
816
|
-
this.
|
|
817
|
-
this.ac = null;
|
|
1286
|
+
this.clearRules();
|
|
818
1287
|
// Reset existing modules
|
|
819
1288
|
this.setModules(this.customModules);
|
|
820
1289
|
}
|