aiwaf 1.1.4 → 1.1.6

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.
@@ -477,8 +477,22 @@ function extractNestRoutes(app, routesInput = null) {
477
477
  }
478
478
  }
479
479
 
480
- function generateExpressManifest(app, outputPath = DEFAULT_MANIFEST_PATH) {
480
+ // Saves the source's injection findings into a manifest that's about to be written. A failed scan
481
+ // leaves the manifest without saved risks, so routes keep their normal checks.
482
+ function auditIntoManifest(manifest, source) {
483
+ if (!source) return null;
484
+ try {
485
+ const { analyzePath } = require('./injectionAnalysis');
486
+ return require('./routeRisks').applyReport(analyzePath(source), manifest);
487
+ } catch (error) {
488
+ console.warn(`Injection audit skipped: ${error.message || error}`);
489
+ return null;
490
+ }
491
+ }
492
+
493
+ function generateExpressManifest(app, outputPath = DEFAULT_MANIFEST_PATH, options = {}) {
481
494
  const manifest = buildManifest({ framework: 'express', routes: extractExpressRoutes(app) });
495
+ auditIntoManifest(manifest, options.auditSource);
482
496
  writeManifest(manifest, outputPath);
483
497
  return manifest;
484
498
  }
@@ -504,12 +518,14 @@ function generateFrameworkManifest(framework, app, outputPath = DEFAULT_MANIFEST
504
518
  routes: extractor(),
505
519
  appContext: options.appContext || {}
506
520
  });
521
+ auditIntoManifest(manifest, options.auditSource);
507
522
  writeManifest(manifest, outputPath);
508
523
  return manifest;
509
524
  }
510
525
 
