UNPKG

1.5 kBJavaScriptView Raw
1// Exports an Analyzer subclass
2
3const regexpTree = require("regexp-tree");
4const analyzer = require("./analyzer");
5
6class HeuristicAnalyzer extends analyzer.Analyzer {
7 constructor(analyzerOptions) {
8 super(analyzerOptions);
9 }
10
11 isVulnerable(regExp) {
12 // Heuristic #1: Star height > 1
13 const starHeight = this._measureStarHeight(regExp);
14 if (starHeight > 1) {
15 return true;
16 }
17
18 // Heuristic #2: # repetitions > limit
19 // TODO This is a poor heuristic
20 const nRepetitions = this._measureRepetitions(regExp);
21 if (nRepetitions > this.options.heuristic_replimit) {
22 return true;
23 }
24
25 return false;
26 }
27
28 genAttackString(regExp) {
29 return null;
30 }
31
32 _measureStarHeight(regExp) {
33 let currentStarHeight = 0;
34 let maxObservedStarHeight = 0;
35
36 const ast = regexpTree.parse(regExp);
37
38 regexpTree.traverse(ast, {
39 Repetition: {
40 pre({ node }) {
41 currentStarHeight++;
42 if (maxObservedStarHeight < currentStarHeight) {
43 maxObservedStarHeight = currentStarHeight;
44 }
45 },
46
47 post({ node }) {
48 currentStarHeight--;
49 }
50 }
51 });
52
53 return maxObservedStarHeight;
54 }
55
56 _measureRepetitions(regExp) {
57 let nRepetitions = 0;
58
59 const ast = regexpTree.parse(regExp);
60 regexpTree.traverse(ast, {
61 Repetition: {
62 pre({ node }) {
63 nRepetitions++;
64 }
65 }
66 });
67
68 return nRepetitions;
69 }
70}
71
72module.exports = HeuristicAnalyzer;