aiwaf 1.2.3 → 1.2.4
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 +73 -37
- package/lib/injectionAnalysis.js +1204 -52
- package/lib/routeRisks.js +1 -1
- package/lib/wafMiddleware.js +1 -1
- package/package.json +2 -2
package/lib/injectionAnalysis.js
CHANGED
|
@@ -2,8 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
// Static analysis that follows request input to dangerous operations.
|
|
4
4
|
// It reads source files only, and never runs application code or affects request handling.
|
|
5
|
-
//
|
|
5
|
+
// Calls into other project files are followed through relative paths, tsconfig or jsconfig paths
|
|
6
|
+
// and baseUrl, and workspace packages, including methods on instances of the project's classes.
|
|
7
|
+
// A clean report doesn't prove code is safe: dynamic calls and packages outside the project can be missed.
|
|
6
8
|
|
|
9
|
+
const crypto = require('crypto');
|
|
7
10
|
const fs = require('fs');
|
|
8
11
|
const path = require('path');
|
|
9
12
|
const parser = require('@babel/parser');
|
|
@@ -23,14 +26,96 @@ const REQUEST_PROPERTIES = new Set([
|
|
|
23
26
|
'querystring', 'raw', 'rawBody', 'state', 'url'
|
|
24
27
|
]);
|
|
25
28
|
const CONTEXT_PROPERTIES = new Set(['body', 'cookies', 'headers', 'params', 'path', 'query', 'querystring', 'request', 'url']);
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
+
// formData(), json() and text() read the body of a Fetch API Request, as in Next.js and Remix.
|
|
30
|
+
const REQUEST_METHODS = new Set([
|
|
31
|
+
'all', 'allParams', 'arrayBuffer', 'blob', 'body', 'cookie', 'file', 'formData', 'get', 'header', 'input', 'json', 'only',
|
|
32
|
+
'param', 'params', 'qs', 'raw', 'text'
|
|
33
|
+
]);
|
|
34
|
+
// NestJS (REST, GraphQL and WebSocket) and TypeGraphQL decorators for request input.
|
|
35
|
+
const NEST_INPUT_DECORATORS = new Set(['Arg', 'Args', 'Body', 'Cookies', 'Headers', 'MessageBody', 'Param', 'Query', 'UploadedFile', 'UploadedFiles']);
|
|
36
|
+
const GRAPHQL_ROOTS = new Set(['Mutation', 'Query', 'Subscription']);
|
|
37
|
+
const TRPC_PROCEDURES = new Set(['mutation', 'query', 'subscription']);
|
|
38
|
+
const SOCKET_EVENTS_IGNORED = new Set(['close', 'connect', 'connection', 'disconnect', 'error', 'listening', 'open']);
|
|
39
|
+
// Methods that call back with each value of what they are called on, as in items.forEach(item => ...).
|
|
40
|
+
const CALLBACK_METHODS = new Set(['every', 'filter', 'find', 'flatMap', 'forEach', 'map', 'some', 'then']);
|
|
41
|
+
// NestJS pipes that reject anything but a number, boolean or UUID, so the value can't carry an injection.
|
|
42
|
+
const NEST_SAFE_PIPES = new Set(['ParseBoolPipe', 'ParseFloatPipe', 'ParseIntPipe', 'ParseUUIDPipe']);
|
|
43
|
+
// Methods that put a value into the collection they are called on.
|
|
44
|
+
const COLLECTION_ADDS = new Set(['add', 'push', 'set', 'splice', 'unshift']);
|
|
45
|
+
const SANITIZERS = new Set(['Boolean', 'Number', 'Number.parseFloat', 'Number.parseInt', 'encodeURIComponent', 'isNaN', 'parseFloat', 'parseInt']);
|
|
46
|
+
// Encoders whose result is safe only for some operations, as escapeHtml is for HTML.
|
|
47
|
+
const KIND_SANITIZERS = new Map([
|
|
48
|
+
...['DOMPurify.sanitize', 'escape', 'escapeHtml', 'filterXSS', 'he.encode', 'he.escape', 'sanitizeHtml', 'validator.escape', 'xss']
|
|
49
|
+
.map(name => [name, ['xss']]),
|
|
50
|
+
['path.basename', ['path']],
|
|
51
|
+
...['shellescape', 'shellQuote.quote', 'quote'].map(name => [name, ['command']]),
|
|
52
|
+
...['mysql.escape', 'mysql.escapeId', 'pgFormat', 'sqlstring.escape', 'sqlstring.escapeId', 'format.literal'].map(name => [name, ['sql']]),
|
|
53
|
+
...['_.escapeRegExp', 'escapeRegExp', 'escapeStringRegexp', 'lodash.escapeRegExp'].map(name => [name, ['redos']]),
|
|
54
|
+
...['ldapEscape.filter', 'ldapEscape'].map(name => [name, ['ldap']]),
|
|
55
|
+
['encodeURI', ['redirect']]
|
|
56
|
+
]);
|
|
57
|
+
// Marks what a source was made safe for: source + SAFE + 'xss,ldap', or '*' for everything.
|
|
58
|
+
const SAFE = '\u0001';
|
|
59
|
+
// Schema checks whose result is a number, boolean, UUID or one of fixed values, as in z.number().parse(x).
|
|
60
|
+
const SAFE_SCHEMA = /\b(?:bigint|boolean|date|datetime|email|enum|int|literal|nativeEnum|number|uuid)\(/;
|
|
61
|
+
const VALIDATOR_CHECKS = /^(?:validator\.)?is(?:Alpha|Alphanumeric|Base32|Boolean|Date|Decimal|Email|Float|Hexadecimal|IP|ISO8601|Int|MongoId|Numeric|Port|UUID)$/;
|
|
62
|
+
const RESPONSE_NAMES = new Set(['res', 'response']);
|
|
63
|
+
const XSS_METHODS = new Set(['end', 'send', 'write']);
|
|
64
|
+
const MERGE_FUNCTIONS = new Set([
|
|
65
|
+
'_.defaultsDeep', '_.merge', '_.mergeWith', '_.set', '_.setWith', '_.zipObjectDeep', 'deepmerge', 'defaultsDeep', 'lodash.merge',
|
|
66
|
+
'lodash.set', 'merge', 'mergeDeep', 'set', 'setWith'
|
|
67
|
+
]);
|
|
68
|
+
const XPATH_FUNCTIONS = new Set(['select', 'select1', 'xpath.evaluate', 'xpath.parse', 'xpath.select', 'xpath.select1', 'xpath.useNamespaces']);
|
|
69
|
+
const XML_FUNCTIONS = new Set(['libxml.parseXml', 'libxml.parseXmlString', 'libxmljs.parseXml', 'libxmljs.parseXmlString', 'parseXml', 'parseXmlString']);
|
|
70
|
+
|
|
71
|
+
function safeSource(source, kinds) {
|
|
72
|
+
if (!source || !kinds || !kinds.length) return source;
|
|
73
|
+
const all = new Set([...safeKinds(source), ...kinds]);
|
|
74
|
+
return `${baseSource(source)}${SAFE}${[...all].sort().join(',')}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function baseSource(source) {
|
|
78
|
+
const marker = source.indexOf(SAFE);
|
|
79
|
+
return marker < 0 ? source : source.slice(0, marker);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function safeKinds(source) {
|
|
83
|
+
const marker = source ? source.indexOf(SAFE) : -1;
|
|
84
|
+
return marker < 0 ? [] : source.slice(marker + 1).split(',');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Two inputs in one value: it's safe only for what both are safe for.
|
|
88
|
+
function combine(left, right) {
|
|
89
|
+
if (!left || !right) return left || right || null;
|
|
90
|
+
const kinds = safeKinds(left).includes('*') ? safeKinds(right)
|
|
91
|
+
: safeKinds(right).includes('*') ? safeKinds(left) : safeKinds(left).filter(kind => safeKinds(right).includes(kind));
|
|
92
|
+
return kinds.length ? safeSource(baseSource(left), kinds) : baseSource(safeKinds(left).length ? right : left);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const UNKNOWN = Symbol('unknown');
|
|
96
|
+
|
|
97
|
+
// True when a block always leaves: return, throw, continue or break.
|
|
98
|
+
function exits(node) {
|
|
99
|
+
if (!node) return false;
|
|
100
|
+
if (['BreakStatement', 'ContinueStatement', 'ReturnStatement', 'ThrowStatement'].includes(node.type)) return true;
|
|
101
|
+
return node.type === 'BlockStatement' && node.body.length > 0 && exits(node.body[node.body.length - 1]);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function assignedNames(node, names = new Set()) {
|
|
105
|
+
if (!node || typeof node.type !== 'string') return names;
|
|
106
|
+
if (node.type === 'AssignmentExpression' && node.left.type === 'Identifier') names.add(node.left.name);
|
|
107
|
+
if (node.type === 'UpdateExpression' && node.argument.type === 'Identifier') names.add(node.argument.name);
|
|
108
|
+
eachChild(node, child => assignedNames(child, names));
|
|
109
|
+
return names;
|
|
110
|
+
}
|
|
29
111
|
const PASSTHROUGH_METHODS = new Set([
|
|
30
112
|
'concat', 'join', 'padEnd', 'padStart', 'replace', 'replaceAll', 'slice', 'split', 'substring', 'toLowerCase',
|
|
31
113
|
'toString', 'toUpperCase', 'trim', 'trimEnd', 'trimStart'
|
|
32
114
|
]);
|
|
33
|
-
const PASSTHROUGH_FUNCTIONS = new Set([
|
|
115
|
+
const PASSTHROUGH_FUNCTIONS = new Set([
|
|
116
|
+
'Array.from', 'Buffer.from', 'JSON.parse', 'JSON.stringify', 'Object.assign', 'Object.entries', 'Object.keys', 'Object.values',
|
|
117
|
+
'Promise.resolve', 'String', 'decodeURIComponent', 'path.join', 'path.normalize', 'path.resolve', 'qs.parse', 'querystring.parse'
|
|
118
|
+
]);
|
|
34
119
|
const SQL_METHODS = new Set(['$executeRawUnsafe', '$queryRawUnsafe', 'execute', 'havingRaw', 'orderByRaw', 'query', 'raw', 'whereRaw']);
|
|
35
120
|
const SQLITE_METHODS = new Set(['all', 'each', 'exec', 'get', 'prepare', 'run']);
|
|
36
121
|
const SQLITE_RECEIVER = /(^|\.)(db|sqlite|database)$/i;
|
|
@@ -86,6 +171,24 @@ function isFunction(node) {
|
|
|
86
171
|
].includes(node.type);
|
|
87
172
|
}
|
|
88
173
|
|
|
174
|
+
// The class a TypeScript annotation names, as in users: UsersService.
|
|
175
|
+
function typeName(annotation) {
|
|
176
|
+
const type = annotation && annotation.type === 'TSTypeAnnotation' ? annotation.typeAnnotation : annotation;
|
|
177
|
+
if (!type || type.type !== 'TSTypeReference') return '';
|
|
178
|
+
const name = type.typeName;
|
|
179
|
+
if (name.type === 'Identifier') return name.name;
|
|
180
|
+
return name.type === 'TSQualifiedName' && name.left.type === 'Identifier' ? `${name.left.name}.${name.right.name}` : '';
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// The class a value is an instance of, when it is built with new, as in new UsersService().
|
|
184
|
+
function constructed(node) {
|
|
185
|
+
let value = node;
|
|
186
|
+
while (value && (value.type === 'AwaitExpression' || value.type === 'TSAsExpression' || value.type === 'ParenthesizedExpression')) {
|
|
187
|
+
value = value.argument || value.expression;
|
|
188
|
+
}
|
|
189
|
+
return value && value.type === 'NewExpression' ? dottedName(value.callee) : '';
|
|
190
|
+
}
|
|
191
|
+
|
|
89
192
|
function eachChild(node, visit) {
|
|
90
193
|
for (const key of Object.keys(node)) {
|
|
91
194
|
if (['loc', 'start', 'end', 'extra', 'leadingComments', 'trailingComments', 'innerComments', 'typeAnnotation', 'returnType', 'typeParameters'].includes(key)) continue;
|
|
@@ -108,22 +211,130 @@ function functionName(node, parent) {
|
|
|
108
211
|
return route && route.type === 'StringLiteral' ? `${label} ${route.value}` : (label || '<anonymous>');
|
|
109
212
|
}
|
|
110
213
|
if (parent && parent.type === 'ExportDefaultDeclaration') return 'default';
|
|
214
|
+
if (parent && parent.type === 'AssignmentExpression' && parent.right === node) {
|
|
215
|
+
const target = dottedName(parent.left);
|
|
216
|
+
if (target === 'module.exports' || target === 'exports') return 'default';
|
|
217
|
+
if (/^(module\.)?exports\.\w+$/.test(target)) return target.split('.').pop();
|
|
218
|
+
}
|
|
111
219
|
return '<anonymous>';
|
|
112
220
|
}
|
|
113
221
|
|
|
114
222
|
class FileAnalyzer {
|
|
115
|
-
constructor(ast, filename) {
|
|
223
|
+
constructor(ast, filename, fullPath = '', project = null, source = '') {
|
|
116
224
|
this.ast = ast;
|
|
225
|
+
this.source = source;
|
|
226
|
+
// Values middleware stores on the request for later handlers, as in req.search = req.query.q.
|
|
227
|
+
this.requestExtras = project ? project.requestExtras : new Map();
|
|
228
|
+
this.serverActions = Boolean(ast.program && ast.program.directives.some(item => item.value.value === 'use server'));
|
|
117
229
|
this.filename = filename;
|
|
230
|
+
this.fullPath = fullPath;
|
|
231
|
+
this.project = project;
|
|
118
232
|
this.findings = new Map();
|
|
119
233
|
this.functions = new Map();
|
|
234
|
+
this.classes = new Map();
|
|
235
|
+
this.methodOwners = new WeakMap();
|
|
236
|
+
this.defaultExport = '';
|
|
237
|
+
this.imports = new Map();
|
|
120
238
|
this.routeLabels = new WeakMap();
|
|
121
239
|
this.collectFunctions(ast);
|
|
240
|
+
if (project) this.collectImports(ast);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Records local names bound to other project files, as in import { build } from './sql'
|
|
244
|
+
// or const sql = require('./sql').
|
|
245
|
+
collectImports(root) {
|
|
246
|
+
const add = (local, spec, name) => {
|
|
247
|
+
const file = this.project.resolver.resolve(this.fullPath, spec);
|
|
248
|
+
if (file && local) this.imports.set(local, { file, name });
|
|
249
|
+
};
|
|
250
|
+
const visit = node => {
|
|
251
|
+
if (node.type === 'ImportDeclaration' && node.importKind !== 'type') {
|
|
252
|
+
for (const item of node.specifiers) {
|
|
253
|
+
if (item.type === 'ImportSpecifier') add(item.local.name, node.source.value, item.imported.name || item.imported.value);
|
|
254
|
+
else if (item.type === 'ImportDefaultSpecifier') add(item.local.name, node.source.value, 'default');
|
|
255
|
+
else if (item.type === 'ImportNamespaceSpecifier') add(item.local.name, node.source.value, '*');
|
|
256
|
+
}
|
|
257
|
+
} else if (node.type === 'VariableDeclarator' && node.init) {
|
|
258
|
+
let init = node.init;
|
|
259
|
+
let member = '';
|
|
260
|
+
if (init.type === 'MemberExpression' && propertyName(init)) {
|
|
261
|
+
member = propertyName(init);
|
|
262
|
+
init = init.object;
|
|
263
|
+
}
|
|
264
|
+
if (init.type === 'CallExpression' && init.callee.type === 'Identifier' && init.callee.name === 'require'
|
|
265
|
+
&& init.arguments[0] && init.arguments[0].type === 'StringLiteral') {
|
|
266
|
+
const spec = init.arguments[0].value;
|
|
267
|
+
if (node.id.type === 'Identifier') add(node.id.name, spec, member || '*');
|
|
268
|
+
else if (node.id.type === 'ObjectPattern' && !member) {
|
|
269
|
+
for (const property of node.id.properties) {
|
|
270
|
+
if (property.type === 'ObjectProperty' && property.value.type === 'Identifier') {
|
|
271
|
+
add(property.value.name, spec, property.key.name || property.key.value);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
eachChild(node, visit);
|
|
278
|
+
};
|
|
279
|
+
visit(root);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Finds the function a call runs, in this file or in a project file it imports. A method call on a
|
|
283
|
+
// value of a known class, as in this.users.find(id) or service.find(id), runs that class's method.
|
|
284
|
+
findFunction(callee, walker = null) {
|
|
285
|
+
return this.findMethod(callee, walker) || this.findPlain(callee);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
findMethod(callee, walker) {
|
|
289
|
+
if (walker && (callee.type === 'MemberExpression' || callee.type === 'OptionalMemberExpression')) {
|
|
290
|
+
const method = propertyName(callee);
|
|
291
|
+
const object = callee.object;
|
|
292
|
+
let type = '';
|
|
293
|
+
if (object.type === 'ThisExpression' && walker.owner) {
|
|
294
|
+
const node = walker.owner.methods.get(method);
|
|
295
|
+
if (node) return { file: this, node };
|
|
296
|
+
} else if (object.type === 'MemberExpression' && object.object.type === 'ThisExpression' && walker.owner) {
|
|
297
|
+
type = walker.owner.fields.get(propertyName(object)) || '';
|
|
298
|
+
} else if (object.type === 'Identifier') {
|
|
299
|
+
type = walker.types.get(object.name) || (/^[A-Z]/.test(object.name) ? object.name : '');
|
|
300
|
+
} else {
|
|
301
|
+
type = constructed(object);
|
|
302
|
+
}
|
|
303
|
+
const found = method && this.classFor(type);
|
|
304
|
+
const node = found && found.info.methods.get(method);
|
|
305
|
+
if (node) return { file: found.file, node };
|
|
306
|
+
}
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
findPlain(callee) {
|
|
311
|
+
const local = name => (this.functions.has(name) ? { file: this, node: this.functions.get(name) } : null);
|
|
312
|
+
const imported = (entry, name) => {
|
|
313
|
+
const target = this.project && this.project.get(entry.file);
|
|
314
|
+
const node = target && target.functions.get(name);
|
|
315
|
+
return node ? { file: target, node } : null;
|
|
316
|
+
};
|
|
317
|
+
if (callee.type === 'Identifier') {
|
|
318
|
+
const entry = this.imports.get(callee.name);
|
|
319
|
+
if (entry) return entry.name === '*' ? imported(entry, 'default') : imported(entry, entry.name);
|
|
320
|
+
return local(callee.name);
|
|
321
|
+
}
|
|
322
|
+
const name = dottedName(callee);
|
|
323
|
+
const parts = name.split('.');
|
|
324
|
+
if (parts.length === 2) {
|
|
325
|
+
const entry = this.imports.get(parts[0]);
|
|
326
|
+
if (entry && entry.name === '*') return imported(entry, parts[1]);
|
|
327
|
+
}
|
|
328
|
+
return name ? local(parts[parts.length - 1]) : null;
|
|
122
329
|
}
|
|
123
330
|
|
|
124
331
|
collectFunctions(root) {
|
|
125
332
|
const visit = (node, parent) => {
|
|
126
333
|
if (node.type === 'ObjectExpression') this.collectRouteLabel(node);
|
|
334
|
+
if (node.type === 'ClassDeclaration' || node.type === 'ClassExpression') this.collectClass(node, parent);
|
|
335
|
+
if (parent && parent.type === 'ExportDefaultDeclaration' && node.type === 'Identifier') this.defaultExport = node.name;
|
|
336
|
+
if (node.type === 'AssignmentExpression' && node.right.type === 'Identifier'
|
|
337
|
+
&& ['module.exports', 'exports'].includes(dottedName(node.left))) this.defaultExport = node.right.name;
|
|
127
338
|
if (isFunction(node)) {
|
|
128
339
|
const name = functionName(node, parent);
|
|
129
340
|
if (name && name !== '<anonymous>' && !this.functions.has(name)) this.functions.set(name, node);
|
|
@@ -133,6 +344,67 @@ class FileAnalyzer {
|
|
|
133
344
|
visit(root, null);
|
|
134
345
|
}
|
|
135
346
|
|
|
347
|
+
// Records a class's methods, and the classes its fields hold, as in
|
|
348
|
+
// constructor(private readonly users: UsersService) or this.users = new UsersService().
|
|
349
|
+
collectClass(node, parent) {
|
|
350
|
+
const name = (node.id && node.id.name)
|
|
351
|
+
|| (parent && parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier' ? parent.id.name : '');
|
|
352
|
+
const info = { name, methods: new Map(), fields: new Map() };
|
|
353
|
+
for (const member of node.body.body) {
|
|
354
|
+
if ((member.type === 'ClassMethod' || member.type === 'ClassPrivateMethod') && member.key) {
|
|
355
|
+
const key = member.key.name || member.key.value || (member.key.id && member.key.id.name);
|
|
356
|
+
if (key) info.methods.set(key, member);
|
|
357
|
+
this.methodOwners.set(member, info);
|
|
358
|
+
} else if ((member.type === 'ClassProperty' || member.type === 'ClassPrivateProperty') && member.key) {
|
|
359
|
+
const type = typeName(member.typeAnnotation) || constructed(member.value);
|
|
360
|
+
const key = member.key.name || (member.key.id && member.key.id.name);
|
|
361
|
+
if (type && key) info.fields.set(key, type);
|
|
362
|
+
}
|
|
363
|
+
if (member.type === 'ClassMethod' && member.kind === 'constructor') {
|
|
364
|
+
const types = new Map();
|
|
365
|
+
for (const parameter of member.params) {
|
|
366
|
+
const target = parameter.type === 'TSParameterProperty' ? parameter.parameter : parameter;
|
|
367
|
+
const inner = target.type === 'AssignmentPattern' ? target.left : target;
|
|
368
|
+
const type = inner.type === 'Identifier' ? typeName(inner.typeAnnotation) : '';
|
|
369
|
+
if (!type) continue;
|
|
370
|
+
types.set(inner.name, type);
|
|
371
|
+
if (parameter.type === 'TSParameterProperty') info.fields.set(inner.name, type);
|
|
372
|
+
}
|
|
373
|
+
for (const statement of member.body.body) {
|
|
374
|
+
const expression = statement.type === 'ExpressionStatement' ? statement.expression : null;
|
|
375
|
+
if (!expression || expression.type !== 'AssignmentExpression' || expression.left.type !== 'MemberExpression'
|
|
376
|
+
|| expression.left.object.type !== 'ThisExpression') continue;
|
|
377
|
+
const key = propertyName(expression.left);
|
|
378
|
+
const type = constructed(expression.right) || (expression.right.type === 'Identifier' ? types.get(expression.right.name) : '');
|
|
379
|
+
if (key && type) info.fields.set(key, type);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (name && !this.classes.has(name)) this.classes.set(name, info);
|
|
384
|
+
if (parent && parent.type === 'ExportDefaultDeclaration') this.classes.set('default', info);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// The class a name refers to here: declared in this file, or imported from a project file.
|
|
388
|
+
classFor(type) {
|
|
389
|
+
if (!type) return null;
|
|
390
|
+
const own = (file, name) => {
|
|
391
|
+
const info = file.classes.get(name) || (name === 'default' && file.defaultExport ? file.classes.get(file.defaultExport) : null);
|
|
392
|
+
return info ? { file, info } : null;
|
|
393
|
+
};
|
|
394
|
+
const imported = (entry, name) => {
|
|
395
|
+
const target = this.project && this.project.get(entry.file);
|
|
396
|
+
return target ? own(target, name) : null;
|
|
397
|
+
};
|
|
398
|
+
const parts = type.split('.');
|
|
399
|
+
if (parts.length === 2) {
|
|
400
|
+
const entry = this.imports.get(parts[0]);
|
|
401
|
+
return entry && entry.name === '*' ? imported(entry, parts[1]) : null;
|
|
402
|
+
}
|
|
403
|
+
const entry = this.imports.get(type);
|
|
404
|
+
if (entry) return imported(entry, entry.name === '*' ? 'default' : entry.name);
|
|
405
|
+
return own(this, type);
|
|
406
|
+
}
|
|
407
|
+
|
|
136
408
|
collectRouteLabel(node) {
|
|
137
409
|
const value = name => node.properties.find(item => item.key && (item.key.name || item.key.value) === name);
|
|
138
410
|
const route = value('path');
|
|
@@ -143,21 +415,100 @@ class FileAnalyzer {
|
|
|
143
415
|
}
|
|
144
416
|
|
|
145
417
|
run() {
|
|
418
|
+
const parents = [];
|
|
146
419
|
const visit = (node, parent, inherited) => {
|
|
147
420
|
if (isFunction(node)) {
|
|
148
421
|
const scope = this.initialScope(node, inherited);
|
|
422
|
+
this.addFrameworkInput(node, parents, scope);
|
|
149
423
|
if (scope.tainted.size || scope.requests.size || scope.contexts.size) {
|
|
150
424
|
this.analyze(node, scope, this.routeLabels.get(node) || functionName(node, parent), 0, new Set());
|
|
151
425
|
}
|
|
152
426
|
// Nested functions are handled while analyzing the function that contains them.
|
|
153
427
|
if (scope.tainted.size || scope.requests.size || scope.contexts.size) return;
|
|
154
428
|
}
|
|
429
|
+
parents.push(node);
|
|
155
430
|
eachChild(node, child => visit(child, node, inherited));
|
|
431
|
+
parents.pop();
|
|
156
432
|
};
|
|
157
433
|
visit(this.ast, null, null);
|
|
158
434
|
return [...this.findings.values()];
|
|
159
435
|
}
|
|
160
436
|
|
|
437
|
+
// Input that frameworks pass as plain arguments: GraphQL resolver arguments, tRPC input, Next.js
|
|
438
|
+
// server action arguments and WebSocket messages.
|
|
439
|
+
addFrameworkInput(node, parents, scope) {
|
|
440
|
+
const parent = parents[parents.length - 1];
|
|
441
|
+
const grand = parents[parents.length - 2];
|
|
442
|
+
const greatGrand = parents[parents.length - 3];
|
|
443
|
+
const params = node.params || [];
|
|
444
|
+
const taintParameter = (parameter, label) => {
|
|
445
|
+
const target = parameter && parameter.type === 'AssignmentPattern' ? parameter.left : parameter;
|
|
446
|
+
if (!target) return;
|
|
447
|
+
if (target.type === 'Identifier') scope.tainted.set(target.name, label);
|
|
448
|
+
else if (target.type === 'ObjectPattern') {
|
|
449
|
+
for (const property of target.properties) {
|
|
450
|
+
const inner = property.type === 'ObjectProperty' ? (property.value.type === 'AssignmentPattern' ? property.value.left : property.value) : property.argument;
|
|
451
|
+
const key = property.type === 'ObjectProperty' ? (property.key.name || property.key.value) : '';
|
|
452
|
+
if (inner && inner.type === 'Identifier') scope.tainted.set(inner.name, key ? `${label}.${key}` : label);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
// { Query: { user: (parent, args) => ... } }
|
|
457
|
+
const property = parent && parent.type === 'ObjectProperty' && parent.value === node ? parent : (node.type === 'ObjectMethod' ? node : null);
|
|
458
|
+
const owner = property && (node.type === 'ObjectMethod' ? parent : grand);
|
|
459
|
+
const ownerProperty = node.type === 'ObjectMethod' ? grand : greatGrand;
|
|
460
|
+
if (owner && owner.type === 'ObjectExpression' && ownerProperty && ownerProperty.type === 'ObjectProperty'
|
|
461
|
+
&& GRAPHQL_ROOTS.has(ownerProperty.key.name || ownerProperty.key.value)) {
|
|
462
|
+
taintParameter(params[1], 'graphql args');
|
|
463
|
+
}
|
|
464
|
+
// t.procedure.input(schema).query(({ input }) => ...)
|
|
465
|
+
if (parent && (parent.type === 'CallExpression' || parent.type === 'OptionalCallExpression') && parent.arguments.includes(node)) {
|
|
466
|
+
const callee = parent.callee;
|
|
467
|
+
const method = callee.type === 'MemberExpression' ? propertyName(callee) : '';
|
|
468
|
+
const chain = this.source ? this.source.slice(callee.start, callee.end) : dottedName(callee);
|
|
469
|
+
if (TRPC_PROCEDURES.has(method) && /procedure|\.input\(/i.test(chain)) {
|
|
470
|
+
const first = params[0];
|
|
471
|
+
if (first && first.type === 'ObjectPattern') {
|
|
472
|
+
for (const item of first.properties) {
|
|
473
|
+
if (item.type === 'ObjectProperty' && (item.key.name || item.key.value) === 'input') {
|
|
474
|
+
const inner = item.value.type === 'AssignmentPattern' ? item.value.left : item.value;
|
|
475
|
+
if (inner.type === 'Identifier') scope.tainted.set(inner.name, 'trpc input');
|
|
476
|
+
else taintParameter(inner, 'trpc input');
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
} else if (first && first.type === 'Identifier') {
|
|
480
|
+
scope.tainted.set(`${first.name}.input`, 'trpc input');
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
// ws.on('message', data => ...), socket.on('chat', payload => ...)
|
|
484
|
+
const receiver = method ? dottedName(callee.object) : '';
|
|
485
|
+
const event = parent.arguments[0];
|
|
486
|
+
if (['on', 'once', 'addListener'].includes(method) && /(^|\.)(ws|wss|socket|io|client|conn|connection)$/i.test(receiver)
|
|
487
|
+
&& event && event.type === 'StringLiteral' && !SOCKET_EVENTS_IGNORED.has(event.value)) {
|
|
488
|
+
for (const parameter of params) taintParameter(parameter, `websocket ${event.value}`);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
// ws.onmessage = event => ...
|
|
492
|
+
if (parent && parent.type === 'AssignmentExpression' && parent.right === node && propertyName(parent.left) === 'onmessage') {
|
|
493
|
+
taintParameter(params[0], 'websocket message');
|
|
494
|
+
}
|
|
495
|
+
// 'use server' functions, whose arguments come from the browser.
|
|
496
|
+
const directives = node.body && node.body.type === 'BlockStatement' ? node.body.directives || [] : [];
|
|
497
|
+
const serverAction = directives.some(item => item.value.value === 'use server')
|
|
498
|
+
|| (this.serverActions && parents.some(item => item.type === 'ExportNamedDeclaration' || item.type === 'ExportDefaultDeclaration')
|
|
499
|
+
&& !parents.some(item => isFunction(item)));
|
|
500
|
+
if (serverAction) {
|
|
501
|
+
for (const parameter of params) {
|
|
502
|
+
const target = parameter.type === 'AssignmentPattern' ? parameter.left : parameter;
|
|
503
|
+
if (target.type === 'Identifier' && (target.name === 'formData' || typeName(target.typeAnnotation) === 'FormData')) {
|
|
504
|
+
scope.requests.add(target.name);
|
|
505
|
+
} else {
|
|
506
|
+
taintParameter(parameter, 'server action argument');
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
161
512
|
initialScope(node, inherited) {
|
|
162
513
|
const scope = {
|
|
163
514
|
tainted: new Map(inherited ? inherited.tainted : []),
|
|
@@ -175,6 +526,8 @@ class FileAnalyzer {
|
|
|
175
526
|
const decorators = parameter.decorators || target.decorators || [];
|
|
176
527
|
const decorator = decorators.find(item => NEST_INPUT_DECORATORS.has(dottedName(item.expression)));
|
|
177
528
|
if (decorator && target.type === 'Identifier') {
|
|
529
|
+
const pipes = (decorator.expression.arguments || []).map(item => dottedName(item.type === 'NewExpression' ? item.callee : item));
|
|
530
|
+
if (pipes.some(pipe => NEST_SAFE_PIPES.has(pipe))) return;
|
|
178
531
|
const key = decorator.expression.arguments && decorator.expression.arguments[0];
|
|
179
532
|
const nest = dottedName(decorator.expression);
|
|
180
533
|
scope.tainted.set(target.name, key && key.type === 'StringLiteral' ? `@${nest} ${key.value}` : `@${nest}`);
|
|
@@ -200,63 +553,403 @@ class FileAnalyzer {
|
|
|
200
553
|
}
|
|
201
554
|
}
|
|
202
555
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
556
|
+
// Walks a function and returns the input source its return value carries, if any. A helper
|
|
557
|
+
// walked before with the same input is not walked again: its findings are recorded again under
|
|
558
|
+
// the new caller, so large projects with shared helpers stay fast.
|
|
559
|
+
analyze(node, scope, label, depth, active, entry = '') {
|
|
560
|
+
const key = `${this.filename}:${node.start}`;
|
|
561
|
+
if (active.has(key) || depth > MAX_HELPER_DEPTH) return null;
|
|
562
|
+
const summaryKey = depth > 0 ? JSON.stringify([key, depth, [...scope.tainted].sort(), [...scope.requests].sort(),
|
|
563
|
+
[...scope.contexts].sort()]) : null;
|
|
564
|
+
const summaries = this.project ? this.project.summaries : (this.summaries = this.summaries || new Map());
|
|
565
|
+
if (summaryKey && summaries.has(summaryKey)) {
|
|
566
|
+
const summary = summaries.get(summaryKey);
|
|
567
|
+
for (const item of summary.recorded) {
|
|
568
|
+
item.file.record(item.node, label + item.label.slice(summary.label.length), item.sink, item.call, item.source, item.confidence, entry);
|
|
569
|
+
}
|
|
570
|
+
return summary.returned;
|
|
571
|
+
}
|
|
572
|
+
const recorded = [];
|
|
573
|
+
const recordings = this.project ? this.project.recordings : (this.recordings = this.recordings || []);
|
|
574
|
+
if (summaryKey) recordings.push(recorded);
|
|
206
575
|
const next = new Set(active);
|
|
207
576
|
next.add(key);
|
|
208
|
-
const walker = new FunctionWalker(this, scope, label, depth, next);
|
|
209
|
-
|
|
210
|
-
|
|
577
|
+
const walker = new FunctionWalker(this, scope, label, depth, next, entry);
|
|
578
|
+
walker.owner = this.methodOwners.get(node) || null;
|
|
579
|
+
walker.addParameterTypes(node);
|
|
580
|
+
try {
|
|
211
581
|
walker.visit(node.body, 0);
|
|
582
|
+
if (node.body.type !== 'BlockStatement') walker.returned = walker.returned || walker.taint(node.body);
|
|
583
|
+
} finally {
|
|
584
|
+
if (summaryKey) recordings.splice(recordings.indexOf(recorded), 1);
|
|
212
585
|
}
|
|
586
|
+
if (summaryKey) summaries.set(summaryKey, { label, recorded, returned: walker.returned });
|
|
587
|
+
return walker.returned;
|
|
213
588
|
}
|
|
214
589
|
|
|
215
|
-
|
|
590
|
+
// entry is the file of the handler that called into this one, when it is another file.
|
|
591
|
+
record(node, label, sink, call, source, confidence, entry = '') {
|
|
592
|
+
const recordings = this.project ? this.project.recordings : (this.recordings || []);
|
|
593
|
+
for (const recorded of recordings) recorded.push({ file: this, node, label, sink, call, source, confidence });
|
|
594
|
+
const kinds = safeKinds(source);
|
|
595
|
+
if (kinds.includes(sink) || kinds.includes('*')) return;
|
|
596
|
+
source = baseSource(source);
|
|
216
597
|
const line = node.loc ? node.loc.start.line : 0;
|
|
217
|
-
const key = `${line}:${sink}:${call}`;
|
|
598
|
+
const key = `${line}:${sink}:${call}:${label.split(' -> ')[0]}:${entry}`;
|
|
218
599
|
if (!this.findings.has(key)) {
|
|
219
|
-
|
|
600
|
+
const finding = { file: this.filename, line, function: label, sink, call, source, confidence };
|
|
601
|
+
if (entry) finding.entry_file = entry;
|
|
602
|
+
this.findings.set(key, finding);
|
|
220
603
|
}
|
|
221
604
|
}
|
|
222
605
|
}
|
|
223
606
|
|
|
224
607
|
class FunctionWalker {
|
|
225
|
-
constructor(file, scope, label, depth, active) {
|
|
608
|
+
constructor(file, scope, label, depth, active, entry = '') {
|
|
226
609
|
this.file = file;
|
|
227
610
|
this.scope = scope;
|
|
228
611
|
this.label = label;
|
|
229
612
|
this.depth = depth;
|
|
230
613
|
this.active = active;
|
|
614
|
+
this.entry = entry;
|
|
615
|
+
this.returned = null;
|
|
616
|
+
this.helperReturns = new WeakMap();
|
|
617
|
+
// The class of the method being walked, and the classes of local values, for method calls.
|
|
618
|
+
this.owner = null;
|
|
619
|
+
this.types = new Map();
|
|
620
|
+
// Values known before running, objects followed by literal key and arrays by position.
|
|
621
|
+
this.constants = new Map();
|
|
622
|
+
this.keyed = new Map();
|
|
623
|
+
this.lists = new Map();
|
|
624
|
+
// What objects built here keep from their constructor: this.<field> input and the request.
|
|
625
|
+
this.fieldInput = new Map();
|
|
626
|
+
this.fieldRequests = new Map();
|
|
627
|
+
// Callbacks called with each value of a tainted receiver, as in items.forEach(item => ...).
|
|
628
|
+
this.callbackInput = new WeakMap();
|
|
629
|
+
// Objects made with Object.create(null), which have no prototype to pollute.
|
|
630
|
+
this.bare = new Set();
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
constant(node) {
|
|
634
|
+
if (!node) return UNKNOWN;
|
|
635
|
+
switch (node.type) {
|
|
636
|
+
case 'StringLiteral':
|
|
637
|
+
case 'NumericLiteral':
|
|
638
|
+
case 'BooleanLiteral':
|
|
639
|
+
return node.value;
|
|
640
|
+
case 'NullLiteral':
|
|
641
|
+
return null;
|
|
642
|
+
case 'Identifier':
|
|
643
|
+
return this.constants.has(node.name) ? this.constants.get(node.name) : UNKNOWN;
|
|
644
|
+
case 'ParenthesizedExpression':
|
|
645
|
+
return this.constant(node.expression);
|
|
646
|
+
case 'UnaryExpression': {
|
|
647
|
+
const value = this.constant(node.argument);
|
|
648
|
+
if (value === UNKNOWN) return UNKNOWN;
|
|
649
|
+
if (node.operator === '!') return !value;
|
|
650
|
+
if (node.operator === '-' && typeof value === 'number') return -value;
|
|
651
|
+
return UNKNOWN;
|
|
652
|
+
}
|
|
653
|
+
case 'LogicalExpression': {
|
|
654
|
+
const left = this.constant(node.left);
|
|
655
|
+
const right = this.constant(node.right);
|
|
656
|
+
if (left === UNKNOWN || right === UNKNOWN) return UNKNOWN;
|
|
657
|
+
return node.operator === '&&' ? left && right : node.operator === '||' ? left || right : left ?? right;
|
|
658
|
+
}
|
|
659
|
+
case 'ConditionalExpression': {
|
|
660
|
+
const test = this.constant(node.test);
|
|
661
|
+
return test === UNKNOWN ? UNKNOWN : this.constant(test ? node.consequent : node.alternate);
|
|
662
|
+
}
|
|
663
|
+
case 'MemberExpression': {
|
|
664
|
+
const object = this.constant(node.object);
|
|
665
|
+
const index = node.computed ? this.constant(node.property) : UNKNOWN;
|
|
666
|
+
return typeof object === 'string' && typeof index === 'number' && index >= 0 && index < object.length ? object[index] : UNKNOWN;
|
|
667
|
+
}
|
|
668
|
+
case 'CallExpression': {
|
|
669
|
+
if (node.callee.type === 'MemberExpression' && propertyName(node.callee) === 'charAt') {
|
|
670
|
+
const object = this.constant(node.callee.object);
|
|
671
|
+
const index = this.constant(node.arguments[0]);
|
|
672
|
+
return typeof object === 'string' && typeof index === 'number' ? object.charAt(index) : UNKNOWN;
|
|
673
|
+
}
|
|
674
|
+
return UNKNOWN;
|
|
675
|
+
}
|
|
676
|
+
case 'BinaryExpression': {
|
|
677
|
+
const left = this.constant(node.left);
|
|
678
|
+
const right = this.constant(node.right);
|
|
679
|
+
if (left === UNKNOWN || right === UNKNOWN) return UNKNOWN;
|
|
680
|
+
const operations = {
|
|
681
|
+
'+': () => left + right, '-': () => left - right, '*': () => left * right, '/': () => (right === 0 ? UNKNOWN : left / right),
|
|
682
|
+
'%': () => (right === 0 ? UNKNOWN : left % right), '<': () => left < right, '<=': () => left <= right, '>': () => left > right,
|
|
683
|
+
'>=': () => left >= right, '===': () => left === right, '!==': () => left !== right, '==': () => left == right, // eslint-disable-line eqeqeq
|
|
684
|
+
'!=': () => left != right // eslint-disable-line eqeqeq
|
|
685
|
+
};
|
|
686
|
+
return operations[node.operator] ? operations[node.operator]() : UNKNOWN;
|
|
687
|
+
}
|
|
688
|
+
default:
|
|
689
|
+
return UNKNOWN;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// The tainted names a condition shows are safe when it is outcome, and what for. A check that
|
|
694
|
+
// returns when it fails is read with outcome false after it; if (ALLOWED.includes(x)) with true inside.
|
|
695
|
+
validated(test, outcome) {
|
|
696
|
+
const names = node => {
|
|
697
|
+
const found = new Set();
|
|
698
|
+
const walk = item => {
|
|
699
|
+
if (!item || typeof item.type !== 'string') return;
|
|
700
|
+
if (item.type === 'Identifier' && this.scope.tainted.has(item.name)) found.add(item.name);
|
|
701
|
+
eachChild(item, walk);
|
|
702
|
+
};
|
|
703
|
+
walk(node);
|
|
704
|
+
return found;
|
|
705
|
+
};
|
|
706
|
+
const all = (node, kinds) => new Map([...names(node)].map(name => [name, kinds]));
|
|
707
|
+
const merge = parts => {
|
|
708
|
+
const found = new Map();
|
|
709
|
+
for (const part of parts) for (const [name, kinds] of part) found.set(name, [...new Set([...(found.get(name) || []), ...kinds])]);
|
|
710
|
+
return found;
|
|
711
|
+
};
|
|
712
|
+
if (!test) return new Map();
|
|
713
|
+
if (test.type === 'UnaryExpression' && test.operator === '!') return this.validated(test.argument, !outcome);
|
|
714
|
+
if (test.type === 'ParenthesizedExpression') return this.validated(test.expression, outcome);
|
|
715
|
+
if (test.type === 'LogicalExpression' && test.operator !== '??') {
|
|
716
|
+
return (test.operator === '&&') === outcome ? merge([this.validated(test.left, outcome), this.validated(test.right, outcome)]) : new Map();
|
|
717
|
+
}
|
|
718
|
+
if (test.type === 'BinaryExpression' && ['===', '==', '!==', '!='].includes(test.operator)) {
|
|
719
|
+
const equal = test.operator.startsWith('=') === outcome;
|
|
720
|
+
for (const [subject, other] of [[test.left, test.right], [test.right, test.left]]) {
|
|
721
|
+
if (subject.type === 'UnaryExpression' && subject.operator === 'typeof' && other.type === 'StringLiteral'
|
|
722
|
+
&& equal && ['number', 'boolean'].includes(other.value)) return all(subject.argument, ['*']);
|
|
723
|
+
if (equal && ['StringLiteral', 'NumericLiteral', 'BooleanLiteral'].includes(other.type)) return all(subject, ['*']);
|
|
724
|
+
}
|
|
725
|
+
return new Map();
|
|
726
|
+
}
|
|
727
|
+
if (test.type !== 'CallExpression' && test.type !== 'OptionalCallExpression') return new Map();
|
|
728
|
+
const name = dottedName(test.callee);
|
|
729
|
+
const method = test.callee.type === 'MemberExpression' ? propertyName(test.callee) : '';
|
|
730
|
+
const receiver = method ? test.callee.object : null;
|
|
731
|
+
const argument = test.arguments[0];
|
|
732
|
+
if (method === 'test' && outcome && receiver && (receiver.type === 'RegExpLiteral' || /(re|regex|pattern)$/i.test(dottedName(receiver)))) {
|
|
733
|
+
return all(argument, ['*']);
|
|
734
|
+
}
|
|
735
|
+
if ((method === 'includes' || method === 'has') && receiver && !names(receiver).size && outcome) {
|
|
736
|
+
return all(argument, ['*']); // One of a fixed set of allowed values.
|
|
737
|
+
}
|
|
738
|
+
if (method === 'includes' && receiver && names(receiver).size && argument && argument.type === 'StringLiteral' && !outcome) {
|
|
739
|
+
// A character or substring that isn't there: '..' and slashes only make a path safe.
|
|
740
|
+
return all(receiver, /\.\.|\/|\\/.test(argument.value) ? ['path'] : ['*']);
|
|
741
|
+
}
|
|
742
|
+
if (outcome && (VALIDATOR_CHECKS.test(name) || ['Number.isInteger', 'Number.isSafeInteger', 'isUUID'].includes(name))) {
|
|
743
|
+
return all(argument, ['*']);
|
|
744
|
+
}
|
|
745
|
+
return new Map();
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// Marks names as checked, as their taint carries which operations they're safe for.
|
|
749
|
+
check(checks) {
|
|
750
|
+
const before = new Map();
|
|
751
|
+
for (const [name, kinds] of checks) {
|
|
752
|
+
const source = this.scope.tainted.get(name);
|
|
753
|
+
if (!source) continue;
|
|
754
|
+
before.set(name, source);
|
|
755
|
+
this.scope.tainted.set(name, safeSource(source, kinds));
|
|
756
|
+
}
|
|
757
|
+
return before;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// Records what an object built from one of the project's classes keeps from its constructor.
|
|
761
|
+
remember(name, value) {
|
|
762
|
+
this.fieldInput.delete(name);
|
|
763
|
+
this.fieldRequests.delete(name);
|
|
764
|
+
if (!value || value.type !== 'NewExpression') return;
|
|
765
|
+
const found = this.file.classFor(dottedName(value.callee));
|
|
766
|
+
const constructor = found && found.info.methods.get('constructor');
|
|
767
|
+
if (!constructor) return;
|
|
768
|
+
const inputs = new Map();
|
|
769
|
+
const requests = new Set();
|
|
770
|
+
constructor.params.forEach((parameter, index) => {
|
|
771
|
+
const target = parameter.type === 'TSParameterProperty' ? parameter.parameter : parameter;
|
|
772
|
+
const inner = target.type === 'AssignmentPattern' ? target.left : target;
|
|
773
|
+
if (inner.type !== 'Identifier') return;
|
|
774
|
+
const argument = value.arguments[index];
|
|
775
|
+
const source = this.taint(argument);
|
|
776
|
+
if (source) inputs.set(inner.name, source);
|
|
777
|
+
else if (argument && this.scope.requests.has(dottedName(argument))) requests.add(inner.name);
|
|
778
|
+
if (parameter.type === 'TSParameterProperty' && source) inputs.set(`=${inner.name}`, source);
|
|
779
|
+
if (parameter.type === 'TSParameterProperty' && requests.has(inner.name)) requests.add(`=${inner.name}`);
|
|
780
|
+
});
|
|
781
|
+
const fields = new Map();
|
|
782
|
+
const requestFields = new Set();
|
|
783
|
+
for (const [key, source] of inputs) if (key.startsWith('=')) fields.set(key.slice(1), source);
|
|
784
|
+
for (const key of requests) if (key.startsWith('=')) requestFields.add(key.slice(1));
|
|
785
|
+
for (const statement of constructor.body.body) {
|
|
786
|
+
const expression = statement.type === 'ExpressionStatement' ? statement.expression : null;
|
|
787
|
+
if (!expression || expression.type !== 'AssignmentExpression' || expression.left.type !== 'MemberExpression'
|
|
788
|
+
|| expression.left.object.type !== 'ThisExpression' || expression.right.type !== 'Identifier') continue;
|
|
789
|
+
const field = propertyName(expression.left);
|
|
790
|
+
if (inputs.has(expression.right.name)) fields.set(field, inputs.get(expression.right.name));
|
|
791
|
+
else if (requests.has(expression.right.name)) requestFields.add(field);
|
|
792
|
+
}
|
|
793
|
+
if (fields.size) this.fieldInput.set(name, fields);
|
|
794
|
+
if (requestFields.size) this.fieldRequests.set(name, requestFields);
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
// Follows a known object or array through one method call; false when it isn't one.
|
|
798
|
+
trackCollection(node) {
|
|
799
|
+
if (node.callee.type !== 'MemberExpression' || node.callee.object.type !== 'Identifier') return false;
|
|
800
|
+
const name = node.callee.object.name;
|
|
801
|
+
const method = propertyName(node.callee);
|
|
802
|
+
const items = this.lists.get(name);
|
|
803
|
+
if (items) {
|
|
804
|
+
if (method === 'push') items.push(...node.arguments.map(argument => this.taint(argument)));
|
|
805
|
+
else if (method === 'unshift') items.unshift(...node.arguments.map(argument => this.taint(argument)));
|
|
806
|
+
else if (method === 'shift') items.shift();
|
|
807
|
+
else if (method === 'pop') items.pop();
|
|
808
|
+
else if (['splice', 'fill', 'copyWithin', 'reverse', 'sort'].includes(method)) this.degrade(name);
|
|
809
|
+
return true;
|
|
810
|
+
}
|
|
811
|
+
const values = this.keyed.get(name);
|
|
812
|
+
if (values && values.isMap) {
|
|
813
|
+
const key = this.constant(node.arguments[0]);
|
|
814
|
+
if (method === 'set' && key !== UNKNOWN) values.set(key, this.taint(node.arguments[1]));
|
|
815
|
+
else if (method === 'delete' && key !== UNKNOWN) values.delete(key);
|
|
816
|
+
else if (method === 'set' || method === 'clear') this.degrade(name);
|
|
817
|
+
return true;
|
|
818
|
+
}
|
|
819
|
+
return false;
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
degrade(name) {
|
|
823
|
+
const values = [...(this.keyed.get(name) || new Map()).values(), ...(this.lists.get(name) || [])];
|
|
824
|
+
this.keyed.delete(name);
|
|
825
|
+
this.lists.delete(name);
|
|
826
|
+
const source = values.reduce((found, value) => combine(found, value), null);
|
|
827
|
+
if (source) this.scope.tainted.set(name, source);
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
read(name, key) {
|
|
831
|
+
if (key === UNKNOWN) return UNKNOWN;
|
|
832
|
+
const values = this.keyed.get(name);
|
|
833
|
+
if (values) return values.has(key) ? values.get(key) : null;
|
|
834
|
+
const items = this.lists.get(name);
|
|
835
|
+
if (items && typeof key === 'number') return key >= 0 && key < items.length ? items[key] : null;
|
|
836
|
+
return UNKNOWN;
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
addParameterTypes(node) {
|
|
840
|
+
for (const parameter of node.params || []) {
|
|
841
|
+
const target = parameter.type === 'TSParameterProperty' ? parameter.parameter : parameter;
|
|
842
|
+
const inner = target.type === 'AssignmentPattern' ? target.left : target;
|
|
843
|
+
const type = inner.type === 'Identifier' ? typeName(inner.typeAnnotation) : '';
|
|
844
|
+
if (type) this.types.set(inner.name, type);
|
|
845
|
+
}
|
|
231
846
|
}
|
|
232
847
|
|
|
233
848
|
visit(node, nesting) {
|
|
234
849
|
if (!node || typeof node.type !== 'string') return;
|
|
235
850
|
switch (node.type) {
|
|
236
851
|
case 'VariableDeclarator':
|
|
852
|
+
if (node.id.type === 'Identifier') {
|
|
853
|
+
const type = constructed(node.init) || typeName(node.id.typeAnnotation);
|
|
854
|
+
if (type) this.types.set(node.id.name, type);
|
|
855
|
+
}
|
|
237
856
|
if (node.init) this.visit(node.init, nesting);
|
|
857
|
+
if (node.id.type === 'Identifier') this.track(node.id.name, node.init, nesting);
|
|
238
858
|
this.bind(node.id, node.init ? this.taint(node.init) : null, nesting, node.init);
|
|
239
859
|
return;
|
|
240
860
|
case 'AssignmentExpression':
|
|
241
861
|
this.visit(node.right, nesting);
|
|
862
|
+
if (node.left.type === 'Identifier') {
|
|
863
|
+
this.constants.delete(node.left.name);
|
|
864
|
+
if (node.operator === '=') this.track(node.left.name, node.right, nesting);
|
|
865
|
+
}
|
|
866
|
+
if (this.assignItem(node)) return;
|
|
867
|
+
this.checkAssignment(node);
|
|
242
868
|
if (node.operator === '=') this.bind(node.left, this.taint(node.right), nesting, node.right);
|
|
243
869
|
else {
|
|
244
870
|
const source = this.taint(node.right);
|
|
245
|
-
if (source) this.bind(node.left, source, nesting, node.right);
|
|
871
|
+
if (source) this.bind(node.left, combine(this.taint(node.left), source), nesting, node.right);
|
|
246
872
|
}
|
|
247
873
|
return;
|
|
874
|
+
case 'UpdateExpression':
|
|
875
|
+
if (node.argument.type === 'Identifier') this.constants.delete(node.argument.name);
|
|
876
|
+
return;
|
|
248
877
|
case 'CallExpression':
|
|
249
878
|
case 'OptionalCallExpression':
|
|
250
879
|
case 'NewExpression':
|
|
251
880
|
this.checkCall(node);
|
|
252
881
|
this.followHelper(node);
|
|
882
|
+
if (node.type !== 'NewExpression' && this.trackCollection(node)) {
|
|
883
|
+
eachChild(node, child => this.visit(child, nesting));
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
this.collect(node, nesting);
|
|
887
|
+
// A callback called with each value of a tainted receiver gets that value.
|
|
888
|
+
if (node.type !== 'NewExpression' && node.callee.type === 'MemberExpression' && CALLBACK_METHODS.has(propertyName(node.callee))) {
|
|
889
|
+
const source = this.taint(node.callee.object);
|
|
890
|
+
const callback = node.arguments[0];
|
|
891
|
+
if (source && callback && isFunction(callback)) this.callbackInput.set(callback, source);
|
|
892
|
+
}
|
|
253
893
|
eachChild(node, child => this.visit(child, nesting));
|
|
254
894
|
return;
|
|
895
|
+
case 'IfStatement': {
|
|
896
|
+
this.visit(node.test, nesting);
|
|
897
|
+
const known = this.constant(node.test);
|
|
898
|
+
if (known !== UNKNOWN) {
|
|
899
|
+
// Only one branch can run, and it always does.
|
|
900
|
+
this.visit(known ? node.consequent : node.alternate, nesting);
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
const failed = this.validated(node.test, false);
|
|
904
|
+
if (failed.size && !node.alternate && exits(node.consequent)) {
|
|
905
|
+
// A check that leaves when it fails: what follows only sees values that passed.
|
|
906
|
+
this.visit(node.consequent, nesting + 1);
|
|
907
|
+
this.check(failed);
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
const passed = this.validated(node.test, true);
|
|
911
|
+
if (passed.size && !exits(node.consequent)) {
|
|
912
|
+
const before = this.check(passed);
|
|
913
|
+
this.visit(node.consequent, nesting + 1);
|
|
914
|
+
for (const [name, source] of before) {
|
|
915
|
+
if (this.scope.tainted.get(name) === safeSource(source, passed.get(name))) this.scope.tainted.set(name, source);
|
|
916
|
+
}
|
|
917
|
+
this.visit(node.alternate, nesting + 1);
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
this.visit(node.consequent, nesting + 1);
|
|
921
|
+
this.visit(node.alternate, nesting + 1);
|
|
922
|
+
return;
|
|
923
|
+
}
|
|
924
|
+
case 'SwitchStatement': {
|
|
925
|
+
this.visit(node.discriminant, nesting);
|
|
926
|
+
const selector = this.constant(node.discriminant);
|
|
927
|
+
const labels = node.cases.map(item => (item.test ? this.constant(item.test) : 'default'));
|
|
928
|
+
if (selector === UNKNOWN || labels.includes(UNKNOWN)) {
|
|
929
|
+
for (const item of node.cases) this.visit(item, nesting + 1);
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
let start = labels.findIndex(label => label !== 'default' && label === selector);
|
|
933
|
+
if (start < 0) start = node.cases.findIndex(item => !item.test);
|
|
934
|
+
// Only the matching case runs, through to its break.
|
|
935
|
+
for (let index = start; start >= 0 && index < node.cases.length; index += 1) {
|
|
936
|
+
for (const statement of node.cases[index].consequent) this.visit(statement, nesting);
|
|
937
|
+
if (node.cases[index].consequent.some(statement => statement.type === 'BreakStatement' || exits(statement))) break;
|
|
938
|
+
}
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
case 'ReturnStatement':
|
|
942
|
+
if (node.argument) {
|
|
943
|
+
this.visit(node.argument, nesting);
|
|
944
|
+
this.returned = this.returned || this.taint(node.argument);
|
|
945
|
+
}
|
|
946
|
+
return;
|
|
255
947
|
case 'TaggedTemplateExpression':
|
|
256
948
|
eachChild(node, child => this.visit(child, nesting));
|
|
257
949
|
return;
|
|
258
950
|
case 'ForOfStatement':
|
|
259
951
|
case 'ForInStatement': {
|
|
952
|
+
for (const name of assignedNames(node.body)) this.constants.delete(name);
|
|
260
953
|
const source = this.taint(node.right);
|
|
261
954
|
const target = node.left.type === 'VariableDeclaration' ? node.left.declarations[0].id : node.left;
|
|
262
955
|
if (source) this.bind(target, source, nesting + 1, node.right);
|
|
@@ -264,11 +957,13 @@ class FunctionWalker {
|
|
|
264
957
|
this.visit(node.body, nesting + 1);
|
|
265
958
|
return;
|
|
266
959
|
}
|
|
267
|
-
case 'IfStatement':
|
|
268
960
|
case 'WhileStatement':
|
|
269
961
|
case 'DoWhileStatement':
|
|
270
962
|
case 'ForStatement':
|
|
271
|
-
|
|
963
|
+
// A loop may change what it assigns, so none of it stays known inside or after it.
|
|
964
|
+
for (const name of assignedNames(node)) this.constants.delete(name);
|
|
965
|
+
eachChild(node, child => this.visit(child, nesting + 1));
|
|
966
|
+
return;
|
|
272
967
|
case 'TryStatement':
|
|
273
968
|
case 'ConditionalExpression':
|
|
274
969
|
eachChild(node, child => this.visit(child, nesting + 1));
|
|
@@ -277,7 +972,19 @@ class FunctionWalker {
|
|
|
277
972
|
if (isFunction(node)) {
|
|
278
973
|
// Callbacks keep the request and values from the enclosing handler.
|
|
279
974
|
const nested = this.file.initialScope(node, this.scope);
|
|
280
|
-
const
|
|
975
|
+
const input = this.callbackInput.get(node);
|
|
976
|
+
const first = node.params[0];
|
|
977
|
+
if (input && first) {
|
|
978
|
+
if (first.type === 'Identifier') nested.tainted.set(first.name, input);
|
|
979
|
+
else this.bindInto(nested, first, input);
|
|
980
|
+
}
|
|
981
|
+
const walker = new FunctionWalker(this.file, nested, this.label, this.depth, this.active, this.entry);
|
|
982
|
+
walker.owner = this.owner;
|
|
983
|
+
walker.types = new Map(this.types);
|
|
984
|
+
walker.constants = new Map(this.constants);
|
|
985
|
+
walker.keyed = this.keyed;
|
|
986
|
+
walker.lists = this.lists;
|
|
987
|
+
walker.addParameterTypes(node);
|
|
281
988
|
walker.visit(node.body, 0);
|
|
282
989
|
return;
|
|
283
990
|
}
|
|
@@ -320,6 +1027,12 @@ class FunctionWalker {
|
|
|
320
1027
|
}
|
|
321
1028
|
if ((target.type === 'MemberExpression' || target.type === 'OptionalMemberExpression') && source) {
|
|
322
1029
|
const name = dottedName(target.object);
|
|
1030
|
+
const property = propertyName(target);
|
|
1031
|
+
if (name && this.scope.requests.has(name) && property && !REQUEST_PROPERTIES.has(property)) {
|
|
1032
|
+
// Middleware keeping input on the request for later handlers.
|
|
1033
|
+
if (!this.file.requestExtras.has(property)) this.file.requestExtras.set(property, `${name}.${property} (${baseSource(source)})`);
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
323
1036
|
if (name) this.scope.tainted.set(name.split('.')[0], source);
|
|
324
1037
|
}
|
|
325
1038
|
}
|
|
@@ -327,22 +1040,35 @@ class FunctionWalker {
|
|
|
327
1040
|
taint(node) {
|
|
328
1041
|
if (!node) return null;
|
|
329
1042
|
switch (node.type) {
|
|
330
|
-
case 'Identifier':
|
|
331
|
-
|
|
1043
|
+
case 'Identifier': {
|
|
1044
|
+
const source = this.scope.tainted.get(node.name);
|
|
1045
|
+
if (source) return source;
|
|
1046
|
+
const values = [...(this.keyed.get(node.name) || new Map()).values(), ...(this.lists.get(node.name) || [])];
|
|
1047
|
+
return values.reduce((found, value) => combine(found, value), null);
|
|
1048
|
+
}
|
|
332
1049
|
case 'MemberExpression':
|
|
333
1050
|
case 'OptionalMemberExpression': {
|
|
1051
|
+
const whole = dottedName(node);
|
|
1052
|
+
if (whole && this.scope.tainted.has(whole)) return this.scope.tainted.get(whole);
|
|
334
1053
|
const source = this.requestProperty(node);
|
|
335
1054
|
if (source) return source;
|
|
1055
|
+
if (node.object.type === 'Identifier') {
|
|
1056
|
+
const item = this.read(node.object.name, node.computed ? this.constant(node.property) : propertyName(node));
|
|
1057
|
+
if (item !== UNKNOWN) return item;
|
|
1058
|
+
}
|
|
336
1059
|
return withKey(this.taint(node.object), propertyName(node));
|
|
337
1060
|
}
|
|
338
1061
|
case 'TemplateLiteral':
|
|
339
1062
|
return this.first(node.expressions);
|
|
340
1063
|
case 'BinaryExpression':
|
|
341
|
-
return node.operator === '+' ? this.taint(node.left)
|
|
1064
|
+
return node.operator === '+' ? combine(this.taint(node.left), this.taint(node.right)) : null;
|
|
342
1065
|
case 'LogicalExpression':
|
|
343
|
-
return this.taint(node.left)
|
|
344
|
-
case 'ConditionalExpression':
|
|
345
|
-
|
|
1066
|
+
return combine(this.taint(node.left), this.taint(node.right));
|
|
1067
|
+
case 'ConditionalExpression': {
|
|
1068
|
+
const known = this.constant(node.test);
|
|
1069
|
+
if (known !== UNKNOWN) return this.taint(known ? node.consequent : node.alternate);
|
|
1070
|
+
return combine(this.taint(node.consequent), this.taint(node.alternate));
|
|
1071
|
+
}
|
|
346
1072
|
case 'AwaitExpression':
|
|
347
1073
|
return this.taint(node.argument);
|
|
348
1074
|
case 'TSAsExpression':
|
|
@@ -371,6 +1097,9 @@ class FunctionWalker {
|
|
|
371
1097
|
const property = propertyName(node);
|
|
372
1098
|
if (!name || !property) return null;
|
|
373
1099
|
if (this.scope.requests.has(name) && REQUEST_PROPERTIES.has(property)) return `${name}.${property}`;
|
|
1100
|
+
if (this.scope.requests.has(name) && this.file.requestExtras.has(property)) {
|
|
1101
|
+
return this.file.requestExtras.get(property);
|
|
1102
|
+
}
|
|
374
1103
|
if (this.scope.contexts.has(name) && CONTEXT_PROPERTIES.has(property) && property !== 'request') return `${name}.${property}`;
|
|
375
1104
|
const parts = name.split('.');
|
|
376
1105
|
if (parts.length === 2 && this.scope.contexts.has(parts[0]) && parts[1] === 'request' && REQUEST_PROPERTIES.has(property)) {
|
|
@@ -380,17 +1109,87 @@ class FunctionWalker {
|
|
|
380
1109
|
}
|
|
381
1110
|
|
|
382
1111
|
first(nodes) {
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
1112
|
+
let found = null;
|
|
1113
|
+
for (const node of nodes) found = combine(found, this.taint(node));
|
|
1114
|
+
return found;
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
// Records known values, and objects and arrays to follow by key and position.
|
|
1118
|
+
track(name, value, nesting) {
|
|
1119
|
+
const known = this.constant(value);
|
|
1120
|
+
if (known !== UNKNOWN && nesting === 0 && known !== null && typeof known !== 'object') this.constants.set(name, known);
|
|
1121
|
+
else this.constants.delete(name);
|
|
1122
|
+
this.keyed.delete(name);
|
|
1123
|
+
this.lists.delete(name);
|
|
1124
|
+
this.bare.delete(name);
|
|
1125
|
+
this.remember(name, value);
|
|
1126
|
+
if (!value) return;
|
|
1127
|
+
if (value.type === 'ObjectExpression' && value.properties.every(item => item.type === 'ObjectProperty' && !item.computed)) {
|
|
1128
|
+
this.keyed.set(name, new Map(value.properties.map(item => [item.key.name || item.key.value, this.taint(item.value)])));
|
|
1129
|
+
} else if (value.type === 'ArrayExpression' && value.elements.every(item => item && item.type !== 'SpreadElement')) {
|
|
1130
|
+
this.lists.set(name, value.elements.map(item => this.taint(item)));
|
|
1131
|
+
} else if (value.type === 'NewExpression' && dottedName(value.callee) === 'Map' && !value.arguments.length) {
|
|
1132
|
+
const values = new Map();
|
|
1133
|
+
values.isMap = true;
|
|
1134
|
+
this.keyed.set(name, values);
|
|
1135
|
+
} else if (value.type === 'CallExpression' && dottedName(value.callee) === 'Object.create'
|
|
1136
|
+
&& value.arguments[0] && value.arguments[0].type === 'NullLiteral') {
|
|
1137
|
+
this.bare.add(name);
|
|
386
1138
|
}
|
|
387
|
-
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
// values.key = x or items[0] = x on a followed object or array.
|
|
1142
|
+
assignItem(node) {
|
|
1143
|
+
if (node.operator !== '=' || node.left.type !== 'MemberExpression' || node.left.object.type !== 'Identifier') return false;
|
|
1144
|
+
const name = node.left.object.name;
|
|
1145
|
+
const key = node.left.computed ? this.constant(node.left.property) : propertyName(node.left);
|
|
1146
|
+
const values = this.keyed.get(name);
|
|
1147
|
+
if (values && !values.isMap && key !== UNKNOWN) {
|
|
1148
|
+
values.set(key, this.taint(node.right));
|
|
1149
|
+
return true;
|
|
1150
|
+
}
|
|
1151
|
+
const items = this.lists.get(name);
|
|
1152
|
+
if (items && typeof key === 'number' && key >= 0 && key <= items.length) {
|
|
1153
|
+
items[key] = this.taint(node.right);
|
|
1154
|
+
return true;
|
|
1155
|
+
}
|
|
1156
|
+
if (values || items) this.degrade(name);
|
|
1157
|
+
return false;
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
bindInto(scope, pattern, source) {
|
|
1161
|
+
if (pattern.type === 'Identifier') scope.tainted.set(pattern.name, source);
|
|
1162
|
+
else if (pattern.type === 'ObjectPattern') {
|
|
1163
|
+
for (const property of pattern.properties) {
|
|
1164
|
+
const inner = property.type === 'ObjectProperty' ? (property.value.type === 'AssignmentPattern' ? property.value.left : property.value) : property.argument;
|
|
1165
|
+
if (inner) this.bindInto(scope, inner, property.type === 'ObjectProperty' ? withKey(source, property.key.name || property.key.value) : source);
|
|
1166
|
+
}
|
|
1167
|
+
} else if (pattern.type === 'ArrayPattern') {
|
|
1168
|
+
for (const element of pattern.elements) if (element) this.bindInto(scope, element, source);
|
|
1169
|
+
} else if (pattern.type === 'AssignmentPattern') this.bindInto(scope, pattern.left, source);
|
|
388
1170
|
}
|
|
389
1171
|
|
|
390
1172
|
callTaint(node) {
|
|
391
1173
|
const name = dottedName(node.callee);
|
|
392
1174
|
if (SANITIZERS.has(name)) return null;
|
|
1175
|
+
if (KIND_SANITIZERS.has(name)) return safeSource(this.first(node.arguments), KIND_SANITIZERS.get(name));
|
|
393
1176
|
if (PASSTHROUGH_FUNCTIONS.has(name)) return this.first(node.arguments);
|
|
1177
|
+
const method = node.callee.type === 'MemberExpression' ? propertyName(node.callee) : '';
|
|
1178
|
+
if (['parse', 'parseAsync', 'validateSync'].includes(method) && this.file.source
|
|
1179
|
+
&& SAFE_SCHEMA.test(this.file.source.slice(node.callee.object.start, node.callee.object.end))
|
|
1180
|
+
&& !/\b(?:object|string|array|any|unknown|record)\(/.test(this.file.source.slice(node.callee.object.start, node.callee.object.end).replace(/string\(\)\.(?:uuid|email|datetime|date)\(/g, ''))) {
|
|
1181
|
+
return null; // A schema that only lets numbers, booleans, UUIDs or fixed values through.
|
|
1182
|
+
}
|
|
1183
|
+
if (['parse', 'parseAsync', 'safeParse', 'validate', 'validateAsync', 'validateSync'].includes(method)
|
|
1184
|
+
&& node.callee.object.type !== 'Identifier' || (['parse', 'parseAsync', 'validateSync'].includes(method)
|
|
1185
|
+
&& /schema$/i.test(dottedName(node.callee.object)))) {
|
|
1186
|
+
const value = this.first(node.arguments);
|
|
1187
|
+
if (value) return value; // Validated against a schema that still lets text through.
|
|
1188
|
+
}
|
|
1189
|
+
if (node.callee.type === 'MemberExpression' && node.callee.object.type === 'Identifier' && ['get', 'at'].includes(method)) {
|
|
1190
|
+
const item = this.read(node.callee.object.name, method === 'at' ? this.constant(node.arguments[0]) : this.constant(node.arguments[0]));
|
|
1191
|
+
if (item !== UNKNOWN) return item;
|
|
1192
|
+
}
|
|
394
1193
|
if (node.callee.type === 'MemberExpression' || node.callee.type === 'OptionalMemberExpression') {
|
|
395
1194
|
const receiver = dottedName(node.callee.object);
|
|
396
1195
|
const method = propertyName(node.callee);
|
|
@@ -404,23 +1203,50 @@ class FunctionWalker {
|
|
|
404
1203
|
if (PASSTHROUGH_METHODS.has(method)) {
|
|
405
1204
|
return this.taint(node.callee.object) || (method === 'concat' || method === 'replace' || method === 'join' ? this.first(node.arguments) : null);
|
|
406
1205
|
}
|
|
1206
|
+
// URLSearchParams, FormData and Headers read back what they hold.
|
|
1207
|
+
if (['get', 'getAll'].includes(method) && this.taint(node.callee.object)) {
|
|
1208
|
+
const key = node.arguments[0];
|
|
1209
|
+
return withKey(this.taint(node.callee.object), key && key.type === 'StringLiteral' ? key.value : '');
|
|
1210
|
+
}
|
|
407
1211
|
}
|
|
408
|
-
return
|
|
1212
|
+
return this.followHelper(node);
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
// A value added to an array, set or map taints the collection, as in parts.push(req.query.q).
|
|
1216
|
+
collect(node, nesting) {
|
|
1217
|
+
if (node.type === 'NewExpression' || (node.callee.type !== 'MemberExpression' && node.callee.type !== 'OptionalMemberExpression')) return;
|
|
1218
|
+
if (!COLLECTION_ADDS.has(propertyName(node.callee))) return;
|
|
1219
|
+
const source = this.first(node.arguments);
|
|
1220
|
+
if (source) this.bind(node.callee.object, source, nesting, null);
|
|
409
1221
|
}
|
|
410
1222
|
|
|
1223
|
+
// Walks a project function that receives input, and returns the input its result carries.
|
|
411
1224
|
followHelper(node) {
|
|
412
|
-
if (this.
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
1225
|
+
if (this.helperReturns.has(node)) return this.helperReturns.get(node);
|
|
1226
|
+
this.helperReturns.set(node, null);
|
|
1227
|
+
if (this.depth >= MAX_HELPER_DEPTH || node.type === 'NewExpression') return null;
|
|
1228
|
+
const helper = this.file.findFunction(node.callee, this);
|
|
1229
|
+
if (!helper) return null;
|
|
416
1230
|
const passed = new Map();
|
|
417
|
-
(helper.params || []).forEach((parameter, index) => {
|
|
1231
|
+
(helper.node.params || []).forEach((parameter, index) => {
|
|
1232
|
+
const target = parameter.type === 'AssignmentPattern' ? parameter.left : parameter;
|
|
418
1233
|
const source = this.taint(node.arguments[index]);
|
|
419
|
-
if (source &&
|
|
1234
|
+
if (source && target.type === 'Identifier') passed.set(target.name, source);
|
|
420
1235
|
});
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
1236
|
+
const requests = new Set();
|
|
1237
|
+
// An object's method also reads what its constructor kept, as this.<field>.
|
|
1238
|
+
if (node.callee.type === 'MemberExpression' && node.callee.object.type === 'Identifier') {
|
|
1239
|
+
const variable = node.callee.object.name;
|
|
1240
|
+
for (const [field, source] of this.fieldInput.get(variable) || []) passed.set(`this.${field}`, source);
|
|
1241
|
+
for (const field of this.fieldRequests.get(variable) || []) requests.add(`this.${field}`);
|
|
1242
|
+
}
|
|
1243
|
+
if (!passed.size && !requests.size) return null;
|
|
1244
|
+
const scope = { tainted: passed, requests, contexts: new Set() };
|
|
1245
|
+
const name = propertyName(node.callee) || dottedName(node.callee).split('.').pop();
|
|
1246
|
+
const entry = helper.file === this.file ? this.entry : (this.entry || this.file.filename);
|
|
1247
|
+
const returned = helper.file.analyze(helper.node, scope, `${this.label} -> ${name}`, this.depth + 1, this.active, entry);
|
|
1248
|
+
this.helperReturns.set(node, returned);
|
|
1249
|
+
return returned;
|
|
424
1250
|
}
|
|
425
1251
|
|
|
426
1252
|
checkCall(node) {
|
|
@@ -431,6 +1257,12 @@ class FunctionWalker {
|
|
|
431
1257
|
const first = node.arguments[0];
|
|
432
1258
|
const source = this.taint(first);
|
|
433
1259
|
|
|
1260
|
+
// A method of one of the project's classes is followed into, not guessed at by its name.
|
|
1261
|
+
if (method && this.file.findMethod(node.callee, this)) return;
|
|
1262
|
+
if (name === 'RegExp' && source) {
|
|
1263
|
+
this.report(node, 'redos', node.type === 'NewExpression' ? 'new RegExp' : 'RegExp', source, 'medium');
|
|
1264
|
+
return;
|
|
1265
|
+
}
|
|
434
1266
|
if (node.type === 'NewExpression') {
|
|
435
1267
|
if (name === 'Function') {
|
|
436
1268
|
const code = this.first(node.arguments);
|
|
@@ -438,6 +1270,42 @@ class FunctionWalker {
|
|
|
438
1270
|
}
|
|
439
1271
|
return;
|
|
440
1272
|
}
|
|
1273
|
+
const head = receiver.split('.')[0];
|
|
1274
|
+
if (method && XSS_METHODS.has(method) && RESPONSE_NAMES.has(head) && source && this.isText(first, source)) {
|
|
1275
|
+
this.report(node, 'xss', name || `res.${method}`, source, 'medium');
|
|
1276
|
+
return;
|
|
1277
|
+
}
|
|
1278
|
+
if (method && (method === 'redirect' || method === 'location') && (RESPONSE_NAMES.has(head) || this.scope.contexts.has(head) || head === 'reply')) {
|
|
1279
|
+
const target = this.taint(node.arguments[node.arguments.length - 1]);
|
|
1280
|
+
if (target) this.report(node, 'redirect', name || method, target, 'medium');
|
|
1281
|
+
return;
|
|
1282
|
+
}
|
|
1283
|
+
if (MERGE_FUNCTIONS.has(name) || (method && ['merge', 'mergeWith', 'defaultsDeep', 'set', 'setWith'].includes(method) && /^(_|lodash)$/.test(receiver))) {
|
|
1284
|
+
const value = this.first(node.arguments.slice(1));
|
|
1285
|
+
if (value && (name !== 'set' && method !== 'set' || this.taint(node.arguments[1]))) {
|
|
1286
|
+
this.report(node, 'prototype', name || method, value, 'medium');
|
|
1287
|
+
}
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
if ((XPATH_FUNCTIONS.has(name) || (method === 'evaluate' && /(doc|document|xpath)$/i.test(receiver))) && source) {
|
|
1291
|
+
this.report(node, 'xpath', name, source, 'high');
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
1294
|
+
if (method === 'search' && /(client|ldap)$/i.test(receiver) && node.arguments[1]) {
|
|
1295
|
+
const options = node.arguments[1];
|
|
1296
|
+
const filter = options.type === 'ObjectExpression'
|
|
1297
|
+
? this.taint((options.properties.find(item => item.key && (item.key.name || item.key.value) === 'filter') || {}).value)
|
|
1298
|
+
: this.taint(options);
|
|
1299
|
+
if (filter) this.report(node, 'ldap', name, filter, 'high');
|
|
1300
|
+
return;
|
|
1301
|
+
}
|
|
1302
|
+
if (XML_FUNCTIONS.has(name) && source) {
|
|
1303
|
+
const options = node.arguments[1];
|
|
1304
|
+
const entities = options && options.type === 'ObjectExpression' && options.properties.some(item =>
|
|
1305
|
+
item.key && (item.key.name || item.key.value) === 'noent' && item.value.type === 'BooleanLiteral' && item.value.value);
|
|
1306
|
+
if (entities) this.report(node, 'xxe', name, source, 'high');
|
|
1307
|
+
return;
|
|
1308
|
+
}
|
|
441
1309
|
if (!source) {
|
|
442
1310
|
if (SHELL_FUNCTIONS.has(name) && this.spawnUsesShell(node)) {
|
|
443
1311
|
const value = this.first(node.arguments.slice(0, 2));
|
|
@@ -470,6 +1338,41 @@ class FunctionWalker {
|
|
|
470
1338
|
}
|
|
471
1339
|
}
|
|
472
1340
|
|
|
1341
|
+
// True for text sent as HTML: built strings and single request values, not whole objects sent as JSON.
|
|
1342
|
+
isText(node, source) {
|
|
1343
|
+
if (!node) return false;
|
|
1344
|
+
if (['TemplateLiteral', 'BinaryExpression', 'StringLiteral'].includes(node.type)) return true;
|
|
1345
|
+
if (node.type === 'CallExpression' && node.callee.type === 'MemberExpression') {
|
|
1346
|
+
return ['concat', 'join', 'replace', 'toString', 'trim', 'toUpperCase', 'toLowerCase'].includes(propertyName(node.callee));
|
|
1347
|
+
}
|
|
1348
|
+
return /\.(?:body|cookies|headers|params|query)\.[^.]+$|\('[^']*'\)$|^websocket|^graphql args\.|^trpc input\./.test(baseSource(source));
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
// obj[key] = value with a key from input can set __proto__ and change every object.
|
|
1352
|
+
checkAssignment(node) {
|
|
1353
|
+
const target = node.left;
|
|
1354
|
+
if (target.type !== 'MemberExpression') return;
|
|
1355
|
+
// ctx.body = text in Koa is sent as HTML.
|
|
1356
|
+
const body = dottedName(target);
|
|
1357
|
+
if (body && this.scope.contexts.has(body.split('.')[0]) && body.endsWith('.body')) {
|
|
1358
|
+
const source = this.taint(node.right);
|
|
1359
|
+
if (source && this.isText(node.right, source)) this.report(node, 'xss', body, source, 'medium');
|
|
1360
|
+
return;
|
|
1361
|
+
}
|
|
1362
|
+
if (!target.computed) return;
|
|
1363
|
+
const object = target.object.type === 'MemberExpression' && target.object.computed ? target.object : null;
|
|
1364
|
+
const keys = [target.property, ...(object ? [object.property] : [])];
|
|
1365
|
+
const root = dottedName(object ? object.object : target.object);
|
|
1366
|
+
if (this.bare.has(root) || this.lists.has(root)) return;
|
|
1367
|
+
for (const key of keys) {
|
|
1368
|
+
const source = this.taint(key);
|
|
1369
|
+
if (source && key.type !== 'NumericLiteral' && this.constant(key) === UNKNOWN) {
|
|
1370
|
+
this.report(node, 'prototype', `${root || 'object'}[...] =`, source, 'medium');
|
|
1371
|
+
return;
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
|
|
473
1376
|
isRequestLike(receiver) {
|
|
474
1377
|
const head = receiver.split('.')[0];
|
|
475
1378
|
return this.scope.requests.has(head) || this.scope.contexts.has(head);
|
|
@@ -485,7 +1388,7 @@ class FunctionWalker {
|
|
|
485
1388
|
}
|
|
486
1389
|
|
|
487
1390
|
report(node, sink, call, source, confidence) {
|
|
488
|
-
this.file.record(node, this.label, sink, call, source, confidence);
|
|
1391
|
+
this.file.record(node, this.label, sink, call, source, confidence, this.entry);
|
|
489
1392
|
}
|
|
490
1393
|
}
|
|
491
1394
|
|
|
@@ -501,11 +1404,170 @@ function parseSource(source) {
|
|
|
501
1404
|
});
|
|
502
1405
|
}
|
|
503
1406
|
|
|
1407
|
+
// Runs every analyzer, then again if middleware was found keeping input on the request, since
|
|
1408
|
+
// the handlers that read it may have run first.
|
|
1409
|
+
function runAll(analyzers, extras, summaries) {
|
|
1410
|
+
for (let pass = 0; pass < 3; pass += 1) {
|
|
1411
|
+
const before = extras.size;
|
|
1412
|
+
for (const analyzer of analyzers) analyzer.run();
|
|
1413
|
+
if (extras.size === before) return;
|
|
1414
|
+
summaries.clear();
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
|
|
504
1418
|
function analyzeSource(source, filename = '<source>') {
|
|
505
|
-
const
|
|
1419
|
+
const analyzer = new FileAnalyzer(parseSource(source), filename, '', null, source);
|
|
1420
|
+
analyzer.summaries = new Map();
|
|
1421
|
+
runAll([analyzer], analyzer.requestExtras, analyzer.summaries);
|
|
1422
|
+
const findings = [...analyzer.findings.values()];
|
|
506
1423
|
return findings.sort((a, b) => a.line - b.line || a.sink.localeCompare(b.sink));
|
|
507
1424
|
}
|
|
508
1425
|
|
|
1426
|
+
// Reads JSON that may have comments and trailing commas, as tsconfig.json may.
|
|
1427
|
+
function readLooseJson(file) {
|
|
1428
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
1429
|
+
let out = '';
|
|
1430
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
1431
|
+
const char = text[index];
|
|
1432
|
+
if (char === '"') {
|
|
1433
|
+
const end = /"(?:[^"\\\n]|\\.)*"/y;
|
|
1434
|
+
end.lastIndex = index;
|
|
1435
|
+
const match = end.exec(text);
|
|
1436
|
+
if (!match) return null;
|
|
1437
|
+
out += match[0];
|
|
1438
|
+
index += match[0].length - 1;
|
|
1439
|
+
} else if (char === '/' && text[index + 1] === '/') {
|
|
1440
|
+
while (index < text.length && text[index] !== '\n') index += 1;
|
|
1441
|
+
} else if (char === '/' && text[index + 1] === '*') {
|
|
1442
|
+
const close = text.indexOf('*/', index + 2);
|
|
1443
|
+
index = close < 0 ? text.length : close + 1;
|
|
1444
|
+
} else {
|
|
1445
|
+
out += char;
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
try {
|
|
1449
|
+
return JSON.parse(out.replace(/,(\s*[}\]])/g, '$1'));
|
|
1450
|
+
} catch (_error) {
|
|
1451
|
+
return null;
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
// Maps import specifiers to scanned files, as Node, TypeScript and bundlers do: relative paths,
|
|
1456
|
+
// tsconfig.json or jsconfig.json paths and baseUrl, and packages in the scanned folder.
|
|
1457
|
+
class ModuleResolver {
|
|
1458
|
+
constructor(root, files) {
|
|
1459
|
+
this.root = root;
|
|
1460
|
+
this.files = files;
|
|
1461
|
+
this.configs = new Map();
|
|
1462
|
+
this.packages = new Map();
|
|
1463
|
+
this.findPackages(root);
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
findPackages(directory) {
|
|
1467
|
+
let entries;
|
|
1468
|
+
try {
|
|
1469
|
+
entries = fs.readdirSync(directory, { withFileTypes: true });
|
|
1470
|
+
} catch (_error) {
|
|
1471
|
+
return;
|
|
1472
|
+
}
|
|
1473
|
+
for (const entry of entries) {
|
|
1474
|
+
const full = path.join(directory, entry.name);
|
|
1475
|
+
if (entry.isDirectory() && !SKIPPED_DIRECTORIES.has(entry.name) && !entry.name.startsWith('.')) this.findPackages(full);
|
|
1476
|
+
else if (entry.isFile() && entry.name === 'package.json') {
|
|
1477
|
+
const manifest = readLooseJson(full);
|
|
1478
|
+
if (!manifest || typeof manifest.name !== 'string' || this.packages.has(manifest.name)) continue;
|
|
1479
|
+
let main = manifest.exports;
|
|
1480
|
+
if (main && typeof main === 'object' && !Array.isArray(main)) main = main['.'] || main;
|
|
1481
|
+
if (main && typeof main === 'object' && !Array.isArray(main)) main = main.import || main.require || main.default;
|
|
1482
|
+
this.packages.set(manifest.name, { directory, main: [main, manifest.module, manifest.main].filter(item => typeof item === 'string') });
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
// The nearest tsconfig.json or jsconfig.json, with extends followed.
|
|
1488
|
+
configFor(directory) {
|
|
1489
|
+
if (this.configs.has(directory)) return this.configs.get(directory);
|
|
1490
|
+
let config = null;
|
|
1491
|
+
for (const name of ['tsconfig.json', 'jsconfig.json']) {
|
|
1492
|
+
const file = path.join(directory, name);
|
|
1493
|
+
if (fs.existsSync(file)) {
|
|
1494
|
+
config = this.loadConfig(file, 0);
|
|
1495
|
+
break;
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
const parent = path.dirname(directory);
|
|
1499
|
+
if (!config && parent !== directory && (directory + path.sep).startsWith(this.root + path.sep) && directory !== this.root) {
|
|
1500
|
+
config = this.configFor(parent);
|
|
1501
|
+
}
|
|
1502
|
+
this.configs.set(directory, config);
|
|
1503
|
+
return config;
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
loadConfig(file, depth) {
|
|
1507
|
+
const data = readLooseJson(file);
|
|
1508
|
+
if (!data || typeof data !== 'object') return null;
|
|
1509
|
+
const directory = path.dirname(file);
|
|
1510
|
+
let inherited = { baseUrl: '', paths: [] };
|
|
1511
|
+
if (typeof data.extends === 'string' && data.extends.startsWith('.') && depth < 3) {
|
|
1512
|
+
const parent = path.resolve(directory, data.extends);
|
|
1513
|
+
inherited = this.loadConfig(parent.endsWith('.json') ? parent : `${parent}.json`, depth + 1) || inherited;
|
|
1514
|
+
}
|
|
1515
|
+
const options = data.compilerOptions || {};
|
|
1516
|
+
const baseUrl = typeof options.baseUrl === 'string' ? path.resolve(directory, options.baseUrl) : inherited.baseUrl;
|
|
1517
|
+
if (!options.paths || typeof options.paths !== 'object') return { baseUrl, paths: inherited.paths };
|
|
1518
|
+
const from = baseUrl || directory;
|
|
1519
|
+
const paths = Object.entries(options.paths)
|
|
1520
|
+
.filter(([, targets]) => Array.isArray(targets))
|
|
1521
|
+
.map(([pattern, targets]) => [pattern, targets.filter(item => typeof item === 'string').map(item => path.resolve(from, item))]);
|
|
1522
|
+
return { baseUrl, paths };
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
file(base) {
|
|
1526
|
+
const stem = base.replace(/\.[cm]?js$/, '');
|
|
1527
|
+
const candidates = [base];
|
|
1528
|
+
for (const extension of SOURCE_EXTENSIONS) candidates.push(`${stem}${extension}`);
|
|
1529
|
+
for (const extension of SOURCE_EXTENSIONS) candidates.push(path.join(base, `index${extension}`));
|
|
1530
|
+
return candidates.find(item => this.files.has(item)) || null;
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
resolve(fromFile, spec) {
|
|
1534
|
+
if (typeof spec !== 'string' || !spec) return null;
|
|
1535
|
+
if (spec.startsWith('.')) return this.file(path.resolve(path.dirname(fromFile), spec));
|
|
1536
|
+
const config = this.configFor(path.dirname(fromFile));
|
|
1537
|
+
if (config) {
|
|
1538
|
+
for (const [pattern, targets] of config.paths) {
|
|
1539
|
+
const star = pattern.indexOf('*');
|
|
1540
|
+
let rest = null;
|
|
1541
|
+
if (star < 0 && pattern === spec) rest = '';
|
|
1542
|
+
else if (star >= 0 && spec.startsWith(pattern.slice(0, star)) && spec.endsWith(pattern.slice(star + 1))
|
|
1543
|
+
&& spec.length >= pattern.length - 1) {
|
|
1544
|
+
rest = spec.slice(star, spec.length - (pattern.length - star - 1));
|
|
1545
|
+
}
|
|
1546
|
+
if (rest === null) continue;
|
|
1547
|
+
for (const target of targets) {
|
|
1548
|
+
const found = this.file(target.replace('*', rest));
|
|
1549
|
+
if (found) return found;
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
if (config.baseUrl) {
|
|
1553
|
+
const found = this.file(path.join(config.baseUrl, spec));
|
|
1554
|
+
if (found) return found;
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
const parts = spec.split('/');
|
|
1558
|
+
const name = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
|
|
1559
|
+
const workspace = this.packages.get(name);
|
|
1560
|
+
if (!workspace) return null;
|
|
1561
|
+
const subpath = spec.slice(name.length + 1);
|
|
1562
|
+
if (subpath) return this.file(path.join(workspace.directory, subpath)) || this.file(path.join(workspace.directory, 'src', subpath));
|
|
1563
|
+
for (const main of workspace.main) {
|
|
1564
|
+
const found = this.file(path.resolve(workspace.directory, main));
|
|
1565
|
+
if (found) return found;
|
|
1566
|
+
}
|
|
1567
|
+
return this.file(path.join(workspace.directory, 'index')) || this.file(path.join(workspace.directory, 'src', 'index'));
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
|
|
509
1571
|
function isTestFile(name) {
|
|
510
1572
|
return /\.(test|spec)\.[cm]?[jt]sx?$/.test(name);
|
|
511
1573
|
}
|
|
@@ -532,7 +1594,8 @@ function analyzePath(target = '.', options = {}) {
|
|
|
532
1594
|
if (!fs.existsSync(target)) throw new Error(`Path not found: ${target}`);
|
|
533
1595
|
const findings = [];
|
|
534
1596
|
const errors = [];
|
|
535
|
-
|
|
1597
|
+
// Every file is parsed first, so calls into other project files can be followed.
|
|
1598
|
+
const parsed = [];
|
|
536
1599
|
for (const file of collectFiles(target, Boolean(options.includeTests), [])) {
|
|
537
1600
|
const display = file.split(path.sep).join('/');
|
|
538
1601
|
try {
|
|
@@ -540,14 +1603,98 @@ function analyzePath(target = '.', options = {}) {
|
|
|
540
1603
|
errors.push({ file: display, error: 'File is too large to analyze' });
|
|
541
1604
|
continue;
|
|
542
1605
|
}
|
|
543
|
-
|
|
544
|
-
|
|
1606
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
1607
|
+
parsed.push({ full: path.resolve(file), display, ast: parseSource(text), text });
|
|
545
1608
|
} catch (error) {
|
|
546
1609
|
errors.push({ file: display, error: String(error.message || error) });
|
|
547
1610
|
}
|
|
548
1611
|
}
|
|
549
|
-
|
|
550
|
-
|
|
1612
|
+
const project = new Map(parsed.map(item => [item.full, null]));
|
|
1613
|
+
const root = path.resolve(fs.statSync(target).isDirectory() ? target : path.dirname(target));
|
|
1614
|
+
project.resolver = new ModuleResolver(root, new Set(project.keys()));
|
|
1615
|
+
project.requestExtras = new Map();
|
|
1616
|
+
project.summaries = new Map();
|
|
1617
|
+
project.recordings = [];
|
|
1618
|
+
for (const item of parsed) project.set(item.full, new FileAnalyzer(item.ast, item.display, item.full, project, item.text));
|
|
1619
|
+
const filesScanned = parsed.length;
|
|
1620
|
+
runAll([...project.values()], project.requestExtras, project.summaries);
|
|
1621
|
+
// One at a time: spreading a large project's findings into push() overflows the call stack.
|
|
1622
|
+
const lines = new Map(parsed.map(item => [item.display, item.text.split(/\r?\n/)]));
|
|
1623
|
+
let suppressed = 0;
|
|
1624
|
+
for (const analyzer of project.values()) {
|
|
1625
|
+
for (const finding of analyzer.findings.values()) {
|
|
1626
|
+
if (ignored(lines.get(finding.file) || [], finding.line, finding.sink)) suppressed += 1;
|
|
1627
|
+
else findings.push(finding);
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
findings.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.sink.localeCompare(b.sink)
|
|
1631
|
+
|| a.function.localeCompare(b.function));
|
|
1632
|
+
const report = { schema_version: SCHEMA_VERSION, language: 'javascript', files_scanned: filesScanned, findings, errors };
|
|
1633
|
+
if (suppressed) report.suppressed = suppressed;
|
|
1634
|
+
return report;
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1637
|
+
// aiwaf: ignore, or aiwaf: ignore[sql, xss], on a finding's line or the line before it.
|
|
1638
|
+
const IGNORE = /aiwaf[:-]\s*ignore(?:\[([a-z_,\s]+)\])?/i;
|
|
1639
|
+
|
|
1640
|
+
function ignored(lines, line, sink) {
|
|
1641
|
+
for (const number of [line, line - 1]) {
|
|
1642
|
+
const match = number >= 1 && number <= lines.length ? IGNORE.exec(lines[number - 1]) : null;
|
|
1643
|
+
if (match && (!match[1] || match[1].split(',').map(item => item.trim().toLowerCase()).includes(sink))) return true;
|
|
1644
|
+
}
|
|
1645
|
+
return false;
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
/** Identifies a finding across runs, without its line, which moves as code changes. */
|
|
1649
|
+
function fingerprint(finding) {
|
|
1650
|
+
const parts = ['file', 'sink', 'call', 'function', 'source'].map(key => String(finding[key] ?? ''));
|
|
1651
|
+
return crypto.createHash('sha256').update(parts.join('\0')).digest('hex').slice(0, 32);
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
/** Leaves out findings already in an earlier report, so CI fails only on new ones. */
|
|
1655
|
+
function applyBaseline(report, baseline) {
|
|
1656
|
+
const known = new Set((baseline.findings || []).map(fingerprint));
|
|
1657
|
+
const findings = report.findings.filter(finding => !known.has(fingerprint(finding)));
|
|
1658
|
+
const result = { ...report, findings };
|
|
1659
|
+
if (findings.length !== report.findings.length) result.baselined = report.findings.length - findings.length;
|
|
1660
|
+
return result;
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
const SINK_TITLES = {
|
|
1664
|
+
code: 'Code injection', command: 'Command injection', deserialization: 'Unsafe deserialization', ldap: 'LDAP injection',
|
|
1665
|
+
nosql: 'NoSQL injection', path: 'Path traversal', prototype: 'Prototype pollution', redirect: 'Open redirect',
|
|
1666
|
+
redos: 'Regular expression denial of service', sql: 'SQL injection', ssrf: 'Server-side request forgery',
|
|
1667
|
+
template: 'Template injection', xpath: 'XPath injection', xss: 'Cross-site scripting', xxe: 'XML external entity expansion'
|
|
1668
|
+
};
|
|
1669
|
+
|
|
1670
|
+
/** The report as SARIF 2.1.0, for GitHub code scanning and other tools that read it. */
|
|
1671
|
+
function toSarif(report) {
|
|
1672
|
+
const sinks = [...new Set(report.findings.map(finding => finding.sink))].sort();
|
|
1673
|
+
const title = sink => SINK_TITLES[sink] || sink;
|
|
1674
|
+
const rules = sinks.map(sink => ({
|
|
1675
|
+
id: `aiwaf.${sink}`,
|
|
1676
|
+
name: title(sink).replace(/(^|[\s-])(\w)/g, (_match, _space, letter) => letter.toUpperCase()).replace(/[\s-]/g, ''),
|
|
1677
|
+
shortDescription: { text: title(sink) },
|
|
1678
|
+
fullDescription: { text: `Request input can reach an operation where it allows ${title(sink).toLowerCase()}.` },
|
|
1679
|
+
defaultConfiguration: { level: 'warning' },
|
|
1680
|
+
properties: { tags: ['security'] }
|
|
1681
|
+
}));
|
|
1682
|
+
const results = report.findings.map(finding => ({
|
|
1683
|
+
ruleId: `aiwaf.${finding.sink}`,
|
|
1684
|
+
ruleIndex: sinks.indexOf(finding.sink),
|
|
1685
|
+
level: finding.confidence === 'high' ? 'error' : 'warning',
|
|
1686
|
+
message: { text: `${finding.source} reaches ${finding.call} in ${finding.function}` },
|
|
1687
|
+
locations: [{ physicalLocation: {
|
|
1688
|
+
artifactLocation: { uri: String(finding.file).replace(/\\/g, '/').replace(/^\.\//, '') },
|
|
1689
|
+
region: { startLine: Math.max(Number(finding.line) || 1, 1) }
|
|
1690
|
+
} }],
|
|
1691
|
+
partialFingerprints: { 'aiwafFinding/v1': fingerprint(finding) }
|
|
1692
|
+
}));
|
|
1693
|
+
return JSON.stringify({
|
|
1694
|
+
$schema: 'https://json.schemastore.org/sarif-2.1.0.json',
|
|
1695
|
+
version: '2.1.0',
|
|
1696
|
+
runs: [{ tool: { driver: { name: 'AIWAF audit', informationUri: 'https://github.com/aiwaf-project/aiwaf', rules } }, results }]
|
|
1697
|
+
}, null, 2);
|
|
551
1698
|
}
|
|
552
1699
|
|
|
553
1700
|
function formatReport(report) {
|
|
@@ -555,34 +1702,39 @@ function formatReport(report) {
|
|
|
555
1702
|
`${finding.file}:${finding.line}: ${finding.sink} (${finding.confidence} confidence) ${finding.source} reaches ${finding.call} in ${finding.function}`);
|
|
556
1703
|
for (const error of report.errors) lines.push(`${error.file}: not analyzed: ${error.error}`);
|
|
557
1704
|
lines.push(`Scanned ${report.files_scanned} files and found ${report.findings.length} possible injection paths.`);
|
|
1705
|
+
if (report.suppressed) lines.push(`Left out ${report.suppressed} marked with an aiwaf: ignore comment.`);
|
|
1706
|
+
if (report.baselined) lines.push(`Left out ${report.baselined} already in the baseline.`);
|
|
558
1707
|
if (!report.findings.length) lines.push("This doesn't prove the code is safe, because static analysis can miss paths.");
|
|
559
1708
|
return lines.join('\n');
|
|
560
1709
|
}
|
|
561
1710
|
|
|
562
1711
|
function runAuditCommand(args, write = text => console.log(text)) {
|
|
563
1712
|
const positional = [];
|
|
564
|
-
const options = { format: 'text', includeTests: false, failOnFindings: false, output: null, manifest: null };
|
|
1713
|
+
const options = { format: 'text', includeTests: false, failOnFindings: false, output: null, manifest: null, baseline: null };
|
|
565
1714
|
for (let index = 0; index < args.length; index += 1) {
|
|
566
1715
|
const argument = args[index];
|
|
567
1716
|
if (argument === '--format') options.format = args[++index];
|
|
568
1717
|
else if (argument === '--output') options.output = args[++index];
|
|
569
1718
|
else if (argument === '--manifest') options.manifest = args[++index];
|
|
1719
|
+
else if (argument === '--baseline') options.baseline = args[++index];
|
|
570
1720
|
else if (argument === '--include-tests') options.includeTests = true;
|
|
571
1721
|
else if (argument === '--fail-on-findings') options.failOnFindings = true;
|
|
572
1722
|
else positional.push(argument);
|
|
573
1723
|
}
|
|
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]');
|
|
1724
|
+
if (!['text', 'json', 'sarif'].includes(options.format)) {
|
|
1725
|
+
write('Usage: aiwaf audit [path] [--format text|json|sarif] [--output file] [--include-tests] [--fail-on-findings] [--manifest file] [--baseline file]');
|
|
576
1726
|
return 2;
|
|
577
1727
|
}
|
|
578
1728
|
let report;
|
|
579
1729
|
try {
|
|
580
1730
|
report = analyzePath(positional[0] || '.', options);
|
|
1731
|
+
if (options.baseline) report = applyBaseline(report, JSON.parse(fs.readFileSync(options.baseline, 'utf8')));
|
|
581
1732
|
} catch (error) {
|
|
582
1733
|
write(String(error.message || error));
|
|
583
1734
|
return 2;
|
|
584
1735
|
}
|
|
585
|
-
const content = options.format === 'json' ? JSON.stringify(report, null, 2)
|
|
1736
|
+
const content = options.format === 'json' ? JSON.stringify(report, null, 2)
|
|
1737
|
+
: options.format === 'sarif' ? toSarif(report) : formatReport(report);
|
|
586
1738
|
if (options.output) fs.writeFileSync(options.output, `${content}\n`);
|
|
587
1739
|
else write(content);
|
|
588
1740
|
if (options.manifest) {
|
|
@@ -597,4 +1749,4 @@ function runAuditCommand(args, write = text => console.log(text)) {
|
|
|
597
1749
|
return options.failOnFindings && report.findings.length ? 1 : 0;
|
|
598
1750
|
}
|
|
599
1751
|
|
|
600
|
-
module.exports = { analyzePath, analyzeSource, formatReport, runAuditCommand };
|
|
1752
|
+
module.exports = { analyzePath, analyzeSource, applyBaseline, fingerprint, formatReport, runAuditCommand, toSarif };
|