aiwaf 1.1.5 → 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.
- package/README.md +191 -31
- package/bin/aiwaf.js +23 -4
- package/lib/geoBlocker.js +1 -7
- package/lib/injectionAnalysis.js +600 -0
- package/lib/nativePipeline.js +13 -0
- package/lib/pathManifest.js +17 -1
- package/lib/routeRisks.js +181 -0
- package/lib/runtimeUtils.js +201 -6
- package/lib/settingsCompat.js +2 -0
- package/lib/sqlInjection.js +55 -49
- package/lib/wafMiddleware.js +14 -4
- package/lib/wasmAdapter.js +8 -1
- package/lib/wasmChecks.js +40 -0
- package/package.json +6 -41
|
@@ -0,0 +1,600 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Static analysis that follows request input to dangerous operations.
|
|
4
|
+
// It reads source files only, and never runs application code or affects request handling.
|
|
5
|
+
// A clean report doesn't prove code is safe: input that crosses modules or dynamic calls can be missed.
|
|
6
|
+
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const parser = require('@babel/parser');
|
|
10
|
+
|
|
11
|
+
const SCHEMA_VERSION = '1.0';
|
|
12
|
+
const SKIPPED_DIRECTORIES = new Set(['.git', '.next', '.nuxt', 'build', 'coverage', 'dist', 'node_modules', 'out', 'vendor']);
|
|
13
|
+
const TEST_DIRECTORIES = new Set(['__tests__', 'test', 'tests']);
|
|
14
|
+
const SOURCE_EXTENSIONS = new Set(['.cjs', '.cts', '.js', '.jsx', '.mjs', '.mts', '.ts', '.tsx']);
|
|
15
|
+
const MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
16
|
+
const MAX_HELPER_DEPTH = 3;
|
|
17
|
+
|
|
18
|
+
// Express, Next.js, Sails, Fastify, Hapi and NestJS use req or request; Koa and Adonis use ctx.
|
|
19
|
+
const REQUEST_NAMES = new Set(['req', 'request']);
|
|
20
|
+
const CONTEXT_NAMES = new Set(['ctx', 'context']);
|
|
21
|
+
const REQUEST_PROPERTIES = new Set([
|
|
22
|
+
'body', 'cookies', 'files', 'file', 'headers', 'hostname', 'originalUrl', 'params', 'path', 'payload', 'query',
|
|
23
|
+
'querystring', 'raw', 'rawBody', 'state', 'url'
|
|
24
|
+
]);
|
|
25
|
+
const CONTEXT_PROPERTIES = new Set(['body', 'cookies', 'headers', 'params', 'path', 'query', 'querystring', 'request', 'url']);
|
|
26
|
+
const REQUEST_METHODS = new Set(['all', 'allParams', 'body', 'cookie', 'file', 'get', 'header', 'input', 'only', 'param', 'params', 'qs', 'raw']);
|
|
27
|
+
const NEST_INPUT_DECORATORS = new Set(['Body', 'Cookies', 'Headers', 'Param', 'Query', 'UploadedFile', 'UploadedFiles']);
|
|
28
|
+
const SANITIZERS = new Set(['Boolean', 'Number', 'encodeURIComponent', 'escape', 'isNaN', 'parseFloat', 'parseInt', 'path.basename', 'shellescape', 'validator.escape', 'sqlstring.escape', 'mysql.escape']);
|
|
29
|
+
const PASSTHROUGH_METHODS = new Set([
|
|
30
|
+
'concat', 'join', 'padEnd', 'padStart', 'replace', 'replaceAll', 'slice', 'split', 'substring', 'toLowerCase',
|
|
31
|
+
'toString', 'toUpperCase', 'trim', 'trimEnd', 'trimStart'
|
|
32
|
+
]);
|
|
33
|
+
const PASSTHROUGH_FUNCTIONS = new Set(['Array.from', 'Buffer.from', 'JSON.parse', 'JSON.stringify', 'Object.assign', 'String', 'decodeURIComponent', 'path.join', 'path.normalize', 'path.resolve']);
|
|
34
|
+
const SQL_METHODS = new Set(['$executeRawUnsafe', '$queryRawUnsafe', 'execute', 'havingRaw', 'orderByRaw', 'query', 'raw', 'whereRaw']);
|
|
35
|
+
const SQLITE_METHODS = new Set(['all', 'each', 'exec', 'get', 'prepare', 'run']);
|
|
36
|
+
const SQLITE_RECEIVER = /(^|\.)(db|sqlite|database)$/i;
|
|
37
|
+
const NOSQL_METHODS = new Set(['aggregate', 'count', 'countDocuments', 'deleteMany', 'deleteOne', 'find', 'findOne', 'findOneAndDelete', 'findOneAndUpdate', 'updateMany', 'updateOne']);
|
|
38
|
+
const NOSQL_RECEIVER = /(coll|db|mongo|model|users?$|^[A-Z])/;
|
|
39
|
+
const COMMAND_FUNCTIONS = new Set(['child_process.exec', 'child_process.execSync', 'cp.exec', 'cp.execSync', 'exec', 'execSync']);
|
|
40
|
+
const SHELL_FUNCTIONS = new Set(['child_process.spawn', 'child_process.spawnSync', 'cp.spawn', 'cp.spawnSync', 'spawn', 'spawnSync']);
|
|
41
|
+
const PATH_METHODS = new Set([
|
|
42
|
+
'appendFile', 'appendFileSync', 'createReadStream', 'createWriteStream', 'readFile', 'readFileSync', 'readdir',
|
|
43
|
+
'readdirSync', 'rm', 'rmSync', 'unlink', 'unlinkSync', 'writeFile', 'writeFileSync'
|
|
44
|
+
]);
|
|
45
|
+
const FS_RECEIVER = /(^|\.)(fs|fsp|promises)$/;
|
|
46
|
+
const RESPONSE_PATH_METHODS = new Set(['download', 'sendFile']);
|
|
47
|
+
const SSRF_FUNCTIONS = new Set([
|
|
48
|
+
'axios', 'axios.delete', 'axios.get', 'axios.head', 'axios.patch', 'axios.post', 'axios.put', 'axios.request', 'fetch', 'got',
|
|
49
|
+
'got.get', 'got.post', 'http.get', 'http.request', 'https.get', 'https.request', 'needle', 'superagent.get', 'superagent.post',
|
|
50
|
+
'undici.fetch', 'undici.request'
|
|
51
|
+
]);
|
|
52
|
+
const CODE_FUNCTIONS = new Set(['eval', 'setImmediate.call', 'vm.compileFunction', 'vm.runInContext', 'vm.runInNewContext', 'vm.runInThisContext']);
|
|
53
|
+
const TEMPLATE_FUNCTIONS = new Set(['Handlebars.compile', 'dot.template', 'ejs.compile', 'ejs.render', 'handlebars.compile', 'lodash.template', 'nunjucks.renderString', 'pug.compile', 'pug.render', '_.template']);
|
|
54
|
+
const DESERIALIZE_FUNCTIONS = new Set(['serialize.unserialize', 'nodeSerialize.unserialize', 'funcster.deepDeserialize']);
|
|
55
|
+
|
|
56
|
+
function dottedName(node) {
|
|
57
|
+
if (!node) return '';
|
|
58
|
+
if (node.type === 'Identifier') return node.name;
|
|
59
|
+
if (node.type === 'ThisExpression') return 'this';
|
|
60
|
+
if (node.type === 'Super') return 'super';
|
|
61
|
+
if (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') {
|
|
62
|
+
const object = dottedName(node.object);
|
|
63
|
+
const property = !node.computed && node.property.type === 'Identifier' ? node.property.name : '';
|
|
64
|
+
return object && property ? `${object}.${property}` : '';
|
|
65
|
+
}
|
|
66
|
+
if (node.type === 'CallExpression' || node.type === 'OptionalCallExpression') return dottedName(node.callee);
|
|
67
|
+
if (node.type === 'AwaitExpression') return dottedName(node.argument);
|
|
68
|
+
return '';
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function propertyName(node) {
|
|
72
|
+
if (!node) return '';
|
|
73
|
+
if (!node.computed && node.property && node.property.type === 'Identifier') return node.property.name;
|
|
74
|
+
return '';
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Adds a parameter name to a whole-container source, as in req.query.id.
|
|
78
|
+
function withKey(source, key) {
|
|
79
|
+
if (!source || !key || !/(?:\.|^request )(?:body|params|payload|query)$/.test(source)) return source;
|
|
80
|
+
return `${source}.${key}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function isFunction(node) {
|
|
84
|
+
return Boolean(node) && [
|
|
85
|
+
'ArrowFunctionExpression', 'ClassMethod', 'ClassPrivateMethod', 'FunctionDeclaration', 'FunctionExpression', 'ObjectMethod'
|
|
86
|
+
].includes(node.type);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function eachChild(node, visit) {
|
|
90
|
+
for (const key of Object.keys(node)) {
|
|
91
|
+
if (['loc', 'start', 'end', 'extra', 'leadingComments', 'trailingComments', 'innerComments', 'typeAnnotation', 'returnType', 'typeParameters'].includes(key)) continue;
|
|
92
|
+
const value = node[key];
|
|
93
|
+
if (Array.isArray(value)) {
|
|
94
|
+
for (const item of value) if (item && typeof item.type === 'string') visit(item);
|
|
95
|
+
} else if (value && typeof value.type === 'string') {
|
|
96
|
+
visit(value);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function functionName(node, parent) {
|
|
102
|
+
if (node.id && node.id.name) return node.id.name;
|
|
103
|
+
if (node.key) return node.key.name || node.key.value || '<anonymous>';
|
|
104
|
+
if (parent && parent.type === 'VariableDeclarator' && parent.id.name) return parent.id.name;
|
|
105
|
+
if (parent && (parent.type === 'CallExpression' || parent.type === 'OptionalCallExpression')) {
|
|
106
|
+
const route = parent.arguments[0];
|
|
107
|
+
const label = dottedName(parent.callee);
|
|
108
|
+
return route && route.type === 'StringLiteral' ? `${label} ${route.value}` : (label || '<anonymous>');
|
|
109
|
+
}
|
|
110
|
+
if (parent && parent.type === 'ExportDefaultDeclaration') return 'default';
|
|
111
|
+
return '<anonymous>';
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
class FileAnalyzer {
|
|
115
|
+
constructor(ast, filename) {
|
|
116
|
+
this.ast = ast;
|
|
117
|
+
this.filename = filename;
|
|
118
|
+
this.findings = new Map();
|
|
119
|
+
this.functions = new Map();
|
|
120
|
+
this.routeLabels = new WeakMap();
|
|
121
|
+
this.collectFunctions(ast);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
collectFunctions(root) {
|
|
125
|
+
const visit = (node, parent) => {
|
|
126
|
+
if (node.type === 'ObjectExpression') this.collectRouteLabel(node);
|
|
127
|
+
if (isFunction(node)) {
|
|
128
|
+
const name = functionName(node, parent);
|
|
129
|
+
if (name && name !== '<anonymous>' && !this.functions.has(name)) this.functions.set(name, node);
|
|
130
|
+
}
|
|
131
|
+
eachChild(node, child => visit(child, node));
|
|
132
|
+
};
|
|
133
|
+
visit(root, null);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
collectRouteLabel(node) {
|
|
137
|
+
const value = name => node.properties.find(item => item.key && (item.key.name || item.key.value) === name);
|
|
138
|
+
const route = value('path');
|
|
139
|
+
const handler = value('handler');
|
|
140
|
+
if (route && handler && route.value.type === 'StringLiteral' && handler.value && isFunction(handler.value)) {
|
|
141
|
+
this.routeLabels.set(handler.value, `route ${route.value.value}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
run() {
|
|
146
|
+
const visit = (node, parent, inherited) => {
|
|
147
|
+
if (isFunction(node)) {
|
|
148
|
+
const scope = this.initialScope(node, inherited);
|
|
149
|
+
if (scope.tainted.size || scope.requests.size || scope.contexts.size) {
|
|
150
|
+
this.analyze(node, scope, this.routeLabels.get(node) || functionName(node, parent), 0, new Set());
|
|
151
|
+
}
|
|
152
|
+
// Nested functions are handled while analyzing the function that contains them.
|
|
153
|
+
if (scope.tainted.size || scope.requests.size || scope.contexts.size) return;
|
|
154
|
+
}
|
|
155
|
+
eachChild(node, child => visit(child, node, inherited));
|
|
156
|
+
};
|
|
157
|
+
visit(this.ast, null, null);
|
|
158
|
+
return [...this.findings.values()];
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
initialScope(node, inherited) {
|
|
162
|
+
const scope = {
|
|
163
|
+
tainted: new Map(inherited ? inherited.tainted : []),
|
|
164
|
+
requests: new Set(inherited ? inherited.requests : []),
|
|
165
|
+
contexts: new Set(inherited ? inherited.contexts : [])
|
|
166
|
+
};
|
|
167
|
+
for (const parameter of node.params || []) this.addParameter(parameter, scope);
|
|
168
|
+
return scope;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
addParameter(parameter, scope) {
|
|
172
|
+
let target = parameter;
|
|
173
|
+
if (target.type === 'TSParameterProperty') target = target.parameter;
|
|
174
|
+
if (target.type === 'AssignmentPattern') target = target.left;
|
|
175
|
+
const decorators = parameter.decorators || target.decorators || [];
|
|
176
|
+
const decorator = decorators.find(item => NEST_INPUT_DECORATORS.has(dottedName(item.expression)));
|
|
177
|
+
if (decorator && target.type === 'Identifier') {
|
|
178
|
+
const key = decorator.expression.arguments && decorator.expression.arguments[0];
|
|
179
|
+
const nest = dottedName(decorator.expression);
|
|
180
|
+
scope.tainted.set(target.name, key && key.type === 'StringLiteral' ? `@${nest} ${key.value}` : `@${nest}`);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (target.type === 'Identifier') {
|
|
184
|
+
if (REQUEST_NAMES.has(target.name)) scope.requests.add(target.name);
|
|
185
|
+
if (CONTEXT_NAMES.has(target.name)) scope.contexts.add(target.name);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
if (target.type === 'ObjectPattern') {
|
|
189
|
+
// Adonis and some Next.js handlers destructure, as in ({ request, params }).
|
|
190
|
+
for (const property of target.properties) {
|
|
191
|
+
if (property.type !== 'ObjectProperty') continue;
|
|
192
|
+
const key = property.key.name || property.key.value;
|
|
193
|
+
const value = property.value.type === 'AssignmentPattern' ? property.value.left : property.value;
|
|
194
|
+
if (value.type !== 'Identifier') continue;
|
|
195
|
+
if (key === 'request' || key === 'req') scope.requests.add(value.name);
|
|
196
|
+
else if (['body', 'params', 'query', 'headers', 'cookies', 'payload'].includes(key)) {
|
|
197
|
+
scope.tainted.set(value.name, `request ${key}`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
analyze(node, scope, label, depth, active) {
|
|
204
|
+
const key = node.start;
|
|
205
|
+
if (active.has(key) || depth > MAX_HELPER_DEPTH) return;
|
|
206
|
+
const next = new Set(active);
|
|
207
|
+
next.add(key);
|
|
208
|
+
const walker = new FunctionWalker(this, scope, label, depth, next);
|
|
209
|
+
if (node.body.type === 'BlockStatement') walker.visit(node.body, 0);
|
|
210
|
+
else {
|
|
211
|
+
walker.visit(node.body, 0);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
record(node, label, sink, call, source, confidence) {
|
|
216
|
+
const line = node.loc ? node.loc.start.line : 0;
|
|
217
|
+
const key = `${line}:${sink}:${call}`;
|
|
218
|
+
if (!this.findings.has(key)) {
|
|
219
|
+
this.findings.set(key, { file: this.filename, line, function: label, sink, call, source, confidence });
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
class FunctionWalker {
|
|
225
|
+
constructor(file, scope, label, depth, active) {
|
|
226
|
+
this.file = file;
|
|
227
|
+
this.scope = scope;
|
|
228
|
+
this.label = label;
|
|
229
|
+
this.depth = depth;
|
|
230
|
+
this.active = active;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
visit(node, nesting) {
|
|
234
|
+
if (!node || typeof node.type !== 'string') return;
|
|
235
|
+
switch (node.type) {
|
|
236
|
+
case 'VariableDeclarator':
|
|
237
|
+
if (node.init) this.visit(node.init, nesting);
|
|
238
|
+
this.bind(node.id, node.init ? this.taint(node.init) : null, nesting, node.init);
|
|
239
|
+
return;
|
|
240
|
+
case 'AssignmentExpression':
|
|
241
|
+
this.visit(node.right, nesting);
|
|
242
|
+
if (node.operator === '=') this.bind(node.left, this.taint(node.right), nesting, node.right);
|
|
243
|
+
else {
|
|
244
|
+
const source = this.taint(node.right);
|
|
245
|
+
if (source) this.bind(node.left, source, nesting, node.right);
|
|
246
|
+
}
|
|
247
|
+
return;
|
|
248
|
+
case 'CallExpression':
|
|
249
|
+
case 'OptionalCallExpression':
|
|
250
|
+
case 'NewExpression':
|
|
251
|
+
this.checkCall(node);
|
|
252
|
+
this.followHelper(node);
|
|
253
|
+
eachChild(node, child => this.visit(child, nesting));
|
|
254
|
+
return;
|
|
255
|
+
case 'TaggedTemplateExpression':
|
|
256
|
+
eachChild(node, child => this.visit(child, nesting));
|
|
257
|
+
return;
|
|
258
|
+
case 'ForOfStatement':
|
|
259
|
+
case 'ForInStatement': {
|
|
260
|
+
const source = this.taint(node.right);
|
|
261
|
+
const target = node.left.type === 'VariableDeclaration' ? node.left.declarations[0].id : node.left;
|
|
262
|
+
if (source) this.bind(target, source, nesting + 1, node.right);
|
|
263
|
+
this.visit(node.right, nesting);
|
|
264
|
+
this.visit(node.body, nesting + 1);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
case 'IfStatement':
|
|
268
|
+
case 'WhileStatement':
|
|
269
|
+
case 'DoWhileStatement':
|
|
270
|
+
case 'ForStatement':
|
|
271
|
+
case 'SwitchStatement':
|
|
272
|
+
case 'TryStatement':
|
|
273
|
+
case 'ConditionalExpression':
|
|
274
|
+
eachChild(node, child => this.visit(child, nesting + 1));
|
|
275
|
+
return;
|
|
276
|
+
default:
|
|
277
|
+
if (isFunction(node)) {
|
|
278
|
+
// Callbacks keep the request and values from the enclosing handler.
|
|
279
|
+
const nested = this.file.initialScope(node, this.scope);
|
|
280
|
+
const walker = new FunctionWalker(this.file, nested, this.label, this.depth, this.active);
|
|
281
|
+
walker.visit(node.body, 0);
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
eachChild(node, child => this.visit(child, nesting));
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
bind(target, source, nesting, value) {
|
|
289
|
+
if (!target) return;
|
|
290
|
+
if (target.type === 'Identifier') {
|
|
291
|
+
if (source) this.scope.tainted.set(target.name, source);
|
|
292
|
+
else if (nesting === 0) this.scope.tainted.delete(target.name);
|
|
293
|
+
if (value && CONTEXT_NAMES.size && dottedName(value)) {
|
|
294
|
+
const name = dottedName(value);
|
|
295
|
+
if (this.scope.contexts.has(name.split('.')[0]) && name.endsWith('.request')) this.scope.requests.add(target.name);
|
|
296
|
+
}
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
if (target.type === 'ObjectPattern') {
|
|
300
|
+
for (const property of target.properties) {
|
|
301
|
+
if (property.type === 'RestElement') this.bind(property.argument, source, nesting);
|
|
302
|
+
else if (property.type === 'ObjectProperty') {
|
|
303
|
+
const inner = property.value.type === 'AssignmentPattern' ? property.value.left : property.value;
|
|
304
|
+
if (source) this.bind(inner, withKey(source, property.key.name || property.key.value), nesting);
|
|
305
|
+
else if (value && value.type === 'Identifier' && (this.scope.contexts.has(value.name) || this.scope.requests.has(value.name))) {
|
|
306
|
+
const key = property.key.name || property.key.value;
|
|
307
|
+
if (key === 'request' && inner.type === 'Identifier') this.scope.requests.add(inner.name);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
if (target.type === 'ArrayPattern') {
|
|
314
|
+
for (const element of target.elements) if (element) this.bind(element, source, nesting);
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
if (target.type === 'AssignmentPattern') {
|
|
318
|
+
this.bind(target.left, source, nesting);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
if ((target.type === 'MemberExpression' || target.type === 'OptionalMemberExpression') && source) {
|
|
322
|
+
const name = dottedName(target.object);
|
|
323
|
+
if (name) this.scope.tainted.set(name.split('.')[0], source);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
taint(node) {
|
|
328
|
+
if (!node) return null;
|
|
329
|
+
switch (node.type) {
|
|
330
|
+
case 'Identifier':
|
|
331
|
+
return this.scope.tainted.get(node.name) || null;
|
|
332
|
+
case 'MemberExpression':
|
|
333
|
+
case 'OptionalMemberExpression': {
|
|
334
|
+
const source = this.requestProperty(node);
|
|
335
|
+
if (source) return source;
|
|
336
|
+
return withKey(this.taint(node.object), propertyName(node));
|
|
337
|
+
}
|
|
338
|
+
case 'TemplateLiteral':
|
|
339
|
+
return this.first(node.expressions);
|
|
340
|
+
case 'BinaryExpression':
|
|
341
|
+
return node.operator === '+' ? this.taint(node.left) || this.taint(node.right) : null;
|
|
342
|
+
case 'LogicalExpression':
|
|
343
|
+
return this.taint(node.left) || this.taint(node.right);
|
|
344
|
+
case 'ConditionalExpression':
|
|
345
|
+
return this.taint(node.consequent) || this.taint(node.alternate);
|
|
346
|
+
case 'AwaitExpression':
|
|
347
|
+
return this.taint(node.argument);
|
|
348
|
+
case 'TSAsExpression':
|
|
349
|
+
case 'TSNonNullExpression':
|
|
350
|
+
case 'TSSatisfiesExpression':
|
|
351
|
+
case 'ParenthesizedExpression':
|
|
352
|
+
return this.taint(node.expression);
|
|
353
|
+
case 'SpreadElement':
|
|
354
|
+
return this.taint(node.argument);
|
|
355
|
+
case 'ArrayExpression':
|
|
356
|
+
return this.first(node.elements);
|
|
357
|
+
case 'ObjectExpression':
|
|
358
|
+
return this.first(node.properties.map(property => property.value || property.argument));
|
|
359
|
+
case 'CallExpression':
|
|
360
|
+
case 'OptionalCallExpression':
|
|
361
|
+
return this.callTaint(node);
|
|
362
|
+
case 'NewExpression':
|
|
363
|
+
return dottedName(node.callee) === 'String' || dottedName(node.callee) === 'URL' ? this.first(node.arguments) : null;
|
|
364
|
+
default:
|
|
365
|
+
return null;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
requestProperty(node) {
|
|
370
|
+
const name = dottedName(node.object);
|
|
371
|
+
const property = propertyName(node);
|
|
372
|
+
if (!name || !property) return null;
|
|
373
|
+
if (this.scope.requests.has(name) && REQUEST_PROPERTIES.has(property)) return `${name}.${property}`;
|
|
374
|
+
if (this.scope.contexts.has(name) && CONTEXT_PROPERTIES.has(property) && property !== 'request') return `${name}.${property}`;
|
|
375
|
+
const parts = name.split('.');
|
|
376
|
+
if (parts.length === 2 && this.scope.contexts.has(parts[0]) && parts[1] === 'request' && REQUEST_PROPERTIES.has(property)) {
|
|
377
|
+
return `${name}.${property}`;
|
|
378
|
+
}
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
first(nodes) {
|
|
383
|
+
for (const node of nodes) {
|
|
384
|
+
const source = this.taint(node);
|
|
385
|
+
if (source) return source;
|
|
386
|
+
}
|
|
387
|
+
return null;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
callTaint(node) {
|
|
391
|
+
const name = dottedName(node.callee);
|
|
392
|
+
if (SANITIZERS.has(name)) return null;
|
|
393
|
+
if (PASSTHROUGH_FUNCTIONS.has(name)) return this.first(node.arguments);
|
|
394
|
+
if (node.callee.type === 'MemberExpression' || node.callee.type === 'OptionalMemberExpression') {
|
|
395
|
+
const receiver = dottedName(node.callee.object);
|
|
396
|
+
const method = propertyName(node.callee);
|
|
397
|
+
const parts = receiver.split('.');
|
|
398
|
+
const isRequest = this.scope.requests.has(receiver)
|
|
399
|
+
|| (parts.length === 2 && this.scope.contexts.has(parts[0]) && parts[1] === 'request');
|
|
400
|
+
if (isRequest && REQUEST_METHODS.has(method)) {
|
|
401
|
+
const key = node.arguments[0];
|
|
402
|
+
return key && key.type === 'StringLiteral' ? `${receiver}.${method}('${key.value}')` : `${receiver}.${method}()`;
|
|
403
|
+
}
|
|
404
|
+
if (PASSTHROUGH_METHODS.has(method)) {
|
|
405
|
+
return this.taint(node.callee.object) || (method === 'concat' || method === 'replace' || method === 'join' ? this.first(node.arguments) : null);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return null;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
followHelper(node) {
|
|
412
|
+
if (this.depth >= MAX_HELPER_DEPTH || node.type === 'NewExpression') return;
|
|
413
|
+
const name = dottedName(node.callee).split('.').pop();
|
|
414
|
+
const helper = name && this.file.functions.get(name);
|
|
415
|
+
if (!helper) return;
|
|
416
|
+
const passed = new Map();
|
|
417
|
+
(helper.params || []).forEach((parameter, index) => {
|
|
418
|
+
const source = this.taint(node.arguments[index]);
|
|
419
|
+
if (source && parameter.type === 'Identifier') passed.set(parameter.name, source);
|
|
420
|
+
});
|
|
421
|
+
if (!passed.size) return;
|
|
422
|
+
const scope = { tainted: passed, requests: new Set(), contexts: new Set() };
|
|
423
|
+
this.file.analyze(helper, scope, `${this.label} -> ${name}`, this.depth + 1, this.active);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
checkCall(node) {
|
|
427
|
+
const name = dottedName(node.callee);
|
|
428
|
+
const method = node.callee.type === 'MemberExpression' || node.callee.type === 'OptionalMemberExpression'
|
|
429
|
+
? propertyName(node.callee) : '';
|
|
430
|
+
const receiver = method ? dottedName(node.callee.object) : '';
|
|
431
|
+
const first = node.arguments[0];
|
|
432
|
+
const source = this.taint(first);
|
|
433
|
+
|
|
434
|
+
if (node.type === 'NewExpression') {
|
|
435
|
+
if (name === 'Function') {
|
|
436
|
+
const code = this.first(node.arguments);
|
|
437
|
+
if (code) this.report(node, 'code', 'new Function', code, 'high');
|
|
438
|
+
}
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
if (!source) {
|
|
442
|
+
if (SHELL_FUNCTIONS.has(name) && this.spawnUsesShell(node)) {
|
|
443
|
+
const value = this.first(node.arguments.slice(0, 2));
|
|
444
|
+
if (value) this.report(node, 'command', name, value, 'high');
|
|
445
|
+
}
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
if (method && SQL_METHODS.has(method) && !this.isRequestLike(receiver)) {
|
|
449
|
+
this.report(node, 'sql', name || method, source, 'high');
|
|
450
|
+
} else if (method && SQLITE_METHODS.has(method) && SQLITE_RECEIVER.test(receiver)) {
|
|
451
|
+
this.report(node, 'sql', name, source, 'high');
|
|
452
|
+
} else if (method && NOSQL_METHODS.has(method) && NOSQL_RECEIVER.test(receiver) && !this.isFunctionNode(first)) {
|
|
453
|
+
this.report(node, 'nosql', name, source, 'medium');
|
|
454
|
+
} else if (COMMAND_FUNCTIONS.has(name)) {
|
|
455
|
+
this.report(node, 'command', name, source, 'high');
|
|
456
|
+
} else if (SHELL_FUNCTIONS.has(name)) {
|
|
457
|
+
if (this.spawnUsesShell(node)) this.report(node, 'command', name, source, 'high');
|
|
458
|
+
} else if ((method && PATH_METHODS.has(method) && FS_RECEIVER.test(receiver)) || PATH_METHODS.has(name)) {
|
|
459
|
+
this.report(node, 'path', name, source, 'medium');
|
|
460
|
+
} else if (method && RESPONSE_PATH_METHODS.has(method)) {
|
|
461
|
+
this.report(node, 'path', name, source, 'medium');
|
|
462
|
+
} else if (SSRF_FUNCTIONS.has(name)) {
|
|
463
|
+
this.report(node, 'ssrf', name, source, 'medium');
|
|
464
|
+
} else if (CODE_FUNCTIONS.has(name)) {
|
|
465
|
+
this.report(node, 'code', name, source, 'high');
|
|
466
|
+
} else if (TEMPLATE_FUNCTIONS.has(name)) {
|
|
467
|
+
this.report(node, 'template', name, source, 'high');
|
|
468
|
+
} else if (DESERIALIZE_FUNCTIONS.has(name)) {
|
|
469
|
+
this.report(node, 'deserialization', name, source, 'high');
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
isRequestLike(receiver) {
|
|
474
|
+
const head = receiver.split('.')[0];
|
|
475
|
+
return this.scope.requests.has(head) || this.scope.contexts.has(head);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
isFunctionNode(node) {
|
|
479
|
+
return isFunction(node);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
spawnUsesShell(node) {
|
|
483
|
+
return node.arguments.some(argument => argument.type === 'ObjectExpression' && argument.properties.some(property =>
|
|
484
|
+
property.type === 'ObjectProperty' && (property.key.name === 'shell') && !(property.value.type === 'BooleanLiteral' && property.value.value === false)));
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
report(node, sink, call, source, confidence) {
|
|
488
|
+
this.file.record(node, this.label, sink, call, source, confidence);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function parseSource(source) {
|
|
493
|
+
return parser.parse(source, {
|
|
494
|
+
sourceType: 'unambiguous',
|
|
495
|
+
errorRecovery: false,
|
|
496
|
+
allowReturnOutsideFunction: true,
|
|
497
|
+
plugins: [
|
|
498
|
+
'asyncGenerators', 'classProperties', 'classPrivateProperties', 'classPrivateMethods', 'decorators-legacy', 'dynamicImport',
|
|
499
|
+
'importAttributes', 'jsx', 'objectRestSpread', 'optionalChaining', 'topLevelAwait', 'typescript'
|
|
500
|
+
]
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function analyzeSource(source, filename = '<source>') {
|
|
505
|
+
const findings = new FileAnalyzer(parseSource(source), filename).run();
|
|
506
|
+
return findings.sort((a, b) => a.line - b.line || a.sink.localeCompare(b.sink));
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function isTestFile(name) {
|
|
510
|
+
return /\.(test|spec)\.[cm]?[jt]sx?$/.test(name);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function collectFiles(root, includeTests, files) {
|
|
514
|
+
const stat = fs.statSync(root);
|
|
515
|
+
if (stat.isFile()) {
|
|
516
|
+
files.push(root);
|
|
517
|
+
return files;
|
|
518
|
+
}
|
|
519
|
+
for (const entry of fs.readdirSync(root, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
520
|
+
const full = path.join(root, entry.name);
|
|
521
|
+
if (entry.isDirectory()) {
|
|
522
|
+
if (SKIPPED_DIRECTORIES.has(entry.name) || (!includeTests && TEST_DIRECTORIES.has(entry.name))) continue;
|
|
523
|
+
collectFiles(full, includeTests, files);
|
|
524
|
+
} else if (entry.isFile() && SOURCE_EXTENSIONS.has(path.extname(entry.name)) && !entry.name.endsWith('.d.ts')) {
|
|
525
|
+
if (includeTests || !isTestFile(entry.name)) files.push(full);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
return files;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function analyzePath(target = '.', options = {}) {
|
|
532
|
+
if (!fs.existsSync(target)) throw new Error(`Path not found: ${target}`);
|
|
533
|
+
const findings = [];
|
|
534
|
+
const errors = [];
|
|
535
|
+
let filesScanned = 0;
|
|
536
|
+
for (const file of collectFiles(target, Boolean(options.includeTests), [])) {
|
|
537
|
+
const display = file.split(path.sep).join('/');
|
|
538
|
+
try {
|
|
539
|
+
if (fs.statSync(file).size > MAX_FILE_BYTES) {
|
|
540
|
+
errors.push({ file: display, error: 'File is too large to analyze' });
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
findings.push(...analyzeSource(fs.readFileSync(file, 'utf8'), display));
|
|
544
|
+
filesScanned += 1;
|
|
545
|
+
} catch (error) {
|
|
546
|
+
errors.push({ file: display, error: String(error.message || error) });
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
findings.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.sink.localeCompare(b.sink));
|
|
550
|
+
return { schema_version: SCHEMA_VERSION, language: 'javascript', files_scanned: filesScanned, findings, errors };
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function formatReport(report) {
|
|
554
|
+
const lines = report.findings.map(finding =>
|
|
555
|
+
`${finding.file}:${finding.line}: ${finding.sink} (${finding.confidence} confidence) ${finding.source} reaches ${finding.call} in ${finding.function}`);
|
|
556
|
+
for (const error of report.errors) lines.push(`${error.file}: not analyzed: ${error.error}`);
|
|
557
|
+
lines.push(`Scanned ${report.files_scanned} files and found ${report.findings.length} possible injection paths.`);
|
|
558
|
+
if (!report.findings.length) lines.push("This doesn't prove the code is safe, because static analysis can miss paths.");
|
|
559
|
+
return lines.join('\n');
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
function runAuditCommand(args, write = text => console.log(text)) {
|
|
563
|
+
const positional = [];
|
|
564
|
+
const options = { format: 'text', includeTests: false, failOnFindings: false, output: null, manifest: null };
|
|
565
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
566
|
+
const argument = args[index];
|
|
567
|
+
if (argument === '--format') options.format = args[++index];
|
|
568
|
+
else if (argument === '--output') options.output = args[++index];
|
|
569
|
+
else if (argument === '--manifest') options.manifest = args[++index];
|
|
570
|
+
else if (argument === '--include-tests') options.includeTests = true;
|
|
571
|
+
else if (argument === '--fail-on-findings') options.failOnFindings = true;
|
|
572
|
+
else positional.push(argument);
|
|
573
|
+
}
|
|
574
|
+
if (!['text', 'json'].includes(options.format)) {
|
|
575
|
+
write('Usage: aiwaf audit [path] [--format text|json] [--output file] [--include-tests] [--fail-on-findings] [--manifest file]');
|
|
576
|
+
return 2;
|
|
577
|
+
}
|
|
578
|
+
let report;
|
|
579
|
+
try {
|
|
580
|
+
report = analyzePath(positional[0] || '.', options);
|
|
581
|
+
} catch (error) {
|
|
582
|
+
write(String(error.message || error));
|
|
583
|
+
return 2;
|
|
584
|
+
}
|
|
585
|
+
const content = options.format === 'json' ? JSON.stringify(report, null, 2) : formatReport(report);
|
|
586
|
+
if (options.output) fs.writeFileSync(options.output, `${content}\n`);
|
|
587
|
+
else write(content);
|
|
588
|
+
if (options.manifest) {
|
|
589
|
+
const { formatCounts, updateManifest } = require('./routeRisks');
|
|
590
|
+
try {
|
|
591
|
+
write(formatCounts(updateManifest(report, options.manifest), options.manifest));
|
|
592
|
+
} catch (error) {
|
|
593
|
+
write(String(error.message || error));
|
|
594
|
+
return 2;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
return options.failOnFindings && report.findings.length ? 1 : 0;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
module.exports = { analyzePath, analyzeSource, formatReport, runAuditCommand };
|
package/lib/nativePipeline.js
CHANGED
|
@@ -3,6 +3,8 @@ const fs = require('fs');
|
|
|
3
3
|
const path = require('path');
|
|
4
4
|
const { performance } = require('perf_hooks');
|
|
5
5
|
const { createRequestPipeline } = require('./wasmAdapter');
|
|
6
|
+
const wasmChecks = require('./wasmChecks');
|
|
7
|
+
const routeRisks = require('./routeRisks');
|
|
6
8
|
const { ALL_MIDDLEWARES, normalizeMiddlewareName } = require('./pathRules');
|
|
7
9
|
|
|
8
10
|
const LOG_HEADER = 'timestamp,ip,method,path,status,response_time_ms,blocked,reason,country,user_agent\n';
|
|
@@ -121,6 +123,10 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
121
123
|
const contextKey = Symbol('aiwaf.native.context');
|
|
122
124
|
const pending = new Set();
|
|
123
125
|
const report = error => { if (options.onError) options.onError(error); else console.error('AIWAF native finalization failed:', error.message); };
|
|
126
|
+
// This pipeline takes no general settings, so these two come from the environment. Route
|
|
127
|
+
// checks run in aiwaf-wasm, loaded here so requests can use them straight away.
|
|
128
|
+
const observeRisks = routeRisks.createObserver({ AIWAF_PATH_MANIFEST: process.env.AIWAF_PATH_MANIFEST });
|
|
129
|
+
if (observeRisks) await wasmChecks.load();
|
|
124
130
|
function payload(req) {
|
|
125
131
|
const b = safeBody(req, maxBytes);
|
|
126
132
|
const query = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
|
|
@@ -133,6 +139,11 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
133
139
|
const start = performance.now();
|
|
134
140
|
try {
|
|
135
141
|
const meta = req.aiwafRoute || {};
|
|
142
|
+
if (observeRisks && !meta.fullyExempt && !(meta.exemptMiddlewares || []).includes('ip_keyword_block')
|
|
143
|
+
&& (!profile.enabled || profile.enabled.includes('ip_keyword_block'))) {
|
|
144
|
+
const riskFinding = observeRisks(req);
|
|
145
|
+
if (riskFinding) return res.status(riskFinding.status).json({ error: riskFinding.rule });
|
|
146
|
+
}
|
|
136
147
|
const required = new Set((meta.requiredMiddlewares || []).map(normalizeMiddlewareName));
|
|
137
148
|
const disabled = new Set((meta.fullyExempt ? ALL_MIDDLEWARES : meta.exemptMiddlewares || []).map(normalizeMiddlewareName));
|
|
138
149
|
for (const key of required) disabled.delete(key);
|
|
@@ -172,6 +183,8 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
172
183
|
const disabled = req.aiwafRoute?.exemptMiddlewares || [];
|
|
173
184
|
if (profile.enabled && !profile.enabled.includes('ip_keyword_block')) return null;
|
|
174
185
|
if (req.aiwafRoute?.fullyExempt || disabled.includes('ip_keyword_block')) return null;
|
|
186
|
+
const riskFinding = observeRisks ? observeRisks(req) : null;
|
|
187
|
+
if (riskFinding) return riskFinding;
|
|
175
188
|
return payload(req);
|
|
176
189
|
};
|
|
177
190
|
middleware.diagnostics = () => JSON.parse(native.diagnostics());
|
package/lib/pathManifest.js
CHANGED
|
@@ -477,8 +477,22 @@ function extractNestRoutes(app, routesInput = null) {
|
|
|
477
477
|
}
|
|
478
478
|
}
|
|
479
479
|
|
|
480
|
-
|
|
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,
|