sekant-intercept-js 1.0.1 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sekant-intercept-js",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "Context-Aware YARA Runtime Detection for JavaScript Environments",
5
5
  "main": "./dist/sekant-intercept.node.mjs",
6
6
  "exports": {
@@ -208,9 +208,13 @@ export class InterceptScanner {
208
208
  const strDef = rule.strings[candidate.varName];
209
209
  if (!strDef || !strDef.matcher) continue;
210
210
 
211
- // For text and regex with literal prefix, verify at the candidate offset
211
+ // For text and regex with literal prefix, verify at the candidate offset. `verifyAt` demands
212
+ // a match starting exactly there; the plain window-scan form would also return a neighbouring
213
+ // occurrence, which duplicates that match and loses this candidate's own.
212
214
  if (strDef.type === "text" || (strDef.type === "regex" && strDef.literalPrefix)) {
213
- const matches = strDef.matcher(data, candidate.offset);
215
+ const matches = typeof strDef.matcher.verifyAt === "function"
216
+ ? strDef.matcher.verifyAt(data, candidate.offset)
217
+ : strDef.matcher(data, candidate.offset);
214
218
  if (matches && matches.length > 0) {
215
219
  verified.push({
216
220
  ...candidate,
@@ -416,6 +420,9 @@ export class InterceptScanner {
416
420
 
417
421
  // Initialize custom modules from this.modules
418
422
  // Check each module to see if it's a custom module (has getName() method and non-reserved name)
423
+ // `modulesWithBinary` already holds the same instances under their registration keys, so the
424
+ // collision that matters is two *custom* modules claiming one keyword — tracked separately.
425
+ const claimedKeywords = new Set();
419
426
  for (const [key, moduleValue] of Object.entries(this.modules)) {
420
427
  try {
421
428
  // Check if this is a custom module by seeing if it has the custom module interface
@@ -461,6 +468,14 @@ export class InterceptScanner {
461
468
  tracker.accumulateModule(modulesTiming, moduleName, tracker.now() - moduleStart);
462
469
  }
463
470
 
471
+ // Conditions reach a custom module by the keyword its `getName()` returns — the key it was
472
+ // registered under is irrelevant. Two instances sharing a name therefore overwrite each
473
+ // other, and the rule silently reads the wrong URL/facts. Say so once per scan.
474
+ if (claimedKeywords.has(moduleName)) {
475
+ console.warn(`InterceptScanner: duplicate custom module name "${moduleName}" - the later instance replaces the earlier one`);
476
+ }
477
+ claimedKeywords.add(moduleName);
478
+
464
479
  // Add to modules available for condition evaluation
465
480
  modulesWithBinary[moduleName] = moduleObject;
466
481
  }
@@ -37,22 +37,8 @@
37
37
 
38
38
  // Constants
39
39
  const PLACEHOLDER_PREFIX = '__LITERAL_';
40
+ const REGEX_PLACEHOLDER_PREFIX = '__REGEX_';
40
41
  const PLACEHOLDER_SUFFIX = '__';
41
- const STRING_WILDCARD_VAR = '$';
42
-
43
- const KEYWORD_LITERALS = {
44
- TRUE: 'true',
45
- FALSE: 'false',
46
- FILESIZE: 'filesize',
47
- ENTRYPOINT: 'entrypoint'
48
- };
49
-
50
- const QUANTIFIER_KEYWORDS = {
51
- ALL: 'all',
52
- ANY: 'any',
53
- NONE: 'none',
54
- THEM: 'them'
55
- };
56
42
 
57
43
  // Data access type definitions
58
44
  const DATA_ACCESS_TYPES = [
@@ -68,33 +54,6 @@ const DATA_ACCESS_TYPES = [
68
54
  { name: 'int32be', bits: 32, signed: true, endian: 'big' }
69
55
  ];
70
56
 
71
- // Operator registry
72
- const OPERATOR_REGISTRY = {
73
- string: [
74
- { pattern: 'icontains', type: 'icontains' },
75
- { pattern: 'contains', type: 'contains' },
76
- { pattern: 'istartswith', type: 'istartswith' },
77
- { pattern: 'startswith', type: 'startswith' },
78
- { pattern: 'iendswith', type: 'iendswith' },
79
- { pattern: 'endswith', type: 'endswith' }
80
- ],
81
- comparison: [
82
- { pattern: '==', type: 'equal' },
83
- { pattern: '!=', type: 'notEqual' },
84
- { pattern: '<=', type: 'lessThanOrEqual' },
85
- { pattern: '>=', type: 'greaterThanOrEqual' },
86
- { pattern: '<', type: 'lessThan' },
87
- { pattern: '>', type: 'greaterThan' }
88
- ],
89
- arithmetic: [
90
- { pattern: '+', type: 'add' },
91
- { pattern: '-', type: 'subtract' },
92
- { pattern: '*', type: 'multiply' },
93
- { pattern: '\\', type: 'divide' },
94
- { pattern: '%', type: 'modulo' }
95
- ]
96
- };
97
-
98
57
  /**
99
58
  * Utility: Skip whitespace in a string starting from a given index
100
59
  * @param {string} str - String to process
@@ -107,22 +66,6 @@ function skipWhitespace(str, startIndex) {
107
66
  return index;
108
67
  }
109
68
 
110
- /**
111
- * Utility: Find matching closing parenthesis
112
- * @param {string} str - String to search
113
- * @param {number} startIndex - Index of opening paren
114
- * @returns {number} Index of closing paren, or -1 if not found
115
- */
116
- function findMatchingParen(str, startIndex) {
117
- let depth = 1;
118
- let index = startIndex + 1;
119
- while (index < str.length && depth > 0) {
120
- if (str[index] === '(') depth++;
121
- if (str[index] === ')') depth--;
122
- index++;
123
- }
124
- return depth === 0 ? index : -1;
125
- }
126
69
 
127
70
  /**
128
71
  * Utility: Check if parentheses wrap the entire expression
@@ -141,107 +84,256 @@ function wrapsEntireExpression(expr) {
141
84
  }
142
85
 
143
86
  /**
144
- * Check if a string has unescaped quotes in the middle
145
- * @param {string} str - String to check (including outer quotes)
146
- * @param {string} quoteChar - Quote character to look for (" or ')
147
- * @returns {boolean} True if there are unescaped quotes in the middle
87
+ * Find the closing quote of a string literal, honouring backslash escapes.
88
+ *
89
+ * @param {string} text
90
+ * @param {number} start - index of the opening quote
91
+ * @param {string} quoteChar - `"` or `'`
92
+ * @returns {number} index of the closing quote, or -1 when unterminated
148
93
  */
149
- function hasUnescapedQuotesInMiddle(str, quoteChar) {
94
+ function findClosingQuote(text, start, quoteChar) {
150
95
  let escaped = false;
151
-
152
- // Check from position 1 to length-1 (excluding outer quotes)
153
- for (let i = 1; i < str.length - 1; i++) {
96
+ for (let i = start + 1; i < text.length; i++) {
97
+ const char = text[i];
154
98
  if (escaped) {
155
99
  escaped = false;
156
100
  continue;
157
101
  }
158
- if (str[i] === '\\') {
102
+ if (char === '\\') {
159
103
  escaped = true;
160
104
  continue;
161
105
  }
162
- if (str[i] === quoteChar) {
163
- return true; // Found unescaped quote in middle
106
+ if (char === quoteChar) return i;
107
+ }
108
+ return -1;
109
+ }
110
+
111
+ /**
112
+ * Scan a regex literal starting at `start` (a `/`).
113
+ * Returns null when the text is not a regex literal — an unterminated slash, an empty `//`, or a
114
+ * newline before the closing slash (which in a rule means the author wrote prose, not a pattern).
115
+ *
116
+ * @param {string} text
117
+ * @param {number} start - index of the opening `/`
118
+ * @returns {{pattern: string, flags: string, end: number}|null}
119
+ */
120
+ function scanRegexLiteral(text, start) {
121
+ let body = '';
122
+ let inClass = false;
123
+ let escaped = false;
124
+
125
+ for (let i = start + 1; i < text.length; i++) {
126
+ const char = text[i];
127
+ if (escaped) {
128
+ body += char;
129
+ escaped = false;
130
+ continue;
164
131
  }
132
+ if (char === '\\') {
133
+ body += char;
134
+ escaped = true;
135
+ continue;
136
+ }
137
+ if (char === '\n') return null;
138
+ if (char === '[') inClass = true;
139
+ else if (char === ']') inClass = false;
140
+ else if (char === '/' && !inClass) {
141
+ if (!body) return null; // `//` is not a pattern
142
+ let end = i + 1;
143
+ let flags = '';
144
+ while (end < text.length && /[a-z]/.test(text[end])) {
145
+ flags += text[end];
146
+ end += 1;
147
+ }
148
+ return { pattern: body, flags, end };
149
+ }
150
+ body += char;
165
151
  }
166
-
167
- return false;
152
+
153
+ return null;
168
154
  }
169
155
 
156
+ // YARA only defines the `i` and `s` regex modifiers (writingrules.html#regular-expressions)
157
+ const YARA_REGEX_FLAGS = new Set(['i', 's']);
158
+
170
159
  /**
171
- * Validate if a string is a properly quoted string literal
172
- * @param {string} str - String to validate (including outer quotes)
173
- * @param {string} quoteChar - Quote character used (" or ')
174
- * @returns {boolean} True if valid string literal
160
+ * Check that a scanned regex literal can actually be compiled.
161
+ *
162
+ * @param {string} pattern
163
+ * @param {string} flags
164
+ * @returns {string|null} reason the literal is unusable, or null when valid
175
165
  */
176
- function isValidStringLiteral(str, quoteChar) {
177
- // Empty string is valid
178
- if (str.length === 2) {
179
- return true;
166
+ function validateRegexLiteral(pattern, flags) {
167
+ const unsupported = [...new Set(flags)].filter((flag) => !YARA_REGEX_FLAGS.has(flag));
168
+ if (unsupported.length > 0) {
169
+ return `unsupported flag(s) "${unsupported.join('')}" (YARA allows only "i" and "s")`;
180
170
  }
181
-
182
- // Check for unescaped quotes in the middle
183
- return !hasUnescapedQuotesInMiddle(str, quoteChar);
171
+ try {
172
+ new RegExp(pattern, flags);
173
+ } catch (error) {
174
+ return error.message;
175
+ }
176
+ return null;
184
177
  }
185
178
 
186
179
  /**
187
- * Extract string literals from condition and replace with placeholders
188
- * Phase 1 of parsing: removes string literals to avoid confusion with operators
189
- *
180
+ * Find the end (exclusive) of a comment that starts at `start` (`//` or `/*`).
181
+ * Comments are stripped by the rule compiler, so this only keeps the parser from misreading
182
+ * comment text when a caller hands it a raw condition.
183
+ *
184
+ * @param {string} text
185
+ * @param {number} start - index of the opening `/`
186
+ * @returns {number} index just past the comment
187
+ */
188
+ function findCommentEnd(text, start) {
189
+ if (text[start + 1] === '/') {
190
+ const newline = text.indexOf('\n', start + 2);
191
+ return newline === -1 ? text.length : newline;
192
+ }
193
+ const close = text.indexOf('*/', start + 2);
194
+ return close === -1 ? text.length : close + 2;
195
+ }
196
+
197
+ /**
198
+ * Replace string and regex literals with identifiers before the structure is parsed.
199
+ * Phase 1 of parsing: without this, `^`, `/` and ` and ` inside a pattern would be read as
200
+ * operators (`^` is bitwise-XOR and `and` is logical AND in this grammar; division is `\`, so a
201
+ * `/` outside a literal is always a mistake).
202
+ *
203
+ * String literals go first in the walk, so a `/` inside `"http://host/path"` never starts a
204
+ * regex, and a quote inside `/[a-z"]+/` never starts a string.
205
+ *
190
206
  * @param {string} condition - Raw condition string
191
- * @returns {Object} { processed: string with placeholders, literals: array of literal info }
207
+ * @returns {Object} { processed, literals } — literals carry { id, type: 'string'|'regex', … }
192
208
  */
193
- function extractStringLiterals(condition) {
209
+ function extractLiterals(condition) {
194
210
  const literals = [];
195
- let processed = condition;
196
- let counter = 0;
197
-
198
- /**
199
- * Helper to extract strings with a specific quote character
200
- * @param {string} text - Text to process
201
- * @param {string} quoteChar - Quote character (" or ')
202
- * @returns {string} Processed text with placeholders
203
- */
204
- const extractQuoted = (text, quoteChar) => {
205
- const regex = new RegExp(`${quoteChar}(?:[^${quoteChar}\\\\]|\\\\.)*${quoteChar}`, 'g');
206
- return text.replace(regex, (match) => {
207
- if (isValidStringLiteral(match, quoteChar)) {
208
- const placeholder = `${PLACEHOLDER_PREFIX}${counter}${PLACEHOLDER_SUFFIX}`;
209
- literals.push({
210
- id: placeholder,
211
- type: 'string',
212
- value: match.slice(1, -1) // Remove quotes
213
- });
214
- counter++;
215
- return placeholder;
216
- }
217
- return match; // Keep as-is if invalid
218
- });
211
+ const chunks = [];
212
+ let stringCount = 0;
213
+ let regexCount = 0;
214
+ let straySlashWarned = false;
215
+ let chunkStart = 0;
216
+ let i = 0;
217
+
218
+ // Append the untouched run of text that ends at `end`, then start a new run there.
219
+ const flush = (end) => {
220
+ chunks.push(condition.slice(chunkStart, end));
221
+ chunkStart = end;
219
222
  };
220
-
221
- // Extract double-quoted strings, then single-quoted strings
222
- processed = extractQuoted(processed, '"');
223
- processed = extractQuoted(processed, "'");
224
-
225
- return { processed, literals };
223
+
224
+ while (i < condition.length) {
225
+ const char = condition[i];
226
+
227
+ if (char === '"' || char === "'") {
228
+ const end = findClosingQuote(condition, i, char);
229
+ if (end !== -1) {
230
+ const id = `${PLACEHOLDER_PREFIX}${stringCount}${PLACEHOLDER_SUFFIX}`;
231
+ literals.push({ id, type: 'string', value: condition.slice(i + 1, end) });
232
+ stringCount += 1;
233
+ flush(i);
234
+ chunks.push(id);
235
+ i = end + 1;
236
+ chunkStart = i;
237
+ continue;
238
+ }
239
+ i += 1; // Unterminated quote: leave the text alone and let the parser cope.
240
+ continue;
241
+ }
242
+
243
+ if (char === '/') {
244
+ const marker = condition[i + 1];
245
+ if (marker === '/' || marker === '*') {
246
+ i = findCommentEnd(condition, i);
247
+ continue;
248
+ }
249
+
250
+ const regex = scanRegexLiteral(condition, i);
251
+ if (regex) {
252
+ const id = `${REGEX_PLACEHOLDER_PREFIX}${regexCount}${PLACEHOLDER_SUFFIX}`;
253
+ const error = validateRegexLiteral(regex.pattern, regex.flags);
254
+ if (error) {
255
+ console.warn(`yaraConditionParser: invalid regex literal /${regex.pattern}/${regex.flags} - ${error}`);
256
+ }
257
+ literals.push({ id, type: 'regex', pattern: regex.pattern, flags: regex.flags, error });
258
+ regexCount += 1;
259
+ flush(i);
260
+ chunks.push(id);
261
+ i = regex.end;
262
+ chunkStart = i;
263
+ continue;
264
+ }
265
+ // `\` is division in YARA, so a `/` that opens no regex is an authoring error.
266
+ if (!straySlashWarned) {
267
+ straySlashWarned = true;
268
+ console.warn(`yaraConditionParser: "/" does not start a regex literal in condition "${condition.slice(0, 80)}" - integer division is "\\"`);
269
+ }
270
+ i += 1;
271
+ continue;
272
+ }
273
+
274
+ i += 1;
275
+ }
276
+
277
+ flush(condition.length);
278
+
279
+ return { processed: chunks.join(''), literals };
280
+ }
281
+
282
+ /** True for either placeholder family (`__LITERAL_n__` / `__REGEX_n__`). */
283
+ function isPlaceholderId(name) {
284
+ return typeof name === 'string' && (name.startsWith(PLACEHOLDER_PREFIX) || name.startsWith(REGEX_PLACEHOLDER_PREFIX));
285
+ }
286
+
287
+ /**
288
+ * Build the AST node for a restored regex literal, carrying the validation failure (if any) so
289
+ * the evaluator can report it instead of silently matching nothing.
290
+ *
291
+ * @param {{pattern: string, flags?: string, error?: string|null}} literal
292
+ * @returns {Object}
293
+ */
294
+ function makeRegexNode(literal) {
295
+ const node = { type: 'regex', pattern: literal.pattern, flags: literal.flags ?? '' };
296
+ if (literal.error) node.error = literal.error;
297
+ return node;
298
+ }
299
+
300
+ /**
301
+ * Human-readable description of a `matches` right-hand operand, for diagnostics.
302
+ *
303
+ * @param {Object} node
304
+ * @returns {string}
305
+ */
306
+ function describeOperand(node) {
307
+ if (!node || typeof node !== 'object') return typeof node;
308
+ if (node.type === 'string') return `string literal "${node.value}"`;
309
+ if (node.type === 'identifier') return `"${node.name}"`;
310
+ if (node.type === 'memberAccess') return 'a module/property value';
311
+ if (node.type === 'functionCall') return 'a function call';
312
+ if (node.type === 'number' || node.type === 'boolean') return `${node.type} ${node.value}`;
313
+ return `a "${node.type}" expression`;
226
314
  }
227
315
 
228
316
  /**
229
- * Restore string literals in AST by replacing placeholder identifiers
317
+ * Restore string and regex literals in AST by replacing placeholder identifiers
230
318
  * Phase 3 of parsing: replaces placeholders with actual string literal nodes
231
- *
319
+ *
232
320
  * @param {Object} ast - AST node to process
233
321
  * @param {Array} literals - Array of literal info from extraction phase
322
+ * @param {string} condition - Original condition, used for diagnostics
234
323
  * @returns {Object} AST with literals restored
235
324
  */
236
- function restoreStringLiterals(ast, literals) {
325
+ function restoreStringLiterals(ast, literals, condition = '') {
237
326
  if (!ast || typeof ast !== 'object') {
238
327
  return ast;
239
328
  }
240
329
 
241
- // Check if this is a placeholder identifier
242
- if (ast.type === 'identifier' && ast.name && ast.name.startsWith(PLACEHOLDER_PREFIX)) {
330
+ // Check if this is a placeholder identifier (string or regex literal)
331
+ if (ast.type === 'identifier' && ast.name && isPlaceholderId(ast.name)) {
243
332
  const literal = literals.find(lit => lit.id === ast.name);
244
333
  if (literal) {
334
+ if (literal.type === 'regex') {
335
+ return makeRegexNode(literal);
336
+ }
245
337
  return { type: 'string', value: literal.value };
246
338
  }
247
339
  }
@@ -253,19 +345,28 @@ function restoreStringLiterals(ast, literals) {
253
345
  if (Array.isArray(result[key])) {
254
346
  result[key] = result[key].map(item => {
255
347
  // Handle plain string items (like in 'items' arrays)
256
- if (typeof item === 'string' && item.startsWith(PLACEHOLDER_PREFIX)) {
348
+ if (typeof item === 'string' && isPlaceholderId(item)) {
257
349
  const literal = literals.find(lit => lit.id === item);
258
- return literal ? literal.value : item;
350
+ if (!literal) return item;
351
+ return literal.type === 'regex' ? makeRegexNode(literal) : literal.value;
259
352
  }
260
353
  // Handle object items
261
- return typeof item === 'object' ? restoreStringLiterals(item, literals) : item;
354
+ return typeof item === 'object' ? restoreStringLiterals(item, literals, condition) : item;
262
355
  });
263
356
  } else if (typeof result[key] === 'object') {
264
- result[key] = restoreStringLiterals(result[key], literals);
357
+ result[key] = restoreStringLiterals(result[key], literals, condition);
265
358
  }
266
359
  }
267
360
  }
268
-
361
+
362
+ // YARA requires a regex literal on the right of `matches`. Anything computed during the scan
363
+ // could become an arbitrary pattern (catastrophic backtracking), so it is rejected here and
364
+ // the rule fails closed at evaluation.
365
+ if (result.type === 'matches' && result.right?.type !== 'regex') {
366
+ result.error = `right operand of "matches" must be a regex literal, got ${describeOperand(result.right)}`;
367
+ console.warn(`yaraConditionParser: invalid "matches" in condition "${condition.slice(0, 80)}" - ${result.error}`);
368
+ }
369
+
269
370
  return result;
270
371
  }
271
372
 
@@ -278,14 +379,15 @@ function restoreStringLiterals(ast, literals) {
278
379
  export function parseConditionToAST(condition, strings = {}) {
279
380
  condition = condition.trim();
280
381
 
281
- // Phase 1: Extract string literals to avoid parsing confusion
282
- const { processed, literals } = extractStringLiterals(condition);
382
+ // Phase 1: extract string and regex literals so `^`, `/` and ` and ` inside them are not
383
+ // mistaken for operators
384
+ const { processed, literals } = extractLiterals(condition);
283
385
 
284
386
  // Phase 2: Parse structure with placeholders
285
387
  const ast = parseStructure(processed, strings);
286
388
 
287
- // Phase 3: Restore string literals in AST
288
- return restoreStringLiterals(ast, literals);
389
+ // Phase 3: restore both kinds of literal in the AST and validate operator operands
390
+ return restoreStringLiterals(ast, literals, condition);
289
391
  }
290
392
 
291
393
  /**
@@ -509,18 +611,20 @@ function parseStructure(condition, strings = {}) {
509
611
  }
510
612
 
511
613
  // Handle "not" operator
512
- if (condition.startsWith('not ')) {
614
+ const notMatch = condition.match(/^not\s+([\s\S]+)$/);
615
+ if (notMatch) {
513
616
  return {
514
617
  type: 'not',
515
- operand: parseStructure(condition.substring(4), strings)
618
+ operand: parseStructure(notMatch[1], strings)
516
619
  };
517
620
  }
518
621
 
519
622
  // Handle "defined" operator
520
- if (condition.startsWith('defined ')) {
623
+ const definedMatch = condition.match(/^defined\s+([\s\S]+)$/);
624
+ if (definedMatch) {
521
625
  return {
522
626
  type: 'defined',
523
- operand: parseStructure(condition.substring(8), strings)
627
+ operand: parseStructure(definedMatch[1], strings)
524
628
  };
525
629
  }
526
630
 
@@ -574,6 +678,8 @@ function parseStructure(condition, strings = {}) {
574
678
  // Handle string operators (must check before comparison operators)
575
679
  // These are word-based operators that require flexible whitespace matching
576
680
  const stringOps = [
681
+ { pattern: 'matches', type: 'matches' },
682
+ { pattern: 'iequals', type: 'iequals' },
577
683
  { pattern: 'icontains', type: 'icontains' },
578
684
  { pattern: 'contains', type: 'contains' },
579
685
  { pattern: 'istartswith', type: 'istartswith' },
@@ -649,8 +755,8 @@ function parseExpression(expr) {
649
755
  return { type: 'number', value: value * multipliers[unit] };
650
756
  }
651
757
 
652
- // Note: String literals are handled in Phase 1 (extractStringLiterals)
653
- // and restored in Phase 3 (restoreStringLiterals).
758
+ // Note: string and regex literals are masked in Phase 1 (extractLiterals)
759
+ // and restored as `string` / `regex` nodes in Phase 3 (restoreStringLiterals).
654
760
  // By this point, they are placeholders like __LITERAL_0__
655
761
 
656
762
  // Floating point number (must be checked before member access)
@@ -673,6 +779,19 @@ function parseExpression(expr) {
673
779
  return { type: 'stringIdentifier', identifier: expr };
674
780
  }
675
781
 
782
+ // Extension (not YARA): $a[i] is the i-th matched substring, built from @a[i] and !a[i].
783
+ // YARA has no indexed form of $a and rejects it as a syntax error.
784
+ const occurrenceMatch = expr.match(/^\$(\w*)\[([^\]]+)\]$/);
785
+ if (occurrenceMatch) {
786
+ const [, name, indexExpr] = occurrenceMatch;
787
+ const trimmedIndex = indexExpr.trim();
788
+ return {
789
+ type: 'stringOccurrence',
790
+ identifier: `$${name}`,
791
+ index: /^\d+$/.test(trimmedIndex) ? parseInt(trimmedIndex) : parseExpression(trimmedIndex)
792
+ };
793
+ }
794
+
676
795
  // String count #a or just # (for loops)
677
796
  if (/^#\w*$/.test(expr)) {
678
797
  return { type: 'stringCount', identifier: expr.replace('#', '$') };
@@ -709,10 +828,10 @@ function parseExpression(expr) {
709
828
  const offsetIndexed = parseIndexedStringOp(expr, '@', 'stringOffset');
710
829
  if (offsetIndexed) return offsetIndexed;
711
830
 
712
- // String length !a or !$
713
- if (/^![\w$]+$/.test(expr)) {
831
+ // String length !a, !$ or a bare ! (the current string inside a for..of loop)
832
+ if (/^![\w$]*$/.test(expr)) {
714
833
  const id = expr.slice(1); // Remove '!'
715
- return { type: 'stringLength', identifier: id.startsWith('$') ? id : `$${id}`, index: 0 };
834
+ return { type: 'stringLength', identifier: id ? (id.startsWith('$') ? id : `$${id}`) : '$', index: 0 };
716
835
  }
717
836
 
718
837
  // String length !a[expr] - supports !a[n], !a[i], !a[i+1], etc.
@@ -829,7 +948,7 @@ function parseExpression(expr) {
829
948
  // Only consume a primary expression (number, identifier, or parenthesized)
830
949
  if (expr.startsWith('~')) {
831
950
  const rest = expr.substring(1).trim();
832
- let operandEnd = 0;
951
+ let operandEnd; // assigned in each branch below
833
952
 
834
953
  // If starts with paren, find matching close paren
835
954
  if (rest.startsWith('(')) {
@@ -1021,6 +1140,12 @@ function parseExpression(expr) {
1021
1140
  return { type: 'ruleIdentifier', name: expr };
1022
1141
  }
1023
1142
 
1143
+ // YARA defines no indexed form of `#a` — only `@a[i]` (offset) and `!a[i]` (length) take an
1144
+ // index. Report the construct here instead of failing later with "Unknown identifier".
1145
+ if (/^#\w*\[[^\]]*\]$/.test(expr)) {
1146
+ console.warn(`yaraConditionParser: "${expr}" is not valid YARA - "#${expr.slice(1).split('[')[0]}" is the total count and takes no index`);
1147
+ }
1148
+
1024
1149
  // Default: treat as unknown identifier
1025
1150
  return { type: 'identifier', name: expr };
1026
1151
  }
@@ -1034,7 +1159,10 @@ function parseExpression(expr) {
1034
1159
  */
1035
1160
  function findOperatorOutsideParens(str, op) {
1036
1161
  const opTrimmed = op.trim();
1037
- const isWordOp = /^(and|or|not)$/.test(opTrimmed);
1162
+ // Every alphabetic operator (`and`, `or`, `not`, `matches`, `contains`, …) is matched as a whole
1163
+ // word with flexible whitespace, so tab- and newline-indented conditions parse like single-line
1164
+ // ones. Symbol operators must keep the exact-match path.
1165
+ const isWordOp = /^[a-z]+$/.test(opTrimmed);
1038
1166
 
1039
1167
  let parenDepth = 0;
1040
1168
  let bracketDepth = 0;