aiwaf 1.2.5 → 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 +178 -40
- package/index.js +4 -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/routeRisks.js +76 -11
- package/lib/sqlInjection.js +59 -10
- package/lib/wafMiddleware.js +11 -8
- package/lib/wasmAdapter.js +18 -3
- package/lib/webSocketGuard.js +97 -0
- package/package.json +9 -3
- package/utils/db.js +82 -6
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// What each handler reads from the query and body, with types, for the route manifest. init
|
|
4
|
+
// saves these as each route's inputs (name to int, float, bool, uuid or text) and
|
|
5
|
+
// inputs_complete: true only when every read was understood. Requests are then reviewed against
|
|
6
|
+
// them in aiwaf-wasm: see AIWAF_ROUTE_SCHEMA_MODE.
|
|
7
|
+
//
|
|
8
|
+
// Anything not understood makes the list incomplete rather than guessed: the request passed to a
|
|
9
|
+
// function, req.query or req.body used whole, a key that isn't a constant, the raw body or URL
|
|
10
|
+
// parsed by hand, or route middleware that isn't a body parser.
|
|
11
|
+
|
|
12
|
+
const REQUEST_NAMES = new Set(['req', 'request']);
|
|
13
|
+
const CONTEXT_NAMES = new Set(['ctx', 'context']);
|
|
14
|
+
const CONTAINERS = new Set(['query', 'body']);
|
|
15
|
+
const CONVERTERS = new Map([
|
|
16
|
+
['parseInt', 'int'], ['Number.parseInt', 'int'], ['Number', 'float'], ['parseFloat', 'float'],
|
|
17
|
+
['Number.parseFloat', 'float'], ['Boolean', 'bool']
|
|
18
|
+
]);
|
|
19
|
+
// Request members that read the query string or body some other way.
|
|
20
|
+
const RAW_MEMBERS = new Set(['rawBody', 'read', 'pipe', 'on', 'once', 'body_raw', 'files', 'file']);
|
|
21
|
+
const URL_PARSERS = /^(?:URL|URLSearchParams|url\.parse|querystring\.parse|qs\.parse|parseUrl)$/;
|
|
22
|
+
// Route middleware that only parses or guards: anything else may read the body itself.
|
|
23
|
+
const SAFE_MIDDLEWARE = /^(?:express\.(?:json|urlencoded|text|raw)|bodyParser\.\w+|cors|helmet|compression|multer)\b/;
|
|
24
|
+
const ROUTE_METHODS = new Set(['all', 'delete', 'get', 'head', 'options', 'patch', 'post', 'put']);
|
|
25
|
+
const SKIPPED = new Set(['loc', 'start', 'end', 'extra', 'leadingComments', 'trailingComments', 'innerComments', 'typeAnnotation', 'returnType', 'typeParameters']);
|
|
26
|
+
|
|
27
|
+
function dotted(node) {
|
|
28
|
+
if (!node) return '';
|
|
29
|
+
if (node.type === 'Identifier') return node.name;
|
|
30
|
+
if (node.type === 'ThisExpression') return 'this';
|
|
31
|
+
if ((node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') && !node.computed) {
|
|
32
|
+
const base = dotted(node.object);
|
|
33
|
+
return base ? `${base}.${node.property.name}` : '';
|
|
34
|
+
}
|
|
35
|
+
if (node.type === 'CallExpression' || node.type === 'OptionalCallExpression') return dotted(node.callee);
|
|
36
|
+
if (node.type === 'NewExpression') return dotted(node.callee);
|
|
37
|
+
return '';
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function isMember(node) {
|
|
41
|
+
return node && (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function isCall(node) {
|
|
45
|
+
return node && (node.type === 'CallExpression' || node.type === 'OptionalCallExpression' || node.type === 'NewExpression');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isFunction(node) {
|
|
49
|
+
return node && ['ArrowFunctionExpression', 'FunctionDeclaration', 'FunctionExpression', 'ObjectMethod', 'ClassMethod'].includes(node.type);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function memberKey(node, constants = new Map()) {
|
|
53
|
+
if (!node.computed) return node.property.name;
|
|
54
|
+
if (node.property.type === 'StringLiteral') return node.property.value;
|
|
55
|
+
// A key held in a module-level string constant, as in req.query[PAGE].
|
|
56
|
+
return node.property.type === 'Identifier' && constants.has(node.property.name) ? constants.get(node.property.name) : null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function children(node) {
|
|
60
|
+
const out = [];
|
|
61
|
+
for (const key of Object.keys(node)) {
|
|
62
|
+
if (SKIPPED.has(key)) continue;
|
|
63
|
+
const value = node[key];
|
|
64
|
+
if (Array.isArray(value)) {
|
|
65
|
+
for (const item of value) if (item && typeof item.type === 'string') out.push(item);
|
|
66
|
+
} else if (value && typeof value.type === 'string') {
|
|
67
|
+
out.push(value);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function merge(inputs, name, kind) {
|
|
74
|
+
// A name read as two types, or as text anywhere, is text: the weaker reading wins.
|
|
75
|
+
inputs[name] = inputs[name] === undefined || inputs[name] === kind ? kind : 'text';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// The type a zod field's chain says, as in z.number().int() or z.string().uuid().
|
|
79
|
+
function zodType(source) {
|
|
80
|
+
if (/\.uuid\(/.test(source)) return 'uuid';
|
|
81
|
+
if (/\bboolean\(/.test(source)) return 'bool';
|
|
82
|
+
if (/\bnumber\(/.test(source) || /\bbigint\(/.test(source)) return /\.int\(/.test(source) ? 'int' : 'float';
|
|
83
|
+
return 'text';
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Module-level zod object schemas, as const Body = z.object({ name: z.string() }), by name.
|
|
87
|
+
function zodSchemas(ast, source) {
|
|
88
|
+
const schemas = new Map();
|
|
89
|
+
const visit = node => {
|
|
90
|
+
if (node.type === 'VariableDeclarator' && node.id.type === 'Identifier' && node.init) {
|
|
91
|
+
let call = node.init;
|
|
92
|
+
const text = source.slice(node.init.start, node.init.end);
|
|
93
|
+
while (isCall(call) && isMember(call.callee) && dotted(call.callee) !== 'z.object') call = call.callee.object;
|
|
94
|
+
const object = isCall(call) && dotted(call.callee) === 'z.object' ? call.arguments[0] : null;
|
|
95
|
+
if (object && object.type === 'ObjectExpression') {
|
|
96
|
+
const fields = {};
|
|
97
|
+
let complete = !/\.(?:passthrough|catchall)\(/.test(text.slice(call.end - node.init.start));
|
|
98
|
+
for (const property of object.properties) {
|
|
99
|
+
const key = property.type === 'ObjectProperty' ? (property.key.name || property.key.value) : null;
|
|
100
|
+
if (!key) { complete = false; continue; }
|
|
101
|
+
merge(fields, key, zodType(source.slice(property.value.start, property.value.end)));
|
|
102
|
+
}
|
|
103
|
+
schemas.set(node.id.name, complete ? fields : null);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
for (const child of children(node)) visit(child);
|
|
107
|
+
};
|
|
108
|
+
visit(ast);
|
|
109
|
+
return schemas;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* What one handler reads: { inputs, complete }. scope holds the file's functions, which the
|
|
114
|
+
* request is followed into when passed to one, and its string constants. named, when given, is
|
|
115
|
+
* the parameter that holds the request in a followed function.
|
|
116
|
+
*/
|
|
117
|
+
function handlerInputs(node, schemas, scope = { functions: new Map(), constants: new Map(), active: new Set() }, named = null) {
|
|
118
|
+
const inputs = {};
|
|
119
|
+
let complete = true;
|
|
120
|
+
const requests = new Set();
|
|
121
|
+
const contexts = new Set();
|
|
122
|
+
for (const parameter of node.params || []) {
|
|
123
|
+
const target = parameter.type === 'AssignmentPattern' ? parameter.left : parameter;
|
|
124
|
+
if (named !== null) {
|
|
125
|
+
if (target.type === 'Identifier' && target.name === named) requests.add(target.name);
|
|
126
|
+
} else if (target.type === 'Identifier' && REQUEST_NAMES.has(target.name)) requests.add(target.name);
|
|
127
|
+
else if (target.type === 'Identifier' && CONTEXT_NAMES.has(target.name)) contexts.add(target.name);
|
|
128
|
+
else if (target.type === 'ObjectPattern') complete = false; // ({ body, query }) destructured from the request.
|
|
129
|
+
}
|
|
130
|
+
const follow = (call, item) => {
|
|
131
|
+
// The request passed to a function in this file, as in return render(req, res): its reads count.
|
|
132
|
+
const target = call.callee.type === 'Identifier' ? scope.functions.get(call.callee.name) : null;
|
|
133
|
+
if (!target || scope.active.has(target) || scope.active.size >= 4) return false;
|
|
134
|
+
const index = call.arguments.indexOf(item);
|
|
135
|
+
const parameter = (target.params || [])[index];
|
|
136
|
+
const name = parameter && (parameter.type === 'AssignmentPattern' ? parameter.left : parameter);
|
|
137
|
+
if (!name || name.type !== 'Identifier') return false;
|
|
138
|
+
scope.active.add(target);
|
|
139
|
+
try {
|
|
140
|
+
const found = handlerInputs(target, schemas, scope, name.name);
|
|
141
|
+
for (const [key, kind] of Object.entries(found.inputs)) merge(inputs, key, kind);
|
|
142
|
+
if (!found.complete) complete = false;
|
|
143
|
+
} finally {
|
|
144
|
+
scope.active.delete(target);
|
|
145
|
+
}
|
|
146
|
+
return true;
|
|
147
|
+
};
|
|
148
|
+
const parents = new Map();
|
|
149
|
+
const nodes = [];
|
|
150
|
+
const index = (item, parent) => {
|
|
151
|
+
parents.set(item, parent);
|
|
152
|
+
nodes.push(item);
|
|
153
|
+
for (const child of children(item)) index(child, item);
|
|
154
|
+
};
|
|
155
|
+
// The body only: the parameters themselves aren't uses of the request.
|
|
156
|
+
if (node.body) index(node.body, node);
|
|
157
|
+
const aliases = new Set();
|
|
158
|
+
|
|
159
|
+
const converted = read => {
|
|
160
|
+
let current = read;
|
|
161
|
+
let parent = parents.get(current);
|
|
162
|
+
// Through a default, as in parseInt(req.query.page || '1').
|
|
163
|
+
while (parent && parent.type === 'LogicalExpression' && parent.left === current) {
|
|
164
|
+
current = parent;
|
|
165
|
+
parent = parents.get(current);
|
|
166
|
+
}
|
|
167
|
+
if (isCall(parent) && parent.arguments[0] === current) return CONVERTERS.get(dotted(parent.callee)) || 'text';
|
|
168
|
+
if (parent && parent.type === 'UnaryExpression' && parent.operator === '+') return 'float';
|
|
169
|
+
return 'text';
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
const container = expr => {
|
|
173
|
+
const parent = parents.get(expr);
|
|
174
|
+
if (isMember(parent) && parent.object === expr) {
|
|
175
|
+
const key = memberKey(parent, scope.constants);
|
|
176
|
+
if (key === null) complete = false;
|
|
177
|
+
else merge(inputs, key, converted(parent));
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (parent && parent.type === 'VariableDeclarator' && parent.init === expr) {
|
|
181
|
+
if (parent.id.type === 'Identifier') {
|
|
182
|
+
aliases.add(parent.id.name);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (parent.id.type === 'ObjectPattern') {
|
|
186
|
+
for (const property of parent.id.properties) {
|
|
187
|
+
const key = property.type === 'ObjectProperty' ? (property.key.name || property.key.value) : null;
|
|
188
|
+
if (!key || property.computed) complete = false;
|
|
189
|
+
else merge(inputs, key, 'text');
|
|
190
|
+
}
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (parent && parent.type === 'BinaryExpression' && parent.operator === 'in' && parent.right === expr) return;
|
|
195
|
+
if (isCall(parent) && parent.arguments.includes(expr) && isMember(parent.callee)) {
|
|
196
|
+
// Body.parse(req.body) with a zod object schema from this file.
|
|
197
|
+
const method = parent.callee.property.name;
|
|
198
|
+
const fields = ['parse', 'safeParse', 'parseAsync', 'safeParseAsync'].includes(method)
|
|
199
|
+
? schemas.get(dotted(parent.callee.object)) : undefined;
|
|
200
|
+
if (fields) {
|
|
201
|
+
for (const [key, kind] of Object.entries(fields)) merge(inputs, key, kind);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
complete = false;
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
const isRequest = item => item && item.type === 'Identifier' && requests.has(item.name);
|
|
209
|
+
const isContext = item => item && item.type === 'Identifier' && contexts.has(item.name);
|
|
210
|
+
for (const item of nodes) {
|
|
211
|
+
if (isMember(item) && !item.computed && (isRequest(item.object) || isContext(item.object)
|
|
212
|
+
|| (isMember(item.object) && isContext(item.object.object) && memberKey(item.object) === 'request'))) {
|
|
213
|
+
const name = item.property.name;
|
|
214
|
+
// Koa's ctx.body is the response; its request body is ctx.request.body.
|
|
215
|
+
const response = isContext(item.object) && name === 'body';
|
|
216
|
+
if (response) continue;
|
|
217
|
+
if (CONTAINERS.has(name)) container(item);
|
|
218
|
+
else if (RAW_MEMBERS.has(name)) complete = false;
|
|
219
|
+
else if (name === 'param') {
|
|
220
|
+
const call = parents.get(item);
|
|
221
|
+
const key = isCall(call) && call.arguments[0];
|
|
222
|
+
if (key && key.type === 'StringLiteral') merge(inputs, key.value, converted(call));
|
|
223
|
+
else complete = false;
|
|
224
|
+
} else if (['url', 'originalUrl', 'querystring', 'search', 'href'].includes(name)) {
|
|
225
|
+
// The URL is fine to log or redirect to, but not to read the query from by hand.
|
|
226
|
+
const call = parents.get(item);
|
|
227
|
+
if (isCall(call) && URL_PARSERS.test(dotted(call.callee))) complete = false;
|
|
228
|
+
}
|
|
229
|
+
} else if (item.type === 'Identifier' && (requests.has(item.name) || contexts.has(item.name))) {
|
|
230
|
+
const parent = parents.get(item);
|
|
231
|
+
const declared = parent && (parent.type === 'VariableDeclarator' && parent.id === item);
|
|
232
|
+
if (!(isMember(parent) && parent.object === item) && !declared && !(parent && parent.type === 'ObjectProperty' && parent.key === item)
|
|
233
|
+
&& !(isCall(parent) && parent.arguments.includes(item) && follow(parent, item))) {
|
|
234
|
+
complete = false; // The request goes somewhere that may read it.
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
// What's read from an alias, as const body = req.body, then body.name.
|
|
239
|
+
for (const item of nodes) {
|
|
240
|
+
if (item.type === 'Identifier' && aliases.has(item.name)) {
|
|
241
|
+
const parent = parents.get(item);
|
|
242
|
+
if (parent && parent.type === 'VariableDeclarator' && parent.id === item) continue;
|
|
243
|
+
if (isMember(parent) && parent.property === item && !parent.computed) continue;
|
|
244
|
+
if (parent && parent.type === 'ObjectProperty' && parent.key === item && !parent.computed) continue;
|
|
245
|
+
container(item);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return { inputs, complete };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Each handler's inputs in one parsed file: { function, file, inputs, complete }. label(node,
|
|
253
|
+
* parent) names a handler as the injection audit does, so both link to the same routes.
|
|
254
|
+
*/
|
|
255
|
+
function fileInputs(ast, filename, source, label) {
|
|
256
|
+
const schemas = zodSchemas(ast, source || '');
|
|
257
|
+
// The file's top-level functions and string constants.
|
|
258
|
+
const scope = { functions: new Map(), constants: new Map(), active: new Set() };
|
|
259
|
+
for (const statement of (ast.program || ast).body || []) {
|
|
260
|
+
const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;
|
|
261
|
+
if (!declaration) continue;
|
|
262
|
+
if (declaration.type === 'FunctionDeclaration' && declaration.id) scope.functions.set(declaration.id.name, declaration);
|
|
263
|
+
if (declaration.type === 'VariableDeclaration') {
|
|
264
|
+
for (const item of declaration.declarations) {
|
|
265
|
+
if (item.id.type !== 'Identifier' || !item.init) continue;
|
|
266
|
+
if (isFunction(item.init)) scope.functions.set(item.id.name, item.init);
|
|
267
|
+
if (declaration.kind === 'const' && item.init.type === 'StringLiteral') scope.constants.set(item.id.name, item.init.value);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const results = [];
|
|
272
|
+
const visit = (node, parent) => {
|
|
273
|
+
if (isFunction(node) && (node.params || []).some(parameter => {
|
|
274
|
+
const target = parameter.type === 'AssignmentPattern' ? parameter.left : parameter;
|
|
275
|
+
return target.type === 'Identifier' && (REQUEST_NAMES.has(target.name) || CONTEXT_NAMES.has(target.name));
|
|
276
|
+
})) {
|
|
277
|
+
scope.active.add(node);
|
|
278
|
+
const found = handlerInputs(node, schemas, scope);
|
|
279
|
+
scope.active.delete(node);
|
|
280
|
+
// app.post('/x', auth, handler): middleware before the handler may read the body itself.
|
|
281
|
+
if (isCall(parent) && isMember(parent.callee) && ROUTE_METHODS.has(parent.callee.property.name)) {
|
|
282
|
+
const others = parent.arguments.slice(1).filter(argument => argument !== node);
|
|
283
|
+
if (others.some(argument => !(isCall(argument) && SAFE_MIDDLEWARE.test(dotted(argument.callee))))) found.complete = false;
|
|
284
|
+
}
|
|
285
|
+
results.push({ function: label(node, parent), file: filename, inputs: found.inputs, complete: found.complete });
|
|
286
|
+
}
|
|
287
|
+
for (const child of children(node)) visit(child, node);
|
|
288
|
+
};
|
|
289
|
+
visit(ast.program || ast, null);
|
|
290
|
+
return results;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Adds one handler's inputs to a route; a route served by several takes them all. */
|
|
294
|
+
function mergeInto(routes, path, entry) {
|
|
295
|
+
const data = routes[path];
|
|
296
|
+
data.inputs = data.inputs || {};
|
|
297
|
+
for (const [name, kind] of Object.entries(entry.inputs)) merge(data.inputs, name, kind);
|
|
298
|
+
data.inputs_complete = (data.inputs_complete ?? true) && Boolean(entry.complete);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
module.exports = { fileInputs, handlerInputs, mergeInto };
|
package/lib/nativePipeline.js
CHANGED
|
@@ -6,7 +6,7 @@ const { createRequestPipeline } = require('./wasmAdapter');
|
|
|
6
6
|
const wasmChecks = require('./wasmChecks');
|
|
7
7
|
const routeRisks = require('./routeRisks');
|
|
8
8
|
const { ALL_MIDDLEWARES, createRoutePlan } = require('./pathRules');
|
|
9
|
-
const { getEffectivePathRules } = require('./pathManifest');
|
|
9
|
+
const { getEffectivePathRules, loadManifest } = require('./pathManifest');
|
|
10
10
|
const { getRequestIp } = require('./runtimeUtils');
|
|
11
11
|
|
|
12
12
|
// RATE_LIMIT names accepted in path rules, as in the regular rate limiter.
|
|
@@ -76,11 +76,11 @@ function readRows(file, expected) {
|
|
|
76
76
|
return Object.fromEntries(expected.map((key, index) => [key, cells[index]]));
|
|
77
77
|
});
|
|
78
78
|
}
|
|
79
|
-
// The content types whose bodies are inspected, as in Python.
|
|
80
|
-
// (
|
|
79
|
+
// The content types whose bodies are inspected, as in Python. A multipart form is checked by
|
|
80
|
+
// its first max bytes; other bodies (binary uploads) pass through unread.
|
|
81
81
|
function inspectable(req) {
|
|
82
82
|
const media = String(req.headers?.['content-type'] || '').split(';', 1)[0].trim().toLowerCase();
|
|
83
|
-
return ['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml'].includes(media)
|
|
83
|
+
return ['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml', 'multipart/form-data'].includes(media)
|
|
84
84
|
|| media.endsWith('+json') || media.endsWith('+xml');
|
|
85
85
|
}
|
|
86
86
|
function declaredBody(req) {
|
|
@@ -93,38 +93,16 @@ function readable(req) {
|
|
|
93
93
|
&& typeof req.read === 'function' && typeof req.unshift === 'function' && !req.readableEnded;
|
|
94
94
|
}
|
|
95
95
|
const PEEKED = Symbol('aiwaf.native.peeked-body');
|
|
96
|
-
|
|
97
|
-
// parsers after this adapter still read the whole body. Python's adapters do the same.
|
|
98
|
-
function peekBody(req, limit) {
|
|
99
|
-
return new Promise((resolve, reject) => {
|
|
100
|
-
const chunks = [];
|
|
101
|
-
let size = 0;
|
|
102
|
-
const expected = Number(req.headers?.['content-length']) || null;
|
|
103
|
-
const finish = () => {
|
|
104
|
-
req.removeListener('readable', onReadable);
|
|
105
|
-
req.removeListener('error', onError);
|
|
106
|
-
const prefix = Buffer.concat(chunks);
|
|
107
|
-
if (prefix.length) req.unshift(prefix);
|
|
108
|
-
resolve(prefix);
|
|
109
|
-
};
|
|
110
|
-
const onError = error => { req.removeListener('readable', onReadable); reject(error); };
|
|
111
|
-
function onReadable() {
|
|
112
|
-
let chunk;
|
|
113
|
-
while ((chunk = req.read()) !== null) {
|
|
114
|
-
chunks.push(chunk);
|
|
115
|
-
size += chunk.length;
|
|
116
|
-
if (size > limit || size === expected) return finish();
|
|
117
|
-
}
|
|
118
|
-
// The whole body is buffered: put it back before the stream emits 'end'.
|
|
119
|
-
if (req._readableState?.ended) finish();
|
|
120
|
-
}
|
|
121
|
-
req.on('error', onError);
|
|
122
|
-
req.on('readable', onReadable);
|
|
123
|
-
});
|
|
124
|
-
}
|
|
96
|
+
const { peekBody, isMultipart } = require('./bodyPeek');
|
|
125
97
|
function safeBody(req, limit) {
|
|
126
98
|
const peeked = req[PEEKED];
|
|
127
99
|
if (peeked) {
|
|
100
|
+
// A large upload is checked by its start: its text fields and file headers come first.
|
|
101
|
+
if (isMultipart(req)) {
|
|
102
|
+
// The query is counted twice in the check, as sent and parsed.
|
|
103
|
+
const query = Buffer.byteLength(String(req.originalUrl || req.url || '').split('?').slice(1).join('?'));
|
|
104
|
+
return { body: peeked.subarray(0, Math.max(0, limit - 2 * query)).toString('utf8'), exhausted: false };
|
|
105
|
+
}
|
|
128
106
|
if (peeked.length > limit) return { body: null, exhausted: true };
|
|
129
107
|
const text = peeked.toString('utf8');
|
|
130
108
|
// JSON is parsed here, as a body parser would, so it's checked exactly like a parsed body.
|
|
@@ -280,7 +258,7 @@ function synchronous(callback, req, fallback) {
|
|
|
280
258
|
module.exports = async function createNativeMiddleware(options = {}) {
|
|
281
259
|
if (!options || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Native adapter options must be an object');
|
|
282
260
|
if (options.profile !== undefined && (!options.profile || typeof options.profile !== 'object' || Array.isArray(options.profile))) throw new TypeError('Native profile must be an object');
|
|
283
|
-
const allowed = new Set(['profile', 'dataDir', 'logPath', 'logFsync', 'persistBlocks', 'model', 'countryLookup', 'authenticated', 'routeExists', 'onError', 'pathRules', 'manifestPath', 'injectionRiskMode', 'logger', 'uuidResolver', 'stores', 'storeCacheSeconds', 'storesFallback',
|
|
261
|
+
const allowed = new Set(['profile', 'dataDir', 'logPath', 'logFsync', 'persistBlocks', 'model', 'countryLookup', 'authenticated', 'routeExists', 'onError', 'pathRules', 'manifestPath', 'injectionRiskMode', 'routeSchemaMode', 'logger', 'uuidResolver', 'stores', 'storeCacheSeconds', 'storesFallback',
|
|
284
262
|
'rateCounter', 'rateCounterFallback', 'rateFailureMode', 'trustedProxies', 'modelFile', 'modelLoader', 'regularLog', 'modelGate', 'exact', 'regularAnomaly', 'userAgentVerdict']);
|
|
285
263
|
for (const key of Object.keys(options)) if (!allowed.has(key)) throw new Error(`Unknown native adapter option: ${key}`);
|
|
286
264
|
if (options.uuidResolver != null && typeof options.uuidResolver !== 'function') throw new TypeError('uuidResolver must be a function');
|
|
@@ -406,6 +384,22 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
406
384
|
stores = null;
|
|
407
385
|
} else if (!supported) throw new Error('stores needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
|
|
408
386
|
}
|
|
387
|
+
// The manifest's saved inputs, which the engine reviews payload findings against, as the
|
|
388
|
+
// regular middleware does: see AIWAF_ROUTE_SCHEMA_MODE.
|
|
389
|
+
const schemaMode = String(options.routeSchemaMode ?? process.env.AIWAF_ROUTE_SCHEMA_MODE ?? 'monitor').trim().toLowerCase();
|
|
390
|
+
if (!['enforce', 'monitor', 'off'].includes(schemaMode)) throw new Error('AIWAF_ROUTE_SCHEMA_MODE must be enforce, monitor, or off');
|
|
391
|
+
const manifest = schemaMode === 'off' ? null : loadManifest(manifestPath || undefined);
|
|
392
|
+
if (Object.values((manifest && manifest.routes) || {}).some(entry => entry && entry.inputs && typeof entry.inputs === 'object')) {
|
|
393
|
+
const probe = await createRequestPipeline({});
|
|
394
|
+
const supported = typeof probe.native.supports === 'function' && probe.native.supports('route_schema');
|
|
395
|
+
probe.native.free();
|
|
396
|
+
if (supported) {
|
|
397
|
+
profile.route_schema_mode = schemaMode;
|
|
398
|
+
profile.route_manifest = manifest;
|
|
399
|
+
} else {
|
|
400
|
+
(options.logger || console).warn?.('AIWAF native: route schemas need a newer aiwaf-wasm, so they aren\'t reviewed. Run: npm install aiwaf-wasm@latest');
|
|
401
|
+
}
|
|
402
|
+
}
|
|
409
403
|
// With stores, blocks and learned keywords live in the stores instead of dataDir.
|
|
410
404
|
const persist = !stores && options.persistBlocks !== false;
|
|
411
405
|
if (stores) profile.policy_store = 'host';
|
|
@@ -445,6 +439,13 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
445
439
|
const { native, setModel } = engine;
|
|
446
440
|
const logger = options.logger || console;
|
|
447
441
|
// Monitored SQL findings are logged as the regular middleware logs them, and never block.
|
|
442
|
+
// The engine's route schema review returns its log line with the result.
|
|
443
|
+
const reviewed = result => {
|
|
444
|
+
if (!result || !result.schema) return result;
|
|
445
|
+
try { logger.warn?.(result.schema); } catch (_) { /* Logging must not decide the outcome. */ }
|
|
446
|
+
const { schema, ...rest } = result;
|
|
447
|
+
return rest.rule ? rest : null;
|
|
448
|
+
};
|
|
448
449
|
const monitored = finding => {
|
|
449
450
|
if (finding?.mode !== 'monitor') return finding;
|
|
450
451
|
logger.warn?.({ event: 'aiwaf.payload', rule: finding.rule, mode: 'monitor' });
|
|
@@ -533,15 +534,24 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
533
534
|
const report = error => { if (options.onError) options.onError(error); else console.error('AIWAF native finalization failed:', error.message); };
|
|
534
535
|
// This pipeline takes no general settings, so these two come from the environment. Route
|
|
535
536
|
// checks run in aiwaf-wasm, loaded here so requests can use them straight away.
|
|
536
|
-
const observeRisks = routeRisks.createObserver({ AIWAF_PATH_MANIFEST: manifestPath, AIWAF_INJECTION_RISK_MODE: options.injectionRiskMode
|
|
537
|
-
|
|
537
|
+
const observeRisks = routeRisks.createObserver({ AIWAF_PATH_MANIFEST: manifestPath, AIWAF_INJECTION_RISK_MODE: options.injectionRiskMode,
|
|
538
|
+
AIWAF_ROUTE_SCHEMA_MODE: 'off' });
|
|
539
|
+
// inspect_payload takes no path, so its findings are reviewed here against the route's saved
|
|
540
|
+
// inputs, as the engine reviews its own.
|
|
541
|
+
const schemaObserver = profile.route_schema_mode
|
|
542
|
+
? routeRisks.createObserver({ AIWAF_PATH_MANIFEST: manifestPath, AIWAF_INJECTION_RISK_MODE: 'off',
|
|
543
|
+
AIWAF_ROUTE_SCHEMA_MODE: profile.route_schema_mode, logger })
|
|
544
|
+
: null;
|
|
545
|
+
if (observeRisks || schemaObserver) await wasmChecks.load();
|
|
538
546
|
function payload(req) {
|
|
539
547
|
const b = safeBody(req, maxBytes);
|
|
540
548
|
const query = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
|
|
541
549
|
if (b.exhausted && profile.sql_mode !== 'off') {
|
|
542
550
|
return monitored({ status: 413, rule: 'payload_inspection_limit', mode: profile.sql_mode });
|
|
543
551
|
}
|
|
544
|
-
|
|
552
|
+
let finding = JSON.parse(native.inspect_payload(JSON.stringify([query, b.body, req.query ?? null])));
|
|
553
|
+
if (schemaObserver?.review) finding = schemaObserver.review(req, finding, maxBytes, b.body);
|
|
554
|
+
return monitored(finding);
|
|
545
555
|
}
|
|
546
556
|
// A uuidResolver may be async, so only requests it applies to wait for it.
|
|
547
557
|
const middleware = (req, res, next) => {
|
|
@@ -628,6 +638,7 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
628
638
|
})));
|
|
629
639
|
} catch (error) { return next(error); }
|
|
630
640
|
if (decision.monitor) monitored({ rule: decision.monitor, mode: 'monitor' });
|
|
641
|
+
if (decision.schema) reviewed(decision);
|
|
631
642
|
pending.add(decision.context);
|
|
632
643
|
req[contextKey] = decision.context;
|
|
633
644
|
let done = false;
|
|
@@ -697,8 +708,8 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
697
708
|
middleware.diagnostics = () => JSON.parse(native.diagnostics());
|
|
698
709
|
middleware.inspectBody = (req, body) => {
|
|
699
710
|
const captured = safeBody({body,headers:{}},maxBytes);
|
|
700
|
-
return monitored(JSON.parse(native.inspect_body(req[contextKey], JSON.stringify(captured.body), captured.exhausted,
|
|
701
|
-
!!synchronous(options.authenticated,req,false), Date.now()/1000)));
|
|
711
|
+
return monitored(reviewed(JSON.parse(native.inspect_body(req[contextKey], JSON.stringify(captured.body), captured.exhausted,
|
|
712
|
+
!!synchronous(options.authenticated,req,false), Date.now()/1000))));
|
|
702
713
|
};
|
|
703
714
|
middleware.setModel = setModel;
|
|
704
715
|
middleware.close = () => {
|
package/lib/routeRisks.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
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
12
|
const SINKS = [
|
|
@@ -42,6 +43,18 @@ function inspectRisks(checker, path, query, body) {
|
|
|
42
43
|
|
|
43
44
|
const hasRisks = manifest => Object.values((manifest && manifest.routes) || {})
|
|
44
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
|
+
}
|
|
45
58
|
|
|
46
59
|
/**
|
|
47
60
|
* Returns a function that checks a request, or null when there's nothing to check. The function
|
|
@@ -50,21 +63,28 @@ const hasRisks = manifest => Object.values((manifest && manifest.routes) || {})
|
|
|
50
63
|
function createObserver(options = {}) {
|
|
51
64
|
const mode = String(options.AIWAF_INJECTION_RISK_MODE ?? process.env.AIWAF_INJECTION_RISK_MODE ?? 'block').trim().toLowerCase();
|
|
52
65
|
if (!['block', 'log', 'off'].includes(mode)) throw new Error('AIWAF_INJECTION_RISK_MODE must be block, log, or off');
|
|
53
|
-
|
|
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');
|
|
54
68
|
const manifest = loadManifest(options.AIWAF_PATH_MANIFEST || undefined);
|
|
55
|
-
if (!
|
|
69
|
+
if (!hasInputs(manifest)) schema = 'off';
|
|
70
|
+
if ((mode === 'off' || !hasRisks(manifest)) && schema === 'off') return null;
|
|
56
71
|
let checker = null;
|
|
57
72
|
const logger = options.logger || console;
|
|
58
73
|
// Adapters can inspect twice: before and after the body is parsed.
|
|
59
74
|
const logged = new WeakMap();
|
|
60
|
-
|
|
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;
|
|
61
84
|
let events;
|
|
62
85
|
try {
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
// Compiled on first use, after the middleware has loaded aiwaf-wasm.
|
|
66
|
-
checker = checker || compileRisks(manifest);
|
|
67
|
-
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);
|
|
68
88
|
} catch (_) {
|
|
69
89
|
// A failing check must not break the request. Other protections still apply.
|
|
70
90
|
return null;
|
|
@@ -82,6 +102,38 @@ function createObserver(options = {}) {
|
|
|
82
102
|
}
|
|
83
103
|
return mode === 'block' ? { rule: events[0].rule, status: 403, mode: 'block' } : null;
|
|
84
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;
|
|
85
137
|
}
|
|
86
138
|
|
|
87
139
|
function inputFromSource(source) {
|
|
@@ -130,7 +182,13 @@ function routesFor(finding, routes) {
|
|
|
130
182
|
function applyReport(report, manifest) {
|
|
131
183
|
const routes = manifest && manifest.routes;
|
|
132
184
|
if (!routes || typeof routes !== 'object' || Array.isArray(routes)) throw new Error('The manifest has no routes');
|
|
133
|
-
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
|
+
}
|
|
134
192
|
let linked = 0;
|
|
135
193
|
let unlinked = 0;
|
|
136
194
|
const collected = new Map();
|
|
@@ -147,13 +205,19 @@ function applyReport(report, manifest) {
|
|
|
147
205
|
for (const [path, risks] of collected) {
|
|
148
206
|
routes[path].injection_risks = [...risks.keys()].sort().map(key => risks.get(key));
|
|
149
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;
|
|
150
213
|
manifest.injection_audit = {
|
|
151
214
|
generated_at: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
|
|
152
215
|
files_scanned: Number(report.files_scanned || 0),
|
|
153
216
|
linked_findings: linked,
|
|
154
|
-
unlinked_findings: unlinked
|
|
217
|
+
unlinked_findings: unlinked,
|
|
218
|
+
routes_with_inputs: typed
|
|
155
219
|
};
|
|
156
|
-
return { routes: collected.size, linked, unlinked };
|
|
220
|
+
return { routes: collected.size, linked, unlinked, inputs: typed };
|
|
157
221
|
}
|
|
158
222
|
|
|
159
223
|
function updateManifest(report, manifestPath) {
|
|
@@ -179,6 +243,7 @@ module.exports = {
|
|
|
179
243
|
formatCounts,
|
|
180
244
|
inputFromSource,
|
|
181
245
|
inspectRisks,
|
|
246
|
+
reviewRequest,
|
|
182
247
|
ruleFor,
|
|
183
248
|
updateManifest
|
|
184
249
|
};
|