aiwaf 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.
- package/LICENSE +22 -21
- package/README.md +1313 -45
- package/bin/aiwaf.js +198 -6
- package/geolock/ipinfo_lite.mmdb +0 -0
- package/index.js +2 -0
- package/lib/adonisMiddleware.js +1 -2
- package/lib/anomalyDetector.js +61 -2
- package/lib/blacklistManager.js +253 -33
- package/lib/csvStore.js +26 -9
- package/lib/dynamicKeyword.js +28 -7
- package/lib/fastifyPlugin.js +1 -0
- package/lib/featureUtils.js +143 -143
- package/lib/geoBlocker.js +12 -1
- package/lib/hapiPlugin.js +1 -0
- package/lib/isolationForest.js +117 -117
- package/lib/keywordDetector.js +18 -5
- package/lib/koaMiddleware.js +1 -1
- package/lib/modelStore.js +14 -0
- package/lib/nextMiddleware.js +1 -1
- package/lib/pathRules.js +7 -2
- package/lib/rateLimiter.js +5 -5
- package/lib/redisClient.js +24 -24
- package/lib/reputation.js +67 -0
- package/lib/settingsCompat.js +3 -0
- package/lib/trainingFeatures.js +85 -0
- package/lib/wafMiddleware.js +23 -15
- package/lib/wasmAdapter.js +36 -3
- package/package.json +29 -4
- package/train.js +23 -54
- package/utils/cache.js +2 -2
- package/utils/db.js +10 -10
package/lib/featureUtils.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
const STATIC_KW = ['.php', '.xmlrpc', 'wp-', '.env', '.git', '.bak', 'shell'];
|
|
2
2
|
const STATUS_IDX = ['200', '403', '404', '500'];
|
|
3
|
-
const defaultCache = new Map();
|
|
4
|
-
const { getClient } = require('./redisClient');
|
|
5
|
-
|
|
3
|
+
const defaultCache = new Map();
|
|
4
|
+
const { getClient } = require('./redisClient');
|
|
5
|
+
|
|
6
6
|
let customCache = null;
|
|
7
7
|
let cleanupInterval = null;
|
|
8
|
-
|
|
9
|
-
// In-memory tracking for burst and 404 calculations
|
|
10
|
-
const ipRequestHistory = new Map(); // IP -> array of timestamps
|
|
11
|
-
const ip404Counts = new Map(); // IP -> count of 404s
|
|
12
|
-
|
|
8
|
+
|
|
9
|
+
// In-memory tracking for burst and 404 calculations
|
|
10
|
+
const ipRequestHistory = new Map(); // IP -> array of timestamps
|
|
11
|
+
const ip404Counts = new Map(); // IP -> count of 404s
|
|
12
|
+
|
|
13
13
|
function init(opts = {}) {
|
|
14
14
|
customCache = opts.cache || null;
|
|
15
15
|
|
|
@@ -18,15 +18,15 @@ function init(opts = {}) {
|
|
|
18
18
|
// Clean up old entries every 5 minutes
|
|
19
19
|
cleanupInterval = setInterval(() => {
|
|
20
20
|
const fiveMinutesAgo = Date.now() - 5 * 60 * 1000;
|
|
21
|
-
|
|
22
|
-
for (const [ip, timestamps] of ipRequestHistory.entries()) {
|
|
23
|
-
const recentTimestamps = timestamps.filter(t => t > fiveMinutesAgo);
|
|
24
|
-
if (recentTimestamps.length > 0) {
|
|
25
|
-
ipRequestHistory.set(ip, recentTimestamps);
|
|
26
|
-
} else {
|
|
27
|
-
ipRequestHistory.delete(ip);
|
|
28
|
-
}
|
|
29
|
-
}
|
|
21
|
+
|
|
22
|
+
for (const [ip, timestamps] of ipRequestHistory.entries()) {
|
|
23
|
+
const recentTimestamps = timestamps.filter(t => t > fiveMinutesAgo);
|
|
24
|
+
if (recentTimestamps.length > 0) {
|
|
25
|
+
ipRequestHistory.set(ip, recentTimestamps);
|
|
26
|
+
} else {
|
|
27
|
+
ipRequestHistory.delete(ip);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
30
|
}, 5 * 60 * 1000);
|
|
31
31
|
if (typeof cleanupInterval.unref === 'function') {
|
|
32
32
|
cleanupInterval.unref();
|
|
@@ -41,134 +41,134 @@ function cleanup() {
|
|
|
41
41
|
ipRequestHistory.clear();
|
|
42
42
|
ip404Counts.clear();
|
|
43
43
|
}
|
|
44
|
-
|
|
45
|
-
function recordRequest(ip, statusCode) {
|
|
46
|
-
const now = Date.now();
|
|
47
|
-
|
|
48
|
-
// Record timestamp for burst calculation
|
|
49
|
-
if (!ipRequestHistory.has(ip)) {
|
|
50
|
-
ipRequestHistory.set(ip, []);
|
|
51
|
-
}
|
|
52
|
-
ipRequestHistory.get(ip).push(now);
|
|
53
|
-
|
|
54
|
-
// Keep only last 100 requests per IP to prevent memory bloat
|
|
55
|
-
const history = ipRequestHistory.get(ip);
|
|
56
|
-
if (history.length > 100) {
|
|
57
|
-
history.splice(0, history.length - 100);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// Track 404 counts
|
|
61
|
-
if (statusCode === 404) {
|
|
62
|
-
ip404Counts.set(ip, (ip404Counts.get(ip) || 0) + 1);
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
function calculateBurstCount(ip) {
|
|
67
|
-
if (!ipRequestHistory.has(ip)) return 0;
|
|
68
|
-
|
|
69
|
-
const now = Date.now();
|
|
70
|
-
const tenSecondsAgo = now - 10000; // 10 seconds
|
|
71
|
-
const recentRequests = ipRequestHistory.get(ip).filter(t => t > tenSecondsAgo);
|
|
72
|
-
|
|
73
|
-
return recentRequests.length;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function get404Count(ip) {
|
|
77
|
-
return ip404Counts.get(ip) || 0;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
// Helper to mark request start time for response time calculation
|
|
81
|
-
function markRequestStart(req) {
|
|
82
|
-
req._startTime = Date.now();
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
// Helper to calculate response time from marked start
|
|
86
|
-
function getResponseTime(req) {
|
|
87
|
-
if (req._startTime) {
|
|
88
|
-
return Date.now() - req._startTime;
|
|
89
|
-
}
|
|
90
|
-
return 0;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
async function extractFeatures(req, res = null) {
|
|
44
|
+
|
|
45
|
+
function recordRequest(ip, statusCode) {
|
|
46
|
+
const now = Date.now();
|
|
47
|
+
|
|
48
|
+
// Record timestamp for burst calculation
|
|
49
|
+
if (!ipRequestHistory.has(ip)) {
|
|
50
|
+
ipRequestHistory.set(ip, []);
|
|
51
|
+
}
|
|
52
|
+
ipRequestHistory.get(ip).push(now);
|
|
53
|
+
|
|
54
|
+
// Keep only last 100 requests per IP to prevent memory bloat
|
|
55
|
+
const history = ipRequestHistory.get(ip);
|
|
56
|
+
if (history.length > 100) {
|
|
57
|
+
history.splice(0, history.length - 100);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Track 404 counts
|
|
61
|
+
if (statusCode === 404) {
|
|
62
|
+
ip404Counts.set(ip, (ip404Counts.get(ip) || 0) + 1);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function calculateBurstCount(ip) {
|
|
67
|
+
if (!ipRequestHistory.has(ip)) return 0;
|
|
68
|
+
|
|
69
|
+
const now = Date.now();
|
|
70
|
+
const tenSecondsAgo = now - 10000; // 10 seconds
|
|
71
|
+
const recentRequests = ipRequestHistory.get(ip).filter(t => t > tenSecondsAgo);
|
|
72
|
+
|
|
73
|
+
return recentRequests.length;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function get404Count(ip) {
|
|
77
|
+
return ip404Counts.get(ip) || 0;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Helper to mark request start time for response time calculation
|
|
81
|
+
function markRequestStart(req) {
|
|
82
|
+
req._startTime = Date.now();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Helper to calculate response time from marked start
|
|
86
|
+
function getResponseTime(req) {
|
|
87
|
+
if (req._startTime) {
|
|
88
|
+
return Date.now() - req._startTime;
|
|
89
|
+
}
|
|
90
|
+
return 0;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function extractFeatures(req, res = null) {
|
|
94
94
|
const uri = req.path || req.url;
|
|
95
95
|
const ip = req.ip || req.socket?.remoteAddress || req.connection?.remoteAddress || 'unknown';
|
|
96
|
-
|
|
97
|
-
// Get status code from response if available, otherwise default to 200
|
|
98
|
-
let statusCode = 200;
|
|
99
|
-
if (res && res.statusCode) {
|
|
100
|
-
statusCode = res.statusCode;
|
|
101
|
-
} else if (req.res && req.res.statusCode) {
|
|
102
|
-
statusCode = req.res.statusCode;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
// Record this request for burst/404 tracking
|
|
106
|
-
recordRequest(ip, statusCode);
|
|
107
|
-
|
|
108
|
-
const redis = getClient();
|
|
109
|
-
const cacheKey = `features:${uri.toLowerCase()}:${ip}`;
|
|
110
|
-
|
|
111
|
-
// Custom cache logic
|
|
112
|
-
if (customCache?.get && customCache?.set) {
|
|
113
|
-
try {
|
|
114
|
-
const cached = await customCache.get(cacheKey);
|
|
115
|
-
if (cached) return cached;
|
|
116
|
-
} catch (err) {
|
|
117
|
-
console.warn('Custom cache read failed:', err.message);
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// Redis check
|
|
122
|
-
if (redis) {
|
|
123
|
-
try {
|
|
124
|
-
const cached = await redis.get(cacheKey);
|
|
125
|
-
if (cached) return JSON.parse(cached);
|
|
126
|
-
} catch (err) {
|
|
127
|
-
console.warn('
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// Compute features
|
|
132
|
-
const pathLen = uri.length;
|
|
133
|
-
const kwHits = STATIC_KW.reduce((count, kw) => count + (uri.toLowerCase().includes(kw) ? 1 : 0), 0);
|
|
134
|
-
const statusIdx = STATUS_IDX.indexOf(String(statusCode));
|
|
135
|
-
|
|
136
|
-
// Response time - try multiple sources
|
|
137
|
-
let responseTime = 0;
|
|
138
|
-
if (req.headers && req.headers['x-response-time']) {
|
|
139
|
-
responseTime = parseFloat(req.headers['x-response-time']);
|
|
140
|
-
} else if (req.responseTime) {
|
|
141
|
-
responseTime = req.responseTime;
|
|
142
|
-
} else if (req._startTime) {
|
|
143
|
-
responseTime = Date.now() - req._startTime;
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
// Calculate real burst and 404 counts
|
|
147
|
-
const burst = calculateBurstCount(ip);
|
|
148
|
-
const total404 = get404Count(ip);
|
|
149
|
-
|
|
150
|
-
const features = [pathLen, kwHits, statusIdx, responseTime, burst, total404];
|
|
151
|
-
|
|
152
|
-
// Write back to cache with shorter TTL for dynamic features
|
|
153
|
-
const ttl = 30; // 30 seconds TTL
|
|
154
|
-
|
|
155
|
-
if (customCache?.set) {
|
|
156
|
-
try {
|
|
157
|
-
await customCache.set(cacheKey, features, ttl);
|
|
158
|
-
} catch (err) {
|
|
159
|
-
console.warn('Custom cache write failed:', err.message);
|
|
160
|
-
}
|
|
161
|
-
} else if (redis) {
|
|
162
|
-
try {
|
|
163
|
-
await redis.set(cacheKey, JSON.stringify(features), { EX: ttl });
|
|
164
|
-
} catch (err) {
|
|
165
|
-
console.warn('
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
return features;
|
|
170
|
-
}
|
|
171
|
-
|
|
96
|
+
|
|
97
|
+
// Get status code from response if available, otherwise default to 200
|
|
98
|
+
let statusCode = 200;
|
|
99
|
+
if (res && res.statusCode) {
|
|
100
|
+
statusCode = res.statusCode;
|
|
101
|
+
} else if (req.res && req.res.statusCode) {
|
|
102
|
+
statusCode = req.res.statusCode;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Record this request for burst/404 tracking
|
|
106
|
+
recordRequest(ip, statusCode);
|
|
107
|
+
|
|
108
|
+
const redis = getClient();
|
|
109
|
+
const cacheKey = `features:${uri.toLowerCase()}:${ip}`;
|
|
110
|
+
|
|
111
|
+
// Custom cache logic
|
|
112
|
+
if (customCache?.get && customCache?.set) {
|
|
113
|
+
try {
|
|
114
|
+
const cached = await customCache.get(cacheKey);
|
|
115
|
+
if (cached) return cached;
|
|
116
|
+
} catch (err) {
|
|
117
|
+
console.warn('Custom cache read failed:', err.message);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Redis check
|
|
122
|
+
if (redis) {
|
|
123
|
+
try {
|
|
124
|
+
const cached = await redis.get(cacheKey);
|
|
125
|
+
if (cached) return JSON.parse(cached);
|
|
126
|
+
} catch (err) {
|
|
127
|
+
console.warn('Redis read failed. Falling back.', err.message);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Compute features
|
|
132
|
+
const pathLen = uri.length;
|
|
133
|
+
const kwHits = STATIC_KW.reduce((count, kw) => count + (uri.toLowerCase().includes(kw) ? 1 : 0), 0);
|
|
134
|
+
const statusIdx = STATUS_IDX.indexOf(String(statusCode));
|
|
135
|
+
|
|
136
|
+
// Response time - try multiple sources
|
|
137
|
+
let responseTime = 0;
|
|
138
|
+
if (req.headers && req.headers['x-response-time']) {
|
|
139
|
+
responseTime = parseFloat(req.headers['x-response-time']);
|
|
140
|
+
} else if (req.responseTime) {
|
|
141
|
+
responseTime = req.responseTime;
|
|
142
|
+
} else if (req._startTime) {
|
|
143
|
+
responseTime = Date.now() - req._startTime;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Calculate real burst and 404 counts
|
|
147
|
+
const burst = calculateBurstCount(ip);
|
|
148
|
+
const total404 = get404Count(ip);
|
|
149
|
+
|
|
150
|
+
const features = [pathLen, kwHits, statusIdx, responseTime, burst, total404];
|
|
151
|
+
|
|
152
|
+
// Write back to cache with shorter TTL for dynamic features
|
|
153
|
+
const ttl = 30; // 30 seconds TTL
|
|
154
|
+
|
|
155
|
+
if (customCache?.set) {
|
|
156
|
+
try {
|
|
157
|
+
await customCache.set(cacheKey, features, ttl);
|
|
158
|
+
} catch (err) {
|
|
159
|
+
console.warn('Custom cache write failed:', err.message);
|
|
160
|
+
}
|
|
161
|
+
} else if (redis) {
|
|
162
|
+
try {
|
|
163
|
+
await redis.set(cacheKey, JSON.stringify(features), { EX: ttl });
|
|
164
|
+
} catch (err) {
|
|
165
|
+
console.warn('Redis write failed. Ignoring.', err.message);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return features;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
172
|
module.exports = {
|
|
173
173
|
extractFeatures,
|
|
174
174
|
init,
|
package/lib/geoBlocker.js
CHANGED
|
@@ -100,9 +100,20 @@ function tryLoadMmdbReader(mmdbPath) {
|
|
|
100
100
|
|
|
101
101
|
module.exports = {
|
|
102
102
|
init(opts = {}) {
|
|
103
|
+
const packagedDefault = path.resolve(__dirname, '..', 'geolock', 'ipinfo_lite.mmdb');
|
|
104
|
+
const monorepoDefault = path.resolve(
|
|
105
|
+
__dirname,
|
|
106
|
+
'..',
|
|
107
|
+
'..',
|
|
108
|
+
'py',
|
|
109
|
+
'aiwaf',
|
|
110
|
+
'core',
|
|
111
|
+
'geolock',
|
|
112
|
+
'ipinfo_lite.mmdb'
|
|
113
|
+
);
|
|
103
114
|
const resolvedPath = opts.AIWAF_GEO_MMDB_PATH
|
|
104
115
|
? path.resolve(opts.AIWAF_GEO_MMDB_PATH)
|
|
105
|
-
:
|
|
116
|
+
: (fs.existsSync(packagedDefault) ? packagedDefault : monorepoDefault);
|
|
106
117
|
config = {
|
|
107
118
|
enabled: !!opts.AIWAF_GEO_BLOCK_ENABLED,
|
|
108
119
|
blocked: (opts.AIWAF_GEO_BLOCK_COUNTRIES || []).map(normalizeCountry),
|
package/lib/hapiPlugin.js
CHANGED
package/lib/isolationForest.js
CHANGED
|
@@ -1,117 +1,117 @@
|
|
|
1
|
-
class IsolationTree {
|
|
2
|
-
constructor(depth = 0, maxDepth = 0) {
|
|
3
|
-
this.depth = depth;
|
|
4
|
-
this.maxDepth = maxDepth;
|
|
5
|
-
this.left = null;
|
|
6
|
-
this.right = null;
|
|
7
|
-
this.splitAttr = null;
|
|
8
|
-
this.splitValue = null;
|
|
9
|
-
this.size = 0;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
fit(data) {
|
|
13
|
-
this.size = data.length;
|
|
14
|
-
if (this.depth >= this.maxDepth || data.length <= 1) return;
|
|
15
|
-
const numFeatures = data[0].length;
|
|
16
|
-
this.splitAttr = Math.floor(Math.random() * numFeatures);
|
|
17
|
-
let vals = data.map(row => row[this.splitAttr]);
|
|
18
|
-
const min = Math.min(...vals), max = Math.max(...vals);
|
|
19
|
-
if (min === max) return;
|
|
20
|
-
this.splitValue = min + Math.random() * (max - min);
|
|
21
|
-
const leftData = [], rightData = [];
|
|
22
|
-
for (let row of data) {
|
|
23
|
-
(row[this.splitAttr] < this.splitValue ? leftData : rightData).push(row);
|
|
24
|
-
}
|
|
25
|
-
this.left = new IsolationTree(this.depth + 1, this.maxDepth);
|
|
26
|
-
this.right = new IsolationTree(this.depth + 1, this.maxDepth);
|
|
27
|
-
this.left.fit(leftData);
|
|
28
|
-
this.right.fit(rightData);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
pathLength(point) {
|
|
32
|
-
if (!this.left || !this.right) {
|
|
33
|
-
return this.depth + c(this.size);
|
|
34
|
-
}
|
|
35
|
-
return point[this.splitAttr] < this.splitValue
|
|
36
|
-
? this.left.pathLength(point)
|
|
37
|
-
: this.right.pathLength(point);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
serialize() {
|
|
41
|
-
return {
|
|
42
|
-
depth: this.depth,
|
|
43
|
-
maxDepth: this.maxDepth,
|
|
44
|
-
splitAttr: this.splitAttr,
|
|
45
|
-
splitValue: this.splitValue,
|
|
46
|
-
size: this.size,
|
|
47
|
-
left: this.left ? this.left.serialize() : null,
|
|
48
|
-
right: this.right ? this.right.serialize() : null
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
static deserialize(obj) {
|
|
53
|
-
const tree = new IsolationTree(obj.depth, obj.maxDepth);
|
|
54
|
-
tree.splitAttr = obj.splitAttr;
|
|
55
|
-
tree.splitValue = obj.splitValue;
|
|
56
|
-
tree.size = obj.size;
|
|
57
|
-
tree.left = obj.left ? IsolationTree.deserialize(obj.left) : null;
|
|
58
|
-
tree.right = obj.right ? IsolationTree.deserialize(obj.right) : null;
|
|
59
|
-
return tree;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// Average path length
|
|
64
|
-
function c(n) {
|
|
65
|
-
if (n <= 1) return 1;
|
|
66
|
-
return 2 * (Math.log(n - 1) + 0.5772156649) - (2 * (n - 1) / n);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
class IsolationForest {
|
|
70
|
-
constructor({ nTrees = 100, sampleSize = 256 } = {}) {
|
|
71
|
-
this.nTrees = nTrees;
|
|
72
|
-
this.sampleSize = sampleSize;
|
|
73
|
-
this.trees = [];
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
fit(data) {
|
|
77
|
-
const heightLimit = Math.ceil(Math.log2(this.sampleSize));
|
|
78
|
-
for (let i = 0; i < this.nTrees; i++) {
|
|
79
|
-
const sample = [];
|
|
80
|
-
for (let j = 0; j < this.sampleSize; j++) {
|
|
81
|
-
sample.push(data[Math.floor(Math.random() * data.length)]);
|
|
82
|
-
}
|
|
83
|
-
const tree = new IsolationTree(0, heightLimit);
|
|
84
|
-
tree.fit(sample);
|
|
85
|
-
this.trees.push(tree);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
anomalyScore(point) {
|
|
90
|
-
const pathLens = this.trees.map(t => t.pathLength(point));
|
|
91
|
-
const avgPath = pathLens.reduce((a, b) => a + b, 0) / this.nTrees;
|
|
92
|
-
return Math.pow(2, -avgPath / c(this.sampleSize));
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
isAnomaly(point, thresh = 0.5) {
|
|
96
|
-
return this.anomalyScore(point) > thresh;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
toJSON() {
|
|
100
|
-
return {
|
|
101
|
-
nTrees: this.nTrees,
|
|
102
|
-
sampleSize: this.sampleSize,
|
|
103
|
-
trees: this.trees.map(t => t.serialize())
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
static fromJSON(obj) {
|
|
108
|
-
const forest = new IsolationForest({
|
|
109
|
-
nTrees: obj.nTrees,
|
|
110
|
-
sampleSize: obj.sampleSize
|
|
111
|
-
});
|
|
112
|
-
forest.trees = obj.trees.map(IsolationTree.deserialize);
|
|
113
|
-
return forest;
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
module.exports = { IsolationForest };
|
|
1
|
+
class IsolationTree {
|
|
2
|
+
constructor(depth = 0, maxDepth = 0) {
|
|
3
|
+
this.depth = depth;
|
|
4
|
+
this.maxDepth = maxDepth;
|
|
5
|
+
this.left = null;
|
|
6
|
+
this.right = null;
|
|
7
|
+
this.splitAttr = null;
|
|
8
|
+
this.splitValue = null;
|
|
9
|
+
this.size = 0;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
fit(data) {
|
|
13
|
+
this.size = data.length;
|
|
14
|
+
if (this.depth >= this.maxDepth || data.length <= 1) return;
|
|
15
|
+
const numFeatures = data[0].length;
|
|
16
|
+
this.splitAttr = Math.floor(Math.random() * numFeatures);
|
|
17
|
+
let vals = data.map(row => row[this.splitAttr]);
|
|
18
|
+
const min = Math.min(...vals), max = Math.max(...vals);
|
|
19
|
+
if (min === max) return;
|
|
20
|
+
this.splitValue = min + Math.random() * (max - min);
|
|
21
|
+
const leftData = [], rightData = [];
|
|
22
|
+
for (let row of data) {
|
|
23
|
+
(row[this.splitAttr] < this.splitValue ? leftData : rightData).push(row);
|
|
24
|
+
}
|
|
25
|
+
this.left = new IsolationTree(this.depth + 1, this.maxDepth);
|
|
26
|
+
this.right = new IsolationTree(this.depth + 1, this.maxDepth);
|
|
27
|
+
this.left.fit(leftData);
|
|
28
|
+
this.right.fit(rightData);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
pathLength(point) {
|
|
32
|
+
if (!this.left || !this.right) {
|
|
33
|
+
return this.depth + c(this.size);
|
|
34
|
+
}
|
|
35
|
+
return point[this.splitAttr] < this.splitValue
|
|
36
|
+
? this.left.pathLength(point)
|
|
37
|
+
: this.right.pathLength(point);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
serialize() {
|
|
41
|
+
return {
|
|
42
|
+
depth: this.depth,
|
|
43
|
+
maxDepth: this.maxDepth,
|
|
44
|
+
splitAttr: this.splitAttr,
|
|
45
|
+
splitValue: this.splitValue,
|
|
46
|
+
size: this.size,
|
|
47
|
+
left: this.left ? this.left.serialize() : null,
|
|
48
|
+
right: this.right ? this.right.serialize() : null
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
static deserialize(obj) {
|
|
53
|
+
const tree = new IsolationTree(obj.depth, obj.maxDepth);
|
|
54
|
+
tree.splitAttr = obj.splitAttr;
|
|
55
|
+
tree.splitValue = obj.splitValue;
|
|
56
|
+
tree.size = obj.size;
|
|
57
|
+
tree.left = obj.left ? IsolationTree.deserialize(obj.left) : null;
|
|
58
|
+
tree.right = obj.right ? IsolationTree.deserialize(obj.right) : null;
|
|
59
|
+
return tree;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Average path length
|
|
64
|
+
function c(n) {
|
|
65
|
+
if (n <= 1) return 1;
|
|
66
|
+
return 2 * (Math.log(n - 1) + 0.5772156649) - (2 * (n - 1) / n);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
class IsolationForest {
|
|
70
|
+
constructor({ nTrees = 100, sampleSize = 256 } = {}) {
|
|
71
|
+
this.nTrees = nTrees;
|
|
72
|
+
this.sampleSize = sampleSize;
|
|
73
|
+
this.trees = [];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
fit(data) {
|
|
77
|
+
const heightLimit = Math.ceil(Math.log2(this.sampleSize));
|
|
78
|
+
for (let i = 0; i < this.nTrees; i++) {
|
|
79
|
+
const sample = [];
|
|
80
|
+
for (let j = 0; j < this.sampleSize; j++) {
|
|
81
|
+
sample.push(data[Math.floor(Math.random() * data.length)]);
|
|
82
|
+
}
|
|
83
|
+
const tree = new IsolationTree(0, heightLimit);
|
|
84
|
+
tree.fit(sample);
|
|
85
|
+
this.trees.push(tree);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
anomalyScore(point) {
|
|
90
|
+
const pathLens = this.trees.map(t => t.pathLength(point));
|
|
91
|
+
const avgPath = pathLens.reduce((a, b) => a + b, 0) / this.nTrees;
|
|
92
|
+
return Math.pow(2, -avgPath / c(this.sampleSize));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
isAnomaly(point, thresh = 0.5) {
|
|
96
|
+
return this.anomalyScore(point) > thresh;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
toJSON() {
|
|
100
|
+
return {
|
|
101
|
+
nTrees: this.nTrees,
|
|
102
|
+
sampleSize: this.sampleSize,
|
|
103
|
+
trees: this.trees.map(t => t.serialize())
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
static fromJSON(obj) {
|
|
108
|
+
const forest = new IsolationForest({
|
|
109
|
+
nTrees: obj.nTrees,
|
|
110
|
+
sampleSize: obj.sampleSize
|
|
111
|
+
});
|
|
112
|
+
forest.trees = obj.trees.map(IsolationTree.deserialize);
|
|
113
|
+
return forest;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
module.exports = { IsolationForest };
|
package/lib/keywordDetector.js
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
const { createKeywordMatcher } = require('./wasmAdapter');
|
|
2
|
+
let staticKeywords = [];
|
|
3
|
+
let matcherPromise = null;
|
|
4
|
+
module.exports = {
|
|
5
|
+
init(o) {
|
|
6
|
+
staticKeywords = o.staticKeywords || [];
|
|
7
|
+
matcherPromise = null;
|
|
8
|
+
},
|
|
9
|
+
check(path) { return staticKeywords.find(kw => path.includes(kw)); },
|
|
10
|
+
async checkAccelerated(path) {
|
|
11
|
+
if (!staticKeywords.length) return undefined;
|
|
12
|
+
if (!matcherPromise) matcherPromise = createKeywordMatcher(staticKeywords);
|
|
13
|
+
const pending = matcherPromise;
|
|
14
|
+
const matcher = await pending;
|
|
15
|
+
if (pending !== matcherPromise) return module.exports.check(path);
|
|
16
|
+
return matcher ? matcher.firstMatch(path) : module.exports.check(path);
|
|
17
|
+
}
|
|
18
|
+
};
|
package/lib/koaMiddleware.js
CHANGED
package/lib/modelStore.js
CHANGED
|
@@ -124,6 +124,20 @@ module.exports = {
|
|
|
124
124
|
}
|
|
125
125
|
},
|
|
126
126
|
|
|
127
|
+
async remove(opts = {}) {
|
|
128
|
+
const storage = opts.AIWAF_MODEL_STORAGE || 'file';
|
|
129
|
+
const cacheKey = getCacheKey(opts);
|
|
130
|
+
if (storage === 'cache') return cache.delete(cacheKey);
|
|
131
|
+
if (storage === 'db') {
|
|
132
|
+
await ensureDb();
|
|
133
|
+
return db('model_artifacts').del();
|
|
134
|
+
}
|
|
135
|
+
const modelPath = getModelPath(opts);
|
|
136
|
+
if (!fs.existsSync(modelPath)) return false;
|
|
137
|
+
fs.unlinkSync(modelPath);
|
|
138
|
+
return true;
|
|
139
|
+
},
|
|
140
|
+
|
|
127
141
|
cacheGet,
|
|
128
142
|
cacheSet
|
|
129
143
|
};
|
package/lib/nextMiddleware.js
CHANGED
package/lib/pathRules.js
CHANGED
|
@@ -106,11 +106,14 @@ function createRoutePlan(path, rules = [], context = {}) {
|
|
|
106
106
|
const exempt = new Set((context.exemptMiddlewares || []).map(normalizeMiddlewareName));
|
|
107
107
|
const fullyExempt = !!context.fullyExempt;
|
|
108
108
|
const enabled = new Set();
|
|
109
|
+
const rule = getPathRule(path, rules);
|
|
110
|
+
const disabledValues = rule && (rule.DISABLE || rule.disable);
|
|
111
|
+
const disabled = new Set(Array.isArray(disabledValues) ? disabledValues.map(normalizeMiddlewareName) : []);
|
|
109
112
|
|
|
110
113
|
ALL_MIDDLEWARES.forEach(name => {
|
|
111
114
|
if (required.has(name)) {
|
|
112
115
|
enabled.add(name);
|
|
113
|
-
} else if (
|
|
116
|
+
} else if (disabled.has(name) || fullyExempt || exempt.has(name)) {
|
|
114
117
|
return;
|
|
115
118
|
} else {
|
|
116
119
|
enabled.add(name);
|
|
@@ -122,7 +125,9 @@ function createRoutePlan(path, rules = [], context = {}) {
|
|
|
122
125
|
return enabled.has(normalizeMiddlewareName(name));
|
|
123
126
|
},
|
|
124
127
|
getOverrides(sectionKey) {
|
|
125
|
-
|
|
128
|
+
if (!rule || !sectionKey) return {};
|
|
129
|
+
const value = rule[String(sectionKey).toUpperCase()] || rule[String(sectionKey).toLowerCase()];
|
|
130
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};
|
|
126
131
|
},
|
|
127
132
|
enabledMiddlewares: enabled
|
|
128
133
|
};
|