sekant-intercept-js 1.0.0 → 1.0.2

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.
@@ -16,7 +16,7 @@
16
16
 
17
17
  /**
18
18
  * YARA Condition Matching Engine
19
- *
19
+ *
20
20
  * Evaluates YARA rule conditions against scan results.
21
21
  * Supports:
22
22
  * - String identifiers ($a, $b, #a, @a)
@@ -33,16 +33,16 @@
33
33
  * - For expressions (for any/all of them)
34
34
  * - Filesize checks
35
35
  * - Entrypoint checks
36
- *
36
+ *
37
37
  * @see https://yara.readthedocs.io/en/stable/writingrules.html
38
38
  */
39
39
 
40
40
  /**
41
41
  * Scan Facts Structure
42
- *
42
+ *
43
43
  * This is the standardized format for scan results that will be evaluated
44
44
  * against YARA rule conditions.
45
- *
45
+ *
46
46
  * @typedef {Object} ScanFacts
47
47
  * @property {Uint8Array} data - The raw file data being scanned
48
48
  * @property {number} filesize - Size of the file in bytes
@@ -51,7 +51,7 @@
51
51
  * @property {Object} modules - Module instances (pe, elf, math, hash, time, string)
52
52
  * @property {Object.<string, boolean>} matchedRules - Map of rule names to match status (for dependent rules)
53
53
  * @property {Object} metadata - Additional metadata about the scan
54
- *
54
+ *
55
55
  * @typedef {Object} StringMatchResult
56
56
  * @property {string} identifier - String identifier (e.g., "$a", "$hex1")
57
57
  * @property {boolean} matched - Whether the string matched at all
@@ -59,12 +59,12 @@
59
59
  * @property {Array<MatchInstance>} matches - Array of individual match instances
60
60
  * @property {Array<number>} offsets - Array of match offsets (for quick access)
61
61
  * @property {number} length - Length of the matched string (if fixed)
62
- *
62
+ *
63
63
  * @typedef {Object} MatchInstance
64
64
  * @property {number} offset - Offset where the match occurred
65
65
  * @property {number} length - Length of the matched data
66
66
  * @property {string} [data] - Optional matched data (for debugging)
67
- *
67
+ *
68
68
  * Example ScanFacts:
69
69
  * {
70
70
  * data: Uint8Array([...]),
@@ -119,7 +119,7 @@
119
119
  export function createScanFacts(data, stringMatches = {}, modules = {}, options = {}) {
120
120
  // Normalize string matches to standard format
121
121
  const normalizedStrings = {};
122
-
122
+
123
123
  for (const [identifier, result] of Object.entries(stringMatches)) {
124
124
  if (Array.isArray(result)) {
125
125
  // Convert array of matches to standard format
@@ -128,19 +128,19 @@ export function createScanFacts(data, stringMatches = {}, modules = {}, options
128
128
  matched: result.length > 0,
129
129
  count: result.length,
130
130
  matches: result,
131
- offsets: result.map(m => m.offset),
131
+ offsets: result.map((m) => m.offset),
132
132
  // length: result.length > 0 ? result[0].length : null
133
133
  };
134
- } else if (typeof result === 'object' && result !== null) {
134
+ } else if (typeof result === "object" && result !== null) {
135
135
  // Already in standard format or close to it
136
136
  normalizedStrings[identifier] = {
137
137
  identifier,
138
- matched: result.matched ?? (result.count > 0),
138
+ matched: result.matched ?? result.count > 0,
139
139
  count: result.count ?? 0,
140
140
  matches: result.matches ?? [],
141
- offsets: result.offsets ?? (result.matches || []).map(m => m.offset),
141
+ offsets: result.offsets ?? (result.matches || []).map((m) => m.offset),
142
142
  // length: result.length ?? result.matches?.length,
143
- ...result
143
+ ...result,
144
144
  };
145
145
  }
146
146
  }
@@ -150,14 +150,39 @@ export function createScanFacts(data, stringMatches = {}, modules = {}, options
150
150
  filesize: data.length,
151
151
  entrypoint: options.entrypoint ?? 0,
152
152
  isFileSizeCapped: options.isFileSizeCapped ?? false,
153
- maxFileSize: options.maxFileSize ?? (1024 * 1024), // Default 1MB
153
+ maxFileSize: options.maxFileSize ?? 1024 * 1024, // Default 1MB
154
154
  strings: normalizedStrings,
155
155
  modules: modules || {},
156
156
  matchedRules: options.matchedRules || {}, // Map of rule names to match status
157
- metadata: options.metadata || {}
157
+ metadata: options.metadata || {},
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
  */
