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/rateLimiter.js
CHANGED
|
@@ -8,8 +8,6 @@ let cleanupInterval;
|
|
|
8
8
|
const defaultMemoryCache = new NodeCache({ stdTTL: 60, checkperiod: 120 }); // Auto cleanup every 2 minutes
|
|
9
9
|
|
|
10
10
|
const fallbackCache = {
|
|
11
|
-
get: (key) => Promise.resolve(defaultMemoryCache.get(key)),
|
|
12
|
-
set: (key, value, ttl) => Promise.resolve(defaultMemoryCache.set(key, value, ttl)),
|
|
13
11
|
lPush: async (key, value) => {
|
|
14
12
|
const arr = defaultMemoryCache.get(key) || [];
|
|
15
13
|
arr.unshift(value);
|
|
@@ -116,7 +114,7 @@ module.exports = {
|
|
|
116
114
|
await blacklistManager.block(ip, 'flood');
|
|
117
115
|
}
|
|
118
116
|
} catch (err) {
|
|
119
|
-
console.warn('
|
|
117
|
+
console.warn('Cache error in record().', err.message);
|
|
120
118
|
}
|
|
121
119
|
},
|
|
122
120
|
|
|
@@ -125,7 +123,7 @@ module.exports = {
|
|
|
125
123
|
try {
|
|
126
124
|
if (await blacklistManager.isBlocked(ip)) return true;
|
|
127
125
|
} catch (err) {
|
|
128
|
-
console.warn('
|
|
126
|
+
console.warn('Blacklist check error:', err.message);
|
|
129
127
|
}
|
|
130
128
|
|
|
131
129
|
try {
|
|
@@ -135,11 +133,13 @@ module.exports = {
|
|
|
135
133
|
const within = timestamps.filter(t => now - t < effective.WINDOW_SEC * 1000);
|
|
136
134
|
return within.length > effective.MAX_REQ;
|
|
137
135
|
} catch (err) {
|
|
138
|
-
console.warn('
|
|
136
|
+
console.warn('Cache error in isBlocked().', err.message);
|
|
139
137
|
return false; // Fail open
|
|
140
138
|
}
|
|
141
139
|
},
|
|
142
140
|
|
|
141
|
+
cleanupExpired: cleanupOldTimestamps,
|
|
142
|
+
|
|
143
143
|
// Cleanup method for graceful shutdown
|
|
144
144
|
cleanup() {
|
|
145
145
|
if (cleanupInterval) {
|
package/lib/redisClient.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
// lib/redisManager.js
|
|
2
|
-
const { createClient } = require('redis');
|
|
3
|
-
|
|
4
|
-
let client = null;
|
|
5
|
-
let isReady = false;
|
|
6
|
-
|
|
1
|
+
// lib/redisManager.js
|
|
2
|
+
const { createClient } = require('redis');
|
|
3
|
+
|
|
4
|
+
let client = null;
|
|
5
|
+
let isReady = false;
|
|
6
|
+
|
|
7
7
|
function getRedisUrl() {
|
|
8
8
|
return process.env.REDIS_URL || process.env.AIWAF_REDIS_URL;
|
|
9
9
|
}
|
|
@@ -11,25 +11,25 @@ function getRedisUrl() {
|
|
|
11
11
|
async function connect() {
|
|
12
12
|
const redisUrl = getRedisUrl();
|
|
13
13
|
if (!redisUrl) {
|
|
14
|
-
console.warn('
|
|
14
|
+
console.warn('No REDIS_URL set. Redis disabled.');
|
|
15
15
|
return;
|
|
16
16
|
}
|
|
17
|
-
|
|
18
|
-
try {
|
|
17
|
+
|
|
18
|
+
try {
|
|
19
19
|
client = createClient({ url: redisUrl });
|
|
20
|
-
client.on('error', err => console.warn('
|
|
21
|
-
await client.connect();
|
|
22
|
-
isReady = true;
|
|
23
|
-
console.log('Redis connected.');
|
|
24
|
-
} catch (err) {
|
|
25
|
-
console.warn('Redis connection failed. Falling back.');
|
|
26
|
-
client = null;
|
|
27
|
-
isReady = false;
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function getClient() {
|
|
32
|
-
return isReady && client?.isOpen ? client : null;
|
|
33
|
-
}
|
|
34
|
-
|
|
20
|
+
client.on('error', err => console.warn('Redis error:', err));
|
|
21
|
+
await client.connect();
|
|
22
|
+
isReady = true;
|
|
23
|
+
console.log('Redis connected.');
|
|
24
|
+
} catch (err) {
|
|
25
|
+
console.warn('Redis connection failed. Falling back.');
|
|
26
|
+
client = null;
|
|
27
|
+
isReady = false;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function getClient() {
|
|
32
|
+
return isReady && client?.isOpen ? client : null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
35
|
module.exports = { connect, getClient, isReady: () => isReady };
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
const REASON_WEIGHTS = Object.freeze({
|
|
2
|
+
scanner: 20, scan: 20, sqli: 40, 'sql injection': 40, xss: 30,
|
|
3
|
+
bruteforce: 25, 'brute force': 25, flood: 25, 'rate limit': 20,
|
|
4
|
+
honeypot: 30, uuid: 25, header: 15, geo: 20, keyword: 20
|
|
5
|
+
});
|
|
6
|
+
const DEFAULT_REASON_WEIGHT = 10;
|
|
7
|
+
const BLOCK_THRESHOLD = 60;
|
|
8
|
+
const LONG_BLOCK_THRESHOLD = 80;
|
|
9
|
+
const FIRST_BLOCK_SECONDS = 15 * 60;
|
|
10
|
+
const SECOND_BLOCK_SECONDS = 60 * 60;
|
|
11
|
+
const REPEATED_BLOCK_SECONDS = 24 * 60 * 60;
|
|
12
|
+
|
|
13
|
+
function normalizeReason(reason) {
|
|
14
|
+
return String(reason || 'unknown').trim() || 'unknown';
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function reasonWeight(reason) {
|
|
18
|
+
const normalized = normalizeReason(reason).toLowerCase();
|
|
19
|
+
for (const [token, weight] of Object.entries(REASON_WEIGHTS)) {
|
|
20
|
+
if (normalized.includes(token)) return weight;
|
|
21
|
+
}
|
|
22
|
+
return DEFAULT_REASON_WEIGHT;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function uniqueReasons(values = []) {
|
|
26
|
+
const seen = new Set();
|
|
27
|
+
return values.reduce((result, value) => {
|
|
28
|
+
const reason = normalizeReason(value);
|
|
29
|
+
const key = reason.toLowerCase();
|
|
30
|
+
if (!seen.has(key)) { seen.add(key); result.push(reason); }
|
|
31
|
+
return result;
|
|
32
|
+
}, []);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function progressiveDuration(score, offenses) {
|
|
36
|
+
if (score < BLOCK_THRESHOLD) return null;
|
|
37
|
+
if (score >= LONG_BLOCK_THRESHOLD || offenses >= 3) return REPEATED_BLOCK_SECONDS;
|
|
38
|
+
if (offenses === 2) return SECOND_BLOCK_SECONDS;
|
|
39
|
+
return FIRST_BLOCK_SECONDS;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function evaluateReputation({ existing = {}, reason, now = Date.now() / 1000 } = {}) {
|
|
43
|
+
const previousReasons = Array.isArray(existing.reasons)
|
|
44
|
+
? existing.reasons
|
|
45
|
+
: (existing.reasons || existing.reason ? [existing.reasons || existing.reason] : []);
|
|
46
|
+
const offenses = Number(existing.offenses || 0) + 1;
|
|
47
|
+
const score = Math.min(100, Number(existing.score || 0) + reasonWeight(reason));
|
|
48
|
+
const duration = progressiveDuration(score, offenses);
|
|
49
|
+
return {
|
|
50
|
+
score,
|
|
51
|
+
offenses,
|
|
52
|
+
reasons: uniqueReasons([...previousReasons, normalizeReason(reason)]),
|
|
53
|
+
shouldBlock: score >= BLOCK_THRESHOLD,
|
|
54
|
+
duration,
|
|
55
|
+
expiresAt: duration ? Number(now) + duration : null
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function formatBlockReason(decision) {
|
|
60
|
+
return `${decision.reasons.join(', ')}; score=${decision.score}; offenses=${decision.offenses}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
module.exports = {
|
|
64
|
+
REASON_WEIGHTS, DEFAULT_REASON_WEIGHT, BLOCK_THRESHOLD, LONG_BLOCK_THRESHOLD,
|
|
65
|
+
FIRST_BLOCK_SECONDS, SECOND_BLOCK_SECONDS, REPEATED_BLOCK_SECONDS,
|
|
66
|
+
normalizeReason, reasonWeight, progressiveDuration, evaluateReputation, formatBlockReason
|
|
67
|
+
};
|
package/lib/settingsCompat.js
CHANGED
|
@@ -120,6 +120,9 @@ function normalizeSettings(rawOpts = {}) {
|
|
|
120
120
|
AIWAF_MIDDLEWARE_LOG_DB: toBool(firstDefined(rawOpts.AIWAF_MIDDLEWARE_LOG_DB, rawOpts.middlewareLogDb, legacy.logging?.dbEnabled, process.env.AIWAF_MIDDLEWARE_LOG_DB), false),
|
|
121
121
|
AIWAF_MIDDLEWARE_LOG_CSV: toBool(firstDefined(rawOpts.AIWAF_MIDDLEWARE_LOG_CSV, rawOpts.middlewareLogCsv, legacy.logging?.csvEnabled, process.env.AIWAF_MIDDLEWARE_LOG_CSV), false),
|
|
122
122
|
AIWAF_MIDDLEWARE_LOG_CSV_PATH: firstDefined(rawOpts.AIWAF_MIDDLEWARE_LOG_CSV_PATH, rawOpts.middlewareLogCsvPath, legacy.logging?.csvPath, process.env.AIWAF_MIDDLEWARE_LOG_CSV_PATH, 'logs/aiwaf-requests.csv'),
|
|
123
|
+
AIWAF_CAPTURE_EXTENDED_REQUEST_INFO: toBool(firstDefined(rawOpts.AIWAF_CAPTURE_EXTENDED_REQUEST_INFO, rawOpts.captureExtendedRequestInfo, legacy.logging?.captureExtendedRequestInfo, process.env.AIWAF_CAPTURE_EXTENDED_REQUEST_INFO), false),
|
|
124
|
+
AIWAF_EXTENDED_INFO_MAX_HEADERS: toNumber(firstDefined(rawOpts.AIWAF_EXTENDED_INFO_MAX_HEADERS, rawOpts.extendedInfoMaxHeaders, process.env.AIWAF_EXTENDED_INFO_MAX_HEADERS), 50),
|
|
125
|
+
AIWAF_EXTENDED_INFO_MAX_VALUE_LENGTH: toNumber(firstDefined(rawOpts.AIWAF_EXTENDED_INFO_MAX_VALUE_LENGTH, rawOpts.extendedInfoMaxValueLength, process.env.AIWAF_EXTENDED_INFO_MAX_VALUE_LENGTH), 512),
|
|
123
126
|
|
|
124
127
|
AIWAF_MIN_AI_LOGS: toNumber(firstDefined(rawOpts.AIWAF_MIN_AI_LOGS, rawOpts.minAiLogs, legacy.training?.minAiLogs, process.env.AIWAF_MIN_AI_LOGS), 0),
|
|
125
128
|
AIWAF_ENABLE_KEYWORD_LEARNING: toBool(firstDefined(rawOpts.AIWAF_ENABLE_KEYWORD_LEARNING, rawOpts.enableKeywordLearning, legacy.keywords?.enableLearning, process.env.AIWAF_ENABLE_KEYWORD_LEARNING), true),
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
const { extractWasmTrainingFeatures } = require('./wasmAdapter');
|
|
2
|
+
|
|
3
|
+
function lowerBound(values, target) {
|
|
4
|
+
let left = 0;
|
|
5
|
+
let right = values.length;
|
|
6
|
+
while (left < right) {
|
|
7
|
+
const mid = (left + right) >>> 1;
|
|
8
|
+
if (values[mid] < target) left = mid + 1;
|
|
9
|
+
else right = mid;
|
|
10
|
+
}
|
|
11
|
+
return left;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function upperBound(values, target) {
|
|
15
|
+
let left = 0;
|
|
16
|
+
let right = values.length;
|
|
17
|
+
while (left < right) {
|
|
18
|
+
const mid = (left + right) >>> 1;
|
|
19
|
+
if (values[mid] <= target) left = mid + 1;
|
|
20
|
+
else right = mid;
|
|
21
|
+
}
|
|
22
|
+
return left;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function calculateTrainingFeatures(parsedRequests, staticKeywords, statusIndices) {
|
|
26
|
+
const keywords = staticKeywords || [];
|
|
27
|
+
const statuses = statusIndices || [];
|
|
28
|
+
const ip404Counts = new Map();
|
|
29
|
+
const timestampsByIp = new Map();
|
|
30
|
+
|
|
31
|
+
for (const req of parsedRequests) {
|
|
32
|
+
if (!timestampsByIp.has(req.ip)) timestampsByIp.set(req.ip, []);
|
|
33
|
+
const timestamp = req.timestamp instanceof Date
|
|
34
|
+
? req.timestamp.getTime()
|
|
35
|
+
: new Date(req.timestamp).getTime();
|
|
36
|
+
if (Number.isFinite(timestamp)) timestampsByIp.get(req.ip).push(timestamp);
|
|
37
|
+
if (req.status === '404') {
|
|
38
|
+
ip404Counts.set(req.ip, (ip404Counts.get(req.ip) || 0) + 1);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
for (const timestamps of timestampsByIp.values()) timestamps.sort((a, b) => a - b);
|
|
42
|
+
|
|
43
|
+
// JS's persisted model format uses statusIdx before responseTime. Preserve that order.
|
|
44
|
+
const records = parsedRequests.map(req => {
|
|
45
|
+
const path = String(req.path || '');
|
|
46
|
+
const timestampMs = req.timestamp instanceof Date
|
|
47
|
+
? req.timestamp.getTime()
|
|
48
|
+
: new Date(req.timestamp).getTime();
|
|
49
|
+
return {
|
|
50
|
+
ip: String(req.ip),
|
|
51
|
+
path_lower: path.toLowerCase(),
|
|
52
|
+
path_len: path.length,
|
|
53
|
+
timestamp: timestampMs / 1000,
|
|
54
|
+
response_time: Number(req.responseTime),
|
|
55
|
+
status_idx: statuses.indexOf(req.status),
|
|
56
|
+
kw_check: true,
|
|
57
|
+
total_404: ip404Counts.get(req.ip) || 0
|
|
58
|
+
};
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
const canUseRust = records.every(rec => Number.isFinite(rec.timestamp) && Number.isFinite(rec.response_time))
|
|
62
|
+
&& keywords.every(kw => kw === String(kw).toLowerCase());
|
|
63
|
+
if (canUseRust && records.length > 0) {
|
|
64
|
+
const rustFeatures = await extractWasmTrainingFeatures(records, keywords);
|
|
65
|
+
if (Array.isArray(rustFeatures) && rustFeatures.length === records.length
|
|
66
|
+
&& rustFeatures.every(rec => rec && Number.isFinite(Number(rec.burst_count)))) {
|
|
67
|
+
return rustFeatures.map(rec => [
|
|
68
|
+
rec.path_len, rec.kw_hits, rec.status_idx, rec.resp_time, rec.burst_count, rec.total_404
|
|
69
|
+
]);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return parsedRequests.map((req, index) => {
|
|
74
|
+
const path = String(req.path || '');
|
|
75
|
+
const timestampMs = records[index].timestamp * 1000;
|
|
76
|
+
const times = timestampsByIp.get(req.ip) || [];
|
|
77
|
+
const burst = Number.isFinite(timestampMs)
|
|
78
|
+
? upperBound(times, timestampMs + 10000) - lowerBound(times, timestampMs - 10000)
|
|
79
|
+
: 0;
|
|
80
|
+
const kwHits = keywords.reduce((sum, kw) => sum + (path.toLowerCase().includes(kw) ? 1 : 0), 0);
|
|
81
|
+
return [path.length, kwHits, statuses.indexOf(req.status), req.responseTime, burst, ip404Counts.get(req.ip) || 0];
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
module.exports = { calculateTrainingFeatures };
|
package/lib/wafMiddleware.js
CHANGED
|
@@ -11,6 +11,7 @@ const geoBlocker = require('./geoBlocker');
|
|
|
11
11
|
const middlewareLogger = require('./middlewareLogger');
|
|
12
12
|
const exemptions = require('./exemptions');
|
|
13
13
|
const requestLogStore = require('./requestLogStore');
|
|
14
|
+
const { extractExtendedRequestInfo } = require('./runtimeUtils');
|
|
14
15
|
const { extractFeatures, init: initFeatureUtils, markRequestStart, STATIC_KW } = require('./featureUtils');
|
|
15
16
|
const { normalizeSettings } = require('./settingsCompat');
|
|
16
17
|
const {
|
|
@@ -201,6 +202,13 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
201
202
|
}
|
|
202
203
|
const routePlan = createRoutePlan(path, pathRules, req.aiwafRoute || {});
|
|
203
204
|
const shouldApply = name => enabledMiddlewares.has(normalizeMiddlewareName(name)) && routePlan.shouldApply(name);
|
|
205
|
+
const blockIp = reason => blacklistManager.block(ip, reason, {
|
|
206
|
+
extendedRequestInfo: extractExtendedRequestInfo(req, {
|
|
207
|
+
enabled: opts.AIWAF_CAPTURE_EXTENDED_REQUEST_INFO,
|
|
208
|
+
maxHeaders: opts.AIWAF_EXTENDED_INFO_MAX_HEADERS,
|
|
209
|
+
maxValueLength: opts.AIWAF_EXTENDED_INFO_MAX_VALUE_LENGTH
|
|
210
|
+
}) || {}
|
|
211
|
+
});
|
|
204
212
|
|
|
205
213
|
// Debug: Log first character of path to ensure it's being captured
|
|
206
214
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
@@ -231,7 +239,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
231
239
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
232
240
|
console.error(`[AIWAF-BLOCK-METHOD] method=${method} not in allowed=${allowed.join(',')}`);
|
|
233
241
|
}
|
|
234
|
-
await
|
|
242
|
+
await blockIp(`method_not_allowed:${method}`);
|
|
235
243
|
return deny(405, 'blocked', `method_not_allowed:${method}`);
|
|
236
244
|
}
|
|
237
245
|
}
|
|
@@ -256,7 +264,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
256
264
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
257
265
|
console.error(`[AIWAF-BLOCK-HEADER] reason=${headerReason}`);
|
|
258
266
|
}
|
|
259
|
-
await
|
|
267
|
+
await blockIp(headerReason);
|
|
260
268
|
return deny(403, 'blocked', headerReason);
|
|
261
269
|
}
|
|
262
270
|
}
|
|
@@ -276,7 +284,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
276
284
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
277
285
|
console.error(`[AIWAF-BLOCK-WASM-HEADER] reason=${headerWasmReason}`);
|
|
278
286
|
}
|
|
279
|
-
await
|
|
287
|
+
await blockIp(`wasm_header:${headerWasmReason}`);
|
|
280
288
|
return deny(403, 'blocked', `wasm_header:${headerWasmReason}`);
|
|
281
289
|
}
|
|
282
290
|
|
|
@@ -290,7 +298,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
290
298
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
291
299
|
console.error(`[AIWAF-BLOCK-WASM-URL] reason=${urlWasmReason}`);
|
|
292
300
|
}
|
|
293
|
-
await
|
|
301
|
+
await blockIp(`wasm_url:${urlWasmReason}`);
|
|
294
302
|
return deny(403, 'blocked', `wasm_url:${urlWasmReason}`);
|
|
295
303
|
}
|
|
296
304
|
|
|
@@ -314,7 +322,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
314
322
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
315
323
|
console.error(`[AIWAF-BLOCK-WASM-CONTENT] reason=${contentWasmReason}`);
|
|
316
324
|
}
|
|
317
|
-
await
|
|
325
|
+
await blockIp(`wasm_content:${contentWasmReason}`);
|
|
318
326
|
return deny(403, 'blocked', `wasm_content:${contentWasmReason}`);
|
|
319
327
|
}
|
|
320
328
|
}
|
|
@@ -332,7 +340,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
332
340
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
333
341
|
console.error(`[AIWAF-BLOCK-WASM-RECENT] reason=${recentWasmReason}`);
|
|
334
342
|
}
|
|
335
|
-
await
|
|
343
|
+
await blockIp(`wasm_recent:${recentWasmReason}`);
|
|
336
344
|
return deny(403, 'blocked', `wasm_recent:${recentWasmReason}`);
|
|
337
345
|
}
|
|
338
346
|
}
|
|
@@ -345,7 +353,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
345
353
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
346
354
|
console.error(`[AIWAF-BLOCK-GEO] reason=${geoResult.reason}`);
|
|
347
355
|
}
|
|
348
|
-
await
|
|
356
|
+
await blockIp(geoResult.reason || 'geo_block');
|
|
349
357
|
return deny(403, 'blocked', geoResult.reason || 'geo_block', geoResult.country);
|
|
350
358
|
}
|
|
351
359
|
}
|
|
@@ -356,7 +364,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
356
364
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
357
365
|
console.error(`[AIWAF-BLOCK-HONEYPOT] reason=${honeypotResult.reason}`);
|
|
358
366
|
}
|
|
359
|
-
await
|
|
367
|
+
await blockIp(honeypotResult.reason || 'honeypot');
|
|
360
368
|
const status = honeypotResult.statusCode || 403;
|
|
361
369
|
const code = honeypotResult.errorCode || 'bot_detected';
|
|
362
370
|
return deny(status, code, honeypotResult.reason || 'honeypot');
|
|
@@ -379,21 +387,21 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
379
387
|
}
|
|
380
388
|
|
|
381
389
|
if (shouldApply('ip_keyword_block')) {
|
|
382
|
-
const staticMatch = keywordDetector.
|
|
390
|
+
const staticMatch = await keywordDetector.checkAccelerated(path);
|
|
383
391
|
if (staticMatch && !exemptions.shouldSkipKeyword(staticMatch, path)) {
|
|
384
392
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
385
393
|
console.error(`[AIWAF-BLOCK-STATIC-KW] match=${staticMatch}`);
|
|
386
394
|
}
|
|
387
|
-
await
|
|
395
|
+
await blockIp(`static:${staticMatch}`);
|
|
388
396
|
return deny(403, 'blocked', `static:${staticMatch}`);
|
|
389
397
|
}
|
|
390
398
|
|
|
391
|
-
const dynamicMatch = dynamicKeyword.
|
|
399
|
+
const dynamicMatch = await dynamicKeyword.checkAccelerated(path);
|
|
392
400
|
if (dynamicMatch && !exemptions.shouldSkipKeyword(dynamicMatch, path)) {
|
|
393
401
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
394
402
|
console.error(`[AIWAF-BLOCK-DYNAMIC-KW] match=${dynamicMatch}`);
|
|
395
403
|
}
|
|
396
|
-
await
|
|
404
|
+
await blockIp(`dynamic:${dynamicMatch}`);
|
|
397
405
|
return deny(403, 'blocked', `dynamic:${dynamicMatch}`);
|
|
398
406
|
}
|
|
399
407
|
}
|
|
@@ -402,7 +410,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
402
410
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
403
411
|
console.error(`[AIWAF-BLOCK-UUID]`);
|
|
404
412
|
}
|
|
405
|
-
await
|
|
413
|
+
await blockIp('uuid');
|
|
406
414
|
return deny(403, 'blocked', 'uuid');
|
|
407
415
|
}
|
|
408
416
|
|
|
@@ -428,7 +436,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
428
436
|
}))
|
|
429
437
|
.filter(entry => now - entry.timestamp <= 5 * 60 * 1000);
|
|
430
438
|
|
|
431
|
-
const stats = anomalyDetector.
|
|
439
|
+
const stats = await anomalyDetector.analyzeRecentBehaviorAccelerated(recentData);
|
|
432
440
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
433
441
|
console.error(`[AIWAF-ANOMALY-STATS] should_block=${stats?.should_block}`);
|
|
434
442
|
}
|
|
@@ -437,7 +445,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
437
445
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
438
446
|
console.error(`[AIWAF-ANOMALY-BLOCKING] reason=${reason}`);
|
|
439
447
|
}
|
|
440
|
-
await
|
|
448
|
+
await blockIp(reason);
|
|
441
449
|
return deny(403, 'blocked', 'anomaly');
|
|
442
450
|
}
|
|
443
451
|
} else if (!anomalyDetector.isModelSufficientlyTrained()) {
|
package/lib/wasmAdapter.js
CHANGED
|
@@ -2,7 +2,6 @@ const fs = require('fs');
|
|
|
2
2
|
const path = require('path');
|
|
3
3
|
const { pathToFileURL } = require('url');
|
|
4
4
|
const { IsolationForest } = require('./isolationForest');
|
|
5
|
-
console.log(require('../node_modules/aiwaf-wasm/package.json').version);
|
|
6
5
|
let wasmModule = null;
|
|
7
6
|
let wasmLoadAttempted = false;
|
|
8
7
|
let wasmLoadError = null;
|
|
@@ -31,10 +30,12 @@ async function loadWasmFromDisk() {
|
|
|
31
30
|
return {
|
|
32
31
|
AiwafIsolationForest: bg.IsolationForest,
|
|
33
32
|
IsolationForest: bg.IsolationForest,
|
|
33
|
+
KeywordMatcher: bg.KeywordMatcher,
|
|
34
34
|
validate_headers: bg.validate_headers,
|
|
35
35
|
validate_headers_with_config: bg.validate_headers_with_config,
|
|
36
36
|
analyze_recent_behavior: bg.analyze_recent_behavior,
|
|
37
37
|
extract_features: bg.extract_features,
|
|
38
|
+
extract_training_features: bg.extract_training_features,
|
|
38
39
|
extract_features_batch_with_state: bg.extract_features_batch_with_state,
|
|
39
40
|
finalize_feature_state: bg.finalize_feature_state,
|
|
40
41
|
build_records: bg.build_records,
|
|
@@ -58,6 +59,10 @@ async function loadWasmFromPackageModule() {
|
|
|
58
59
|
async function loadWasm() {
|
|
59
60
|
if (wasmLoadAttempted) return wasmModule;
|
|
60
61
|
wasmLoadAttempted = true;
|
|
62
|
+
if (process.env.AIWAF_DISABLE_WASM === '1') {
|
|
63
|
+
wasmModule = null;
|
|
64
|
+
return wasmModule;
|
|
65
|
+
}
|
|
61
66
|
try {
|
|
62
67
|
// Optional dependency: aiwaf-wasm
|
|
63
68
|
// eslint-disable-next-line global-require, import/no-extraneous-dependencies
|
|
@@ -216,8 +221,9 @@ function normalizeValidationResult(result, fallbackReason) {
|
|
|
216
221
|
|
|
217
222
|
function normalizeRecentEntries(entries = []) {
|
|
218
223
|
return (Array.isArray(entries) ? entries : []).map(entry => {
|
|
219
|
-
const
|
|
220
|
-
const
|
|
224
|
+
const hasMilliseconds = entry.timestamp_ms !== undefined && entry.timestamp_ms !== null;
|
|
225
|
+
const rawTimestamp = Number(hasMilliseconds ? entry.timestamp_ms : (entry.timestamp ?? entry.timestamp_epoch ?? Date.now()));
|
|
226
|
+
const timestamp = (hasMilliseconds || rawTimestamp > 1000000000000) ? rawTimestamp / 1000 : rawTimestamp;
|
|
221
227
|
return {
|
|
222
228
|
path_lower: String(entry.path_lower || entry.path || '').toLowerCase(),
|
|
223
229
|
timestamp: Number.isFinite(timestamp) ? timestamp : Date.now() / 1000,
|
|
@@ -379,6 +385,31 @@ async function extractWasmFeatures(records, staticKeywords = []) {
|
|
|
379
385
|
}
|
|
380
386
|
}
|
|
381
387
|
|
|
388
|
+
async function extractWasmTrainingFeatures(records, staticKeywords = []) {
|
|
389
|
+
const mod = await loadWasm();
|
|
390
|
+
if (!mod || typeof mod.extract_training_features !== 'function') return null;
|
|
391
|
+
try {
|
|
392
|
+
return mod.extract_training_features(records || [], staticKeywords || []);
|
|
393
|
+
} catch (err) {
|
|
394
|
+
return null;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
async function createKeywordMatcher(keywords = []) {
|
|
399
|
+
const mod = await loadWasm();
|
|
400
|
+
if (!mod || typeof mod.KeywordMatcher !== 'function') return null;
|
|
401
|
+
try {
|
|
402
|
+
const matcher = new mod.KeywordMatcher(keywords);
|
|
403
|
+
return {
|
|
404
|
+
firstMatch(path) {
|
|
405
|
+
return matcher.first_match(path) || null;
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
} catch (err) {
|
|
409
|
+
return null;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
382
413
|
async function extractWasmFeaturesBatchWithState(records, staticKeywords = [], state = null) {
|
|
383
414
|
const mod = await loadWasm();
|
|
384
415
|
if (!mod || typeof mod.extract_features_batch_with_state !== 'function') return null;
|
|
@@ -470,6 +501,8 @@ module.exports = {
|
|
|
470
501
|
validateRecent,
|
|
471
502
|
analyzeRecentBehavior,
|
|
472
503
|
extractWasmFeatures,
|
|
504
|
+
extractWasmTrainingFeatures,
|
|
505
|
+
createKeywordMatcher,
|
|
473
506
|
extractWasmFeaturesBatchWithState,
|
|
474
507
|
finalizeWasmFeatureState,
|
|
475
508
|
buildWasmRecords,
|
package/package.json
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiwaf",
|
|
3
|
-
"version": "1.0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "1.0.2",
|
|
4
|
+
"description": "AIWAF Web Application Firewall for JavaScript applications and major Node.js frameworks",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"files": [
|
|
7
7
|
"index.js",
|
|
8
8
|
"bin/",
|
|
9
9
|
"lib/",
|
|
10
|
+
"geolock/",
|
|
10
11
|
"resources/",
|
|
11
12
|
"utils/",
|
|
12
13
|
"train.js",
|
|
@@ -21,10 +22,15 @@
|
|
|
21
22
|
"retrain": "AIWAF_LOG_PATH=/var/log/nginx/access.log npm run train",
|
|
22
23
|
"train": "node train.js",
|
|
23
24
|
"test": "jest --runInBand",
|
|
25
|
+
"test:coverage": "jest --runInBand --coverage",
|
|
26
|
+
"test:wasm": "jest --runInBand --runTestsByPath test/wasmAdapter.test.js test/wasm-header-config.test.js test/wasm-header-input.test.js test/wasm-retrain-behavior.test.js test/wasm-waf-integration.test.js && node test/wasm-real.js",
|
|
24
27
|
"aiwaf": "node bin/aiwaf.js",
|
|
25
28
|
"perf:wasm": "node test/perf-wasm.js",
|
|
26
29
|
"test:wasm-real": "node test/wasm-real.js"
|
|
27
30
|
},
|
|
31
|
+
"allowScripts": {
|
|
32
|
+
"sqlite3": true
|
|
33
|
+
},
|
|
28
34
|
"dependencies": {
|
|
29
35
|
"@babel/parser": "^7.29.2",
|
|
30
36
|
"aiwaf-wasm": "^0.2.0",
|
|
@@ -50,7 +56,25 @@
|
|
|
50
56
|
},
|
|
51
57
|
"jest": {
|
|
52
58
|
"globalTeardown": "<rootDir>/test/jest.teardown.js",
|
|
53
|
-
"forceExit": true
|
|
59
|
+
"forceExit": true,
|
|
60
|
+
"coverageProvider": "v8",
|
|
61
|
+
"testPathIgnorePatterns": [
|
|
62
|
+
"<rootDir>/test/wasm-adapter-real.test.js"
|
|
63
|
+
],
|
|
64
|
+
"collectCoverageFrom": [
|
|
65
|
+
"index.js",
|
|
66
|
+
"train.js",
|
|
67
|
+
"lib/**/*.js",
|
|
68
|
+
"utils/**/*.js"
|
|
69
|
+
],
|
|
70
|
+
"coverageThreshold": {
|
|
71
|
+
"global": {
|
|
72
|
+
"branches": 66,
|
|
73
|
+
"functions": 100,
|
|
74
|
+
"lines": 80,
|
|
75
|
+
"statements": 80
|
|
76
|
+
}
|
|
77
|
+
}
|
|
54
78
|
},
|
|
55
79
|
"optionalDependencies": {
|
|
56
80
|
"maxmind": "^4.3.0"
|
|
@@ -78,7 +102,8 @@
|
|
|
78
102
|
],
|
|
79
103
|
"repository": {
|
|
80
104
|
"type": "git",
|
|
81
|
-
"url": "git+https://github.com/aiwaf-project/aiwaf
|
|
105
|
+
"url": "git+https://github.com/aiwaf-project/aiwaf.git",
|
|
106
|
+
"directory": "js"
|
|
82
107
|
},
|
|
83
108
|
"author": "Aayush Gauba",
|
|
84
109
|
"license": "MIT"
|