sekant-intercept-js 1.0.2 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sekant-intercept-js",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "Context-Aware YARA Runtime Detection for JavaScript Environments",
5
5
  "main": "./dist/sekant-intercept.node.mjs",
6
6
  "exports": {
@@ -14,15 +14,80 @@
14
14
  * limitations under the License.
15
15
  */
16
16
 
17
+ // Atoms are the fixed-size fragments stored in the automaton. Three bytes keeps the trie small
18
+ // while still producing specific enough candidates to avoid a verification flood.
19
+ const DEFAULT_ATOM_LENGTH = 3;
20
+
17
21
  class Node {
18
22
  constructor() {
19
- this.children = {}; // edges
23
+ this.children = new Map(); // byte (or char code) -> Node; numeric keys avoid per-byte strings
20
24
  this.fail = null; // failure link
21
- this.outputs = []; // matched patterns
22
- this.nocase = false;
25
+ this.outputs = null; // matched atoms, allocated on demand
26
+ }
27
+ }
28
+
29
+ const isAsciiLetter = (code) =>
30
+ (code >= 0x61 && code <= 0x7a) || (code >= 0x41 && code <= 0x5a);
31
+
32
+ function generateCaseVariants(atom) {
33
+ const variants = [atom];
34
+
35
+ for (let i = 0; i < atom.length; i++) {
36
+ const code = atom[i];
37
+ if (!isAsciiLetter(code)) continue;
38
+
39
+ const alternateCode = code >= 0x61 ? code - 0x20 : code + 0x20;
40
+ const existingCount = variants.length;
41
+ for (let j = 0; j < existingCount; j++) {
42
+ const variant = variants[j].slice();
43
+ variant[i] = alternateCode;
44
+ variants.push(variant);
45
+ }
46
+ }
47
+
48
+ return variants;
49
+ }
50
+
51
+ /**
52
+ * Pick the atom window deterministically. More distinct bytes means a more selective atom (fewer
53
+ * false candidates); zero bytes are common in binaries, and every ASCII letter doubles the case
54
+ * variants a `nocase` atom needs, so both are penalized. Ties keep the earliest window.
55
+ */
56
+ function chooseAtomOffset(bytes, atomLength, nocase) {
57
+ const maxOffset = bytes.length - atomLength;
58
+ const seen = new Int32Array(256);
59
+ let stamp = 0;
60
+ let bestOffset = 0;
61
+ let bestScore = -Infinity;
62
+
63
+ for (let offset = 0; offset <= maxOffset; offset++) {
64
+ stamp += 1;
65
+ let distinct = 0;
66
+ let zeroes = 0;
67
+ let letters = 0;
68
+
69
+ for (let i = offset; i < offset + atomLength; i++) {
70
+ const code = bytes[i];
71
+ if (seen[code] !== stamp) {
72
+ seen[code] = stamp;
73
+ distinct += 1;
74
+ }
75
+ if (code === 0) zeroes += 1;
76
+ else if (nocase && isAsciiLetter(code)) letters += 1;
77
+ }
78
+
79
+ const score = distinct * 8 - zeroes * 4 - letters * 2;
80
+ if (score > bestScore) {
81
+ bestScore = score;
82
+ bestOffset = offset;
83
+ }
23
84
  }
85
+
86
+ return bestOffset;
24
87
  }
25
88
 
89
+ const atomEncoder = new TextEncoder();
90
+
26
91
  // Rule structure example:
27
92
  // {
28
93
  // name: ruleName,
@@ -42,109 +107,134 @@ class Node {
42
107
  // patterns // for text
43
108
  // };
44
109
 
45
- // Format for outputs node
46
- // { id, varName }
110
+ // Format for a trie output (one atom variant of one pattern):
111
+ // {
112
+ // group, // shared by every variant of one pattern, used to collapse duplicate hits
113
+ // id, // rule id
114
+ // varName, // string identifier
115
+ // matcher, // exact-position verifier for the pattern
116
+ // atom, // Uint8Array atom stored in the trie
117
+ // atomOffset, // atom position within the full pattern
118
+ // atomLength,
119
+ // length, // full pattern length in bytes
120
+ // xorKey, // present for XOR variants
121
+ // }
47
122
 
48
123
  export class AhoCorasick {
49
124
  constructor(rules) {
50
125
  this.root = new Node();
126
+ this.groupCount = 0;
127
+ this.lastOffsets = new Float64Array(0);
51
128
  this.addRules(rules);
52
129
  }
53
130
 
54
131
  addRules(rules) {
55
- // Add multiple rules to the AC automaton
56
- const patterns = [];
57
-
58
- const decoder = new TextDecoder();
132
+ // Collect one entry per underlying pattern; every atom variant derived from it shares a group,
133
+ // so duplicate hits from case/XOR variants collapse into a single candidate.
134
+ const entries = [];
59
135
 
60
- // console.log(JSON.stringify(rules));
61
-
62
- // Extract all the relevant patterns from the rules
63
136
  for (const rule of rules) {
64
137
  const { id, strings } = rule;
65
138
  for (const varName of Object.keys(strings)) {
66
139
  const strDef = strings[varName];
140
+
67
141
  if (strDef.type === "text") {
68
- for (const patternObj of strDef.patterns) {
69
- // patterns is an array of { bytes: Uint8Array }
142
+ for (const patternObj of strDef.patterns ?? []) {
70
143
  const bytes = patternObj.bytes;
71
- const patternStr = decoder.decode(bytes);
72
- patterns.push({ id, varName, pattern: patternStr, matcher: strDef.matcher, xor: strDef.xor, nocase: strDef.nocase });
144
+ if (!bytes || bytes.length === 0) continue; // empty strings never match
145
+ entries.push({
146
+ group: this.groupCount++,
147
+ id,
148
+ varName,
149
+ bytes,
150
+ matcher: strDef.matcher,
151
+ xor: strDef.xor ?? null,
152
+ nocase: strDef.nocase === true,
153
+ });
73
154
  }
74
- } else if (strDef.type === "regex" && strDef.literalPrefix && strDef.literalPrefix.length > 0) {
75
- patterns.push({ id, varName, pattern: strDef.literalPrefix, matcher: strDef.matcher, nocase: strDef.nocase });
155
+ } else if (strDef.type === "regex" && strDef.literalPrefix) {
156
+ const bytes = atomEncoder.encode(strDef.literalPrefix);
157
+ if (bytes.length === 0) continue;
158
+ entries.push({
159
+ group: this.groupCount++,
160
+ id,
161
+ varName,
162
+ bytes,
163
+ matcher: strDef.matcher,
164
+ xor: null,
165
+ nocase: strDef.nocase === true,
166
+ });
76
167
  }
77
168
  }
78
169
  }
79
170
 
80
- // Generate atoms per pattern for optimization ; modifies the patterns array
81
- this.generateAtoms(patterns);
82
-
83
- // console.log(`Aho-Corasick: Adding ${patterns.length} patterns to trie`);
84
- // console.log(patterns);
85
-
86
- this.buildTrie(patterns);
171
+ this.buildTrie(this.buildAtoms(entries));
87
172
  this.buildFailures();
88
173
  }
89
174
 
90
- generateAtoms(patterns, atomLength = 3) {
91
- const xorPatterns = [];
92
-
93
- for (const p of patterns) {
94
- if (p.pattern.length <= atomLength) {
95
- p.atom = p.pattern;
96
- p.atomOffset = 0;
97
- } else {
98
- // Pick random offset to avoid bias
99
- const randomOffset = Math.floor(Math.random() * (p.pattern.length - atomLength));
100
- p.atom = p.pattern.slice(randomOffset, randomOffset + atomLength);
101
- p.atomOffset = randomOffset;
102
- }
103
- p.atomLength = p.atom.length;
104
- p.length = p.pattern.length;
105
-
106
- if (p.xor) {
107
- const [minKey, maxKey] = p.xor;
108
-
109
- const originalAtomChars = Array.from(p.atom);
175
+ buildAtoms(entries, atomLength = DEFAULT_ATOM_LENGTH) {
176
+ const atoms = [];
177
+
178
+ for (const entry of entries) {
179
+ const bytes = entry.bytes;
180
+ const length = bytes.length;
181
+ const useWholePattern = length <= atomLength;
182
+ const atomOffset = useWholePattern ? 0 : chooseAtomOffset(bytes, atomLength, entry.nocase);
183
+ const usedAtomLength = useWholePattern ? length : atomLength;
184
+ const atom = bytes.subarray(atomOffset, atomOffset + usedAtomLength);
185
+ const base = {
186
+ group: entry.group,
187
+ id: entry.id,
188
+ varName: entry.varName,
189
+ matcher: entry.matcher,
190
+ atomOffset,
191
+ atomLength: usedAtomLength,
192
+ length,
193
+ };
194
+
195
+ if (entry.nocase && !entry.xor) {
196
+ for (const variant of generateCaseVariants(atom)) {
197
+ atoms.push({ ...base, atom: variant });
198
+ }
199
+ } else if (entry.xor) {
200
+ const [minKey, maxKey] = entry.xor;
110
201
  for (let key = minKey; key <= maxKey; key++) {
111
- const xorredAtom = originalAtomChars.map((c) => String.fromCharCode(c.charCodeAt(0) ^ key)).join("");
112
- if (key === minKey) {
113
- // Overwrite original pattern's atom with first XOR variant
114
- p.atom = xorredAtom;
115
- p.xorKey = key;
116
- } else {
117
- // Add additional patterns for other XOR variants
118
- xorPatterns.push({ ...p, atom: xorredAtom, xorKey: key });
119
- }
202
+ const xoredAtom = new Uint8Array(usedAtomLength);
203
+ for (let i = 0; i < usedAtomLength; i++) xoredAtom[i] = atom[i] ^ key;
204
+ atoms.push({ ...base, atom: xoredAtom, xorKey: key });
120
205
  }
206
+ } else {
207
+ atoms.push({ ...base, atom });
121
208
  }
122
- // Memory optimization
123
- // delete p.pattern;
124
209
  }
125
210
 
126
- patterns.push(...xorPatterns);
211
+ return atoms;
127
212
  }
128
213
 
129
- buildTrie(patterns) {
130
- for (const p of patterns) {
214
+ buildTrie(atoms) {
215
+ for (const atomEntry of atoms) {
131
216
  let node = this.root;
132
- // Iterate over code units (not code points) to handle surrogate pairs correctly
133
- for (let i = 0; i < p.atom.length; i++) {
134
- const ch = p.atom[i];
135
- if (!node.children[ch]) node.children[ch] = new Node();
136
- node = node.children[ch];
137
- node.nocase = p.nocase ?? false;
217
+ const atom = atomEntry.atom;
218
+ for (let i = 0; i < atom.length; i++) {
219
+ const code = atom[i];
220
+ let child = node.children.get(code);
221
+ if (child === undefined) {
222
+ child = new Node();
223
+ node.children.set(code, child);
224
+ }
225
+ node = child;
138
226
  }
139
- node.outputs.push(p);
227
+ if (node.outputs === null) node.outputs = [atomEntry];
228
+ else node.outputs.push(atomEntry);
140
229
  }
141
- // this.printTrie();
142
230
  }
143
231
 
144
232
  printTrie() {
145
233
  const traverse = (node, prefix) => {
146
- for (const [ch, child] of Object.entries(node.children)) {
147
- console.log(`${prefix}${ch} (nocase: ${child.nocase}) (children: [${Object.keys(child.children)}]) (outputs: ${child.outputs.length})`);
234
+ for (const [code, child] of node.children) {
235
+ const childCodes = [...child.children.keys()].map((c) => String.fromCharCode(c));
236
+ const count = child.outputs === null ? 0 : child.outputs.length;
237
+ console.log(`${prefix}${String.fromCharCode(code)} (children: [${childCodes}]) (outputs: ${count})`);
148
238
  traverse(child, prefix + " ");
149
239
  }
150
240
  };
@@ -153,69 +243,86 @@ export class AhoCorasick {
153
243
 
154
244
  buildFailures() {
155
245
  const queue = [];
246
+
156
247
  // Level 1 fail links = root
157
- for (const ch in this.root.children) {
158
- const child = this.root.children[ch];
248
+ for (const child of this.root.children.values()) {
159
249
  child.fail = this.root;
160
250
  queue.push(child);
161
251
  }
162
252
 
163
- while (queue.length > 0) {
164
- const current = queue.shift();
165
- for (const [ch, nextNode] of Object.entries(current.children)) {
253
+ for (let qi = 0; qi < queue.length; qi++) {
254
+ const current = queue[qi];
255
+ for (const [code, nextNode] of current.children) {
166
256
  queue.push(nextNode);
167
257
 
168
- // Compute failure link
169
258
  let fail = current.fail;
170
- while (fail && !fail.children[ch]) {
259
+ while (fail && !fail.children.has(code)) {
171
260
  fail = fail.fail;
172
261
  }
173
- nextNode.fail = fail ? fail.children[ch] : this.root;
262
+ nextNode.fail = fail ? fail.children.get(code) : this.root;
174
263
 
175
264
  // Merge output patterns from failure link
176
- nextNode.outputs = nextNode.outputs.concat(nextNode.fail.outputs);
265
+ const failOutputs = nextNode.fail.outputs;
266
+ if (failOutputs !== null) {
267
+ nextNode.outputs = nextNode.outputs === null
268
+ ? failOutputs.slice()
269
+ : nextNode.outputs.concat(failOutputs);
270
+ }
177
271
  }
178
272
  }
179
273
  }
180
274
 
275
+ resetGroupState() {
276
+ if (this.lastOffsets.length < this.groupCount) {
277
+ this.lastOffsets = new Float64Array(this.groupCount);
278
+ }
279
+ this.lastOffsets.fill(-1, 0, this.groupCount);
280
+ }
281
+
181
282
  search(text) {
182
- const results = [];
183
- let node = this.root;
283
+ // Atoms are byte sequences, so text handed in as a string is matched as its UTF-8 bytes.
284
+ if (typeof text === "string") text = atomEncoder.encode(text);
184
285
 
185
- for (let i = 0; i < text.length; i++) {
186
- const ch = text[i];
286
+ const results = [];
287
+ const root = this.root;
288
+ const lastOffsets = this.lastOffsets;
289
+ const length = text.length;
290
+ let node = root;
187
291
 
188
- // For Uint8Array, ch is a number (byte value); convert to character
189
- // For string, ch is already a character
190
- const charValue = typeof ch === "number" ? String.fromCharCode(ch) : ch;
191
- const lowerCharValue = charValue.toLowerCase();
292
+ this.resetGroupState();
192
293
 
193
- // console.log(`i=${i}, ch=${ch}, charValue='${charValue}', lower='${lowerCharValue}'`);
294
+ for (let i = 0; i < length; i++) {
295
+ const code = text[i];
194
296
 
195
297
  // Follow failure links until we find a valid transition
196
- while (node && !(node.children[charValue] || (node.children[lowerCharValue] && node.children[lowerCharValue].nocase))) {
298
+ let next = node.children.get(code);
299
+ while (next === undefined && node !== root) {
197
300
  node = node.fail;
301
+ next = node.children.get(code);
198
302
  }
199
303
 
200
- if (!node) node = this.root;
201
- else {
202
- if (node.children[charValue]) node = node.children[charValue];
203
- else if (node.children[lowerCharValue]?.nocase) node = node.children[lowerCharValue];
204
- else node = this.root; // Should never happen due to the while loop above
205
- }
304
+ node = next === undefined ? root : next;
305
+ if (node === root) continue;
306
+
307
+ // If this node outputs atoms, record candidate matches
308
+ const outputs = node.outputs;
309
+ if (outputs === null) continue;
206
310
 
207
- // Do not report matches for root node (zero-length patterns)
208
- if (node === this.root) continue;
311
+ for (let k = 0; k < outputs.length; k++) {
312
+ const output = outputs[k];
313
+ const index = i - output.atomLength + 1;
314
+ const offset = index - output.atomOffset;
315
+ // Ignore matches that would start before or run past the end of the text
316
+ if (offset < 0 || offset + output.length > length) continue;
317
+ // Every atom variant of one pattern reaches a given offset at the same position, so a
318
+ // non-increasing offset is always a duplicate of what this pattern already reported.
319
+ if (offset <= lastOffsets[output.group]) continue;
320
+ lastOffsets[output.group] = offset;
209
321
 
210
- // If this node outputs patterns, record matches
211
- for (const output of node.outputs) {
212
- const index = i - (output.atomLength || 0) + 1;
213
- if (index - output.atomOffset < 0) continue; // Ignore matches that would start before text begins
214
- if (index - output.atomOffset + output.length > text.length) continue; // Ignore matches that would exceed text length
215
322
  results.push({
216
323
  id: output.id,
217
324
  varName: output.varName,
218
- offset: index - output.atomOffset, // byte offset of the start of the full pattern
325
+ offset,
219
326
  index,
220
327
  xorKey: output.xorKey,
221
328
  matcher: output.matcher,
@@ -223,8 +330,6 @@ export class AhoCorasick {
223
330
  }
224
331
  }
225
332
 
226
- // console.log(results.filter(r => r.varName === 'a9').length, " $a9 candidate matches");
227
- // console.log(results.filter(r => r.varName === 'a9'));
228
333
  return results;
229
334
  }
230
335
  }