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.
@@ -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(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
@@ -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
 
@@ -258,6 +286,19 @@ export class ConditionEvaluator {
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
304
  case "and": {
@@ -384,6 +425,10 @@ export class ConditionEvaluator {
384
425
  case "iequals":
385
426
  return await this.stringEquals(node.left, node.right, true);
386
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
@@ -665,8 +710,7 @@ export class ConditionEvaluator {
665
710
  }
666
711
 
667
712
  // YARA uses 1-indexed arrays: @a or @a[1] = first match, @a[2] = second match
668
- // Convert to 0-indexed for JavaScript arrays
669
- // 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.
670
714
  const arrayIndex = index === 0 ? 0 : index - 1;
671
715
  return stringInfo.offsets[arrayIndex];
672
716
  }
@@ -693,8 +737,7 @@ export class ConditionEvaluator {
693
737
  }
694
738
 
695
739
  // YARA uses 1-indexed arrays: !a or !a[1] = first match, !a[2] = second match
696
- // Convert to 0-indexed for JavaScript arrays
697
- // 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.
698
741
  const arrayIndex = index === 0 ? 0 : index - 1;
699
742
  const match = stringInfo.matches[arrayIndex];
700
743
  return match ? match.length : undefined;
@@ -1194,7 +1237,7 @@ export class ConditionEvaluator {
1194
1237
  // Handle both sync and async module functions
1195
1238
  return result instanceof Promise ? await result : result;
1196
1239
  } catch (error) {
1197
- throw new Error(`Error calling ${module}.${functionName}: ${error.message}`);
1240
+ throw new Error(`Error calling ${module}.${functionName}: ${error.message}`, { cause: error });
1198
1241
  }
1199
1242
  }
1200
1243
 
@@ -1316,20 +1359,17 @@ export class ConditionEvaluator {
1316
1359
  // YARA: string operators return undefined if operands are undefined
1317
1360
  if (this.isAnyUndefined(left, right)) return undefined;
1318
1361
 
1319
- if (typeof left !== "string") {
1320
- 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}`);
1321
1366
  }
1322
1367
 
1323
- let regex;
1324
- if (right instanceof RegExp) {
1325
- regex = right;
1326
- } else if (typeof right === "string") {
1327
- regex = new RegExp(right);
1328
- } else {
1368
+ if (typeof left !== "string") {
1329
1369
  return false;
1330
1370
  }
1331
1371
 
1332
- return regex.test(left);
1372
+ return right.test(left);
1333
1373
  }
1334
1374
  }
1335
1375
 
@@ -57,14 +57,18 @@ export function compileYaraLike(definition) {
57
57
  }
58
58
 
59
59
  function addOptionsToMatcher(matcher) {
60
- return (data, offset = -1, maxLength = MAX_STRING_MATCH_LENGTH) => {
61
- // If offset is specified, slice the data accordingly and limit length for matching
62
- const singleRun = offset >= 0;
63
- // Start 1 byte before to do fullword checks if needed
64
- offset = Math.max(0, offset - 1);
65
- data = singleRun ? data.slice(offset, offset + maxLength) : data;
66
- return matcher(data, singleRun ? offset : -1);
60
+ // Public contract: `offset < 0` scans the whole buffer, otherwise the search window starts at
61
+ // `offset` (one byte earlier, so fullword checks at the window start can see the preceding byte).
62
+ const scan = (data, offset = -1, maxLength = MAX_STRING_MATCH_LENGTH, exactIndex = -1) => {
63
+ if (offset < 0) return matcher(data, -1);
64
+ const start = Math.max(0, offset - 1);
65
+ return matcher(data.slice(start, start + maxLength), start, exactIndex < 0 ? -1 : exactIndex - start);
67
66
  };
67
+
68
+ // Aho-Corasick candidates ask "is there a match starting exactly here?", which a window scan
69
+ // cannot answer — its first match may be a neighbouring occurrence.
70
+ scan.verifyAt = (data, offset) => scan(data, offset, MAX_STRING_MATCH_LENGTH, offset);
71
+ return scan;
68
72
  }
69
73
 
70
74
  // ╭─────────────────────────────╮
@@ -80,14 +84,21 @@ function makeRegexMatcher(definition) {
80
84
  const literalPrefix = getRegexPrefix(pattern, nocase);
81
85
  const re = new RegExp(pattern, flags);
82
86
 
83
- const matcher = (data, offset = -1) => {
87
+ const matcher = (data, offset = -1, exactIndex = -1) => {
84
88
  const encoder = new TextEncoder();
85
89
  const text = new TextDecoder().decode(data);
86
90
  const results = [];
87
91
  const singleRun = offset >= 0;
92
+ const exact = exactIndex >= 0;
93
+ // `re` outlives a call: the matcher runs once per Aho-Corasick candidate plus once per full
94
+ // scan, and an early `break` (or the MAX_MATCHES cap) leaves `lastIndex` mid-text. Position it
95
+ // explicitly on entry instead of inheriting the previous run's position.
96
+ const runIndex = exact ? exactIndex : 0;
88
97
  offset = offset < 0 ? 0 : offset;
98
+ re.lastIndex = runIndex;
89
99
  let m;
90
100
  while ((m = re.exec(text)) !== null && results.length < MAX_MATCHES) {
101
+ if (exact && m.index !== runIndex) break; // prefix hit the regex rejects
91
102
  const byteIndex = encoder.encode(text.slice(0, m.index)).length;
92
103
  results.push({ offset: byteIndex + offset, length: encoder.encode(m[0]).length });
93
104
  re.lastIndex = m.index + 1; // Move forward to find overlapping matches
@@ -180,17 +191,19 @@ function makeTextMatcher(text, opts) {
180
191
  }
181
192
  }
182
193
 
183
- const matcher = (data, offset = -1) => {
194
+ const matcher = (data, offset = -1, exactIndex = -1) => {
184
195
  let matches = [];
185
196
  const singleRun = offset >= 0;
197
+ // `exactIndex` (relative to the slice) restricts a single run to the candidate's own byte.
198
+ const runIndex = exactIndex >= 0 ? exactIndex : -1;
186
199
  offset = offset < 0 ? 0 : offset;
187
200
 
188
201
  for (const { bytes, isWide } of patterns) {
189
202
  if (opts.xor) {
190
- const xorMatches = findXorMatches(data, bytes, opts.xor, opts.allowKey0, singleRun);
203
+ const xorMatches = findXorMatches(data, bytes, opts.xor, opts.allowKey0, singleRun, runIndex);
191
204
  matches.push(...xorMatches.map((m) => ({ ...m, length: bytes.length, isWide })));
192
205
  } else {
193
- const plainMatches = findPlainMatches(data, bytes, opts.nocase, singleRun);
206
+ const plainMatches = findPlainMatches(data, bytes, opts.nocase, singleRun, runIndex);
194
207
  matches.push(...plainMatches.map((m) => ({ ...m, length: bytes.length, isWide })));
195
208
  }
196
209
  }
@@ -213,15 +226,16 @@ function makeTextMatcher(text, opts) {
213
226
  // ╭─────────────────────────────╮
214
227
  // │ XOR-AWARE MATCHING │
215
228
  // ╰─────────────────────────────╯
216
- function findXorMatches(data, pattern, keyRange, allowKey0 = true, singleRun = false) {
229
+ function findXorMatches(data, pattern, keyRange, allowKey0 = true, singleRun = false, exactIndex = -1) {
217
230
  const [minKey, maxKey] = keyRange;
218
231
  const matches = [];
219
232
  const pLen = pattern.length;
220
233
  const dLen = data.length;
234
+ const from = exactIndex >= 0 ? exactIndex : 0;
221
235
  if (pLen === 0 || pLen > dLen) return matches;
222
236
 
223
237
  for (let candidateKey = minKey; candidateKey <= maxKey; candidateKey++) {
224
- for (let i = 0; i <= dLen - pLen; i++) {
238
+ for (let i = from; i <= dLen - pLen; i++) {
225
239
  let ok = true;
226
240
  for (let j = 0; j < pLen; j++) {
227
241
  if ((data[i + j] ^ candidateKey) !== pattern[j]) {
@@ -230,7 +244,8 @@ function findXorMatches(data, pattern, keyRange, allowKey0 = true, singleRun = f
230
244
  }
231
245
  }
232
246
  if (ok) {
233
- matches.push({ offset: i, key: candidateKey });
247
+ // An exact run only accepts the requested offset; a later hit belongs to another candidate.
248
+ if (exactIndex < 0 || i === exactIndex) matches.push({ offset: i, key: candidateKey });
234
249
  if (singleRun) break;
235
250
  }
236
251
  }
@@ -241,15 +256,17 @@ function findXorMatches(data, pattern, keyRange, allowKey0 = true, singleRun = f
241
256
  // ╭─────────────────────────────╮
242
257
  // │ PLAIN MATCHING │
243
258
  // ╰─────────────────────────────╯
244
- function findPlainMatches(data, pattern, nocase = false, singleRun = false) {
259
+ function findPlainMatches(data, pattern, nocase = false, singleRun = false, exactIndex = -1) {
245
260
  const matches = [];
246
261
  const pLen = pattern.length;
247
262
  const dLen = data.length;
248
- outer: for (let i = 0; i <= dLen - pLen; i++) {
263
+ const from = exactIndex >= 0 ? exactIndex : 0;
264
+ outer: for (let i = from; i <= dLen - pLen; i++) {
249
265
  for (let j = 0; j < pLen; j++) {
250
266
  if ((nocase ? lowercaseByte(data[i + j]) : data[i + j]) !== pattern[j]) continue outer;
251
267
  }
252
- matches.push({ offset: i });
268
+ // An exact run only accepts the requested offset; a later hit belongs to another candidate.
269
+ if (exactIndex < 0 || i === exactIndex) matches.push({ offset: i });
253
270
  if (singleRun) break;
254
271
  }
255
272
  return matches;
@@ -364,6 +381,9 @@ function makeHexMatcher(hexBody, mods) {
364
381
 
365
382
  const matches = [];
366
383
  let m;
384
+ // Same shared-instance hazard as the regex matcher: `regex` lives as long as the matcher, so
385
+ // reset before each run (the MAX_MATCHES cap can leave `lastIndex` mid-string).
386
+ regex.lastIndex = 0;
367
387
  while ((m = regex.exec(hexString)) !== null && matches.length < MAX_MATCHES) {
368
388
  // Convert hex string offset to byte offset
369
389
  if (m.index % 2 !== 0) {
@@ -376,7 +396,7 @@ function makeHexMatcher(hexBody, mods) {
376
396
  // // Skip non-aligned length matches
377
397
  // continue;
378
398
  // }
379
- matches.push({ offset: m.index / 2 });
399
+ matches.push({ offset: m.index / 2, length: Math.ceil(m[0].length / 2) });
380
400
  regex.lastIndex = m.index + 2; // Move forward to find overlapping matches
381
401
  }
382
402
  return matches;