aiwaf 1.2.2 → 1.2.4
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 +84 -44
- 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/injectionAnalysis.js +1204 -52
- package/lib/modelStore.js +1 -1
- package/lib/nativePipeline.js +187 -21
- package/lib/nativeSettings.js +120 -42
- package/lib/pathRules.js +29 -4
- package/lib/requestLogStore.js +7 -7
- package/lib/routeRisks.js +1 -1
- package/lib/settingsCompat.js +3 -1
- package/lib/uuidDetector.js +7 -1
- package/lib/wafMiddleware.js +38 -7
- package/lib/wasmAdapter.js +4 -1
- package/package.json +2 -2
package/lib/pathRules.js
CHANGED
|
@@ -37,11 +37,18 @@ function normalizePaths(items = []) {
|
|
|
37
37
|
return (items || []).map(item => normalizePath(item, false));
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
// Patterns come from configuration, so each is compiled once.
|
|
41
|
+
const compiledWildcards = new Map();
|
|
40
42
|
function wildcardMatch(pathValue, pattern) {
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
43
|
+
const key = String(pattern);
|
|
44
|
+
let regex = compiledWildcards.get(key);
|
|
45
|
+
if (!regex) {
|
|
46
|
+
const escaped = key.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
|
|
47
|
+
regex = new RegExp(`^${escaped}$`);
|
|
48
|
+
if (compiledWildcards.size >= 1024) compiledWildcards.clear();
|
|
49
|
+
compiledWildcards.set(key, regex);
|
|
50
|
+
}
|
|
51
|
+
return regex.test(pathValue);
|
|
45
52
|
}
|
|
46
53
|
|
|
47
54
|
function isPathExempt(pathValue, exemptPaths = [], { allowWildcards = true, allowPrefix = true } = {}) {
|
|
@@ -101,7 +108,25 @@ function isMiddlewareDisabledForPath(path, rules, middlewareName) {
|
|
|
101
108
|
return disabled.some(entry => normalizeMiddlewareName(entry) === target);
|
|
102
109
|
}
|
|
103
110
|
|
|
111
|
+
// Path rules and route markers are fixed once the app runs, so a plan is built once per path
|
|
112
|
+
// and markers, for each rules list. Plans are only read, and getOverrides returns copies.
|
|
113
|
+
const planCaches = new WeakMap();
|
|
104
114
|
function createRoutePlan(path, rules = [], context = {}) {
|
|
115
|
+
if (!Array.isArray(rules)) return buildRoutePlan(path, rules, context);
|
|
116
|
+
const key = [path, rules.length, context.fullyExempt ? 1 : 0, (context.exemptMiddlewares || []).join(','),
|
|
117
|
+
(context.requiredMiddlewares || []).join(',')].join('\u0000');
|
|
118
|
+
let plans = planCaches.get(rules);
|
|
119
|
+
if (!plans) planCaches.set(rules, plans = new Map());
|
|
120
|
+
let plan = plans.get(key);
|
|
121
|
+
if (!plan) {
|
|
122
|
+
plan = buildRoutePlan(path, rules, context);
|
|
123
|
+
if (plans.size >= 4096) plans.delete(plans.keys().next().value);
|
|
124
|
+
plans.set(key, plan);
|
|
125
|
+
}
|
|
126
|
+
return plan;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function buildRoutePlan(path, rules = [], context = {}) {
|
|
105
130
|
const required = new Set((context.requiredMiddlewares || []).map(normalizeMiddlewareName));
|
|
106
131
|
const exempt = new Set((context.exemptMiddlewares || []).map(normalizeMiddlewareName));
|
|
107
132
|
const fullyExempt = !!context.fullyExempt;
|
package/lib/requestLogStore.js
CHANGED
|
@@ -96,8 +96,8 @@ module.exports = {
|
|
|
96
96
|
}
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
-
|
|
100
|
-
csvStore.appendRow(csvPath, headers, { id: csvStore.nextId(
|
|
99
|
+
// IDs only increase, so the last row gives the next one without reading the whole log.
|
|
100
|
+
csvStore.appendRow(csvPath, headers, { id: csvStore.nextId(csvStore.readTailRows(csvPath, headers, 1)), ...payload });
|
|
101
101
|
},
|
|
102
102
|
|
|
103
103
|
async recent(limit = 5000) {
|
|
@@ -105,15 +105,15 @@ module.exports = {
|
|
|
105
105
|
|
|
106
106
|
if (await initialize()) {
|
|
107
107
|
try {
|
|
108
|
-
return db('request_logs').select('*').orderBy('created_at', 'desc').limit(normalizedLimit);
|
|
108
|
+
return await db('request_logs').select('*').orderBy('created_at', 'desc').limit(normalizedLimit);
|
|
109
109
|
} catch (err) {
|
|
110
110
|
dbAvailable = false;
|
|
111
111
|
}
|
|
112
112
|
}
|
|
113
113
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
.
|
|
114
|
+
// The log is appended in time order, so the newest rows are its last lines.
|
|
115
|
+
return csvStore.readTailRows(csvPath, headers, normalizedLimit)
|
|
116
|
+
.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)));
|
|
117
117
|
},
|
|
118
118
|
|
|
119
119
|
async geoSummary(limit = 25) {
|
|
@@ -121,7 +121,7 @@ module.exports = {
|
|
|
121
121
|
|
|
122
122
|
if (await initialize()) {
|
|
123
123
|
try {
|
|
124
|
-
return db('request_logs')
|
|
124
|
+
return await db('request_logs')
|
|
125
125
|
.select('country')
|
|
126
126
|
.count({ requests: '*' })
|
|
127
127
|
.sum({ blocked_count: db.raw('CASE WHEN blocked THEN 1 ELSE 0 END') })
|
package/lib/routeRisks.js
CHANGED
|
@@ -104,7 +104,7 @@ function fileRoute(filename) {
|
|
|
104
104
|
function routesFor(finding, routes) {
|
|
105
105
|
const entry = String(finding.function || '').split(' -> ')[0];
|
|
106
106
|
const paths = Object.keys(routes);
|
|
107
|
-
const fromSource = (/^\S+ (\/\S*)$/.exec(entry) || [])[1] || fileRoute(finding.file);
|
|
107
|
+
const fromSource = (/^\S+ (\/\S*)$/.exec(entry) || [])[1] || fileRoute(finding.entry_file || finding.file);
|
|
108
108
|
if (fromSource) {
|
|
109
109
|
const wanted = trimRoute(fromSource);
|
|
110
110
|
const exact = paths.filter(path => trimRoute(path) === wanted);
|
package/lib/settingsCompat.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
const { loginPathPrefixes } = require('./honeypotDefaults');
|
|
2
|
+
|
|
1
3
|
function firstDefined(...values) {
|
|
2
4
|
for (const value of values) {
|
|
3
5
|
if (value !== undefined && value !== null) return value;
|
|
@@ -76,7 +78,7 @@ function normalizeSettings(rawOpts = {}) {
|
|
|
76
78
|
HONEYPOT_FIELD: firstDefined(rawOpts.HONEYPOT_FIELD, rawOpts.honeypotField, legacy.honeypot?.field),
|
|
77
79
|
AIWAF_MIN_FORM_TIME: toNumber(firstDefined(rawOpts.AIWAF_MIN_FORM_TIME, rawOpts.minFormTime, legacy.honeypot?.minFormTime, process.env.AIWAF_MIN_FORM_TIME), 0),
|
|
78
80
|
AIWAF_MAX_PAGE_TIME: toNumber(firstDefined(rawOpts.AIWAF_MAX_PAGE_TIME, rawOpts.maxPageTime, legacy.honeypot?.maxPageTime, process.env.AIWAF_MAX_PAGE_TIME), 3600),
|
|
79
|
-
AIWAF_LOGIN_PATH_PREFIXES: toArray(firstDefined(rawOpts.AIWAF_LOGIN_PATH_PREFIXES, rawOpts.loginPathPrefixes, legacy.honeypot?.loginPathPrefixes, process.env.AIWAF_LOGIN_PATH_PREFIXES),
|
|
81
|
+
AIWAF_LOGIN_PATH_PREFIXES: toArray(firstDefined(rawOpts.AIWAF_LOGIN_PATH_PREFIXES, rawOpts.loginPathPrefixes, legacy.honeypot?.loginPathPrefixes, process.env.AIWAF_LOGIN_PATH_PREFIXES), [...loginPathPrefixes]),
|
|
80
82
|
AIWAF_POST_ONLY_SUFFIXES: toArray(firstDefined(rawOpts.AIWAF_POST_ONLY_SUFFIXES, rawOpts.postOnlySuffixes, legacy.honeypot?.postOnlySuffixes, process.env.AIWAF_POST_ONLY_SUFFIXES), undefined),
|
|
81
83
|
AIWAF_ALLOWED_METHODS: toArray(firstDefined(rawOpts.AIWAF_ALLOWED_METHODS, rawOpts.allowedMethods, legacy.honeypot?.allowedMethods, process.env.AIWAF_ALLOWED_METHODS), undefined),
|
|
82
84
|
AIWAF_METHOD_POLICY_ENABLED: toBool(firstDefined(rawOpts.AIWAF_METHOD_POLICY_ENABLED, rawOpts.methodPolicyEnabled, legacy.honeypot?.methodPolicyEnabled, process.env.AIWAF_METHOD_POLICY_ENABLED), false),
|
package/lib/uuidDetector.js
CHANGED
|
@@ -9,10 +9,16 @@ let config = {
|
|
|
9
9
|
uuidResolver: null
|
|
10
10
|
};
|
|
11
11
|
|
|
12
|
+
// The prefix is literal text: escaped, and compiled once per prefix.
|
|
13
|
+
let prefixPattern = { prefix: null, regex: null };
|
|
12
14
|
function extractUuid(req) {
|
|
13
15
|
if (req?.params?.uuid) return String(req.params.uuid);
|
|
14
16
|
const path = String(req.path || req.url || '');
|
|
15
|
-
|
|
17
|
+
if (prefixPattern.prefix !== config.prefix) {
|
|
18
|
+
const escaped = String(config.prefix).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
19
|
+
prefixPattern = { prefix: config.prefix, regex: new RegExp(`^${escaped}/([^/]+)$`) };
|
|
20
|
+
}
|
|
21
|
+
const regex = prefixPattern.regex;
|
|
16
22
|
const match = path.match(regex);
|
|
17
23
|
return match ? match[1] : null;
|
|
18
24
|
}
|
package/lib/wafMiddleware.js
CHANGED
|
@@ -44,9 +44,20 @@ function knownRoutes(app) {
|
|
|
44
44
|
|
|
45
45
|
// An Express route path (a string, an array of them, or a RegExp) matched against a request
|
|
46
46
|
// path: :name is one segment (:name? optional) and * is anything. Other characters are literal.
|
|
47
|
+
const compiledRoutes = new Map();
|
|
47
48
|
function routeMatches(route, path) {
|
|
48
49
|
if (route instanceof RegExp) return route.test(path);
|
|
49
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) {
|
|
50
61
|
const pattern = String(route).split(/(\/?:\w+\??|\*)/).map(part => {
|
|
51
62
|
if (part === '*') return '.*';
|
|
52
63
|
const param = part.match(/^(\/?):\w+(\?)?$/);
|
|
@@ -54,9 +65,9 @@ function routeMatches(route, path) {
|
|
|
54
65
|
return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
55
66
|
}).join('');
|
|
56
67
|
try {
|
|
57
|
-
return new RegExp(`^${pattern}/?$`)
|
|
68
|
+
return new RegExp(`^${pattern}/?$`);
|
|
58
69
|
} catch (_) {
|
|
59
|
-
return
|
|
70
|
+
return null;
|
|
60
71
|
}
|
|
61
72
|
}
|
|
62
73
|
|
|
@@ -147,7 +158,7 @@ function applyAutoMiddlewareDefaults(opts, enabled, rawOpts = {}) {
|
|
|
147
158
|
|
|
148
159
|
// The first aiwaf-wasm with every engine feature from_settings relies on: stores, shared rate
|
|
149
160
|
// counts, path-rule limits, monitor mode and UUID resolvers.
|
|
150
|
-
const NATIVE_DEFAULT_WASM = '0.2.
|
|
161
|
+
const NATIVE_DEFAULT_WASM = '0.2.9';
|
|
151
162
|
|
|
152
163
|
function installedWasmVersion() {
|
|
153
164
|
const fs = require('fs');
|
|
@@ -173,14 +184,31 @@ const OFF = new Set(['false', '0', 'off', 'no']);
|
|
|
173
184
|
function automaticNative(rawOpts) {
|
|
174
185
|
if (OFF.has(String(process.env.AIWAF_NATIVE_PIPELINE ?? '').trim().toLowerCase())) return null;
|
|
175
186
|
const version = installedWasmVersion();
|
|
176
|
-
if (!version
|
|
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
|
+
}
|
|
177
191
|
let conversion;
|
|
178
192
|
try {
|
|
179
193
|
conversion = require('./nativeSettings').nativeOptionsFromSettings(rawOpts);
|
|
180
|
-
} catch (
|
|
181
|
-
|
|
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}).`);
|
|
182
197
|
}
|
|
183
|
-
|
|
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;
|
|
184
212
|
}
|
|
185
213
|
|
|
186
214
|
// Store reads fail open, as exemption checks already do: a storage outage is reported once per
|
|
@@ -218,6 +246,8 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
218
246
|
const conversion = converted || require('./nativeSettings').nativeOptionsFromSettings(regular);
|
|
219
247
|
conversion.log(nativeOptions.logger || console);
|
|
220
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;
|
|
221
251
|
} else if (Object.keys(rawOpts).some(key => key !== 'AIWAF_NATIVE_PIPELINE')) {
|
|
222
252
|
throw new Error('Native pipeline uses a dedicated profile; do not mix legacy options');
|
|
223
253
|
}
|
|
@@ -621,3 +651,4 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
621
651
|
};
|
|
622
652
|
|
|
623
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
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiwaf",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.4",
|
|
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.9",
|
|
38
38
|
"express": "^4.21.2",
|
|
39
39
|
"glob": "^14.0.6",
|
|
40
40
|
"knex": "^2.4.2",
|