511
526
  module.exports = {
512
527
  DEFAULT_MANIFEST_PATH,
528
+ auditIntoManifest,
513
529
  SCHEMA_VERSION,
514
530
  computeContextHash,
515
531
  classifyRoute,
@@ -1,5 +1,5 @@
1
1
  const NodeCache = require('node-cache');
2
- const blacklistManager = require('./blacklistManager');
2
+ const blocklistManager = require('./blocklistManager');
3
3
 
4
4
  let cacheBackend;
5
5
  let opts;
@@ -119,7 +119,7 @@ module.exports = {
119
119
  await cacheBackend.expire(key, effective.WINDOW_SEC * 2); // Extended TTL
120
120
  const count = await cacheBackend.lLen(key);
121
121
  if (count > effective.FLOOD_REQ) {
122
- await blacklistManager.block(ip, 'flood');
122
+ await blocklistManager.block(ip, 'flood');
123
123
  }
124
124
  } catch (err) {
125
125
  console.warn('Rate cache unavailable in record().');
@@ -130,9 +130,9 @@ module.exports = {
130
130
  async isBlocked(ip, overrides = {}) {
131
131
  const effective = getEffectiveOpts(overrides);
132
132
  try {
133
- if (await blacklistManager.isBlocked(ip)) return true;
133
+ if (await blocklistManager.isBlocked(ip)) return true;
134
134
  } catch (err) {
135
- console.warn('Blacklist unavailable during rate check.');
135
+ console.warn('Blocklist unavailable during rate check.');
136
136
  if (opts.failureMode === 'closed') throw unavailable();
137
137
  }
138
138
 
@@ -0,0 +1,181 @@
1
+ 'use strict';
2
+
3
+ // Uses audit findings to check risky routes' inputs on live requests. The checks run in
4
+ // aiwaf-wasm. Matches are logged and, in block mode (the default), blocked. Log events never
5
+ // include request values.
6
+ const { loadManifest, writeManifest } = require('./pathManifest');
7
+ const { bodyBytes } = require('./sqlInjection');
8
+ const wasmChecks = require('./wasmChecks');
9
+
10
+ // The operations a saved finding can name. The rules for each run in aiwaf-wasm.
11
+ const SINKS = ['sql', 'nosql', 'command', 'path', 'ssrf', 'code', 'template', 'deserialization'];
12
+
13
+ /** Returns the first rule for this operation that matches the value. Needs aiwaf-wasm loaded. */
14
+ function ruleFor(sink, value) {
15
+ return wasmChecks.get().route_rule(String(sink), String(value)) ?? null;
16
+ }
17
+
18
+ /** Compiles a manifest's saved risks in aiwaf-wasm. Needs aiwaf-wasm loaded. */
19
+ function compileRisks(manifest) {
20
+ return new (wasmChecks.get().RouteRiskChecker)(JSON.stringify(manifest ?? null));
21
+ }
22
+
23
+ // Turns a parsed query object back into name=value pairs, as in user[$ne]=1.
24
+ function queryString(query, prefix = '', out = []) {
25
+ if (query === null || query === undefined) return out;
26
+ if (typeof query !== 'object') {
27
+ out.push(`${encodeURIComponent(prefix)}=${encodeURIComponent(String(query))}`);
28
+ return out;
29
+ }
30
+ for (const [key, value] of Object.entries(query)) queryString(value, prefix ? `${prefix}[${key}]` : key, out);
31
+ return out;
32
+ }
33
+
34
+ /** Checks one request against a compiled checker and returns its matches. */
35
+ function inspectRisks(checker, path, query, body) {
36
+ const text = typeof query === 'string' ? query : queryString(query).join('&');
37
+ return JSON.parse(checker.inspect(String(path || '/'), text, bodyBytes(body) || Buffer.alloc(0)));
38
+ }
39
+
40
+ const hasRisks = manifest => Object.values((manifest && manifest.routes) || {})
41
+ .some(entry => entry && Array.isArray(entry.injection_risks) && entry.injection_risks.length);
42
+
43
+ /**
44
+ * Returns a function that checks a request, or null when there's nothing to check. The function
45
+ * returns a blocking finding in block mode, and null otherwise.
46
+ */
47
+ function createObserver(options = {}) {
48
+ const mode = String(options.AIWAF_INJECTION_RISK_MODE ?? process.env.AIWAF_INJECTION_RISK_MODE ?? 'block').trim().toLowerCase();
49
+ if (!['block', 'log', 'off'].includes(mode)) throw new Error('AIWAF_INJECTION_RISK_MODE must be block, log, or off');
50
+ if (mode === 'off') return null;
51
+ const manifest = loadManifest(options.AIWAF_PATH_MANIFEST || undefined);
52
+ if (!hasRisks(manifest)) return null;
53
+ let checker = null;
54
+ const logger = options.logger || console;
55
+ // Adapters can inspect twice: before and after the body is parsed.
56
+ const logged = new WeakMap();
57
+ return req => {
58
+ let events;
59
+ try {
60
+ const url = String(req.path || req.url || '/');
61
+ const raw = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
62
+ // Compiled on first use, after the middleware has loaded aiwaf-wasm.
63
+ checker = checker || compileRisks(manifest);
64
+ events = inspectRisks(checker, url.split('?')[0], raw || req.query, req.body);
65
+ } catch (_) {
66
+ // A failing check must not break the request. Other protections still apply.
67
+ return null;
68
+ }
69
+ if (!events.length) return null;
70
+ const seen = logged.get(req) || new Set();
71
+ logged.set(req, seen);
72
+ for (const event of events) {
73
+ const key = JSON.stringify(event);
74
+ if (seen.has(key)) continue;
75
+ seen.add(key);
76
+ try {
77
+ logger.warn?.({ event: 'aiwaf.injection_risk', mode, method: String(req.method || ''), ...event });
78
+ } catch (_) { /* Logging must not decide the outcome. */ }
79
+ }
80
+ return mode === 'block' ? { rule: events[0].rule, status: 403, mode: 'block' } : null;
81
+ };
82
+ }
83
+
84
+ function inputFromSource(source) {
85
+ const text = String(source || '');
86
+ let match = /^@\w+ (.+)$/.exec(text);
87
+ if (match) return match[1];
88
+ match = /\('(.+?)'\)$/.exec(text);
89
+ if (match) return match[1];
90
+ match = /(?:\.|^request )(?:body|params|payload|query)\.([^.]+)$/.exec(text);
91
+ return match ? match[1] : '';
92
+ }
93
+
94
+ const trimRoute = path => (path.length > 1 ? path.replace(/\/+$/, '') : path);
95
+
96
+ function fileRoute(filename) {
97
+ const file = String(filename).replace(/\\/g, '/');
98
+ let match = /(?:^|\/)pages(\/api\/.*?)(?:\/index)?\.[cm]?[jt]sx?$/.exec(file);
99
+ if (match) return match[1].replace(/\[\.{3}([^\]]+)\]/g, ':$1*').replace(/\[([^\]]+)\]/g, ':$1');
100
+ match = /(?:^|\/)app(\/.*?)\/route\.[cm]?[jt]sx?$/.exec(file);
101
+ return match ? match[1].replace(/\[\.{3}([^\]]+)\]/g, ':$1*').replace(/\[([^\]]+)\]/g, ':$1') : '';
102
+ }
103
+
104
+ function routesFor(finding, routes) {
105
+ const entry = String(finding.function || '').split(' -> ')[0];
106
+ const paths = Object.keys(routes);
107
+ const fromSource = (/^\S+ (\/\S*)$/.exec(entry) || [])[1] || fileRoute(finding.file);
108
+ if (fromSource) {
109
+ const wanted = trimRoute(fromSource);
110
+ const exact = paths.filter(path => trimRoute(path) === wanted);
111
+ if (exact.length) return exact;
112
+ // A router mounted under a prefix. Only trust this when one route fits.
113
+ const mounted = paths.filter(path => trimRoute(path).endsWith(wanted));
114
+ if (mounted.length === 1) return mounted;
115
+ if (entry.includes(' ')) return [];
116
+ }
117
+ // JavaScript views are bare function names, so a name used twice can't be trusted.
118
+ const name = entry.split('.').pop();
119
+ const named = paths.filter(path => {
120
+ const view = String(routes[path]?.view || '').replace(/^bound /, '');
121
+ return view && view.split('.').pop() === name;
122
+ });
123
+ return named.length === 1 ? named : [];
124
+ }
125
+
126
+ /** Replaces saved risks in a manifest with this report's findings, and counts the results. */
127
+ function applyReport(report, manifest) {
128
+ const routes = manifest && manifest.routes;
129
+ if (!routes || typeof routes !== 'object' || Array.isArray(routes)) throw new Error('The manifest has no routes');
130
+ for (const entry of Object.values(routes)) if (entry && typeof entry === 'object') delete entry.injection_risks;
131
+ let linked = 0;
132
+ let unlinked = 0;
133
+ const collected = new Map();
134
+ for (const finding of report.findings || []) {
135
+ const matches = routesFor(finding, routes);
136
+ if (matches.length) linked += 1;
137
+ else unlinked += 1;
138
+ for (const path of matches) {
139
+ const risk = { sink: String(finding.sink), input: inputFromSource(finding.source), confidence: String(finding.confidence) };
140
+ if (!collected.has(path)) collected.set(path, new Map());
141
+ collected.get(path).set(`${risk.sink}\0${risk.input}`, risk);
142
+ }
143
+ }
144
+ for (const [path, risks] of collected) {
145
+ routes[path].injection_risks = [...risks.keys()].sort().map(key => risks.get(key));
146
+ }
147
+ manifest.injection_audit = {
148
+ generated_at: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
149
+ files_scanned: Number(report.files_scanned || 0),
150
+ linked_findings: linked,
151
+ unlinked_findings: unlinked
152
+ };
153
+ return { routes: collected.size, linked, unlinked };
154
+ }
155
+
156
+ function updateManifest(report, manifestPath) {
157
+ const manifest = loadManifest(manifestPath);
158
+ if (!manifest) throw new Error(`Manifest not found or unreadable: ${manifestPath}. Generate it first with init.`);
159
+ const counts = applyReport(report, manifest);
160
+ writeManifest(manifest, manifestPath);
161
+ return counts;
162
+ }
163
+
164
+ function formatCounts(counts, manifestPath) {
165
+ const saved = `Saved ${counts.linked} possible injection paths to ${counts.routes} routes in ${manifestPath}.`;
166
+ return counts.unlinked
167
+ ? `${saved} ${counts.unlinked} couldn't be tied to a route, so they get no route-specific checks.`
168
+ : saved;
169
+ }
170
+
171
+ module.exports = {
172
+ SINKS,
173
+ applyReport,
174
+ compileRisks,
175
+ createObserver,
176
+ formatCounts,
177
+ inputFromSource,
178
+ inspectRisks,
179
+ ruleFor,
180
+ updateManifest
181
+ };
@@ -7,12 +7,200 @@ const STATIC_EXTENSIONS = new Set([
7
7
  '.xml', '.txt', '.pdf', '.zip', '.tar', '.gz', '.webp', '.avif'
8
8
  ]);
