aiwaf 1.2.1 → 1.2.3
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 +30 -26
- package/lib/anomalyDetector.js +6 -0
- package/lib/csvStore.js +47 -0
- package/lib/dynamicKeywordStore.js +1 -1
- package/lib/exemptionStore.js +4 -4
- package/lib/geoBlocker.js +58 -0
- package/lib/geoStore.js +2 -2
- package/lib/headerValidation.js +29 -9
- package/lib/honeypotDefaults.js +1 -0
- package/lib/honeypotDetector.js +4 -8
- package/lib/modelStore.js +1 -1
- package/lib/nativePipeline.js +202 -25
- package/lib/nativeSettings.js +192 -50
- package/lib/pathRules.js +29 -4
- package/lib/requestLogStore.js +7 -7
- package/lib/settingsCompat.js +3 -1
- package/lib/uuidDetector.js +7 -1
- package/lib/wafMiddleware.js +103 -20
- package/lib/wasmAdapter.js +11 -2
- package/package.json +2 -2
package/lib/wafMiddleware.js
CHANGED
|
@@ -42,6 +42,35 @@ function knownRoutes(app) {
|
|
|
42
42
|
.map(layer => layer.route.path);
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
+
// An Express route path (a string, an array of them, or a RegExp) matched against a request
|
|
46
|
+
// path: :name is one segment (:name? optional) and * is anything. Other characters are literal.
|
|
47
|
+
const compiledRoutes = new Map();
|
|
48
|
+
function routeMatches(route, path) {
|
|
49
|
+
if (route instanceof RegExp) return route.test(path);
|
|
50
|
+
if (Array.isArray(route)) return route.some(item => routeMatches(item, path));
|
|
51
|
+
const key = String(route);
|
|
52
|
+
if (compiledRoutes.has(key)) return compiledRoutes.get(key)?.test(path) ?? false;
|
|
53
|
+
const regex = compileRoute(key);
|
|
54
|
+
if (compiledRoutes.size >= 1024) compiledRoutes.clear();
|
|
55
|
+
compiledRoutes.set(key, regex);
|
|
56
|
+
return regex ? regex.test(path) : false;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// null when the route can't be compiled, which then matches nothing.
|
|
60
|
+
function compileRoute(route) {
|
|
61
|
+
const pattern = String(route).split(/(\/?:\w+\??|\*)/).map(part => {
|
|
62
|
+
if (part === '*') return '.*';
|
|
63
|
+
const param = part.match(/^(\/?):\w+(\?)?$/);
|
|
64
|
+
if (param) return param[2] ? `(?:${param[1] ? '/' : ''}[^/]+)?` : `${param[1] ? '/' : ''}[^/]+`;
|
|
65
|
+
return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
66
|
+
}).join('');
|
|
67
|
+
try {
|
|
68
|
+
return new RegExp(`^${pattern}/?$`);
|
|
69
|
+
} catch (_) {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
45
74
|
function matchesKnownRoute(app, path) {
|
|
46
75
|
// In proxy setups, req.app may be undefined or not have routes
|
|
47
76
|
// Return true (treat as known) to skip anomaly detection on proxies
|
|
@@ -62,10 +91,7 @@ function matchesKnownRoute(app, path) {
|
|
|
62
91
|
return true;
|
|
63
92
|
}
|
|
64
93
|
|
|
65
|
-
const result = routes.some(route =>
|
|
66
|
-
const regex = new RegExp(`^${String(route).replace(/:\\w+/g, '[^/]+')}$`);
|
|
67
|
-
return regex.test(path);
|
|
68
|
-
});
|
|
94
|
+
const result = routes.some(route => routeMatches(route, path));
|
|
69
95
|
|
|
70
96
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
71
97
|
console.error(`[AIWAF-ROUTE-CHECK] path=${path} matched=${result}`);
|
|
@@ -132,7 +158,7 @@ function applyAutoMiddlewareDefaults(opts, enabled, rawOpts = {}) {
|
|
|
132
158
|
|
|
133
159
|
// The first aiwaf-wasm with every engine feature from_settings relies on: stores, shared rate
|
|
134
160
|
// counts, path-rule limits, monitor mode and UUID resolvers.
|
|
135
|
-
const NATIVE_DEFAULT_WASM = '0.2.
|
|
161
|
+
const NATIVE_DEFAULT_WASM = '0.2.8';
|
|
136
162
|
|
|
137
163
|
function installedWasmVersion() {
|
|
138
164
|
const fs = require('fs');
|
|
@@ -158,10 +184,45 @@ const OFF = new Set(['false', '0', 'off', 'no']);
|
|
|
158
184
|
function automaticNative(rawOpts) {
|
|
159
185
|
if (OFF.has(String(process.env.AIWAF_NATIVE_PIPELINE ?? '').trim().toLowerCase())) return null;
|
|
160
186
|
const version = installedWasmVersion();
|
|
161
|
-
if (!version
|
|
162
|
-
|
|
163
|
-
|
|
187
|
+
if (!version) return staysRegular('aiwaf-wasm isn\'t installed (npm install aiwaf-wasm).');
|
|
188
|
+
if (!atLeast(version, NATIVE_DEFAULT_WASM)) {
|
|
189
|
+
return staysRegular(`the installed aiwaf-wasm ${version} is older than ${NATIVE_DEFAULT_WASM} (npm install aiwaf-wasm@latest).`);
|
|
190
|
+
}
|
|
191
|
+
let conversion;
|
|
192
|
+
try {
|
|
193
|
+
conversion = require('./nativeSettings').nativeOptionsFromSettings(rawOpts);
|
|
194
|
+
} catch (error) {
|
|
195
|
+
// Options the converter can't read stay with the regular middleware.
|
|
196
|
+
return staysRegular(`its options couldn't be converted (${error && error.message}).`);
|
|
197
|
+
}
|
|
198
|
+
const differences = conversion.differences();
|
|
199
|
+
if (!differences.length) return conversion;
|
|
200
|
+
return staysRegular(`these options don't carry over to it exactly:\n${differences
|
|
201
|
+
.map(note => `- ${note.setting}: ${note.outcome}. ${note.detail}`.trimEnd()).join('\n')}`);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Why an app runs the regular middleware and not the native pipeline, said once per reason.
|
|
205
|
+
const reportedReasons = new Set();
|
|
206
|
+
function staysRegular(reason) {
|
|
207
|
+
if (!reportedReasons.has(reason)) {
|
|
208
|
+
reportedReasons.add(reason);
|
|
209
|
+
console.info(`AIWAF: using the regular middleware, not the native pipeline, because ${reason}`);
|
|
210
|
+
}
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Store reads fail open, as exemption checks already do: a storage outage is reported once per
|
|
215
|
+
// kind and requests carry on unblocked, rather than every request failing.
|
|
216
|
+
const reportedStoreFailures = new Set();
|
|
217
|
+
function storeFailed(what, error) {
|
|
218
|
+
if (reportedStoreFailures.has(what)) return;
|
|
219
|
+
reportedStoreFailures.add(what);
|
|
220
|
+
console.warn(`AIWAF: ${what} failed (${error && error.message}); continuing without it. This is reported once.`);
|
|
164
221
|
}
|
|
222
|
+
const isBlocked = ip => Promise.resolve().then(() => blocklistManager.isBlocked(ip))
|
|
223
|
+
.catch(error => { storeFailed('blocklist read', error); return false; });
|
|
224
|
+
const recentRequests = limit => Promise.resolve().then(() => requestLogStore.recent(limit))
|
|
225
|
+
.catch(error => { storeFailed('request log read', error); return []; });
|
|
165
226
|
|
|
166
227
|
module.exports = function aiwaf(rawOpts = {}) {
|
|
167
228
|
if (rawOpts.AIWAF_NATIVE_PIPELINE === false) {
|
|
@@ -172,7 +233,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
172
233
|
if (conversion) {
|
|
173
234
|
console.info('AIWAF: using the native pipeline, since every option carries over to it. '
|
|
174
235
|
+ 'Set AIWAF_NATIVE_PIPELINE: false (or the environment variable) to keep the regular middleware.');
|
|
175
|
-
rawOpts = { ...rawOpts, AIWAF_NATIVE_PIPELINE: { fromSettings: true, conversion } };
|
|
236
|
+
rawOpts = { ...rawOpts, AIWAF_NATIVE_PIPELINE: { fromSettings: true, conversion, automatic: rawOpts } };
|
|
176
237
|
}
|
|
177
238
|
}
|
|
178
239
|
if (rawOpts.AIWAF_NATIVE_PIPELINE !== undefined) {
|
|
@@ -181,17 +242,32 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
181
242
|
if (fromSettings) {
|
|
182
243
|
// Convert the regular options passed alongside; native options given here win, as in Python.
|
|
183
244
|
const { AIWAF_NATIVE_PIPELINE: _ignored, ...regular } = rawOpts;
|
|
184
|
-
const { fromSettings: _flag, profile: overrides, conversion: converted, ...nativeOptions } = typeof native === 'object' ? native : {};
|
|
245
|
+
const { fromSettings: _flag, profile: overrides, conversion: converted, automatic: _automatic, ...nativeOptions } = typeof native === 'object' ? native : {};
|
|
185
246
|
const conversion = converted || require('./nativeSettings').nativeOptionsFromSettings(regular);
|
|
186
247
|
conversion.log(nativeOptions.logger || console);
|
|
187
248
|
native = { ...conversion.options, ...nativeOptions, profile: { ...conversion.profile, ...(overrides || {}) } };
|
|
249
|
+
// Chosen automatically, it runs only if it can answer exactly as the regular middleware.
|
|
250
|
+
if (rawOpts.AIWAF_NATIVE_PIPELINE.automatic) native.exact = true;
|
|
188
251
|
} else if (Object.keys(rawOpts).some(key => key !== 'AIWAF_NATIVE_PIPELINE')) {
|
|
189
252
|
throw new Error('Native pipeline uses a dedicated profile; do not mix legacy options');
|
|
190
253
|
}
|
|
191
|
-
const
|
|
254
|
+
const automatic = rawOpts.AIWAF_NATIVE_PIPELINE?.automatic;
|
|
255
|
+
let ready = require('./nativePipeline')(native);
|
|
256
|
+
if (automatic) {
|
|
257
|
+
// Chosen automatically: if it can't start, the regular middleware runs instead, as it
|
|
258
|
+
// would have without the switch. A native pipeline chosen explicitly keeps its error.
|
|
259
|
+
ready = ready.catch(error => {
|
|
260
|
+
console.warn(`AIWAF: the native pipeline couldn't start (${error.message}), so the regular middleware runs instead.`);
|
|
261
|
+
const regular = aiwaf({ ...automatic, AIWAF_NATIVE_PIPELINE: false });
|
|
262
|
+
// The native methods framework adapters call.
|
|
263
|
+
Object.assign(regular, { inspectBody: () => null, close: () => {}, setModel: () => {},
|
|
264
|
+
diagnostics: () => ({ native: false, fallback: error.message }) });
|
|
265
|
+
return regular;
|
|
266
|
+
});
|
|
267
|
+
}
|
|
192
268
|
// Compatibility wrapper for framework adapters. Await ready during application startup.
|
|
193
|
-
//
|
|
194
|
-
const middleware =
|
|
269
|
+
// A startup failure goes to next(error) for each request instead of an unhandled rejection.
|
|
270
|
+
const middleware = (req, res, next) => ready.then(handler => handler(req, res, next)).catch(next);
|
|
195
271
|
middleware.ready = ready;
|
|
196
272
|
middleware.inspectPayload = async req => (await ready).inspectPayload(req);
|
|
197
273
|
return middleware;
|
|
@@ -263,7 +339,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
263
339
|
}
|
|
264
340
|
return finding;
|
|
265
341
|
};
|
|
266
|
-
const
|
|
342
|
+
const handle = async (req, res, next) => {
|
|
267
343
|
const ip = getRequestIp(req, opts.AIWAF_TRUSTED_PROXIES);
|
|
268
344
|
// Geo checks and logging must judge the same address as this middleware.
|
|
269
345
|
req.aiwafClientIp = ip;
|
|
@@ -292,13 +368,14 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
292
368
|
}
|
|
293
369
|
const routePlan = createRoutePlan(path, pathRules, req.aiwafRoute || {});
|
|
294
370
|
const shouldApply = name => enabledMiddlewares.has(normalizeMiddlewareName(name)) && routePlan.shouldApply(name);
|
|
295
|
-
|
|
371
|
+
// A block that can't be written is reported; the request is still denied.
|
|
372
|
+
const blockIp = reason => Promise.resolve().then(() => blocklistManager.block(ip, reason, {
|
|
296
373
|
extendedRequestInfo: extractExtendedRequestInfo(req, {
|
|
297
374
|
enabled: opts.AIWAF_CAPTURE_EXTENDED_REQUEST_INFO,
|
|
298
375
|
maxHeaders: opts.AIWAF_EXTENDED_INFO_MAX_HEADERS,
|
|
299
376
|
maxValueLength: opts.AIWAF_EXTENDED_INFO_MAX_VALUE_LENGTH
|
|
300
377
|
}) || {}
|
|
301
|
-
});
|
|
378
|
+
})).catch(error => { storeFailed('blocklist write', error); return false; });
|
|
302
379
|
|
|
303
380
|
// Debug: Log first character of path to ensure it's being captured
|
|
304
381
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
@@ -341,7 +418,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
341
418
|
return next();
|
|
342
419
|
}
|
|
343
420
|
|
|
344
|
-
if (shouldApply('ip_keyword_block') && await
|
|
421
|
+
if (shouldApply('ip_keyword_block') && await isBlocked(ip)) {
|
|
345
422
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
346
423
|
console.error(`[AIWAF-BLOCK-BLOCKLIST] ip=${ip}`);
|
|
347
424
|
}
|
|
@@ -423,7 +500,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
423
500
|
}
|
|
424
501
|
|
|
425
502
|
if (opts.AIWAF_WASM_VALIDATE_RECENT && shouldApply('ai_anomaly')) {
|
|
426
|
-
const recentRows = await
|
|
503
|
+
const recentRows = await recentRequests(200);
|
|
427
504
|
const recent = recentRows
|
|
428
505
|
.filter(row => row.ip_address === ip)
|
|
429
506
|
.map(row => ({ path: row.path, status: Number(row.status || 0) }));
|
|
@@ -473,7 +550,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
473
550
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
474
551
|
console.error(`[AIWAF-BLOCK-RATE] ip=${ip}`);
|
|
475
552
|
}
|
|
476
|
-
if (await
|
|
553
|
+
if (await isBlocked(ip)) {
|
|
477
554
|
return deny(403, 'blocked', 'flood_or_blocklist');
|
|
478
555
|
}
|
|
479
556
|
return deny(429, 'too_many_requests', 'rate_limit');
|
|
@@ -526,7 +603,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
526
603
|
if (isAnomaly && anomalyDetector.isModelSufficientlyTrained()) {
|
|
527
604
|
// Analyze recent behavior before blocking.
|
|
528
605
|
const now = Date.now();
|
|
529
|
-
const recentData = (await
|
|
606
|
+
const recentData = (await recentRequests(5000))
|
|
530
607
|
.filter(row => row.ip_address === ip)
|
|
531
608
|
.map(row => ({
|
|
532
609
|
timestamp: row.created_at ? new Date(row.created_at).getTime() : now,
|
|
@@ -564,8 +641,14 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
564
641
|
|
|
565
642
|
next();
|
|
566
643
|
};
|
|
644
|
+
// Express 4 doesn't await middleware, so an error here would otherwise be an unhandled
|
|
645
|
+
// rejection, which ends the process, and the request would hang. It goes to next(error).
|
|
646
|
+
const middleware = (req, res, next) => handle(req, res, next).catch(error => {
|
|
647
|
+
if (!res.headersSent) next(error);
|
|
648
|
+
});
|
|
567
649
|
middleware.inspectPayload = inspectPayload;
|
|
568
650
|
return middleware;
|
|
569
651
|
};
|
|
570
652
|
|
|
571
653
|
module.exports.NATIVE_DEFAULT_WASM = NATIVE_DEFAULT_WASM;
|
|
654
|
+
module.exports.matchesKnownRoute = matchesKnownRoute;
|
package/lib/wasmAdapter.js
CHANGED
|
@@ -315,7 +315,10 @@ async function validateHeaders(headers, config) {
|
|
|
315
315
|
if (config && typeof mod.validate_headers_with_config === 'function') {
|
|
316
316
|
const required = (config.requiredHeaders && config.requiredHeaders.length) ? config.requiredHeaders : null;
|
|
317
317
|
const minScore = Number.isFinite(Number(config.minScore)) ? Number(config.minScore) : null;
|
|
318
|
-
|
|
318
|
+
// An older aiwaf-wasm takes no cap, ignores it and keeps its own 500.
|
|
319
|
+
const maxUserAgent = Number.isInteger(config.maxUserAgentLength) && config.maxUserAgentLength >= 0
|
|
320
|
+
? config.maxUserAgentLength : undefined;
|
|
321
|
+
result = mod.validate_headers_with_config(headerInput, required, minScore, maxUserAgent);
|
|
319
322
|
} else {
|
|
320
323
|
result = mod.validate_headers(headerInput);
|
|
321
324
|
}
|
|
@@ -541,7 +544,13 @@ async function createRequestPipeline(profile = {}, model = null) {
|
|
|
541
544
|
wireProfile.blacklist = wireProfile.blocklist;
|
|
542
545
|
delete wireProfile.blocklist;
|
|
543
546
|
}
|
|
544
|
-
|
|
547
|
+
let native;
|
|
548
|
+
try {
|
|
549
|
+
native = new mod.NativeRequestPipeline(JSON.stringify(wireProfile));
|
|
550
|
+
} catch (error) {
|
|
551
|
+
// The engine reports its startup errors as strings; give them an Error's message and stack.
|
|
552
|
+
throw error instanceof Error ? error : new Error(`Native pipeline: ${String(error)}`);
|
|
553
|
+
}
|
|
545
554
|
if (['begin','finish','inspect_payload','inspect_body','set_model','clear_model','diagnostics'].some(name => typeof native[name] !== 'function')) {
|
|
546
555
|
native.free();
|
|
547
556
|
throw new Error('Incompatible NativeRequestPipeline API; install the matching WASM build');
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiwaf",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.3",
|
|
4
4
|
"description": "AIWAF Web Application Firewall for JavaScript applications and major Node.js frameworks",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"files": [
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"@babel/parser": "^7.29.2",
|
|
37
|
-
"aiwaf-wasm": "^0.2.
|
|
37
|
+
"aiwaf-wasm": "^0.2.8",
|
|
38
38
|
"express": "^4.21.2",
|
|
39
39
|
"glob": "^14.0.6",
|
|
40
40
|
"knex": "^2.4.2",
|