aiwaf 1.0.0
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/INSTALLATION.md +144 -0
- package/LICENSE +21 -0
- package/README.md +621 -0
- package/bin/aiwaf.js +349 -0
- package/index.js +62 -0
- package/lib/adonisMiddleware.js +82 -0
- package/lib/anomalyDetector.js +221 -0
- package/lib/blacklistManager.js +134 -0
- package/lib/blockResponses.js +25 -0
- package/lib/csvStore.js +84 -0
- package/lib/dynamicKeyword.js +42 -0
- package/lib/dynamicKeywordStore.js +169 -0
- package/lib/exemptionStore.js +204 -0
- package/lib/exemptions.js +56 -0
- package/lib/fastifyPlugin.js +49 -0
- package/lib/featureUtils.js +183 -0
- package/lib/geoBlocker.js +159 -0
- package/lib/geoPolicy.js +42 -0
- package/lib/geoStore.js +111 -0
- package/lib/hapiPlugin.js +92 -0
- package/lib/headerValidation.js +275 -0
- package/lib/honeypotDetector.js +91 -0
- package/lib/isolationForest.js +117 -0
- package/lib/keywordDetector.js +5 -0
- package/lib/keywordFallbackStore.js +39 -0
- package/lib/koaMiddleware.js +68 -0
- package/lib/middlewareLogger.js +123 -0
- package/lib/middlewarePlan.js +72 -0
- package/lib/modelSecurity.js +17 -0
- package/lib/modelStore.js +129 -0
- package/lib/nestMiddleware.js +12 -0
- package/lib/nextMiddleware.js +78 -0
- package/lib/pathManifest.js +533 -0
- package/lib/pathRules.js +184 -0
- package/lib/rateLimiter.js +153 -0
- package/lib/redisClient.js +35 -0
- package/lib/requestLogStore.js +167 -0
- package/lib/runtimeUtils.js +166 -0
- package/lib/settingsCompat.js +140 -0
- package/lib/sourceAst.js +294 -0
- package/lib/trainingLogic.js +87 -0
- package/lib/uuidDetector.js +46 -0
- package/lib/wafMiddleware.js +459 -0
- package/lib/wasmAdapter.js +480 -0
- package/lib/whois.js +38 -0
- package/package.json +85 -0
- package/resources/model.json +9536 -0
- package/train.js +595 -0
- package/utils/cache.js +3 -0
- package/utils/db.js +11 -0
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
const rateLimiter = require('./rateLimiter');
|
|
2
|
+
const blacklistManager = require('./blacklistManager');
|
|
3
|
+
const keywordDetector = require('./keywordDetector');
|
|
4
|
+
const dynamicKeyword = require('./dynamicKeyword');
|
|
5
|
+
const dynamicKeywordStore = require('./dynamicKeywordStore');
|
|
6
|
+
const honeypotDetector = require('./honeypotDetector');
|
|
7
|
+
const uuidDetector = require('./uuidDetector');
|
|
8
|
+
const anomalyDetector = require('./anomalyDetector');
|
|
9
|
+
const headerValidation = require('./headerValidation');
|
|
10
|
+
const geoBlocker = require('./geoBlocker');
|
|
11
|
+
const middlewareLogger = require('./middlewareLogger');
|
|
12
|
+
const exemptions = require('./exemptions');
|
|
13
|
+
const requestLogStore = require('./requestLogStore');
|
|
14
|
+
const { extractFeatures, init: initFeatureUtils, markRequestStart, STATIC_KW } = require('./featureUtils');
|
|
15
|
+
const { normalizeSettings } = require('./settingsCompat');
|
|
16
|
+
const {
|
|
17
|
+
createRoutePlan,
|
|
18
|
+
normalizeMiddlewareName
|
|
19
|
+
} = require('./pathRules');
|
|
20
|
+
const {
|
|
21
|
+
isAutoSelection,
|
|
22
|
+
planEnabledMiddlewares
|
|
23
|
+
} = require('./middlewarePlan');
|
|
24
|
+
const { getEffectivePathRules } = require('./pathManifest');
|
|
25
|
+
const {
|
|
26
|
+
validateHeaders: wasmValidateHeaders,
|
|
27
|
+
validateUrl: wasmValidateUrl,
|
|
28
|
+
validateContent: wasmValidateContent,
|
|
29
|
+
validateRecent: wasmValidateRecent
|
|
30
|
+
} = require('./wasmAdapter');
|
|
31
|
+
|
|
32
|
+
function knownRoutes(app) {
|
|
33
|
+
// Skip route checking if app is undefined (common in proxy setups)
|
|
34
|
+
if (!app) return [];
|
|
35
|
+
const stack = app?._router?.stack || [];
|
|
36
|
+
return stack
|
|
37
|
+
.filter(layer => layer.route && layer.route.path)
|
|
38
|
+
.map(layer => layer.route.path);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function matchesKnownRoute(app, path) {
|
|
42
|
+
// In proxy setups, req.app may be undefined or not have routes
|
|
43
|
+
// Return true (treat as known) to skip anomaly detection on proxies
|
|
44
|
+
if (!app || !app._router || !app._router.stack) {
|
|
45
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
46
|
+
console.error(`[AIWAF-ROUTE-CHECK] app=${!!app} app._router=${!!app?._router} returning true (proxy setup)`);
|
|
47
|
+
}
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const routes = knownRoutes(app);
|
|
52
|
+
|
|
53
|
+
// If no routes found, assume this is a proxy setup and allow traffic
|
|
54
|
+
if (routes.length === 0) {
|
|
55
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
56
|
+
console.error(`[AIWAF-ROUTE-CHECK] no routes found, returning true (proxy setup)`);
|
|
57
|
+
}
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const result = routes.some(route => {
|
|
62
|
+
const regex = new RegExp(`^${String(route).replace(/:\\w+/g, '[^/]+')}$`);
|
|
63
|
+
return regex.test(path);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
67
|
+
console.error(`[AIWAF-ROUTE-CHECK] path=${path} matched=${result}`);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function hasUuidRoutes(app) {
|
|
74
|
+
if (!app || !app._router || !app._router.stack) return null;
|
|
75
|
+
const routes = knownRoutes(app);
|
|
76
|
+
if (routes.length === 0) return null;
|
|
77
|
+
return routes.some(route => /(^|[/:{_-])uuid([}/_-]|$)/i.test(String(route)));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function shouldReturnJson(req, opts) {
|
|
81
|
+
if (opts.AIWAF_FORCE_JSON_ERRORS) return true;
|
|
82
|
+
const accepts = req.headers?.accept || '';
|
|
83
|
+
const contentType = req.headers?.['content-type'] || '';
|
|
84
|
+
return accepts.includes('application/json') || contentType.includes('application/json') || req.xhr;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function normalizeHeaders(rawHeaders) {
|
|
88
|
+
return Object.fromEntries(
|
|
89
|
+
Object.entries(rawHeaders || {}).map(([key, value]) => {
|
|
90
|
+
let normalizedValue = value;
|
|
91
|
+
if (Array.isArray(normalizedValue)) {
|
|
92
|
+
normalizedValue = normalizedValue.join(', ');
|
|
93
|
+
} else if (normalizedValue !== undefined && normalizedValue !== null) {
|
|
94
|
+
normalizedValue = String(normalizedValue);
|
|
95
|
+
}
|
|
96
|
+
return [String(key).toLowerCase(), normalizedValue];
|
|
97
|
+
})
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function normalizedMiddlewareList(list) {
|
|
102
|
+
if (!Array.isArray(list)) return list;
|
|
103
|
+
return list.map(normalizeMiddlewareName);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function applyAutoMiddlewareDefaults(opts, enabled, rawOpts = {}) {
|
|
107
|
+
if (!isAutoSelection(opts.AIWAF_MIDDLEWARES)) return opts;
|
|
108
|
+
const nextOpts = { ...opts };
|
|
109
|
+
const legacy = rawOpts.AIWAF_SETTINGS || {};
|
|
110
|
+
const loggingExplicit = Object.prototype.hasOwnProperty.call(rawOpts, 'AIWAF_MIDDLEWARE_LOGGING')
|
|
111
|
+
|| Object.prototype.hasOwnProperty.call(rawOpts, 'middlewareLogging')
|
|
112
|
+
|| legacy.logging?.enabled !== undefined
|
|
113
|
+
|| process.env.AIWAF_MIDDLEWARE_LOGGING !== undefined;
|
|
114
|
+
const geoExplicit = Object.prototype.hasOwnProperty.call(rawOpts, 'AIWAF_GEO_BLOCK_ENABLED')
|
|
115
|
+
|| Object.prototype.hasOwnProperty.call(rawOpts, 'geoBlockEnabled')
|
|
116
|
+
|| legacy.geo?.enabled !== undefined
|
|
117
|
+
|| process.env.AIWAF_GEO_BLOCK_ENABLED !== undefined;
|
|
118
|
+
|
|
119
|
+
if (enabled.has('logging') && !loggingExplicit) {
|
|
120
|
+
nextOpts.AIWAF_MIDDLEWARE_LOGGING = true;
|
|
121
|
+
}
|
|
122
|
+
if (enabled.has('geo_block') && !geoExplicit) {
|
|
123
|
+
nextOpts.AIWAF_GEO_BLOCK_ENABLED = true;
|
|
124
|
+
}
|
|
125
|
+
return nextOpts;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
module.exports = function aiwaf(rawOpts = {}) {
|
|
130
|
+
let opts = normalizeSettings(rawOpts);
|
|
131
|
+
opts.AIWAF_MIDDLEWARES = normalizedMiddlewareList(opts.AIWAF_MIDDLEWARES);
|
|
132
|
+
opts.AIWAF_DISABLE_MIDDLEWARES = normalizedMiddlewareList(opts.AIWAF_DISABLE_MIDDLEWARES) || [];
|
|
133
|
+
const pathRules = getEffectivePathRules(opts.AIWAF_PATH_RULES, { manifestPath: opts.AIWAF_PATH_MANIFEST });
|
|
134
|
+
|
|
135
|
+
let enabledMiddlewares = planEnabledMiddlewares({
|
|
136
|
+
orderedAvailable: [
|
|
137
|
+
'geo_block',
|
|
138
|
+
'ip_keyword_block',
|
|
139
|
+
'rate_limit',
|
|
140
|
+
'ai_anomaly',
|
|
141
|
+
'honeypot',
|
|
142
|
+
'uuid_tamper',
|
|
143
|
+
'header_validation',
|
|
144
|
+
'logging'
|
|
145
|
+
],
|
|
146
|
+
requested: opts.AIWAF_MIDDLEWARES,
|
|
147
|
+
disabled: opts.AIWAF_DISABLE_MIDDLEWARES,
|
|
148
|
+
accessLog: opts.AIWAF_ACCESS_LOG,
|
|
149
|
+
geoEnabledFlag: !!opts.AIWAF_GEO_BLOCK_ENABLED,
|
|
150
|
+
staticBlockCountries: opts.AIWAF_GEO_BLOCK_COUNTRIES || [],
|
|
151
|
+
dynamicBlockCountries: [],
|
|
152
|
+
hasUuidRoutes: null
|
|
153
|
+
});
|
|
154
|
+
opts = applyAutoMiddlewareDefaults(opts, enabledMiddlewares, rawOpts);
|
|
155
|
+
|
|
156
|
+
rateLimiter.init(opts);
|
|
157
|
+
keywordDetector.init(opts);
|
|
158
|
+
dynamicKeyword.init(opts);
|
|
159
|
+
honeypotDetector.init(opts);
|
|
160
|
+
uuidDetector.init(opts);
|
|
161
|
+
anomalyDetector.init(opts);
|
|
162
|
+
initFeatureUtils(opts);
|
|
163
|
+
headerValidation.init(opts);
|
|
164
|
+
geoBlocker.init(opts);
|
|
165
|
+
middlewareLogger.init(opts);
|
|
166
|
+
exemptions.init(opts);
|
|
167
|
+
|
|
168
|
+
if (opts.AIWAF_CLEAR_STATE_ON_START) {
|
|
169
|
+
Promise.allSettled([
|
|
170
|
+
blacklistManager.clear(),
|
|
171
|
+
requestLogStore.clear(),
|
|
172
|
+
dynamicKeywordStore.clear()
|
|
173
|
+
]).catch(() => {});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return async (req, res, next) => {
|
|
177
|
+
const ipHdr = req.headers['x-forwarded-for'];
|
|
178
|
+
const ip = ipHdr ? ipHdr.split(',')[0].trim() : req.ip;
|
|
179
|
+
const path = String(req.path || req.url || '/').toLowerCase();
|
|
180
|
+
const method = String(req.method || 'GET').toUpperCase();
|
|
181
|
+
if (isAutoSelection(opts.AIWAF_MIDDLEWARES)) {
|
|
182
|
+
enabledMiddlewares = planEnabledMiddlewares({
|
|
183
|
+
orderedAvailable: [
|
|
184
|
+
'geo_block',
|
|
185
|
+
'ip_keyword_block',
|
|
186
|
+
'rate_limit',
|
|
187
|
+
'ai_anomaly',
|
|
188
|
+
'honeypot',
|
|
189
|
+
'uuid_tamper',
|
|
190
|
+
'header_validation',
|
|
191
|
+
'logging'
|
|
192
|
+
],
|
|
193
|
+
requested: opts.AIWAF_MIDDLEWARES,
|
|
194
|
+
disabled: opts.AIWAF_DISABLE_MIDDLEWARES,
|
|
195
|
+
accessLog: opts.AIWAF_ACCESS_LOG,
|
|
196
|
+
geoEnabledFlag: !!opts.AIWAF_GEO_BLOCK_ENABLED,
|
|
197
|
+
staticBlockCountries: opts.AIWAF_GEO_BLOCK_COUNTRIES || [],
|
|
198
|
+
dynamicBlockCountries: [],
|
|
199
|
+
hasUuidRoutes: hasUuidRoutes(req.app)
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
const routePlan = createRoutePlan(path, pathRules, req.aiwafRoute || {});
|
|
203
|
+
const shouldApply = name => enabledMiddlewares.has(normalizeMiddlewareName(name)) && routePlan.shouldApply(name);
|
|
204
|
+
|
|
205
|
+
// Debug: Log first character of path to ensure it's being captured
|
|
206
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
207
|
+
console.error(`[AIWAF-DEBUG] method=${method} path=${path} req.path=${req.path} req.url=${req.url} ip=${ip} req.ip=${req.ip} x-forwarded-for=${ipHdr}`);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (shouldApply('logging')) {
|
|
211
|
+
middlewareLogger.attach(req, res, { ip });
|
|
212
|
+
}
|
|
213
|
+
markRequestStart(req);
|
|
214
|
+
|
|
215
|
+
const deny = (status, code, reason, country = '') => {
|
|
216
|
+
middlewareLogger.markBlocked(res, reason || code, country);
|
|
217
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
218
|
+
console.error(`[AIWAF-BLOCK] status=${status} code=${code} reason=${reason} ip=${ip}`);
|
|
219
|
+
}
|
|
220
|
+
if (shouldReturnJson(req, opts)) {
|
|
221
|
+
res.status(status).json({ error: code });
|
|
222
|
+
} else {
|
|
223
|
+
res.status(status).send(code);
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
if (opts.AIWAF_METHOD_POLICY_ENABLED === true) {
|
|
228
|
+
const allowed = (opts.AIWAF_ALLOWED_METHODS || ['GET', 'POST', 'HEAD', 'OPTIONS'])
|
|
229
|
+
.map(m => String(m).toUpperCase());
|
|
230
|
+
if (!allowed.includes(method)) {
|
|
231
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
232
|
+
console.error(`[AIWAF-BLOCK-METHOD] method=${method} not in allowed=${allowed.join(',')}`);
|
|
233
|
+
}
|
|
234
|
+
await blacklistManager.block(ip, `method_not_allowed:${method}`);
|
|
235
|
+
return deny(405, 'blocked', `method_not_allowed:${method}`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
if (await exemptions.isExemptRequest(ip, path)) {
|
|
240
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
241
|
+
console.error(`[AIWAF-EXEMPT] path=${path}`);
|
|
242
|
+
}
|
|
243
|
+
return next();
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if (shouldApply('ip_keyword_block') && await blacklistManager.isBlocked(ip)) {
|
|
247
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
248
|
+
console.error(`[AIWAF-BLOCK-BLACKLIST] ip=${ip}`);
|
|
249
|
+
}
|
|
250
|
+
return deny(403, 'blocked', 'blacklist');
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if (shouldApply('header_validation')) {
|
|
254
|
+
const headerReason = headerValidation.validate(req);
|
|
255
|
+
if (headerReason) {
|
|
256
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
257
|
+
console.error(`[AIWAF-BLOCK-HEADER] reason=${headerReason}`);
|
|
258
|
+
}
|
|
259
|
+
await blacklistManager.block(ip, headerReason);
|
|
260
|
+
return deny(403, 'blocked', headerReason);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const headerValidationApplies = shouldApply('header_validation');
|
|
265
|
+
const ipKeywordApplies = shouldApply('ip_keyword_block');
|
|
266
|
+
const wasmValidationEnabled = opts.AIWAF_WASM_VALIDATION !== false && (headerValidationApplies || ipKeywordApplies);
|
|
267
|
+
const wasmHeaderValidationEnabled = opts.AIWAF_WASM_HEADER_VALIDATION !== false;
|
|
268
|
+
if (wasmValidationEnabled) {
|
|
269
|
+
const pathForHeaders = req.path || req.url || '';
|
|
270
|
+
const wasmConfig = headerValidation.getWasmConfig(req.method);
|
|
271
|
+
const shouldSkipWasmHeaders = headerValidation.isStaticRequest(pathForHeaders);
|
|
272
|
+
const headerWasmReason = (shouldSkipWasmHeaders || !wasmHeaderValidationEnabled || !headerValidationApplies)
|
|
273
|
+
? null
|
|
274
|
+
: await wasmValidateHeaders(normalizeHeaders(req.headers || {}), wasmConfig);
|
|
275
|
+
if (headerWasmReason) {
|
|
276
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
277
|
+
console.error(`[AIWAF-BLOCK-WASM-HEADER] reason=${headerWasmReason}`);
|
|
278
|
+
}
|
|
279
|
+
await blacklistManager.block(ip, `wasm_header:${headerWasmReason}`);
|
|
280
|
+
return deny(403, 'blocked', `wasm_header:${headerWasmReason}`);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
if (ipKeywordApplies) {
|
|
284
|
+
const host = req.headers?.host || '';
|
|
285
|
+
const urlPath = req.originalUrl || req.url || '/';
|
|
286
|
+
const protocol = req.protocol || (req.headers?.['x-forwarded-proto'] || 'http');
|
|
287
|
+
const fullUrl = host ? `${protocol}://${host}${urlPath}` : urlPath;
|
|
288
|
+
const urlWasmReason = await wasmValidateUrl(fullUrl);
|
|
289
|
+
if (urlWasmReason) {
|
|
290
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
291
|
+
console.error(`[AIWAF-BLOCK-WASM-URL] reason=${urlWasmReason}`);
|
|
292
|
+
}
|
|
293
|
+
await blacklistManager.block(ip, `wasm_url:${urlWasmReason}`);
|
|
294
|
+
return deny(403, 'blocked', `wasm_url:${urlWasmReason}`);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (req.body !== undefined && req.body !== null) {
|
|
298
|
+
let content = req.body;
|
|
299
|
+
if (Buffer.isBuffer(content)) {
|
|
300
|
+
content = content.toString('utf8');
|
|
301
|
+
} else if (typeof content === 'object') {
|
|
302
|
+
try {
|
|
303
|
+
content = JSON.stringify(content);
|
|
304
|
+
} catch (err) {
|
|
305
|
+
content = String(content);
|
|
306
|
+
}
|
|
307
|
+
} else {
|
|
308
|
+
content = String(content);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
if (content && content.length) {
|
|
312
|
+
const contentWasmReason = await wasmValidateContent(content);
|
|
313
|
+
if (contentWasmReason) {
|
|
314
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
315
|
+
console.error(`[AIWAF-BLOCK-WASM-CONTENT] reason=${contentWasmReason}`);
|
|
316
|
+
}
|
|
317
|
+
await blacklistManager.block(ip, `wasm_content:${contentWasmReason}`);
|
|
318
|
+
return deny(403, 'blocked', `wasm_content:${contentWasmReason}`);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
if (opts.AIWAF_WASM_VALIDATE_RECENT && shouldApply('ai_anomaly')) {
|
|
325
|
+
const recentRows = await requestLogStore.recent(200);
|
|
326
|
+
const recent = recentRows
|
|
327
|
+
.filter(row => row.ip_address === ip)
|
|
328
|
+
.map(row => ({ path: row.path, status: Number(row.status || 0) }));
|
|
329
|
+
if (recent.length) {
|
|
330
|
+
const recentWasmReason = await wasmValidateRecent(recent);
|
|
331
|
+
if (recentWasmReason) {
|
|
332
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
333
|
+
console.error(`[AIWAF-BLOCK-WASM-RECENT] reason=${recentWasmReason}`);
|
|
334
|
+
}
|
|
335
|
+
await blacklistManager.block(ip, `wasm_recent:${recentWasmReason}`);
|
|
336
|
+
return deny(403, 'blocked', `wasm_recent:${recentWasmReason}`);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
if (shouldApply('geo_block')) {
|
|
343
|
+
const geoResult = await geoBlocker.check(req);
|
|
344
|
+
if (geoResult.blocked) {
|
|
345
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
346
|
+
console.error(`[AIWAF-BLOCK-GEO] reason=${geoResult.reason}`);
|
|
347
|
+
}
|
|
348
|
+
await blacklistManager.block(ip, geoResult.reason || 'geo_block');
|
|
349
|
+
return deny(403, 'blocked', geoResult.reason || 'geo_block', geoResult.country);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
if (shouldApply('honeypot')) {
|
|
354
|
+
const honeypotResult = honeypotDetector.evaluate(req, ip, path);
|
|
355
|
+
if (honeypotResult.triggered) {
|
|
356
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
357
|
+
console.error(`[AIWAF-BLOCK-HONEYPOT] reason=${honeypotResult.reason}`);
|
|
358
|
+
}
|
|
359
|
+
await blacklistManager.block(ip, honeypotResult.reason || 'honeypot');
|
|
360
|
+
const status = honeypotResult.statusCode || 403;
|
|
361
|
+
const code = honeypotResult.errorCode || 'bot_detected';
|
|
362
|
+
return deny(status, code, honeypotResult.reason || 'honeypot');
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
if (shouldApply('rate_limit')) {
|
|
367
|
+
const rateOverrides = routePlan.getOverrides('RATE_LIMIT');
|
|
368
|
+
await rateLimiter.record(ip, rateOverrides);
|
|
369
|
+
|
|
370
|
+
if (await rateLimiter.isBlocked(ip, rateOverrides)) {
|
|
371
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
372
|
+
console.error(`[AIWAF-BLOCK-RATE] ip=${ip}`);
|
|
373
|
+
}
|
|
374
|
+
if (await blacklistManager.isBlocked(ip)) {
|
|
375
|
+
return deny(403, 'blocked', 'flood_or_blacklist');
|
|
376
|
+
}
|
|
377
|
+
return deny(429, 'too_many_requests', 'rate_limit');
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
if (shouldApply('ip_keyword_block')) {
|
|
382
|
+
const staticMatch = keywordDetector.check(path);
|
|
383
|
+
if (staticMatch && !exemptions.shouldSkipKeyword(staticMatch, path)) {
|
|
384
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
385
|
+
console.error(`[AIWAF-BLOCK-STATIC-KW] match=${staticMatch}`);
|
|
386
|
+
}
|
|
387
|
+
await blacklistManager.block(ip, `static:${staticMatch}`);
|
|
388
|
+
return deny(403, 'blocked', `static:${staticMatch}`);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const dynamicMatch = dynamicKeyword.check(path);
|
|
392
|
+
if (dynamicMatch && !exemptions.shouldSkipKeyword(dynamicMatch, path)) {
|
|
393
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
394
|
+
console.error(`[AIWAF-BLOCK-DYNAMIC-KW] match=${dynamicMatch}`);
|
|
395
|
+
}
|
|
396
|
+
await blacklistManager.block(ip, `dynamic:${dynamicMatch}`);
|
|
397
|
+
return deny(403, 'blocked', `dynamic:${dynamicMatch}`);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
if (shouldApply('uuid_tamper') && await uuidDetector.isSuspicious(req)) {
|
|
402
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
403
|
+
console.error(`[AIWAF-BLOCK-UUID]`);
|
|
404
|
+
}
|
|
405
|
+
await blacklistManager.block(ip, 'uuid');
|
|
406
|
+
return deny(403, 'blocked', 'uuid');
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
if (shouldApply('ai_anomaly') && !matchesKnownRoute(req.app, req.path || req.url || '/')) {
|
|
410
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
411
|
+
console.error(`[AIWAF-ANOMALY-CHECK] path=${req.path || req.url} has no known route`);
|
|
412
|
+
}
|
|
413
|
+
const features = await extractFeatures(req);
|
|
414
|
+
const isAnomaly = await anomalyDetector.isAnomalous(features);
|
|
415
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
416
|
+
console.error(`[AIWAF-ANOMALY-RESULT] isAnomaly=${isAnomaly} hasModel=${anomalyDetector.hasModel()} isSufficient=${anomalyDetector.isModelSufficientlyTrained()}`);
|
|
417
|
+
}
|
|
418
|
+
if (isAnomaly && anomalyDetector.isModelSufficientlyTrained()) {
|
|
419
|
+
// Analyze recent behavior before blocking.
|
|
420
|
+
const now = Date.now();
|
|
421
|
+
const recentData = (await requestLogStore.recent(5000))
|
|
422
|
+
.filter(row => row.ip_address === ip)
|
|
423
|
+
.map(row => ({
|
|
424
|
+
timestamp: row.created_at ? new Date(row.created_at).getTime() : now,
|
|
425
|
+
path: row.path,
|
|
426
|
+
status: Number(row.status || 0),
|
|
427
|
+
responseTime: Number(row.response_time_ms || 0)
|
|
428
|
+
}))
|
|
429
|
+
.filter(entry => now - entry.timestamp <= 5 * 60 * 1000);
|
|
430
|
+
|
|
431
|
+
const stats = anomalyDetector.analyzeRecentBehavior(recentData);
|
|
432
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
433
|
+
console.error(`[AIWAF-ANOMALY-STATS] should_block=${stats?.should_block}`);
|
|
434
|
+
}
|
|
435
|
+
if (stats && stats.should_block) {
|
|
436
|
+
const reason = `AI anomaly + scanning 404s (total:${stats.max_404s}, scanning:${stats.scanning_404s}, kw:${stats.avg_kw_hits.toFixed(1)}, burst:${stats.avg_burst.toFixed(1)})`;
|
|
437
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
438
|
+
console.error(`[AIWAF-ANOMALY-BLOCKING] reason=${reason}`);
|
|
439
|
+
}
|
|
440
|
+
await blacklistManager.block(ip, reason);
|
|
441
|
+
return deny(403, 'blocked', 'anomaly');
|
|
442
|
+
}
|
|
443
|
+
} else if (!anomalyDetector.isModelSufficientlyTrained()) {
|
|
444
|
+
// No sufficient model - skip aggressive anomaly detection
|
|
445
|
+
// Fallback is disabled until we have at least 10k training samples
|
|
446
|
+
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
447
|
+
console.error(`[AIWAF-ANOMALY-FALLBACK-DISABLED] No sufficiently trained model available - skipping fallback`);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
res.on('finish', () => {
|
|
453
|
+
const statusCode = Number(res.statusCode || 0);
|
|
454
|
+
anomalyDetector.maybeLearnKeyword(req.path || req.url || '', statusCode, opts);
|
|
455
|
+
});
|
|
456
|
+
|
|
457
|
+
next();
|
|
458
|
+
};
|
|
459
|
+
};
|