@@ -168,7 +193,7 @@ export class ConditionEvaluator {
168
193
  this.filesize = scanFacts.filesize;
169
194
  this.entrypoint = scanFacts.entrypoint;
170
195
  this.isFileSizeCapped = scanFacts.isFileSizeCapped ?? false;
171
- this.maxFileSize = scanFacts.maxFileSize ?? (1024 * 1024);
196
+ this.maxFileSize = scanFacts.maxFileSize ?? 1024 * 1024;
172
197
  this.strings = scanFacts.strings;
173
198
  this.modules = scanFacts.modules;
174
199
  this.matchedRules = scanFacts.matchedRules || {}; // Map of rule names to match status
@@ -176,13 +201,13 @@ export class ConditionEvaluator {
176
201
 
177
202
  /**
178
203
  * Check if any operand is undefined (YARA semantics)
179
- * According to YARA docs: "All remaining operators, including the not operator,
204
+ * According to YARA docs: "All remaining operators, including the not operator,
180
205
  * return undefined if any of their operands is undefined"
181
206
  * @param {...*} operands - One or more operands to check
182
207
  * @returns {boolean} True if any operand is undefined
183
208
  */
184
209
  isAnyUndefined(...operands) {
185
- return operands.some(operand => operand === undefined);
210
+ return operands.some((operand) => operand === undefined);
186
211
  }
187
212
 
188
213
  /**
@@ -191,7 +216,7 @@ export class ConditionEvaluator {
191
216
  * @returns {Promise<boolean>} Result of condition evaluation
192
217
  */
193
218
  async evaluate(condition) {
194
- if (typeof condition === 'string') {
219
+ if (typeof condition === "string") {
195
220
  condition = this.parseCondition(condition);
196
221
  }
197
222
  return await this.evaluateNode(condition);
@@ -200,19 +225,18 @@ 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(condition) {
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
210
- throw new Error('String parsing not implemented - pass AST directly');
234
+ throw new Error("String parsing not implemented - pass AST directly");
211
235
  }
212
236
 
213
237
  /**
214
238
  * Evaluate an AST node
215
- * @param {Object} node
239
+ * @param {Object} node
216
240
  * @returns {Promise<*>} Evaluation result
217
241
  */
218
242
  async evaluateNode(node) {
@@ -224,43 +248,60 @@ export class ConditionEvaluator {
224
248
 
225
249
  switch (type) {
226
250
  // Literals
227
- case 'boolean':
251
+ case "boolean":
228
252
  return node.value;
229
- case 'number':
253
+ case "number":
230
254
  return node.value;
231
- case 'string':
255
+ case "string":
232
256
  return node.value;
233
- case 'identifier':
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);
261
+ case "identifier":
234
262
  return this.resolveIdentifier(node.name);
235
263
 
236
264
  // Rule identifiers (dependent rules)
237
- case 'ruleIdentifier':
265
+ case "ruleIdentifier":
238
266
  return this.evaluateRuleIdentifier(node);
239
267
 
240
268
  // String identifiers
241
- case 'stringIdentifier':
269
+ case "stringIdentifier":
242
270
  return this.evaluateStringIdentifier(node);
243
- case 'stringCount':
271
+ case "stringCount":
244
272
  return this.getStringCount(node.identifier);
245
- case 'stringOffset': {
273
+ case "stringOffset": {
246
274
  // Evaluate index if it's an expression (e.g., for loop variable)
247
275
  let index = node.index;
248
- if (typeof index === 'object') {
276
+ if (typeof index === "object") {
249
277
  index = await this.evaluateNode(index);
250
278
  }
251
279
  return this.getStringOffset(node.identifier, index);
252
280
  }
253
- case 'stringLength': {
281
+ case "stringLength": {
254
282
  // Evaluate index if it's an expression (e.g., for loop variable)
255
283
  let index = node.index;
256
- if (typeof index === 'object') {
284
+ if (typeof index === "object") {
257
285
  index = await this.evaluateNode(index);
258
286
  }
259
287
  return this.getStringLength(node.identifier, index);
260
288
  }
289
+ case "stringOccurrence": {
290
+ // Extension (not YARA): the i-th matched substring, sliced from the scanned data using
291
+ // @a[i] for the offset and !a[i] for the length.
292
+ let index = node.index;
293
+ if (typeof index === "object" && index !== null) {
294
+ index = await this.evaluateNode(index);
295
+ }
296
+ const offset = this.getStringOffset(node.identifier, index);
297
+ const length = this.getStringLength(node.identifier, index);
298
+ if (offset === undefined || length === undefined) return undefined;
299
+ if (!this.data || typeof this.data.subarray !== "function") return undefined;
300
+ return new TextDecoder().decode(this.data.subarray(offset, offset + length));
301
+ }
261
302
 
262
303
  // Logical operators
263
- case 'and': {
304
+ case "and": {
264
305
  const left = await this.evaluateNode(node.left);
265
306
  const right = await this.evaluateNode(node.right);
266
307
  // YARA: treat undefined as false in AND operation
@@ -268,7 +309,7 @@ export class ConditionEvaluator {
268
309
  if (right === undefined || right === false) return false;
269
310
  return true;
270
311
  }
271
- case 'or': {
312
+ case "or": {
272
313
  const left = await this.evaluateNode(node.left);
273
314
  const right = await this.evaluateNode(node.right);
274
315
  // YARA: treat undefined as false in OR operation
@@ -276,55 +317,55 @@ export class ConditionEvaluator {
276
317
  const rightBool = right === undefined ? false : right;
277
318
  return leftBool || rightBool;
278
319
  }
279
- case 'not': {
320
+ case "not": {
280
321
  const operand = await this.evaluateNode(node.operand);
281
322
  // YARA: not of undefined returns undefined
282
323
  if (this.isAnyUndefined(operand)) return undefined;
283
324
  return !operand;
284
325
  }
285
- case 'defined':
326
+ case "defined":
286
327
  return await this.evaluateDefined(node.operand);
287
328
 
288
329
  // Comparison operators
289
- case 'equal':
330
+ case "equal":
290
331
  return await this.evaluateEqual(node);
291
- case 'notEqual':
332
+ case "notEqual":
292
333
  return await this.evaluateNotEqual(node);
293
- case 'lessThan':
334
+ case "lessThan":
294
335
  return await this.evaluateLessThan(node);
295
- case 'greaterThan':
336
+ case "greaterThan":
296
337
  return await this.evaluateGreaterThan(node);
297
- case 'lessThanOrEqual':
338
+ case "lessThanOrEqual":
298
339
  return await this.evaluateLessThanOrEqual(node);
299
- case 'greaterThanOrEqual':
340
+ case "greaterThanOrEqual":
300
341
  return await this.evaluateGreaterThanOrEqual(node);
301
342
 
302
343
  // Arithmetic operators
303
- case 'add': {
344
+ case "add": {
304
345
  const left = await this.evaluateNode(node.left);
305
346
  const right = await this.evaluateNode(node.right);
306
347
  if (this.isAnyUndefined(left, right)) return undefined;
307
348
  return left + right;
308
349
  }
309
- case 'subtract': {
350
+ case "subtract": {
310
351
  const left = await this.evaluateNode(node.left);
311
352
  const right = await this.evaluateNode(node.right);
312
353
  if (this.isAnyUndefined(left, right)) return undefined;
313
354
  return left - right;
314
355
  }
315
- case 'multiply': {
356
+ case "multiply": {
316
357
  const left = await this.evaluateNode(node.left);
317
358
  const right = await this.evaluateNode(node.right);
318
359
  if (this.isAnyUndefined(left, right)) return undefined;
319
360
  return left * right;
320
361
  }
321
- case 'divide': {
362
+ case "divide": {
322
363
  const left = await this.evaluateNode(node.left);
323
364
  const right = await this.evaluateNode(node.right);
324
365
  if (this.isAnyUndefined(left, right)) return undefined;
325
366
  return Math.floor(left / right);
326
367
  }
327
- case 'modulo': {
368
+ case "modulo": {
328
369
  const left = await this.evaluateNode(node.left);
329
370
  const right = await this.evaluateNode(node.right);
330
371
  if (this.isAnyUndefined(left, right)) return undefined;
@@ -332,36 +373,36 @@ export class ConditionEvaluator {
332
373
  }
333
374
 
334
375
  // Bitwise operators (use signed 32-bit integers to match standard YARA behavior)
335
- case 'bitwiseAnd': {
376
+ case "bitwiseAnd": {
336
377
  const left = await this.evaluateNode(node.left);
337
378
  const right = await this.evaluateNode(node.right);
338
379
  if (this.isAnyUndefined(left, right)) return undefined;
339
- return (left & right);
380
+ return left & right;
340
381
  }
341
- case 'bitwiseOr': {
382
+ case "bitwiseOr": {
342
383
  const left = await this.evaluateNode(node.left);
343
384
  const right = await this.evaluateNode(node.right);
344
385
  if (this.isAnyUndefined(left, right)) return undefined;
345
- return (left | right);
386
+ return left | right;
346
387
  }
347
- case 'bitwiseXor': {
388
+ case "bitwiseXor": {
348
389
  const left = await this.evaluateNode(node.left);
349
390
  const right = await this.evaluateNode(node.right);
350
391
  if (this.isAnyUndefined(left, right)) return undefined;
351
- return (left ^ right);
392
+ return left ^ right;
352
393
  }
353
- case 'bitwiseNot': {
394
+ case "bitwiseNot": {
354
395
  const operand = await this.evaluateNode(node.operand);
355
396
  if (this.isAnyUndefined(operand)) return undefined;
356
- return (~operand);
397
+ return ~operand;
357
398
  }
358
- case 'shiftLeft': {
399
+ case "shiftLeft": {
359
400
  const left = await this.evaluateNode(node.left);
360
401
  const right = await this.evaluateNode(node.right);
361
402
  if (this.isAnyUndefined(left, right)) return undefined;
362
403
  return left << right;
363
404
  }
364
- case 'shiftRight': {
405
+ case "shiftRight": {
365
406
  const left = await this.evaluateNode(node.left);
366
407
  const right = await this.evaluateNode(node.right);
367
408
  if (this.isAnyUndefined(left, right)) return undefined;
@@ -369,75 +410,79 @@ export class ConditionEvaluator {
369
410
  }
370
411
 
371
412
  // String operators
372
- case 'contains':
413
+ case "contains":
373
414
  return await this.stringContains(node.left, node.right, false);
374
- case 'icontains':
415
+ case "icontains":
375
416
  return await this.stringContains(node.left, node.right, true);
376
- case 'startswith':
417
+ case "startswith":
377
418
  return await this.stringStartsWith(node.left, node.right, false);
378
- case 'istartswith':
419
+ case "istartswith":
379
420
  return await this.stringStartsWith(node.left, node.right, true);
380
- case 'endswith':
421
+ case "endswith":
381
422
  return await this.stringEndsWith(node.left, node.right, false);
382
- case 'iendswith':
423
+ case "iendswith":
383
424
  return await this.stringEndsWith(node.left, node.right, true);
384
- case 'iequals':
425
+ case "iequals":
385
426
  return await this.stringEquals(node.left, node.right, true);
386
- case 'matches':
427
+ case "matches":
428
+ // YARA requires a regex literal on the right; the parser flags anything else.
429
+ if (node.error) {
430
+ throw new Error(`Invalid "matches" comparison - ${node.error}`);
431
+ }
387
432
  return await this.stringMatches(node.left, node.right);
388
433
 
389
434
  // Set membership
390
- case 'in':
435
+ case "in":
391
436
  return await this.evaluateInOperator(node);
392
437
 
393
438
  // Range
394
- case 'range':
439
+ case "range":
395
440
  return { start: await this.evaluateNode(node.start), end: await this.evaluateNode(node.end) };
396
441
 
397
442
  // Quantifiers
398
- case 'all':
443
+ case "all":
399
444
  return await this.evaluateAll(node.items);
400
- case 'any':
445
+ case "any":
401
446
  return await this.evaluateAny(node.items);
402
- case 'none':
447
+ case "none":
403
448
  return await this.evaluateNone(node.items);
404
- case 'quantified':
449
+ case "quantified":
405
450
  return await this.evaluateQuantified(node);
406
451
 
407
452
  // For expressions
408
- case 'for':
453
+ case "for":
409
454
  return await this.evaluateFor(node);
410
455
 
411
456
  // Member access (e.g., pe.entry_point)
412
- case 'memberAccess':
457
+ case "memberAccess":
413
458
  return await this.evaluateMemberAccess(node);
414
459
 
415
460
  // Array access (e.g., pe.sections[0])
416
- case 'arrayAccess':
461
+ case "arrayAccess":
417
462
  return await this.evaluateArrayAccess(node);
418
463
 
419
464
  // Function call
420
- case 'functionCall':
465
+ case "functionCall":
421
466
  return await this.evaluateFunctionCall(node);
422
467
 
423
468
  // Data access (uint8, uint16, etc.)
424
- case 'dataAccess':
469
+ case "dataAccess":
425
470
  return this.evaluateDataAccess(node);
426
471
 
427
472
  // At expression ($a at 0x100)
428
- case 'at':
473
+ case "at":
429
474
  return await this.evaluateAt(node);
430
475
 
431
476
  // In range expression ($a in (0..100))
432
- case 'inRange':
477
+ case "inRange":
433
478
  return await this.evaluateInRange(node);
434
479
 
435
480
  // Within expression ($a within N of $b)
436
- case 'within':
481
+ case "within":
437
482
  return await this.evaluateWithin(node);
438
483
 
439
484
  // Module function call (e.g., string.to_int(), time.now())
440
- case 'moduleFunction':
485
+ case "moduleFunction":
441
486
  return await this.evaluateModuleFunction(node);
442
487
 
443
488
  default:
@@ -453,24 +498,33 @@ export class ConditionEvaluator {
453
498
  if (this.forContext && name in this.forContext) {
454
499
  return this.forContext[name];
455
500
  }
456
-
501
+
502
+ const splitName = name?.split(".");
503
+ name = splitName[0];
504
+
457
505
  switch (name) {
458
- case 'filesize':
506
+ case "filesize":
459
507
  return this.filesize;
460
- case 'entrypoint':
508
+ case "entrypoint":
461
509
  // entrypoint can be 0 (valid for non-binary files or PE at offset 0)
462
- if (typeof this.entrypoint !== 'number') {
463
- throw new Error('Entrypoint is not defined');
510
+ if (typeof this.entrypoint !== "number") {
511
+ throw new Error("Entrypoint is not defined");
464
512
  }
465
513
  return this.entrypoint;
466
514
  default:
467
515
  // Check if it's a module name (pe, elf, hash, math, string, time)
468
516
  if (this.modules && name in this.modules) {
469
- return this.modules[name]; // Could be undefined if module not available
517
+ if (!this.modules[name]) return this.modules[name]; // Nothing to do
518
+ let currentObj = this.modules;
519
+ for (const key of splitName) {
520
+ currentObj = currentObj[key];
521
+ if (!currentObj) return currentObj;
522
+ }
523
+ return currentObj;
470
524
  }
471
525
  // Return undefined for known module names when module is unavailable
472
526
  // This allows graceful handling of missing modules (e.g., ELF module for non-ELF files)
473
- if (['pe', 'elf', 'hash', 'math', 'string', 'time'].includes(name)) {
527
+ if (["pe", "elf", "hash", "math", "string", "time"].includes(name)) {
474
528
  return undefined;
475
529
  }
476
530
  throw new Error(`Unknown identifier: ${name}`);
@@ -481,7 +535,7 @@ export class ConditionEvaluator {
481
535
  * Check if left side is filesize identifier
482
536
  */
483
537
  isFilesizeNode(node) {
484
- return node && node.type === 'identifier' && node.name === 'filesize';
538
+ return node && node.type === "identifier" && node.name === "filesize";
485
539
  }
486
540
 
487
541
  /**
@@ -490,10 +544,10 @@ export class ConditionEvaluator {
490
544
  async evaluateEqual(node) {
491
545
  const left = await this.evaluateNode(node.left);
492
546
  const right = await this.evaluateNode(node.right);
493
-
547
+
494
548
  // YARA: comparison with undefined returns undefined
495
549
  if (this.isAnyUndefined(left, right)) return undefined;
496
-
550
+
497
551
  // Special handling: if file is capped and comparing filesize == N where N >= maxFileSize
498
552
  if (this.isFilesizeNode(node.left) && this.isFileSizeCapped && right >= this.maxFileSize) {
499
553
  return true; // Assume any filesize >= maxFileSize when capped
@@ -501,7 +555,7 @@ export class ConditionEvaluator {
501
555
  if (this.isFilesizeNode(node.right) && this.isFileSizeCapped && left >= this.maxFileSize) {
502
556
  return true;
503
557
  }
504
-
558
+
505
559
  return left === right;
506
560
  }
507
561
 
@@ -521,10 +575,10 @@ export class ConditionEvaluator {
521
575
  async evaluateLessThan(node) {
522
576
  const left = await this.evaluateNode(node.left);
523
577
  const right = await this.evaluateNode(node.right);
524
-
578
+
525
579
  // YARA: comparison with undefined returns undefined
526
580
  if (this.isAnyUndefined(left, right)) return undefined;
527
-
581
+
528
582
  // Normal comparison - filesize < N uses actual value
529
583
  return left < right;
530
584
  }
@@ -535,15 +589,15 @@ export class ConditionEvaluator {
535
589
  async evaluateGreaterThan(node) {
536
590
  const left = await this.evaluateNode(node.left);
537
591
  const right = await this.evaluateNode(node.right);
538
-
592
+
539
593
  // YARA: comparison with undefined returns undefined
540
594
  if (this.isAnyUndefined(left, right)) return undefined;
541
-
595
+
542
596
  // Special handling: if file is capped and comparing filesize > N where N >= maxFileSize
543
597
  if (this.isFilesizeNode(node.left) && this.isFileSizeCapped && right >= this.maxFileSize) {
544
598
  return true; // File could be larger than the cap
545
599
  }
546
-
600
+
547
601
  // Normal comparison
548
602
  return left > right;
549
603
  }
@@ -554,10 +608,10 @@ export class ConditionEvaluator {
554
608
  async evaluateLessThanOrEqual(node) {
555
609
  const left = await this.evaluateNode(node.left);
556
610
  const right = await this.evaluateNode(node.right);
557
-
611
+
558
612
  // YARA: comparison with undefined returns undefined
559
613
  if (this.isAnyUndefined(left, right)) return undefined;
560
-
614
+
561
615
  // Normal comparison - filesize <= N uses actual value
562
616
  return left <= right;
563
617
  }
@@ -568,15 +622,15 @@ export class ConditionEvaluator {
568
622
  async evaluateGreaterThanOrEqual(node) {
569
623
  const left = await this.evaluateNode(node.left);
570
624
  const right = await this.evaluateNode(node.right);
571
-
625
+
572
626
  // YARA: comparison with undefined returns undefined
573
627
  if (this.isAnyUndefined(left, right)) return undefined;
574
-
628
+
575
629
  // Special handling: if file is capped and comparing filesize >= N where N >= maxFileSize
576
630
  if (this.isFilesizeNode(node.left) && this.isFileSizeCapped && right >= this.maxFileSize) {
577
631
  return true; // File could be larger than or equal to the cap
578
632
  }
579
-
633
+
580
634
  // Normal comparison
581
635
  return left >= right;
582
636
  }
@@ -587,14 +641,14 @@ export class ConditionEvaluator {
587
641
  */
588
642
  evaluateStringIdentifier(node) {
589
643
  let identifier = node.identifier;
590
-
644
+
591
645
  // In for loops with string iteration, '$' refers to the current string
592
- if (identifier === '$' && this.forContext && this.forContext['$']) {
593
- identifier = this.forContext['$'];
646
+ if (identifier === "$" && this.forContext && this.forContext["$"]) {
647
+ identifier = this.forContext["$"];
594
648
  }
595
-
649
+
596
650
  const stringInfo = this.strings[identifier];
597
-
651
+
598
652
  if (!stringInfo) {
599
653
  return false;
600
654
  }
@@ -608,7 +662,7 @@ export class ConditionEvaluator {
608
662
  */
609
663
  evaluateRuleIdentifier(node) {
610
664
  const ruleName = node.name;
611
-
665
+
612
666
  // Check if rule has been evaluated
613
667
  if (!(ruleName in this.matchedRules)) {
614
668
  // Rule not found or not yet evaluated
@@ -616,7 +670,7 @@ export class ConditionEvaluator {
616
670
  // but we'll return false for now
617
671
  return false;
618
672
  }
619
-
673
+
620
674
  return this.matchedRules[ruleName] === true;
621
675
  }
622
676
 
@@ -626,10 +680,10 @@ export class ConditionEvaluator {
626
680
  */
627
681
  getStringCount(identifier) {
628
682
  // Handle for loop context: if identifier is '$', use current string
629
- if (identifier === '$' && this.forContext && this.forContext['$']) {
630
- identifier = this.forContext['$'];
683
+ if (identifier === "$" && this.forContext && this.forContext["$"]) {
684
+ identifier = this.forContext["$"];
631
685
  }
632
-
686
+
633
687
  const stringInfo = this.strings[identifier];
634
688
  return stringInfo ? stringInfo.count : 0;
635
689
  }
@@ -641,23 +695,22 @@ export class ConditionEvaluator {
641
695
  */
642
696
  getStringOffset(identifier, index = 0) {
643
697
  // Handle for loop context: if identifier is '$', use current string
644
- if (identifier === '$' && this.forContext && this.forContext['$']) {
645
- identifier = this.forContext['$'];
698
+ if (identifier === "$" && this.forContext && this.forContext["$"]) {
699
+ identifier = this.forContext["$"];
646
700
  }
647
-
701
+
648
702
  // If index is an identifier in for context, resolve it
649
- if (typeof index === 'string' && this.forContext && index in this.forContext) {
703
+ if (typeof index === "string" && this.forContext && index in this.forContext) {
650
704
  index = this.forContext[index];
651
705
  }
652
-
706
+
653
707
  const stringInfo = this.strings[identifier];
654
708
  if (!stringInfo || !stringInfo.offsets || stringInfo.offsets.length === 0) {
655
709
  return undefined;
656
710
  }
657
-
711
+
658
712
  // YARA uses 1-indexed arrays: @a or @a[1] = first match, @a[2] = second match
659
- // Convert to 0-indexed for JavaScript arrays
660
- // Special case: @a (without index) and @a[0] both return first match
713
+ // Extension: @a[0] is treated like @a (first match); real YARA makes it undefined.
661
714
  const arrayIndex = index === 0 ? 0 : index - 1;
662
715
  return stringInfo.offsets[arrayIndex];
663
716
  }
@@ -669,23 +722,22 @@ export class ConditionEvaluator {
669
722
  */
670
723
  getStringLength(identifier, index = 0) {
671
724
  // Handle for loop context: if identifier is '$', use current string
672
- if (identifier === '$' && this.forContext && this.forContext['$']) {
673
- identifier = this.forContext['$'];
725
+ if (identifier === "$" && this.forContext && this.forContext["$"]) {
726
+ identifier = this.forContext["$"];
674
727
  }
675
-
728
+
676
729
  // If index is an identifier in for context, resolve it
677
- if (typeof index === 'string' && this.forContext && index in this.forContext) {
730
+ if (typeof index === "string" && this.forContext && index in this.forContext) {
678
731
  index = this.forContext[index];
679
732
  }
680
-
733
+
681
734
  const stringInfo = this.strings[identifier];
682
735
  if (!stringInfo || !stringInfo.matches || stringInfo.matches.length === 0) {
683
736
  return undefined;
684
737
  }
685
-
738
+
686
739
  // YARA uses 1-indexed arrays: !a or !a[1] = first match, !a[2] = second match
687
- // Convert to 0-indexed for JavaScript arrays
688
- // Special case: !a (without index) and !a[0] both return first match
740
+ // Extension: !a[0] is treated like !a (first match); real YARA makes it undefined.
689
741
  const arrayIndex = index === 0 ? 0 : index - 1;
690
742
  const match = stringInfo.matches[arrayIndex];
691
743
  return match ? match.length : undefined;
@@ -697,8 +749,8 @@ export class ConditionEvaluator {
697
749
  evaluateAll(items) {
698
750
  const identifiers = this.resolveStringSet(items);
699
751
  if (identifiers.length === 0) return false;
700
-
701
- return identifiers.every(id => {
752
+
753
+ return identifiers.every((id) => {
702
754
  const stringInfo = this.strings[id];
703
755
  return stringInfo && stringInfo.matched && stringInfo.count > 0;
704
756
  });
@@ -710,8 +762,8 @@ export class ConditionEvaluator {
710
762
  evaluateAny(items) {
711
763
  const identifiers = this.resolveStringSet(items);
712
764
  if (identifiers.length === 0) return false;
713
-
714
- return identifiers.some(id => {
765
+
766
+ return identifiers.some((id) => {
715
767
  const stringInfo = this.strings[id];
716
768
  return stringInfo && stringInfo.matched && stringInfo.count > 0;
717
769
  });
@@ -723,8 +775,8 @@ export class ConditionEvaluator {
723
775
  evaluateNone(items) {
724
776
  const identifiers = this.resolveStringSet(items);
725
777
  if (identifiers.length === 0) return true;
726
-
727
- return identifiers.every(id => {
778
+
779
+ return identifiers.every((id) => {
728
780
  const stringInfo = this.strings[id];
729
781
  return !stringInfo || !stringInfo.matched || stringInfo.count === 0;
730
782
  });
@@ -736,25 +788,25 @@ export class ConditionEvaluator {
736
788
  evaluateQuantified(node) {
737
789
  const identifiers = this.resolveStringSet(node.items);
738
790
  if (identifiers.length === 0) return false;
739
-
740
- const matchCount = identifiers.filter(id => {
791
+
792
+ const matchCount = identifiers.filter((id) => {
741
793
  const stringInfo = this.strings[id];
742
794
  return stringInfo && stringInfo.matched && stringInfo.count > 0;
743
795
  }).length;
744
796
 
745
797
  const quantifier = node.quantifier;
746
-
747
- if (quantifier.type === 'number') {
798
+
799
+ if (quantifier.type === "number") {
748
800
  return matchCount >= quantifier.value;
749
- } else if (quantifier.type === 'percentage') {
750
- const required = Math.ceil(identifiers.length * quantifier.value / 100);
801
+ } else if (quantifier.type === "percentage") {
802
+ const required = Math.ceil((identifiers.length * quantifier.value) / 100);
751
803
  return matchCount >= required;
752
- } else if (quantifier.type === 'range') {
804
+ } else if (quantifier.type === "range") {
753
805
  const min = quantifier.min;
754
806
  const max = quantifier.max;
755
807
  return matchCount >= min && matchCount <= max;
756
808
  }
757
-
809
+
758
810
  return false;
759
811
  }
760
812
 
@@ -762,19 +814,19 @@ export class ConditionEvaluator {
762
814
  * Resolve string set (e.g., 'them', '$a*', '($a, $b, $c)')
763
815
  */
764
816
  resolveStringSet(items) {
765
- if (items === 'them') {
817
+ if (items === "them") {
766
818
  return Object.keys(this.strings);
767
819
  }
768
-
820
+
769
821
  if (Array.isArray(items)) {
770
822
  // Process each item in the array, expanding wildcards
771
823
  const resolved = [];
772
824
  for (const item of items) {
773
- if (item.includes('*')) {
825
+ if (item.includes("*")) {
774
826
  // Expand wildcard pattern
775
- const pattern = item.replace(/\*/g, '.*').replace(/\$/g, '\\$');
776
- const regex = new RegExp('^' + pattern + '$');
777
- const matches = Object.keys(this.strings).filter(id => regex.test(id));
827
+ const pattern = item.replace(/\*/g, ".*").replace(/\$/g, "\\$");
828
+ const regex = new RegExp("^" + pattern + "$");
829
+ const matches = Object.keys(this.strings).filter((id) => regex.test(id));
778
830
  resolved.push(...matches);
779
831
  } else {
780
832
  resolved.push(item);
@@ -782,17 +834,17 @@ export class ConditionEvaluator {
782
834
  }
783
835
  return resolved;
784
836
  }
785
-
786
- if (typeof items === 'string') {
837
+
838
+ if (typeof items === "string") {
787
839
  // Handle wildcard patterns like '$a*'
788
- if (items.includes('*')) {
789
- const pattern = items.replace(/\*/g, '.*').replace(/\$/g, '\\$');
790
- const regex = new RegExp('^' + pattern + '$');
791
- return Object.keys(this.strings).filter(id => regex.test(id));
840
+ if (items.includes("*")) {
841
+ const pattern = items.replace(/\*/g, ".*").replace(/\$/g, "\\$");
842
+ const regex = new RegExp("^" + pattern + "$");
843
+ return Object.keys(this.strings).filter((id) => regex.test(id));
792
844
  }
793
845
  return [items];
794
846
  }
795
-
847
+
796
848
  return [];
797
849
  }
798
850
 
@@ -810,31 +862,31 @@ export class ConditionEvaluator {
810
862
  const condition = node.condition; // condition to evaluate
811
863
 
812
864
  let items = [];
813
-
814
- if (set.type === 'stringSet') {
865
+
866
+ if (set.type === "stringSet") {
815
867
  // Iterating over string identifiers
816
868
  items = this.resolveStringSet(set.items);
817
-
869
+
818
870
  if (items.length === 0) {
819
871
  // For "all", empty set means true; for "any", empty set means false
820
- if (quantifier === 'all') return true;
872
+ if (quantifier === "all") return true;
821
873
  return false;
822
874
  }
823
- } else if (set.type === 'range') {
875
+ } else if (set.type === "range") {
824
876
  // Iterating over numeric range
825
877
  const startVal = await this.evaluateNode(set.start);
826
878
  const endVal = await this.evaluateNode(set.end);
827
-
828
- if (typeof startVal !== 'number' || typeof endVal !== 'number') {
879
+
880
+ if (typeof startVal !== "number" || typeof endVal !== "number") {
829
881
  throw new Error(`Invalid range values: ${startVal} to ${endVal}`);
830
882
  }
831
-
883
+
832
884
  for (let i = startVal; i <= endVal; i++) {
833
885
  items.push(i);
834
886
  }
835
-
887
+
836
888
  if (items.length === 0) {
837
- if (quantifier === 'all') return true;
889
+ if (quantifier === "all") return true;
838
890
  return false;
839
891
  }
840
892
  } else {
@@ -849,19 +901,19 @@ export class ConditionEvaluator {
849
901
 
850
902
  if (items.length === 0) {
851
903
  // Empty set: "all" is vacuously true, others are false
852
- if (quantifier === 'all') return true;
904
+ if (quantifier === "all") return true;
853
905
  return false;
854
906
  }
855
907
 
856
908
  // Store original context
857
909
  const originalContext = this.forContext || {};
858
-
910
+
859
911
  // Evaluate condition for each item (sequentially to maintain order)
860
912
  const results = [];
861
913
  for (const item of items) {
862
914
  // Set the iterator variable in the context
863
915
  this.forContext = { ...originalContext, [variable]: item };
864
-
916
+
865
917
  try {
866
918
  // Evaluate the condition with the current item
867
919
  const result = await this.evaluateNode(condition);
@@ -872,27 +924,27 @@ export class ConditionEvaluator {
872
924
  results.push(false);
873
925
  }
874
926
  }
875
-
927
+
876
928
  // Restore original context
877
929
  this.forContext = originalContext;
878
930
 
879
931
  // Apply quantifier to results
880
- const trueCount = results.filter(r => r).length;
881
-
882
- if (quantifier === 'any') {
932
+ const trueCount = results.filter((r) => r).length;
933
+
934
+ if (quantifier === "any") {
883
935
  return trueCount > 0;
884
- } else if (quantifier === 'all') {
936
+ } else if (quantifier === "all") {
885
937
  return trueCount === items.length;
886
- } else if (quantifier === 'none') {
938
+ } else if (quantifier === "none") {
887
939
  return trueCount === 0;
888
- } else if (typeof quantifier === 'number') {
940
+ } else if (typeof quantifier === "number") {
889
941
  // Exact count: "2 of them" means at least 2
890
942
  return trueCount >= quantifier;
891
- } else if (quantifier && quantifier.type === 'percentage') {
943
+ } else if (quantifier && quantifier.type === "percentage") {
892
944
  // Percentage: "50% of them" means at least 50%
893
- const required = Math.ceil(items.length * quantifier.value / 100);
945
+ const required = Math.ceil((items.length * quantifier.value) / 100);
894
946
  return trueCount >= required;
895
- } else if (quantifier && quantifier.type === 'number') {
947
+ } else if (quantifier && quantifier.type === "number") {
896
948
  // Number from object
897
949
  return trueCount >= quantifier.value;
898
950
  }
@@ -911,7 +963,7 @@ export class ConditionEvaluator {
911
963
  return undefined;
912
964
  }
913
965
 
914
- if (typeof property === 'string') {
966
+ if (typeof property === "string") {
915
967
  return obj[property];
916
968
  } else {
917
969
  // Computed property access
@@ -937,7 +989,7 @@ export class ConditionEvaluator {
937
989
 
938
990
  // Handle negative indices (not standard in YARA but useful)
939
991
  const actualIndex = index < 0 ? obj.length + index : index;
940
-
992
+
941
993
  if (actualIndex < 0 || actualIndex >= obj.length) {
942
994
  return undefined;
943
995
  }
@@ -950,9 +1002,9 @@ export class ConditionEvaluator {
950
1002
  */
951
1003
  async evaluateFunctionCall(node) {
952
1004
  const func = await this.evaluateNode(node.function);
953
- const args = await Promise.all(node.arguments.map(arg => this.evaluateNode(arg)));
1005
+ const args = await Promise.all(node.arguments.map((arg) => this.evaluateNode(arg)));
954
1006
 
955
- if (typeof func !== 'function') {
1007
+ if (typeof func !== "function") {
956
1008
  throw new Error(`Not a function: ${node.function}`);
957
1009
  }
958
1010
 
@@ -967,28 +1019,28 @@ export class ConditionEvaluator {
967
1019
  async evaluateDataAccess(node) {
968
1020
  const offset = await this.evaluateNode(node.offset);
969
1021
  const dataType = node.dataType;
970
- const endian = node.endian || 'little'; // 'little' or 'big'
1022
+ const endian = node.endian || "little"; // 'little' or 'big'
971
1023
 
972
1024
  if (offset < 0 || offset >= this.data.length) {
973
1025
  return undefined;
974
1026
  }
975
1027
 
976
1028
  const view = new DataView(this.data.buffer, this.data.byteOffset, this.data.byteLength);
977
- const littleEndian = endian === 'little';
1029
+ const littleEndian = endian === "little";
978
1030
 
979
1031
  try {
980
1032
  switch (dataType) {
981
- case 'uint8':
1033
+ case "uint8":
982
1034
  return view.getUint8(offset);
983
- case 'uint16':
1035
+ case "uint16":
984
1036
  return view.getUint16(offset, littleEndian);
985
- case 'uint32':
1037
+ case "uint32":
986
1038
  return view.getUint32(offset, littleEndian);
987
- case 'int8':
1039
+ case "int8":
988
1040
  return view.getInt8(offset);
989
- case 'int16':
1041
+ case "int16":
990
1042
  return view.getInt16(offset, littleEndian);
991
- case 'int32':
1043
+ case "int32":
992
1044
  return view.getInt32(offset, littleEndian);
993
1045
  default:
994
1046
  throw new Error(`Unknown data type: ${dataType}`);
@@ -1019,18 +1071,18 @@ export class ConditionEvaluator {
1019
1071
  */
1020
1072
  async evaluateAt(node) {
1021
1073
  let identifier = node.identifier;
1022
-
1074
+
1023
1075
  // Handle string literal nodes (e.g., "PDF" at 0)
1024
- if (typeof identifier === 'object' && identifier.type === 'string') {
1076
+ if (typeof identifier === "object" && identifier.type === "string") {
1025
1077
  const offset = await this.evaluateNode(node.offset);
1026
1078
  const stringValue = identifier.value;
1027
1079
  const stringBytes = new TextEncoder().encode(stringValue);
1028
-
1080
+
1029
1081
  // Check if the string exists at the specified offset
1030
1082
  if (offset < 0 || offset + stringBytes.length > this.data.length) {
1031
1083
  return false;
1032
1084
  }
1033
-
1085
+
1034
1086
  // Compare byte by byte
1035
1087
  for (let i = 0; i < stringBytes.length; i++) {
1036
1088
  if (this.data[offset + i] !== stringBytes[i]) {
@@ -1039,12 +1091,12 @@ export class ConditionEvaluator {
1039
1091
  }
1040
1092
  return true;
1041
1093
  }
1042
-
1094
+
1043
1095
  // In for loops with string iteration, '$' refers to the current string
1044
- if (identifier === '$' && this.forContext && this.forContext['$']) {
1045
- identifier = this.forContext['$'];
1096
+ if (identifier === "$" && this.forContext && this.forContext["$"]) {
1097
+ identifier = this.forContext["$"];
1046
1098
  }
1047
-
1099
+
1048
1100
  const offset = await this.evaluateNode(node.offset);
1049
1101
  const stringInfo = this.strings[identifier];
1050
1102
 
@@ -1061,12 +1113,12 @@ export class ConditionEvaluator {
1061
1113
  */
1062
1114
  async evaluateInRange(node) {
1063
1115
  let identifier = node.identifier;
1064
-
1116
+
1065
1117
  // In for loops with string iteration, '$' refers to the current string
1066
- if (identifier === '$' && this.forContext && this.forContext['$']) {
1067
- identifier = this.forContext['$'];
1118
+ if (identifier === "$" && this.forContext && this.forContext["$"]) {
1119
+ identifier = this.forContext["$"];
1068
1120
  }
1069
-
1121
+
1070
1122
  const range = await this.evaluateNode(node.range);
1071
1123
  const stringInfo = this.strings[identifier];
1072
1124
 
@@ -1074,21 +1126,19 @@ export class ConditionEvaluator {
1074
1126
  return false;
1075
1127
  }
1076
1128
 
1077
- return stringInfo.offsets.some(offset =>
1078
- offset >= range.start && offset <= range.end
1079
- );
1129
+ return stringInfo.offsets.some((offset) => offset >= range.start && offset <= range.end);
1080
1130
  }
1081
1131
 
1082
1132
  /**
1083
1133
  * Evaluate 'within' expression ($a within N of $b)
1084
1134
  * Checks if any occurrence of $a is within N bytes of any occurrence of $b
1085
- *
1135
+ *
1086
1136
  * Distance is measured from start offset to start offset (YARA standard behavior).
1087
1137
  * Returns true if the absolute distance between any pair of matches is <= N.
1088
- *
1138
+ *
1089
1139
  * @param {Object} node - AST node with identifier, distance, reference
1090
1140
  * @returns {Promise<boolean>} True if any match is within distance
1091
- *
1141
+ *
1092
1142
  * TODO: Performance optimization needed for large match sets
1093
1143
  * - Current O(n*m) complexity could be slow with many matches
1094
1144
  * - Consider: early termination, sorted offset arrays with binary search,
@@ -1097,19 +1147,19 @@ export class ConditionEvaluator {
1097
1147
  async evaluateWithin(node) {
1098
1148
  let identifier = node.identifier;
1099
1149
  let reference = node.reference;
1100
-
1150
+
1101
1151
  // Handle for-loop context: if identifier is '$', use current loop variable
1102
- if (identifier === '$' && this.forContext && this.forContext['$']) {
1103
- identifier = this.forContext['$'];
1152
+ if (identifier === "$" && this.forContext && this.forContext["$"]) {
1153
+ identifier = this.forContext["$"];
1104
1154
  }
1105
- if (reference === '$' && this.forContext && this.forContext['$']) {
1106
- reference = this.forContext['$'];
1155
+ if (reference === "$" && this.forContext && this.forContext["$"]) {
1156
+ reference = this.forContext["$"];
1107
1157
  }
1108
-
1158
+
1109
1159
  const distance = await this.evaluateNode(node.distance);
1110
1160
  const stringInfo = this.strings[identifier];
1111
1161
  const refInfo = this.strings[reference];
1112
-
1162
+
1113
1163
  // Handle missing/empty matches - return false if either string has no matches
1114
1164
  if (!stringInfo || !stringInfo.offsets || stringInfo.offsets.length === 0) {
1115
1165
  return false;
@@ -1117,7 +1167,7 @@ export class ConditionEvaluator {
1117
1167
  if (!refInfo || !refInfo.offsets || refInfo.offsets.length === 0) {
1118
1168
  return false;
1119
1169
  }
1120
-
1170
+
1121
1171
  // Check if any occurrence of identifier is within distance of any occurrence of reference
1122
1172
  // YARA measures distance from start offset to start offset (not considering match lengths)
1123
1173
  // TODO: Performance - consider optimizing this nested loop for large match sets
@@ -1129,7 +1179,7 @@ export class ConditionEvaluator {
1129
1179
  }
1130
1180
  }
1131
1181
  }
1132
-
1182
+
1133
1183
  return false;
1134
1184
  }
1135
1185
 
@@ -1138,7 +1188,7 @@ export class ConditionEvaluator {
1138
1188
  */
1139
1189
  async evaluateModuleFunction(node) {
1140
1190
  const { module, function: functionName, args } = node;
1141
-
1191
+
1142
1192
  // Get the module from available modules
1143
1193
  const moduleObj = this.modules[module];
1144
1194
  if (!moduleObj) {
@@ -1146,46 +1196,48 @@ export class ConditionEvaluator {
1146
1196
  // This allows conditions like "pe.imports(...)" to evaluate to undefined/false
1147
1197
  return undefined;
1148
1198
  }
1149
-
1199
+
1150
1200
  // Get the function from the module
1151
1201
  const func = moduleObj[functionName];
1152
- if (typeof func !== 'function') {
1202
+ if (typeof func !== "function") {
1153
1203
  // Return undefined if function not found in module
1154
1204
  return undefined;
1155
1205
  }
1156
-
1206
+
1157
1207
  // Evaluate arguments
1158
- const evaluatedArgs = await Promise.all(args.map(async arg => {
1159
- const result = await this.evaluateNode(arg);
1160
-
1161
- // For string identifiers, get the actual matched string value
1162
- if (arg.type === 'stringIdentifier') {
1163
- const stringInfo = this.strings[arg.identifier];
1164
- if (stringInfo && stringInfo.matches && stringInfo.matches.length > 0) {
1165
- // Get the first match value
1166
- const match = stringInfo.matches[0];
1167
- if (match.value) {
1168
- return match.value;
1169
- }
1170
- // If no value stored, try to extract from data
1171
- if (this.data && match.offset !== undefined && match.length !== undefined) {
1172
- const bytes = this.data.slice(match.offset, match.offset + match.length);
1173
- return new TextDecoder().decode(bytes);
1208
+ const evaluatedArgs = await Promise.all(
1209
+ args.map(async (arg) => {
1210
+ const result = await this.evaluateNode(arg);
1211
+
1212
+ // For string identifiers, get the actual matched string value
1213
+ if (arg.type === "stringIdentifier") {
1214
+ const stringInfo = this.strings[arg.identifier];
1215
+ if (stringInfo && stringInfo.matches && stringInfo.matches.length > 0) {
1216
+ // Get the first match value
1217
+ const match = stringInfo.matches[0];
1218
+ if (match.value) {
1219
+ return match.value;
1220
+ }
1221
+ // If no value stored, try to extract from data
1222
+ if (this.data && match.offset !== undefined && match.length !== undefined) {
1223
+ const bytes = this.data.slice(match.offset, match.offset + match.length);
1224
+ return new TextDecoder().decode(bytes);
1225
+ }
1174
1226
  }
1227
+ return "";
1175
1228
  }
1176
- return '';
1177
- }
1178
-
1179
- return result;
1180
- }));
1181
-
1229
+
1230
+ return result;
1231
+ }),
1232
+ );
1233
+
1182
1234
  // Call the function with evaluated arguments
1183
1235
  try {
1184
1236
  const result = func.apply(moduleObj, evaluatedArgs);
1185
1237
  // Handle both sync and async module functions
1186
1238
  return result instanceof Promise ? await result : result;
1187
1239
  } catch (error) {
1188
- throw new Error(`Error calling ${module}.${functionName}: ${error.message}`);
1240
+ throw new Error(`Error calling ${module}.${functionName}: ${error.message}`, { cause: error });
1189
1241
  }
1190
1242
  }
1191
1243
 
@@ -1201,7 +1253,7 @@ export class ConditionEvaluator {
1201
1253
 
1202
1254
  if (Array.isArray(set)) {
1203
1255
  return set.includes(value);
1204
- } else if (set && typeof set === 'object' && set.start !== undefined && set.end !== undefined) {
1256
+ } else if (set && typeof set === "object" && set.start !== undefined && set.end !== undefined) {
1205
1257
  // Range
1206
1258
  return value >= set.start && value <= set.end;
1207
1259
  }
@@ -1219,7 +1271,7 @@ export class ConditionEvaluator {
1219
1271
  // YARA: string operators return undefined if operands are undefined
1220
1272
  if (this.isAnyUndefined(left, right)) return undefined;
1221
1273
 
1222
- if (typeof left !== 'string' || typeof right !== 'string') {
1274
+ if (typeof left !== "string" || typeof right !== "string") {
1223
1275
  return false;
1224
1276
  }
1225
1277
 
@@ -1241,7 +1293,7 @@ export class ConditionEvaluator {
1241
1293
  // YARA: string operators return undefined if operands are undefined
1242
1294
  if (this.isAnyUndefined(left, right)) return undefined;
1243
1295
 
1244
- if (typeof left !== 'string' || typeof right !== 'string') {
1296
+ if (typeof left !== "string" || typeof right !== "string") {
1245
1297
  return false;
1246
1298
  }
1247
1299
 
@@ -1263,7 +1315,7 @@ export class ConditionEvaluator {
1263
1315
  // YARA: string operators return undefined if operands are undefined
1264
1316
  if (this.isAnyUndefined(left, right)) return undefined;
1265
1317
 
1266
- if (typeof left !== 'string' || typeof right !== 'string') {
1318
+ if (typeof left !== "string" || typeof right !== "string") {
1267
1319
  return false;
1268
1320
  }
1269
1321
 
@@ -1285,7 +1337,7 @@ export class ConditionEvaluator {
1285
1337
  // YARA: string operators return undefined if operands are undefined
1286
1338
  if (this.isAnyUndefined(left, right)) return undefined;
1287
1339
 
1288
- if (typeof left !== 'string' || typeof right !== 'string') {
1340
+ if (typeof left !== "string" || typeof right !== "string") {
1289
1341
  return false;
1290
1342
  }
1291
1343
 
@@ -1307,20 +1359,17 @@ export class ConditionEvaluator {
1307
1359
  // YARA: string operators return undefined if operands are undefined
1308
1360
  if (this.isAnyUndefined(left, right)) return undefined;
1309
1361
 
1310
- if (typeof left !== 'string') {
1311
- return false;
1362
+ // The pattern must come from rule text. Compiling a value that was produced during the scan
1363
+ // would allow arbitrary patterns (catastrophic backtracking), so it is rejected outright.
1364
+ if (!(right instanceof RegExp)) {
1365
+ throw new Error(`"matches" requires a regex literal as its right operand, got ${typeof right}`);
1312
1366
  }
1313
1367
 
1314
- let regex;
1315
- if (right instanceof RegExp) {
1316
- regex = right;
1317
- } else if (typeof right === 'string') {
1318
- regex = new RegExp(right);
1319
- } else {
1368
+ if (typeof left !== "string") {
1320
1369
  return false;
1321
1370
  }
1322
1371
 
1323
- return regex.test(left);
1372
+ return right.test(left);
1324
1373
  }
1325
1374
  }
1326
1375
 
@@ -1351,13 +1400,13 @@ export async function evaluateRules(rules, scanFacts) {
1351
1400
  results.push({
1352
1401
  rule: rule.name || rule.id,
1353
1402
  matched,
1354
- error: null
1403
+ error: null,
1355
1404
  });
1356
1405
  } catch (error) {
1357
1406
  results.push({
1358
1407
  rule: rule.name || rule.id,
1359
1408
  matched: false,
1360
- error: error.message
1409
+ error: error.message,
1361
1410
  });
1362
1411
  }
1363
1412
  }
@@ -1369,5 +1418,5 @@ export default {
1369
1418
  createScanFacts,
1370
1419
  ConditionEvaluator,
1371
1420
  evaluateCondition,
1372
- evaluateRules
1421
+ evaluateRules,
1373
1422
  };