aiwaf 1.1.5 → 1.2.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/README.md +366 -44
- package/bin/aiwaf.js +23 -4
- package/index.js +3 -0
- package/lib/geoBlocker.js +1 -7
- package/lib/hapiPlugin.js +5 -2
- package/lib/injectionAnalysis.js +600 -0
- package/lib/nativePipeline.js +370 -23
- package/lib/nativeRateCounter.js +45 -0
- package/lib/nativeSettings.js +242 -0
- package/lib/pathManifest.js +17 -1
- package/lib/routeRisks.js +181 -0
- package/lib/runtimeUtils.js +201 -6
- package/lib/settingsCompat.js +2 -0
- package/lib/sqlInjection.js +55 -49
- package/lib/wafMiddleware.js +71 -6
- package/lib/wasmAdapter.js +8 -1
- package/lib/wasmChecks.js +40 -0
- package/package.json +6 -41
package/lib/runtimeUtils.js
CHANGED
|
@@ -7,12 +7,200 @@ const STATIC_EXTENSIONS = new Set([
|
|
|
7
7
|
'.xml', '.txt', '.pdf', '.zip', '.tar', '.gz', '.webp', '.avif'
|
|
8
8
|
]);
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
10
|
+
// Upstream peers allowed to supply X-Forwarded-For unless AIWAF_TRUSTED_PROXIES
|
|
11
|
+
// is set. A public peer is never trusted by default, so internet clients that
|
|
12
|
+
// reach the application directly can't choose their own address.
|
|
13
|
+
const DEFAULT_TRUSTED_PROXIES = [
|
|
14
|
+
'127.0.0.0/8', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '169.254.0.0/16',
|
|
15
|
+
'::1/128', 'fc00::/7', 'fe80::/10'
|
|
16
|
+
];
|
|
17
|
+
// Published at https://www.cloudflare.com/ips/ (retrieved 2026-11-15). Keep in step with
|
|
18
|
+
// CLOUDFLARE_PROXIES in py/aiwaf/core/utils.py. Opt-in only: anyone can send requests
|
|
19
|
+
// through Cloudflare, so these ranges don't prove a request came from your own zone.
|
|
20
|
+
const CLOUDFLARE_PROXIES = [
|
|
21
|
+
'173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22',
|
|
22
|
+
'141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20',
|
|
23
|
+
'197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13',
|
|
24
|
+
'104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22',
|
|
25
|
+
'2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32',
|
|
26
|
+
'2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32'
|
|
27
|
+
];
|
|
28
|
+
// Names accepted in AIWAF_TRUSTED_PROXIES alongside addresses and ranges, for example
|
|
29
|
+
// 'default,cloudflare' to keep the built-in ranges and add Cloudflare's.
|
|
30
|
+
const TRUSTED_PROXY_PRESETS = { default: DEFAULT_TRUSTED_PROXIES, cloudflare: CLOUDFLARE_PROXIES };
|
|
31
|
+
const MAX_FORWARDED_FOR_LENGTH = 4096;
|
|
32
|
+
const MAX_FORWARDED_FOR_ENTRIES = 32;
|
|
33
|
+
const trustedProxyCache = new Map();
|
|
34
|
+
|
|
35
|
+
// Write an IPv6 address in canonical form (lowercase, zeros compressed) and an IPv4-mapped one as
|
|
36
|
+
// IPv4, as Python and aiwaf-wasm do, so the same client keeps the same address everywhere.
|
|
37
|
+
function canonicalIpv6(text) {
|
|
38
|
+
const zone = text.indexOf('%');
|
|
39
|
+
const address = zone === -1 ? text : text.slice(0, zone);
|
|
40
|
+
let canonical;
|
|
41
|
+
try {
|
|
42
|
+
canonical = new URL(`http://[${address}]/`).hostname.slice(1, -1);
|
|
43
|
+
} catch {
|
|
44
|
+
return text;
|
|
45
|
+
}
|
|
46
|
+
const mapped = canonical.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
|
|
47
|
+
if (mapped) {
|
|
48
|
+
const [high, low] = [parseInt(mapped[1], 16), parseInt(mapped[2], 16)];
|
|
49
|
+
return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
|
|
50
|
+
}
|
|
51
|
+
return zone === -1 ? canonical : canonical + text.slice(zone);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function normalizeIp(value) {
|
|
55
|
+
let text = String(value ?? '').trim();
|
|
56
|
+
if (text.startsWith('[') && text.includes(']')) {
|
|
57
|
+
text = text.slice(1, text.indexOf(']'));
|
|
58
|
+
} else if (text.split(':').length === 2) {
|
|
59
|
+
// IPv4 with a port, as sent by some load balancers.
|
|
60
|
+
text = text.split(':')[0];
|
|
61
|
+
}
|
|
62
|
+
text = text.replace(/^::ffff:(?=\d+\.)/i, '');
|
|
63
|
+
const family = net.isIP(text);
|
|
64
|
+
if (!family) return '';
|
|
65
|
+
return family === 6 ? canonicalIpv6(text) : text;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function buildTrustedProxies(entries) {
|
|
69
|
+
const list = new net.BlockList();
|
|
70
|
+
let size = 0;
|
|
71
|
+
for (const entry of entries) {
|
|
72
|
+
const [address, prefix] = entry.split('/');
|
|
73
|
+
const family = net.isIP(address);
|
|
74
|
+
const bits = prefix === undefined ? (family === 6 ? 128 : 32) : Number(prefix);
|
|
75
|
+
const max = family === 6 ? 128 : 32;
|
|
76
|
+
if (!family || !Number.isInteger(bits) || bits < 0 || bits > max) {
|
|
77
|
+
// An unparseable entry must never widen trust.
|
|
78
|
+
console.warn(`[AIWAF] Ignoring invalid AIWAF_TRUSTED_PROXIES entry: ${entry}`);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
list.addSubnet(address, bits, family === 6 ? 'ipv6' : 'ipv4');
|
|
82
|
+
size += 1;
|
|
83
|
+
}
|
|
84
|
+
return size ? list : null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Parsed once per setting, keyed by the raw value, so a request does no parsing.
|
|
88
|
+
function getTrustedProxyConfig(configured) {
|
|
89
|
+
const source = configured ?? process.env.AIWAF_TRUSTED_PROXIES ?? DEFAULT_TRUSTED_PROXIES;
|
|
90
|
+
const key = typeof source === 'string' ? `s:${source}` : `a:${Array.from(source).join('\u0000')}`;
|
|
91
|
+
let config = trustedProxyCache.get(key);
|
|
92
|
+
if (!config) {
|
|
93
|
+
const entries = (typeof source === 'string' ? source.split(',') : Array.from(source))
|
|
94
|
+
.map(entry => String(entry).trim())
|
|
95
|
+
.filter(Boolean)
|
|
96
|
+
.flatMap(entry => (Object.hasOwn(TRUSTED_PROXY_PRESETS, entry.toLowerCase())
|
|
97
|
+
? TRUSTED_PROXY_PRESETS[entry.toLowerCase()]
|
|
98
|
+
: [entry]));
|
|
99
|
+
if (trustedProxyCache.size >= 64) trustedProxyCache.clear();
|
|
100
|
+
config = { entries, list: buildTrustedProxies(entries), native: undefined };
|
|
101
|
+
trustedProxyCache.set(key, config);
|
|
102
|
+
}
|
|
103
|
+
return config;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function getTrustedProxies(configured) {
|
|
107
|
+
return getTrustedProxyConfig(configured).list;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
let wasmChecks = null;
|
|
111
|
+
|
|
112
|
+
// The aiwaf-wasm resolver for this setting, once aiwaf-wasm has loaded. Until then, or with an
|
|
113
|
+
// older aiwaf-wasm, requests use the JavaScript walk below, which gives the same answers.
|
|
114
|
+
function nativeTrustedProxies(config) {
|
|
115
|
+
if (config.native !== undefined) return config.native;
|
|
116
|
+
wasmChecks = wasmChecks || require('./wasmChecks');
|
|
117
|
+
const mod = wasmChecks.loadedModule();
|
|
118
|
+
if (!mod) return null;
|
|
119
|
+
config.native = typeof mod.TrustedProxySet === 'function' ? new mod.TrustedProxySet(config.entries) : null;
|
|
120
|
+
return config.native;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
let untrustedPeerWarned = false;
|
|
124
|
+
|
|
125
|
+
// Point out, once per process, a proxy that may need adding to AIWAF_TRUSTED_PROXIES.
|
|
126
|
+
function warnUntrustedPeerOnce(peer, header) {
|
|
127
|
+
if (untrustedPeerWarned) return;
|
|
128
|
+
untrustedPeerWarned = true;
|
|
129
|
+
console.warn(
|
|
130
|
+
`[AIWAF] Ignoring ${header} from untrusted peer ${peer} and using the peer's address as the client. ` +
|
|
131
|
+
`If ${peer} is your proxy or CDN, add it to AIWAF_TRUSTED_PROXIES (behind Cloudflare, use ` +
|
|
132
|
+
'AIWAF_TRUSTED_PROXIES=default,cloudflare); otherwise no action is needed. This warning is logged once.'
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function resetUntrustedPeerWarning() {
|
|
137
|
+
untrustedPeerWarned = false;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function isTrustedProxy(ip, list) {
|
|
141
|
+
try {
|
|
142
|
+
return list.check(ip, net.isIP(ip) === 6 ? 'ipv6' : 'ipv4');
|
|
143
|
+
} catch {
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function resolveForwardedIp(req, list) {
|
|
149
|
+
const header = String(req.headers?.['x-forwarded-for'] ?? '');
|
|
150
|
+
if (header && header.length <= MAX_FORWARDED_FOR_LENGTH) {
|
|
151
|
+
// Proxies append, so walk from the right and stop at the first untrusted
|
|
152
|
+
// address. Anything further left is client-supplied.
|
|
153
|
+
const hops = header.split(',').slice(-MAX_FORWARDED_FOR_ENTRIES).reverse();
|
|
154
|
+
let rightmost = '';
|
|
155
|
+
for (const hop of hops) {
|
|
156
|
+
const candidate = normalizeIp(hop);
|
|
157
|
+
// Stop rather than skip, so a malformed hop can't expose values to its left.
|
|
158
|
+
if (!candidate) break;
|
|
159
|
+
if (!isTrustedProxy(candidate, list)) return candidate;
|
|
160
|
+
rightmost = rightmost || candidate;
|
|
161
|
+
}
|
|
162
|
+
// Every hop is internal. Only the rightmost was written by our proxy.
|
|
163
|
+
if (rightmost) return rightmost;
|
|
164
|
+
}
|
|
165
|
+
return normalizeIp(req.headers?.['x-real-ip']);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Resolve the client address, honoring proxy headers only from a trusted peer.
|
|
170
|
+
* A framework that already resolved req.ip (Express `trust proxy`, for example)
|
|
171
|
+
* is respected. A missing peer means a local Unix socket.
|
|
172
|
+
*/
|
|
173
|
+
function getRequestIp(req = {}, trustedProxies) {
|
|
174
|
+
if (req.aiwafClientIp) return req.aiwafClientIp;
|
|
175
|
+
const socketPeer = req.socket?.remoteAddress || req.connection?.remoteAddress || '';
|
|
176
|
+
const rawPeer = String(socketPeer || req.ip || '');
|
|
177
|
+
const declared = normalizeIp(req.ip);
|
|
178
|
+
if (socketPeer && declared && declared !== normalizeIp(rawPeer)) return declared;
|
|
179
|
+
|
|
180
|
+
const config = getTrustedProxyConfig(trustedProxies);
|
|
181
|
+
const native = nativeTrustedProxies(config);
|
|
182
|
+
if (!native) return resolveRequestIpInJavaScript(req, rawPeer, config.list);
|
|
183
|
+
const forwardedFor = req.headers?.['x-forwarded-for'];
|
|
184
|
+
const realIp = req.headers?.['x-real-ip'];
|
|
185
|
+
const ip = native.resolve(rawPeer, forwardedFor == null ? '' : String(forwardedFor),
|
|
186
|
+
realIp == null ? '' : String(realIp));
|
|
187
|
+
const ignored = native.ignored_header();
|
|
188
|
+
if (ignored) warnUntrustedPeerOnce(ip, ignored);
|
|
189
|
+
return ip;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function resolveRequestIpInJavaScript(req, rawPeer, list) {
|
|
193
|
+
const peer = normalizeIp(rawPeer);
|
|
194
|
+
const fallback = peer || rawPeer.trim();
|
|
195
|
+
if (!list) return fallback;
|
|
196
|
+
if (rawPeer.trim() && !(peer && isTrustedProxy(peer, list))) {
|
|
197
|
+
const forwardedFor = req.headers?.['x-forwarded-for'];
|
|
198
|
+
if (peer && (forwardedFor || req.headers?.['x-real-ip'])) {
|
|
199
|
+
warnUntrustedPeerOnce(peer, forwardedFor ? 'X-Forwarded-For' : 'X-Real-IP');
|
|
200
|
+
}
|
|
201
|
+
return fallback;
|
|
202
|
+
}
|
|
203
|
+
return resolveForwardedIp(req, list) || fallback;
|
|
16
204
|
}
|
|
17
205
|
|
|
18
206
|
function isPrivateIp(ip) {
|
|
@@ -154,7 +342,14 @@ class RateLimiter {
|
|
|
154
342
|
|
|
155
343
|
module.exports = {
|
|
156
344
|
STATIC_EXTENSIONS,
|
|
345
|
+
CLOUDFLARE_PROXIES,
|
|
157
346
|
getRequestIp,
|
|
347
|
+
resetUntrustedPeerWarning,
|
|
348
|
+
// For parity tests: the JavaScript walk used until aiwaf-wasm has loaded.
|
|
349
|
+
_resolveRequestIpInJavaScript: (req, trustedProxies) => {
|
|
350
|
+
const rawPeer = String(req.socket?.remoteAddress || req.connection?.remoteAddress || req.ip || '');
|
|
351
|
+
return resolveRequestIpInJavaScript(req, rawPeer, getTrustedProxies(trustedProxies));
|
|
352
|
+
},
|
|
158
353
|
isPrivateIp,
|
|
159
354
|
isStaticFile,
|
|
160
355
|
sanitizeHeaderValue,
|
package/lib/settingsCompat.js
CHANGED
|
@@ -83,6 +83,7 @@ function normalizeSettings(rawOpts = {}) {
|
|
|
83
83
|
|
|
84
84
|
AIWAF_EXEMPT_PATHS: toArray(firstDefined(rawOpts.AIWAF_EXEMPT_PATHS, rawOpts.exemptPaths, legacy.exemptions?.paths, process.env.AIWAF_EXEMPT_PATHS), []),
|
|
85
85
|
AIWAF_EXEMPT_IPS: toArray(firstDefined(rawOpts.AIWAF_EXEMPT_IPS, rawOpts.exemptIps, legacy.exemptions?.ips, process.env.AIWAF_EXEMPT_IPS), []),
|
|
86
|
+
AIWAF_TRUSTED_PROXIES: toArray(firstDefined(rawOpts.AIWAF_TRUSTED_PROXIES, rawOpts.trustedProxies, process.env.AIWAF_TRUSTED_PROXIES), null),
|
|
86
87
|
AIWAF_ALLOWED_PATH_KEYWORDS: toArray(firstDefined(rawOpts.AIWAF_ALLOWED_PATH_KEYWORDS, rawOpts.allowedPathKeywords, legacy.exemptions?.allowedPathKeywords, process.env.AIWAF_ALLOWED_PATH_KEYWORDS), []),
|
|
87
88
|
AIWAF_EXEMPT_KEYWORDS: toArray(firstDefined(rawOpts.AIWAF_EXEMPT_KEYWORDS, rawOpts.exemptKeywords, legacy.exemptions?.keywords, process.env.AIWAF_EXEMPT_KEYWORDS), []),
|
|
88
89
|
AIWAF_EXEMPTIONS_DB: toBool(firstDefined(rawOpts.AIWAF_EXEMPTIONS_DB, rawOpts.exemptionsDb, legacy.exemptions?.dbEnabled, process.env.AIWAF_EXEMPTIONS_DB), true),
|
|
@@ -131,6 +132,7 @@ function normalizeSettings(rawOpts = {}) {
|
|
|
131
132
|
AIWAF_DISABLE_MIDDLEWARES: toArray(firstDefined(rawOpts.AIWAF_DISABLE_MIDDLEWARES, rawOpts.disableMiddlewares, rawOpts.disabledMiddlewares, legacy.middlewares?.disabled, process.env.AIWAF_DISABLE_MIDDLEWARES), []),
|
|
132
133
|
AIWAF_PATH_RULES: toPathRules(firstDefined(rawOpts.AIWAF_PATH_RULES, rawOpts.pathRules, legacy.pathRules, process.env.AIWAF_PATH_RULES), []),
|
|
133
134
|
AIWAF_PATH_MANIFEST: firstDefined(rawOpts.AIWAF_PATH_MANIFEST, rawOpts.pathManifest, legacy.pathManifest, process.env.AIWAF_PATH_MANIFEST, '.aiwaf/paths.json'),
|
|
135
|
+
AIWAF_INJECTION_RISK_MODE: firstDefined(rawOpts.AIWAF_INJECTION_RISK_MODE, rawOpts.injectionRiskMode, process.env.AIWAF_INJECTION_RISK_MODE, 'block'),
|
|
134
136
|
AIWAF_ROUTE_PLAN_VERSION: firstDefined(rawOpts.AIWAF_ROUTE_PLAN_VERSION, rawOpts.routePlanVersion, legacy.routePlanVersion, process.env.AIWAF_ROUTE_PLAN_VERSION, 0),
|
|
135
137
|
AIWAF_ACCESS_LOG: firstDefined(rawOpts.AIWAF_ACCESS_LOG, rawOpts.accessLog, process.env.AIWAF_ACCESS_LOG, process.env.NODE_LOG_PATH),
|
|
136
138
|
|
package/lib/sqlInjection.js
CHANGED
|
@@ -1,61 +1,67 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// SQL injection checks. The check runs in aiwaf-wasm (sql_inspect), which walks the query and
|
|
4
|
+
// body, decodes values, parses JSON, applies the size limits and runs the SQL tokenizer.
|
|
5
|
+
// Findings never include request values.
|
|
6
|
+
const wasmChecks = require('./wasmChecks');
|
|
7
|
+
|
|
8
|
+
const EMPTY = new Uint8Array(0);
|
|
9
|
+
|
|
10
|
+
// Returns body bytes, or null when the body can't be serialized, such as one that contains itself.
|
|
11
|
+
function bodyBytes(body) {
|
|
12
|
+
if (body === undefined || body === null) return EMPTY;
|
|
13
|
+
if (Buffer.isBuffer(body) || body instanceof Uint8Array) return body;
|
|
14
|
+
if (typeof body === 'string') return Buffer.from(body);
|
|
15
|
+
// Frameworks may expose an unparsed upload stream; never read or consume it.
|
|
16
|
+
if (typeof body.pipe === 'function') return EMPTY;
|
|
17
|
+
try {
|
|
18
|
+
return Buffer.from(JSON.stringify(body) ?? '');
|
|
19
|
+
} catch (_) {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Every header is passed on. aiwaf-wasm decides which to check: cookies, the Referer and any
|
|
25
|
+
// other header except those holding credentials, framing or browser-set values.
|
|
26
|
+
function headerPairs(headers) {
|
|
27
|
+
if (!headers || typeof headers !== 'object') return [];
|
|
28
|
+
const found = [];
|
|
29
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
30
|
+
if (value === undefined || value === null) continue;
|
|
31
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
32
|
+
found.push([String(name), String(item)]);
|
|
33
|
+
if (found.length >= 256) return found;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return found;
|
|
37
|
+
}
|
|
8
38
|
|
|
9
39
|
function createInspector(options = {}) {
|
|
10
40
|
const mode = String(options.AIWAF_SQL_INJECTION_MODE ?? process.env.AIWAF_SQL_INJECTION_MODE ?? 'block').toLowerCase();
|
|
11
41
|
if (!['block', 'monitor', 'off'].includes(mode)) throw new Error('Invalid AIWAF_SQL_INJECTION_MODE');
|
|
12
42
|
const maxBytes = Number(options.AIWAF_PAYLOAD_MAX_BYTES ?? process.env.AIWAF_PAYLOAD_MAX_BYTES ?? 65536);
|
|
13
43
|
if (!Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > 1048576) throw new Error('AIWAF_PAYLOAD_MAX_BYTES must be 1..1048576');
|
|
44
|
+
/** Checks a request. Await wasmChecks.load() before the first call. */
|
|
14
45
|
return function inspect(req) {
|
|
15
46
|
if (mode === 'off') return null;
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
// Frameworks may expose an unparsed upload stream; never traverse or consume it.
|
|
28
|
-
if (typeof value.pipe === 'function') continue;
|
|
29
|
-
if (Buffer.isBuffer(value)) {
|
|
30
|
-
if (value.length + bytes > maxBytes) return finding('payload_inspection_limit', 413);
|
|
31
|
-
stack.push([value.toString('utf8'), depth + 1]);
|
|
32
|
-
} else if (typeof value === 'object') {
|
|
33
|
-
if (seen.has(value)) return finding('payload_inspection_limit', 413);
|
|
34
|
-
seen.add(value);
|
|
35
|
-
for (const [key, item] of Object.entries(value)) {
|
|
36
|
-
stack.push([key, depth + 1], [item, depth + 1]);
|
|
37
|
-
if (stack.length > 4096) return finding('payload_inspection_limit', 413);
|
|
38
|
-
}
|
|
39
|
-
} else if (typeof value === 'string') {
|
|
40
|
-
bytes += Buffer.byteLength(value);
|
|
41
|
-
if (bytes > maxBytes) return finding('payload_inspection_limit', 413);
|
|
42
|
-
let normalized = value;
|
|
43
|
-
for (let round = 0; round < 2; round++) {
|
|
44
|
-
try { normalized = decodeURIComponent(normalized.replace(/\+/g, ' ')); } catch (_) { break; }
|
|
45
|
-
}
|
|
46
|
-
// Decode serialized JSON escapes before signature matching.
|
|
47
|
-
if (/^\s*[\[{]/.test(normalized)) {
|
|
48
|
-
try {
|
|
49
|
-
const parsed = JSON.parse(normalized);
|
|
50
|
-
stack.push([parsed, depth + 1]);
|
|
51
|
-
} catch (_) { /* Non-JSON strings still receive signature checks. */ }
|
|
52
|
-
}
|
|
53
|
-
normalized = normalized.replace(/\/\*[\s\S]*?\*\//g, ' ');
|
|
54
|
-
for (const [rule, pattern] of RULES) if (pattern.test(normalized)) return finding(rule);
|
|
55
|
-
}
|
|
47
|
+
const wasm = wasmChecks.get();
|
|
48
|
+
const body = bodyBytes(req.body);
|
|
49
|
+
if (body === null) return { rule: 'payload_inspection_limit', status: 413, mode };
|
|
50
|
+
// Raw Node requests have only a URL. Frameworks may also have parsed the query.
|
|
51
|
+
const raw = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
|
|
52
|
+
let found = JSON.parse(wasm.sql_inspect(Buffer.from(raw), body, maxBytes));
|
|
53
|
+
if (!found && !raw && req.query && typeof req.query === 'object') {
|
|
54
|
+
const query = bodyBytes(req.query);
|
|
55
|
+
found = query === null
|
|
56
|
+
? { rule: 'payload_inspection_limit', status: 413 }
|
|
57
|
+
: JSON.parse(wasm.sql_inspect(EMPTY, query, maxBytes));
|
|
56
58
|
}
|
|
57
|
-
|
|
59
|
+
if (!found) found = JSON.parse(wasm.sql_inspect_headers(JSON.stringify(headerPairs(req.headers)), maxBytes));
|
|
60
|
+
// The URL path, one segment at a time, as in /post/1 OR 1=1.
|
|
61
|
+
const path = String(req.originalUrl || req.url || '').split('?')[0];
|
|
62
|
+
if (!found && path) found = JSON.parse(wasm.sql_inspect_path(path, maxBytes));
|
|
63
|
+
return found ? { rule: found.rule, status: found.status, mode } : null;
|
|
58
64
|
};
|
|
59
65
|
}
|
|
60
66
|
|
|
61
|
-
module.exports = { createInspector };
|
|
67
|
+
module.exports = { createInspector, bodyBytes };
|
package/lib/wafMiddleware.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
const rateLimiter = require('./rateLimiter');
|
|
2
2
|
const { createInspector } = require('./sqlInjection');
|
|
3
|
+
const wasmChecks = require('./wasmChecks');
|
|
4
|
+
const routeRisks = require('./routeRisks');
|
|
3
5
|
const blocklistManager = require('./blocklistManager');
|
|
4
6
|
const keywordDetector = require('./keywordDetector');
|
|
5
7
|
const dynamicKeyword = require('./dynamicKeyword');
|
|
@@ -12,7 +14,7 @@ const geoBlocker = require('./geoBlocker');
|
|
|
12
14
|
const middlewareLogger = require('./middlewareLogger');
|
|
13
15
|
const exemptions = require('./exemptions');
|
|
14
16
|
const requestLogStore = require('./requestLogStore');
|
|
15
|
-
const { extractExtendedRequestInfo } = require('./runtimeUtils');
|
|
17
|
+
const { extractExtendedRequestInfo, getRequestIp } = require('./runtimeUtils');
|
|
16
18
|
const { extractFeatures, init: initFeatureUtils, markRequestStart, STATIC_KW } = require('./featureUtils');
|
|
17
19
|
const { normalizeSettings } = require('./settingsCompat');
|
|
18
20
|
const {
|
|
@@ -128,12 +130,65 @@ function applyAutoMiddlewareDefaults(opts, enabled, rawOpts = {}) {
|
|
|
128
130
|
}
|
|
129
131
|
|
|
130
132
|
|
|
133
|
+
// The first aiwaf-wasm with every engine feature from_settings relies on: stores, shared rate
|
|
134
|
+
// counts, path-rule limits, monitor mode and UUID resolvers.
|
|
135
|
+
const NATIVE_DEFAULT_WASM = '0.2.7';
|
|
136
|
+
|
|
137
|
+
function installedWasmVersion() {
|
|
138
|
+
const fs = require('fs');
|
|
139
|
+
const path = require('path');
|
|
140
|
+
for (const file of [path.join(__dirname, '..', 'node_modules', 'aiwaf-wasm', 'package.json'),
|
|
141
|
+
() => require.resolve('aiwaf-wasm/package.json')]) {
|
|
142
|
+
try { return JSON.parse(fs.readFileSync(typeof file === 'function' ? file() : file, 'utf8')).version; } catch (_) { /* next */ }
|
|
143
|
+
}
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
function atLeast(version, minimum) {
|
|
147
|
+
const parse = v => String(v).split('-')[0].split('.').map(Number);
|
|
148
|
+
const [a, b] = [parse(version), parse(minimum)];
|
|
149
|
+
for (let i = 0; i < 3; i++) if ((a[i] || 0) !== (b[i] || 0)) return (a[i] || 0) > (b[i] || 0);
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
const OFF = new Set(['false', '0', 'off', 'no']);
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Whether aiwaf(options) runs the native pipeline when AIWAF_NATIVE_PIPELINE isn't set: when
|
|
156
|
+
* the installed aiwaf-wasm has every native feature and every option carries over exactly.
|
|
157
|
+
*/
|
|
158
|
+
function automaticNative(rawOpts) {
|
|
159
|
+
if (OFF.has(String(process.env.AIWAF_NATIVE_PIPELINE ?? '').trim().toLowerCase())) return null;
|
|
160
|
+
const version = installedWasmVersion();
|
|
161
|
+
if (!version || !atLeast(version, NATIVE_DEFAULT_WASM)) return null;
|
|
162
|
+
const conversion = require('./nativeSettings').nativeOptionsFromSettings(rawOpts);
|
|
163
|
+
return conversion.differences().length ? null : conversion;
|
|
164
|
+
}
|
|
165
|
+
|
|
131
166
|
module.exports = function aiwaf(rawOpts = {}) {
|
|
167
|
+
if (rawOpts.AIWAF_NATIVE_PIPELINE === false) {
|
|
168
|
+
const { AIWAF_NATIVE_PIPELINE: _off, ...regularOpts } = rawOpts;
|
|
169
|
+
rawOpts = regularOpts;
|
|
170
|
+
} else if (rawOpts.AIWAF_NATIVE_PIPELINE === undefined) {
|
|
171
|
+
const conversion = automaticNative(rawOpts);
|
|
172
|
+
if (conversion) {
|
|
173
|
+
console.info('AIWAF: using the native pipeline, since every option carries over to it. '
|
|
174
|
+
+ 'Set AIWAF_NATIVE_PIPELINE: false (or the environment variable) to keep the regular middleware.');
|
|
175
|
+
rawOpts = { ...rawOpts, AIWAF_NATIVE_PIPELINE: { fromSettings: true, conversion } };
|
|
176
|
+
}
|
|
177
|
+
}
|
|
132
178
|
if (rawOpts.AIWAF_NATIVE_PIPELINE !== undefined) {
|
|
133
|
-
|
|
179
|
+
let native = rawOpts.AIWAF_NATIVE_PIPELINE;
|
|
180
|
+
const fromSettings = native === 'from_settings' || (native && typeof native === 'object' && native.fromSettings);
|
|
181
|
+
if (fromSettings) {
|
|
182
|
+
// Convert the regular options passed alongside; native options given here win, as in Python.
|
|
183
|
+
const { AIWAF_NATIVE_PIPELINE: _ignored, ...regular } = rawOpts;
|
|
184
|
+
const { fromSettings: _flag, profile: overrides, conversion: converted, ...nativeOptions } = typeof native === 'object' ? native : {};
|
|
185
|
+
const conversion = converted || require('./nativeSettings').nativeOptionsFromSettings(regular);
|
|
186
|
+
conversion.log(nativeOptions.logger || console);
|
|
187
|
+
native = { ...conversion.options, ...nativeOptions, profile: { ...conversion.profile, ...(overrides || {}) } };
|
|
188
|
+
} else if (Object.keys(rawOpts).some(key => key !== 'AIWAF_NATIVE_PIPELINE')) {
|
|
134
189
|
throw new Error('Native pipeline uses a dedicated profile; do not mix legacy options');
|
|
135
190
|
}
|
|
136
|
-
const ready = require('./nativePipeline')(
|
|
191
|
+
const ready = require('./nativePipeline')(native);
|
|
137
192
|
// Compatibility wrapper for framework adapters. Await ready during application startup.
|
|
138
193
|
// No legacy modules are initialized and no fallback is selected on this branch.
|
|
139
194
|
const middleware = async (req, res, next) => (await ready)(req, res, next);
|
|
@@ -146,6 +201,10 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
146
201
|
opts.AIWAF_MIDDLEWARES = normalizedMiddlewareList(opts.AIWAF_MIDDLEWARES);
|
|
147
202
|
opts.AIWAF_DISABLE_MIDDLEWARES = normalizedMiddlewareList(opts.AIWAF_DISABLE_MIDDLEWARES) || [];
|
|
148
203
|
const pathRules = getEffectivePathRules(opts.AIWAF_PATH_RULES, { manifestPath: opts.AIWAF_PATH_MANIFEST });
|
|
204
|
+
const observeRisks = routeRisks.createObserver(opts);
|
|
205
|
+
// The SQL check and route checks run in aiwaf-wasm. Requests wait for it, and fail if it's missing.
|
|
206
|
+
const checksReady = wasmChecks.load();
|
|
207
|
+
checksReady.catch(() => {});
|
|
149
208
|
|
|
150
209
|
let enabledMiddlewares = planEnabledMiddlewares({
|
|
151
210
|
orderedAvailable: [
|
|
@@ -190,10 +249,13 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
190
249
|
|
|
191
250
|
const inspectPayload = async req => {
|
|
192
251
|
const path = String(req.path || req.url || '/').split('?')[0].toLowerCase();
|
|
193
|
-
const ip = req
|
|
252
|
+
const ip = getRequestIp(req, opts.AIWAF_TRUSTED_PROXIES);
|
|
194
253
|
const plan = createRoutePlan(path, pathRules, req.aiwafRoute || {});
|
|
195
254
|
if (!enabledMiddlewares.has('ip_keyword_block') || !plan.shouldApply('ip_keyword_block')
|
|
196
255
|
|| await exemptions.isExemptRequest(ip, path)) return null;
|
|
256
|
+
await checksReady;
|
|
257
|
+
const riskFinding = observeRisks ? observeRisks(req) : null;
|
|
258
|
+
if (riskFinding) return riskFinding;
|
|
197
259
|
const finding = inspectSql(req);
|
|
198
260
|
if (finding?.mode === 'monitor') {
|
|
199
261
|
(opts.logger || console).warn?.({ event: 'aiwaf.payload', rule: finding.rule, mode: finding.mode });
|
|
@@ -202,8 +264,9 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
202
264
|
return finding;
|
|
203
265
|
};
|
|
204
266
|
const middleware = async (req, res, next) => {
|
|
205
|
-
const
|
|
206
|
-
|
|
267
|
+
const ip = getRequestIp(req, opts.AIWAF_TRUSTED_PROXIES);
|
|
268
|
+
// Geo checks and logging must judge the same address as this middleware.
|
|
269
|
+
req.aiwafClientIp = ip;
|
|
207
270
|
const path = String(req.path || req.url || '/').toLowerCase();
|
|
208
271
|
const method = String(req.method || 'GET').toUpperCase();
|
|
209
272
|
if (isAutoSelection(opts.AIWAF_MIDDLEWARES)) {
|
|
@@ -504,3 +567,5 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
504
567
|
middleware.inspectPayload = inspectPayload;
|
|
505
568
|
return middleware;
|
|
506
569
|
};
|
|
570
|
+
|
|
571
|
+
module.exports.NATIVE_DEFAULT_WASM = NATIVE_DEFAULT_WASM;
|
package/lib/wasmAdapter.js
CHANGED
|
@@ -47,7 +47,13 @@ async function loadWasmFromDisk() {
|
|
|
47
47
|
python_feature_from_record: bg.python_feature_from_record,
|
|
48
48
|
python_features_batched: bg.python_features_batched,
|
|
49
49
|
NativeRequestPipeline: bg.NativeRequestPipeline,
|
|
50
|
-
NativeTrainingEvidence: bg.NativeTrainingEvidence
|
|
50
|
+
NativeTrainingEvidence: bg.NativeTrainingEvidence,
|
|
51
|
+
RouteRiskChecker: bg.RouteRiskChecker,
|
|
52
|
+
route_rule: bg.route_rule,
|
|
53
|
+
sql_inspect: bg.sql_inspect,
|
|
54
|
+
sql_inspect_headers: bg.sql_inspect_headers,
|
|
55
|
+
sql_inspect_path: bg.sql_inspect_path,
|
|
56
|
+
sql_tokenizer: bg.sql_tokenizer
|
|
51
57
|
};
|
|
52
58
|
}
|
|
53
59
|
|
|
@@ -560,6 +566,7 @@ async function createTrainingEvidence(state) {
|
|
|
560
566
|
}
|
|
561
567
|
|
|
562
568
|
module.exports = {
|
|
569
|
+
loadWasm,
|
|
563
570
|
createTrainingEvidence,
|
|
564
571
|
createRequestPipeline,
|
|
565
572
|
createIsolationForest,
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The SQL check and route checks run in aiwaf-wasm, which Node.js requires, as Python requires
|
|
4
|
+
// aiwaf-rust. There is no JavaScript copy. Call load() once before the first check.
|
|
5
|
+
const NEEDED = ['sql_inspect', 'sql_inspect_headers', 'sql_inspect_path', 'sql_tokenizer', 'route_rule', 'RouteRiskChecker'];
|
|
6
|
+
const MESSAGE = "AIWAF's request checks need aiwaf-wasm 0.2.6 or newer. Run: npm install aiwaf-wasm@^0.2.6";
|
|
7
|
+
|
|
8
|
+
let pending = null;
|
|
9
|
+
let loaded = null;
|
|
10
|
+
|
|
11
|
+
function check(mod) {
|
|
12
|
+
if (!mod || NEEDED.some(name => typeof mod[name] !== 'function')) throw new Error(MESSAGE);
|
|
13
|
+
return mod;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Loads aiwaf-wasm once. Rejects with an install hint when it's missing or too old. */
|
|
17
|
+
function load() {
|
|
18
|
+
if (!pending) {
|
|
19
|
+
pending = require('./wasmAdapter').loadWasm().then(mod => {
|
|
20
|
+
loaded = check(mod);
|
|
21
|
+
return loaded;
|
|
22
|
+
});
|
|
23
|
+
// A failed load is reported to whoever awaits it, and retried on the next call.
|
|
24
|
+
pending.catch(() => { pending = null; });
|
|
25
|
+
}
|
|
26
|
+
return pending;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Returns the loaded module. Throws when load() hasn't finished. */
|
|
30
|
+
function get() {
|
|
31
|
+
if (!loaded) throw new Error(`aiwaf-wasm isn't loaded yet. Await its load() first. ${MESSAGE}`);
|
|
32
|
+
return loaded;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Returns the loaded module, or null when load() hasn't finished. */
|
|
36
|
+
function loadedModule() {
|
|
37
|
+
return loaded;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
module.exports = { load, get, loadedModule, MESSAGE };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiwaf",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "AIWAF Web Application Firewall for JavaScript applications and major Node.js frameworks",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"files": [
|
|
@@ -22,9 +22,9 @@
|
|
|
22
22
|
"scripts": {
|
|
23
23
|
"retrain": "AIWAF_LOG_PATH=/var/log/nginx/access.log npm run train",
|
|
24
24
|
"train": "node train.js",
|
|
25
|
-
"test": "jest --runInBand",
|
|
26
|
-
"test:coverage": "jest --runInBand --coverage",
|
|
27
|
-
"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",
|
|
25
|
+
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBand",
|
|
26
|
+
"test:coverage": "node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBand --coverage",
|
|
27
|
+
"test:wasm": "node --experimental-vm-modules node_modules/jest/bin/jest.js --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",
|
|
28
28
|
"aiwaf": "node bin/aiwaf.js",
|
|
29
29
|
"test:wasm-real": "node test/wasm-real.js",
|
|
30
30
|
"test:native": "node test/native-pipeline-real.js && node test/native-frameworks-real.js"
|
|
@@ -34,9 +34,9 @@
|
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"@babel/parser": "^7.29.2",
|
|
37
|
-
"aiwaf-wasm": "^0.2.
|
|
37
|
+
"aiwaf-wasm": "^0.2.6",
|
|
38
38
|
"express": "^4.21.2",
|
|
39
|
-
"glob": "^
|
|
39
|
+
"glob": "^14.0.6",
|
|
40
40
|
"knex": "^2.4.2",
|
|
41
41
|
"node-cache": "^5.1.2",
|
|
42
42
|
"redis": "^4.6.5",
|
|
@@ -57,41 +57,6 @@
|
|
|
57
57
|
"reflect-metadata": "^0.2.2",
|
|
58
58
|
"rxjs": "^7.8.1"
|
|
59
59
|
},
|
|
60
|
-
"jest": {
|
|
61
|
-
"globalTeardown": "<rootDir>/test/jest.teardown.js",
|
|
62
|
-
"forceExit": true,
|
|
63
|
-
"coverageProvider": "v8",
|
|
64
|
-
"transform": {
|
|
65
|
-
"^.+\\.m?js$": [
|
|
66
|
-
"babel-jest",
|
|
67
|
-
{
|
|
68
|
-
"plugins": [
|
|
69
|
-
"@babel/plugin-transform-modules-commonjs"
|
|
70
|
-
]
|
|
71
|
-
}
|
|
72
|
-
]
|
|
73
|
-
},
|
|
74
|
-
"transformIgnorePatterns": [
|
|
75
|
-
"node_modules[/\\\\](?!(?:.*[/\\\\])?cookie[/\\\\])"
|
|
76
|
-
],
|
|
77
|
-
"testPathIgnorePatterns": [
|
|
78
|
-
"<rootDir>/test/wasm-adapter-real.test.js"
|
|
79
|
-
],
|
|
80
|
-
"collectCoverageFrom": [
|
|
81
|
-
"index.js",
|
|
82
|
-
"train.js",
|
|
83
|
-
"lib/**/*.js",
|
|
84
|
-
"utils/**/*.js"
|
|
85
|
-
],
|
|
86
|
-
"coverageThreshold": {
|
|
87
|
-
"global": {
|
|
88
|
-
"branches": 66,
|
|
89
|
-
"functions": 100,
|
|
90
|
-
"lines": 80,
|
|
91
|
-
"statements": 80
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
},
|
|
95
60
|
"optionalDependencies": {
|
|
96
61
|
"maxmind": "^4.3.0"
|
|
97
62
|
},
|