aiwaf 1.0.0 → 1.0.1
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/README.md +1312 -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/blacklistManager.js +253 -33
- package/lib/csvStore.js +26 -9
- package/lib/fastifyPlugin.js +1 -0
- package/lib/featureUtils.js +2 -2
- package/lib/geoBlocker.js +12 -1
- package/lib/hapiPlugin.js +1 -0
- package/lib/koaMiddleware.js +1 -1
- package/lib/modelStore.js +14 -0
- package/lib/nextMiddleware.js +1 -1
- package/lib/rateLimiter.js +5 -5
- package/lib/redisClient.js +2 -2
- package/lib/reputation.js +67 -0
- package/lib/settingsCompat.js +3 -0
- package/lib/wafMiddleware.js +20 -12
- package/lib/wasmAdapter.js +4 -1
- package/package.json +29 -4
- package/train.js +11 -1
package/lib/csvStore.js
CHANGED
|
@@ -17,13 +17,27 @@ function escapeCsv(value) {
|
|
|
17
17
|
}
|
|
18
18
|
|
|
19
19
|
function parseCsvLine(line) {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
20
|
+
const cells = [];
|
|
21
|
+
let value = '';
|
|
22
|
+
let quoted = false;
|
|
23
|
+
for (let index = 0; index < String(line).length; index += 1) {
|
|
24
|
+
const char = String(line)[index];
|
|
25
|
+
if (char === '"') {
|
|
26
|
+
if (quoted && String(line)[index + 1] === '"') {
|
|
27
|
+
value += '"';
|
|
28
|
+
index += 1;
|
|
29
|
+
} else {
|
|
30
|
+
quoted = !quoted;
|
|
31
|
+
}
|
|
32
|
+
} else if (char === ',' && !quoted) {
|
|
33
|
+
cells.push(value.trim());
|
|
34
|
+
value = '';
|
|
35
|
+
} else {
|
|
36
|
+
value += char;
|
|
24
37
|
}
|
|
25
|
-
|
|
26
|
-
|
|
38
|
+
}
|
|
39
|
+
cells.push(value.trim());
|
|
40
|
+
return cells;
|
|
27
41
|
}
|
|
28
42
|
|
|
29
43
|
function readRows(filePath, headers) {
|
|
@@ -33,15 +47,18 @@ function readRows(filePath, headers) {
|
|
|
33
47
|
if (raw.length === 0) return [];
|
|
34
48
|
|
|
35
49
|
const fileHeader = parseCsvLine(raw[0]);
|
|
36
|
-
const
|
|
50
|
+
const hasHeader = fileHeader.some(header => headers.includes(header));
|
|
51
|
+
const sourceHeaders = hasHeader ? fileHeader : headers;
|
|
52
|
+
const startIndex = hasHeader ? 1 : 0;
|
|
37
53
|
const rows = [];
|
|
38
54
|
|
|
39
55
|
for (let i = startIndex; i < raw.length; i += 1) {
|
|
40
56
|
const cells = parseCsvLine(raw[i]);
|
|
41
57
|
if (cells.length === 0) continue;
|
|
42
58
|
const row = {};
|
|
43
|
-
headers.forEach(
|
|
44
|
-
|
|
59
|
+
headers.forEach(header => {
|
|
60
|
+
const index = sourceHeaders.indexOf(header);
|
|
61
|
+
row[header] = index >= 0 ? (cells[index] ?? '') : '';
|
|
45
62
|
});
|
|
46
63
|
rows.push(row);
|
|
47
64
|
}
|
package/lib/fastifyPlugin.js
CHANGED
package/lib/featureUtils.js
CHANGED
|
@@ -124,7 +124,7 @@ async function extractFeatures(req, res = null) {
|
|
|
124
124
|
const cached = await redis.get(cacheKey);
|
|
125
125
|
if (cached) return JSON.parse(cached);
|
|
126
126
|
} catch (err) {
|
|
127
|
-
console.warn('
|
|
127
|
+
console.warn('Redis read failed. Falling back.', err.message);
|
|
128
128
|
}
|
|
129
129
|
}
|
|
130
130
|
|
|
@@ -162,7 +162,7 @@ async function extractFeatures(req, res = null) {
|
|
|
162
162
|
try {
|
|
163
163
|
await redis.set(cacheKey, JSON.stringify(features), { EX: ttl });
|
|
164
164
|
} catch (err) {
|
|
165
|
-
console.warn('
|
|
165
|
+
console.warn('Redis write failed. Ignoring.', err.message);
|
|
166
166
|
}
|
|
167
167
|
}
|
|
168
168
|
|
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/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/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
|
@@ -11,13 +11,13 @@ 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
17
|
|
|
18
18
|
try {
|
|
19
19
|
client = createClient({ url: redisUrl });
|
|
20
|
-
client.on('error', err => console.warn('
|
|
20
|
+
client.on('error', err => console.warn('Redis error:', err));
|
|
21
21
|
await client.connect();
|
|
22
22
|
isReady = true;
|
|
23
23
|
console.log('Redis connected.');
|
|
@@ -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),
|
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');
|
|
@@ -384,7 +392,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
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
|
|
|
@@ -393,7 +401,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
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
|
|
|
@@ -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;
|
|
@@ -58,6 +57,10 @@ async function loadWasmFromPackageModule() {
|
|
|
58
57
|
async function loadWasm() {
|
|
59
58
|
if (wasmLoadAttempted) return wasmModule;
|
|
60
59
|
wasmLoadAttempted = true;
|
|
60
|
+
if (process.env.AIWAF_DISABLE_WASM === '1') {
|
|
61
|
+
wasmModule = null;
|
|
62
|
+
return wasmModule;
|
|
63
|
+
}
|
|
61
64
|
try {
|
|
62
65
|
// Optional dependency: aiwaf-wasm
|
|
63
66
|
// eslint-disable-next-line global-require, import/no-extraneous-dependencies
|
package/package.json
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiwaf",
|
|
3
|
-
"version": "1.0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "1.0.1",
|
|
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/
|
|
105
|
+
"url": "git+https://github.com/aayushgauba/aiwaf.git",
|
|
106
|
+
"directory": "js"
|
|
82
107
|
},
|
|
83
108
|
"author": "Aayush Gauba",
|
|
84
109
|
"license": "MIT"
|
package/train.js
CHANGED
|
@@ -148,9 +148,19 @@ function normalizeTokens(value) {
|
|
|
148
148
|
}
|
|
149
149
|
|
|
150
150
|
const LOGIN_PATH_PREFIXES = normalizeTokens(process.env.AIWAF_LOGIN_PATH_PREFIXES || '/admin/login/,/login/,/accounts/login/,/auth/login/,/signin/');
|
|
151
|
+
const PACKAGED_GEO_MMDB_PATH = path.resolve(__dirname, 'geolock', 'ipinfo_lite.mmdb');
|
|
152
|
+
const MONOREPO_GEO_MMDB_PATH = path.resolve(
|
|
153
|
+
__dirname,
|
|
154
|
+
'..',
|
|
155
|
+
'py',
|
|
156
|
+
'aiwaf',
|
|
157
|
+
'core',
|
|
158
|
+
'geolock',
|
|
159
|
+
'ipinfo_lite.mmdb'
|
|
160
|
+
);
|
|
151
161
|
const GEO_MMDB_PATH = process.env.AIWAF_GEO_MMDB_PATH
|
|
152
162
|
? path.resolve(process.env.AIWAF_GEO_MMDB_PATH)
|
|
153
|
-
:
|
|
163
|
+
: (fs.existsSync(PACKAGED_GEO_MMDB_PATH) ? PACKAGED_GEO_MMDB_PATH : MONOREPO_GEO_MMDB_PATH);
|
|
154
164
|
|
|
155
165
|
let geoReader = null;
|
|
156
166
|
function loadGeoReader() {
|