circle-ir 4.22.0 → 4.24.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/configs/sink-semantics.json +6 -0
- package/dist/analysis/config-loader.d.ts.map +1 -1
- package/dist/analysis/config-loader.js +24 -5
- package/dist/analysis/config-loader.js.map +1 -1
- package/dist/analysis/constant-propagation/patterns.d.ts +16 -8
- package/dist/analysis/constant-propagation/patterns.d.ts.map +1 -1
- package/dist/analysis/constant-propagation/patterns.js +18 -9
- package/dist/analysis/constant-propagation/patterns.js.map +1 -1
- package/dist/analysis/findings.d.ts +8 -1
- package/dist/analysis/findings.d.ts.map +1 -1
- package/dist/analysis/findings.js +67 -5
- package/dist/analysis/findings.js.map +1 -1
- package/dist/analysis/hono-env.d.ts +24 -0
- package/dist/analysis/hono-env.d.ts.map +1 -0
- package/dist/analysis/hono-env.js +105 -0
- package/dist/analysis/hono-env.js.map +1 -0
- package/dist/analysis/html/html-extractor.d.ts +6 -0
- package/dist/analysis/html/html-extractor.d.ts.map +1 -1
- package/dist/analysis/html/html-extractor.js +16 -0
- package/dist/analysis/html/html-extractor.js.map +1 -1
- package/dist/analysis/interprocedural.d.ts.map +1 -1
- package/dist/analysis/interprocedural.js +51 -2
- package/dist/analysis/interprocedural.js.map +1 -1
- package/dist/analysis/js-helper-return.d.ts +7 -0
- package/dist/analysis/js-helper-return.d.ts.map +1 -1
- package/dist/analysis/js-helper-return.js +165 -0
- package/dist/analysis/js-helper-return.js.map +1 -1
- package/dist/analysis/js-spawn-argv.d.ts +34 -0
- package/dist/analysis/js-spawn-argv.d.ts.map +1 -0
- package/dist/analysis/js-spawn-argv.js +156 -0
- package/dist/analysis/js-spawn-argv.js.map +1 -0
- package/dist/analysis/maven-declared.d.ts.map +1 -1
- package/dist/analysis/maven-declared.js +5 -1
- package/dist/analysis/maven-declared.js.map +1 -1
- package/dist/analysis/passes/cli-main-reflection-suppress-pass.d.ts +1 -1
- package/dist/analysis/passes/cli-main-reflection-suppress-pass.d.ts.map +1 -1
- package/dist/analysis/passes/cli-main-reflection-suppress-pass.js +3 -1
- package/dist/analysis/passes/cli-main-reflection-suppress-pass.js.map +1 -1
- package/dist/analysis/passes/cross-file-pass.d.ts.map +1 -1
- package/dist/analysis/passes/cross-file-pass.js +2 -1
- package/dist/analysis/passes/cross-file-pass.js.map +1 -1
- package/dist/analysis/passes/interprocedural-pass.d.ts.map +1 -1
- package/dist/analysis/passes/interprocedural-pass.js +113 -2
- package/dist/analysis/passes/interprocedural-pass.js.map +1 -1
- package/dist/analysis/passes/language-sources-pass.d.ts +15 -0
- package/dist/analysis/passes/language-sources-pass.d.ts.map +1 -1
- package/dist/analysis/passes/language-sources-pass.js +1551 -119
- package/dist/analysis/passes/language-sources-pass.js.map +1 -1
- package/dist/analysis/passes/module-side-effect-pass.d.ts +9 -0
- package/dist/analysis/passes/module-side-effect-pass.d.ts.map +1 -1
- package/dist/analysis/passes/module-side-effect-pass.js +30 -3
- package/dist/analysis/passes/module-side-effect-pass.js.map +1 -1
- package/dist/analysis/passes/orphan-module-pass.d.ts +6 -1
- package/dist/analysis/passes/orphan-module-pass.d.ts.map +1 -1
- package/dist/analysis/passes/orphan-module-pass.js +6 -1
- package/dist/analysis/passes/orphan-module-pass.js.map +1 -1
- package/dist/analysis/passes/param-source-flow-gate-pass.d.ts.map +1 -1
- package/dist/analysis/passes/param-source-flow-gate-pass.js +2 -1
- package/dist/analysis/passes/param-source-flow-gate-pass.js.map +1 -1
- package/dist/analysis/passes/scan-secrets-pass.d.ts +8 -0
- package/dist/analysis/passes/scan-secrets-pass.d.ts.map +1 -1
- package/dist/analysis/passes/scan-secrets-pass.js +78 -10
- package/dist/analysis/passes/scan-secrets-pass.js.map +1 -1
- package/dist/analysis/passes/sink-filter-pass.d.ts +17 -0
- package/dist/analysis/passes/sink-filter-pass.d.ts.map +1 -1
- package/dist/analysis/passes/sink-filter-pass.js +691 -7
- package/dist/analysis/passes/sink-filter-pass.js.map +1 -1
- package/dist/analysis/passes/taint-propagation-pass.d.ts +19 -0
- package/dist/analysis/passes/taint-propagation-pass.d.ts.map +1 -1
- package/dist/analysis/passes/taint-propagation-pass.js +116 -12
- package/dist/analysis/passes/taint-propagation-pass.js.map +1 -1
- package/dist/analysis/require-entry-path.d.ts +4 -1
- package/dist/analysis/require-entry-path.d.ts.map +1 -1
- package/dist/analysis/require-entry-path.js +150 -7
- package/dist/analysis/require-entry-path.js.map +1 -1
- package/dist/analysis/rules.d.ts +7 -0
- package/dist/analysis/rules.d.ts.map +1 -1
- package/dist/analysis/rules.js +65 -0
- package/dist/analysis/rules.js.map +1 -1
- package/dist/analysis/sbom.d.ts +32 -4
- package/dist/analysis/sbom.d.ts.map +1 -1
- package/dist/analysis/sbom.js +57 -19
- package/dist/analysis/sbom.js.map +1 -1
- package/dist/analysis/taint-matcher.d.ts.map +1 -1
- package/dist/analysis/taint-matcher.js +85 -8
- package/dist/analysis/taint-matcher.js.map +1 -1
- package/dist/analysis/taint-propagation.d.ts +7 -0
- package/dist/analysis/taint-propagation.d.ts.map +1 -1
- package/dist/analysis/taint-propagation.js +84 -0
- package/dist/analysis/taint-propagation.js.map +1 -1
- package/dist/analysis/test-to-production-taint-gate.d.ts.map +1 -1
- package/dist/analysis/test-to-production-taint-gate.js +6 -2
- package/dist/analysis/test-to-production-taint-gate.js.map +1 -1
- package/dist/analyzer.d.ts +30 -5
- package/dist/analyzer.d.ts.map +1 -1
- package/dist/analyzer.js +93 -13
- package/dist/analyzer.js.map +1 -1
- package/dist/browser/circle-ir.js +11477 -8820
- package/dist/core/circle-ir-core.cjs +351 -28
- package/dist/core/circle-ir-core.js +351 -28
- package/dist/core/extractors/calls.d.ts.map +1 -1
- package/dist/core/extractors/calls.js +83 -1
- package/dist/core/extractors/calls.js.map +1 -1
- package/dist/core/extractors/meta.d.ts +3 -2
- package/dist/core/extractors/meta.d.ts.map +1 -1
- package/dist/core/extractors/meta.js +3 -2
- package/dist/core/extractors/meta.js.map +1 -1
- package/dist/core/extractors/runtime-registrations.js +5 -2
- package/dist/core/extractors/runtime-registrations.js.map +1 -1
- package/dist/core/extractors/types.d.ts +3 -2
- package/dist/core/extractors/types.d.ts.map +1 -1
- package/dist/core/extractors/types.js +22 -20
- package/dist/core/extractors/types.js.map +1 -1
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +1 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/parser.d.ts +11 -6
- package/dist/core/parser.d.ts.map +1 -1
- package/dist/core/parser.js +29 -5
- package/dist/core/parser.js.map +1 -1
- package/dist/core/partial-parse-recovery.d.ts +26 -0
- package/dist/core/partial-parse-recovery.d.ts.map +1 -0
- package/dist/core/partial-parse-recovery.js +129 -0
- package/dist/core/partial-parse-recovery.js.map +1 -0
- package/dist/graph/code-graph.d.ts +1 -0
- package/dist/graph/code-graph.d.ts.map +1 -1
- package/dist/graph/code-graph.js +1 -0
- package/dist/graph/code-graph.js.map +1 -1
- package/dist/graph/import-graph.d.ts +14 -4
- package/dist/graph/import-graph.d.ts.map +1 -1
- package/dist/graph/import-graph.js +72 -9
- package/dist/graph/import-graph.js.map +1 -1
- package/dist/graph-facts/dead-code.d.ts +2 -0
- package/dist/graph-facts/dead-code.d.ts.map +1 -1
- package/dist/graph-facts/dead-code.js +126 -1
- package/dist/graph-facts/dead-code.js.map +1 -1
- package/dist/graph-facts/index.d.ts +1 -1
- package/dist/graph-facts/index.d.ts.map +1 -1
- package/dist/graph-facts/index.js +1 -1
- package/dist/graph-facts/index.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/languages/plugins/javascript.d.ts.map +1 -1
- package/dist/languages/plugins/javascript.js +1 -1
- package/dist/languages/plugins/javascript.js.map +1 -1
- package/dist/languages/registry.d.ts.map +1 -1
- package/dist/languages/registry.js +12 -0
- package/dist/languages/registry.js.map +1 -1
- package/dist/navigation/index.d.ts +1 -1
- package/dist/navigation/index.d.ts.map +1 -1
- package/dist/navigation/index.js.map +1 -1
- package/dist/navigation/navigation-index.js +3 -1
- package/dist/navigation/navigation-index.js.map +1 -1
- package/dist/navigation/python-graph.d.ts +3 -1
- package/dist/navigation/python-graph.d.ts.map +1 -1
- package/dist/navigation/python-graph.js +236 -23
- package/dist/navigation/python-graph.js.map +1 -1
- package/dist/navigation/ts-call-edges.d.ts +18 -0
- package/dist/navigation/ts-call-edges.d.ts.map +1 -1
- package/dist/navigation/ts-call-edges.js +207 -18
- package/dist/navigation/ts-call-edges.js.map +1 -1
- package/dist/path-set/path-set.d.ts +5 -2
- package/dist/path-set/path-set.d.ts.map +1 -1
- package/dist/path-set/path-set.js +4 -1
- package/dist/path-set/path-set.js.map +1 -1
- package/dist/resolution/cross-file.d.ts +12 -0
- package/dist/resolution/cross-file.d.ts.map +1 -1
- package/dist/resolution/cross-file.js +357 -3
- package/dist/resolution/cross-file.js.map +1 -1
- package/dist/stable-ids/ts-parse-errors.d.ts +2 -0
- package/dist/stable-ids/ts-parse-errors.d.ts.map +1 -1
- package/dist/stable-ids/ts-parse-errors.js +43 -1
- package/dist/stable-ids/ts-parse-errors.js.map +1 -1
- package/dist/types/config.d.ts +2 -1
- package/dist/types/config.d.ts.map +1 -1
- package/dist/types/index.d.ts +74 -5
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/docs/SPEC.md +1 -1
- package/package.json +2 -2
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* Depends on: taint-matcher, constant-propagation
|
|
15
15
|
*/
|
|
16
16
|
import { runsArgvAsCommand } from '../arg-executing-programs.js';
|
|
17
|
+
import { SHELL_OPTION_ON } from '../js-spawn-argv.js';
|
|
17
18
|
import { DOM_ASSIGNMENT_SINK_METHODS, isProvablyLiteralExpression, } from '../literal-expression.js';
|
|
18
19
|
import { attachSourceLineCode } from '../taint-matcher.js';
|
|
19
20
|
import { javaReplaceCrLfCoverage } from '../java-crlf-strip.js';
|
|
@@ -298,6 +299,7 @@ export class LanguageSourcesPass {
|
|
|
298
299
|
}
|
|
299
300
|
}
|
|
300
301
|
const jsTaintedVars = buildJavaScriptTaintedVars(code, language);
|
|
302
|
+
const jsSubscribeInterproceduralVars = javascriptSubscribeInterproceduralTaintVars(code, language);
|
|
301
303
|
// -- Bash/Shell: taint sources + pattern-based findings --
|
|
302
304
|
if (language === 'bash') {
|
|
303
305
|
additionalSources.push(...findBashTaintSources(code, graph.ir.dfg));
|
|
@@ -363,8 +365,12 @@ export class LanguageSourcesPass {
|
|
|
363
365
|
}
|
|
364
366
|
// -- Python: safe-handler sanitizer detectors (cognium-dev #114 Sprint 31) --
|
|
365
367
|
if (language === 'python') {
|
|
366
|
-
|
|
367
|
-
|
|
368
|
+
for (const s of findPythonNetlocAllowlistGuardSanitizers(code)) {
|
|
369
|
+
additionalSanitizers.push(s);
|
|
370
|
+
}
|
|
371
|
+
for (const s of findPythonRangeCheckGuardSanitizers(code)) {
|
|
372
|
+
additionalSanitizers.push(s);
|
|
373
|
+
}
|
|
368
374
|
// Sprint 74 (#216 Pattern B): regex-allowlist wrapper functions,
|
|
369
375
|
// var-aware set-membership xss guard, and defusedxml import-alias
|
|
370
376
|
// recognition.
|
|
@@ -481,6 +487,19 @@ export class LanguageSourcesPass {
|
|
|
481
487
|
for (const finding of findRustLogInjectionFindings(code, graph.ir.meta.file)) {
|
|
482
488
|
ctx.addFinding(finding);
|
|
483
489
|
}
|
|
490
|
+
for (const r of findRustActixBodyFormatFormatStringSinks(code)) {
|
|
491
|
+
if (additionalSinks.some((s) => s.line === r.sinkLine && s.type === 'format_string')) {
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
additionalSinks.push({
|
|
495
|
+
type: 'format_string',
|
|
496
|
+
cwe: 'CWE-134',
|
|
497
|
+
line: r.sinkLine,
|
|
498
|
+
location: `Actix HttpResponse body built with format! containing request data at line ${r.sinkLine}`,
|
|
499
|
+
method: 'body',
|
|
500
|
+
confidence: 0.9,
|
|
501
|
+
});
|
|
502
|
+
}
|
|
484
503
|
}
|
|
485
504
|
// -- JavaScript/TypeScript: Sprint 73 (#216 Pattern A + B) — ETE
|
|
486
505
|
// sanitizer-chain recognition (JSON.parse / bcrypt.hash / csv
|
|
@@ -492,12 +511,15 @@ export class LanguageSourcesPass {
|
|
|
492
511
|
additionalSanitizers.push(...findJsWrapperFunctionSanitizers(code));
|
|
493
512
|
// Sprint 75 (#216 Pattern D): JS SSRF allow-list guard (var-aware).
|
|
494
513
|
additionalSanitizers.push(...findJsSsrfAllowlistGuardSanitizers(code));
|
|
514
|
+
additionalSanitizers.push(...findJsSsrfAllowlistWrapperSanitizers(code));
|
|
495
515
|
// Sprint 77b (#216 Pattern X): JS/TS argv-form execFile/spawn and
|
|
496
516
|
// parameterized SQL placeholder sanitizers.
|
|
497
517
|
additionalSanitizers.push(...findJsArgvFormExecSanitizers(code));
|
|
498
518
|
additionalSanitizers.push(...findJsParameterizedSqlSanitizers(code));
|
|
499
519
|
// #223 REG-144-20: JS path.resolve/join + startsWith(root) guard.
|
|
500
520
|
additionalSanitizers.push(...findJsPathResolveStartsWithGuardSanitizers(code));
|
|
521
|
+
// cognium-dev#1305 E4: isAbsolute(x) || x has a `..` segment → reject.
|
|
522
|
+
additionalSanitizers.push(...findJsAbsoluteDotDotGuardSanitizers(code));
|
|
501
523
|
// JS/TS open_redirect: a same-site relative-path guard that rejects `//` AND `/\`.
|
|
502
524
|
additionalSanitizers.push(...findJsRelativeRedirectGuardSanitizers(code));
|
|
503
525
|
// cognium-dev#1146: same-file helper returns path.resolve after allow-list guard.
|
|
@@ -656,7 +678,15 @@ export class LanguageSourcesPass {
|
|
|
656
678
|
// (LLM enrichment, SARIF reporters) can render the offending line without
|
|
657
679
|
// re-reading the file.
|
|
658
680
|
attachSourceLineCode(additionalSources, additionalSinks, code);
|
|
659
|
-
return {
|
|
681
|
+
return {
|
|
682
|
+
additionalSources,
|
|
683
|
+
additionalSinks,
|
|
684
|
+
additionalSanitizers,
|
|
685
|
+
pyTaintedVars,
|
|
686
|
+
pySanitizedVars,
|
|
687
|
+
jsTaintedVars,
|
|
688
|
+
jsSubscribeInterproceduralVars,
|
|
689
|
+
};
|
|
660
690
|
}
|
|
661
691
|
}
|
|
662
692
|
function findGetterSources(types, instanceFieldTaint, _sourceCode) {
|
|
@@ -1249,7 +1279,7 @@ function findSetterChainSources(types, sourceCode, language) {
|
|
|
1249
1279
|
return [];
|
|
1250
1280
|
const sources = [];
|
|
1251
1281
|
const lines = sourceCode.split('\n');
|
|
1252
|
-
const javaHttpPattern = /\b(?:req|request|httpRequest|servletRequest|httpServletRequest)\.(?:getParameter|getParameterValues|getParameterMap|getHeader|getHeaders|getCookies|getQueryString|getPathInfo|getRequestURI|getRequestURL|getInputStream|getReader)\b/;
|
|
1282
|
+
const javaHttpPattern = /\b(?:req|request|r|httpRequest|servletRequest|httpServletRequest)\.(?:getParameter|getParameterValues|getParameterMap|getHeader|getHeaders|getCookies|getQueryString|getPathInfo|getRequestURI|getRequestURL|getInputStream|getReader)\b/;
|
|
1253
1283
|
const setterArgFromHttp = (arg) => {
|
|
1254
1284
|
const trimmed = arg.trim();
|
|
1255
1285
|
if (javaHttpPattern.test(trimmed))
|
|
@@ -1261,7 +1291,7 @@ function findSetterChainSources(types, sourceCode, language) {
|
|
|
1261
1291
|
// cognium-dev#1198 — SecuriBench Basic16 passes taint as a local (`writePayload(s)`)
|
|
1262
1292
|
// after `String s = req.getParameter(...)`; the setter-chain emitter only
|
|
1263
1293
|
// matched literal HTTP call expressions in the argument position.
|
|
1264
|
-
return new RegExp(`\\b(?:[\\w.<>,\\s]+\\s+)?${v}\\s*=\\s*[^;\\n]*\\b(?:req|request|httpRequest|servletRequest|httpServletRequest)\\.(?:getParameter|getParameterValues|getHeader|getCookies|getQueryString|getInputStream|getReader)\\s*\\(`).test(sourceCode);
|
|
1294
|
+
return new RegExp(`\\b(?:[\\w.<>,\\s]+\\s+)?${v}\\s*=\\s*[^;\\n]*\\b(?:req|request|r|httpRequest|servletRequest|httpServletRequest)\\.(?:getParameter|getParameterValues|getHeader|getCookies|getQueryString|getInputStream|getReader)\\s*\\(`).test(sourceCode);
|
|
1265
1295
|
};
|
|
1266
1296
|
for (const type of types) {
|
|
1267
1297
|
if (type.kind !== 'class')
|
|
@@ -1271,6 +1301,7 @@ function findSetterChainSources(types, sourceCode, language) {
|
|
|
1271
1301
|
// Build setter/getter pairs by inspecting per-method bodies.
|
|
1272
1302
|
const pairs = new Map();
|
|
1273
1303
|
const setterRe = /this\.([A-Za-z_]\w*)\s*=\s*([A-Za-z_]\w*)\s*;?/;
|
|
1304
|
+
const staticSetterRe = /^([A-Za-z_]\w*)\s*=\s*([A-Za-z_]\w*)\s*;?\s*$/;
|
|
1274
1305
|
const getterRe = /return\s+(?:this\.)?([A-Za-z_]\w*)\s*;?/;
|
|
1275
1306
|
for (const m of type.methods) {
|
|
1276
1307
|
if (m.name === type.name)
|
|
@@ -1304,6 +1335,18 @@ function findSetterChainSources(types, sourceCode, language) {
|
|
|
1304
1335
|
continue;
|
|
1305
1336
|
}
|
|
1306
1337
|
}
|
|
1338
|
+
// Static setter (`last = v` in `static void remember(String v)`).
|
|
1339
|
+
if (m.modifiers.includes('static') &&
|
|
1340
|
+
m.parameters.length === 1 &&
|
|
1341
|
+
staticSetterRe.test(inner.trim())) {
|
|
1342
|
+
const stm = staticSetterRe.exec(inner.trim());
|
|
1343
|
+
if (stm && stm[2] === m.parameters[0].name) {
|
|
1344
|
+
const entry = pairs.get(stm[1]) ?? {};
|
|
1345
|
+
entry.setter = m.name;
|
|
1346
|
+
pairs.set(stm[1], entry);
|
|
1347
|
+
continue;
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1307
1350
|
// Getter?
|
|
1308
1351
|
const gm = inner.match(getterRe);
|
|
1309
1352
|
if (gm && m.parameters.length === 0) {
|
|
@@ -1321,16 +1364,16 @@ function findSetterChainSources(types, sourceCode, language) {
|
|
|
1321
1364
|
if (!setter || !getter)
|
|
1322
1365
|
continue;
|
|
1323
1366
|
const setterCallRe = new RegExp(`\\b([A-Za-z_]\\w*)\\.${setter}\\s*\\(\\s*([^)]+?)\\s*\\)\\s*;?`);
|
|
1367
|
+
const staticSetterCallRe = new RegExp(`\\b${setter}\\s*\\(\\s*([^)]+?)\\s*\\)\\s*;?`);
|
|
1324
1368
|
for (let i = 0; i < lines.length; i++) {
|
|
1325
1369
|
const line = lines[i] ?? '';
|
|
1326
1370
|
const trimmed = line.trim();
|
|
1327
1371
|
if (!trimmed || trimmed.startsWith('//'))
|
|
1328
1372
|
continue;
|
|
1329
1373
|
const cm = trimmed.match(setterCallRe);
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
if (!setterArgFromHttp(arg))
|
|
1374
|
+
const scm = !cm ? trimmed.match(staticSetterCallRe) : null;
|
|
1375
|
+
const arg = cm ? cm[2] : scm?.[1];
|
|
1376
|
+
if (!arg || !setterArgFromHttp(arg))
|
|
1334
1377
|
continue;
|
|
1335
1378
|
sources.push({
|
|
1336
1379
|
type: 'http_param',
|
|
@@ -1388,6 +1431,8 @@ function findJavaHeapFieldDerivedSources(code, language) {
|
|
|
1388
1431
|
// Direct write or same-line alias (e.g. head.next.value after next.value = name).
|
|
1389
1432
|
if (varName !== written && !varName.endsWith(`.${m[2]}`))
|
|
1390
1433
|
continue;
|
|
1434
|
+
if (varName === written && isJavaHeapFieldStronglyUpdated(code, line - 1, m[1], m[2]))
|
|
1435
|
+
continue;
|
|
1391
1436
|
sources.push({
|
|
1392
1437
|
type: 'http_param',
|
|
1393
1438
|
location: `heap field read ${varName} — #1198`,
|
|
@@ -1399,6 +1444,138 @@ function findJavaHeapFieldDerivedSources(code, language) {
|
|
|
1399
1444
|
}
|
|
1400
1445
|
return sources;
|
|
1401
1446
|
}
|
|
1447
|
+
const JAVA_LITERAL_RHS_RE = /^(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)'|-?\d[\w.]*|true|false|null)$/;
|
|
1448
|
+
const JAVA_JUMP_RE = /\b(?:return|break|continue|throw|yield)\b/;
|
|
1449
|
+
// `[final] [Type] local = <literal>;`: no call, division, array or field access.
|
|
1450
|
+
const JAVA_NON_THROWING_STMT_RE = new RegExp('^(?:final\\s+)?(?:[A-Za-z_][\\w.]*(?:<[^;=()]*>)?(?:\\s*\\[\\s*\\])*\\s+)?' +
|
|
1451
|
+
`[A-Za-z_]\\w*\\s*=\\s*(?:${JAVA_LITERAL_RHS_RE.source.slice(1, -1)})\\s*;$`);
|
|
1452
|
+
/**
|
|
1453
|
+
* True when line `idx` sits inside a `try` or `catch` block, at any depth.
|
|
1454
|
+
* Walks back over the enclosing blocks and checks the header of each.
|
|
1455
|
+
*/
|
|
1456
|
+
function isInsideJavaTryOrCatch(lines, idx) {
|
|
1457
|
+
let depth = 0;
|
|
1458
|
+
for (let i = idx - 1; i >= 0; i--) {
|
|
1459
|
+
const line = lines[i].replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""');
|
|
1460
|
+
for (let j = line.length - 1; j >= 0; j--) {
|
|
1461
|
+
if (line[j] === '}')
|
|
1462
|
+
depth++;
|
|
1463
|
+
else if (line[j] === '{') {
|
|
1464
|
+
if (depth > 0) {
|
|
1465
|
+
depth--;
|
|
1466
|
+
continue;
|
|
1467
|
+
}
|
|
1468
|
+
let header = line.slice(0, j).trim();
|
|
1469
|
+
for (let k = i - 1; !header && k >= 0; k--)
|
|
1470
|
+
header = lines[k].trim();
|
|
1471
|
+
if (/\btry\s*(?:\(.*\))?$/.test(header) || /\bcatch\s*\(.*\)$/.test(header)) {
|
|
1472
|
+
return true;
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
return false;
|
|
1478
|
+
}
|
|
1479
|
+
/**
|
|
1480
|
+
* Strong update of a heap field (SecuriBench StrongUpdates3): the tainted
|
|
1481
|
+
* write `recv.field = x;` on line `writeIdx` is overwritten by a later
|
|
1482
|
+
* `recv.field = <literal>;` before any read. Only the plain straight-line case
|
|
1483
|
+
* counts, so anything unsure keeps the taint:
|
|
1484
|
+
* - the kill is in the same block, and the lines between the two writes have
|
|
1485
|
+
* no braces, jumps or calls and do not mention `recv`;
|
|
1486
|
+
* - the line before the kill ends a statement (no brace-less `if`/`else`);
|
|
1487
|
+
* - inside a `try` or `catch`, every statement between the writes cannot
|
|
1488
|
+
* throw (a local assigned a literal), so no exception path skips the kill;
|
|
1489
|
+
* - the tainted write is alone on its line;
|
|
1490
|
+
* - every read of `recv.field` comes after the kill, and no later write of
|
|
1491
|
+
* the field (plain, compound or `++`/`--`) stores anything but a literal;
|
|
1492
|
+
* - no method is called on `recv` after the kill, since it may write the field;
|
|
1493
|
+
* - `recv` is only ever used as `recv.<member>` or assigned to, never passed
|
|
1494
|
+
* or copied, so no other reference can read the field.
|
|
1495
|
+
*/
|
|
1496
|
+
function isJavaHeapFieldStronglyUpdated(code, writeIdx, recv, field) {
|
|
1497
|
+
const lines = code.split('\n').map(stripJavaTrailingLineComment);
|
|
1498
|
+
const recvRe = new RegExp(`\\b${recv}\\b`);
|
|
1499
|
+
const fieldRe = new RegExp(`(?<![\\w.])${recv}\\s*\\.\\s*${field}\\b`, 'g');
|
|
1500
|
+
const fieldWriteRe = new RegExp(`^\\s*${recv}\\.${field}\\s*=(?!=)\\s*(.+?);\\s*$`);
|
|
1501
|
+
let killIdx = -1;
|
|
1502
|
+
for (let i = writeIdx + 1; i < lines.length; i++) {
|
|
1503
|
+
const line = lines[i];
|
|
1504
|
+
const trimmed = line.trim();
|
|
1505
|
+
if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('*'))
|
|
1506
|
+
continue;
|
|
1507
|
+
const w = fieldWriteRe.exec(line);
|
|
1508
|
+
if (w) {
|
|
1509
|
+
if (!JAVA_LITERAL_RHS_RE.test(w[1].trim()))
|
|
1510
|
+
return false;
|
|
1511
|
+
killIdx = i;
|
|
1512
|
+
break;
|
|
1513
|
+
}
|
|
1514
|
+
if (/[{}]/.test(trimmed) || JAVA_JUMP_RE.test(trimmed))
|
|
1515
|
+
return false;
|
|
1516
|
+
if (/[\w)\]>]\s*\(/.test(trimmed) || recvRe.test(trimmed))
|
|
1517
|
+
return false;
|
|
1518
|
+
}
|
|
1519
|
+
if (killIdx < 0)
|
|
1520
|
+
return false;
|
|
1521
|
+
for (let i = killIdx - 1; i > writeIdx; i--) {
|
|
1522
|
+
const trimmed = lines[i].trim();
|
|
1523
|
+
if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('*'))
|
|
1524
|
+
continue;
|
|
1525
|
+
if (!trimmed.endsWith(';'))
|
|
1526
|
+
return false;
|
|
1527
|
+
break;
|
|
1528
|
+
}
|
|
1529
|
+
// Inside a `try` or `catch`, an exception between the two writes skips the
|
|
1530
|
+
// kill and reaches a handler, a `finally` or the code after the statement,
|
|
1531
|
+
// any of which can read the field. Only statements that cannot throw count.
|
|
1532
|
+
if (isInsideJavaTryOrCatch(lines, killIdx)) {
|
|
1533
|
+
for (let i = writeIdx + 1; i < killIdx; i++) {
|
|
1534
|
+
const trimmed = lines[i].trim();
|
|
1535
|
+
if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('*'))
|
|
1536
|
+
continue;
|
|
1537
|
+
if (!JAVA_NON_THROWING_STMT_RE.test(trimmed))
|
|
1538
|
+
return false;
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
// Every mention of `recv` must be a member access or an assignment to it.
|
|
1542
|
+
const mentionRe = new RegExp(`(?<![\\w.])${recv}\\b(?!\\s*\\.)(?!\\s*=(?!=))`);
|
|
1543
|
+
// A method on `recv` may write the field (`b.setValue(name)`).
|
|
1544
|
+
const recvCallRe = new RegExp(`(?<![\\w.])${recv}\\s*\\.\\s*[A-Za-z_]\\w*\\s*\\(`);
|
|
1545
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1546
|
+
const line = lines[i].replace(/"(?:[^"\\]|\\.)*"/g, '""');
|
|
1547
|
+
const trimmed = line.trim();
|
|
1548
|
+
if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('*'))
|
|
1549
|
+
continue;
|
|
1550
|
+
if (mentionRe.test(line))
|
|
1551
|
+
return false;
|
|
1552
|
+
// The tainted write must be alone on its line: a read after it on the same
|
|
1553
|
+
// line (`b.value = name; writer.println(b.value);`) comes before the kill.
|
|
1554
|
+
if (i === writeIdx) {
|
|
1555
|
+
if (trimmed.indexOf(';') !== trimmed.length - 1)
|
|
1556
|
+
return false;
|
|
1557
|
+
continue;
|
|
1558
|
+
}
|
|
1559
|
+
if (i === killIdx)
|
|
1560
|
+
continue;
|
|
1561
|
+
if (i > killIdx && recvCallRe.test(line))
|
|
1562
|
+
return false;
|
|
1563
|
+
for (const fm of line.matchAll(fieldRe)) {
|
|
1564
|
+
if (i < killIdx)
|
|
1565
|
+
return false;
|
|
1566
|
+
// `++b.value`, `b.value++`, `b.value += x`: a write of a non-literal.
|
|
1567
|
+
if (/(?:\+\+|--)\s*$/.test(line.slice(0, fm.index)))
|
|
1568
|
+
return false;
|
|
1569
|
+
const after = line.slice((fm.index ?? 0) + fm[0].length);
|
|
1570
|
+
if (/^\s*(?:\+\+|--|(?:[-+*/%&|^]|<<|>>>?)=)/.test(after))
|
|
1571
|
+
return false;
|
|
1572
|
+
const w = /^\s*=(?!=)\s*([^;]*)/.exec(after);
|
|
1573
|
+
if (w && !JAVA_LITERAL_RHS_RE.test(w[1].trim()))
|
|
1574
|
+
return false;
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
return true;
|
|
1578
|
+
}
|
|
1402
1579
|
/**
|
|
1403
1580
|
* Explicit ASP.NET Core request sources (cognium-dev C#/.NET Phase-1).
|
|
1404
1581
|
*
|
|
@@ -2913,37 +3090,114 @@ function findJavaScriptCallbackParamSources(sourceCode) {
|
|
|
2913
3090
|
}
|
|
2914
3091
|
return sources;
|
|
2915
3092
|
}
|
|
2916
|
-
/**
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
const
|
|
2925
|
-
const
|
|
3093
|
+
/** Shared subscribe-callback param discovery (#1224 direct callback, #1381 observer + method forwarding). */
|
|
3094
|
+
function subscribeCallbackParamUseLine(lines, subscribeLineIdx, paramName) {
|
|
3095
|
+
const end = Math.min(subscribeLineIdx + 12, lines.length);
|
|
3096
|
+
const windowLines = lines.slice(subscribeLineIdx, end);
|
|
3097
|
+
const windowText = windowLines.join('\n');
|
|
3098
|
+
const subMatch = windowText.search(/\.subscribe\s*\(/);
|
|
3099
|
+
const searchFrom = subMatch >= 0 ? subMatch : 0;
|
|
3100
|
+
const afterSubscribe = windowText.slice(searchFrom);
|
|
3101
|
+
const re = new RegExp(`\\b${paramName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
|
|
3102
|
+
const m = re.exec(afterSubscribe);
|
|
3103
|
+
if (!m)
|
|
3104
|
+
return subscribeLineIdx + 1;
|
|
3105
|
+
const absoluteIdx = searchFrom + m.index;
|
|
3106
|
+
let consumed = 0;
|
|
3107
|
+
for (let j = 0; j < windowLines.length; j++) {
|
|
3108
|
+
const lineLen = windowLines[j].length + (j < windowLines.length - 1 ? 1 : 0);
|
|
3109
|
+
if (consumed + lineLen > absoluteIdx)
|
|
3110
|
+
return subscribeLineIdx + j + 1;
|
|
3111
|
+
consumed += lineLen;
|
|
3112
|
+
}
|
|
3113
|
+
return subscribeLineIdx + 1;
|
|
3114
|
+
}
|
|
3115
|
+
function collectJavaScriptSubscribeCallbackParams(sourceCode) {
|
|
3116
|
+
const out = [];
|
|
3117
|
+
const seen = new Set();
|
|
3118
|
+
const pushParam = (name, subscribeLineIdx) => {
|
|
3119
|
+
const id = name.trim().replace(/[,):].*/, '');
|
|
3120
|
+
if (!id || id === 'err' || id === 'error')
|
|
3121
|
+
return;
|
|
3122
|
+
const line = subscribeCallbackParamUseLine(lines, subscribeLineIdx, id);
|
|
3123
|
+
if (seen.has(`${line}:${id}`))
|
|
3124
|
+
return;
|
|
3125
|
+
seen.add(`${line}:${id}`);
|
|
3126
|
+
out.push({ name: id, line });
|
|
3127
|
+
};
|
|
3128
|
+
const splitDestructuring = (paramList) => {
|
|
3129
|
+
const t = paramList.trim();
|
|
3130
|
+
if (t.startsWith('[') || t.startsWith('{')) {
|
|
3131
|
+
return (t.match(/[\p{L}\p{N}_$]+/gu) ?? []).filter(id => !['err', 'error'].includes(id));
|
|
3132
|
+
}
|
|
3133
|
+
const simple = t.replace(/[,):].*/, '').trim();
|
|
3134
|
+
return simple ? [simple] : [];
|
|
3135
|
+
};
|
|
3136
|
+
const SUBSCRIBE_CB_RE = /\.subscribe\s*\(\s*(?:async\s+)?(?:function\s*\*?\s*(?:\w+\s*)?\(\s*([^)]*)|(?:\(\s*([^)]*)\s*\)|([^,\s]+))\s*(?:[,):]|=>|$))/;
|
|
3137
|
+
const SUBSCRIBE_NEXT_RE = /\bnext\s*:\s*(?:async\s+)?(?:function\s*\*?\s*(?:\w+\s*)?\(\s*([^)]*)|\(\s*([^)]*)\)\s*=>|([^,\s]+)\s*=>)/;
|
|
2926
3138
|
const lines = sourceCode.split('\n');
|
|
2927
3139
|
for (let i = 0; i < lines.length; i++) {
|
|
2928
3140
|
const line = lines[i];
|
|
2929
3141
|
const trimmed = line.trimStart();
|
|
2930
3142
|
if (trimmed.startsWith('//') || trimmed.startsWith('*'))
|
|
2931
3143
|
continue;
|
|
2932
|
-
const
|
|
2933
|
-
|
|
3144
|
+
const isObserverSubscribe = /\.subscribe\s*\(\s*\{/.test(line);
|
|
3145
|
+
const direct = isObserverSubscribe ? null : line.match(SUBSCRIBE_CB_RE);
|
|
3146
|
+
if (direct) {
|
|
3147
|
+
const paramList = direct[1] ?? direct[2] ?? direct[3] ?? '';
|
|
3148
|
+
for (const name of splitDestructuring(paramList))
|
|
3149
|
+
pushParam(name, i);
|
|
2934
3150
|
continue;
|
|
2935
|
-
|
|
2936
|
-
if (!
|
|
3151
|
+
}
|
|
3152
|
+
if (!isObserverSubscribe)
|
|
2937
3153
|
continue;
|
|
2938
|
-
|
|
3154
|
+
const window = lines.slice(i, Math.min(i + 12, lines.length)).join(' ');
|
|
3155
|
+
const subscribeIdx = window.lastIndexOf('.subscribe(');
|
|
3156
|
+
const afterSubscribe = subscribeIdx >= 0 ? window.slice(subscribeIdx) : window;
|
|
3157
|
+
const observer = afterSubscribe.match(SUBSCRIBE_NEXT_RE);
|
|
3158
|
+
if (!observer)
|
|
2939
3159
|
continue;
|
|
3160
|
+
const paramList = observer[1] ?? observer[2] ?? observer[3] ?? '';
|
|
3161
|
+
for (const name of splitDestructuring(paramList))
|
|
3162
|
+
pushParam(name, i);
|
|
3163
|
+
}
|
|
3164
|
+
return out;
|
|
3165
|
+
}
|
|
3166
|
+
/** Names InterproceduralPass should merge beyond constProp.tainted (#1381). */
|
|
3167
|
+
export function javascriptSubscribeInterproceduralTaintVars(sourceCode, language) {
|
|
3168
|
+
if (!['javascript', 'typescript'].includes(language))
|
|
3169
|
+
return new Set();
|
|
3170
|
+
const out = new Set();
|
|
3171
|
+
const seeded = new Map();
|
|
3172
|
+
for (const { name, line } of collectJavaScriptSubscribeCallbackParams(sourceCode)) {
|
|
3173
|
+
out.add(name);
|
|
3174
|
+
seeded.set(name, line);
|
|
3175
|
+
}
|
|
3176
|
+
const beforeCallee = new Set(seeded.keys());
|
|
3177
|
+
seedJsCalleeParamsFromSubscribeForwarding(sourceCode, seeded);
|
|
3178
|
+
for (const name of seeded.keys()) {
|
|
3179
|
+
if (!beforeCallee.has(name))
|
|
3180
|
+
out.add(name);
|
|
3181
|
+
}
|
|
3182
|
+
return out;
|
|
3183
|
+
}
|
|
3184
|
+
/**
|
|
3185
|
+
* cognium-dev #1224 — RxJS/Observable `.subscribe` callback first-parameter sources.
|
|
3186
|
+
*
|
|
3187
|
+
* Angular services return HTTP payloads through `service.method().subscribe((data) => …)`.
|
|
3188
|
+
* The first callback argument is user-influenced response body (stored-XSS shapes in Juice Shop).
|
|
3189
|
+
* Scoped to `.subscribe(` only — not every higher-order function — to avoid unrelated FPs.
|
|
3190
|
+
*/
|
|
3191
|
+
function findJavaScriptSubscribeCallbackParamSources(sourceCode) {
|
|
3192
|
+
const sources = [];
|
|
3193
|
+
for (const { name, line } of collectJavaScriptSubscribeCallbackParams(sourceCode)) {
|
|
2940
3194
|
sources.push({
|
|
2941
3195
|
type: 'http_body',
|
|
2942
|
-
location: `Observable .subscribe(...) callback param '${
|
|
3196
|
+
location: `Observable .subscribe(...) callback param '${name}' at line ${line}`,
|
|
2943
3197
|
severity: 'high',
|
|
2944
|
-
line
|
|
3198
|
+
line,
|
|
2945
3199
|
confidence: 0.9,
|
|
2946
|
-
variable:
|
|
3200
|
+
variable: name,
|
|
2947
3201
|
});
|
|
2948
3202
|
}
|
|
2949
3203
|
return sources;
|
|
@@ -4350,6 +4604,12 @@ export function buildJavaScriptTaintedVars(sourceCode, language) {
|
|
|
4350
4604
|
continue;
|
|
4351
4605
|
tainted.set(paramName, i + 1);
|
|
4352
4606
|
}
|
|
4607
|
+
// cognium-dev #1224 / #1381 — subscribe callback params (incl. `{ next: … }` observer).
|
|
4608
|
+
for (const { name, line } of collectJavaScriptSubscribeCallbackParams(sourceCode)) {
|
|
4609
|
+
if (!tainted.has(name))
|
|
4610
|
+
tainted.set(name, line);
|
|
4611
|
+
}
|
|
4612
|
+
seedJsCalleeParamsFromSubscribeForwarding(sourceCode, tainted);
|
|
4353
4613
|
// cognium-dev#582 / #490: scan every assignment on the line; #1149: skip
|
|
4354
4614
|
// matches inside string literals so `WHERE name = '…'` in SQL is not a bind.
|
|
4355
4615
|
const assignmentRe = /(?:(?:var|let|const)\s+(\w+)\s*:\s*[^=;]+?\s*=(?![>=])|(?:(?:var|let|const)\s+)?(\w+)\s*=)\s*/g;
|
|
@@ -5345,7 +5605,9 @@ export function findBashPatternFindings(sourceCode, file) {
|
|
|
5345
5605
|
pass: 'language-sources',
|
|
5346
5606
|
category: 'security',
|
|
5347
5607
|
rule_id: 'predictable-temp-file',
|
|
5348
|
-
|
|
5608
|
+
// Maps to CWE-379 (Creation of Temporary File in Directory with Incorrect
|
|
5609
|
+
// Permissions), since 377 is deprecated in CWE 5.0 (#1309).
|
|
5610
|
+
cwe: 'CWE-379',
|
|
5349
5611
|
severity: 'medium',
|
|
5350
5612
|
level: 'warning',
|
|
5351
5613
|
message: `Predictable temp file: /tmp/${tmpRel}. Use mktemp instead`,
|
|
@@ -6298,7 +6560,7 @@ function findRustNumericRangeCheckGuardSanitizers(code) {
|
|
|
6298
6560
|
type: 'rust_numeric_range_check_guard',
|
|
6299
6561
|
method: 'if',
|
|
6300
6562
|
line: l + 1,
|
|
6301
|
-
sanitizes: ['xss', 'external_taint_escape'],
|
|
6563
|
+
sanitizes: ['xss', 'external_taint_escape', 'format_string'],
|
|
6302
6564
|
});
|
|
6303
6565
|
}
|
|
6304
6566
|
}
|
|
@@ -6311,10 +6573,17 @@ function findPythonRangeCheckGuardSanitizers(code) {
|
|
|
6311
6573
|
// Matches single- and two-sided range checks. Identifier must repeat.
|
|
6312
6574
|
const rangeGuard = /^(\s*)if\s+([A-Za-z_][A-Za-z0-9_]*)\s*[<>]=?\s*(?:\d+|-?\d+\.?\d*|[A-Z][A-Z0-9_]+)\s*(?:(?:or|and)\s+\2\s*[<>]=?\s*(?:\d+|-?\d+\.?\d*|[A-Z][A-Z0-9_]+)\s*)?:\s*$/;
|
|
6313
6575
|
const terminator = /\b(return|raise|abort\s*\(|sys\.exit\s*\()/;
|
|
6576
|
+
const maxGuards = 2000;
|
|
6577
|
+
const maxSanitizers = 50_000;
|
|
6578
|
+
const maxTailLines = 400;
|
|
6579
|
+
let guardCount = 0;
|
|
6314
6580
|
for (let i = 0; i < lines.length; i++) {
|
|
6581
|
+
if (guardCount >= maxGuards || sanitizers.length >= maxSanitizers)
|
|
6582
|
+
break;
|
|
6315
6583
|
const m = rangeGuard.exec(lines[i]);
|
|
6316
6584
|
if (!m)
|
|
6317
6585
|
continue;
|
|
6586
|
+
guardCount++;
|
|
6318
6587
|
const guardIndent = m[1].length;
|
|
6319
6588
|
let bodyHasTerminator = false;
|
|
6320
6589
|
let blockEnd = -1;
|
|
@@ -6335,7 +6604,10 @@ function findPythonRangeCheckGuardSanitizers(code) {
|
|
|
6335
6604
|
blockEnd = Math.min(lines.length - 1, i + 25);
|
|
6336
6605
|
if (!bodyHasTerminator)
|
|
6337
6606
|
continue;
|
|
6338
|
-
|
|
6607
|
+
const tailEnd = Math.min(lines.length, blockEnd + 2 + maxTailLines);
|
|
6608
|
+
for (let l = blockEnd + 2; l <= tailEnd; l++) {
|
|
6609
|
+
if (sanitizers.length >= maxSanitizers)
|
|
6610
|
+
break;
|
|
6339
6611
|
sanitizers.push({
|
|
6340
6612
|
type: 'python_range_check_guard',
|
|
6341
6613
|
method: 'if',
|
|
@@ -7227,6 +7499,7 @@ function findRustPatInfoHttpOnlyResponseSanitizers(code) {
|
|
|
7227
7499
|
'external_taint_escape',
|
|
7228
7500
|
'open_redirect',
|
|
7229
7501
|
'log_injection',
|
|
7502
|
+
'format_string',
|
|
7230
7503
|
],
|
|
7231
7504
|
});
|
|
7232
7505
|
}
|
|
@@ -7824,6 +8097,56 @@ function findJsSsrfAllowlistGuardSanitizers(code) {
|
|
|
7824
8097
|
}
|
|
7825
8098
|
return sanitizers;
|
|
7826
8099
|
}
|
|
8100
|
+
/**
|
|
8101
|
+
* JS/TS: custom-wrapper SSRF allow-list (flow-combo c08 / #1244).
|
|
8102
|
+
*
|
|
8103
|
+
* Recognizes helpers that validate `new URL(param).hostname` against a
|
|
8104
|
+
* fixed allow-list (`ALLOWED.has` / `includes`) and return the same param,
|
|
8105
|
+
* e.g. flow-sanitize `custom_wrapper` clean probes.
|
|
8106
|
+
*/
|
|
8107
|
+
function findJsSsrfAllowlistWrapperSanitizers(code) {
|
|
8108
|
+
const sanitizers = [];
|
|
8109
|
+
const lines = code.split('\n');
|
|
8110
|
+
const fnDeclRe = /\bfunction\s+([A-Za-z_]\w*)\s*\(\s*([A-Za-z_]\w*)\s*\)/;
|
|
8111
|
+
const arrowDeclRe = /\b(?:const|let|var)\s+([A-Za-z_]\w*)\s*=\s*\(\s*([A-Za-z_]\w*)\s*\)\s*=>/;
|
|
8112
|
+
const allowlistName = /^(?:[A-Z][A-Z0-9_]+|.*?(allowed|accepted|whitelist|permitted|valid|approved).*)$/i;
|
|
8113
|
+
const allowGuard = /!\s*([A-Za-z_]\w*)\s*\.\s*(?:has|includes)\s*\(/;
|
|
8114
|
+
const wrappers = new Set();
|
|
8115
|
+
for (let i = 0; i < lines.length; i++) {
|
|
8116
|
+
const m = fnDeclRe.exec(lines[i]) ?? arrowDeclRe.exec(lines[i]);
|
|
8117
|
+
if (!m)
|
|
8118
|
+
continue;
|
|
8119
|
+
const name = m[1];
|
|
8120
|
+
const param = m[2];
|
|
8121
|
+
const body = lines.slice(i, Math.min(lines.length, i + 12)).join('\n');
|
|
8122
|
+
if (!new RegExp(`new\\s+URL\\s*\\(\\s*${param}\\b`).test(body))
|
|
8123
|
+
continue;
|
|
8124
|
+
const gm = allowGuard.exec(body);
|
|
8125
|
+
if (!gm || !allowlistName.test(gm[1]))
|
|
8126
|
+
continue;
|
|
8127
|
+
if (!/\b(?:throw|return)\b/.test(body))
|
|
8128
|
+
continue;
|
|
8129
|
+
if (!new RegExp(`\\breturn\\s+${param}\\b`).test(body))
|
|
8130
|
+
continue;
|
|
8131
|
+
wrappers.add(name);
|
|
8132
|
+
}
|
|
8133
|
+
for (const name of wrappers) {
|
|
8134
|
+
for (let i = 0; i < lines.length; i++) {
|
|
8135
|
+
const declSelf = new RegExp(`\\b(?:function|const|let|var)\\s+${name}\\b`);
|
|
8136
|
+
if (declSelf.test(lines[i]))
|
|
8137
|
+
continue;
|
|
8138
|
+
if (!new RegExp(`\\b${name}\\s*\\(`).test(lines[i]))
|
|
8139
|
+
continue;
|
|
8140
|
+
sanitizers.push({
|
|
8141
|
+
type: 'js_ssrf_allowlist_wrapper',
|
|
8142
|
+
method: name,
|
|
8143
|
+
line: i + 1,
|
|
8144
|
+
sanitizes: ['ssrf', 'external_taint_escape'],
|
|
8145
|
+
});
|
|
8146
|
+
}
|
|
8147
|
+
}
|
|
8148
|
+
return sanitizers;
|
|
8149
|
+
}
|
|
7827
8150
|
/**
|
|
7828
8151
|
* JS/TS: argv-form `execFile`/`spawn`/`execFileSync`/`spawnSync` with
|
|
7829
8152
|
* a string-literal program and an array literal argv (cognium-dev #216
|
|
@@ -7869,6 +8192,10 @@ function findJsArgvFormExecSanitizers(code) {
|
|
|
7869
8192
|
const prog = /\b(?:execFile|spawn)(?:Sync)?\s*\(\s*(['"`])([^'"`]*)\1/.exec(text);
|
|
7870
8193
|
if (prog && runsArgvAsCommand(prog[2]))
|
|
7871
8194
|
continue;
|
|
8195
|
+
// `shell: true` joins program and argv into a shell command line,
|
|
8196
|
+
// and an interpolated template program is not a fixed program.
|
|
8197
|
+
if (SHELL_OPTION_ON.test(text) || (prog && prog[1] === '`' && prog[2].includes('${')))
|
|
8198
|
+
continue;
|
|
7872
8199
|
sanitizers.push({
|
|
7873
8200
|
type: 'js_argv_form_exec',
|
|
7874
8201
|
method: 'execFile',
|
|
@@ -8021,99 +8348,984 @@ function findJsPathResolveStartsWithGuardSanitizers(code) {
|
|
|
8021
8348
|
return sanitizers;
|
|
8022
8349
|
}
|
|
8023
8350
|
/**
|
|
8024
|
-
*
|
|
8025
|
-
*
|
|
8026
|
-
*
|
|
8027
|
-
*
|
|
8028
|
-
*
|
|
8029
|
-
* if (next.startsWith('/') && !next.startsWith('//') && !next.startsWith('/\\')) { res.redirect(next); }
|
|
8030
|
-
* if (/^\/(?![\/\\])/.test(next)) { res.redirect(next); }
|
|
8031
|
-
* res.redirect(next.startsWith('/') && !next.startsWith('//') && !next.startsWith('/\\') ? next : '/');
|
|
8032
|
-
*
|
|
8033
|
-
* A path that starts with one `/` and is not `//…` (protocol-relative) or `/\…` (which browsers read as
|
|
8034
|
-
* `//…`) stays on the same site, so the redirect cannot leave it. BOTH `//` and `/\` must be rejected: a guard
|
|
8035
|
-
* that only rejects `//` is still bypassable with `/\evil.example`, and is not credited. The reject form
|
|
8036
|
-
* (conditions joined by `||`, then a terminator) credits every later line that uses the variable; the accept
|
|
8037
|
-
* form (joined by `&&`, or one of the strict regex spellings) credits the lines of its block. Only
|
|
8038
|
-
* `open_redirect` is sanitized. Matching is by substring on the whitespace-free condition (no new regex).
|
|
8351
|
+
* Whether a `split(…)` argument splits on both `/` and `\\` (#1416 review 2): a regex
|
|
8352
|
+
* literal whose body holds a backslash escape and a slash, e.g. `/[\\/]/`, `/[/\\]/`,
|
|
8353
|
+
* `/\\/|\\\\/`. A string (`'/'`), `path.sep` or any other argument is one separator.
|
|
8354
|
+
* `arg` has its whitespace removed.
|
|
8039
8355
|
*/
|
|
8040
|
-
function
|
|
8041
|
-
const
|
|
8042
|
-
if (!
|
|
8043
|
-
return
|
|
8044
|
-
const
|
|
8045
|
-
const
|
|
8046
|
-
const
|
|
8047
|
-
|
|
8048
|
-
|
|
8049
|
-
|
|
8050
|
-
|
|
8051
|
-
|
|
8052
|
-
|
|
8053
|
-
|
|
8054
|
-
|
|
8055
|
-
|
|
8056
|
-
|
|
8057
|
-
|
|
8058
|
-
|
|
8059
|
-
|
|
8060
|
-
|
|
8061
|
-
|
|
8062
|
-
|
|
8063
|
-
|
|
8064
|
-
|
|
8065
|
-
|
|
8066
|
-
|
|
8067
|
-
|
|
8068
|
-
|
|
8069
|
-
|
|
8070
|
-
|
|
8071
|
-
|
|
8072
|
-
|
|
8073
|
-
|
|
8074
|
-
|
|
8075
|
-
|
|
8076
|
-
|
|
8356
|
+
function splitsOnBothSeparators(arg) {
|
|
8357
|
+
const m = /^\/(.+)\/[a-z]*$/.exec(arg);
|
|
8358
|
+
if (!m)
|
|
8359
|
+
return false;
|
|
8360
|
+
const body = m[1];
|
|
8361
|
+
const hasBackslash = body.includes('\\\\');
|
|
8362
|
+
const hasSlash = body.replace(/\\\\/g, '').includes('/');
|
|
8363
|
+
return hasBackslash && hasSlash;
|
|
8364
|
+
}
|
|
8365
|
+
/**
|
|
8366
|
+
* Calls an argument of which is used as is (#1416 re-review 2): the path builders and the
|
|
8367
|
+
* path sinks. An allow-list: any other callee, a local wrapper included, may decode or
|
|
8368
|
+
* rewrite its argument, so a guard on the raw value does not cover its result. A builder
|
|
8369
|
+
* counts only when it comes from `path` / `node:path` (#1416 re-review 3): `path.join`
|
|
8370
|
+
* with `path` imported or required from it, or a bare `join` imported from it.
|
|
8371
|
+
*/
|
|
8372
|
+
const JS_PATH_BUILDERS = new Set(['join', 'resolve', 'normalize']);
|
|
8373
|
+
const JS_PATH_SINK_CALLEES = new Set([
|
|
8374
|
+
'readFile', 'readFileSync', 'writeFile', 'writeFileSync', 'appendFile', 'appendFileSync',
|
|
8375
|
+
'createReadStream', 'createWriteStream', 'open', 'openSync', 'stat', 'statSync',
|
|
8376
|
+
'lstat', 'lstatSync', 'access', 'accessSync', 'existsSync', 'readdir', 'readdirSync',
|
|
8377
|
+
'mkdir', 'mkdirSync', 'rm', 'rmSync', 'rmdir', 'rmdirSync', 'unlink', 'unlinkSync',
|
|
8378
|
+
'copyFile', 'copyFileSync', 'rename', 'renameSync', 'sendFile', 'download',
|
|
8379
|
+
]);
|
|
8380
|
+
/** Sinks whose first two arguments are both paths: the other one must be constant too. */
|
|
8381
|
+
const JS_TWO_PATH_SINKS = new Set(['copyFile', 'copyFileSync', 'rename', 'renameSync']);
|
|
8382
|
+
const JS_PATH_MODULES = new Set(['path', 'node:path', 'path/posix', 'node:path/posix', 'path/win32', 'node:path/win32']);
|
|
8383
|
+
const JS_IDENT = /^[A-Za-z_$][\w$]*$/;
|
|
8384
|
+
/** The module named by a `'…'` / `"…"` string, or undefined. */
|
|
8385
|
+
function quotedModule(text) {
|
|
8386
|
+
const t = text.trim();
|
|
8387
|
+
const q = t.charAt(0);
|
|
8388
|
+
if ((q !== "'" && q !== '"') || t.length < 2 || t.charAt(t.length - 1) !== q)
|
|
8389
|
+
return undefined;
|
|
8390
|
+
return t.slice(1, -1);
|
|
8391
|
+
}
|
|
8392
|
+
/** Records `{ a, b as c }` (import) or `{ a, b: c }` (require) taken from the path module. */
|
|
8393
|
+
function addPathNamedBindings(inner, sep, b) {
|
|
8394
|
+
for (const part of inner.split(',')) {
|
|
8395
|
+
const t = part.trim();
|
|
8396
|
+
if (!t)
|
|
8077
8397
|
continue;
|
|
8078
|
-
const
|
|
8079
|
-
const
|
|
8080
|
-
const
|
|
8081
|
-
|
|
8082
|
-
anyQ(cond, (q) => `!${slash(q)}`) && anyQ(cond, dbl) && anyQ(cond, back) &&
|
|
8083
|
-
!anyQ(cond, (q) => `!${dbl(q)}`) && !anyQ(cond, (q) => `!${back(q)}`);
|
|
8084
|
-
const accept = (cond.includes('&&') && !cond.includes('||') &&
|
|
8085
|
-
anyQ(cond, slash) && !anyQ(cond, (q) => `!${slash(q)}`) &&
|
|
8086
|
-
anyQ(cond, (q) => `!${dbl(q)}`) && anyQ(cond, (q) => `!${back(q)}`)) ||
|
|
8087
|
-
(!!regexAccept && !cond.includes(`!${regexAccept}`) && !cond.includes('||'));
|
|
8088
|
-
const ref = varRefFor(v);
|
|
8089
|
-
if (!isIf) {
|
|
8090
|
-
// ternary: credited only when the guarded value is the consequent (`<guard> ? next : <fallback>`)
|
|
8091
|
-
if (accept && cond.includes(`?${v}:`))
|
|
8092
|
-
sanitizers.push({ type: 'js_relative_redirect_guard', method: 'startsWith', line: i + 1, sanitizes: ['open_redirect'] });
|
|
8398
|
+
const at = sep === 'as' ? t.search(/\sas\s/) : t.indexOf(':');
|
|
8399
|
+
const imported = (at < 0 ? t : t.slice(0, at)).trim();
|
|
8400
|
+
const local = (at < 0 ? t : t.slice(at + (sep === 'as' ? 4 : 1))).trim();
|
|
8401
|
+
if (!JS_IDENT.test(local))
|
|
8093
8402
|
continue;
|
|
8403
|
+
if (JS_PATH_BUILDERS.has(imported))
|
|
8404
|
+
b.builders.add(local);
|
|
8405
|
+
else if (imported === 'posix' || imported === 'win32')
|
|
8406
|
+
b.modules.add(local);
|
|
8407
|
+
}
|
|
8408
|
+
}
|
|
8409
|
+
/** The identifier that starts `text` (after leading whitespace), or undefined. A plain scan, no regex. */
|
|
8410
|
+
function leadingIdentifier(text) {
|
|
8411
|
+
const t = text.trimStart();
|
|
8412
|
+
let k = 0;
|
|
8413
|
+
while (k < t.length && /[\w$]/.test(t[k]))
|
|
8414
|
+
k++;
|
|
8415
|
+
const id = t.slice(0, k);
|
|
8416
|
+
return id && JS_IDENT.test(id) ? id : undefined;
|
|
8417
|
+
}
|
|
8418
|
+
/** The index of the bracket that closes the `(` / `[` / `{` at `open`, skipping quoted strings; -1 if none. */
|
|
8419
|
+
function matchingBracket(text, open) {
|
|
8420
|
+
let depth = 0;
|
|
8421
|
+
for (let k = open; k < text.length; k++) {
|
|
8422
|
+
const ch = text[k];
|
|
8423
|
+
if (ch === "'" || ch === '"' || ch === '`') {
|
|
8424
|
+
const q = ch;
|
|
8425
|
+
for (k++; k < text.length && text[k] !== q; k++)
|
|
8426
|
+
if (text[k] === '\\')
|
|
8427
|
+
k++;
|
|
8094
8428
|
}
|
|
8095
|
-
if (
|
|
8096
|
-
|
|
8097
|
-
|
|
8098
|
-
|
|
8099
|
-
sanitizers.push({ type: 'js_relative_redirect_guard', method: 'startsWith', line: l + 1, sanitizes: ['open_redirect'] });
|
|
8100
|
-
}
|
|
8101
|
-
}
|
|
8102
|
-
else if (accept) {
|
|
8103
|
-
const block = jsBracedBlockLines(lines, i);
|
|
8104
|
-
const body = block ?? [raw];
|
|
8105
|
-
for (let k = 0; k < body.length; k++) {
|
|
8106
|
-
if (ref.test(k === 0 ? raw.slice(raw.indexOf(')', raw.indexOf('if')) + 1) : body[k])) {
|
|
8107
|
-
sanitizers.push({ type: 'js_relative_redirect_guard', method: 'startsWith', line: i + k + 1, sanitizes: ['open_redirect'] });
|
|
8108
|
-
}
|
|
8109
|
-
}
|
|
8110
|
-
}
|
|
8429
|
+
else if (ch === '(' || ch === '[' || ch === '{')
|
|
8430
|
+
depth++;
|
|
8431
|
+
else if ((ch === ')' || ch === ']' || ch === '}') && --depth === 0)
|
|
8432
|
+
return k;
|
|
8111
8433
|
}
|
|
8112
|
-
return
|
|
8434
|
+
return -1;
|
|
8113
8435
|
}
|
|
8114
8436
|
/**
|
|
8115
|
-
*
|
|
8116
|
-
*
|
|
8437
|
+
* `text` cut at its first top-level `;` or unbalanced closing bracket, then split at the
|
|
8438
|
+
* top-level `sep` characters; quoted strings and bracketed parts are kept whole.
|
|
8439
|
+
*/
|
|
8440
|
+
function splitTopLevel(text, sep) {
|
|
8441
|
+
const parts = [];
|
|
8442
|
+
let depth = 0;
|
|
8443
|
+
let from = 0;
|
|
8444
|
+
for (let k = 0; k < text.length; k++) {
|
|
8445
|
+
const ch = text[k];
|
|
8446
|
+
if (ch === "'" || ch === '"' || ch === '`') {
|
|
8447
|
+
const q = ch;
|
|
8448
|
+
for (k++; k < text.length && text[k] !== q; k++)
|
|
8449
|
+
if (text[k] === '\\')
|
|
8450
|
+
k++;
|
|
8451
|
+
}
|
|
8452
|
+
else if (ch === '(' || ch === '[' || ch === '{')
|
|
8453
|
+
depth++;
|
|
8454
|
+
else if (ch === ')' || ch === ']' || ch === '}') {
|
|
8455
|
+
if (--depth < 0) {
|
|
8456
|
+
parts.push(text.slice(from, k));
|
|
8457
|
+
return parts;
|
|
8458
|
+
}
|
|
8459
|
+
}
|
|
8460
|
+
else if (depth === 0 && ch === ';') {
|
|
8461
|
+
parts.push(text.slice(from, k));
|
|
8462
|
+
return parts;
|
|
8463
|
+
}
|
|
8464
|
+
else if (depth === 0 && ch === sep) {
|
|
8465
|
+
parts.push(text.slice(from, k));
|
|
8466
|
+
from = k + 1;
|
|
8467
|
+
}
|
|
8468
|
+
}
|
|
8469
|
+
parts.push(text.slice(from));
|
|
8470
|
+
return parts;
|
|
8471
|
+
}
|
|
8472
|
+
/** Adds the names a binding target binds: `a`, `a: T`, `...a`, `{ a, b: c, d = 1 }`, `[a, [b]]`. */
|
|
8473
|
+
function addBindingNames(target, out, depth = 0) {
|
|
8474
|
+
let t = target.trim();
|
|
8475
|
+
if (t.startsWith('...'))
|
|
8476
|
+
t = t.slice(3).trim();
|
|
8477
|
+
const c = t.charAt(0);
|
|
8478
|
+
if ((c === '{' || c === '[') && depth < 8) {
|
|
8479
|
+
const close = matchingBracket(t, 0);
|
|
8480
|
+
for (const part of splitTopLevel(t.slice(1, close < 0 ? t.length : close), ',')) {
|
|
8481
|
+
const element = splitTopLevel(part, '=')[0];
|
|
8482
|
+
const kv = c === '{' ? splitTopLevel(element, ':') : [element];
|
|
8483
|
+
addBindingNames(kv.length > 1 ? kv.slice(1).join(':') : kv[0], out, depth + 1);
|
|
8484
|
+
}
|
|
8485
|
+
return;
|
|
8486
|
+
}
|
|
8487
|
+
const id = leadingIdentifier(t);
|
|
8488
|
+
if (id !== undefined)
|
|
8489
|
+
out.push(id);
|
|
8490
|
+
}
|
|
8491
|
+
/** Adds the names a parameter list (the text inside its parentheses) binds; TS parameter-property modifiers are skipped. */
|
|
8492
|
+
function addParameterNames(params, out) {
|
|
8493
|
+
for (const p of splitTopLevel(params, ',')) {
|
|
8494
|
+
const t = p.trim().replace(/^(?:(?:public|private|protected|readonly|override)\s+)+/, '');
|
|
8495
|
+
addBindingNames(splitTopLevel(t, '=')[0], out);
|
|
8496
|
+
}
|
|
8497
|
+
}
|
|
8498
|
+
/** Each `(` of the text mapped to the `)` that closes it, in one pass that skips quoted strings. */
|
|
8499
|
+
function parenPairs(line) {
|
|
8500
|
+
const pairs = new Map();
|
|
8501
|
+
const open = [];
|
|
8502
|
+
for (let k = 0; k < line.length; k++) {
|
|
8503
|
+
const ch = line[k];
|
|
8504
|
+
if (ch === "'" || ch === '"' || ch === '`') {
|
|
8505
|
+
const q = ch;
|
|
8506
|
+
for (k++; k < line.length && line[k] !== q; k++)
|
|
8507
|
+
if (line[k] === '\\')
|
|
8508
|
+
k++;
|
|
8509
|
+
}
|
|
8510
|
+
else if (ch === '(')
|
|
8511
|
+
open.push(k);
|
|
8512
|
+
else if (ch === ')' && open.length > 0)
|
|
8513
|
+
pairs.set(open.pop(), k);
|
|
8514
|
+
}
|
|
8515
|
+
return pairs;
|
|
8516
|
+
}
|
|
8517
|
+
/** Whether `text` ends with the word `function`, optionally followed by `*` (a generator). */
|
|
8518
|
+
function endsWithFunctionKeyword(text) {
|
|
8519
|
+
let t = text.trimEnd();
|
|
8520
|
+
if (t.endsWith('*'))
|
|
8521
|
+
t = t.slice(0, -1).trimEnd();
|
|
8522
|
+
if (!t.endsWith('function'))
|
|
8523
|
+
return false;
|
|
8524
|
+
const before = t.charAt(t.length - 9);
|
|
8525
|
+
return before === '' || !/[\w$.]/.test(before);
|
|
8526
|
+
}
|
|
8527
|
+
/** Words that take a parenthesised head followed by a block, and so are not method definitions. */
|
|
8528
|
+
const JS_BLOCK_KEYWORDS = new Set(['if', 'for', 'while', 'switch', 'with', 'return', 'typeof', 'await', 'function']);
|
|
8529
|
+
/**
|
|
8530
|
+
* The file text the declaration scan reads (#1416 re-review 5): comments and the contents of
|
|
8531
|
+
* quoted strings and template literals blanked to spaces, newlines kept, and a `\x` escape
|
|
8532
|
+
* outside a string blanked, so no bracket or quote in them is counted. The contents of a regex
|
|
8533
|
+
* literal that starts where a regex may (`regexMayStart`) and ends on its line are blanked too.
|
|
8534
|
+
* A `'` or `"` string ends at the end of its line, and a quote left open (`/'/`) is blanked.
|
|
8535
|
+
*/
|
|
8536
|
+
function jsDeclarationText(code) {
|
|
8537
|
+
const c = code.split('');
|
|
8538
|
+
const blank = (from, to) => {
|
|
8539
|
+
for (let k = from; k < to && k < c.length; k++)
|
|
8540
|
+
if (c[k] !== '\n')
|
|
8541
|
+
c[k] = ' ';
|
|
8542
|
+
};
|
|
8543
|
+
for (let k = 0; k < c.length; k++) {
|
|
8544
|
+
const ch = c[k];
|
|
8545
|
+
if (ch === '\\') {
|
|
8546
|
+
blank(k, k + 2);
|
|
8547
|
+
k++;
|
|
8548
|
+
}
|
|
8549
|
+
else if (ch === "'" || ch === '"' || ch === '`') {
|
|
8550
|
+
const lineEnd = ch === '`' ? '`' : '\n';
|
|
8551
|
+
let e = k + 1;
|
|
8552
|
+
for (; e < c.length && c[e] !== ch && c[e] !== lineEnd; e++)
|
|
8553
|
+
if (c[e] === '\\')
|
|
8554
|
+
e++;
|
|
8555
|
+
// an unclosed quote is blanked too, so every quote left in the text pairs on its line
|
|
8556
|
+
blank(c[e] === ch ? k + 1 : k, e);
|
|
8557
|
+
k = e;
|
|
8558
|
+
}
|
|
8559
|
+
else if (ch === '/' && c[k + 1] === '/') {
|
|
8560
|
+
const e = code.indexOf('\n', k);
|
|
8561
|
+
blank(k, e < 0 ? c.length : e);
|
|
8562
|
+
k = e < 0 ? c.length : e;
|
|
8563
|
+
}
|
|
8564
|
+
else if (ch === '/' && c[k + 1] === '*') {
|
|
8565
|
+
const e = code.indexOf('*/', k + 2);
|
|
8566
|
+
blank(k, e < 0 ? c.length : e + 2);
|
|
8567
|
+
k = e < 0 ? c.length : e + 1;
|
|
8568
|
+
}
|
|
8569
|
+
else if (ch === '/' && regexMayStart(c, k)) {
|
|
8570
|
+
// a regex literal on one line: its contents are blanked, so a `/*`, `//` or quote in it
|
|
8571
|
+
// (`/[/*]/`) opens nothing
|
|
8572
|
+
let e = k + 1;
|
|
8573
|
+
let inClass = false;
|
|
8574
|
+
for (; e < c.length && c[e] !== '\n'; e++) {
|
|
8575
|
+
if (c[e] === '\\' && c[e + 1] !== '\n')
|
|
8576
|
+
e++;
|
|
8577
|
+
else if (c[e] === '[')
|
|
8578
|
+
inClass = true;
|
|
8579
|
+
else if (c[e] === ']')
|
|
8580
|
+
inClass = false;
|
|
8581
|
+
else if (c[e] === '/' && !inClass)
|
|
8582
|
+
break;
|
|
8583
|
+
}
|
|
8584
|
+
if (c[e] === '/') {
|
|
8585
|
+
blank(k + 1, e);
|
|
8586
|
+
k = e;
|
|
8587
|
+
}
|
|
8588
|
+
}
|
|
8589
|
+
}
|
|
8590
|
+
return c.join('');
|
|
8591
|
+
}
|
|
8592
|
+
/** Words after which a `/` starts a regex literal, not a division (`return /re/`). */
|
|
8593
|
+
const JS_REGEX_PREFIX_WORDS = new Set([
|
|
8594
|
+
'return', 'typeof', 'case', 'void', 'delete', 'throw', 'new', 'in', 'of', 'yield', 'await', 'else', 'do',
|
|
8595
|
+
]);
|
|
8596
|
+
/**
|
|
8597
|
+
* Whether a `/` at `k` (not followed by `/` or `*`) can start a regex literal rather than divide:
|
|
8598
|
+
* the previous non-blank character is one of `( , = : [ ! & | ? { } ; < > + - * % ~ ^` (so after
|
|
8599
|
+
* `=>` too), the previous word is a whole `return`, `typeof`, `case`, `void`, `delete`, `throw`,
|
|
8600
|
+
* `new`, `in`, `of`, `yield`, `await`, `else` or `do`, or there is nothing before it on its line
|
|
8601
|
+
* (#1416 re-review 6). Accepted misreads, of division: after a postfix `++` / `--`, after a `}`
|
|
8602
|
+
* that ends an expression, and on a continued line that starts with `/` (`total⏎ / 2 / n`).
|
|
8603
|
+
* The text between the two slashes is then blanked, which could hide a declaration only in
|
|
8604
|
+
* contrived code.
|
|
8605
|
+
*/
|
|
8606
|
+
function regexMayStart(c, k) {
|
|
8607
|
+
let p = k - 1;
|
|
8608
|
+
while (p >= 0 && (c[p] === ' ' || c[p] === '\t'))
|
|
8609
|
+
p--;
|
|
8610
|
+
if (p < 0 || '(,=:[!&|?{};<>+-*%~^\n'.includes(c[p]))
|
|
8611
|
+
return true;
|
|
8612
|
+
let w = p;
|
|
8613
|
+
while (w >= 0 && /[a-z]/.test(c[w]))
|
|
8614
|
+
w--;
|
|
8615
|
+
if (w === p || (w >= 0 && /[\w$.]/.test(c[w])))
|
|
8616
|
+
return false;
|
|
8617
|
+
return JS_REGEX_PREFIX_WORDS.has(c.slice(w + 1, p + 1).join(''));
|
|
8618
|
+
}
|
|
8619
|
+
/** The index of the first non-blank character at or after `k` (`text.length` if none). */
|
|
8620
|
+
function skipBlank(text, k) {
|
|
8621
|
+
while (k < text.length && /\s/.test(text[k]))
|
|
8622
|
+
k++;
|
|
8623
|
+
return k;
|
|
8624
|
+
}
|
|
8625
|
+
/**
|
|
8626
|
+
* The end of a `const` / `let` / `var` declarator list that starts at `from`: its first `;` or
|
|
8627
|
+
* unbalanced closing bracket, or a line break outside brackets that neither follows nor precedes
|
|
8628
|
+
* a `,` or `=`. Brackets may span lines, so `const {⏎ join,⏎ } = h` is read whole.
|
|
8629
|
+
*/
|
|
8630
|
+
function declarationEnd(text, from) {
|
|
8631
|
+
let depth = 0;
|
|
8632
|
+
for (let k = from; k < text.length; k++) {
|
|
8633
|
+
const ch = text[k];
|
|
8634
|
+
if (ch === '(' || ch === '[' || ch === '{')
|
|
8635
|
+
depth++;
|
|
8636
|
+
else if (ch === ')' || ch === ']' || ch === '}') {
|
|
8637
|
+
if (--depth < 0)
|
|
8638
|
+
return k;
|
|
8639
|
+
}
|
|
8640
|
+
else if (depth === 0 && ch === ';')
|
|
8641
|
+
return k;
|
|
8642
|
+
else if (depth === 0 && ch === '\n') {
|
|
8643
|
+
const prev = text.slice(from, k).trimEnd().slice(-1);
|
|
8644
|
+
const next = text.charAt(skipBlank(text, k));
|
|
8645
|
+
if (prev !== ',' && prev !== '=' && next !== ',' && next !== '=')
|
|
8646
|
+
return k;
|
|
8647
|
+
}
|
|
8648
|
+
}
|
|
8649
|
+
return text.length;
|
|
8650
|
+
}
|
|
8651
|
+
/** How far past a `)` a return type is read before the scan gives up. */
|
|
8652
|
+
const JS_TYPE_WINDOW = 2000;
|
|
8653
|
+
/**
|
|
8654
|
+
* Where the body or arrow after a parameter list's `)` at `close` starts: the `{` or `=>` that
|
|
8655
|
+
* follows, after an optional TypeScript return type (`: T`, `: Promise<{ a: string }>`,
|
|
8656
|
+
* `: (a: string) => string`); -1 when none follows. A type may span lines inside brackets; a
|
|
8657
|
+
* line break outside them ends it unless the next line starts with `{`, `=>`, `|` or `&`.
|
|
8658
|
+
* A `{` at depth 0 is the body unless its matching `}` is followed by `=>`, `{`, `|`, `&` or
|
|
8659
|
+
* `[`: then the braces are an object type (`): { data: Buffer } => {`) and the scan goes on,
|
|
8660
|
+
* falling back to that `{` if nothing after it reads as a body (#1416 re-review 6).
|
|
8661
|
+
*/
|
|
8662
|
+
function parameterListBodyStart(text, close) {
|
|
8663
|
+
let k = skipBlank(text, close + 1);
|
|
8664
|
+
if (text[k] === '{' || text.startsWith('=>', k))
|
|
8665
|
+
return k;
|
|
8666
|
+
if (text[k] !== ':')
|
|
8667
|
+
return -1;
|
|
8668
|
+
let depth = 0;
|
|
8669
|
+
let objectType = -1;
|
|
8670
|
+
const end = Math.min(text.length, k + JS_TYPE_WINDOW);
|
|
8671
|
+
for (k++; k < end; k++) {
|
|
8672
|
+
const ch = text[k];
|
|
8673
|
+
if (ch === '=' && text[k + 1] === '>') {
|
|
8674
|
+
if (depth === 0)
|
|
8675
|
+
return k;
|
|
8676
|
+
k++;
|
|
8677
|
+
}
|
|
8678
|
+
else if (ch === '(' || ch === '[' || ch === '<')
|
|
8679
|
+
depth++;
|
|
8680
|
+
else if (ch === '{') {
|
|
8681
|
+
if (depth === 0) {
|
|
8682
|
+
const close = matchingBrace(text, k);
|
|
8683
|
+
const next = close < 0 ? -1 : skipBlank(text, close + 1);
|
|
8684
|
+
if (next < 0 || !(['{', '|', '&', '['].includes(text.charAt(next)) || text.startsWith('=>', next)))
|
|
8685
|
+
return k;
|
|
8686
|
+
if (objectType < 0)
|
|
8687
|
+
objectType = k;
|
|
8688
|
+
k = next - 1;
|
|
8689
|
+
continue;
|
|
8690
|
+
}
|
|
8691
|
+
depth++;
|
|
8692
|
+
}
|
|
8693
|
+
else if (ch === ')' || ch === ']' || ch === '>' || ch === '}') {
|
|
8694
|
+
if (--depth < 0)
|
|
8695
|
+
return objectType;
|
|
8696
|
+
}
|
|
8697
|
+
else if (depth === 0 && (ch === ';' || ch === ',' || ch === '='))
|
|
8698
|
+
return objectType;
|
|
8699
|
+
else if (depth === 0 && ch === '\n') {
|
|
8700
|
+
const next = skipBlank(text, k);
|
|
8701
|
+
if (!['{', '|', '&'].includes(text.charAt(next)) && !text.startsWith('=>', next))
|
|
8702
|
+
return objectType;
|
|
8703
|
+
}
|
|
8704
|
+
}
|
|
8705
|
+
return objectType;
|
|
8706
|
+
}
|
|
8707
|
+
/** The index of the `}` that closes the `{` at `open` (-1 if none). */
|
|
8708
|
+
function matchingBrace(text, open) {
|
|
8709
|
+
let depth = 0;
|
|
8710
|
+
for (let k = open; k < text.length; k++) {
|
|
8711
|
+
if (text[k] === '{')
|
|
8712
|
+
depth++;
|
|
8713
|
+
else if (text[k] === '}' && --depth === 0)
|
|
8714
|
+
return k;
|
|
8715
|
+
}
|
|
8716
|
+
return -1;
|
|
8717
|
+
}
|
|
8718
|
+
/** `head` (the text before a `(`) with a trailing `<…>` type-parameter list removed. */
|
|
8719
|
+
function withoutTypeParameters(head) {
|
|
8720
|
+
const t = head.trimEnd();
|
|
8721
|
+
if (!t.endsWith('>'))
|
|
8722
|
+
return t;
|
|
8723
|
+
let depth = 0;
|
|
8724
|
+
for (let k = t.length - 1; k >= 0; k--) {
|
|
8725
|
+
if (t[k] === '>' && t[k - 1] !== '=')
|
|
8726
|
+
depth++;
|
|
8727
|
+
else if (t[k] === '<' && --depth === 0)
|
|
8728
|
+
return t.slice(0, k).trimEnd();
|
|
8729
|
+
}
|
|
8730
|
+
return t;
|
|
8731
|
+
}
|
|
8732
|
+
/** How far back from a `(` the scan looks for the function or method name before it. */
|
|
8733
|
+
const JS_HEAD_WINDOW = 400;
|
|
8734
|
+
/**
|
|
8735
|
+
* Every name a file declares (#1416 re-review 5): `const` / `let` / `var` targets, destructuring
|
|
8736
|
+
* included; `function` and `class` names; the parameters of functions, arrows, methods and
|
|
8737
|
+
* `catch`; import bindings. It reads the whole file text with comments and string contents
|
|
8738
|
+
* blanked, not line by line, so a parameter list or destructuring pattern over several lines,
|
|
8739
|
+
* a TypeScript return type after `)` and `<…>` type parameters before `(` are all read. A plain
|
|
8740
|
+
* scan: it may also list a name that is not declared (that only costs a credit).
|
|
8741
|
+
*/
|
|
8742
|
+
function jsDeclaredNames(code) {
|
|
8743
|
+
const text = jsDeclarationText(code);
|
|
8744
|
+
const out = [];
|
|
8745
|
+
for (const m of text.matchAll(/^[ \t]*import\s([^;'"`]*?)\sfrom\s*['"]/gm)) {
|
|
8746
|
+
let clause = m[1].replace(/\s+/g, ' ').trim();
|
|
8747
|
+
if (clause.startsWith('type '))
|
|
8748
|
+
continue;
|
|
8749
|
+
const brace = clause.indexOf('{');
|
|
8750
|
+
if (brace >= 0) {
|
|
8751
|
+
const close = clause.indexOf('}', brace);
|
|
8752
|
+
for (const part of clause.slice(brace + 1, close > brace ? close : clause.length).split(',')) {
|
|
8753
|
+
const t = part.trim().replace(/^type\s/, '').trim();
|
|
8754
|
+
const at = t.lastIndexOf(' as ');
|
|
8755
|
+
const id = leadingIdentifier(at < 0 ? t : t.slice(at + 4));
|
|
8756
|
+
if (id !== undefined)
|
|
8757
|
+
out.push(id);
|
|
8758
|
+
}
|
|
8759
|
+
clause = clause.slice(0, brace);
|
|
8760
|
+
}
|
|
8761
|
+
for (const part of clause.split(',')) {
|
|
8762
|
+
const t = part.trim();
|
|
8763
|
+
const id = leadingIdentifier(t.startsWith('*') ? t.slice(t.indexOf(' as ') + 4) : t);
|
|
8764
|
+
if (id !== undefined)
|
|
8765
|
+
out.push(id);
|
|
8766
|
+
}
|
|
8767
|
+
}
|
|
8768
|
+
for (const m of text.matchAll(/\b(?:const|let|var)\s/g)) {
|
|
8769
|
+
const from = m.index + m[0].length;
|
|
8770
|
+
for (const declarator of splitTopLevel(text.slice(from, declarationEnd(text, from)), ',')) {
|
|
8771
|
+
addBindingNames(splitTopLevel(declarator, '=')[0], out);
|
|
8772
|
+
}
|
|
8773
|
+
}
|
|
8774
|
+
for (const m of text.matchAll(/\b(?:function|class)\b/g)) {
|
|
8775
|
+
const id = leadingIdentifier(text.slice(m.index + m[0].length, m.index + m[0].length + JS_HEAD_WINDOW).replace(/^\s*\*/, ''));
|
|
8776
|
+
if (id !== undefined)
|
|
8777
|
+
out.push(id);
|
|
8778
|
+
}
|
|
8779
|
+
for (const [k, close] of parenPairs(text)) {
|
|
8780
|
+
const head = withoutTypeParameters(text.slice(Math.max(0, k - JS_HEAD_WINDOW), k));
|
|
8781
|
+
const name = trailingIdentifier(head);
|
|
8782
|
+
const before = name === undefined ? head : head.slice(0, -name.length).trimEnd();
|
|
8783
|
+
const body = parameterListBodyStart(text, close);
|
|
8784
|
+
const arrow = body >= 0 && text.startsWith('=>', body);
|
|
8785
|
+
const isFunction = name === 'function' || endsWithFunctionKeyword(before);
|
|
8786
|
+
// a method: `name(…) {` or `name(…): T {`; not `a ? f(x) : {…}`, `case f(x): {` or `o.f(x)`
|
|
8787
|
+
const method = name !== undefined && !JS_BLOCK_KEYWORDS.has(name) && body >= 0 && !arrow &&
|
|
8788
|
+
!/[.?]$/.test(before) && trailingIdentifier(before) !== 'case';
|
|
8789
|
+
if (arrow || isFunction || method)
|
|
8790
|
+
addParameterNames(text.slice(k + 1, close), out);
|
|
8791
|
+
}
|
|
8792
|
+
for (let k = text.indexOf('=>'); k >= 0; k = text.indexOf('=>', k + 2)) {
|
|
8793
|
+
const before = text.slice(Math.max(0, k - JS_HEAD_WINDOW), k);
|
|
8794
|
+
const id = trailingIdentifier(before);
|
|
8795
|
+
if (id !== undefined && !before.trimEnd().endsWith(')'))
|
|
8796
|
+
out.push(id);
|
|
8797
|
+
}
|
|
8798
|
+
return out;
|
|
8799
|
+
}
|
|
8800
|
+
/** `line` trimmed, without a trailing line comment or any block comment that closes on it. */
|
|
8801
|
+
function withoutLineComments(line) {
|
|
8802
|
+
let out = '';
|
|
8803
|
+
for (let k = 0; k < line.length; k++) {
|
|
8804
|
+
if (line.startsWith('//', k))
|
|
8805
|
+
break;
|
|
8806
|
+
if (line.startsWith('/*', k)) {
|
|
8807
|
+
const e = line.indexOf('*/', k + 2);
|
|
8808
|
+
if (e < 0)
|
|
8809
|
+
break;
|
|
8810
|
+
out += ' ';
|
|
8811
|
+
k = e + 1;
|
|
8812
|
+
}
|
|
8813
|
+
else
|
|
8814
|
+
out += line[k];
|
|
8815
|
+
}
|
|
8816
|
+
return out.trim();
|
|
8817
|
+
}
|
|
8818
|
+
/**
|
|
8819
|
+
* The `path` bindings of a file, by a plain scan of its lines: `import path from 'path'`,
|
|
8820
|
+
* `import * as p from 'node:path'`, `import { join as j, posix } from 'path'` (on one line or
|
|
8821
|
+
* over several),
|
|
8822
|
+
* `const path = require('path')`, `const { join, resolve: r } = require('node:path')`.
|
|
8823
|
+
* A name the file declares more than once (re-declared or shadowed in any scope, as a
|
|
8824
|
+
* variable, function or parameter) is dropped from all three sets (#1416 re-review 4).
|
|
8825
|
+
*/
|
|
8826
|
+
function jsPathBindings(lines) {
|
|
8827
|
+
const b = { modules: new Set(), builders: new Set(), constants: new Map() };
|
|
8828
|
+
const declared = new Map();
|
|
8829
|
+
for (const n of jsDeclaredNames(lines.join('\n')))
|
|
8830
|
+
declared.set(n, (declared.get(n) ?? 0) + 1);
|
|
8831
|
+
for (let i = 0; i < lines.length; i++) {
|
|
8832
|
+
let line = lines[i].trim();
|
|
8833
|
+
// an import list over several lines (`import {` … `} from 'path';`) is read as one line
|
|
8834
|
+
if (line.startsWith('import ') && line.includes('{') && !line.includes('}')) {
|
|
8835
|
+
// a line or block comment in the list is dropped, so it hides no name after it
|
|
8836
|
+
line = withoutLineComments(line);
|
|
8837
|
+
while (i + 1 < lines.length && !line.includes('}'))
|
|
8838
|
+
line += ' ' + withoutLineComments(lines[++i]);
|
|
8839
|
+
}
|
|
8840
|
+
line = line.replace(/;$/, '').trimEnd();
|
|
8841
|
+
if (line.startsWith('import ')) {
|
|
8842
|
+
const from = line.lastIndexOf(' from ');
|
|
8843
|
+
if (from < 0)
|
|
8844
|
+
continue;
|
|
8845
|
+
const mod = quotedModule(line.slice(from + 6));
|
|
8846
|
+
if (mod === undefined || !JS_PATH_MODULES.has(mod))
|
|
8847
|
+
continue;
|
|
8848
|
+
let clause = line.slice(7, from).trim();
|
|
8849
|
+
if (clause.startsWith('type '))
|
|
8850
|
+
continue;
|
|
8851
|
+
const brace = clause.indexOf('{');
|
|
8852
|
+
if (brace >= 0) {
|
|
8853
|
+
const close = clause.indexOf('}', brace);
|
|
8854
|
+
if (close > brace)
|
|
8855
|
+
addPathNamedBindings(clause.slice(brace + 1, close), 'as', b);
|
|
8856
|
+
clause = clause.slice(0, brace);
|
|
8857
|
+
}
|
|
8858
|
+
for (const part of clause.split(',')) {
|
|
8859
|
+
const t = part.trim();
|
|
8860
|
+
const local = t.startsWith('*') ? t.slice(t.indexOf(' as ') + 4).trim() : t;
|
|
8861
|
+
if (JS_IDENT.test(local))
|
|
8862
|
+
b.modules.add(local);
|
|
8863
|
+
}
|
|
8864
|
+
continue;
|
|
8865
|
+
}
|
|
8866
|
+
const decl = /^(const|let|var)\s+/.exec(line);
|
|
8867
|
+
if (!decl)
|
|
8868
|
+
continue;
|
|
8869
|
+
const rest = line.slice(decl[0].length);
|
|
8870
|
+
const eq = rest.indexOf('=');
|
|
8871
|
+
if (eq < 0 || rest.charAt(eq + 1) === '=')
|
|
8872
|
+
continue;
|
|
8873
|
+
const target = rest.slice(0, eq).trim();
|
|
8874
|
+
const init = rest.slice(eq + 1).trim();
|
|
8875
|
+
if (init.startsWith('require(') && init.endsWith(')')) {
|
|
8876
|
+
const mod = quotedModule(init.slice(8, -1));
|
|
8877
|
+
if (mod !== undefined && JS_PATH_MODULES.has(mod)) {
|
|
8878
|
+
if (JS_IDENT.test(target))
|
|
8879
|
+
b.modules.add(target);
|
|
8880
|
+
else if (target.startsWith('{') && target.endsWith('}'))
|
|
8881
|
+
addPathNamedBindings(target.slice(1, -1), ':', b);
|
|
8882
|
+
continue;
|
|
8883
|
+
}
|
|
8884
|
+
}
|
|
8885
|
+
if (decl[1] === 'const' && JS_IDENT.test(target))
|
|
8886
|
+
b.constants.set(target, init);
|
|
8887
|
+
}
|
|
8888
|
+
// a name declared more than once means something else in some scope
|
|
8889
|
+
const once = (n) => declared.get(n) === 1;
|
|
8890
|
+
return {
|
|
8891
|
+
modules: new Set([...b.modules].filter(once)),
|
|
8892
|
+
builders: new Set([...b.builders].filter(once)),
|
|
8893
|
+
constants: new Map([...b.constants].filter(([n]) => once(n))),
|
|
8894
|
+
};
|
|
8895
|
+
}
|
|
8896
|
+
/** The identifier that ends `text` (after trailing whitespace), or undefined. A plain scan, no regex. */
|
|
8897
|
+
function trailingIdentifier(text) {
|
|
8898
|
+
const t = text.trimEnd();
|
|
8899
|
+
let k = t.length;
|
|
8900
|
+
while (k > 0 && /[\w$]/.test(t[k - 1]))
|
|
8901
|
+
k--;
|
|
8902
|
+
const id = t.slice(k);
|
|
8903
|
+
return id && /^[A-Za-z_$][\w$]*$/.test(id) ? id : undefined;
|
|
8904
|
+
}
|
|
8905
|
+
/** Whether the receiver chain that ends `text` (`path`, `path.posix`) is the path module. */
|
|
8906
|
+
function isPathModuleRef(text, b) {
|
|
8907
|
+
const recv = trailingIdentifier(text);
|
|
8908
|
+
if (recv === undefined)
|
|
8909
|
+
return false;
|
|
8910
|
+
const before = text.trimEnd().slice(0, -recv.length).trimEnd();
|
|
8911
|
+
if (!before.endsWith('.'))
|
|
8912
|
+
return b.modules.has(recv);
|
|
8913
|
+
// `x.posix` / `x.win32` where `x` is the module; any other member (`this.path`) is not
|
|
8914
|
+
if (recv !== 'posix' && recv !== 'win32')
|
|
8915
|
+
return false;
|
|
8916
|
+
const outer = before.slice(0, -1);
|
|
8917
|
+
const id = trailingIdentifier(outer);
|
|
8918
|
+
return id !== undefined && !outer.trimEnd().slice(0, -id.length).trimEnd().endsWith('.') && b.modules.has(id);
|
|
8919
|
+
}
|
|
8920
|
+
/** What `head` (the text before a call's `(`) names: a path builder, a path sink, or neither. */
|
|
8921
|
+
function pathCallKind(head, b) {
|
|
8922
|
+
const callee = trailingIdentifier(head);
|
|
8923
|
+
if (!callee)
|
|
8924
|
+
return undefined;
|
|
8925
|
+
const rest = head.trimEnd().slice(0, -callee.length).trimEnd();
|
|
8926
|
+
const member = rest.endsWith('.');
|
|
8927
|
+
if (!member && b.builders.has(callee))
|
|
8928
|
+
return 'builder';
|
|
8929
|
+
if (member && JS_PATH_BUILDERS.has(callee) && isPathModuleRef(rest.slice(0, -1), b))
|
|
8930
|
+
return 'builder';
|
|
8931
|
+
if (JS_PATH_SINK_CALLEES.has(callee))
|
|
8932
|
+
return 'sink';
|
|
8933
|
+
return undefined;
|
|
8934
|
+
}
|
|
8935
|
+
/** The index of the `)` that closes the `(` at `open`, skipping quoted strings; -1 if not on the line. */
|
|
8936
|
+
function closingParen(line, open) {
|
|
8937
|
+
let depth = 0;
|
|
8938
|
+
for (let k = open; k < line.length; k++) {
|
|
8939
|
+
const ch = line[k];
|
|
8940
|
+
if (ch === "'" || ch === '"' || ch === '`') {
|
|
8941
|
+
const q = ch;
|
|
8942
|
+
for (k++; k < line.length && line[k] !== q; k++)
|
|
8943
|
+
if (line[k] === '\\')
|
|
8944
|
+
k++;
|
|
8945
|
+
}
|
|
8946
|
+
else if (ch === '(' || ch === '[' || ch === '{')
|
|
8947
|
+
depth++;
|
|
8948
|
+
else if (ch === ')' || ch === ']' || ch === '}') {
|
|
8949
|
+
if (--depth === 0)
|
|
8950
|
+
return ch === ')' ? k : -1;
|
|
8951
|
+
}
|
|
8952
|
+
}
|
|
8953
|
+
return -1;
|
|
8954
|
+
}
|
|
8955
|
+
/** The top-level arguments of the call whose `(` is at `open` and `)` at `close`, trimmed. */
|
|
8956
|
+
function callArguments(line, open, close) {
|
|
8957
|
+
const args = [];
|
|
8958
|
+
let depth = 0;
|
|
8959
|
+
let from = open + 1;
|
|
8960
|
+
for (let k = open + 1; k < close; k++) {
|
|
8961
|
+
const ch = line[k];
|
|
8962
|
+
if (ch === "'" || ch === '"' || ch === '`') {
|
|
8963
|
+
const q = ch;
|
|
8964
|
+
for (k++; k < close && line[k] !== q; k++)
|
|
8965
|
+
if (line[k] === '\\')
|
|
8966
|
+
k++;
|
|
8967
|
+
}
|
|
8968
|
+
else if (ch === '(' || ch === '[' || ch === '{')
|
|
8969
|
+
depth++;
|
|
8970
|
+
else if (ch === ')' || ch === ']' || ch === '}')
|
|
8971
|
+
depth--;
|
|
8972
|
+
else if (ch === ',' && depth === 0) {
|
|
8973
|
+
args.push(line.slice(from, k).trim());
|
|
8974
|
+
from = k + 1;
|
|
8975
|
+
}
|
|
8976
|
+
}
|
|
8977
|
+
args.push(line.slice(from, close).trim());
|
|
8978
|
+
return args;
|
|
8979
|
+
}
|
|
8980
|
+
/**
|
|
8981
|
+
* Whether `arg` is a constant path piece (#1416 re-review 3): a string literal, `__dirname`,
|
|
8982
|
+
* `process.cwd()`, a `const` bound once to one of these, or a path builder over them.
|
|
8983
|
+
*/
|
|
8984
|
+
function isConstantPathArg(arg, b, depth = 0) {
|
|
8985
|
+
const a = arg.trim();
|
|
8986
|
+
if (depth > 4 || a === '')
|
|
8987
|
+
return false;
|
|
8988
|
+
const q = a.charAt(0);
|
|
8989
|
+
if ((q === "'" || q === '"') && a.length >= 2 && a.charAt(a.length - 1) === q && !a.slice(1, -1).includes(q))
|
|
8990
|
+
return true;
|
|
8991
|
+
if (q === '`' && a.length >= 2 && a.charAt(a.length - 1) === '`' && !a.slice(1, -1).includes('`') && !a.includes('${'))
|
|
8992
|
+
return true;
|
|
8993
|
+
if (a === '__dirname' || a === 'process.cwd()' || a === 'import.meta.dirname')
|
|
8994
|
+
return true;
|
|
8995
|
+
if (JS_IDENT.test(a)) {
|
|
8996
|
+
const init = b.constants.get(a);
|
|
8997
|
+
return init !== undefined && isConstantPathArg(init.replace(/;$/, ''), b, depth + 1);
|
|
8998
|
+
}
|
|
8999
|
+
const open = a.indexOf('(');
|
|
9000
|
+
if (open > 0 && closingParen(a, open) === a.length - 1 && pathCallKind(a.slice(0, open), b) === 'builder') {
|
|
9001
|
+
return callArguments(a, open, a.length - 1).every((x) => isConstantPathArg(x, b, depth + 1));
|
|
9002
|
+
}
|
|
9003
|
+
return false;
|
|
9004
|
+
}
|
|
9005
|
+
/** The start of the callee expression (`fs.readFileSync`, `path?.join`) that ends just before `open`. */
|
|
9006
|
+
function calleeStart(line, open) {
|
|
9007
|
+
let k = open;
|
|
9008
|
+
while (k > 0 && /\s/.test(line[k - 1]))
|
|
9009
|
+
k--;
|
|
9010
|
+
while (k > 0) {
|
|
9011
|
+
const ch = line[k - 1];
|
|
9012
|
+
if (/[\w$.]/.test(ch))
|
|
9013
|
+
k--;
|
|
9014
|
+
else if (ch === '?' && line[k] === '.')
|
|
9015
|
+
k--;
|
|
9016
|
+
else
|
|
9017
|
+
break;
|
|
9018
|
+
}
|
|
9019
|
+
return k;
|
|
9020
|
+
}
|
|
9021
|
+
/** The nearest unclosed `(` before `at`, or -1. */
|
|
9022
|
+
function enclosingOpenParen(line, at) {
|
|
9023
|
+
let depth = 0;
|
|
9024
|
+
for (let k = at - 1; k >= 0; k--) {
|
|
9025
|
+
const ch = line[k];
|
|
9026
|
+
if (ch === ')')
|
|
9027
|
+
depth++;
|
|
9028
|
+
else if (ch === '(') {
|
|
9029
|
+
if (depth === 0)
|
|
9030
|
+
return k;
|
|
9031
|
+
depth--;
|
|
9032
|
+
}
|
|
9033
|
+
}
|
|
9034
|
+
return -1;
|
|
9035
|
+
}
|
|
9036
|
+
/**
|
|
9037
|
+
* Whether every mention of `v` on `line` uses the value as is (#1416 review 1, re-reviews 2
|
|
9038
|
+
* and 3): a direct argument of a path builder or a path sink, and every call around it up
|
|
9039
|
+
* to the sink a path builder too (`fs.readFileSync(path.join(ROOT, name))`). A method call
|
|
9040
|
+
* on it (`name.replace(…)`), an argument of any other call (`decodeURIComponent(name)`, a
|
|
9041
|
+
* local `dec(name)`), any call around the builder (`decodeURIComponent(path.join(ROOT,
|
|
9042
|
+
* name))`, `path.join(ROOT, name).replace(…)`), an assignment or any other expression
|
|
9043
|
+
* around it is not as is. The other arguments of a builder (and of a two-path sink such as
|
|
9044
|
+
* `rename`) must be constant (`isConstantPathArg`) or another guarded value in `carriers`,
|
|
9045
|
+
* so `path.join(ROOT, name, other)` with a tainted `other` is not as is. A builder that is
|
|
9046
|
+
* not inside a sink may stand only as `const|let|var x = <builder>(…);`; its result `x` is
|
|
9047
|
+
* returned in `boundTo` for the caller to follow.
|
|
9048
|
+
*/
|
|
9049
|
+
function jsPathUse(line, v, b, carriers) {
|
|
9050
|
+
const esc = v.replace(/\$/g, '\\$');
|
|
9051
|
+
const ref = new RegExp(`(?<![\\w$.])${esc}(?![\\w$])`, 'g');
|
|
9052
|
+
const otherOk = (arg) => carriers.has(arg) || isConstantPathArg(arg, b);
|
|
9053
|
+
let m;
|
|
9054
|
+
let any = false;
|
|
9055
|
+
let boundTo;
|
|
9056
|
+
while ((m = ref.exec(line)) !== null) {
|
|
9057
|
+
any = true;
|
|
9058
|
+
// the expression that carries the value: the mention, then each builder call around it
|
|
9059
|
+
let start = m.index;
|
|
9060
|
+
let end = m.index + v.length;
|
|
9061
|
+
let builders = 0;
|
|
9062
|
+
for (;;) {
|
|
9063
|
+
const prev = line.slice(0, start).trimEnd().slice(-1);
|
|
9064
|
+
const next = line.slice(end).trimStart().charAt(0);
|
|
9065
|
+
if ((prev === '(' || prev === ',') && (next === ')' || next === ',')) {
|
|
9066
|
+
const open = enclosingOpenParen(line, start);
|
|
9067
|
+
if (open < 0)
|
|
9068
|
+
return { asIs: false };
|
|
9069
|
+
const kind = pathCallKind(line.slice(0, open), b);
|
|
9070
|
+
if (kind === undefined)
|
|
9071
|
+
return { asIs: false };
|
|
9072
|
+
const close = closingParen(line, open);
|
|
9073
|
+
if (close < 0)
|
|
9074
|
+
return { asIs: false };
|
|
9075
|
+
const args = callArguments(line, open, close);
|
|
9076
|
+
const mine = line.slice(start, end).trim();
|
|
9077
|
+
if (kind === 'sink') {
|
|
9078
|
+
const callee = trailingIdentifier(line.slice(0, open)) ?? '';
|
|
9079
|
+
if (JS_TWO_PATH_SINKS.has(callee) && !args.slice(0, 2).every((x) => x === mine || otherOk(x)))
|
|
9080
|
+
return { asIs: false };
|
|
9081
|
+
break; // the path is consumed here; what the sink returns is not a path
|
|
9082
|
+
}
|
|
9083
|
+
let own = false;
|
|
9084
|
+
for (const x of args) {
|
|
9085
|
+
if (!own && x === mine) {
|
|
9086
|
+
own = true;
|
|
9087
|
+
continue;
|
|
9088
|
+
}
|
|
9089
|
+
if (!otherOk(x))
|
|
9090
|
+
return { asIs: false };
|
|
9091
|
+
}
|
|
9092
|
+
start = calleeStart(line, open);
|
|
9093
|
+
end = close + 1;
|
|
9094
|
+
builders++;
|
|
9095
|
+
continue;
|
|
9096
|
+
}
|
|
9097
|
+
// not an argument: only a builder result bound on its own, `const x = <builder>(…);`
|
|
9098
|
+
if (builders === 0)
|
|
9099
|
+
return { asIs: false };
|
|
9100
|
+
const lhs = /^(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=$/.exec(line.slice(0, start).trim());
|
|
9101
|
+
const tail = line.slice(end).trim();
|
|
9102
|
+
if (!lhs || !(tail === '' || tail === ';' || tail.startsWith('//') || (tail.startsWith(';') && tail.slice(1).trim().startsWith('//')))) {
|
|
9103
|
+
return { asIs: false };
|
|
9104
|
+
}
|
|
9105
|
+
if (boundTo !== undefined && boundTo !== lhs[1])
|
|
9106
|
+
return { asIs: false };
|
|
9107
|
+
boundTo = lhs[1];
|
|
9108
|
+
break;
|
|
9109
|
+
}
|
|
9110
|
+
}
|
|
9111
|
+
return { asIs: any, boundTo };
|
|
9112
|
+
}
|
|
9113
|
+
/** `const|let|var x = <one of names>;` on its own: the alias name, or undefined. */
|
|
9114
|
+
function plainAliasOf(line, names) {
|
|
9115
|
+
const m = /^(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)(?:\s*;)?(?:\s*\/\/.*)?$/.exec(line.trim());
|
|
9116
|
+
if (!m)
|
|
9117
|
+
return undefined;
|
|
9118
|
+
for (const n of names)
|
|
9119
|
+
if (n === m[2])
|
|
9120
|
+
return m[1];
|
|
9121
|
+
return undefined;
|
|
9122
|
+
}
|
|
9123
|
+
/**
|
|
9124
|
+
* JS/TS: absolute-path + `..`-segment reject guard (cognium-dev#1305 E4).
|
|
9125
|
+
*
|
|
9126
|
+
* if (path.isAbsolute(name) || name.split(/[\\/]/).includes('..')) throw new Error('bad name');
|
|
9127
|
+
* const full = path.join(ROOT, name);
|
|
9128
|
+
* fs.readFileSync(full);
|
|
9129
|
+
*
|
|
9130
|
+
* A name that is not absolute and has no `..` segment, joined onto a root,
|
|
9131
|
+
* stays under that root — the two ways out are exactly the two rejected. BOTH
|
|
9132
|
+
* checks must be in one `||` condition on the same variable, and the guard must
|
|
9133
|
+
* reject (`guardRejects`, #333): either check alone leaves the other escape
|
|
9134
|
+
* open. The `..` check may be the substring test (`name.includes('..')`) or a
|
|
9135
|
+
* segment test that splits on BOTH separators (`name.split(/[\\/]/).includes('..')`):
|
|
9136
|
+
* `path.join` on Windows also splits on `\`, so a POSIX-only `split('/')` lets
|
|
9137
|
+
* `..\x` through and earns nothing. A negated check or an `&&` in the condition
|
|
9138
|
+
* is a different guard and earns nothing.
|
|
9139
|
+
*
|
|
9140
|
+
* Credits the guard line and every later line in the same block, until the
|
|
9141
|
+
* variable is reassigned (`jsGuardCreditLines`), where the variable is used as
|
|
9142
|
+
* is: a direct argument of a path builder or a path sink (`path.join(ROOT, name)`,
|
|
9143
|
+
* `fs.readFileSync(name)`). A line that decodes or rewrites it
|
|
9144
|
+
* (`decodeURIComponent(name)`, `name.replace(…)`, a local `dec(name)`, …) is not
|
|
9145
|
+
* credited: the guard checked the raw value, and `%2e%2e/` decodes to `../`
|
|
9146
|
+
* after it. Every call around the value up to the sink must be a path call too,
|
|
9147
|
+
* so `decodeURIComponent(path.join(ROOT, name))` is not credited, and a builder
|
|
9148
|
+
* counts only when it comes from `path` / `node:path`, so a local `normalize`
|
|
9149
|
+
* that decodes is not one. The other arguments of the builder must be constant
|
|
9150
|
+
* (`ROOT`, `'sub'`, `__dirname`): `path.join(ROOT, name, other)` is not credited.
|
|
9151
|
+
* A plain alias (`const safe = name`) and a builder's result (`const full =
|
|
9152
|
+
* path.join(ROOT, name)`) are followed, not credited: their later lines are
|
|
9153
|
+
* held to the same rule, so `decodeURIComponent(safe)` and
|
|
9154
|
+
* `decodeURIComponent(full)` still report. Only `path_traversal` is sanitized.
|
|
9155
|
+
*/
|
|
9156
|
+
function findJsAbsoluteDotDotGuardSanitizers(code) {
|
|
9157
|
+
const sanitizers = [];
|
|
9158
|
+
const lines = code.split('\n');
|
|
9159
|
+
const terminatorRe = /\b(?:throw|return|continue|res\s*\.\s*status\s*\([^)]*\)\s*\.\s*(?:send|end|json))/;
|
|
9160
|
+
// Matched against the condition with its whitespace removed.
|
|
9161
|
+
const absRe = /(?<![!\w$.])(?:(?:path|nodePath|Path)\.(?:(?:posix|win32)\.)?)?isAbsolute\(([A-Za-z_$][\w$]*)\)/;
|
|
9162
|
+
let bindings;
|
|
9163
|
+
for (let i = 0; i < lines.length; i++) {
|
|
9164
|
+
const open = /\bif\s*\(/.exec(lines[i]);
|
|
9165
|
+
if (!open)
|
|
9166
|
+
continue;
|
|
9167
|
+
// The condition: the balanced parens after `if`, on this line only.
|
|
9168
|
+
let depth = 0;
|
|
9169
|
+
let end = -1;
|
|
9170
|
+
for (let k = open.index + open[0].length - 1; k < lines[i].length; k++) {
|
|
9171
|
+
if (lines[i][k] === '(')
|
|
9172
|
+
depth++;
|
|
9173
|
+
else if (lines[i][k] === ')' && --depth === 0) {
|
|
9174
|
+
end = k;
|
|
9175
|
+
break;
|
|
9176
|
+
}
|
|
9177
|
+
}
|
|
9178
|
+
if (end < 0)
|
|
9179
|
+
continue;
|
|
9180
|
+
const cond = lines[i].slice(open.index + open[0].length, end).replace(/\s+/g, '');
|
|
9181
|
+
if (cond.includes('&&') || !cond.includes('||'))
|
|
9182
|
+
continue;
|
|
9183
|
+
const abs = absRe.exec(cond);
|
|
9184
|
+
if (!abs)
|
|
9185
|
+
continue;
|
|
9186
|
+
const v = abs[1];
|
|
9187
|
+
const esc = v.replace(/\$/g, '\\$');
|
|
9188
|
+
const dotDot = new RegExp(`(?<![!\\w$.])${esc}(?:\\.split\\(([^)]*)\\))?\\.includes\\((['"\`])\\.\\.\\2\\)`);
|
|
9189
|
+
const dd = dotDot.exec(cond);
|
|
9190
|
+
// a segment test must split on both separators (not POSIX-only); no split = the substring test
|
|
9191
|
+
if (!dd || (dd[1] !== undefined && !splitsOnBothSeparators(dd[1])))
|
|
9192
|
+
continue;
|
|
9193
|
+
if (!guardRejects(lines, i, terminatorRe, 4))
|
|
9194
|
+
continue;
|
|
9195
|
+
const pb = (bindings ??= jsPathBindings(lines));
|
|
9196
|
+
const range = jsGuardCreditLines(lines, i, v);
|
|
9197
|
+
const inRange = new Set(range);
|
|
9198
|
+
// the guarded value and its plain aliases, each with the lines it is live on
|
|
9199
|
+
const carriers = new Map([[v, inRange]]);
|
|
9200
|
+
const refRe = (n) => new RegExp(`(?<![\\w$.])${n.replace(/\$/g, '\\$')}(?![\\w$])`);
|
|
9201
|
+
for (const l of range) {
|
|
9202
|
+
const named = [...carriers].filter(([n, live]) => live.has(l) && refRe(n).test(lines[l]));
|
|
9203
|
+
if (named.length === 0)
|
|
9204
|
+
continue;
|
|
9205
|
+
if (l !== i) {
|
|
9206
|
+
const alias = plainAliasOf(lines[l], named.map(([n]) => n));
|
|
9207
|
+
if (alias !== undefined) {
|
|
9208
|
+
carriers.set(alias, new Set(jsGuardCreditLines(lines, l, alias).filter((x) => x > l && inRange.has(x))));
|
|
9209
|
+
continue;
|
|
9210
|
+
}
|
|
9211
|
+
const live = new Set(named.map(([n]) => n));
|
|
9212
|
+
const uses = named.map(([n]) => jsPathUse(lines[l], n, pb, live));
|
|
9213
|
+
if (!uses.every((u) => u.asIs))
|
|
9214
|
+
continue;
|
|
9215
|
+
const bound = new Set(uses.map((u) => u.boundTo));
|
|
9216
|
+
if (bound.size > 1)
|
|
9217
|
+
continue;
|
|
9218
|
+
const [result] = bound;
|
|
9219
|
+
if (result !== undefined) {
|
|
9220
|
+
// `const full = path.join(ROOT, name)`: followed like an alias, not credited on its own
|
|
9221
|
+
carriers.set(result, new Set(jsGuardCreditLines(lines, l, result).filter((x) => x > l && inRange.has(x))));
|
|
9222
|
+
continue;
|
|
9223
|
+
}
|
|
9224
|
+
}
|
|
9225
|
+
sanitizers.push({
|
|
9226
|
+
type: 'js_absolute_dotdot_guard',
|
|
9227
|
+
method: 'isAbsolute',
|
|
9228
|
+
line: l + 1,
|
|
9229
|
+
sanitizes: ['path_traversal'],
|
|
9230
|
+
});
|
|
9231
|
+
}
|
|
9232
|
+
}
|
|
9233
|
+
return sanitizers;
|
|
9234
|
+
}
|
|
9235
|
+
/**
|
|
9236
|
+
* JS/TS open_redirect: the same-site relative-path guard (CWE-601).
|
|
9237
|
+
*
|
|
9238
|
+
* if (!next.startsWith('/') || next.startsWith('//') || next.startsWith('/\\')) return res.redirect('/');
|
|
9239
|
+
* res.redirect(next);
|
|
9240
|
+
*
|
|
9241
|
+
* if (next.startsWith('/') && !next.startsWith('//') && !next.startsWith('/\\')) { res.redirect(next); }
|
|
9242
|
+
* if (/^\/(?![\/\\])/.test(next)) { res.redirect(next); }
|
|
9243
|
+
* res.redirect(next.startsWith('/') && !next.startsWith('//') && !next.startsWith('/\\') ? next : '/');
|
|
9244
|
+
*
|
|
9245
|
+
* A path that starts with one `/` and is not `//…` (protocol-relative) or `/\…` (which browsers read as
|
|
9246
|
+
* `//…`) stays on the same site, so the redirect cannot leave it. BOTH `//` and `/\` must be rejected: a guard
|
|
9247
|
+
* that only rejects `//` is still bypassable with `/\evil.example`, and is not credited. The reject form
|
|
9248
|
+
* (conditions joined by `||`, then a terminator) credits every later line that uses the variable; the accept
|
|
9249
|
+
* form (joined by `&&`, or one of the strict regex spellings) credits the lines of its block. Only
|
|
9250
|
+
* `open_redirect` is sanitized. Matching is by substring on the whitespace-free condition (no new regex).
|
|
9251
|
+
*/
|
|
9252
|
+
function findJsRelativeRedirectGuardSanitizers(code) {
|
|
9253
|
+
const sanitizers = [];
|
|
9254
|
+
if (!code.includes('startsWith') && !code.includes('.test('))
|
|
9255
|
+
return sanitizers;
|
|
9256
|
+
const lines = code.split('\n');
|
|
9257
|
+
const quotes = ["'", '"', '`'];
|
|
9258
|
+
const lit = (q, body) => `${q}${body}${q}`;
|
|
9259
|
+
const anyQ = (cond, f) => quotes.some((q) => cond.includes(f(q)));
|
|
9260
|
+
const strictRegexes = ['/^\\/(?![\\/\\\\])/.test(', '/^\\/(?!\\/|\\\\)/.test(', '/^\\/[^\\/\\\\]/.test('];
|
|
9261
|
+
const terminatorRe = /\b(?:throw|return|res\s*\.\s*status\s*\([^)]*\)\s*\.\s*(?:send|end|json))/;
|
|
9262
|
+
const varRefFor = (v) => new RegExp(`(?<![\\w$.])${v.replace(/[.$]/g, '\\$&')}(?![\\w$])`);
|
|
9263
|
+
for (let i = 0; i < lines.length; i++) {
|
|
9264
|
+
const raw = lines[i];
|
|
9265
|
+
const cond = raw.replace(/\s+/g, '');
|
|
9266
|
+
const isIf = /\bif\s*\(/.test(raw);
|
|
9267
|
+
// the ternary form on the redirect line itself: `res.redirect(<guard> ? next : '/')`
|
|
9268
|
+
if (!isIf && !(cond.includes('?') && cond.includes(':')))
|
|
9269
|
+
continue;
|
|
9270
|
+
// the guarded variable: the receiver of `.startsWith('//')`, or the argument of a strict regex's `.test(`
|
|
9271
|
+
let v;
|
|
9272
|
+
for (const q of quotes) {
|
|
9273
|
+
const at = cond.indexOf(`.startsWith(${lit(q, '//')})`);
|
|
9274
|
+
if (at > 0) {
|
|
9275
|
+
let k = at;
|
|
9276
|
+
while (k > 0 && /[\w$.]/.test(cond[k - 1]))
|
|
9277
|
+
k--;
|
|
9278
|
+
v = cond.slice(k, at).replace(/^!+/, '');
|
|
9279
|
+
break;
|
|
9280
|
+
}
|
|
9281
|
+
}
|
|
9282
|
+
const regexAccept = strictRegexes.find((r) => cond.includes(r));
|
|
9283
|
+
if (!v && regexAccept) {
|
|
9284
|
+
const after = cond.slice(cond.indexOf(regexAccept) + regexAccept.length);
|
|
9285
|
+
const m = /^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\)/.exec(after);
|
|
9286
|
+
v = m?.[1];
|
|
9287
|
+
}
|
|
9288
|
+
if (!v || !/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(v))
|
|
9289
|
+
continue;
|
|
9290
|
+
const slash = (q) => `${v}.startsWith(${lit(q, '/')})`;
|
|
9291
|
+
const dbl = (q) => `${v}.startsWith(${lit(q, '//')})`;
|
|
9292
|
+
const back = (q) => `${v}.startsWith(${lit(q, '/\\\\')})`;
|
|
9293
|
+
const reject = cond.includes('||') && !cond.includes('&&') &&
|
|
9294
|
+
anyQ(cond, (q) => `!${slash(q)}`) && anyQ(cond, dbl) && anyQ(cond, back) &&
|
|
9295
|
+
!anyQ(cond, (q) => `!${dbl(q)}`) && !anyQ(cond, (q) => `!${back(q)}`);
|
|
9296
|
+
const accept = (cond.includes('&&') && !cond.includes('||') &&
|
|
9297
|
+
anyQ(cond, slash) && !anyQ(cond, (q) => `!${slash(q)}`) &&
|
|
9298
|
+
anyQ(cond, (q) => `!${dbl(q)}`) && anyQ(cond, (q) => `!${back(q)}`)) ||
|
|
9299
|
+
(!!regexAccept && !cond.includes(`!${regexAccept}`) && !cond.includes('||'));
|
|
9300
|
+
const ref = varRefFor(v);
|
|
9301
|
+
if (!isIf) {
|
|
9302
|
+
// ternary: credited only when the guarded value is the consequent (`<guard> ? next : <fallback>`)
|
|
9303
|
+
if (accept && cond.includes(`?${v}:`))
|
|
9304
|
+
sanitizers.push({ type: 'js_relative_redirect_guard', method: 'startsWith', line: i + 1, sanitizes: ['open_redirect'] });
|
|
9305
|
+
continue;
|
|
9306
|
+
}
|
|
9307
|
+
if (reject && guardRejects(lines, i, terminatorRe, 2)) {
|
|
9308
|
+
// from the guard line itself, so a block-form guard's own `{ … }` is counted, not read as the function's end
|
|
9309
|
+
for (const l of jsGuardCreditLines(lines, i, v)) {
|
|
9310
|
+
if (ref.test(lines[l]))
|
|
9311
|
+
sanitizers.push({ type: 'js_relative_redirect_guard', method: 'startsWith', line: l + 1, sanitizes: ['open_redirect'] });
|
|
9312
|
+
}
|
|
9313
|
+
}
|
|
9314
|
+
else if (accept) {
|
|
9315
|
+
const block = jsBracedBlockLines(lines, i);
|
|
9316
|
+
const body = block ?? [raw];
|
|
9317
|
+
for (let k = 0; k < body.length; k++) {
|
|
9318
|
+
if (ref.test(k === 0 ? raw.slice(raw.indexOf(')', raw.indexOf('if')) + 1) : body[k])) {
|
|
9319
|
+
sanitizers.push({ type: 'js_relative_redirect_guard', method: 'startsWith', line: i + k + 1, sanitizes: ['open_redirect'] });
|
|
9320
|
+
}
|
|
9321
|
+
}
|
|
9322
|
+
}
|
|
9323
|
+
}
|
|
9324
|
+
return sanitizers;
|
|
9325
|
+
}
|
|
9326
|
+
/**
|
|
9327
|
+
* The lines a guard on `v` at line index `from` may credit: from `from` to the end of the block that encloses it
|
|
9328
|
+
* (the handler or function the guard is in: the first `}` that closes a brace opened before `from`), stopping
|
|
8117
9329
|
* before any reassignment of `v` (`v = …`, `v += …`, `let|const|var v = …`). Another handler in the same file, or the
|
|
8118
9330
|
* variable after it is reassigned, is never credited by this guard. Braces inside string literals and comments
|
|
8119
9331
|
* are not counted apart (a guard line with unbalanced quoted braces credits less, never more).
|
|
@@ -8538,8 +9750,8 @@ const JAVA_LITERAL_COLLECTION_IDENTS = new Set([
|
|
|
8538
9750
|
* file whose initializer is nothing but string literals inside the standard
|
|
8539
9751
|
* collection factories, and the guard must reject (throw / return). Credits
|
|
8540
9752
|
* `<v>` on later lines of the enclosing method until `<v>` is reassigned.
|
|
8541
|
-
* Scoped to `code_injection`
|
|
8542
|
-
* are untouched.
|
|
9753
|
+
* Scoped to reflective instantiation sinks (`code_injection`, `deserialization`);
|
|
9754
|
+
* other sink types are untouched.
|
|
8543
9755
|
*/
|
|
8544
9756
|
function findJavaReflectionAllowlistGuardSanitizers(code, types) {
|
|
8545
9757
|
const sanitizers = [];
|
|
@@ -8649,7 +9861,7 @@ function findJavaReflectionAllowlistGuardSanitizers(code, types) {
|
|
|
8649
9861
|
type: 'java_reflection_allowlist_guard',
|
|
8650
9862
|
method: 'contains',
|
|
8651
9863
|
line: l + 1,
|
|
8652
|
-
sanitizes: ['code_injection'],
|
|
9864
|
+
sanitizes: ['code_injection', 'deserialization'],
|
|
8653
9865
|
});
|
|
8654
9866
|
}
|
|
8655
9867
|
}
|
|
@@ -10751,6 +11963,31 @@ export function findJsVueVHtmlXssFindings(code, file) {
|
|
|
10751
11963
|
}
|
|
10752
11964
|
return out;
|
|
10753
11965
|
}
|
|
11966
|
+
/** #1381 — when a subscribe callback forwards a tainted param into `this.meth(arg)`, seed the callee's parameter name for Stage-7 XSS retention in other methods. */
|
|
11967
|
+
function seedJsCalleeParamsFromSubscribeForwarding(sourceCode, tainted) {
|
|
11968
|
+
const lines = sourceCode.split('\n');
|
|
11969
|
+
const THIS_FORWARD_RE = /\bthis\.(\w+)\s*\(\s*([^,)]+)\s*\)/g;
|
|
11970
|
+
for (let i = 0; i < lines.length; i++) {
|
|
11971
|
+
if (!/\.subscribe\s*\(/.test(lines[i]))
|
|
11972
|
+
continue;
|
|
11973
|
+
const window = lines.slice(i, Math.min(i + 10, lines.length)).join('\n');
|
|
11974
|
+
let m;
|
|
11975
|
+
THIS_FORWARD_RE.lastIndex = 0;
|
|
11976
|
+
while ((m = THIS_FORWARD_RE.exec(window)) !== null) {
|
|
11977
|
+
const methodName = m[1];
|
|
11978
|
+
const argExpr = m[2].trim();
|
|
11979
|
+
const argName = argExpr.replace(/[,):].*/, '').trim();
|
|
11980
|
+
if (!argName || !tainted.has(argName))
|
|
11981
|
+
continue;
|
|
11982
|
+
const paramRe = new RegExp(`\\b${methodName}\\s*\\(\\s*(?:[^:)]*?\\s+)?(\\w+)\\s*:`);
|
|
11983
|
+
const paramM = sourceCode.match(paramRe);
|
|
11984
|
+
const paramName = paramM?.[1];
|
|
11985
|
+
if (paramName && !tainted.has(paramName)) {
|
|
11986
|
+
tainted.set(paramName, i + 1);
|
|
11987
|
+
}
|
|
11988
|
+
}
|
|
11989
|
+
}
|
|
11990
|
+
}
|
|
10754
11991
|
/**
|
|
10755
11992
|
* Angular xss — `<recv>.bypassSecurityTrust(Html|Script|Url|ResourceUrl|
|
|
10756
11993
|
* Style)(<arg>)` where `<recv>` is typed `DomSanitizer`. Skip when
|
|
@@ -13248,6 +14485,181 @@ export function findRustLdapInjectionFindings(code, file) {
|
|
|
13248
14485
|
}
|
|
13249
14486
|
return findings;
|
|
13250
14487
|
}
|
|
14488
|
+
/** Identifier mention with word boundaries; avoids dynamic `RegExp` (regex-lint). */
|
|
14489
|
+
function exprMentionsIdent(expr, ident) {
|
|
14490
|
+
if (!ident)
|
|
14491
|
+
return false;
|
|
14492
|
+
let from = 0;
|
|
14493
|
+
for (;;) {
|
|
14494
|
+
const idx = expr.indexOf(ident, from);
|
|
14495
|
+
if (idx === -1)
|
|
14496
|
+
return false;
|
|
14497
|
+
const before = idx > 0 ? expr.charAt(idx - 1) : ' ';
|
|
14498
|
+
const after = expr.charAt(idx + ident.length);
|
|
14499
|
+
if (!/[A-Za-z0-9_]/.test(before) && !/[A-Za-z0-9_]/.test(after))
|
|
14500
|
+
return true;
|
|
14501
|
+
from = idx + 1;
|
|
14502
|
+
}
|
|
14503
|
+
}
|
|
14504
|
+
/**
|
|
14505
|
+
* flow-quartet tier-1 rust `format_string` (#1245): `HttpResponse::Ok().body(format!(...))`
|
|
14506
|
+
* with actix `web::Query` / path data in the macro arguments. Gates classify this as
|
|
14507
|
+
* CWE-134 (`format_string`), not only CWE-79 xss on `.body(...)`.
|
|
14508
|
+
*/
|
|
14509
|
+
export function findRustActixBodyFormatFormatStringSinks(code) {
|
|
14510
|
+
const sinks = [];
|
|
14511
|
+
if (typeof code !== 'string' || code.length === 0)
|
|
14512
|
+
return sinks;
|
|
14513
|
+
if (!/HttpResponse::\w+\(\)\s*\.\s*body\s*\(\s*format!\s*\(/.test(code)) {
|
|
14514
|
+
return sinks;
|
|
14515
|
+
}
|
|
14516
|
+
const lines = code.split('\n');
|
|
14517
|
+
const extractorTypeRe = /:\s*(?:String|Bytes|bytes::Bytes|axum::body::Bytes|web::Query\b|web::Path\b|web::Form\b|web::Json\b|HttpRequest\b|actix_web::HttpRequest\b)/;
|
|
14518
|
+
const httpGetRe = /\.get\s*\(\s*"[^"]+"\s*\)/;
|
|
14519
|
+
const fns = [];
|
|
14520
|
+
let cur = null;
|
|
14521
|
+
for (let i = 0; i < lines.length; i++) {
|
|
14522
|
+
const t = lines[i];
|
|
14523
|
+
if (/^\s*(?:pub\s+)?(?:async\s+)?fn\s+\w+\s*\(/.test(t)) {
|
|
14524
|
+
if (cur) {
|
|
14525
|
+
cur.end = i - 1;
|
|
14526
|
+
fns.push(cur);
|
|
14527
|
+
}
|
|
14528
|
+
cur = { start: i, end: lines.length - 1, tainted: new Set() };
|
|
14529
|
+
let headerJoined = '';
|
|
14530
|
+
for (let j = i; j < Math.min(i + 12, lines.length); j++) {
|
|
14531
|
+
headerJoined += lines[j];
|
|
14532
|
+
if (/\{\s*$/.test(lines[j]))
|
|
14533
|
+
break;
|
|
14534
|
+
}
|
|
14535
|
+
const open = headerJoined.indexOf('(');
|
|
14536
|
+
const close = headerJoined.lastIndexOf(')');
|
|
14537
|
+
if (open !== -1 && close > open) {
|
|
14538
|
+
const params = headerJoined.substring(open + 1, close);
|
|
14539
|
+
let depth = 0;
|
|
14540
|
+
let buf = '';
|
|
14541
|
+
const parts = [];
|
|
14542
|
+
for (const ch of params) {
|
|
14543
|
+
if (ch === '<' || ch === '(')
|
|
14544
|
+
depth++;
|
|
14545
|
+
else if (ch === '>' || ch === ')')
|
|
14546
|
+
depth--;
|
|
14547
|
+
if (ch === ',' && depth === 0) {
|
|
14548
|
+
parts.push(buf);
|
|
14549
|
+
buf = '';
|
|
14550
|
+
continue;
|
|
14551
|
+
}
|
|
14552
|
+
buf += ch;
|
|
14553
|
+
}
|
|
14554
|
+
if (buf.trim().length > 0)
|
|
14555
|
+
parts.push(buf);
|
|
14556
|
+
for (const p of parts) {
|
|
14557
|
+
const pm = p.match(/(?:mut\s+)?(\w+)\s*:/);
|
|
14558
|
+
if (!pm)
|
|
14559
|
+
continue;
|
|
14560
|
+
if (extractorTypeRe.test(p))
|
|
14561
|
+
cur.tainted.add(pm[1]);
|
|
14562
|
+
}
|
|
14563
|
+
}
|
|
14564
|
+
}
|
|
14565
|
+
}
|
|
14566
|
+
if (cur)
|
|
14567
|
+
fns.push(cur);
|
|
14568
|
+
const bodyFormatRe = /HttpResponse::\w+\(\)\s*\.\s*body\s*\(\s*format!\s*\(\s*([^)]+)\)\s*\)/;
|
|
14569
|
+
const splitFormatArgs = (argSpan) => {
|
|
14570
|
+
const parts = [];
|
|
14571
|
+
let d = 0;
|
|
14572
|
+
let b = '';
|
|
14573
|
+
let inStr = null;
|
|
14574
|
+
for (let k = 0; k < argSpan.length; k++) {
|
|
14575
|
+
const ch = argSpan[k];
|
|
14576
|
+
if (inStr) {
|
|
14577
|
+
if (ch === '\\') {
|
|
14578
|
+
b += ch + (argSpan[k + 1] ?? '');
|
|
14579
|
+
k++;
|
|
14580
|
+
continue;
|
|
14581
|
+
}
|
|
14582
|
+
if (ch === inStr)
|
|
14583
|
+
inStr = null;
|
|
14584
|
+
b += ch;
|
|
14585
|
+
continue;
|
|
14586
|
+
}
|
|
14587
|
+
if (ch === '"') {
|
|
14588
|
+
inStr = ch;
|
|
14589
|
+
b += ch;
|
|
14590
|
+
continue;
|
|
14591
|
+
}
|
|
14592
|
+
if (ch === '(' || ch === '[' || ch === '{')
|
|
14593
|
+
d++;
|
|
14594
|
+
else if (ch === ')' || ch === ']' || ch === '}')
|
|
14595
|
+
d--;
|
|
14596
|
+
if (ch === ',' && d === 0) {
|
|
14597
|
+
parts.push(b);
|
|
14598
|
+
b = '';
|
|
14599
|
+
continue;
|
|
14600
|
+
}
|
|
14601
|
+
b += ch;
|
|
14602
|
+
}
|
|
14603
|
+
if (b.trim().length > 0)
|
|
14604
|
+
parts.push(b);
|
|
14605
|
+
return parts;
|
|
14606
|
+
};
|
|
14607
|
+
for (const fn of fns) {
|
|
14608
|
+
for (let pass = 0; pass < 3; pass++) {
|
|
14609
|
+
const before = fn.tainted.size;
|
|
14610
|
+
for (let i = fn.start; i <= fn.end; i++) {
|
|
14611
|
+
const t = lines[i].trim();
|
|
14612
|
+
const letM = t.match(/^let\s+(?:mut\s+)?(\w+)\s*(?::\s*[^=]+)?=\s*(.+?);?$/);
|
|
14613
|
+
if (letM) {
|
|
14614
|
+
const lhs = letM[1];
|
|
14615
|
+
const rhs = letM[2];
|
|
14616
|
+
if (!fn.tainted.has(lhs)) {
|
|
14617
|
+
if (httpGetRe.test(rhs))
|
|
14618
|
+
fn.tainted.add(lhs);
|
|
14619
|
+
else {
|
|
14620
|
+
for (const v of fn.tainted) {
|
|
14621
|
+
if (exprMentionsIdent(rhs, v)) {
|
|
14622
|
+
fn.tainted.add(lhs);
|
|
14623
|
+
break;
|
|
14624
|
+
}
|
|
14625
|
+
}
|
|
14626
|
+
}
|
|
14627
|
+
}
|
|
14628
|
+
}
|
|
14629
|
+
}
|
|
14630
|
+
if (fn.tainted.size === before)
|
|
14631
|
+
break;
|
|
14632
|
+
}
|
|
14633
|
+
if (fn.tainted.size === 0)
|
|
14634
|
+
continue;
|
|
14635
|
+
for (let i = fn.start; i <= fn.end; i++) {
|
|
14636
|
+
const line = lines[i];
|
|
14637
|
+
const m = bodyFormatRe.exec(line);
|
|
14638
|
+
if (!m)
|
|
14639
|
+
continue;
|
|
14640
|
+
const argParts = splitFormatArgs(m[1]);
|
|
14641
|
+
if (argParts.length < 2)
|
|
14642
|
+
continue;
|
|
14643
|
+
let hit = false;
|
|
14644
|
+
for (let p = 1; p < argParts.length; p++) {
|
|
14645
|
+
for (const v of fn.tainted) {
|
|
14646
|
+
if (exprMentionsIdent(argParts[p], v)) {
|
|
14647
|
+
hit = true;
|
|
14648
|
+
break;
|
|
14649
|
+
}
|
|
14650
|
+
}
|
|
14651
|
+
if (hit)
|
|
14652
|
+
break;
|
|
14653
|
+
}
|
|
14654
|
+
if (!hit)
|
|
14655
|
+
continue;
|
|
14656
|
+
if (!sinks.some((s) => s.sinkLine === i + 1)) {
|
|
14657
|
+
sinks.push({ sinkLine: i + 1 });
|
|
14658
|
+
}
|
|
14659
|
+
}
|
|
14660
|
+
}
|
|
14661
|
+
return sinks;
|
|
14662
|
+
}
|
|
13251
14663
|
/**
|
|
13252
14664
|
* Sprint 87 detector D (#189) — Rust log injection via the `log` crate
|
|
13253
14665
|
* macros (`info!`, `warn!`, `error!`, `debug!`, `trace!`) where a
|
|
@@ -13576,6 +14988,22 @@ function maskJsLiteralsAndComments(code) {
|
|
|
13576
14988
|
}
|
|
13577
14989
|
return out.join('');
|
|
13578
14990
|
}
|
|
14991
|
+
/**
|
|
14992
|
+
* True when the call spanning `[start, end)` of masked line `i` is a whole
|
|
14993
|
+
* expression statement whose value is dropped: a statement starts right
|
|
14994
|
+
* before it (start of code, or after `;`, `{` or `}`) and `;` follows it.
|
|
14995
|
+
* Anything else (assignment, argument, `return`, chained access, a call
|
|
14996
|
+
* the line regex cut short at an inner `)`) is not treated as discarded.
|
|
14997
|
+
*/
|
|
14998
|
+
function isDiscardedJsCallStatement(codeLines, i, start, end) {
|
|
14999
|
+
if (!codeLines[i].slice(end).trimStart().startsWith(';'))
|
|
15000
|
+
return false;
|
|
15001
|
+
let before = codeLines[i].slice(0, start).trimEnd();
|
|
15002
|
+
for (let k = i - 1; before === '' && k >= 0; k--) {
|
|
15003
|
+
before = codeLines[k].trimEnd();
|
|
15004
|
+
}
|
|
15005
|
+
return before === '' || /[;{}]$/.test(before);
|
|
15006
|
+
}
|
|
13579
15007
|
/**
|
|
13580
15008
|
* Sprint 89 detector B (#189) — JS insecure deserialization via
|
|
13581
15009
|
* `JSON.parse(req.body)`.
|
|
@@ -13651,6 +15079,10 @@ export function findJsJsonParseBodyFindings(code, file) {
|
|
|
13651
15079
|
}
|
|
13652
15080
|
if (!tainted)
|
|
13653
15081
|
continue;
|
|
15082
|
+
// #1332: `JSON.parse(x);` on its own only checks the syntax; with
|
|
15083
|
+
// the result thrown away no parsed object reaches a property lookup.
|
|
15084
|
+
if (isDiscardedJsCallStatement(codeLines, i, m.index, m.index + m[0].length))
|
|
15085
|
+
continue;
|
|
13654
15086
|
if (seen.has(i + 1))
|
|
13655
15087
|
continue;
|
|
13656
15088
|
seen.add(i + 1);
|