9
9
 
10
- function getRequestIp(req = {}) {
11
- const forwarded = req.headers?.['x-forwarded-for'];
12
- const raw = forwarded
13
- ? String(forwarded).split(',')[0].trim()
14
- : (req.ip || req.connection?.remoteAddress || req.socket?.remoteAddress || '');
15
- return String(raw).replace(/^::ffff:/, '');
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,
@@ -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
 
@@ -1,61 +1,67 @@
1
- // Deterministic, bounded signatures. Findings never include request values.
2
- const RULES = [
3
- ['sql_union_select', /\bunion\s+(?:all\s+)?select\b/i],
4
- ['sql_boolean_tautology', /['"`]\s*(?:or|and)\s+(?:true\b|\d+\s*=\s*\d+|['"][^'"\r\n]{0,80}['"]\s*=\s*['"])/i],
5
- ['sql_quote_comment', /['"`]\s*(?:--|#)/],
6
- ['sql_stacked_statement', /;\s*(?:drop\s+table|delete\s+from|insert\s+into|update\s+\w+\s+set)\b/i]
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 stack = [[req.body, 0], [req.query, 0]];
17
- // Also handles raw Node requests whose framework has not populated query.
18
- const query = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
19
- if (query) stack.push([query, 0]);
20
- let bytes = 0, nodes = 0;
21
- const seen = new Set();
22
- const finding = (rule, status = 403) => ({ rule, status, mode });
23
- while (stack.length) {
24
- const [value, depth] = stack.pop();
25
- if (++nodes > 4096 || depth > 16) return finding('payload_inspection_limit', 413);
26
- if (value === undefined || value === null) continue;
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
- return null;
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 };