@blundergoat/gruff-ts 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +82 -0
- package/CONTRIBUTING.md +32 -25
- package/README.md +49 -50
- package/SECURITY.md +18 -31
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -10
- package/docs/agent-hook.md +32 -35
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +160 -89
- package/docs/dashboard.md +12 -13
- package/docs/output-formats.md +100 -25
- package/docs/philosophy.md +2 -2
- package/docs/reports-and-ci.md +14 -172
- package/docs/rules.md +126 -98
- package/package.json +10 -8
- package/src/analyser.ts +817 -323
- package/src/baseline-file.ts +867 -0
- package/src/baseline-identity.ts +463 -0
- package/src/baseline-options.ts +139 -34
- package/src/baseline.ts +62 -68
- package/src/blocks.ts +512 -336
- package/src/changed-regions.ts +380 -79
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +445 -436
- package/src/cli-program.ts +915 -172
- package/src/cli.ts +9 -3
- package/src/comment-rules.ts +236 -418
- package/src/comment-scanner.ts +339 -47
- package/src/complexity-metrics.ts +111 -35
- package/src/config-load-error.ts +17 -8
- package/src/config-parse.ts +291 -98
- package/src/config-preservation.ts +81 -26
- package/src/config.ts +751 -223
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +182 -54
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +493 -140
- package/src/doc-rules.ts +602 -126
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +134 -109
- package/src/findings.ts +47 -27
- package/src/fixture-purpose-rules.ts +194 -50
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +328 -121
- package/src/hook-contract.ts +681 -255
- package/src/init-config.ts +163 -118
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -468
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +32 -127
- package/src/parsed-script.ts +868 -314
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +86 -74
- package/src/project-config-rules.ts +324 -140
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +102 -38
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +821 -203
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +249 -55
- package/src/security-flow-rules.ts +791 -115
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +460 -387
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +378 -104
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +343 -253
- package/src/text-scans.ts +62 -11
- package/src/types.ts +220 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -163
- package/src/test-fixtures.ts +0 -671
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
1
|
+
// Finds candidate security issues in TypeScript and JavaScript during analysis.
|
|
2
|
+
//
|
|
3
|
+
// Uses written source and local assignments to connect inputs with calls worth reviewing.
|
|
4
|
+
// A finding points the developer to the code to inspect, with no need to run the scanned project.
|
|
3
5
|
import type { SourceFile } from "./discovery.ts";
|
|
4
6
|
import { makeFinding } from "./findings.ts";
|
|
5
7
|
import { parseScript } from "./parsed-script.ts";
|
|
@@ -17,11 +19,14 @@ type TsNode = import("typescript").Node;
|
|
|
17
19
|
type TsCallLikeExpression = import("typescript").CallExpression | import("typescript").NewExpression;
|
|
18
20
|
type TsNamedImportBindings = import("typescript").NamedImportBindings;
|
|
19
21
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
22
|
+
/**
|
|
23
|
+
* Parse source text for a discovered file through the shared syntax-only parser; script parsing increments the shared parse count.
|
|
24
|
+
* Parser exceptions stay silent because full scans retain their separate same-line pass.
|
|
25
|
+
*
|
|
26
|
+
* @param file - discovered file passed to the shared script parser
|
|
27
|
+
* @param source - source text to parse into a syntax tree
|
|
28
|
+
* @returns An AST even with syntax diagnostics, or null to skip AST flow for non-script input or parser exceptions.
|
|
29
|
+
*/
|
|
25
30
|
function getSourceFile(file: SourceFile, source: string): TsSourceFile | null {
|
|
26
31
|
try {
|
|
27
32
|
return parseScript(file, source)?.sourceFile ?? null;
|
|
@@ -30,7 +35,13 @@ function getSourceFile(file: SourceFile, source: string): TsSourceFile | null {
|
|
|
30
35
|
}
|
|
31
36
|
}
|
|
32
37
|
|
|
33
|
-
|
|
38
|
+
/**
|
|
39
|
+
* Walk the subtree rooted at a node depth-first, calling the visitor before its children.
|
|
40
|
+
*
|
|
41
|
+
* @param node - root AST node of the subtree to traverse
|
|
42
|
+
* @param visit - callback invoked for each visited node; returning false skips that node's children
|
|
43
|
+
* @returns Nothing. The visitor performs the work at each visited node.
|
|
44
|
+
*/
|
|
34
45
|
function walk(node: TsNode, visit: (node: TsNode) => boolean | void): void {
|
|
35
46
|
if (visit(node) === false) {
|
|
36
47
|
return;
|
|
@@ -40,7 +51,13 @@ function walk(node: TsNode, visit: (node: TsNode) => boolean | void): void {
|
|
|
40
51
|
});
|
|
41
52
|
}
|
|
42
53
|
|
|
43
|
-
|
|
54
|
+
/**
|
|
55
|
+
* Compute a node's zero-based start line so callers can convert it to a one-based finding line.
|
|
56
|
+
*
|
|
57
|
+
* @param parsedSource - parsed syntax tree that owns the node's character offsets
|
|
58
|
+
* @param node - AST node whose start position is mapped to a line index
|
|
59
|
+
* @returns Zero-based start line of node within parsedSource.
|
|
60
|
+
*/
|
|
44
61
|
function lineIndexOf(parsedSource: TsSourceFile, node: TsNode): number {
|
|
45
62
|
return parsedSource.getLineAndCharacterOfPosition(node.getStart(parsedSource)).line;
|
|
46
63
|
}
|
|
@@ -51,6 +68,9 @@ interface SourceToken {
|
|
|
51
68
|
pattern: RegExp;
|
|
52
69
|
}
|
|
53
70
|
|
|
71
|
+
// Each imported reader records function scopes whose hoisted locals hide its import.
|
|
72
|
+
type FileReadBindings = ReadonlyMap<string, ReadonlySet<TsNode>>;
|
|
73
|
+
|
|
54
74
|
// One source-to-sink heuristic: a risky call pattern plus the remediation attached to its finding.
|
|
55
75
|
interface SecurityFlowRule {
|
|
56
76
|
ruleId: string;
|
|
@@ -67,6 +87,10 @@ const SOURCE_TOKENS: readonly SourceToken[] = [
|
|
|
67
87
|
{ kind: "browser-location", pattern: /\blocation\.search\b|\bURLSearchParams\s*\(\s*location\.search\b/ },
|
|
68
88
|
];
|
|
69
89
|
|
|
90
|
+
// The receivers the request source token reads. A nested function declaring one as its own parameter is a handler
|
|
91
|
+
// whose request is its own argument, so `textOutsideRequestHandlers` blanks its reads of that name.
|
|
92
|
+
const REQUEST_RECEIVER_NAMES: ReadonlySet<string> = new Set(["req", "request", "ctx"]);
|
|
93
|
+
|
|
70
94
|
const SECURITY_FLOW_RULES: readonly SecurityFlowRule[] = [
|
|
71
95
|
{
|
|
72
96
|
ruleId: "security.path-traversal-candidate",
|
|
@@ -98,7 +122,18 @@ const SECURITY_FLOW_RULES: readonly SecurityFlowRule[] = [
|
|
|
98
122
|
},
|
|
99
123
|
];
|
|
100
124
|
|
|
101
|
-
|
|
125
|
+
/**
|
|
126
|
+
* Scan one source line for same-line external-input-to-sink matches.
|
|
127
|
+
*
|
|
128
|
+
* Same-line matching is intentional: reports stable candidate findings without implying full taint analysis.
|
|
129
|
+
* Shared sink matchers reset only when a recognized source token is found.
|
|
130
|
+
*
|
|
131
|
+
* @param file - discovered file whose display path anchors emitted findings
|
|
132
|
+
* @param codeLine - single source line checked for the first catalogue source pattern and matching sink calls
|
|
133
|
+
* @param lineNumber - one-based line number assigned to appended findings
|
|
134
|
+
* @param findings - accumulator that receives matching candidate findings
|
|
135
|
+
* @returns Nothing. Appends to findings at lineNumber in file for matching sinks, leaving matchers and findings untouched if no source matches.
|
|
136
|
+
*/
|
|
102
137
|
export function analyseSecurityFlowLine(file: SourceFile, codeLine: string, lineNumber: number, findings: Finding[]): void {
|
|
103
138
|
const source = sourceToken(codeLine);
|
|
104
139
|
if (!source) {
|
|
@@ -111,12 +146,25 @@ export function analyseSecurityFlowLine(file: SourceFile, codeLine: string, line
|
|
|
111
146
|
}
|
|
112
147
|
}
|
|
113
148
|
|
|
114
|
-
|
|
149
|
+
/**
|
|
150
|
+
* Match a source line against SOURCE_TOKENS in catalogue order for deterministic metadata.
|
|
151
|
+
*
|
|
152
|
+
* @param codeLine - single source line checked for recognized external-input tokens
|
|
153
|
+
* @returns The first matching SOURCE_TOKENS entry, or undefined when the line contains no recognized external-input token.
|
|
154
|
+
*/
|
|
115
155
|
function sourceToken(codeLine: string): SourceToken | undefined {
|
|
116
156
|
return SOURCE_TOKENS.find((source) => source.pattern.test(codeLine));
|
|
117
157
|
}
|
|
118
158
|
|
|
119
|
-
|
|
159
|
+
/**
|
|
160
|
+
* Check whether a bounded sink call segment contains external-input evidence.
|
|
161
|
+
* Resets callPattern.lastIndex to zero; testing a global or sticky sourcePattern can also advance or reset its lastIndex.
|
|
162
|
+
*
|
|
163
|
+
* @param codeLine - single source line searched for sink calls
|
|
164
|
+
* @param sourcePattern - external-input pattern tested against each bounded call segment
|
|
165
|
+
* @param callPattern - sink matcher that must have the global flag to enumerate call sites
|
|
166
|
+
* @returns True if sourcePattern matches a bounded call segment selected by callPattern, or false when no segment contains source evidence.
|
|
167
|
+
*/
|
|
120
168
|
function sourceAppearsInSink(codeLine: string, sourcePattern: RegExp, callPattern: RegExp): boolean {
|
|
121
169
|
callPattern.lastIndex = 0;
|
|
122
170
|
for (const call of codeLine.matchAll(callPattern)) {
|
|
@@ -128,16 +176,31 @@ function sourceAppearsInSink(codeLine: string, sourcePattern: RegExp, callPatter
|
|
|
128
176
|
return false;
|
|
129
177
|
}
|
|
130
178
|
|
|
131
|
-
|
|
179
|
+
/**
|
|
180
|
+
* Extract a bounded source slice from a sink call start for same-line sink matching.
|
|
181
|
+
* Stops at the first closing parenthesis or 240 characters.
|
|
182
|
+
*
|
|
183
|
+
* @param codeLine - single source line containing the candidate sink call
|
|
184
|
+
* @param callStart - zero-based start offset of the call match within codeLine
|
|
185
|
+
* @returns Bounded slice from callStart up to the first closing parenthesis, or up to 240 characters if none occurs.
|
|
186
|
+
*/
|
|
132
187
|
function singleLineCallSegment(codeLine: string, callStart: number): string {
|
|
133
|
-
//
|
|
188
|
+
// Cap the text inspected per candidate call; this is a bounded heuristic, not balanced-parenthesis parsing.
|
|
134
189
|
const maxSegmentLength = 240;
|
|
135
190
|
const segment = codeLine.slice(callStart, callStart + maxSegmentLength);
|
|
136
191
|
const close = segment.indexOf(")");
|
|
137
192
|
return close === -1 ? segment : segment.slice(0, close + 1);
|
|
138
193
|
}
|
|
139
194
|
|
|
140
|
-
|
|
195
|
+
/**
|
|
196
|
+
* Build a warning finding with a stable finding contract: medium confidence and metadata containing sourceKind and the rule's sink kind.
|
|
197
|
+
*
|
|
198
|
+
* @param file - discovered file whose display path locates the finding
|
|
199
|
+
* @param line - one-based line number of the candidate sink
|
|
200
|
+
* @param rule - rule definition supplying the finding's id, message, remediation, and sink kind
|
|
201
|
+
* @param sourceKind - external-input category recorded in finding metadata
|
|
202
|
+
* @returns A medium-confidence security warning at the supplied file and line.
|
|
203
|
+
*/
|
|
141
204
|
function securityFlowFinding(file: SourceFile, line: number, rule: SecurityFlowRule, sourceKind: string): Finding {
|
|
142
205
|
return makeFinding({
|
|
143
206
|
ruleId: rule.ruleId,
|
|
@@ -153,11 +216,9 @@ function securityFlowFinding(file: SourceFile, line: number, rule: SecurityFlowR
|
|
|
153
216
|
}
|
|
154
217
|
|
|
155
218
|
// --- Bounded intra-function AST flow (ADR-012) -------------------------
|
|
156
|
-
//
|
|
157
|
-
//
|
|
158
|
-
//
|
|
159
|
-
// fingerprints are unchanged; this pass only adds genuinely cross-line cases and
|
|
160
|
-
// skips any flow whose source and sink share a line.
|
|
219
|
+
//
|
|
220
|
+
// Augments the same-line checks above by tracking local variables assigned from external input to sinks across lines within one function.
|
|
221
|
+
// Same-line flows remain owned by the line pass so existing fingerprints never move; this pass adds cross-line flows and AST-only sinks.
|
|
161
222
|
|
|
162
223
|
// One tainted local: the 0-based line of the originating external source, the
|
|
163
224
|
// source kind for metadata, and how many alias hops removed it is (cap below).
|
|
@@ -167,6 +228,13 @@ interface TaintRecord {
|
|
|
167
228
|
depth: number;
|
|
168
229
|
}
|
|
169
230
|
|
|
231
|
+
// Deserialization needs content provenance while the other sinks still inspect path influence.
|
|
232
|
+
interface FlowInputs {
|
|
233
|
+
tainted: Map<string, TaintRecord>;
|
|
234
|
+
contentTainted: Map<string, TaintRecord>;
|
|
235
|
+
fileReadCallees: FileReadBindings;
|
|
236
|
+
}
|
|
237
|
+
|
|
170
238
|
// Bundles the syntax context each sink matcher needs so all text extraction remains anchored
|
|
171
239
|
// to the parsed source file instead of raw substrings.
|
|
172
240
|
interface AstSinkInput {
|
|
@@ -236,8 +304,248 @@ const AST_FLOW_SINKS: readonly AstFlowSink[] = [
|
|
|
236
304
|
const MAX_ALIAS_DEPTH = 2;
|
|
237
305
|
const MAX_SCOPE_NODES = 4000;
|
|
238
306
|
|
|
239
|
-
|
|
240
|
-
|
|
307
|
+
/**
|
|
308
|
+
* Collect runtime filesystem-reader names imported from fs, node:fs, and their promises modules (promises support readFile only).
|
|
309
|
+
* Only these imports establish the filename/content boundary; unrelated helpers retain ordinary taint.
|
|
310
|
+
*
|
|
311
|
+
* @param parsedSource - parsed syntax tree whose top-level imports are inspected
|
|
312
|
+
* @returns Set of imported reader callees including default/namespace member paths and named local aliases, or an empty set if none qualify.
|
|
313
|
+
*/
|
|
314
|
+
function importedFileReadCallees(parsedSource: TsSourceFile): ReadonlySet<string> {
|
|
315
|
+
const callees = new Set<string>();
|
|
316
|
+
for (const statement of parsedSource.statements) {
|
|
317
|
+
if (!typescriptSyntax.isImportDeclaration(statement) || !typescriptSyntax.isStringLiteral(statement.moduleSpecifier)) continue;
|
|
318
|
+
const moduleName = statement.moduleSpecifier.text;
|
|
319
|
+
if (!/^(?:node:)?fs(?:\/promises)?$/.test(moduleName)) continue;
|
|
320
|
+
const clause = statement.importClause;
|
|
321
|
+
if (!clause || clause.isTypeOnly) continue;
|
|
322
|
+
const methods = moduleName.endsWith("/promises") ? ["readFile"] : ["readFile", "readFileSync"];
|
|
323
|
+
for (const name of fileReadBindingNames(clause, methods)) callees.add(name);
|
|
324
|
+
}
|
|
325
|
+
return callees;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Extract callable reader names exposed by a non-type-only import clause for the requested methods.
|
|
330
|
+
* Skips named type-only imports; the caller must exclude whole type-only import clauses.
|
|
331
|
+
*
|
|
332
|
+
* @param clause - import clause whose default, namespace, and named bindings are inspected
|
|
333
|
+
* @param methods - filesystem reader method names allowed for the imported module
|
|
334
|
+
* @returns Default/namespace member paths and matching named local aliases, or an empty array if none match.
|
|
335
|
+
*/
|
|
336
|
+
function fileReadBindingNames(clause: import("typescript").ImportClause, methods: readonly string[]): string[] {
|
|
337
|
+
const names: string[] = [];
|
|
338
|
+
if (clause.name) for (const method of methods) names.push(`${clause.name.text}.${method}`);
|
|
339
|
+
const bindings = clause.namedBindings;
|
|
340
|
+
if (!bindings) return names;
|
|
341
|
+
if (typescriptSyntax.isNamespaceImport(bindings)) {
|
|
342
|
+
for (const method of methods) names.push(`${bindings.name.text}.${method}`);
|
|
343
|
+
} else {
|
|
344
|
+
for (const binding of bindings.elements) {
|
|
345
|
+
if (!binding.isTypeOnly && methods.includes(binding.propertyName?.text ?? binding.name.text)) names.push(binding.name.text);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return names;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Normalizes a simple identifier or dotted property chain (such as `fs . readFileSync`) into compact `a.b` text without whitespace or comments.
|
|
353
|
+
*
|
|
354
|
+
* @param expr - AST expression inspected as an identifier or chain of property accesses
|
|
355
|
+
* @returns Compact dotted name when `expr` is an identifier or property-access chain, or undefined for other expression shapes.
|
|
356
|
+
*/
|
|
357
|
+
function dottedIdentifierPath(expr: TsNode): string | undefined {
|
|
358
|
+
if (typescriptSyntax.isParenthesizedExpression(expr)) {
|
|
359
|
+
return dottedIdentifierPath(expr.expression);
|
|
360
|
+
}
|
|
361
|
+
if (typescriptSyntax.isIdentifier(expr)) {
|
|
362
|
+
return expr.text;
|
|
363
|
+
}
|
|
364
|
+
if (typescriptSyntax.isPropertyAccessExpression(expr)) {
|
|
365
|
+
const receiver = dottedIdentifierPath(expr.expression);
|
|
366
|
+
return receiver === undefined ? undefined : `${receiver}.${expr.name.text}`;
|
|
367
|
+
}
|
|
368
|
+
return undefined;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Check whether an AST node is an unshadowed call to an imported filesystem reader.
|
|
373
|
+
* Returning false leaves the expression eligible for content taint.
|
|
374
|
+
*
|
|
375
|
+
* @param node - AST node tested as a call expression
|
|
376
|
+
* @param parsedSource - parsed syntax tree used to extract the callee text
|
|
377
|
+
* @param bindings - imported-reader names and their hoisted shadowing scopes
|
|
378
|
+
* @returns True if node is a call whose normalized callee belongs to bindings with no visible reader shadowing; otherwise false.
|
|
379
|
+
*/
|
|
380
|
+
function isImportedFileRead(node: TsNode, parsedSource: TsSourceFile, bindings: FileReadBindings): boolean {
|
|
381
|
+
if (!typescriptSyntax.isCallExpression(node)) return false;
|
|
382
|
+
const callee = dottedIdentifierPath(node.expression) ?? node.expression.getText(parsedSource);
|
|
383
|
+
return bindings.has(callee) && !isFileReadBindingShadowed(node, callee, bindings);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Build reader exemptions from imports in parsedSource and drop exemptions for unshadowed assignments to tracked reader members
|
|
388
|
+
* so that replacement methods remain eligible for content taint.
|
|
389
|
+
*
|
|
390
|
+
* A module too large to walk drops every exemption, so file reads stay reported.
|
|
391
|
+
* A function or static block too large to walk loses the exemptions inside it; a reader assigned there loses its exemption everywhere.
|
|
392
|
+
*
|
|
393
|
+
* @param parsedSource - parsed syntax tree providing imports and assignment target text
|
|
394
|
+
* @param scopes - function, module, and static-block scope roots scanned for hoisted shadowing and member writes
|
|
395
|
+
* @returns Map of reader names to shadowing scopes, or an empty map when no readers exist or the module root exceeds the node budget.
|
|
396
|
+
*/
|
|
397
|
+
function fileReadBindingsForScopes(parsedSource: TsSourceFile, scopes: readonly TsNode[]): FileReadBindings {
|
|
398
|
+
const bindings = new Map([...importedFileReadCallees(parsedSource)].map((callee) => [callee, new Set<TsNode>()]));
|
|
399
|
+
if (bindings.size === 0) return bindings;
|
|
400
|
+
const writes: TsNode[] = [];
|
|
401
|
+
const exhaustedScopes: TsNode[] = [];
|
|
402
|
+
for (const scope of scopes) {
|
|
403
|
+
// A scope too large to walk fully cannot prove that a file reader was left untouched.
|
|
404
|
+
if (!indexFileReadScope(scope, bindings, writes)) {
|
|
405
|
+
// Module-level exhaustion can hide top-level hoisting or reassignment that affects every scope, so fail closed globally.
|
|
406
|
+
if (scope === parsedSource) {
|
|
407
|
+
return new Map();
|
|
408
|
+
}
|
|
409
|
+
exhaustedScopes.push(scope);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
for (const write of writes) {
|
|
413
|
+
const callee = writtenFileReadCallee(write, parsedSource);
|
|
414
|
+
if (callee && bindings.has(callee) && !isFileReadBindingShadowed(write, callee, bindings)) bindings.delete(callee);
|
|
415
|
+
}
|
|
416
|
+
// Scope-local exhaustion fails closed for that scope and drops any member reader whose text matches an assignment in the exhausted body.
|
|
417
|
+
for (const exhaustedScope of exhaustedScopes) {
|
|
418
|
+
dropExhaustedScopeWrittenCallees(exhaustedScope.getText(parsedSource), bindings);
|
|
419
|
+
// Treat the oversized scope as shadowing every reader, so reads inside it lose the exemption and can still be reported.
|
|
420
|
+
for (const shadowedScopes of bindings.values()) {
|
|
421
|
+
shadowedScopes.add(exhaustedScope);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return bindings;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Drops tracked member-reader bindings globally when an exhausted scope's source text appears to assign to that member.
|
|
429
|
+
* Mutates `bindings` in place so an unwalked tail beyond `MAX_SCOPE_NODES` cannot monkey-patch a reader while leaving sibling exemptions active.
|
|
430
|
+
*
|
|
431
|
+
* @param scopeText - source text of a function or static-block scope that exceeded `MAX_SCOPE_NODES`
|
|
432
|
+
* @param bindings - mutable reader-binding map whose member entries are removed on assignment matches
|
|
433
|
+
* @returns Nothing. Deletes matching member callees from `bindings` in place.
|
|
434
|
+
*/
|
|
435
|
+
function dropExhaustedScopeWrittenCallees(scopeText: string, bindings: Map<string, Set<TsNode>>): void {
|
|
436
|
+
// Check each tracked reader, such as `fs.readFileSync`, for an assignment in the oversized scope.
|
|
437
|
+
for (const callee of [...bindings.keys()]) {
|
|
438
|
+
const dotIndex = callee.indexOf(".");
|
|
439
|
+
// A bare imported name cannot be replaced through a member write, so only `module.method` readers are checked.
|
|
440
|
+
if (dotIndex === -1) {
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
const rootPattern = escapeRegExpLiteral(callee.slice(0, dotIndex));
|
|
444
|
+
const methodPattern = escapeRegExpLiteral(callee.slice(dotIndex + 1));
|
|
445
|
+
const memberWritePattern = new RegExp(
|
|
446
|
+
`(?<![\\w$])${rootPattern}\\s*(?:\\.\\s*${methodPattern}(?![\\w$])|\\[\\s*["']${methodPattern}["']\\s*\\])\\s*(?:\\?\\?|&&|\\|\\||\\*\\*|<<|>>>?|[+\\-*/%&|^])?=(?!=)`,
|
|
447
|
+
);
|
|
448
|
+
// Text such as `fs.readFileSync = fake` in the unwalked scope may replace the reader, so its exemption is dropped everywhere.
|
|
449
|
+
if (memberWritePattern.test(scopeText)) {
|
|
450
|
+
bindings.delete(callee);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Escapes regular-expression metacharacters in an identifier segment before interpolating it into a pattern.
|
|
457
|
+
* Identifiers may start with `$`, so callers bound matches with `(?<![\w$])` rather than `\b`.
|
|
458
|
+
*
|
|
459
|
+
* @param literalText - raw identifier text such as `fs` or `$fs`
|
|
460
|
+
* @returns Escaped string safe for literal matching inside `RegExp`.
|
|
461
|
+
*/
|
|
462
|
+
function escapeRegExpLiteral(literalText: string): string {
|
|
463
|
+
return literalText.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Scan a scope for hoisted reader shadowing and assignment targets while skipping nested functions and static blocks.
|
|
468
|
+
* Mutates both bindings and writes in place.
|
|
469
|
+
*
|
|
470
|
+
* @param scope - root AST node of the scope to scan up to MAX_SCOPE_NODES
|
|
471
|
+
* @param bindings - mutable map from reader names to shadowing scopes updated with hoisted var declarations
|
|
472
|
+
* @param writes - mutable list receiving assignment left-hand targets for replacement checks
|
|
473
|
+
* @returns True when the scan completes within the node budget, or false on exhaustion leaving partial records to discard.
|
|
474
|
+
*/
|
|
475
|
+
function indexFileReadScope(scope: TsNode, bindings: Map<string, Set<TsNode>>, writes: TsNode[]): boolean {
|
|
476
|
+
let budget = MAX_SCOPE_NODES;
|
|
477
|
+
walk(scope, (node) => {
|
|
478
|
+
if (budget-- <= 0) return false;
|
|
479
|
+
if ((isFunctionLike(node) || typescriptSyntax.isClassStaticBlockDeclaration(node)) && node !== scope) return false;
|
|
480
|
+
recordHoistedFileReadBindings(node, scope, bindings);
|
|
481
|
+
if (typescriptSyntax.isBinaryExpression(node) && node.operatorToken.kind >= typescriptSyntax.SyntaxKind.FirstAssignment && node.operatorToken.kind <= typescriptSyntax.SyntaxKind.LastAssignment) {
|
|
482
|
+
writes.push(node.left);
|
|
483
|
+
}
|
|
484
|
+
return;
|
|
485
|
+
});
|
|
486
|
+
return budget >= 0;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* Record hoisted var declarations that shadow an imported reader root name in the enclosing scope.
|
|
491
|
+
* Block-scoped let/const declarations and non-declaration nodes leave bindings unchanged.
|
|
492
|
+
*
|
|
493
|
+
* @param node - AST node inspected as a non-block-scoped variable declaration list
|
|
494
|
+
* @param scope - enclosing scope boundary recorded when a reader root name matches
|
|
495
|
+
* @param bindings - mutable reader-to-scope sets updated in place for matching reader root names
|
|
496
|
+
* @returns Nothing. Adds scope to matching entries in bindings when a var declaration binds a reader root name.
|
|
497
|
+
*/
|
|
498
|
+
function recordHoistedFileReadBindings(node: TsNode, scope: TsNode, bindings: Map<string, Set<TsNode>>): void {
|
|
499
|
+
if (!typescriptSyntax.isVariableDeclarationList(node) || (node.flags & typescriptSyntax.NodeFlags.BlockScoped)) return;
|
|
500
|
+
for (const [callee, shadowedScopes] of bindings) {
|
|
501
|
+
if (variableDeclarationListBindsName(node, callee.split(".", 1)[0] ?? "")) shadowedScopes.add(scope);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* Normalize an assignment target to a reader call spelling, unwrapping parentheses and string-literal element access.
|
|
507
|
+
*
|
|
508
|
+
* @param node - assignment left-hand AST node to normalize
|
|
509
|
+
* @param parsedSource - parsed syntax tree used to read expression text
|
|
510
|
+
* @returns Dotted property text for property or string-literal element access, or undefined for other target shapes.
|
|
511
|
+
*/
|
|
512
|
+
function writtenFileReadCallee(node: TsNode, parsedSource: TsSourceFile): string | undefined {
|
|
513
|
+
if (typescriptSyntax.isParenthesizedExpression(node)) return writtenFileReadCallee(node.expression, parsedSource);
|
|
514
|
+
// Normalize property access so `fs . readFileSync = ...` invalidates the `fs.readFileSync` reader binding reliably.
|
|
515
|
+
if (typescriptSyntax.isPropertyAccessExpression(node)) return dottedIdentifierPath(node) ?? node.getText(parsedSource);
|
|
516
|
+
if (typescriptSyntax.isElementAccessExpression(node) && typescriptSyntax.isStringLiteral(node.argumentExpression)) {
|
|
517
|
+
const receiver = dottedIdentifierPath(node.expression) ?? node.expression.getText(parsedSource);
|
|
518
|
+
return `${receiver}.${node.argumentExpression.text}`;
|
|
519
|
+
}
|
|
520
|
+
return undefined;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* Check whether an imported reader call is hidden by a lexical binding, a hoisted shadowing scope, or a named class expression.
|
|
525
|
+
* These extra guards apply only to reader exemptions; redirect matching uses the common lexical checks.
|
|
526
|
+
*
|
|
527
|
+
* @param node - AST call or write site where the imported reader appears
|
|
528
|
+
* @param callee - imported reader call spelling whose root identifier is checked
|
|
529
|
+
* @param bindings - hoisted shadowing scopes per reader name; a missing entry adds no hoisted evidence
|
|
530
|
+
* @returns True if callee is shadowed at node by lexical bindings, recorded scopes, or a named class expression; otherwise false.
|
|
531
|
+
*/
|
|
532
|
+
function isFileReadBindingShadowed(node: TsNode, callee: string, bindings: FileReadBindings): boolean {
|
|
533
|
+
if (isImportedCalleeShadowed(node, callee)) return true;
|
|
534
|
+
const shadowedScopes = bindings.get(callee);
|
|
535
|
+
const rootName = callee.split(".", 1)[0];
|
|
536
|
+
for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
|
|
537
|
+
if (shadowedScopes?.has(ancestor)) return true;
|
|
538
|
+
if (typescriptSyntax.isClassExpression(ancestor) && ancestor.name?.text === rootName) return true;
|
|
539
|
+
}
|
|
540
|
+
return false;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* Collect local redirect call names imported from supported framework packages, ignoring unrelated and type-only bindings.
|
|
545
|
+
*
|
|
546
|
+
* @param parsedSource - parsed syntax tree whose top-level imports are inspected
|
|
547
|
+
* @returns Set of local redirect aliases from named imports and member paths from namespace imports, or an empty set if none match.
|
|
548
|
+
*/
|
|
241
549
|
function importedFrameworkRedirectCallees(parsedSource: TsSourceFile): ReadonlySet<string> {
|
|
242
550
|
const callees = new Set<string>();
|
|
243
551
|
for (const statement of parsedSource.statements) {
|
|
@@ -256,17 +564,26 @@ function importedFrameworkRedirectCallees(parsedSource: TsSourceFile): ReadonlyS
|
|
|
256
564
|
return callees;
|
|
257
565
|
}
|
|
258
566
|
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
567
|
+
/**
|
|
568
|
+
* Check whether a module specifier belongs to the supported framework redirect allowlist to exclude unrelated redirect helpers.
|
|
569
|
+
* Recognizes next/navigation, React Router's core and DOM packages, and supported Remix runtime packages.
|
|
570
|
+
*
|
|
571
|
+
* @param moduleName - import-source module specifier text
|
|
572
|
+
* @returns True if moduleName matches the framework redirect allowlist; otherwise false.
|
|
573
|
+
*/
|
|
262
574
|
function isFrameworkRedirectModule(moduleName: string): boolean {
|
|
263
575
|
return moduleName === "next/navigation" ||
|
|
264
576
|
/^react-router(?:-dom)?$/.test(moduleName) ||
|
|
265
577
|
/^@remix-run\/(?:node|cloudflare|deno|server-runtime)$/.test(moduleName);
|
|
266
578
|
}
|
|
267
579
|
|
|
268
|
-
|
|
269
|
-
|
|
580
|
+
/**
|
|
581
|
+
* Record the local alias each binding style gives the framework redirect export, skipping named specifiers marked type-only.
|
|
582
|
+
*
|
|
583
|
+
* @param namedBindings - namespace or named import bindings from a framework redirect import
|
|
584
|
+
* @param callees - mutable set receiving the namespace member path or renamed local redirect names
|
|
585
|
+
* @returns Nothing. Adds redirect aliases from namedBindings to callees in place.
|
|
586
|
+
*/
|
|
270
587
|
function collectRedirectAliases(namedBindings: TsNamedImportBindings, callees: Set<string>): void {
|
|
271
588
|
if (typescriptSyntax.isNamespaceImport(namedBindings)) {
|
|
272
589
|
callees.add(`${namedBindings.name.text}.redirect`);
|
|
@@ -281,37 +598,40 @@ function collectRedirectAliases(namedBindings: TsNamedImportBindings, callees: S
|
|
|
281
598
|
}
|
|
282
599
|
|
|
283
600
|
/**
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
* when the file cannot be parsed, so the same-line scan remains the fallback.
|
|
601
|
+
* Collect syntax-only source-to-sink findings. A local script parse increments the shared parse count.
|
|
602
|
+
* An unavailable parse or failed traversal leaves findings unchanged; full scans retain the separate same-line pass.
|
|
287
603
|
* Invariant: this pass never uses TypeScript type-checking, emit, or schema changes.
|
|
288
604
|
*
|
|
289
605
|
* @param file - discovered script file whose display path anchors emitted fingerprints
|
|
290
606
|
* @param source - full source text to parse with syntax-only TypeScript APIs
|
|
291
607
|
* @param findings - accumulator that receives additional AST flow findings
|
|
292
|
-
* @param sharedSourceFile - the run's shared parse result
|
|
608
|
+
* @param sharedSourceFile - the run's shared parse result. Null or undefined triggers a local parse.
|
|
609
|
+
* @returns Nothing. Appends AST flow findings after a successful traversal.
|
|
293
610
|
*/
|
|
294
611
|
export function analyseSecurityFlow(file: SourceFile, source: string, findings: Finding[], sharedSourceFile?: TsSourceFile | null): void {
|
|
295
|
-
//
|
|
296
|
-
// fallback for direct callers that have no boundary result, such as focused unit tests.
|
|
612
|
+
// Reuse the run's AST when available to avoid parsing and counting the script twice.
|
|
297
613
|
const parsedSource = sharedSourceFile ?? getSourceFile(file, source);
|
|
298
614
|
if (!parsedSource) {
|
|
299
615
|
return;
|
|
300
616
|
}
|
|
301
|
-
//
|
|
302
|
-
//
|
|
303
|
-
//
|
|
617
|
+
// Recovery-tree text or position access can throw, so publish the local buffer only after traversal succeeds.
|
|
618
|
+
// This optional pass reports security evidence; recovery failures add no reliable evidence, so they stay silent.
|
|
619
|
+
// Discarding the buffer avoids partial results, while full scans retain separate same-line candidates.
|
|
304
620
|
const flowFindings: Finding[] = [];
|
|
305
621
|
try {
|
|
306
622
|
const frameworkRedirectCallees = importedFrameworkRedirectCallees(parsedSource);
|
|
307
623
|
const scopes: TsNode[] = [parsedSource];
|
|
624
|
+
const staticBlocks: TsNode[] = [];
|
|
308
625
|
walk(parsedSource, (node) => {
|
|
309
626
|
if (isFunctionLike(node)) {
|
|
310
627
|
scopes.push(node);
|
|
628
|
+
} else if (typescriptSyntax.isClassStaticBlockDeclaration(node)) {
|
|
629
|
+
staticBlocks.push(node);
|
|
311
630
|
}
|
|
312
631
|
});
|
|
632
|
+
const fileReadCallees = fileReadBindingsForScopes(parsedSource, [...scopes, ...staticBlocks]);
|
|
313
633
|
for (const scope of scopes) {
|
|
314
|
-
analyseFlowScope(parsedSource, scope, frameworkRedirectCallees, file, flowFindings);
|
|
634
|
+
analyseFlowScope(parsedSource, scope, frameworkRedirectCallees, fileReadCallees, file, flowFindings);
|
|
315
635
|
}
|
|
316
636
|
} catch {
|
|
317
637
|
return;
|
|
@@ -323,21 +643,28 @@ export function analyseSecurityFlow(file: SourceFile, source: string, findings:
|
|
|
323
643
|
|
|
324
644
|
/**
|
|
325
645
|
* Walk one function or the module top level and record bounded local taint evidence.
|
|
326
|
-
* Invariant: nested functions
|
|
646
|
+
* Invariant: each scope starts with fresh taint maps and its walk skips nested functions, so nested-function sinks never see outer tainted locals.
|
|
647
|
+
* When the node budget runs out, the rest of the scope contributes no findings.
|
|
327
648
|
*
|
|
328
649
|
* @param parsedSource - syntax tree that owns positions and text extraction
|
|
329
650
|
* @param scopeOwner - top-level source file or function-like node to scan
|
|
651
|
+
* @param frameworkRedirectCallees - local names of framework redirect functions this file imports; an unshadowed call to one is a redirect sink
|
|
652
|
+
* @param fileReadCallees - imported file readers and the scopes shadowing each; an unshadowed read keeps a tainted filename out of content taint
|
|
330
653
|
* @param file - discovered file used for stable finding locations
|
|
331
654
|
* @param findings - accumulator that receives sink findings for this scope
|
|
655
|
+
* @returns - Nothing. Appends the scope's sink findings to the supplied accumulator.
|
|
332
656
|
*/
|
|
333
657
|
function analyseFlowScope(
|
|
334
658
|
parsedSource: TsSourceFile,
|
|
335
659
|
scopeOwner: TsNode,
|
|
336
660
|
frameworkRedirectCallees: ReadonlySet<string>,
|
|
661
|
+
fileReadCallees: FileReadBindings,
|
|
337
662
|
file: SourceFile,
|
|
338
663
|
findings: Finding[],
|
|
339
664
|
): void {
|
|
340
665
|
const tainted = new Map<string, TaintRecord>();
|
|
666
|
+
const contentTainted = new Map<string, TaintRecord>();
|
|
667
|
+
const inputs = { tainted, contentTainted, fileReadCallees };
|
|
341
668
|
const unsafeXmlParsers = new Set<string>();
|
|
342
669
|
let budget = MAX_SCOPE_NODES;
|
|
343
670
|
walk(scopeOwner, (node) => {
|
|
@@ -350,22 +677,29 @@ function analyseFlowScope(
|
|
|
350
677
|
}
|
|
351
678
|
recordUnsafeXmlParser(parsedSource, node, unsafeXmlParsers);
|
|
352
679
|
recordTaint(parsedSource, node, tainted);
|
|
353
|
-
|
|
680
|
+
recordTaint(parsedSource, node, contentTainted, fileReadCallees);
|
|
681
|
+
reportSink(parsedSource, node, inputs, unsafeXmlParsers, frameworkRedirectCallees, file, findings);
|
|
354
682
|
return;
|
|
355
683
|
});
|
|
356
684
|
}
|
|
357
685
|
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
686
|
+
/**
|
|
687
|
+
* Update local provenance for variable declarations or identifier assignments, clearing an assignment's entry when its new value has no source.
|
|
688
|
+
* Function initializers add no record; without fileReads, alias lookup uses bare identifiers instead of compound expressions.
|
|
689
|
+
*
|
|
690
|
+
* @param parsedSource - parsed syntax tree used for expression text and line positions
|
|
691
|
+
* @param node - AST node inspected as a variable declaration or simple identifier assignment
|
|
692
|
+
* @param tainted - mutable map of local variable names to source provenance records
|
|
693
|
+
* @param fileReads - optional reader bindings that mask proven reader calls and enable depth-bounded compound alias lookup
|
|
694
|
+
* @returns Nothing. Updates tainted in place for declarations and identifier assignments.
|
|
695
|
+
*/
|
|
696
|
+
function recordTaint(parsedSource: TsSourceFile, node: TsNode, tainted: Map<string, TaintRecord>, fileReads?: FileReadBindings): void {
|
|
363
697
|
if (typescriptSyntax.isVariableDeclaration(node)) {
|
|
364
|
-
recordVariableTaint(parsedSource, node, tainted);
|
|
698
|
+
recordVariableTaint(parsedSource, node, tainted, fileReads);
|
|
365
699
|
return;
|
|
366
700
|
}
|
|
367
701
|
if (typescriptSyntax.isBinaryExpression(node) && node.operatorToken.kind === typescriptSyntax.SyntaxKind.EqualsToken && typescriptSyntax.isIdentifier(node.left)) {
|
|
368
|
-
const nextRecord = taintRecordFromExpression(parsedSource, node.right, tainted);
|
|
702
|
+
const nextRecord = taintRecordFromExpression(parsedSource, node.right, tainted, fileReads);
|
|
369
703
|
if (nextRecord) {
|
|
370
704
|
tainted.set(node.left.text, nextRecord);
|
|
371
705
|
} else {
|
|
@@ -374,13 +708,21 @@ function recordTaint(parsedSource: TsSourceFile, node: TsNode, tainted: Map<stri
|
|
|
374
708
|
}
|
|
375
709
|
}
|
|
376
710
|
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
711
|
+
/**
|
|
712
|
+
* Record source provenance from a variable declaration's initializer for each bound identifier, including nested destructuring.
|
|
713
|
+
* Missing initializers or untainted values leave existing entries unchanged; destructured names share one record regardless of keys or defaults.
|
|
714
|
+
*
|
|
715
|
+
* @param parsedSource - parsed syntax tree used to inspect the initializer and compute source lines
|
|
716
|
+
* @param node - variable declaration whose initializer and binding pattern are analysed
|
|
717
|
+
* @param tainted - mutable map of local provenance updated in place
|
|
718
|
+
* @param fileReads - optional reader bindings that mask proven reader calls and enable compound alias lookup
|
|
719
|
+
* @returns Nothing. Writes provenance entries into tainted for each identifier bound by node.
|
|
720
|
+
*/
|
|
721
|
+
function recordVariableTaint(parsedSource: TsSourceFile, node: import("typescript").VariableDeclaration, tainted: Map<string, TaintRecord>, fileReads?: FileReadBindings): void {
|
|
380
722
|
if (!node.initializer) {
|
|
381
723
|
return;
|
|
382
724
|
}
|
|
383
|
-
const record = taintRecordFromExpression(parsedSource, node.initializer, tainted);
|
|
725
|
+
const record = taintRecordFromExpression(parsedSource, node.initializer, tainted, fileReads);
|
|
384
726
|
if (!record) {
|
|
385
727
|
return;
|
|
386
728
|
}
|
|
@@ -391,26 +733,41 @@ function recordVariableTaint(parsedSource: TsSourceFile, node: import("typescrip
|
|
|
391
733
|
taintBindingNames(node.name, record, tainted);
|
|
392
734
|
}
|
|
393
735
|
|
|
394
|
-
|
|
395
|
-
|
|
736
|
+
/**
|
|
737
|
+
* Derive provenance for an expression from direct sources or bounded aliases, incrementing depth on successful alias propagation.
|
|
738
|
+
*
|
|
739
|
+
* @param parsedSource - parsed syntax tree used to classify direct sources and extract text
|
|
740
|
+
* @param expression - initializer or right-hand expression evaluated for provenance
|
|
741
|
+
* @param tainted - existing local provenance records consulted for identifier or compound aliases
|
|
742
|
+
* @param fileReads - optional reader bindings that mask reader calls and enable compound-value alias searches
|
|
743
|
+
* @returns Direct record at depth 1, incremented alias record below MAX_ALIAS_DEPTH, or undefined when ineligible including function values.
|
|
744
|
+
*/
|
|
745
|
+
function taintRecordFromExpression(parsedSource: TsSourceFile, expression: TsNode, tainted: Map<string, TaintRecord>, fileReads?: FileReadBindings): TaintRecord | undefined {
|
|
396
746
|
if (isFunctionLike(expression)) {
|
|
397
747
|
return undefined;
|
|
398
748
|
}
|
|
399
|
-
const kind = sourceKindOf(parsedSource, expression);
|
|
749
|
+
const kind = sourceKindOf(parsedSource, expression, fileReads);
|
|
400
750
|
if (kind !== undefined) {
|
|
401
751
|
return { line: lineIndexOf(parsedSource, expression), kind, depth: 1 };
|
|
402
752
|
}
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
const upstream = tainted.get(expression.text);
|
|
753
|
+
const upstream = typescriptSyntax.isIdentifier(expression)
|
|
754
|
+
? tainted.get(expression.text)
|
|
755
|
+
: fileReads ? taintedExpression(expression, parsedSource, tainted, fileReads, MAX_ALIAS_DEPTH - 1) : undefined;
|
|
407
756
|
if (upstream?.depth !== undefined && upstream.depth < MAX_ALIAS_DEPTH) {
|
|
408
757
|
return { line: upstream.line, kind: upstream.kind, depth: upstream.depth + 1 };
|
|
409
758
|
}
|
|
410
759
|
return undefined;
|
|
411
760
|
}
|
|
412
761
|
|
|
413
|
-
|
|
762
|
+
/**
|
|
763
|
+
* Propagate shared source provenance across every identifier in a binding pattern, including nested object and array destructuring.
|
|
764
|
+
* Array holes are ignored and tainted is mutated in place.
|
|
765
|
+
*
|
|
766
|
+
* @param name - identifier or destructuring binding pattern receiving provenance
|
|
767
|
+
* @param record - shared source provenance record assigned to each bound identifier
|
|
768
|
+
* @param tainted - mutable local provenance map updated in place
|
|
769
|
+
* @returns Nothing. Writes record into tainted for every identifier bound by name.
|
|
770
|
+
*/
|
|
414
771
|
function taintBindingNames(name: import("typescript").BindingName, record: TaintRecord, tainted: Map<string, TaintRecord>): void {
|
|
415
772
|
if (typescriptSyntax.isIdentifier(name)) {
|
|
416
773
|
tainted.set(name.text, record);
|
|
@@ -424,8 +781,14 @@ function taintBindingNames(name: import("typescript").BindingName, record: Taint
|
|
|
424
781
|
}
|
|
425
782
|
}
|
|
426
783
|
|
|
427
|
-
|
|
428
|
-
|
|
784
|
+
/**
|
|
785
|
+
* Record local variables initialized with XMLParser (processEntities: true) or DOMParser (resolveEntity) constructor options.
|
|
786
|
+
*
|
|
787
|
+
* @param parsedSource - parsed syntax tree used to inspect constructor text
|
|
788
|
+
* @param node - AST node tested as an identifier-bound variable declaration
|
|
789
|
+
* @param unsafeXmlParsers - mutable set receiving flagged local parser variable names for later XXE sink checks
|
|
790
|
+
* @returns Nothing. Adds matching local parser names to unsafeXmlParsers in place.
|
|
791
|
+
*/
|
|
429
792
|
function recordUnsafeXmlParser(parsedSource: TsSourceFile, node: TsNode, unsafeXmlParsers: Set<string>): void {
|
|
430
793
|
if (!typescriptSyntax.isVariableDeclaration(node) || !typescriptSyntax.isIdentifier(node.name) || !node.initializer) {
|
|
431
794
|
return;
|
|
@@ -435,29 +798,42 @@ function recordUnsafeXmlParser(parsedSource: TsSourceFile, node: TsNode, unsafeX
|
|
|
435
798
|
}
|
|
436
799
|
}
|
|
437
800
|
|
|
438
|
-
|
|
439
|
-
|
|
801
|
+
/**
|
|
802
|
+
* Check redirect assignments and sink calls for request-derived input.
|
|
803
|
+
* Same-line invariant: legacy scanners own these cases except for opted-in sink rules and unshadowed imported framework redirects.
|
|
804
|
+
*
|
|
805
|
+
* @param parsedSource - parsed file used to read expressions and locate them in source
|
|
806
|
+
* @param node - source node checked for an assignment or call
|
|
807
|
+
* @param inputs - tracked request flows and file readers used to distinguish path influence from content influence
|
|
808
|
+
* @param unsafeXmlParsers - parser names that qualify for the XML sink rule
|
|
809
|
+
* @param frameworkRedirectCallees - imported redirect names to recognize where their bindings are visible
|
|
810
|
+
* @param file - source file used to locate the emitted findings
|
|
811
|
+
* @param findings - caller's accumulator for qualifying findings
|
|
812
|
+
* @returns Nothing. Appends any matching findings to the accumulator.
|
|
813
|
+
*/
|
|
440
814
|
function reportSink(
|
|
441
815
|
parsedSource: TsSourceFile,
|
|
442
816
|
node: TsNode,
|
|
443
|
-
|
|
817
|
+
inputs: FlowInputs,
|
|
444
818
|
unsafeXmlParsers: ReadonlySet<string>,
|
|
445
819
|
frameworkRedirectCallees: ReadonlySet<string>,
|
|
446
820
|
file: SourceFile,
|
|
447
821
|
findings: Finding[],
|
|
448
822
|
): void {
|
|
449
|
-
reportRedirectAssignmentSink(parsedSource, node, tainted, file, findings);
|
|
823
|
+
reportRedirectAssignmentSink(parsedSource, node, inputs.tainted, file, findings);
|
|
450
824
|
const call = callLikeExpression(node);
|
|
451
825
|
if (!call) {
|
|
452
826
|
return;
|
|
453
827
|
}
|
|
454
828
|
const callee = call.expression.getText(parsedSource);
|
|
455
|
-
const isFrameworkRedirectCallee = frameworkRedirectCallees.has(callee) && !
|
|
829
|
+
const isFrameworkRedirectCallee = frameworkRedirectCallees.has(callee) && !isImportedCalleeShadowed(call, callee);
|
|
456
830
|
const sink = AST_FLOW_SINKS.find((candidate) => candidate.isSink({ callee, call, sourceFile: parsedSource, unsafeXmlParsers, isFrameworkRedirectCallee }));
|
|
457
831
|
if (!sink) {
|
|
458
832
|
return;
|
|
459
833
|
}
|
|
460
|
-
|
|
834
|
+
// A request-controlled filename proves path influence, not control of the bytes read.
|
|
835
|
+
const contentOnly = sink.ruleId === "security.unsafe-deserialization";
|
|
836
|
+
const hit = taintedInput(call, parsedSource, contentOnly ? inputs.contentTainted : inputs.tainted, contentOnly ? inputs.fileReadCallees : undefined);
|
|
461
837
|
if (!hit) {
|
|
462
838
|
return;
|
|
463
839
|
}
|
|
@@ -466,12 +842,43 @@ function reportSink(
|
|
|
466
842
|
if (sinkLine === hit.line && !reportsSameLine) {
|
|
467
843
|
return;
|
|
468
844
|
}
|
|
469
|
-
|
|
845
|
+
const sinkForm = sink.ruleId === "security.unsafe-deserialization" ? unsafeDeserializationSinkForm(callee) : undefined;
|
|
846
|
+
findings.push(flowFinding(file, sinkLine, sink.ruleId, sink.sinkKind, hit.kind, hit.depth, sinkForm));
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
type DeserializationSinkForm = "eval" | "function-constructor" | "unserialize" | "yaml-load" | "vm";
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* Classifies an unsafe-deserialization callee into a closed token so duplicate-eval merging never suppresses a co-located `vm` or `yaml` sink.
|
|
853
|
+
*
|
|
854
|
+
* @param callee - normalized sink callee text matched by `isUnsafeDeserializationSink`
|
|
855
|
+
* @returns Closed sink mechanism token (`"eval"`, `"function-constructor"`, `"unserialize"`, `"yaml-load"`, or `"vm"`).
|
|
856
|
+
*/
|
|
857
|
+
function unsafeDeserializationSinkForm(callee: string): DeserializationSinkForm {
|
|
858
|
+
if (/^eval$/.test(callee)) {
|
|
859
|
+
return "eval";
|
|
860
|
+
}
|
|
861
|
+
if (/^Function$/.test(callee)) {
|
|
862
|
+
return "function-constructor";
|
|
863
|
+
}
|
|
864
|
+
if (/(?:^|\.)unserialize$/.test(callee)) {
|
|
865
|
+
return "unserialize";
|
|
866
|
+
}
|
|
867
|
+
if (/^(?:yaml|YAML|jsYaml|jsyaml)\.load$/.test(callee)) {
|
|
868
|
+
return "yaml-load";
|
|
869
|
+
}
|
|
870
|
+
return "vm";
|
|
470
871
|
}
|
|
471
872
|
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
873
|
+
/**
|
|
874
|
+
* Check whether an imported callee's root name is rebound around a call by a parameter, local declaration, loop binding, or catch binding.
|
|
875
|
+
* Scans ancestors below the source file.
|
|
876
|
+
*
|
|
877
|
+
* @param call - AST call use site from which enclosing scopes are walked upward
|
|
878
|
+
* @param callee - source spelling of the callee whose root identifier is checked
|
|
879
|
+
* @returns True if callee's root name is shadowed by an enclosing binding, or false if unshadowed or root is empty.
|
|
880
|
+
*/
|
|
881
|
+
function isImportedCalleeShadowed(call: TsNode, callee: string): boolean {
|
|
475
882
|
const rootName = callee.split(".", 1)[0];
|
|
476
883
|
if (!rootName) {
|
|
477
884
|
return false;
|
|
@@ -484,9 +891,14 @@ function isFrameworkRedirectShadowed(call: TsCallLikeExpression, callee: string)
|
|
|
484
891
|
return false;
|
|
485
892
|
}
|
|
486
893
|
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
894
|
+
/**
|
|
895
|
+
* Check whether a function-like node binds an identifier through a parameter or its own declaration/expression name.
|
|
896
|
+
* Methods and accessors contribute only parameter bindings because their property names do not hide imported functions.
|
|
897
|
+
*
|
|
898
|
+
* @param node - AST node inspected as a function-like scope boundary
|
|
899
|
+
* @param name - identifier name checked for local binding
|
|
900
|
+
* @returns True if node binds name via parameter or function declaration/expression name; false for non-function nodes or no match.
|
|
901
|
+
*/
|
|
490
902
|
function functionLikeBindsName(node: TsNode, name: string): boolean {
|
|
491
903
|
if (!isFunctionLike(node)) {
|
|
492
904
|
return false;
|
|
@@ -502,8 +914,13 @@ function functionLikeBindsName(node: TsNode, name: string): boolean {
|
|
|
502
914
|
return functionNode.parameters.some((parameter) => bindingNameContains(parameter.name, name));
|
|
503
915
|
}
|
|
504
916
|
|
|
505
|
-
|
|
506
|
-
|
|
917
|
+
/**
|
|
918
|
+
* Check whether a lexical block or switch clause binds a name via direct runtime statements, including its temporal-dead-zone prefix.
|
|
919
|
+
*
|
|
920
|
+
* @param node - AST block, module block, case clause, or default clause to inspect
|
|
921
|
+
* @param name - identifier name checked against direct value declarations
|
|
922
|
+
* @returns True if node is a block or switch clause whose direct statements bind name; otherwise false.
|
|
923
|
+
*/
|
|
507
924
|
function lexicalStatementsBindName(node: TsNode, name: string): boolean {
|
|
508
925
|
if (typescriptSyntax.isBlock(node) || typescriptSyntax.isModuleBlock(node) || typescriptSyntax.isCaseClause(node) || typescriptSyntax.isDefaultClause(node)) {
|
|
509
926
|
return node.statements.some((statement) => statementBindsName(statement, name));
|
|
@@ -511,7 +928,13 @@ function lexicalStatementsBindName(node: TsNode, name: string): boolean {
|
|
|
511
928
|
return false;
|
|
512
929
|
}
|
|
513
930
|
|
|
514
|
-
|
|
931
|
+
/**
|
|
932
|
+
* Check whether a loop or catch clause binds an identifier in its catch variable or variable-declaration initializer.
|
|
933
|
+
*
|
|
934
|
+
* @param node - AST node inspected as a catch clause or for/for-in/for-of loop
|
|
935
|
+
* @param name - identifier name checked against the clause's local bindings
|
|
936
|
+
* @returns True if node binds name; missing catch variables, non-declaration loop initializers, and other node kinds return false.
|
|
937
|
+
*/
|
|
515
938
|
function loopOrCatchBindsName(node: TsNode, name: string): boolean {
|
|
516
939
|
if (typescriptSyntax.isCatchClause(node)) {
|
|
517
940
|
return node.variableDeclaration ? bindingNameContains(node.variableDeclaration.name, name) : false;
|
|
@@ -529,7 +952,14 @@ function loopOrCatchBindsName(node: TsNode, name: string): boolean {
|
|
|
529
952
|
return false;
|
|
530
953
|
}
|
|
531
954
|
|
|
532
|
-
|
|
955
|
+
/**
|
|
956
|
+
* Check whether a statement introduces a runtime value binding for name; only runtime declarations count
|
|
957
|
+
* because type-only declarations do not shadow an imported value.
|
|
958
|
+
*
|
|
959
|
+
* @param statement - AST statement checked for variable, function, class, enum, import-equals, or identifier namespace declarations
|
|
960
|
+
* @param name - identifier name tested against the statement's runtime bindings
|
|
961
|
+
* @returns True if statement declares a runtime binding matching name; otherwise false.
|
|
962
|
+
*/
|
|
533
963
|
function statementBindsName(statement: import("typescript").Statement, name: string): boolean {
|
|
534
964
|
if (typescriptSyntax.isVariableStatement(statement)) {
|
|
535
965
|
return variableDeclarationListBindsName(statement.declarationList, name);
|
|
@@ -546,12 +976,25 @@ function statementBindsName(statement: import("typescript").Statement, name: str
|
|
|
546
976
|
return false;
|
|
547
977
|
}
|
|
548
978
|
|
|
549
|
-
|
|
979
|
+
/**
|
|
980
|
+
* Check whether any declaration in a variable declaration list binds an identifier, including nested destructuring, for import-shadow checks.
|
|
981
|
+
*
|
|
982
|
+
* @param list - variable declaration list whose declarators are inspected
|
|
983
|
+
* @param name - identifier name checked across all declarator binding patterns
|
|
984
|
+
* @returns True if any declaration in list binds name; otherwise false.
|
|
985
|
+
*/
|
|
550
986
|
function variableDeclarationListBindsName(list: import("typescript").VariableDeclarationList, name: string): boolean {
|
|
551
987
|
return list.declarations.some((declaration) => bindingNameContains(declaration.name, name));
|
|
552
988
|
}
|
|
553
989
|
|
|
554
|
-
|
|
990
|
+
/**
|
|
991
|
+
* Check whether a binding pattern declares a local identifier, including nested object and array destructuring.
|
|
992
|
+
* Property keys and omitted array elements are ignored.
|
|
993
|
+
*
|
|
994
|
+
* @param bindingName - identifier or destructuring pattern inspected recursively
|
|
995
|
+
* @param name - target identifier name to match against bound locals
|
|
996
|
+
* @returns True if bindingName declares name; an empty binding pattern or non-matching pattern returns false.
|
|
997
|
+
*/
|
|
555
998
|
function bindingNameContains(bindingName: import("typescript").BindingName, name: string): boolean {
|
|
556
999
|
if (typescriptSyntax.isIdentifier(bindingName)) {
|
|
557
1000
|
return bindingName.text === name;
|
|
@@ -561,7 +1004,17 @@ function bindingNameContains(bindingName: import("typescript").BindingName, name
|
|
|
561
1004
|
);
|
|
562
1005
|
}
|
|
563
1006
|
|
|
564
|
-
|
|
1007
|
+
/**
|
|
1008
|
+
* Check for a location.href or window.location.href assignment receiving a direct source or tracked tainted value.
|
|
1009
|
+
* Same-line invariant: skips same-line hits because the legacy scanner looks for direct source tokens in the sink segment.
|
|
1010
|
+
*
|
|
1011
|
+
* @param parsedSource - parsed syntax tree used to inspect assignment text and sink line
|
|
1012
|
+
* @param node - AST node tested as an equals assignment to location.href or window.location.href
|
|
1013
|
+
* @param tainted - local provenance map consulted for right-hand side taint
|
|
1014
|
+
* @param file - discovered file whose display path locates emitted findings
|
|
1015
|
+
* @param findings - accumulator receiving cross-line open-redirect candidate findings
|
|
1016
|
+
* @returns Nothing. Appends a finding to findings when a cross-line assignment match qualifies.
|
|
1017
|
+
*/
|
|
565
1018
|
function reportRedirectAssignmentSink(parsedSource: TsSourceFile, node: TsNode, tainted: Map<string, TaintRecord>, file: SourceFile, findings: Finding[]): void {
|
|
566
1019
|
if (!typescriptSyntax.isBinaryExpression(node) || node.operatorToken.kind !== typescriptSyntax.SyntaxKind.EqualsToken) {
|
|
567
1020
|
return;
|
|
@@ -581,17 +1034,29 @@ function reportRedirectAssignmentSink(parsedSource: TsSourceFile, node: TsNode,
|
|
|
581
1034
|
findings.push(flowFinding(file, sinkLine, "security.open-redirect-candidate", "redirect", hit.kind, hit.depth));
|
|
582
1035
|
}
|
|
583
1036
|
|
|
584
|
-
|
|
585
|
-
|
|
1037
|
+
/**
|
|
1038
|
+
* Narrow an AST node to a call or constructor expression because both forms can be dynamic-regexp sinks handled through one interface.
|
|
1039
|
+
*
|
|
1040
|
+
* @param node - AST node checked for CallExpression or NewExpression syntax
|
|
1041
|
+
* @returns node unchanged when it is a call or constructor expression, or undefined when it is neither.
|
|
1042
|
+
*/
|
|
586
1043
|
function callLikeExpression(node: TsNode): TsCallLikeExpression | undefined {
|
|
587
1044
|
return typescriptSyntax.isCallExpression(node) || typescriptSyntax.isNewExpression(node) ? node : undefined;
|
|
588
1045
|
}
|
|
589
1046
|
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
1047
|
+
/**
|
|
1048
|
+
* Search call arguments in order for the first tainted expression record; prunes functions and sanitizer calls, though direct-source checks
|
|
1049
|
+
* can still see pruned function or sanitizer text in an ancestor.
|
|
1050
|
+
*
|
|
1051
|
+
* @param call - call or constructor expression whose arguments are searched in order
|
|
1052
|
+
* @param parsedSource - parsed syntax tree used for source-text extraction and line mapping
|
|
1053
|
+
* @param tainted - local provenance map consulted for tainted identifier references
|
|
1054
|
+
* @param fileReads - optional reader bindings that mask proven reader calls and exclude property-key aliases
|
|
1055
|
+
* @returns First source record found across arguments, or undefined for absent arguments or no match.
|
|
1056
|
+
*/
|
|
1057
|
+
function taintedInput(call: TsCallLikeExpression, parsedSource: TsSourceFile, tainted: Map<string, TaintRecord>, fileReads?: FileReadBindings): TaintRecord | undefined {
|
|
593
1058
|
for (const argument of call.arguments ?? []) {
|
|
594
|
-
const found = taintedExpression(argument, parsedSource, tainted);
|
|
1059
|
+
const found = taintedExpression(argument, parsedSource, tainted, fileReads);
|
|
595
1060
|
if (found) {
|
|
596
1061
|
return found;
|
|
597
1062
|
}
|
|
@@ -599,8 +1064,18 @@ function taintedInput(call: TsCallLikeExpression, parsedSource: TsSourceFile, ta
|
|
|
599
1064
|
return undefined;
|
|
600
1065
|
}
|
|
601
1066
|
|
|
602
|
-
|
|
603
|
-
|
|
1067
|
+
/**
|
|
1068
|
+
* Search an expression for direct sources or tainted aliases while pruning functions and sanitizer calls (direct-source checks can still see
|
|
1069
|
+
* their text because they scan ancestor text). With fileReads, skips proven reader calls and excludes property-key aliases.
|
|
1070
|
+
*
|
|
1071
|
+
* @param expression - root expression node walked for taint evidence
|
|
1072
|
+
* @param parsedSource - parsed syntax tree used for text extraction and line lookup
|
|
1073
|
+
* @param tainted - local provenance map consulted for tracked identifiers
|
|
1074
|
+
* @param fileReads - optional reader bindings enabling content-only filtering of proven reads and property keys
|
|
1075
|
+
* @param maxAliasDepth - depth limit applied to alias records only (defaults to MAX_ALIAS_DEPTH)
|
|
1076
|
+
* @returns First eligible taint record found, or undefined if none qualifies.
|
|
1077
|
+
*/
|
|
1078
|
+
function taintedExpression(expression: TsNode, parsedSource: TsSourceFile, tainted: Map<string, TaintRecord>, fileReads?: FileReadBindings, maxAliasDepth = MAX_ALIAS_DEPTH): TaintRecord | undefined {
|
|
604
1079
|
let found: TaintRecord | undefined;
|
|
605
1080
|
if (isFunctionLike(expression)) {
|
|
606
1081
|
return undefined;
|
|
@@ -612,17 +1087,16 @@ function taintedExpression(expression: TsNode, parsedSource: TsSourceFile, taint
|
|
|
612
1087
|
if (node !== expression && isFunctionLike(node)) {
|
|
613
1088
|
return false;
|
|
614
1089
|
}
|
|
1090
|
+
if (fileReads && isImportedFileRead(node, parsedSource, fileReads)) return false;
|
|
615
1091
|
if (isSafeWrapperExpression(parsedSource, node)) {
|
|
616
1092
|
return false;
|
|
617
1093
|
}
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
return false;
|
|
623
|
-
}
|
|
1094
|
+
const record = taintedIdentifierRecord(node, tainted, maxAliasDepth, fileReads !== undefined);
|
|
1095
|
+
if (record) {
|
|
1096
|
+
found = record;
|
|
1097
|
+
return false;
|
|
624
1098
|
}
|
|
625
|
-
const kind = sourceKindOf(parsedSource, node);
|
|
1099
|
+
const kind = sourceKindOf(parsedSource, node, fileReads);
|
|
626
1100
|
if (kind !== undefined) {
|
|
627
1101
|
found = { line: lineIndexOf(parsedSource, node), kind, depth: 0 };
|
|
628
1102
|
return false;
|
|
@@ -632,7 +1106,31 @@ function taintedExpression(expression: TsNode, parsedSource: TsSourceFile, taint
|
|
|
632
1106
|
return found;
|
|
633
1107
|
}
|
|
634
1108
|
|
|
635
|
-
|
|
1109
|
+
/**
|
|
1110
|
+
* Look up an identifier in tainted only when its alias depth does not exceed maxAliasDepth.
|
|
1111
|
+
*
|
|
1112
|
+
* @param node - AST node tested as a local identifier reference
|
|
1113
|
+
* @param tainted - local provenance map indexed by identifier name
|
|
1114
|
+
* @param maxAliasDepth - maximum alias depth permitted for returned records
|
|
1115
|
+
* @param contentOnly - when true, excludes property-access names and property-assignment keys so key spelling cannot stand in for a local value
|
|
1116
|
+
* @returns Matching source record within the depth limit, or undefined for non-identifiers, excluded keys, unknown locals, or deeper records.
|
|
1117
|
+
*/
|
|
1118
|
+
function taintedIdentifierRecord(node: TsNode, tainted: Map<string, TaintRecord>, maxAliasDepth: number, contentOnly: boolean): TaintRecord | undefined {
|
|
1119
|
+
if (!typescriptSyntax.isIdentifier(node)) return undefined;
|
|
1120
|
+
const propertyKey = isPropertyAccessName(node) || (typescriptSyntax.isPropertyAssignment(node.parent) && node.parent.name === node);
|
|
1121
|
+
if (contentOnly && propertyKey) return undefined;
|
|
1122
|
+
const record = tainted.get(node.text);
|
|
1123
|
+
return record && record.depth <= maxAliasDepth ? record : undefined;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/**
|
|
1127
|
+
* Check whether a call's spelling identifies a supported deserialization or dynamic-code sink.
|
|
1128
|
+
*
|
|
1129
|
+
* @param callee - source text of the call or constructor callee
|
|
1130
|
+
* @param call - call expression supplying arguments for YAML schema checks
|
|
1131
|
+
* @param parsedSource - parsed syntax tree used to read argument text
|
|
1132
|
+
* @returns True for supported deserialization or dynamic-code sinks; safe-schema YAML loads and other names return false.
|
|
1133
|
+
*/
|
|
636
1134
|
function isUnsafeDeserializationSink(callee: string, call: TsCallLikeExpression, parsedSource: TsSourceFile): boolean {
|
|
637
1135
|
return (
|
|
638
1136
|
/^eval$/.test(callee) ||
|
|
@@ -644,7 +1142,14 @@ function isUnsafeDeserializationSink(callee: string, call: TsCallLikeExpression,
|
|
|
644
1142
|
);
|
|
645
1143
|
}
|
|
646
1144
|
|
|
647
|
-
|
|
1145
|
+
/**
|
|
1146
|
+
* Check whether a call is a recognized YAML load lacking safe-schema option text; missing options make a recognized load unsafe.
|
|
1147
|
+
*
|
|
1148
|
+
* @param callee - source text of the call target matched against recognized YAML loaders
|
|
1149
|
+
* @param call - call expression whose second argument is checked for safe-schema options
|
|
1150
|
+
* @param parsedSource - parsed syntax tree used to inspect option text
|
|
1151
|
+
* @returns True if callee is a recognized YAML load without safe-schema options; other callees return false.
|
|
1152
|
+
*/
|
|
648
1153
|
function isUnsafeYamlLoad(callee: string, call: TsCallLikeExpression, parsedSource: TsSourceFile): boolean {
|
|
649
1154
|
if (!/^(?:yaml|YAML|jsYaml|jsyaml)\.load$/.test(callee)) {
|
|
650
1155
|
return false;
|
|
@@ -652,13 +1157,27 @@ function isUnsafeYamlLoad(callee: string, call: TsCallLikeExpression, parsedSour
|
|
|
652
1157
|
return !hasSafeYamlSchema(call, parsedSource);
|
|
653
1158
|
}
|
|
654
1159
|
|
|
655
|
-
|
|
1160
|
+
/**
|
|
1161
|
+
* Check whether a YAML load's second argument text contains schema: followed by FAILSAFE_SCHEMA, JSON_SCHEMA, or CORE_SCHEMA.
|
|
1162
|
+
* Accepts an optional qualifier and can also match nested, quoted, or commented text.
|
|
1163
|
+
*
|
|
1164
|
+
* @param call - call expression whose second argument supplies YAML options
|
|
1165
|
+
* @param parsedSource - parsed syntax tree used to read the options argument text
|
|
1166
|
+
* @returns True when safe-schema text is found; missing options return false so the YAML load receives no safe-schema exemption.
|
|
1167
|
+
*/
|
|
656
1168
|
function hasSafeYamlSchema(call: TsCallLikeExpression, parsedSource: TsSourceFile): boolean {
|
|
657
1169
|
const options = call.arguments?.[1];
|
|
658
1170
|
return options !== undefined && /\bschema\s*:\s*(?:[A-Za-z_$][A-Za-z0-9_$]*\.)?(?:FAILSAFE_SCHEMA|JSON_SCHEMA|CORE_SCHEMA)\b/.test(options.getText(parsedSource));
|
|
659
1171
|
}
|
|
660
1172
|
|
|
661
|
-
|
|
1173
|
+
/**
|
|
1174
|
+
* Check callee text and call options for XXE sink syntax, including locals initialized by flagged parser constructions.
|
|
1175
|
+
*
|
|
1176
|
+
* @param callee - source text of the call target checked for parser methods or inline construction
|
|
1177
|
+
* @param call - call expression whose arguments are checked for unsafe libxml options
|
|
1178
|
+
* @param unsafeXmlParsers - local parser variable names recorded as constructed with entity expansion enabled
|
|
1179
|
+
* @returns True for flagged libxml options, recorded parser methods, or inline unsafe parser constructions; otherwise false.
|
|
1180
|
+
*/
|
|
662
1181
|
function isXxeSink(callee: string, call: TsCallLikeExpression, unsafeXmlParsers: ReadonlySet<string>): boolean {
|
|
663
1182
|
const parserMethod = callee.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.(?:parse|parseFromString)$/);
|
|
664
1183
|
return (
|
|
@@ -668,18 +1187,33 @@ function isXxeSink(callee: string, call: TsCallLikeExpression, unsafeXmlParsers:
|
|
|
668
1187
|
);
|
|
669
1188
|
}
|
|
670
1189
|
|
|
671
|
-
|
|
1190
|
+
/**
|
|
1191
|
+
* Check whether a callee names parseXml or parseXmlString, optionally qualified by libxmljs, for subsequent unsafe-option checks.
|
|
1192
|
+
* A name match alone does not establish entity expansion because the caller checks the call's options.
|
|
1193
|
+
*
|
|
1194
|
+
* @param callee - source text of the call expression target
|
|
1195
|
+
* @returns True if callee matches parseXml or parseXmlString (optionally prefixed with libxmljs); otherwise false.
|
|
1196
|
+
*/
|
|
672
1197
|
function isLibxmlEntityExpandingCall(callee: string): boolean {
|
|
673
1198
|
return /^(?:libxmljs\.)?(?:parseXml|parseXmlString)$/.test(callee);
|
|
674
1199
|
}
|
|
675
1200
|
|
|
676
|
-
|
|
1201
|
+
/**
|
|
1202
|
+
* Perform textual option checks on call arguments for unsafe XML entity-expansion flags.
|
|
1203
|
+
*
|
|
1204
|
+
* @param call - call expression whose arguments are inspected as source text
|
|
1205
|
+
* @returns True if any argument contains noent, dtdload, or processEntities set to true, or a resolveEntity property; missing arguments return false.
|
|
1206
|
+
*/
|
|
677
1207
|
function hasUnsafeXmlParserOption(call: TsCallLikeExpression): boolean {
|
|
678
1208
|
return (call.arguments ?? []).some((argument) => /\b(?:noent|dtdload|processEntities)\s*:\s*true\b|\bresolveEntity\s*:/.test(argument.getText()));
|
|
679
1209
|
}
|
|
680
1210
|
|
|
681
|
-
|
|
682
|
-
|
|
1211
|
+
/**
|
|
1212
|
+
* Check whether callee text matches an inline XMLParser or DOMParser call with entity-expansion option syntax.
|
|
1213
|
+
*
|
|
1214
|
+
* @param callee - source text of the call target
|
|
1215
|
+
* @returns True for inline new XMLParser(...).parse with processEntities: true or new DOMParser(...).parseFromString with resolveEntity; else false.
|
|
1216
|
+
*/
|
|
683
1217
|
function isInlineUnsafeXmlParserCall(callee: string): boolean {
|
|
684
1218
|
return (
|
|
685
1219
|
/\bnew\s+XMLParser\s*\([^)]*\bprocessEntities\s*:\s*true[^)]*\)\.parse$/.test(callee) ||
|
|
@@ -687,7 +1221,13 @@ function isInlineUnsafeXmlParserCall(callee: string): boolean {
|
|
|
687
1221
|
);
|
|
688
1222
|
}
|
|
689
1223
|
|
|
690
|
-
|
|
1224
|
+
/**
|
|
1225
|
+
* Check whether an expression constructs XMLParser (with processEntities: true) or DOMParser (with resolveEntity).
|
|
1226
|
+
*
|
|
1227
|
+
* @param parsedSource - parsed syntax tree used to inspect constructor callee and argument text
|
|
1228
|
+
* @param expr - AST expression tested as a NewExpression parser construction
|
|
1229
|
+
* @returns True for recognized XMLParser or DOMParser constructions containing unsafe-option syntax; other expressions return false.
|
|
1230
|
+
*/
|
|
691
1231
|
function isUnsafeXmlParserConstruction(parsedSource: TsSourceFile, expr: TsNode): boolean {
|
|
692
1232
|
if (!typescriptSyntax.isNewExpression(expr)) {
|
|
693
1233
|
return false;
|
|
@@ -700,17 +1240,39 @@ function isUnsafeXmlParserConstruction(parsedSource: TsSourceFile, expr: TsNode)
|
|
|
700
1240
|
);
|
|
701
1241
|
}
|
|
702
1242
|
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
1243
|
+
/**
|
|
1244
|
+
* Identify the first recognized external-input source in an expression so a flow finding can report where an unchecked value came from.
|
|
1245
|
+
*
|
|
1246
|
+
* @param parsedSource - parsed syntax tree used to inspect wrapper calls and blank nested handler parameters
|
|
1247
|
+
* @param expr - AST expression evaluated for external-input tokens
|
|
1248
|
+
* @param fileReads - optional reader bindings whose calls are masked so file contents remain distinct from file paths
|
|
1249
|
+
* @returns First matching source kind string, or undefined for no input evidence such as plain text or a recognized escaping call.
|
|
1250
|
+
*/
|
|
1251
|
+
function sourceKindOf(parsedSource: TsSourceFile, expr: TsNode, fileReads?: FileReadBindings): string | undefined {
|
|
1252
|
+
// A recognized escaping helper is evidence that the developer prepared the value for this check.
|
|
706
1253
|
if (isSafeWrapperExpression(parsedSource, expr)) {
|
|
707
1254
|
return undefined;
|
|
708
1255
|
}
|
|
1256
|
+
// A literal in code or a template with no substitutions supplies text rather than a request value.
|
|
709
1257
|
if (isSourceTextLiteral(expr)) {
|
|
710
1258
|
return undefined;
|
|
711
1259
|
}
|
|
712
|
-
|
|
1260
|
+
let text = textOutsideRequestHandlers(parsedSource, expr);
|
|
1261
|
+
// Without recognized file reads, there are no read paths to mask from input classification.
|
|
1262
|
+
if (fileReads?.size) {
|
|
1263
|
+
const start = expr.getStart(parsedSource);
|
|
1264
|
+
walk(expr, (node) => {
|
|
1265
|
+
// Keep other calls visible. A file read's path is separate from the file contents the developer uses.
|
|
1266
|
+
if (!isImportedFileRead(node, parsedSource, fileReads)) return;
|
|
1267
|
+
const from = node.getStart(parsedSource) - start;
|
|
1268
|
+
const endOffset = node.getEnd() - start;
|
|
1269
|
+
text = text.slice(0, from) + " ".repeat(endOffset - from) + text.slice(endOffset);
|
|
1270
|
+
return false;
|
|
1271
|
+
});
|
|
1272
|
+
}
|
|
1273
|
+
// Use the first recognized input kind to describe the starting point in the finding.
|
|
713
1274
|
for (const token of SOURCE_TOKENS) {
|
|
1275
|
+
// When the remaining source matches this check, show its input kind in the report.
|
|
714
1276
|
if (token.pattern.test(text)) {
|
|
715
1277
|
return token.kind;
|
|
716
1278
|
}
|
|
@@ -718,13 +1280,107 @@ function sourceKindOf(parsedSource: TsSourceFile, expr: TsNode): string | undefi
|
|
|
718
1280
|
return undefined;
|
|
719
1281
|
}
|
|
720
1282
|
|
|
721
|
-
|
|
1283
|
+
/**
|
|
1284
|
+
* Blank local request parameters inside nested non-contributing handlers while retaining source offsets and evidence from value-producing callbacks.
|
|
1285
|
+
*
|
|
1286
|
+
* @param parsedSource - parsed syntax tree used to locate expression and parameter offsets
|
|
1287
|
+
* @param expr - AST expression whose text is filtered for nested handler request bindings
|
|
1288
|
+
* @returns Expression text with non-contributing nested handler request parameters replaced by spaces.
|
|
1289
|
+
*/
|
|
1290
|
+
function textOutsideRequestHandlers(parsedSource: TsSourceFile, expr: TsNode): string {
|
|
1291
|
+
const expressionStart = expr.getStart(parsedSource);
|
|
1292
|
+
let text = expr.getText(parsedSource);
|
|
1293
|
+
walk(expr, (node) => {
|
|
1294
|
+
// Keep expressions and value-producing callbacks in view when they can supply input to the current finding.
|
|
1295
|
+
if (node === expr || !isFunctionLike(node) || contributesCallbackValue(node)) {
|
|
1296
|
+
return;
|
|
1297
|
+
}
|
|
1298
|
+
const declaredNames = declaredRequestParameterNames(node);
|
|
1299
|
+
// A nested handler with no recognized request parameter has no local request names to hide.
|
|
1300
|
+
if (declaredNames.size === 0) {
|
|
1301
|
+
return;
|
|
1302
|
+
}
|
|
1303
|
+
walk(node, (inner) => {
|
|
1304
|
+
// Mask the handler's parameter references. A property named req, such as this.req, is a different binding.
|
|
1305
|
+
if (typescriptSyntax.isIdentifier(inner) && declaredNames.has(inner.text) && !isPropertyAccessName(inner)) {
|
|
1306
|
+
const blankStart = inner.getStart(parsedSource) - expressionStart;
|
|
1307
|
+
const blankEnd = inner.getEnd() - expressionStart;
|
|
1308
|
+
text = text.slice(0, blankStart) + " ".repeat(blankEnd - blankStart) + text.slice(blankEnd);
|
|
1309
|
+
}
|
|
1310
|
+
});
|
|
1311
|
+
return;
|
|
1312
|
+
});
|
|
1313
|
+
return text;
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
/**
|
|
1317
|
+
* Collect direct identifier parameter names matching req, request, or ctx for the scanner's name-based filter.
|
|
1318
|
+
*
|
|
1319
|
+
* @param node - function-like AST node whose direct parameter list is inspected
|
|
1320
|
+
* @returns Set of matching parameter names; an empty set means the scanner skips blanking for this function.
|
|
1321
|
+
*/
|
|
1322
|
+
function declaredRequestParameterNames(node: TsNode): Set<string> {
|
|
1323
|
+
const { parameters } = node as import("typescript").SignatureDeclaration;
|
|
1324
|
+
return new Set(parameters.flatMap((parameter) => (typescriptSyntax.isIdentifier(parameter.name) && REQUEST_RECEIVER_NAMES.has(parameter.name.text) ? [parameter.name.text] : [])));
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
/**
|
|
1328
|
+
* Check whether a function-like node is immediately invoked or passed to a known value-producing collection/promise method.
|
|
1329
|
+
*
|
|
1330
|
+
* @param node - function-like AST node whose parent call context is inspected
|
|
1331
|
+
* @returns True when the callback can contribute its return value to the enclosing expression; otherwise false.
|
|
1332
|
+
*/
|
|
1333
|
+
function contributesCallbackValue(node: TsNode): boolean {
|
|
1334
|
+
// Extra parentheses around a function do not change whether its value is used.
|
|
1335
|
+
while (typescriptSyntax.isParenthesizedExpression(node.parent)) {
|
|
1336
|
+
node = node.parent;
|
|
1337
|
+
}
|
|
1338
|
+
const parent = node.parent;
|
|
1339
|
+
// Developers can invoke a function through call or apply. Reading one of those properties alone supplies no result.
|
|
1340
|
+
if (typescriptSyntax.isPropertyAccessExpression(parent) && parent.expression === node) {
|
|
1341
|
+
return (parent.name.text === "call" || parent.name.text === "apply")
|
|
1342
|
+
&& typescriptSyntax.isCallExpression(parent.parent) && parent.parent.expression === parent;
|
|
1343
|
+
}
|
|
1344
|
+
// A function merely stored as a value does not contribute its body to the current finding.
|
|
1345
|
+
if (!typescriptSyntax.isCallExpression(parent)) {
|
|
1346
|
+
return false;
|
|
1347
|
+
}
|
|
1348
|
+
// An immediately invoked function can pass its return value into the expression being checked.
|
|
1349
|
+
if (parent.expression === node) {
|
|
1350
|
+
return true;
|
|
1351
|
+
}
|
|
1352
|
+
// Known collection and promise methods use a callback result, such as a value returned from then.
|
|
1353
|
+
return parent.arguments[0] === node && typescriptSyntax.isPropertyAccessExpression(parent.expression)
|
|
1354
|
+
&& /^(?:map|flatMap|reduce|reduceRight|then|catch)$/u.test(parent.expression.name.text);
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
/**
|
|
1358
|
+
* Check whether a node is the property name of a dotted property access (such as this.req), where it reads no local binding.
|
|
1359
|
+
*
|
|
1360
|
+
* @param identifier - AST node compared against its parent PropertyAccessExpression name
|
|
1361
|
+
* @returns True when identifier names the property in a dotted access; otherwise false.
|
|
1362
|
+
*/
|
|
1363
|
+
function isPropertyAccessName(identifier: TsNode): boolean {
|
|
1364
|
+
return typescriptSyntax.isPropertyAccessExpression(identifier.parent) && identifier.parent.name === identifier;
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
/**
|
|
1368
|
+
* Check whether an expression is plain literal text rather than an interpolated template or dynamic expression.
|
|
1369
|
+
*
|
|
1370
|
+
* @param expr - AST expression tested as a string literal or substitution-free template literal
|
|
1371
|
+
* @returns True for string literals and substitution-free template literals; other expressions including interpolating templates return false.
|
|
1372
|
+
*/
|
|
722
1373
|
function isSourceTextLiteral(expr: TsNode): boolean {
|
|
723
1374
|
return typescriptSyntax.isStringLiteral(expr) || typescriptSyntax.isNoSubstitutionTemplateLiteral(expr);
|
|
724
1375
|
}
|
|
725
1376
|
|
|
726
|
-
|
|
727
|
-
|
|
1377
|
+
/**
|
|
1378
|
+
* Check whether an expression calls a recognized regexp-escaping helper so callers can treat it as sanitizer evidence and skip its argument subtree.
|
|
1379
|
+
*
|
|
1380
|
+
* @param parsedSource - parsed syntax tree used to extract the call target text
|
|
1381
|
+
* @param expr - AST node tested as a CallExpression
|
|
1382
|
+
* @returns True when expr calls a recognized regexp-escaping helper; non-calls and other names return false.
|
|
1383
|
+
*/
|
|
728
1384
|
function isSafeWrapperExpression(parsedSource: TsSourceFile, expr: TsNode): boolean {
|
|
729
1385
|
if (!typescriptSyntax.isCallExpression(expr)) {
|
|
730
1386
|
return false;
|
|
@@ -733,7 +1389,12 @@ function isSafeWrapperExpression(parsedSource: TsSourceFile, expr: TsNode): bool
|
|
|
733
1389
|
return /^(?:escapeRegExp|escapeStringRegexp|regexpEscape|RegExp\.escape)$/.test(callee);
|
|
734
1390
|
}
|
|
735
1391
|
|
|
736
|
-
|
|
1392
|
+
/**
|
|
1393
|
+
* Check whether an AST node is a function-like boundary that receives separate taint analysis.
|
|
1394
|
+
*
|
|
1395
|
+
* @param node - AST node tested against function, arrow, method, constructor, and accessor kinds
|
|
1396
|
+
* @returns True for functions, arrows, methods, constructors, and accessors; other nodes return false.
|
|
1397
|
+
*/
|
|
737
1398
|
function isFunctionLike(node: TsNode): boolean {
|
|
738
1399
|
return (
|
|
739
1400
|
typescriptSyntax.isFunctionDeclaration(node) ||
|
|
@@ -756,8 +1417,18 @@ function isFunctionLike(node: TsNode): boolean {
|
|
|
756
1417
|
* @param sinkKind - sink category for machine-readable metadata
|
|
757
1418
|
* @param sourceKind - external input category for machine-readable metadata
|
|
758
1419
|
* @param flowDepth - bounded alias distance between source and sink
|
|
1420
|
+
* @param sinkForm - closed sink mechanism token attached for `security.unsafe-deserialization`; omit for other rules
|
|
1421
|
+
* @returns A medium-confidence security warning on the one-based sink line, with the rule's own message and remediation or generic cross-line text.
|
|
759
1422
|
*/
|
|
760
|
-
function flowFinding(
|
|
1423
|
+
function flowFinding(
|
|
1424
|
+
file: SourceFile,
|
|
1425
|
+
lineIndex: number,
|
|
1426
|
+
ruleId: string,
|
|
1427
|
+
sinkKind: string,
|
|
1428
|
+
sourceKind: string,
|
|
1429
|
+
flowDepth: number,
|
|
1430
|
+
sinkForm?: DeserializationSinkForm,
|
|
1431
|
+
): Finding {
|
|
761
1432
|
const base = securityRuleDetails(ruleId);
|
|
762
1433
|
return makeFinding({
|
|
763
1434
|
ruleId,
|
|
@@ -768,11 +1439,16 @@ function flowFinding(file: SourceFile, lineIndex: number, ruleId: string, sinkKi
|
|
|
768
1439
|
pillar: "security",
|
|
769
1440
|
confidence: "medium",
|
|
770
1441
|
remediation: base ? base.remediation : "Validate external input before it reaches the sink.",
|
|
771
|
-
metadata: { sourceKind, sinkKind, flowDepth },
|
|
1442
|
+
metadata: { sourceKind, sinkKind, flowDepth, ...(sinkForm === undefined ? {} : { sinkForm }) },
|
|
772
1443
|
});
|
|
773
1444
|
}
|
|
774
1445
|
|
|
775
|
-
|
|
1446
|
+
/**
|
|
1447
|
+
* Look up message and remediation text for both same-line rule ids and AST-only security candidates.
|
|
1448
|
+
*
|
|
1449
|
+
* @param ruleId - security rule identifier emitted by a same-line or AST flow sink
|
|
1450
|
+
* @returns Message and remediation pair for known rules, or undefined if ruleId is unrecognized.
|
|
1451
|
+
*/
|
|
776
1452
|
function securityRuleDetails(ruleId: string): Pick<SecurityFlowRule, "message" | "remediation"> | undefined {
|
|
777
1453
|
return (
|
|
778
1454
|
SECURITY_FLOW_RULES.find((rule) => rule.ruleId === ruleId) ??
|