aiwaf 1.2.4 → 1.3.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 +207 -32
- package/index.js +4 -0
- package/lib/blocklistManager.js +1 -0
- package/lib/bodyPeek.js +40 -0
- package/lib/injectionAnalysis.js +29 -4
- package/lib/inputSchema.js +301 -0
- package/lib/nativePipeline.js +50 -39
- package/lib/profiles.js +53 -0
- package/lib/routeRisks.js +80 -12
- package/lib/settingsCompat.js +9 -4
- package/lib/sqlInjection.js +59 -10
- package/lib/wafMiddleware.js +28 -8
- package/lib/wasmAdapter.js +18 -3
- package/lib/webSocketGuard.js +97 -0
- package/package.json +9 -3
- package/utils/db.js +82 -6
package/lib/routeRisks.js
CHANGED
|
@@ -6,9 +6,13 @@
|
|
|
6
6
|
const { loadManifest, writeManifest } = require('./pathManifest');
|
|
7
7
|
const { bodyBytes } = require('./sqlInjection');
|
|
8
8
|
const wasmChecks = require('./wasmChecks');
|
|
9
|
+
const { mergeInto } = require('./inputSchema');
|
|
9
10
|
|
|
10
11
|
// The operations a saved finding can name. The rules for each run in aiwaf-wasm.
|
|
11
|
-
const SINKS = [
|
|
12
|
+
const SINKS = [
|
|
13
|
+
'sql', 'nosql', 'command', 'path', 'ssrf', 'code', 'template', 'deserialization', 'xss', 'redirect', 'ldap', 'xpath', 'xxe',
|
|
14
|
+
'redos', 'prototype'
|
|
15
|
+
];
|
|
12
16
|
|
|
13
17
|
/** Returns the first rule for this operation that matches the value. Needs aiwaf-wasm loaded. */
|
|
14
18
|
function ruleFor(sink, value) {
|
|
@@ -39,6 +43,18 @@ function inspectRisks(checker, path, query, body) {
|
|
|
39
43
|
|
|
40
44
|
const hasRisks = manifest => Object.values((manifest && manifest.routes) || {})
|
|
41
45
|
.some(entry => entry && Array.isArray(entry.injection_risks) && entry.injection_risks.length);
|
|
46
|
+
const hasInputs = manifest => Object.values((manifest && manifest.routes) || {})
|
|
47
|
+
.some(entry => entry && entry.inputs && typeof entry.inputs === 'object' && !Array.isArray(entry.inputs));
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Reviews a request against the inputs init saved for its route, after the general check found
|
|
51
|
+
* `found` (a rule, or null). Returns {action: 'mismatch', route, input, type},
|
|
52
|
+
* {action: 'relax', route, rule}, or null to keep the general check's answer. See aiwaf-rust.
|
|
53
|
+
*/
|
|
54
|
+
function reviewRequest(checker, path, query, body, maxBytes, found) {
|
|
55
|
+
const text = typeof query === 'string' ? query : queryString(query).join('&');
|
|
56
|
+
return JSON.parse(checker.review(String(path || '/'), text, bodyBytes(body) || Buffer.alloc(0), maxBytes, found || ''));
|
|
57
|
+
}
|
|
42
58
|
|
|
43
59
|
/**
|
|
44
60
|
* Returns a function that checks a request, or null when there's nothing to check. The function
|
|
@@ -47,21 +63,28 @@ const hasRisks = manifest => Object.values((manifest && manifest.routes) || {})
|
|
|
47
63
|
function createObserver(options = {}) {
|
|
48
64
|
const mode = String(options.AIWAF_INJECTION_RISK_MODE ?? process.env.AIWAF_INJECTION_RISK_MODE ?? 'block').trim().toLowerCase();
|
|
49
65
|
if (!['block', 'log', 'off'].includes(mode)) throw new Error('AIWAF_INJECTION_RISK_MODE must be block, log, or off');
|
|
50
|
-
|
|
66
|
+
let schema = String(options.AIWAF_ROUTE_SCHEMA_MODE ?? process.env.AIWAF_ROUTE_SCHEMA_MODE ?? 'monitor').trim().toLowerCase();
|
|
67
|
+
if (!['enforce', 'monitor', 'off'].includes(schema)) throw new Error('AIWAF_ROUTE_SCHEMA_MODE must be enforce, monitor, or off');
|
|
51
68
|
const manifest = loadManifest(options.AIWAF_PATH_MANIFEST || undefined);
|
|
52
|
-
if (!
|
|
69
|
+
if (!hasInputs(manifest)) schema = 'off';
|
|
70
|
+
if ((mode === 'off' || !hasRisks(manifest)) && schema === 'off') return null;
|
|
53
71
|
let checker = null;
|
|
54
72
|
const logger = options.logger || console;
|
|
55
73
|
// Adapters can inspect twice: before and after the body is parsed.
|
|
56
74
|
const logged = new WeakMap();
|
|
57
|
-
|
|
75
|
+
const target = req => {
|
|
76
|
+
const url = String(req.path || req.url || '/');
|
|
77
|
+
const raw = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
|
|
78
|
+
// Compiled on first use, after the middleware has loaded aiwaf-wasm.
|
|
79
|
+
checker = checker || compileRisks(manifest);
|
|
80
|
+
return [url.split('?')[0], raw || req.query];
|
|
81
|
+
};
|
|
82
|
+
const observe = req => {
|
|
83
|
+
if (mode === 'off') return null;
|
|
58
84
|
let events;
|
|
59
85
|
try {
|
|
60
|
-
const
|
|
61
|
-
|
|
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);
|
|
86
|
+
const [path, query] = target(req);
|
|
87
|
+
events = inspectRisks(checker, path, query, req.body);
|
|
65
88
|
} catch (_) {
|
|
66
89
|
// A failing check must not break the request. Other protections still apply.
|
|
67
90
|
return null;
|
|
@@ -79,6 +102,38 @@ function createObserver(options = {}) {
|
|
|
79
102
|
}
|
|
80
103
|
return mode === 'block' ? { rule: events[0].rule, status: 403, mode: 'block' } : null;
|
|
81
104
|
};
|
|
105
|
+
if (schema !== 'off') {
|
|
106
|
+
/**
|
|
107
|
+
* The general check's finding (or null), after the route's saved inputs review it: enforce
|
|
108
|
+
* blocks a typed input of another type and drops findings the schema clears; monitor logs.
|
|
109
|
+
*/
|
|
110
|
+
const decide = (req, finding, run) => {
|
|
111
|
+
let result;
|
|
112
|
+
try {
|
|
113
|
+
result = run();
|
|
114
|
+
} catch (_) {
|
|
115
|
+
return finding;
|
|
116
|
+
}
|
|
117
|
+
if (!result) return finding;
|
|
118
|
+
const { action, route } = result;
|
|
119
|
+
const event = { event: 'aiwaf.route_schema', mode: schema, method: String(req.method || ''), route, action,
|
|
120
|
+
...(action === 'mismatch' ? { input: result.input, type: result.type } : { rule: result.rule }) };
|
|
121
|
+
try { logger.warn?.(event); } catch (_) { /* Logging must not decide the outcome. */ }
|
|
122
|
+
if (schema !== 'enforce') return finding;
|
|
123
|
+
return action === 'mismatch' ? { rule: 'schema_type_mismatch', status: 403, mode: 'block' } : null;
|
|
124
|
+
};
|
|
125
|
+
observe.review = (req, finding, maxBytes, body = req.body) => decide(req, finding, () => {
|
|
126
|
+
const [path, query] = target(req);
|
|
127
|
+
const found = finding && finding.status === 403 ? finding.rule : null;
|
|
128
|
+
return reviewRequest(checker, path, query, body, maxBytes, found);
|
|
129
|
+
});
|
|
130
|
+
/** A finding from the URL path, reviewed against the route's parameters. */
|
|
131
|
+
observe.reviewPath = (req, finding, maxBytes) => (finding.status !== 403 ? finding : decide(req, finding, () => {
|
|
132
|
+
const [path] = target(req);
|
|
133
|
+
return JSON.parse(checker.review_path(path, maxBytes, finding.rule));
|
|
134
|
+
}));
|
|
135
|
+
}
|
|
136
|
+
return observe;
|
|
82
137
|
}
|
|
83
138
|
|
|
84
139
|
function inputFromSource(source) {
|
|
@@ -127,7 +182,13 @@ function routesFor(finding, routes) {
|
|
|
127
182
|
function applyReport(report, manifest) {
|
|
128
183
|
const routes = manifest && manifest.routes;
|
|
129
184
|
if (!routes || typeof routes !== 'object' || Array.isArray(routes)) throw new Error('The manifest has no routes');
|
|
130
|
-
for (const entry of Object.values(routes))
|
|
185
|
+
for (const entry of Object.values(routes)) {
|
|
186
|
+
if (entry && typeof entry === 'object') {
|
|
187
|
+
delete entry.injection_risks;
|
|
188
|
+
delete entry.inputs;
|
|
189
|
+
delete entry.inputs_complete;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
131
192
|
let linked = 0;
|
|
132
193
|
let unlinked = 0;
|
|
133
194
|
const collected = new Map();
|
|
@@ -144,13 +205,19 @@ function applyReport(report, manifest) {
|
|
|
144
205
|
for (const [path, risks] of collected) {
|
|
145
206
|
routes[path].injection_risks = [...risks.keys()].sort().map(key => risks.get(key));
|
|
146
207
|
}
|
|
208
|
+
// What each route reads, with types. A route whose handlers weren't all found gets none.
|
|
209
|
+
for (const entry of report.inputs || []) {
|
|
210
|
+
for (const path of routesFor(entry, routes)) mergeInto(routes, path, entry);
|
|
211
|
+
}
|
|
212
|
+
const typed = Object.values(routes).filter(entry => entry && typeof entry === 'object' && entry.inputs).length;
|
|
147
213
|
manifest.injection_audit = {
|
|
148
214
|
generated_at: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
|
|
149
215
|
files_scanned: Number(report.files_scanned || 0),
|
|
150
216
|
linked_findings: linked,
|
|
151
|
-
unlinked_findings: unlinked
|
|
217
|
+
unlinked_findings: unlinked,
|
|
218
|
+
routes_with_inputs: typed
|
|
152
219
|
};
|
|
153
|
-
return { routes: collected.size, linked, unlinked };
|
|
220
|
+
return { routes: collected.size, linked, unlinked, inputs: typed };
|
|
154
221
|
}
|
|
155
222
|
|
|
156
223
|
function updateManifest(report, manifestPath) {
|
|
@@ -176,6 +243,7 @@ module.exports = {
|
|
|
176
243
|
formatCounts,
|
|
177
244
|
inputFromSource,
|
|
178
245
|
inspectRisks,
|
|
246
|
+
reviewRequest,
|
|
179
247
|
ruleFor,
|
|
180
248
|
updateManifest
|
|
181
249
|
};
|
package/lib/settingsCompat.js
CHANGED
|
@@ -65,6 +65,9 @@ function toPathRules(value, defaultValue = []) {
|
|
|
65
65
|
|
|
66
66
|
function normalizeSettings(rawOpts = {}) {
|
|
67
67
|
const legacy = rawOpts.AIWAF_SETTINGS || {};
|
|
68
|
+
// AIWAF_PROFILE supplies the defaults below; a setting given explicitly still wins.
|
|
69
|
+
const profile = require('./profiles').resolve(firstDefined(rawOpts.AIWAF_PROFILE, rawOpts.profile));
|
|
70
|
+
const preset = require('./profiles').defaultsFor(profile);
|
|
68
71
|
|
|
69
72
|
const normalized = {
|
|
70
73
|
...rawOpts,
|
|
@@ -72,8 +75,8 @@ function normalizeSettings(rawOpts = {}) {
|
|
|
72
75
|
dynamicTopN: toNumber(firstDefined(rawOpts.dynamicTopN, rawOpts.DYNAMIC_TOP_N, legacy.keywords?.dynamicTopN), 10),
|
|
73
76
|
|
|
74
77
|
WINDOW_SEC: toNumber(firstDefined(rawOpts.WINDOW_SEC, rawOpts.windowSec, rawOpts.AIWAF_WINDOW_SECONDS, legacy.rate?.window, process.env.AIWAF_RATE_WINDOW), 60),
|
|
75
|
-
MAX_REQ: toNumber(firstDefined(rawOpts.MAX_REQ, rawOpts.maxReq, legacy.rate?.max, process.env.AIWAF_RATE_MAX), 100),
|
|
76
|
-
FLOOD_REQ: toNumber(firstDefined(rawOpts.FLOOD_REQ, rawOpts.floodReq, legacy.rate?.flood, process.env.AIWAF_RATE_FLOOD), 200),
|
|
78
|
+
MAX_REQ: toNumber(firstDefined(rawOpts.MAX_REQ, rawOpts.maxReq, legacy.rate?.max, process.env.AIWAF_RATE_MAX), preset.MAX_REQ ?? 100),
|
|
79
|
+
FLOOD_REQ: toNumber(firstDefined(rawOpts.FLOOD_REQ, rawOpts.floodReq, legacy.rate?.flood, process.env.AIWAF_RATE_FLOOD), preset.FLOOD_REQ ?? 200),
|
|
77
80
|
|
|
78
81
|
HONEYPOT_FIELD: firstDefined(rawOpts.HONEYPOT_FIELD, rawOpts.honeypotField, legacy.honeypot?.field),
|
|
79
82
|
AIWAF_MIN_FORM_TIME: toNumber(firstDefined(rawOpts.AIWAF_MIN_FORM_TIME, rawOpts.minFormTime, legacy.honeypot?.minFormTime, process.env.AIWAF_MIN_FORM_TIME), 0),
|
|
@@ -81,7 +84,7 @@ function normalizeSettings(rawOpts = {}) {
|
|
|
81
84
|
AIWAF_LOGIN_PATH_PREFIXES: toArray(firstDefined(rawOpts.AIWAF_LOGIN_PATH_PREFIXES, rawOpts.loginPathPrefixes, legacy.honeypot?.loginPathPrefixes, process.env.AIWAF_LOGIN_PATH_PREFIXES), [...loginPathPrefixes]),
|
|
82
85
|
AIWAF_POST_ONLY_SUFFIXES: toArray(firstDefined(rawOpts.AIWAF_POST_ONLY_SUFFIXES, rawOpts.postOnlySuffixes, legacy.honeypot?.postOnlySuffixes, process.env.AIWAF_POST_ONLY_SUFFIXES), undefined),
|
|
83
86
|
AIWAF_ALLOWED_METHODS: toArray(firstDefined(rawOpts.AIWAF_ALLOWED_METHODS, rawOpts.allowedMethods, legacy.honeypot?.allowedMethods, process.env.AIWAF_ALLOWED_METHODS), undefined),
|
|
84
|
-
AIWAF_METHOD_POLICY_ENABLED: toBool(firstDefined(rawOpts.AIWAF_METHOD_POLICY_ENABLED, rawOpts.methodPolicyEnabled, legacy.honeypot?.methodPolicyEnabled, process.env.AIWAF_METHOD_POLICY_ENABLED), false),
|
|
87
|
+
AIWAF_METHOD_POLICY_ENABLED: toBool(firstDefined(rawOpts.AIWAF_METHOD_POLICY_ENABLED, rawOpts.methodPolicyEnabled, legacy.honeypot?.methodPolicyEnabled, process.env.AIWAF_METHOD_POLICY_ENABLED), preset.AIWAF_METHOD_POLICY_ENABLED ?? false),
|
|
85
88
|
|
|
86
89
|
AIWAF_EXEMPT_PATHS: toArray(firstDefined(rawOpts.AIWAF_EXEMPT_PATHS, rawOpts.exemptPaths, legacy.exemptions?.paths, process.env.AIWAF_EXEMPT_PATHS), []),
|
|
87
90
|
AIWAF_EXEMPT_IPS: toArray(firstDefined(rawOpts.AIWAF_EXEMPT_IPS, rawOpts.exemptIps, legacy.exemptions?.ips, process.env.AIWAF_EXEMPT_IPS), []),
|
|
@@ -134,7 +137,9 @@ function normalizeSettings(rawOpts = {}) {
|
|
|
134
137
|
AIWAF_DISABLE_MIDDLEWARES: toArray(firstDefined(rawOpts.AIWAF_DISABLE_MIDDLEWARES, rawOpts.disableMiddlewares, rawOpts.disabledMiddlewares, legacy.middlewares?.disabled, process.env.AIWAF_DISABLE_MIDDLEWARES), []),
|
|
135
138
|
AIWAF_PATH_RULES: toPathRules(firstDefined(rawOpts.AIWAF_PATH_RULES, rawOpts.pathRules, legacy.pathRules, process.env.AIWAF_PATH_RULES), []),
|
|
136
139
|
AIWAF_PATH_MANIFEST: firstDefined(rawOpts.AIWAF_PATH_MANIFEST, rawOpts.pathManifest, legacy.pathManifest, process.env.AIWAF_PATH_MANIFEST, '.aiwaf/paths.json'),
|
|
137
|
-
AIWAF_INJECTION_RISK_MODE: firstDefined(rawOpts.AIWAF_INJECTION_RISK_MODE, rawOpts.injectionRiskMode, process.env.AIWAF_INJECTION_RISK_MODE, 'block'),
|
|
140
|
+
AIWAF_INJECTION_RISK_MODE: firstDefined(rawOpts.AIWAF_INJECTION_RISK_MODE, rawOpts.injectionRiskMode, process.env.AIWAF_INJECTION_RISK_MODE, preset.AIWAF_INJECTION_RISK_MODE, 'block'),
|
|
141
|
+
AIWAF_SQL_INJECTION_MODE: firstDefined(rawOpts.AIWAF_SQL_INJECTION_MODE, rawOpts.sqlInjectionMode, process.env.AIWAF_SQL_INJECTION_MODE, preset.AIWAF_SQL_INJECTION_MODE),
|
|
142
|
+
AIWAF_PROFILE: profile,
|
|
138
143
|
AIWAF_ROUTE_PLAN_VERSION: firstDefined(rawOpts.AIWAF_ROUTE_PLAN_VERSION, rawOpts.routePlanVersion, legacy.routePlanVersion, process.env.AIWAF_ROUTE_PLAN_VERSION, 0),
|
|
139
144
|
AIWAF_ACCESS_LOG: firstDefined(rawOpts.AIWAF_ACCESS_LOG, rawOpts.accessLog, process.env.AIWAF_ACCESS_LOG, process.env.NODE_LOG_PATH),
|
|
140
145
|
|
package/lib/sqlInjection.js
CHANGED
|
@@ -3,7 +3,12 @@
|
|
|
3
3
|
// SQL injection checks. The check runs in aiwaf-wasm (sql_inspect), which walks the query and
|
|
4
4
|
// body, decodes values, parses JSON, applies the size limits and runs the SQL tokenizer.
|
|
5
5
|
// Findings never include request values.
|
|
6
|
+
const zlib = require('zlib');
|
|
6
7
|
const wasmChecks = require('./wasmChecks');
|
|
8
|
+
const { peekBody, isMultipart } = require('./bodyPeek');
|
|
9
|
+
|
|
10
|
+
// The start of a multipart body, read by peekUpload before a body parser has run.
|
|
11
|
+
const UPLOAD = Symbol('aiwaf.upload-prefix');
|
|
7
12
|
|
|
8
13
|
const EMPTY = new Uint8Array(0);
|
|
9
14
|
|
|
@@ -30,25 +35,63 @@ function headerPairs(headers) {
|
|
|
30
35
|
if (value === undefined || value === null) continue;
|
|
31
36
|
for (const item of Array.isArray(value) ? value : [value]) {
|
|
32
37
|
found.push([String(name), String(item)]);
|
|
33
|
-
|
|
38
|
+
// One past what aiwaf-wasm checks, so it refuses a request with too many, not skips them.
|
|
39
|
+
if (found.length > 256) return found;
|
|
34
40
|
}
|
|
35
41
|
}
|
|
36
42
|
return found;
|
|
37
43
|
}
|
|
38
44
|
|
|
45
|
+
// A raw body in the encoding it was sent in. aiwaf-wasm reads gzip and deflate itself; br is
|
|
46
|
+
// decoded here, to at most maxBytes + 1 bytes, so the check refuses a larger one. Null for an
|
|
47
|
+
// encoding that can't be read.
|
|
48
|
+
function decoded(body, encoding, maxBytes) {
|
|
49
|
+
const name = String(encoding || 'identity').trim().toLowerCase();
|
|
50
|
+
if (['', 'identity', 'gzip', 'x-gzip', 'deflate'].includes(name)) return body;
|
|
51
|
+
if (name !== 'br') return null;
|
|
52
|
+
try {
|
|
53
|
+
return zlib.brotliDecompressSync(body, { maxOutputLength: maxBytes + 1 });
|
|
54
|
+
} catch (_) {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Reads the start of an unparsed multipart body, then puts it back on the stream, so the
|
|
61
|
+
* inspector checks its text fields, file names and file headers before an upload parser runs.
|
|
62
|
+
* A body that isn't multipart, or was already read, is left alone.
|
|
63
|
+
*/
|
|
64
|
+
async function peekUpload(req, maxBytes) {
|
|
65
|
+
if (req.body !== undefined || req[UPLOAD] || !isMultipart(req) || typeof req.read !== 'function'
|
|
66
|
+
|| typeof req.unshift !== 'function' || req.readableEnded) return;
|
|
67
|
+
const declared = Number(req.headers?.['content-length'] || 0) > 0 || !!req.headers?.['transfer-encoding'];
|
|
68
|
+
if (declared) req[UPLOAD] = await peekBody(req, maxBytes);
|
|
69
|
+
}
|
|
70
|
+
|
|
39
71
|
function createInspector(options = {}) {
|
|
40
72
|
const mode = String(options.AIWAF_SQL_INJECTION_MODE ?? process.env.AIWAF_SQL_INJECTION_MODE ?? 'block').toLowerCase();
|
|
41
73
|
if (!['block', 'monitor', 'off'].includes(mode)) throw new Error('Invalid AIWAF_SQL_INJECTION_MODE');
|
|
42
74
|
const maxBytes = Number(options.AIWAF_PAYLOAD_MAX_BYTES ?? process.env.AIWAF_PAYLOAD_MAX_BYTES ?? 65536);
|
|
43
75
|
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
|
|
45
|
-
|
|
76
|
+
/** Checks a request. Await wasmChecks.load(), and inspect.prepare(req), before the call. */
|
|
77
|
+
inspect.prepare = req => (mode === 'off' ? Promise.resolve() : peekUpload(req, maxBytes));
|
|
78
|
+
inspect.maxBytes = maxBytes;
|
|
79
|
+
return inspect;
|
|
80
|
+
function inspect(req) {
|
|
46
81
|
if (mode === 'off') return null;
|
|
47
82
|
const wasm = wasmChecks.get();
|
|
48
|
-
const body = bodyBytes(req.body);
|
|
49
|
-
if (body === null) return { rule: 'payload_inspection_limit', status: 413, mode };
|
|
50
83
|
// Raw Node requests have only a URL. Frameworks may also have parsed the query.
|
|
51
84
|
const raw = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
|
|
85
|
+
let body = req.body === undefined && req[UPLOAD]
|
|
86
|
+
// A large upload is checked by its start: its text fields and file headers come first.
|
|
87
|
+
? req[UPLOAD].subarray(0, Math.max(0, maxBytes - Buffer.byteLength(raw)))
|
|
88
|
+
: bodyBytes(req.body);
|
|
89
|
+
// Only a raw body is still encoded: a parsed one was decoded by its parser.
|
|
90
|
+
const unparsed = Buffer.isBuffer(req.body) || req.body instanceof Uint8Array || typeof req.body === 'string';
|
|
91
|
+
if (body !== null && body.length && unparsed) body = decoded(body, req.headers?.['content-encoding'], maxBytes);
|
|
92
|
+
if (body === null) return { rule: 'payload_inspection_limit', status: 413, mode };
|
|
93
|
+
// Where the finding came from, so the route's saved inputs can review it.
|
|
94
|
+
let source = 'payload';
|
|
52
95
|
let found = JSON.parse(wasm.sql_inspect(Buffer.from(raw), body, maxBytes));
|
|
53
96
|
if (!found && !raw && req.query && typeof req.query === 'object') {
|
|
54
97
|
const query = bodyBytes(req.query);
|
|
@@ -56,12 +99,18 @@ function createInspector(options = {}) {
|
|
|
56
99
|
? { rule: 'payload_inspection_limit', status: 413 }
|
|
57
100
|
: JSON.parse(wasm.sql_inspect(EMPTY, query, maxBytes));
|
|
58
101
|
}
|
|
59
|
-
if (!found)
|
|
102
|
+
if (!found) {
|
|
103
|
+
source = 'headers';
|
|
104
|
+
found = JSON.parse(wasm.sql_inspect_headers(JSON.stringify(headerPairs(req.headers)), maxBytes));
|
|
105
|
+
}
|
|
60
106
|
// The URL path, one segment at a time, as in /post/1 OR 1=1.
|
|
61
107
|
const path = String(req.originalUrl || req.url || '').split('?')[0];
|
|
62
|
-
if (!found && path)
|
|
63
|
-
|
|
64
|
-
|
|
108
|
+
if (!found && path) {
|
|
109
|
+
source = 'path';
|
|
110
|
+
found = JSON.parse(wasm.sql_inspect_path(path, maxBytes));
|
|
111
|
+
}
|
|
112
|
+
return found ? { rule: found.rule, status: found.status, mode, source } : null;
|
|
113
|
+
}
|
|
65
114
|
}
|
|
66
115
|
|
|
67
|
-
module.exports = { createInspector, bodyBytes };
|
|
116
|
+
module.exports = { createInspector, bodyBytes, peekUpload };
|
package/lib/wafMiddleware.js
CHANGED
|
@@ -161,13 +161,9 @@ function applyAutoMiddlewareDefaults(opts, enabled, rawOpts = {}) {
|
|
|
161
161
|
const NATIVE_DEFAULT_WASM = '0.2.9';
|
|
162
162
|
|
|
163
163
|
function installedWasmVersion() {
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
() => require.resolve('aiwaf-wasm/package.json')]) {
|
|
168
|
-
try { return JSON.parse(fs.readFileSync(typeof file === 'function' ? file() : file, 'utf8')).version; } catch (_) { /* next */ }
|
|
169
|
-
}
|
|
170
|
-
return null;
|
|
164
|
+
const dir = require('./wasmAdapter').wasmPackageDir();
|
|
165
|
+
if (!dir) return null;
|
|
166
|
+
try { return JSON.parse(require('fs').readFileSync(require('path').join(dir, 'package.json'), 'utf8')).version; } catch (_) { return null; }
|
|
171
167
|
}
|
|
172
168
|
function atLeast(version, minimum) {
|
|
173
169
|
const parse = v => String(v).split('-')[0].split('.').map(Number);
|
|
@@ -225,6 +221,18 @@ const recentRequests = limit => Promise.resolve().then(() => requestLogStore.rec
|
|
|
225
221
|
.catch(error => { storeFailed('request log read', error); return []; });
|
|
226
222
|
|
|
227
223
|
module.exports = function aiwaf(rawOpts = {}) {
|
|
224
|
+
const profiles = require('./profiles');
|
|
225
|
+
if (profiles.activate(rawOpts.AIWAF_PROFILE ?? rawOpts.profile) === 'monitor') {
|
|
226
|
+
// Monitor runs the regular middleware, whose every block can be logged instead.
|
|
227
|
+
if (rawOpts.AIWAF_NATIVE_PIPELINE !== undefined && rawOpts.AIWAF_NATIVE_PIPELINE !== false) {
|
|
228
|
+
throw new Error('AIWAF_PROFILE=monitor runs the regular middleware: leave AIWAF_NATIVE_PIPELINE unset.');
|
|
229
|
+
}
|
|
230
|
+
if (rawOpts.AIWAF_NATIVE_PIPELINE === undefined) {
|
|
231
|
+
staysRegular('AIWAF_PROFILE is monitor, which logs what it would block instead of blocking.');
|
|
232
|
+
console.warn('AIWAF monitor: nothing is blocked; what would be blocked is logged.');
|
|
233
|
+
}
|
|
234
|
+
rawOpts = { ...rawOpts, AIWAF_NATIVE_PIPELINE: false };
|
|
235
|
+
}
|
|
228
236
|
if (rawOpts.AIWAF_NATIVE_PIPELINE === false) {
|
|
229
237
|
const { AIWAF_NATIVE_PIPELINE: _off, ...regularOpts } = rawOpts;
|
|
230
238
|
rawOpts = regularOpts;
|
|
@@ -332,7 +340,14 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
332
340
|
await checksReady;
|
|
333
341
|
const riskFinding = observeRisks ? observeRisks(req) : null;
|
|
334
342
|
if (riskFinding) return riskFinding;
|
|
335
|
-
|
|
343
|
+
await inspectSql.prepare(req);
|
|
344
|
+
let finding = inspectSql(req);
|
|
345
|
+
// The route's saved inputs review the general check's answer: see AIWAF_ROUTE_SCHEMA_MODE.
|
|
346
|
+
if (observeRisks?.review && finding?.status !== 413 && finding?.source !== 'headers') {
|
|
347
|
+
finding = finding?.source === 'path'
|
|
348
|
+
? observeRisks.reviewPath(req, finding, inspectSql.maxBytes)
|
|
349
|
+
: observeRisks.review(req, finding, inspectSql.maxBytes);
|
|
350
|
+
}
|
|
336
351
|
if (finding?.mode === 'monitor') {
|
|
337
352
|
(opts.logger || console).warn?.({ event: 'aiwaf.payload', rule: finding.rule, mode: finding.mode });
|
|
338
353
|
return null;
|
|
@@ -388,6 +403,11 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
388
403
|
markRequestStart(req);
|
|
389
404
|
|
|
390
405
|
const deny = (status, code, reason, country = '') => {
|
|
406
|
+
if (opts.AIWAF_PROFILE === 'monitor') {
|
|
407
|
+
// A dry run: say what would be blocked, and let the request through.
|
|
408
|
+
require('./profiles').wouldBlock(method, path, ip, status, reason || code);
|
|
409
|
+
return next();
|
|
410
|
+
}
|
|
391
411
|
middlewareLogger.markBlocked(res, reason || code, country);
|
|
392
412
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
393
413
|
console.error(`[AIWAF-BLOCK] status=${status} code=${code} reason=${reason} ip=${ip}`);
|
package/lib/wasmAdapter.js
CHANGED
|
@@ -6,8 +6,21 @@ let wasmModule = null;
|
|
|
6
6
|
let wasmLoadAttempted = false;
|
|
7
7
|
let wasmLoadError = null;
|
|
8
8
|
|
|
9
|
+
/**
|
|
10
|
+
* The installed aiwaf-wasm folder, found the way require() finds it, so it works wherever npm
|
|
11
|
+
* put it (in aiwaf's own node_modules or hoisted to the app's), or null when it isn't installed.
|
|
12
|
+
*/
|
|
13
|
+
function wasmPackageDir() {
|
|
14
|
+
try {
|
|
15
|
+
return path.dirname(require.resolve('aiwaf-wasm/package.json'));
|
|
16
|
+
} catch (_) {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
9
21
|
async function loadWasmFromDisk() {
|
|
10
|
-
const pkgDir =
|
|
22
|
+
const pkgDir = wasmPackageDir();
|
|
23
|
+
if (!pkgDir) return null;
|
|
11
24
|
const wasmPath = path.join(pkgDir, 'aiwaf_wasm_bg.wasm');
|
|
12
25
|
const bgPath = path.join(pkgDir, 'aiwaf_wasm_bg.js');
|
|
13
26
|
|
|
@@ -58,7 +71,8 @@ async function loadWasmFromDisk() {
|
|
|
58
71
|
}
|
|
59
72
|
|
|
60
73
|
async function loadWasmFromPackageModule() {
|
|
61
|
-
const pkgDir =
|
|
74
|
+
const pkgDir = wasmPackageDir();
|
|
75
|
+
if (!pkgDir) return null;
|
|
62
76
|
const modulePath = path.join(pkgDir, 'aiwaf_wasm.js');
|
|
63
77
|
if (!fs.existsSync(modulePath)) return null;
|
|
64
78
|
try {
|
|
@@ -596,5 +610,6 @@ module.exports = {
|
|
|
596
610
|
rustPayloadFromRecords,
|
|
597
611
|
pythonFeatureFromRecord,
|
|
598
612
|
pythonFeaturesBatched,
|
|
599
|
-
getWasmStatus
|
|
613
|
+
getWasmStatus,
|
|
614
|
+
wasmPackageDir
|
|
600
615
|
};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// WebSocket messages, checked like request bodies. HTTP checks never see what a WebSocket
|
|
4
|
+
// carries after its handshake, so this checks each message a client sends with the payload
|
|
5
|
+
// check in aiwaf-wasm: SQL injection, remote code execution and their disguises, and JSON
|
|
6
|
+
// messages by their values. A message with a finding closes the socket with 1008 (policy
|
|
7
|
+
// violation), or 1009 when it's too large to check, and never reaches the application's
|
|
8
|
+
// handlers. It follows AIWAF_SQL_INJECTION_MODE: monitor logs the rule and passes the message,
|
|
9
|
+
// off checks nothing. Log events carry the rule and path only, never message content.
|
|
10
|
+
const wasmChecks = require('./wasmChecks');
|
|
11
|
+
const { bodyBytes } = require('./sqlInjection');
|
|
12
|
+
|
|
13
|
+
const EMPTY = new Uint8Array(0);
|
|
14
|
+
|
|
15
|
+
function settings(options = {}) {
|
|
16
|
+
const mode = String(options.AIWAF_SQL_INJECTION_MODE ?? process.env.AIWAF_SQL_INJECTION_MODE ?? 'block').toLowerCase();
|
|
17
|
+
if (!['block', 'monitor', 'off'].includes(mode)) throw new Error('Invalid AIWAF_SQL_INJECTION_MODE');
|
|
18
|
+
const maxBytes = Number(options.AIWAF_PAYLOAD_MAX_BYTES ?? process.env.AIWAF_PAYLOAD_MAX_BYTES ?? 65536);
|
|
19
|
+
if (!Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > 1048576) throw new Error('AIWAF_PAYLOAD_MAX_BYTES must be 1..1048576');
|
|
20
|
+
return { mode, maxBytes, logger: options.logger || console };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// A message as bytes: ws gives a Buffer, an array of Buffers or an ArrayBuffer; socket.io gives
|
|
24
|
+
// event arguments, which are checked as JSON.
|
|
25
|
+
function messageBytes(data) {
|
|
26
|
+
if (Buffer.isBuffer(data) || data instanceof Uint8Array) return data;
|
|
27
|
+
if (Array.isArray(data) && data.every(item => Buffer.isBuffer(item))) return Buffer.concat(data);
|
|
28
|
+
if (data instanceof ArrayBuffer) return Buffer.from(data);
|
|
29
|
+
return bodyBytes(data);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The finding for one message, or null. Await wasmChecks.load() first. Ignores the mode. */
|
|
33
|
+
function inspectMessage(data, options = {}) {
|
|
34
|
+
const { maxBytes } = settings(options);
|
|
35
|
+
const bytes = messageBytes(data);
|
|
36
|
+
if (bytes === null) return { rule: 'payload_inspection_limit', status: 413 };
|
|
37
|
+
return JSON.parse(wasmChecks.get().sql_inspect(EMPTY, bytes, maxBytes));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function report(logger, mode, path, finding) {
|
|
41
|
+
try {
|
|
42
|
+
logger.warn?.({ event: 'aiwaf.websocket', mode, path: String(path || ''), rule: finding.rule });
|
|
43
|
+
} catch (_) { /* Logging must not decide the outcome. */ }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Checks every message clients send to a `ws` WebSocketServer. Resolves once the checks are
|
|
48
|
+
* loaded; messages are checked from then on.
|
|
49
|
+
*/
|
|
50
|
+
async function guardWebSocketServer(wss, options = {}) {
|
|
51
|
+
const config = settings(options);
|
|
52
|
+
if (config.mode === 'off') return wss;
|
|
53
|
+
await wasmChecks.load();
|
|
54
|
+
wss.on('connection', (socket, req) => {
|
|
55
|
+
const path = String(req?.url || '').split('?')[0];
|
|
56
|
+
let closed = false;
|
|
57
|
+
const emit = socket.emit;
|
|
58
|
+
socket.emit = function emitChecked(event, ...args) {
|
|
59
|
+
if (event === 'message') {
|
|
60
|
+
if (closed) return false;
|
|
61
|
+
const finding = inspectMessage(args[0], options);
|
|
62
|
+
if (finding) {
|
|
63
|
+
report(config.logger, config.mode, path, finding);
|
|
64
|
+
if (config.mode === 'block') {
|
|
65
|
+
closed = true;
|
|
66
|
+
socket.close(finding.status === 413 ? 1009 : 1008, 'aiwaf');
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return emit.call(this, event, ...args);
|
|
72
|
+
};
|
|
73
|
+
});
|
|
74
|
+
return wss;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Checks every event clients send to a socket.io server, with per-socket packet middleware. */
|
|
78
|
+
async function guardSocketIo(io, options = {}) {
|
|
79
|
+
const config = settings(options);
|
|
80
|
+
if (config.mode === 'off') return io;
|
|
81
|
+
await wasmChecks.load();
|
|
82
|
+
io.on('connection', socket => {
|
|
83
|
+
const path = String(socket.handshake?.url || '').split('?')[0];
|
|
84
|
+
socket.use(([event, ...args], next) => {
|
|
85
|
+
// The event name and its arguments, except an acknowledgement callback.
|
|
86
|
+
const finding = inspectMessage([event, ...args.filter(item => typeof item !== 'function')], options);
|
|
87
|
+
if (!finding) return next();
|
|
88
|
+
report(config.logger, config.mode, path, finding);
|
|
89
|
+
if (config.mode !== 'block') return next();
|
|
90
|
+
next(new Error(finding.rule));
|
|
91
|
+
socket.disconnect(true);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
return io;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
module.exports = { guardSocketIo, guardWebSocketServer, inspectMessage };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiwaf",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.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,8 +22,11 @@
|
|
|
22
22
|
"scripts": {
|
|
23
23
|
"retrain": "AIWAF_LOG_PATH=/var/log/nginx/access.log npm run train",
|
|
24
24
|
"train": "node train.js",
|
|
25
|
+
"pretest": "node scripts/check-local-wasm.js",
|
|
25
26
|
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBand",
|
|
27
|
+
"pretest:coverage": "node scripts/check-local-wasm.js",
|
|
26
28
|
"test:coverage": "node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBand --coverage",
|
|
29
|
+
"pretest:wasm": "node scripts/check-local-wasm.js",
|
|
27
30
|
"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
31
|
"aiwaf": "node bin/aiwaf.js",
|
|
29
32
|
"test:wasm-real": "node test/wasm-real.js",
|
|
@@ -34,7 +37,7 @@
|
|
|
34
37
|
},
|
|
35
38
|
"dependencies": {
|
|
36
39
|
"@babel/parser": "^7.29.2",
|
|
37
|
-
"aiwaf-wasm": "^0.2.
|
|
40
|
+
"aiwaf-wasm": "^0.2.11",
|
|
38
41
|
"express": "^4.21.2",
|
|
39
42
|
"glob": "^14.0.6",
|
|
40
43
|
"knex": "^2.4.2",
|
|
@@ -55,7 +58,10 @@
|
|
|
55
58
|
"@nestjs/core": "^11.1.18",
|
|
56
59
|
"@nestjs/platform-express": "^11.1.18",
|
|
57
60
|
"reflect-metadata": "^0.2.2",
|
|
58
|
-
"rxjs": "^7.8.1"
|
|
61
|
+
"rxjs": "^7.8.1",
|
|
62
|
+
"ws": "8.22.1",
|
|
63
|
+
"socket.io": "4.8.4",
|
|
64
|
+
"socket.io-client": "4.8.4"
|
|
59
65
|
},
|
|
60
66
|
"optionalDependencies": {
|
|
61
67
|
"maxmind": "^4.3.0"
|
package/utils/db.js
CHANGED
|
@@ -2,10 +2,86 @@ const knex = require('knex');
|
|
|
2
2
|
|
|
3
3
|
const isTest = process.env.NODE_ENV === 'test';
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
// npm 12 no longer runs dependencies' install scripts unless the app allows them, and sqlite3's
|
|
6
|
+
// install script is what fetches or builds its native binary. Without it, sqlite3 can't load.
|
|
7
|
+
// So the database connects on first use rather than when aiwaf is required: when sqlite3 can't
|
|
8
|
+
// load, each use throws SqliteUnavailableError, and the stores fall back to their CSV files.
|
|
9
|
+
const FIX = 'To store data in SQLite instead, run: npm approve-scripts sqlite3 && npm rebuild sqlite3';
|
|
10
|
+
|
|
11
|
+
class SqliteUnavailableError extends Error {
|
|
12
|
+
constructor(cause) {
|
|
13
|
+
super(`AIWAF can't load sqlite3's native binary, so it stores data in CSV files under logs/storage. `
|
|
14
|
+
+ `npm 12 skips install scripts unless they're approved, and sqlite3 needs its install script. ${FIX}`);
|
|
15
|
+
this.name = 'SqliteUnavailableError';
|
|
16
|
+
this.code = 'AIWAF_SQLITE_UNAVAILABLE';
|
|
17
|
+
this.cause = cause;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let instance = null;
|
|
22
|
+
let failure = null;
|
|
23
|
+
let warned = false;
|
|
24
|
+
|
|
25
|
+
function loadDriver() {
|
|
26
|
+
// Required for its side effect: it throws when the native binary is missing.
|
|
27
|
+
// eslint-disable-next-line global-require
|
|
28
|
+
require('sqlite3');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function connect() {
|
|
32
|
+
if (instance) return instance;
|
|
33
|
+
if (failure) throw failure;
|
|
34
|
+
try {
|
|
35
|
+
loadDriver();
|
|
36
|
+
} catch (err) {
|
|
37
|
+
failure = new SqliteUnavailableError(err);
|
|
38
|
+
if (!warned && !isTest) {
|
|
39
|
+
warned = true;
|
|
40
|
+
console.warn(`[aiwaf] ${failure.message}`);
|
|
41
|
+
}
|
|
42
|
+
throw failure;
|
|
43
|
+
}
|
|
44
|
+
instance = knex({
|
|
45
|
+
client: 'sqlite3',
|
|
46
|
+
connection: {
|
|
47
|
+
filename: isTest ? ':memory:' : './aiwaf.sqlite'
|
|
48
|
+
},
|
|
49
|
+
useNullAsDefault: true,
|
|
50
|
+
});
|
|
51
|
+
return instance;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Properties that inspection and module tooling read; answering them must not connect.
|
|
55
|
+
const PASSIVE = new Set(['then', '__esModule', 'default', 'inspect', 'toJSON', 'constructor', 'prototype']);
|
|
56
|
+
|
|
57
|
+
// Calling db('table') runs this function; reading a property goes through the get trap below.
|
|
58
|
+
function aiwafDb(...args) {
|
|
59
|
+
return connect()(...args);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const db = new Proxy(aiwafDb, {
|
|
63
|
+
get(target, prop) {
|
|
64
|
+
if (prop === 'available') return available;
|
|
65
|
+
if (prop === 'SqliteUnavailableError') return SqliteUnavailableError;
|
|
66
|
+
if (typeof prop === 'symbol' || PASSIVE.has(prop)) return Reflect.get(target, prop);
|
|
67
|
+
const conn = connect();
|
|
68
|
+
const value = conn[prop];
|
|
69
|
+
return typeof value === 'function' ? value.bind(conn) : value;
|
|
9
70
|
},
|
|
10
|
-
|
|
11
|
-
});
|
|
71
|
+
has(_target, prop) {
|
|
72
|
+
try { return prop in connect(); } catch (_) { return false; }
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
/** Whether sqlite3 loads. False means the stores use their CSV files. */
|
|
77
|
+
function available() {
|
|
78
|
+
try {
|
|
79
|
+
connect();
|
|
80
|
+
return true;
|
|
81
|
+
} catch (err) {
|
|
82
|
+
if (err instanceof SqliteUnavailableError) return false;
|
|
83
|
+
throw err;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
module.exports = db;
|