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
|
@@ -158,6 +158,31 @@ export function createScanFacts(data, stringMatches = {}, modules = {}, options
|
|
|
158
158
|
};
|
|
159
159
|
}
|
|
160
160
|
|
|
161
|
+
/**
|
|
162
|
+
* Compiled regex literals, cached per AST node. Conditions are parsed once per rule per scan and
|
|
163
|
+
* `for` loops re-evaluate the same node many times, so compiling once per node matters.
|
|
164
|
+
* `g`/`y` are dropped to keep `test()` stateless across those repeated evaluations.
|
|
165
|
+
*/
|
|
166
|
+
const compiledRegexCache = new WeakMap();
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Compile (or fetch) the RegExp for a `regex` AST node.
|
|
170
|
+
*
|
|
171
|
+
* @param {Object} node
|
|
172
|
+
* @returns {RegExp}
|
|
173
|
+
*/
|
|
174
|
+
function compileRegexNode(node) {
|
|
175
|
+
if (node.error) {
|
|
176
|
+
throw new Error(`Invalid regex literal /${node.pattern}/${node.flags ?? ''} - ${node.error}`);
|
|
177
|
+
}
|
|
178
|
+
let regex = compiledRegexCache.get(node);
|
|
179
|
+
if (!regex) {
|
|
180
|
+
regex = new RegExp(node.pattern, (node.flags ?? '').replace(/[gy]/g, ''));
|
|
181
|
+
compiledRegexCache.set(node, regex);
|
|
182
|
+
}
|
|
183
|
+
return regex;
|
|
184
|
+
}
|
|
185
|
+
|
|
161
186
|
/**
|
|
162
187
|
* YARA Condition Evaluator
|
|
163
188
|
*/
|
|
@@ -200,10 +225,9 @@ export class ConditionEvaluator {
|
|
|
200
225
|
/**
|
|
201
226
|
* Parse a condition string into an AST
|
|
202
227
|
* This is a simplified parser - in production, use a proper parser
|
|
203
|
-
* @param {string} condition
|
|
204
228
|
* @returns {Object} AST node
|
|
205
229
|
*/
|
|
206
|
-
parseCondition(
|
|
230
|
+
parseCondition() {
|
|
207
231
|
// This would normally use a proper parser (e.g., PEG.js, antlr)
|
|
208
232
|
// For now, return a simple structure
|
|
209
233
|
// In practice, the rule compiler would generate this AST
|
|
@@ -230,6 +254,10 @@ export class ConditionEvaluator {
|
|
|
230
254
|
return node.value;
|
|
231
255
|
case "string":
|
|
232
256
|
return node.value;
|
|
257
|
+
case "regex":
|
|
258
|
+
// `/…/flags` in a condition. Compiled once per node and cached; an invalid pattern makes
|
|
259
|
+
// the rule fail (caught per rule by the scanner) rather than silently matching nothing.
|
|
260
|
+
return compileRegexNode(node);
|
|
233
261
|
case "identifier":
|
|
234
262
|
return this.resolveIdentifier(node.name);
|
|
235
263
|
|
|
@@ -240,6 +268,10 @@ export class ConditionEvaluator {
|
|
|
240
268
|
// String identifiers
|
|
241
269
|
case "stringIdentifier":
|
|
242
270
|
return this.evaluateStringIdentifier(node);
|
|
271
|
+
|
|
272
|
+
// Intercept extension: an undeclared `$_` resolves to the buffer text
|
|
273
|
+
case "buffer":
|
|
274
|
+
return this.bufferText();
|
|
243
275
|
case "stringCount":
|
|
244
276
|
return this.getStringCount(node.identifier);
|
|
245
277
|
case "stringOffset": {
|
|
@@ -258,6 +290,19 @@ export class ConditionEvaluator {
|
|
|
258
290
|
}
|
|
259
291
|
return this.getStringLength(node.identifier, index);
|
|
260
292
|
}
|
|
293
|
+
case "stringOccurrence": {
|
|
294
|
+
// Extension (not YARA): the i-th matched substring, sliced from the scanned data using
|
|
295
|
+
// @a[i] for the offset and !a[i] for the length.
|
|
296
|
+
let index = node.index;
|
|
297
|
+
if (typeof index === "object" && index !== null) {
|
|
298
|
+
index = await this.evaluateNode(index);
|
|
299
|
+
}
|
|
300
|
+
const offset = this.getStringOffset(node.identifier, index);
|
|
301
|
+
const length = this.getStringLength(node.identifier, index);
|
|
302
|
+
if (offset === undefined || length === undefined) return undefined;
|
|
303
|
+
if (!this.data || typeof this.data.subarray !== "function") return undefined;
|
|
304
|
+
return new TextDecoder().decode(this.data.subarray(offset, offset + length));
|
|
305
|
+
}
|
|
261
306
|
|
|
262
307
|
// Logical operators
|
|
263
308
|
case "and": {
|
|
@@ -384,6 +429,10 @@ export class ConditionEvaluator {
|
|
|
384
429
|
case "iequals":
|
|
385
430
|
return await this.stringEquals(node.left, node.right, true);
|
|
386
431
|
case "matches":
|
|
432
|
+
// YARA requires a regex literal on the right; the parser flags anything else.
|
|
433
|
+
if (node.error) {
|
|
434
|
+
throw new Error(`Invalid "matches" comparison - ${node.error}`);
|
|
435
|
+
}
|
|
387
436
|
return await this.stringMatches(node.left, node.right);
|
|
388
437
|
|
|
389
438
|
// Set membership
|
|
@@ -445,6 +494,18 @@ export class ConditionEvaluator {
|
|
|
445
494
|
}
|
|
446
495
|
}
|
|
447
496
|
|
|
497
|
+
/**
|
|
498
|
+
* Intercept extension: text of the buffer under evaluation. `$_` resolves here when the rule does
|
|
499
|
+
* not declare a string with that name. Decoded once per evaluator, and there is one evaluator per
|
|
500
|
+
* rule per scan, so nothing is shared across scans and modules stay pure.
|
|
501
|
+
*/
|
|
502
|
+
bufferText() {
|
|
503
|
+
if (this._bufferText === undefined) {
|
|
504
|
+
this._bufferText = this.data ? new TextDecoder().decode(this.data) : "";
|
|
505
|
+
}
|
|
506
|
+
return this._bufferText;
|
|
507
|
+
}
|
|
508
|
+
|
|
448
509
|
/**
|
|
449
510
|
* Resolve a simple identifier (filesize, entrypoint, modules, etc.)
|
|
450
511
|
*/
|
|
@@ -665,8 +726,7 @@ export class ConditionEvaluator {
|
|
|
665
726
|
}
|
|
666
727
|
|
|
667
728
|
// YARA uses 1-indexed arrays: @a or @a[1] = first match, @a[2] = second match
|
|
668
|
-
//
|
|
669
|
-
// Special case: @a (without index) and @a[0] both return first match
|
|
729
|
+
// Extension: @a[0] is treated like @a (first match); real YARA makes it undefined.
|
|
670
730
|
const arrayIndex = index === 0 ? 0 : index - 1;
|
|
671
731
|
return stringInfo.offsets[arrayIndex];
|
|
672
732
|
}
|
|
@@ -693,8 +753,7 @@ export class ConditionEvaluator {
|
|
|
693
753
|
}
|
|
694
754
|
|
|
695
755
|
// YARA uses 1-indexed arrays: !a or !a[1] = first match, !a[2] = second match
|
|
696
|
-
//
|
|
697
|
-
// Special case: !a (without index) and !a[0] both return first match
|
|
756
|
+
// Extension: !a[0] is treated like !a (first match); real YARA makes it undefined.
|
|
698
757
|
const arrayIndex = index === 0 ? 0 : index - 1;
|
|
699
758
|
const match = stringInfo.matches[arrayIndex];
|
|
700
759
|
return match ? match.length : undefined;
|
|
@@ -1194,7 +1253,7 @@ export class ConditionEvaluator {
|
|
|
1194
1253
|
// Handle both sync and async module functions
|
|
1195
1254
|
return result instanceof Promise ? await result : result;
|
|
1196
1255
|
} catch (error) {
|
|
1197
|
-
throw new Error(`Error calling ${module}.${functionName}: ${error.message}
|
|
1256
|
+
throw new Error(`Error calling ${module}.${functionName}: ${error.message}`, { cause: error });
|
|
1198
1257
|
}
|
|
1199
1258
|
}
|
|
1200
1259
|
|
|
@@ -1316,20 +1375,17 @@ export class ConditionEvaluator {
|
|
|
1316
1375
|
// YARA: string operators return undefined if operands are undefined
|
|
1317
1376
|
if (this.isAnyUndefined(left, right)) return undefined;
|
|
1318
1377
|
|
|
1319
|
-
|
|
1320
|
-
|
|
1378
|
+
// The pattern must come from rule text. Compiling a value that was produced during the scan
|
|
1379
|
+
// would allow arbitrary patterns (catastrophic backtracking), so it is rejected outright.
|
|
1380
|
+
if (!(right instanceof RegExp)) {
|
|
1381
|
+
throw new Error(`"matches" requires a regex literal as its right operand, got ${typeof right}`);
|
|
1321
1382
|
}
|
|
1322
1383
|
|
|
1323
|
-
|
|
1324
|
-
if (right instanceof RegExp) {
|
|
1325
|
-
regex = right;
|
|
1326
|
-
} else if (typeof right === "string") {
|
|
1327
|
-
regex = new RegExp(right);
|
|
1328
|
-
} else {
|
|
1384
|
+
if (typeof left !== "string") {
|
|
1329
1385
|
return false;
|
|
1330
1386
|
}
|
|
1331
1387
|
|
|
1332
|
-
return
|
|
1388
|
+
return right.test(left);
|
|
1333
1389
|
}
|
|
1334
1390
|
}
|
|
1335
1391
|
|
package/src/yaraRuleCompiler.mjs
CHANGED
|
@@ -15,6 +15,11 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import { compileYaraLike } from './yaraStringMatch.mjs';
|
|
18
|
+
import { parseConditionToAST } from './yaraConditionParser.mjs';
|
|
19
|
+
|
|
20
|
+
const RULE_START_RE = /^\s*(?:\s*(?:private|global)\s+)*rule\b/i;
|
|
21
|
+
const FILTER_RULE_START_RE = /^\s*(?:\s*(?:private|global)\s+)*filter\s+rule\b/i;
|
|
22
|
+
const BUILTIN_MODULE_NAMES = new Set(['pe', 'elf', 'math', 'hash', 'string', 'time']);
|
|
18
23
|
|
|
19
24
|
/**
|
|
20
25
|
* List of supported YARA modules
|
|
@@ -60,10 +65,39 @@ function parseImports(text) {
|
|
|
60
65
|
return imports;
|
|
61
66
|
}
|
|
62
67
|
|
|
68
|
+
/**
|
|
69
|
+
* A regex literal only starts where YARA allows one: after the `=` of a string definition, or
|
|
70
|
+
* after the `matches` operator. Everywhere else `/` is just a character.
|
|
71
|
+
*/
|
|
72
|
+
function isRegexStart(text, index) {
|
|
73
|
+
let p = index - 1;
|
|
74
|
+
while (p >= 0 && (text[p] === ' ' || text[p] === '\t')) p--;
|
|
75
|
+
if (p < 0) return false;
|
|
76
|
+
if (text[p] === '=') return true;
|
|
77
|
+
|
|
78
|
+
let wordStart = p;
|
|
79
|
+
while (wordStart >= 0 && /[A-Za-z_]/.test(text[wordStart])) wordStart--;
|
|
80
|
+
return text.slice(wordStart + 1, p + 1) === 'matches';
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Index of the closing slash of the regex literal starting at `start`, or -1 if it never closes. */
|
|
84
|
+
function findRegexEnd(text, start) {
|
|
85
|
+
for (let i = start + 1; i < text.length; i++) {
|
|
86
|
+
if (text[i] === '\\') {
|
|
87
|
+
i += 1; // escaped character, including \/
|
|
88
|
+
} else if (text[i] === '/') {
|
|
89
|
+
return i;
|
|
90
|
+
} else if (text[i] === '\n') {
|
|
91
|
+
return -1; // regex literals cannot span lines
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return -1;
|
|
95
|
+
}
|
|
96
|
+
|
|
63
97
|
/**
|
|
64
98
|
* Remove comments from YARA rule text
|
|
65
99
|
* Handles both single-line (//) and multi-line C-style comments
|
|
66
|
-
* Preserves
|
|
100
|
+
* Preserves string and regex literals to avoid removing comment-like patterns inside them
|
|
67
101
|
* @param {string} text - The text to strip comments from
|
|
68
102
|
* @returns {string} Text with comments removed
|
|
69
103
|
*/
|
|
@@ -91,6 +125,19 @@ function stripComments(text) {
|
|
|
91
125
|
}
|
|
92
126
|
}
|
|
93
127
|
}
|
|
128
|
+
// Check for a regex literal (preserve it as-is). Without this, an escaped `\/` right before
|
|
129
|
+
// the closing `/` reads as the start of a `//` comment and truncates the definition. `//` and
|
|
130
|
+
// `/*` are always comments, never empty regexes.
|
|
131
|
+
else if (text[i] === '/' && text[i + 1] !== '/' && text[i + 1] !== '*' && isRegexStart(text, i)) {
|
|
132
|
+
const end = findRegexEnd(text, i);
|
|
133
|
+
if (end < 0) {
|
|
134
|
+
// Unterminated: leave the slash as ordinary text so the rest is still comment-stripped.
|
|
135
|
+
result += text[i++];
|
|
136
|
+
} else {
|
|
137
|
+
result += text.slice(i, end + 1);
|
|
138
|
+
i = end + 1;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
94
141
|
// Check for single-line comment
|
|
95
142
|
else if (text[i] === '/' && i + 1 < len && text[i + 1] === '/') {
|
|
96
143
|
// Skip until end of line
|
|
@@ -172,7 +219,7 @@ function countBracesOutsideStrings(line) {
|
|
|
172
219
|
return { openCount, closeCount };
|
|
173
220
|
}
|
|
174
221
|
|
|
175
|
-
export function parseYaraRuleGroup(multiRuleText, existingRules = []) {
|
|
222
|
+
export function parseYaraRuleGroup(multiRuleText, existingRules = [], options = {}) {
|
|
176
223
|
// Parse and validate import statements before processing rules
|
|
177
224
|
// This will throw an error if an unsupported module is imported
|
|
178
225
|
parseImports(multiRuleText);
|
|
@@ -185,11 +232,28 @@ export function parseYaraRuleGroup(multiRuleText, existingRules = []) {
|
|
|
185
232
|
let currentRuleText = '';
|
|
186
233
|
let braceDepth = 0;
|
|
187
234
|
let inRule = false;
|
|
235
|
+
let skipFilterDepth = 0;
|
|
188
236
|
|
|
189
237
|
const lines = multiRuleText.split('\n');
|
|
190
238
|
for (let line of lines) {
|
|
239
|
+
// Filter rules are owned by parseInterceptFilterRuleGroup. Skip their blocks entirely instead
|
|
240
|
+
// of relying on the rule-start pattern failing to match, so rule-like text inside a filter
|
|
241
|
+
// body cannot open a bogus rule.
|
|
242
|
+
if (skipFilterDepth > 0) {
|
|
243
|
+
const braceCounts = countBracesOutsideStrings(line);
|
|
244
|
+
skipFilterDepth += braceCounts.openCount - braceCounts.closeCount;
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (!inRule && FILTER_RULE_START_RE.test(line)) {
|
|
249
|
+
const braceCounts = countBracesOutsideStrings(line);
|
|
250
|
+
const depth = braceCounts.openCount - braceCounts.closeCount;
|
|
251
|
+
skipFilterDepth = depth > 0 ? depth : 0;
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
|
|
191
255
|
// Check for the start of a rule (with or without private modifier)
|
|
192
|
-
if (!inRule &&
|
|
256
|
+
if (!inRule && RULE_START_RE.test(line)) {
|
|
193
257
|
inRule = true;
|
|
194
258
|
currentRuleText = line + '\n';
|
|
195
259
|
// Count braces while ignoring those inside strings
|
|
@@ -199,7 +263,7 @@ export function parseYaraRuleGroup(multiRuleText, existingRules = []) {
|
|
|
199
263
|
|
|
200
264
|
// Handle single-line rules where braces balance immediately
|
|
201
265
|
if (braceDepth === 0 && atleastOneBrace) {
|
|
202
|
-
rules.push(parseYaraRule(currentRuleText));
|
|
266
|
+
rules.push(parseYaraRule(currentRuleText, options));
|
|
203
267
|
inRule = false;
|
|
204
268
|
currentRuleText = '';
|
|
205
269
|
}
|
|
@@ -212,7 +276,7 @@ export function parseYaraRuleGroup(multiRuleText, existingRules = []) {
|
|
|
212
276
|
// Check for end of rule
|
|
213
277
|
if (braceDepth === 0) {
|
|
214
278
|
// Complete rule found
|
|
215
|
-
rules.push(parseYaraRule(currentRuleText));
|
|
279
|
+
rules.push(parseYaraRule(currentRuleText, options));
|
|
216
280
|
inRule = false;
|
|
217
281
|
currentRuleText = '';
|
|
218
282
|
// console.log("Pushed rule: ", rules[rules.length - 1].name);
|
|
@@ -232,12 +296,263 @@ export function parseYaraRuleGroup(multiRuleText, existingRules = []) {
|
|
|
232
296
|
return rules;
|
|
233
297
|
}
|
|
234
298
|
|
|
299
|
+
/**
|
|
300
|
+
* Parse Intercept filter rules from a rule group.
|
|
301
|
+
*
|
|
302
|
+
* Filter rules are kept in their own registry: `parseYaraRuleGroup` skips their blocks, so the two
|
|
303
|
+
* sets never mix. Each returned rule carries a cached condition AST and the module roots its
|
|
304
|
+
* condition references, both reused for every candidate evaluation.
|
|
305
|
+
*
|
|
306
|
+
* @param {string} multiRuleText - Rule text that may contain `filter rule` declarations
|
|
307
|
+
* @param {Array} existingFilterRules - Previously parsed filter rules (appended to / replaced)
|
|
308
|
+
* @param {Object} options - `{ limits, availableModules }`
|
|
309
|
+
* @returns {{ rules: Array, diagnostics: Array }}
|
|
310
|
+
*/
|
|
311
|
+
export function parseInterceptFilterRuleGroup(multiRuleText, existingFilterRules = [], options = {}) {
|
|
312
|
+
parseImports(multiRuleText);
|
|
313
|
+
|
|
314
|
+
multiRuleText = multiRuleText.replace(/^\s*import\s+"[^"]+"\s*$/gm, '');
|
|
315
|
+
|
|
316
|
+
const rules = [...(existingFilterRules ?? [])];
|
|
317
|
+
const diagnostics = [];
|
|
318
|
+
let currentRuleText = '';
|
|
319
|
+
let braceDepth = 0;
|
|
320
|
+
let inFilterRule = false;
|
|
321
|
+
let skipRuleDepth = 0;
|
|
322
|
+
|
|
323
|
+
const addFilterRule = (ruleText) => {
|
|
324
|
+
const { rule, diagnostics: ruleDiagnostics } = parseFilterRule(ruleText, options);
|
|
325
|
+
diagnostics.push(...ruleDiagnostics);
|
|
326
|
+
|
|
327
|
+
const existingIndex = rules.findIndex((existing) => existing.name === rule.name);
|
|
328
|
+
if (existingIndex >= 0) {
|
|
329
|
+
diagnostics.push({
|
|
330
|
+
code: 'duplicate-filter-rule',
|
|
331
|
+
severity: 'warning',
|
|
332
|
+
message: `Filter rule "${rule.name}" redefined; the later definition replaces the earlier one`,
|
|
333
|
+
filter: rule.name,
|
|
334
|
+
});
|
|
335
|
+
rules[existingIndex] = rule;
|
|
336
|
+
} else {
|
|
337
|
+
rules.push(rule);
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
for (const line of multiRuleText.split('\n')) {
|
|
342
|
+
// Skip normal rule bodies so rule-like text inside them cannot be mistaken for a filter rule.
|
|
343
|
+
if (skipRuleDepth > 0) {
|
|
344
|
+
const braceCounts = countBracesOutsideStrings(line);
|
|
345
|
+
skipRuleDepth += braceCounts.openCount - braceCounts.closeCount;
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
if (!inFilterRule && FILTER_RULE_START_RE.test(line)) {
|
|
350
|
+
inFilterRule = true;
|
|
351
|
+
currentRuleText = line + '\n';
|
|
352
|
+
const braceCounts = countBracesOutsideStrings(line);
|
|
353
|
+
braceDepth = braceCounts.openCount - braceCounts.closeCount;
|
|
354
|
+
if (braceDepth === 0 && braceCounts.openCount > 0) {
|
|
355
|
+
addFilterRule(currentRuleText);
|
|
356
|
+
inFilterRule = false;
|
|
357
|
+
currentRuleText = '';
|
|
358
|
+
}
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
if (!inFilterRule && RULE_START_RE.test(line)) {
|
|
363
|
+
const braceCounts = countBracesOutsideStrings(line);
|
|
364
|
+
const depth = braceCounts.openCount - braceCounts.closeCount;
|
|
365
|
+
skipRuleDepth = depth > 0 ? depth : 0;
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
if (inFilterRule) {
|
|
370
|
+
currentRuleText += line + '\n';
|
|
371
|
+
const braceCounts = countBracesOutsideStrings(line);
|
|
372
|
+
braceDepth += braceCounts.openCount - braceCounts.closeCount;
|
|
373
|
+
if (braceDepth === 0) {
|
|
374
|
+
addFilterRule(currentRuleText);
|
|
375
|
+
inFilterRule = false;
|
|
376
|
+
currentRuleText = '';
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
rules.forEach((rule) => {
|
|
382
|
+
rule.id = `filter:${rule.name}`;
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
return { rules, diagnostics };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Parse a single `filter rule` declaration.
|
|
390
|
+
* @param {string} ruleText - Complete filter rule text
|
|
391
|
+
* @param {Object} options - `{ limits, availableModules }`
|
|
392
|
+
* @returns {{ rule: Object, diagnostics: Array }}
|
|
393
|
+
*/
|
|
394
|
+
function parseFilterRule(ruleText, options = {}) {
|
|
395
|
+
const text = stripComments(ruleText).trim();
|
|
396
|
+
const diagnostics = [];
|
|
397
|
+
|
|
398
|
+
const ruleKeywordIndex = text.search(/\brule\b/i);
|
|
399
|
+
const prefix = ruleKeywordIndex >= 0 ? text.slice(0, ruleKeywordIndex) : '';
|
|
400
|
+
if (/\bglobal\b/i.test(prefix)) {
|
|
401
|
+
throw new Error('Invalid Intercept filter rule: global filter rules are not supported');
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const ruleMatch = text.match(/^(?:.*)?rule\s+(\w+)(?:\s*:\s*([\w\s]+))?\s*\{/);
|
|
405
|
+
if (!ruleMatch) {
|
|
406
|
+
throw new Error('Invalid Intercept filter rule: missing rule declaration');
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
const name = ruleMatch[1];
|
|
410
|
+
const tags = ruleMatch[2] ? ruleMatch[2].trim().split(/\s+/) : [];
|
|
411
|
+
|
|
412
|
+
const bodyMatch = text.match(/\{([\s\S]*)\}/);
|
|
413
|
+
if (!bodyMatch) {
|
|
414
|
+
throw new Error('Invalid Intercept filter rule: missing rule body');
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const ruleBody = bodyMatch[1];
|
|
418
|
+
const metadata = parseMetadata(ruleBody);
|
|
419
|
+
const strings = parseStrings(ruleBody, options);
|
|
420
|
+
|
|
421
|
+
for (const [varName, strDef] of Object.entries(strings)) {
|
|
422
|
+
if (strDef.reject?.length || strDef.rejectCapture?.length) {
|
|
423
|
+
throw new Error(
|
|
424
|
+
`Invalid Intercept filter rule "${name}": reject(...) and rejectRECapture(...) are not allowed on string ${varName}`
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const condition = parseCondition(ruleBody);
|
|
430
|
+
|
|
431
|
+
let conditionAST = null;
|
|
432
|
+
try {
|
|
433
|
+
conditionAST = parseConditionToAST(condition, strings);
|
|
434
|
+
} catch (error) {
|
|
435
|
+
diagnostics.push({
|
|
436
|
+
code: 'invalid-filter-condition',
|
|
437
|
+
severity: 'warning',
|
|
438
|
+
message: `Filter rule "${name}" condition could not be parsed: ${error.message}`,
|
|
439
|
+
filter: name,
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const usedModules = collectUsedModules(conditionAST, {
|
|
444
|
+
availableModules: options.availableModules ?? [],
|
|
445
|
+
filterName: name,
|
|
446
|
+
diagnostics,
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
return {
|
|
450
|
+
rule: {
|
|
451
|
+
name,
|
|
452
|
+
tags,
|
|
453
|
+
metadata,
|
|
454
|
+
strings,
|
|
455
|
+
condition,
|
|
456
|
+
conditionAST,
|
|
457
|
+
usedModules,
|
|
458
|
+
filter: true,
|
|
459
|
+
private: true,
|
|
460
|
+
},
|
|
461
|
+
diagnostics,
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* Collect the module roots a filter condition references.
|
|
467
|
+
*
|
|
468
|
+
* Qualified roots (`pe.foo`, `hash.md5(...)`) are the only candidates; loop variables are excluded
|
|
469
|
+
* so `for any s in pe.sections : (s.name == ...)` doesn't treat `s` as a module. Unknown roots are
|
|
470
|
+
* kept (a custom module may be registered later) but produce a diagnostic.
|
|
471
|
+
*/
|
|
472
|
+
function collectUsedModules(ast, { availableModules = [], filterName, diagnostics }) {
|
|
473
|
+
if (!ast) return [];
|
|
474
|
+
|
|
475
|
+
const loopVariables = new Set();
|
|
476
|
+
const qualifiedRoots = new Set();
|
|
477
|
+
|
|
478
|
+
walkAst(ast, (node) => {
|
|
479
|
+
if (node.type === 'ruleIdentifier') {
|
|
480
|
+
throw new Error(
|
|
481
|
+
`Invalid Intercept filter rule "${filterName}": conditions cannot reference rules ("${node.name}")`
|
|
482
|
+
);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
if (node.type === 'for') {
|
|
486
|
+
const variable = node.variable;
|
|
487
|
+
if (typeof variable === 'string') loopVariables.add(variable);
|
|
488
|
+
else if (variable?.name) loopVariables.add(variable.name);
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
if (node.type === 'moduleFunction' && typeof node.module === 'string') {
|
|
492
|
+
qualifiedRoots.add(node.module);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
if (
|
|
496
|
+
node.type === 'memberAccess' &&
|
|
497
|
+
node.object?.type === 'identifier' &&
|
|
498
|
+
typeof node.object.name === 'string'
|
|
499
|
+
) {
|
|
500
|
+
qualifiedRoots.add(node.object.name.split('.')[0]);
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
if (node.type === 'identifier' && typeof node.name === 'string' && node.name.includes('.')) {
|
|
504
|
+
qualifiedRoots.add(node.name.split('.')[0]);
|
|
505
|
+
}
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
const knownModules = new Set([...BUILTIN_MODULE_NAMES, ...availableModules]);
|
|
509
|
+
const usedModules = [];
|
|
510
|
+
|
|
511
|
+
for (const root of qualifiedRoots) {
|
|
512
|
+
if (loopVariables.has(root)) continue;
|
|
513
|
+
|
|
514
|
+
if (root === 'pe' || root === 'elf') {
|
|
515
|
+
throw new Error(
|
|
516
|
+
`Invalid Intercept filter rule "${filterName}": the "${root}" module is not available for candidate buffers`
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
usedModules.push(root);
|
|
521
|
+
|
|
522
|
+
if (!knownModules.has(root)) {
|
|
523
|
+
diagnostics.push({
|
|
524
|
+
code: 'unknown-module',
|
|
525
|
+
severity: 'warning',
|
|
526
|
+
message: `Filter rule "${filterName}" references unknown module "${root}"`,
|
|
527
|
+
filter: filterName,
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
return usedModules;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function walkAst(node, visit) {
|
|
536
|
+
if (!node || typeof node !== 'object') return;
|
|
537
|
+
|
|
538
|
+
if (Array.isArray(node)) {
|
|
539
|
+
for (const item of node) walkAst(item, visit);
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
visit(node);
|
|
544
|
+
|
|
545
|
+
for (const value of Object.values(node)) {
|
|
546
|
+
if (value && typeof value === 'object') walkAst(value, visit);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
235
550
|
/**
|
|
236
551
|
* Parse a YARA rule and return an object representation
|
|
237
552
|
* @param {string} ruleText - The complete YARA rule text
|
|
238
553
|
* @returns {Object} Parsed rule object with metadata, strings, and condition
|
|
239
554
|
*/
|
|
240
|
-
export function parseYaraRule(ruleText) {
|
|
555
|
+
export function parseYaraRule(ruleText, options = {}) {
|
|
241
556
|
// Strip comments before parsing
|
|
242
557
|
ruleText = stripComments(ruleText).trim();
|
|
243
558
|
|
|
@@ -268,7 +583,7 @@ export function parseYaraRule(ruleText) {
|
|
|
268
583
|
const metadata = parseMetadata(ruleBody);
|
|
269
584
|
|
|
270
585
|
// Parse strings section
|
|
271
|
-
const strings = parseStrings(ruleBody);
|
|
586
|
+
const strings = parseStrings(ruleBody, options);
|
|
272
587
|
|
|
273
588
|
// Parse condition section
|
|
274
589
|
const condition = parseCondition(ruleBody);
|
|
@@ -325,7 +640,7 @@ function parseMetadata(ruleBody) {
|
|
|
325
640
|
* @param {string} ruleBody - The rule body text
|
|
326
641
|
* @returns {Object} String definitions with their compiled matchers
|
|
327
642
|
*/
|
|
328
|
-
function parseStrings(ruleBody) {
|
|
643
|
+
function parseStrings(ruleBody, options = {}) {
|
|
329
644
|
const stringsMatch = ruleBody.match(/strings:\s*([\s\S]*?)(?=condition:|$)/);
|
|
330
645
|
if (!stringsMatch) return {};
|
|
331
646
|
|
|
@@ -356,7 +671,9 @@ function parseStrings(ruleBody) {
|
|
|
356
671
|
|
|
357
672
|
try {
|
|
358
673
|
// Compile the string definition into a matcher function
|
|
359
|
-
const compiledRule = compileYaraLike(definition.trim()
|
|
674
|
+
const compiledRule = compileYaraLike(definition.trim(), options.limits, {
|
|
675
|
+
includeCaptures: options.includeCaptures,
|
|
676
|
+
});
|
|
360
677
|
|
|
361
678
|
strings[varName] = {
|
|
362
679
|
definition: definition.trim(),
|