t<\/b>/.test(out));
assert.match(out, /<script>alert\(1\)/);
});
+
+test('every rule links to an existing guide section', () => {
+ const { loadGuides, pickGuides } = require('../../core/guides');
+ const guides = loadGuides(path.join(__dirname, '..', '..', 'langs', 'php', 'guides'));
+ for (const r of RULES) assert.ok(guides.has(r.guide), `${r.id} -> ${r.guide}`);
+ for (const n of require('../../langs/php/notices')) assert.ok(guides.has(n.guide), `notice -> ${n.guide}`);
+ const picked = pickGuides(guides, ['injection#sql-injection']);
+ assert.match(picked['injection#sql-injection'].html, //);
+ assert.match(picked['injection#sql-injection'].html, /target="_blank" rel="noopener noreferrer"/);
+});
From a96727c548bf4f35cc8c382e5258a80bf6f4299e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tar=C4=B1k=20Seyceri?=
Date: Fri, 13 Nov 2026 18:07:01 +0300
Subject: [PATCH 06/12] feat(php): cross-file data flow and faster
large-project scans
- Includes are resolved and executed in the including scope, as PHP
does: __DIR__/__FILE__, dirname(), define()d paths and file names
chosen in a switch (several possible values) are followed, with
*_once tracking and depth limits.
- Functions, classes and methods are resolved across the project;
analysis results are shared between entry scripts, and findings in
shared helpers list the entry points that reach them.
- Structural rules run in a single pass with memoized name lookups;
DOM XSS checks focus on real browser sources and skip minified
bundles.
Benchmark: DVWA F1 96.3% (precision 100%), NIST SARD sample 66.5%,
WordPress core (1,512 PHP files) scanned in about 12 seconds.
Co-Authored-By: Claude Opus 5.5
---
CHANGELOG.md | 4 +-
bench/RESULTS.md | 30 ++--
bench/baseline-metrics.json | 6 +-
bench/lib/metrics.js | 2 +-
bench/lib/runner.js | 2 +-
bench/run.js | 3 +
core/taint/interpreter.js | 179 ++++++++++++++++---
core/taint/value.js | 38 +++-
langs/php/index.js | 45 +++--
langs/php/rules/ast-rules.js | 42 +++--
langs/php/rules/text-rules.js | 35 +++-
langs/php/taint/index.js | 74 +++++++-
langs/php/taint/lower.js | 6 +-
test/fixtures/php-crossfile/index.php | 7 +
test/fixtures/php-crossfile/levels/fixed.php | 2 +
test/fixtures/php-crossfile/levels/list.php | 2 +
test/fixtures/php-crossfile/lib/helpers.php | 13 ++
test/fixtures/php-crossfile/pages/home.php | 1 +
test/fixtures/php-crossfile/tools.php | 10 ++
test/fixtures/php-crossfile/view.php | 4 +
test/unit/php-fixtures.test.js | 13 ++
21 files changed, 431 insertions(+), 87 deletions(-)
create mode 100644 test/fixtures/php-crossfile/index.php
create mode 100644 test/fixtures/php-crossfile/levels/fixed.php
create mode 100644 test/fixtures/php-crossfile/levels/list.php
create mode 100644 test/fixtures/php-crossfile/lib/helpers.php
create mode 100644 test/fixtures/php-crossfile/pages/home.php
create mode 100644 test/fixtures/php-crossfile/tools.php
create mode 100644 test/fixtures/php-crossfile/view.php
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 13f96bf..161968a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ ASST 2.0 is a major upgrade built on the foundation of the original thesis relea
- Data-flow (taint) analysis for PHP. Every PHP file is parsed, and user input is followed from request sources to dangerous functions through variables, arrays, string building, `sprintf`, functions, methods and classes. Sanitizers and validation checks are understood per output context: SQL quoting, HTML text/attribute/script/URL, shell quoting, LDAP filters, XPath, file paths and URLs. Each finding shows the data-flow trace from source to sink.
- New detections: server-side request forgery, open redirect, path traversal, XPath injection, insecure deserialization, variable extraction (`extract`/`parse_str`), log and mail-header injection, code injection through `eval`/`assert`/`create_function`, unsafe dynamic calls, execution after redirect, weak password hashing, predictable random tokens, loose comparison of secrets, session fixation, hard-coded credentials, errors and `phpinfo()` shown to visitors, database error disclosure, DOM-based XSS and JavaScript `eval`, and version-control folders, backups, keys and dumps inside the web root.
- Remediation guides in Markdown (`langs/php/guides/`), one section per rule, written for current PHP 8 practice and the OWASP Top 10:2025. The relevant section is shown under each finding in the HTML report and used as rule help in SARIF.
+- Cross-file analysis: `include`/`require` targets are resolved (including `__DIR__`, `define()`d paths and file names chosen in a `switch`) and run in the including scope, and functions and classes are resolved across the whole project. A vulnerability inside a shared helper lists the entry scripts that reach it.
- Findings are mapped to the OWASP Top 10:2025 (with the 2021 category) and to CWE, and carry a severity, a confidence level and a code snippet.
- Interactive HTML report: one self-contained file that works offline, with severity tiles, search, filters (severity, confidence, OWASP category), grouping by category/file/rule, code snippets with the line highlighted, data-flow traces, dark mode and print layout. Content is fully HTML-escaped and protected by a strict Content-Security-Policy.
- SARIF 2.1.0 output (`--format sarif`) for GitHub code scanning and IDE viewers, with CWE/OWASP tags, security-severity scores, stable fingerprints and data-flow code flows.
@@ -33,7 +34,8 @@ ASST 2.0 is a major upgrade built on the foundation of the original thesis relea
- Redirect checks recognize every way a script stops (`exit;`, `die;`, `return`, `throw`).
- CSRF checks focus on POST forms and recognize framework token helpers.
- XML checks focus on the parser options that enable external entities on current PHP versions.
-- Benchmark results (see `bench/RESULTS.md`): on the NIST SARD PHP sample, F1 rises from 35.6% to 66.5% while scanning about 15 times faster; on DVWA, F1 rises from 84.6% to 88.0% with 100% precision.
+- Benchmark results (see `bench/RESULTS.md`): on the NIST SARD PHP sample, F1 rises from 35.6% to 66.5% while scanning about 15 times faster; on DVWA, F1 rises from 84.6% to 96.3% with 100% precision. WordPress core (1,500 PHP files) is scanned in about 12 seconds.
+- DOM-based XSS checks focus on real browser sources (URL, referrer, window name, cross-window messages) and skip minified third-party bundles.
- About 10x faster scans: the project tree is walked once and every file is read once per scan (NIST SARD sample: 97 s to 9 s; DVWA: 10 s to 1 s).
- Dependency folders (`vendor/`, `node_modules/`, `bower_components/`) and version-control folders are skipped by default.
- Paths are resolved relative to the ASST folder: ASST can be started from any directory, the folder may keep the name `ASST-main`, and `DEFAULT_PROJECT_PATH_TO_SCAN` accepts absolute paths on every operating system.
diff --git a/bench/RESULTS.md b/bench/RESULTS.md
index daa107d..69f2ca0 100644
--- a/bench/RESULTS.md
+++ b/bench/RESULTS.md
@@ -1,6 +1,6 @@
# ASST benchmark results
-Generated 2026-11-13T14:31:38.387Z on win32-x64, Node 22.23.5. Findings counted at confidence ≥ medium. Reproduce with `npm run bench`.
+Generated 2026-11-13T15:05:06.101Z on win32-x64, Node 22.23.5. Findings counted at confidence ≥ medium. Reproduce with `npm run bench`.
Precision = TP/(TP+FP), Recall = TP/(TP+FN), F1 = harmonic mean (percent).
@@ -8,8 +8,8 @@ Precision = TP/(TP+FP), Recall = TP/(TP+FN), F1 = harmonic mean (percent).
| Version | Precision | Recall | F1 | TP | FP | FN | Time (s) | Files/s | Peak RSS (MB) |
|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|
-| v1.0 (line-based engine) | 19.0 | 30.8 | 23.5 | 12 | 51 | 27 | 0.5 | 121 | 41 |
-| v2 (current branch) | 100.0 | 100.0 | 100.0 | 39 | 0 | 0 | 0.2 | 358 | 49 |
+| v1.0 (line-based engine) | 19.0 | 30.8 | 23.5 | 12 | 51 | 27 | 0.8 | 78 | 55 |
+| v2 (current branch) | 100.0 | 100.0 | 100.0 | 39 | 0 | 0 | 0.3 | 208 | 61 |
| CWE | v1.0 (line-based engine) P / R / F1 | v2 (current branch) P / R / F1 |
|---|---:|---:|
@@ -41,8 +41,8 @@ Precision = TP/(TP+FP), Recall = TP/(TP+FN), F1 = harmonic mean (percent).
| Version | Precision | Recall | F1 | TP | FP | FN | Time (s) | Files/s | Peak RSS (MB) |
|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|
-| v1.0 (line-based engine) | 41.2 | 41.2 | 41.2 | 7 | 10 | 10 | 0.1 | 136 | 42 |
-| v2 (current branch) | 100.0 | 100.0 | 100.0 | 17 | 0 | 0 | 0.2 | 106 | 45 |
+| v1.0 (line-based engine) | 41.2 | 41.2 | 41.2 | 7 | 10 | 10 | 0.2 | 104 | 54 |
+| v2 (current branch) | 100.0 | 100.0 | 100.0 | 17 | 0 | 0 | 0.2 | 90 | 57 |
| CWE | v1.0 (line-based engine) P / R / F1 | v2 (current branch) P / R / F1 |
|---|---:|---:|
@@ -63,15 +63,15 @@ Precision = TP/(TP+FP), Recall = TP/(TP+FN), F1 = harmonic mean (percent).
| Version | Precision | Recall | F1 | TP | FP | FN | Time (s) | Files/s | Peak RSS (MB) |
|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|
-| v1.0 (line-based engine) | 91.7 | 78.6 | 84.6 | 11 | 1 | 3 | 3.4 | 73 | 59 |
-| v2 (current branch) | 100.0 | 78.6 | 88.0 | 11 | 0 | 3 | 0.5 | 483 | 69 |
+| v1.0 (line-based engine) | 91.7 | 78.6 | 84.6 | 11 | 1 | 3 | 5.5 | 46 | 70 |
+| v2 (current branch) | 100.0 | 92.9 | 96.3 | 13 | 0 | 1 | 0.6 | 433 | 102 |
| CWE | v1.0 (line-based engine) P / R / F1 | v2 (current branch) P / R / F1 |
|---|---:|---:|
| CWE-78 | 75.0 / 100.0 / 85.7 | 100.0 / 100.0 / 100.0 |
-| CWE-79 | 100.0 / 100.0 / 100.0 | – / 0.0 / 0.0 |
+| CWE-79 | 100.0 / 100.0 / 100.0 | 100.0 / 100.0 / 100.0 |
| CWE-89 | 100.0 / 100.0 / 100.0 | 100.0 / 83.3 / 90.9 |
-| CWE-98 | 100.0 / 100.0 / 100.0 | – / 0.0 / 0.0 |
+| CWE-98 | 100.0 / 100.0 / 100.0 | 100.0 / 100.0 / 100.0 |
| CWE-601 | – / 0.0 / 0.0 | 100.0 / 100.0 / 100.0 |
## sard
@@ -80,8 +80,8 @@ Precision = TP/(TP+FP), Recall = TP/(TP+FN), F1 = harmonic mean (percent).
| Version | Precision | Recall | F1 | TP | FP | FN | Time (s) | Files/s | Peak RSS (MB) |
|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|
-| v1.0 (line-based engine) | 28.1 | 48.6 | 35.6 | 300 | 769 | 317 | 34.7 | 58 | 79 |
-| v2 (current branch) | 73.4 | 60.8 | 66.5 | 375 | 136 | 242 | 2.4 | 844 | 96 |
+| v1.0 (line-based engine) | 28.1 | 48.6 | 35.6 | 300 | 769 | 317 | 54.2 | 37 | 85 |
+| v2 (current branch) | 73.4 | 60.8 | 66.5 | 375 | 136 | 242 | 2.5 | 802 | 125 |
| CWE | v1.0 (line-based engine) P / R / F1 | v2 (current branch) P / R / F1 |
|---|---:|---:|
@@ -98,10 +98,18 @@ Precision = TP/(TP+FP), Recall = TP/(TP+FN), F1 = harmonic mean (percent).
| CWE-601 | – / 0.0 / 0.0 | 100.0 / 61.0 / 75.8 |
| CWE-862 | – / 0.0 / 0.0 | – / 0.0 / 0.0 |
+## wordpress
+
+| Version | Precision | Recall | F1 | TP | FP | FN | Time (s) | Files/s | Peak RSS (MB) |
+|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|
+| v2 (current branch) | – | – | – | – | – | – | 12.5 | 303 | 547 |
+
## Notes
- Fixtures: the annotated ASST fixture corpus (test/fixtures). It is also the regression suite, so high scores are expected there; DVWA and NIST SARD are the independent measures.
- DVWA: ground truth per module and security level in bench/truth/dvwa.json ("impossible" level = secure reference). Modules whose flaw spans several files are scored at module level.
- NIST SARD #103: scored per test-case file. The suite treats session data, files and command output as untrusted input, so the current engine runs with --second-order on this dataset. Labels are used exactly as published; a small number of generated cases sanitize a different variable than the one they use, which affects every tool equally.
+- WordPress core is used for throughput only (no ground truth); findings there are not scored.
+- Findings inside shared helper files are matched to every entry script that reaches them (the entry points listed in the report).
- v1.0 findings are mapped to CWE ids by the function or message each finding names.
diff --git a/bench/baseline-metrics.json b/bench/baseline-metrics.json
index 7f8c088..b7e1052 100644
--- a/bench/baseline-metrics.json
+++ b/bench/baseline-metrics.json
@@ -47,12 +47,12 @@
}
},
"dvwa": {
- "f1": 0.88,
+ "f1": 0.963,
"perCwe": {
"CWE-78": 1,
- "CWE-79": 0,
+ "CWE-79": 1,
"CWE-89": 0.9091,
- "CWE-98": 0,
+ "CWE-98": 1,
"CWE-601": 1
}
},
diff --git a/bench/lib/metrics.js b/bench/lib/metrics.js
index 90e8595..c6da649 100644
--- a/bench/lib/metrics.js
+++ b/bench/lib/metrics.js
@@ -103,7 +103,7 @@ function scoreFileLevel(cases, allFindings) {
let detected;
if (c.scope === 'dir') {
const prefix = c.file.endsWith('/') ? c.file : c.file + '/';
- detected = findings.some((f) => f.file.startsWith(prefix) && cwes.includes(f.cwe));
+ detected = findings.some((f) => cwes.includes(f.cwe) && (f.file.startsWith(prefix) || (f.entryPoints || []).some((e) => e.startsWith(prefix))));
} else {
const set = byFile.get(c.file);
detected = !!set && cwes.some((cwe) => set.has(cwe));
diff --git a/bench/lib/runner.js b/bench/lib/runner.js
index 86838cb..1d0d649 100644
--- a/bench/lib/runner.js
+++ b/bench/lib/runner.js
@@ -131,7 +131,7 @@ function scan(prepared, datasetDir, datasetName, opts = {}) {
const reportFile = path.join(runDir, 'report.json');
if (!fs.existsSync(reportFile)) throw new Error(`no report.json produced (exit ${stats.exitCode}): ${stats.stderr}`);
const report = JSON.parse(fs.readFileSync(reportFile, 'utf8'));
- const findings = report.findings.map((f) => ({ file: f.file, line: f.line ?? null, cwe: f.cwe, confidence: f.confidence || 'high', ruleId: f.ruleId }));
+ const findings = report.findings.map((f) => ({ file: f.file, line: f.line ?? null, cwe: f.cwe, confidence: f.confidence || 'high', ruleId: f.ruleId, entryPoints: f.entryPoints || [] }));
return { findings, stats, filesScanned: report.summary ? report.summary.filesScanned : null };
}
diff --git a/bench/run.js b/bench/run.js
index 7064cc5..325e6d4 100644
--- a/bench/run.js
+++ b/bench/run.js
@@ -127,6 +127,8 @@ const NOTES = [
'Fixtures: the annotated ASST fixture corpus (test/fixtures). It is also the regression suite, so high scores are expected there; DVWA and NIST SARD are the independent measures.',
'DVWA: ground truth per module and security level in bench/truth/dvwa.json ("impossible" level = secure reference). Modules whose flaw spans several files are scored at module level.',
'NIST SARD #103: scored per test-case file. The suite treats session data, files and command output as untrusted input, so the current engine runs with --second-order on this dataset. Labels are used exactly as published; a small number of generated cases sanitize a different variable than the one they use, which affects every tool equally.',
+ 'WordPress core is used for throughput only (no ground truth); findings there are not scored.',
+ 'Findings inside shared helper files are matched to every entry script that reaches them (the entry points listed in the report).',
'v1.0 findings are mapped to CWE ids by the function or message each finding names.',
];
@@ -171,6 +173,7 @@ async function main() {
const fileCount = walk(ds.dir).filter((f) => !f.startsWith('.git/')).length;
results.datasets[name] = { note: ds.note || null, fileCount, versions: {} };
for (const v of opts.versions) {
+ if (name === 'wordpress' && v === 'v1') continue; // throughput dataset: current engine only
log(`${name}: scanning with ${v} (${prepared[v].mode} engine)`);
const out = scan(prepared[v], ds.dir, name);
const findings = filterConfidence(out.findings, opts.minConfidence);
diff --git a/core/taint/interpreter.js b/core/taint/interpreter.js
index 09ccf8b..7326fb0 100644
--- a/core/taint/interpreter.js
+++ b/core/taint/interpreter.js
@@ -30,12 +30,16 @@ class Env {
this.out = out || contexts.initialHtmlState();
this.bottom = false;
this.globals = null; // Set of names bound to the main environment
+ this.included = null; // files already included (for *_once)
+ this.haltKind = null; // 'exit' | 'return'
}
clone() {
const e = new Env(new Map(this.vars), { ...this.out });
e.bottom = this.bottom;
e.globals = this.globals ? new Set(this.globals) : null;
+ e.included = this.included ? new Set(this.included) : null;
+ e.haltKind = this.haltKind;
return e;
}
@@ -47,12 +51,15 @@ class Env {
this.out = { ...other.out };
this.bottom = false;
this.globals = other.globals ? new Set(other.globals) : null;
+ this.included = other.included ? new Set(other.included) : null;
+ this.haltKind = null;
return this;
}
for (const [k, v] of other.vars) this.vars.set(k, this.vars.has(k) ? V.join(this.vars.get(k), v) : v);
for (const [k, v] of this.vars) if (!other.vars.has(k)) this.vars.set(k, v);
if (JSON.stringify(this.out) !== JSON.stringify(other.out)) this.out = contexts.initialHtmlState();
if (other.globals) this.globals = new Set([...(this.globals || []), ...other.globals]);
+ if (other.included) this.included = new Set([...(this.included || []), ...other.included]);
return this;
}
@@ -89,20 +96,32 @@ class Interpreter {
this.p = program;
this.cat = catalog;
this.opts = options;
- this.hits = new Map();
+ const shared = options.shared || {};
+ this.hits = shared.hits || new Map();
+ this.memo = shared.memo || new Map();
+ this.analyzed = shared.analyzed || new Set();
+ this.hitLog = [];
+ this.project = options.project || null;
+ this.entry = program.file;
+ this.constants = new Map();
+ this.includeCount = 0;
this.depth = 0;
this.budget = options.budget || 400000;
- this.memo = new Map();
- this.analyzed = new Set();
this.mainEnv = null;
this.exhausted = false;
}
- run() {
+ run({ standalone = true } = {}) {
const env = new Env();
this.mainEnv = env;
- this.execBlock(this.p.main, env, { fn: null });
- for (const fn of this.p.allFunctions) {
+ this.execBlock(this.p.main, env, { fn: null, file: this.p.file });
+ if (standalone) this.analyzeRemaining(this.p.allFunctions);
+ return { hits: [...this.hits.values()], exhausted: this.exhausted };
+ }
+
+ /** Analyzes functions that were never called, with untainted (or assumed-tainted) parameters. */
+ analyzeRemaining(functions) {
+ for (const fn of functions) {
if (this.analyzed.has(fn)) continue;
const args = this.opts.assumeParamsTainted
? fn.params.map((p) => V.source('src', `parameter $${p.name}`, fn.line, 2))
@@ -110,7 +129,6 @@ class Interpreter {
const thisVal = fn.cls ? this.newObjectValue(fn.cls, false) : null;
this.invoke(fn, args, [], thisVal, fn.line);
}
- return { hits: [...this.hits.values()], exhausted: this.exhausted };
}
tick() {
@@ -220,11 +238,13 @@ class Interpreter {
this.recordExit(env, f);
}
env.bottom = true;
+ env.haltKind = f.fn ? 'return' : 'top-return';
break;
}
case 'halt':
if (f.fn) this.recordExit(env, f);
env.bottom = true;
+ env.haltKind = 'exit';
break;
case 'global':
env.globals = env.globals || new Set();
@@ -246,6 +266,8 @@ class Interpreter {
env.out = other.out;
env.bottom = other.bottom;
env.globals = other.globals;
+ env.included = other.included;
+ env.haltKind = other.haltKind;
}
recordExit(env, f) {
@@ -434,7 +456,16 @@ class Interpreter {
if (typeof e.value === 'string') return V.constant(e.value);
return V.CLEAN;
case 'const':
+ if (this.constants.has(e.name)) return this.constants.get(e.name);
return this.cat.constant ? this.cat.constant(e.name) : V.CLEAN;
+ case 'magic': {
+ const file = f.file || this.p.file || '';
+ const dir = file.includes('/') ? file.slice(0, file.lastIndexOf('/')) : '';
+ if (e.name === '__DIR__') return V.constant(dir ? `/${dir}` : '');
+ if (e.name === '__FILE__') return V.constant(`/${file}`);
+ if (e.name === '__LINE__') return { t: false, num: true };
+ return V.constant(e.name);
+ }
case 'path':
if (e.base === 'this' && f.fn && !env.vars.has('this')) return V.CLEAN;
return this.read(e, env, f);
@@ -514,7 +545,7 @@ class Interpreter {
}
newObjectValue(cls, runConstructor, args = [], env = null, f = null, line = 0) {
- const def = this.p.classes.get(String(cls).toLowerCase());
+ const def = this.findClass(cls);
const fields = new Map();
let obj = { t: false, obj: { cls: def ? def.name : cls, fields } };
if (def) {
@@ -539,11 +570,36 @@ class Interpreter {
while (cur && !seen.has(cur.name)) {
chain.push(cur);
seen.add(cur.name);
- cur = cur.parent ? this.p.classes.get(cur.parent.toLowerCase()) : null;
+ cur = cur.parent ? this.findClass(cur.parent) : null;
}
return chain;
}
+ findClass(name) {
+ const lc = String(name || '').toLowerCase();
+ if (this.p.classes.has(lc)) return this.p.classes.get(lc);
+ if (this.project) {
+ const list = this.project.classes.get(lc);
+ if (list && list.length === 1) return list[0];
+ }
+ return null;
+ }
+
+ findFunction(lcName) {
+ if (this.p.functions.has(lcName)) return this.p.functions.get(lcName);
+ if (this.project) {
+ const list = this.project.functions.get(lcName);
+ if (list && list.length === 1) return list[0];
+ }
+ return null;
+ }
+
+ methodsNamed(lcName) {
+ const own = this.p.methodsByName.get(lcName) || [];
+ if (!this.project) return own;
+ return this.project.methodsByName.get(lcName) || own;
+ }
+
findMethod(def, lcName) {
for (const c of this.classChain(def)) if (c.methods.has(lcName)) return c.methods.get(lcName);
return null;
@@ -552,12 +608,64 @@ class Interpreter {
evalNew(e, env, f) {
const args = (e.args || []).map((a) => this.eval(a, env, f));
const cls = e.cls;
- if (cls && this.p.classes.has(cls.toLowerCase())) return this.newObjectValue(cls, true, args, env, f, e.line);
+ if (cls && this.findClass(cls)) return this.newObjectValue(cls, true, args, env, f, e.line);
const hit = this.cat.call ? this.cat.call(`new:${String(cls || '').toLowerCase()}`, args, e, this.ctxApi(env, f)) : null;
if (hit) return this.applyCatalogResult(hit, e, args, env, f);
return { t: false, obj: { cls: cls || null, fields: new Map() } };
}
+ /** Resolves an include path (as PHP would) to a file of the project, or null. */
+ resolveInclude(candidate, currentFile) {
+ if (!this.project || typeof candidate !== 'string' || candidate.includes('<') || /^[a-z]+:\/\//i.test(candidate)) return null;
+ const posix = require('path').posix;
+ const dirOf = (file) => (file && file.includes('/') ? file.slice(0, file.lastIndexOf('/')) : '');
+ const tries = [];
+ if (candidate.startsWith('/')) tries.push(candidate.replace(/^\/+/, ''));
+ else {
+ tries.push(posix.join(dirOf(this.entry), candidate));
+ tries.push(posix.join(dirOf(currentFile), candidate));
+ tries.push(candidate);
+ }
+ for (const t of tries) {
+ const norm = posix.normalize(t).replace(/^\.\//, '');
+ if (!norm.startsWith('..') && this.project.programs.has(norm)) return norm;
+ }
+ return null;
+ }
+
+ /** Runs an included file in the including scope (PHP semantics). */
+ executeInclude(target, e, env, f) {
+ if (!this.project || !target) return;
+ const depth = f.includeDepth || 0;
+ if (depth >= 4 || this.includeCount >= 60) return;
+ const candidates = V.alternatives(target);
+ if (!candidates) return;
+ const files = [];
+ for (const c of candidates) {
+ const rel = this.resolveInclude(c, f.file || this.entry);
+ if (!rel || files.includes(rel)) continue;
+ if (e.once && env.included && env.included.has(rel)) continue;
+ if ((f.including || []).includes(rel) || rel === (f.file || this.entry)) continue;
+ files.push(rel);
+ }
+ if (files.length === 0) return;
+ const branches = files.map((rel) => {
+ const branch = files.length > 1 ? env.clone() : env;
+ branch.included = new Set([...(branch.included || []), rel]);
+ const sub = { ...f, file: rel, includeDepth: depth + 1, including: [...(f.including || []), rel] };
+ this.includeCount++;
+ this.execBlock(this.project.programs.get(rel).main, branch, sub);
+ if (branch.bottom && branch.haltKind === 'top-return') { branch.bottom = false; branch.haltKind = null; }
+ return branch;
+ });
+ if (files.length > 1) {
+ const merged = branches[0];
+ for (const b of branches.slice(1)) merged.joinFrom(b);
+ this.replace(env, merged);
+ env.included = merged.included;
+ }
+ }
+
ctxApi(env, f) {
return {
env,
@@ -584,6 +692,20 @@ class Interpreter {
return res.ret ? V.step(res.ret, e.line, `returned by ${user.fn.name}()`) : V.CLEAN;
}
+ if (callee === 'fn:define' && args[0] && args[0].str !== undefined) {
+ this.constants.set(args[0].str, args[1] || V.CLEAN);
+ return V.CLEAN;
+ }
+ if (callee === 'fn:dirname' && args[0]) {
+ const alts = V.alternatives(args[0]);
+ if (alts && alts.length === 1) return V.constant(alts[0].includes('/') ? alts[0].slice(0, alts[0].lastIndexOf('/')) || '/' : '.');
+ }
+ if (callee === '@include') {
+ const hit = this.cat.call ? this.cat.call(callee, args, e, this.ctxApi(env, f)) : null;
+ if (hit) this.applyCatalogResult(hit, e, args, env, f);
+ this.executeInclude(args[0], e, env, f);
+ return V.CLEAN;
+ }
if (callee === '@inline') {
const text = argExprs[0] && argExprs[0].value !== undefined ? String(argExprs[0].value) : '';
env.out = contexts.htmlScan({ ...env.out }, text);
@@ -613,7 +735,7 @@ class Interpreter {
resolveUser(e, env, f) {
const callee = e.callee || '';
if (callee.startsWith('fn:')) {
- const fn = this.p.functions.get(callee.slice(3).replace(/^\\/, '').split('\\').pop());
+ const fn = this.findFunction(callee.slice(3).replace(/^\\/, '').split('\\').pop());
return fn ? { fn, thisVal: null } : null;
}
if (callee.startsWith('m:') && e.recv) {
@@ -621,11 +743,11 @@ class Interpreter {
const recv = this.eval(e.recv, env, f);
let fn = null;
if (recv.obj && recv.obj.cls) {
- const def = this.p.classes.get(String(recv.obj.cls).toLowerCase());
+ const def = this.findClass(recv.obj.cls);
if (def) fn = this.findMethod(def, name);
}
if (!fn) {
- const candidates = this.p.methodsByName.get(name) || [];
+ const candidates = this.methodsNamed(name);
if (candidates.length === 1 && !(this.cat.isKnownMethod && this.cat.isKnownMethod(name))) fn = candidates[0];
}
if (!fn) return null;
@@ -635,11 +757,11 @@ class Interpreter {
if (callee.startsWith('sm:')) {
const [cls, name] = callee.slice(3).split('::');
let def = null;
- if (['self', 'static'].includes(cls) && f.fn && f.fn.cls) def = this.p.classes.get(f.fn.cls.toLowerCase());
+ if (['self', 'static'].includes(cls) && f.fn && f.fn.cls) def = this.findClass(f.fn.cls);
else if (cls === 'parent' && f.fn && f.fn.cls) {
- const own = this.p.classes.get(f.fn.cls.toLowerCase());
- def = own && own.parent ? this.p.classes.get(own.parent.toLowerCase()) : null;
- } else def = this.p.classes.get(cls);
+ const own = this.findClass(f.fn.cls);
+ def = own && own.parent ? this.findClass(own.parent) : null;
+ } else def = this.findClass(cls);
const fn = def ? this.findMethod(def, name) : null;
if (!fn) return null;
const thisVal = env.vars.get('this') || null;
@@ -656,17 +778,23 @@ class Interpreter {
};
if (this.depth >= MAX_DEPTH || this.exhausted) return fallback();
const key = `${fn.id}#${signature(args)}#${signature([thisVal])}`;
- if (this.memo.has(key)) return this.memo.get(key);
+ if (this.memo.has(key)) {
+ const cached = this.memo.get(key);
+ // findings produced inside this function are reachable from the current entry point too
+ for (const k of cached.hitKeys || []) { const h = this.hits.get(k); if (h) h.entries.add(this.entry); }
+ return cached;
+ }
this.memo.set(key, fallback()); // recursion guard
+ const logStart = this.hitLog.length;
const env = new Env();
fn.params.forEach((p, i) => {
let v = args[i];
if (p.variadic) v = V.joinAll(args.slice(i));
- if (v === undefined) v = p.def ? this.eval(p.def, env, { fn }) : V.CLEAN;
+ if (v === undefined) v = p.def ? this.eval(p.def, env, { fn, file: fn.file }) : V.CLEAN;
env.vars.set(p.name, v && v.t ? V.step(v, line, `passed to ${fn.name}() as $${p.name}`) : v);
});
if (thisVal) env.vars.set('this', thisVal);
- const f = { fn, ret: null, thisOut: null, byRefParams: fn.params.filter((p) => p.byRef).map((p) => p.name), byRefOut: new Map() };
+ const f = { fn, file: fn.file || this.p.file, ret: null, thisOut: null, byRefParams: fn.params.filter((p) => p.byRef).map((p) => p.name), byRefOut: new Map() };
this.depth++;
try {
this.execBlock(fn.body, env, f);
@@ -674,14 +802,14 @@ class Interpreter {
this.depth--;
}
if (!env.bottom) this.recordExit(env, f);
- const result = { ret: f.ret || V.CLEAN, thisOut: f.thisOut || thisVal, byRefOut: f.byRefOut };
+ const result = { ret: f.ret || V.CLEAN, thisOut: f.thisOut || thisVal, byRefOut: f.byRefOut, hitKeys: this.hitLog.slice(logStart) };
this.memo.set(key, result);
return result;
}
/* ---------------------------------------------------------------- sinks */
- checkSink(sink, e, args, env) {
+ checkSink(sink, e, args, env, f = {}) {
let value;
if (sink.value) value = sink.value;
else if (sink.arg === 'all') value = V.concat(args);
@@ -703,10 +831,15 @@ class Interpreter {
const v = u.v;
if (!v.origins || !v.origins.some((o) => o === 'src' || o === 'src2')) continue;
const conf = Math.min(2, (v.c || 0) + (v.g ? 2 : 0) + (sink.confPenalty || 0));
- const key = `${sink.rule}|${e.line}|${e.col || 0}`;
+ const file = f.file || this.p.file;
+ const key = `${file}|${sink.rule}|${e.line}|${e.col || 0}`;
const prev = this.hits.get(key);
+ this.hitLog.push(key);
+ if (prev) prev.entries.add(this.entry);
if (prev && prev.conf <= conf && prev.trace.length <= (v.trace || []).length) continue;
this.hits.set(key, {
+ file,
+ entries: prev ? prev.entries : new Set([this.entry]),
rule: sink.rule,
line: e.line,
col: e.col || null,
diff --git a/core/taint/value.js b/core/taint/value.js
index 97abc50..6f4ffad 100644
--- a/core/taint/value.js
+++ b/core/taint/value.js
@@ -85,6 +85,10 @@ function join(a, b) {
} else {
out = { t: false };
if (a.str !== undefined && a.str === b.str) out.str = a.str;
+ else {
+ const set = unionAlternatives(alternatives(a), alternatives(b));
+ if (set) out.strs = set;
+ }
}
if (a.arr || b.arr) out.arr = joinMaps(a.arr, b.arr);
if (a.obj || b.obj) {
@@ -95,6 +99,23 @@ function join(a, b) {
return out;
}
+const MAX_ALTERNATIVES = 8;
+
+/** Possible constant string values of an untainted value, or null when unknown. */
+function alternatives(v) {
+ if (!v || v.t) return null;
+ if (v.str !== undefined) return [v.str];
+ if (v.strs) return v.strs;
+ if (v.num && v.str === undefined) return null;
+ return null;
+}
+
+function unionAlternatives(a, b) {
+ if (!a || !b) return null;
+ const set = [...new Set([...a, ...b])];
+ return set.length <= MAX_ALTERNATIVES ? set : null;
+}
+
function joinMaps(a, b) {
const out = new Map(a || []);
for (const [k, v] of b || []) out.set(k, out.has(k) ? join(out.get(k), v) : v);
@@ -142,7 +163,20 @@ function concat(values) {
segs.push({ text: '' }); // unknown untainted text (e.g. a number or unknown clean value)
}
}
- if (!anyTaint) return allConst ? constant(constText) : CLEAN;
+ if (!anyTaint) {
+ if (allConst) return constant(constText);
+ // several possible constant strings (e.g. a file name chosen in a switch)
+ let combos = [''];
+ for (const v of values) {
+ const alts = alternatives(v);
+ if (!alts) return CLEAN;
+ const next = [];
+ for (const c of combos) for (const a of alts) next.push(c + a);
+ if (next.length > MAX_ALTERNATIVES) return CLEAN;
+ combos = next;
+ }
+ return combos.length === 1 ? constant(combos[0]) : { t: false, strs: combos };
+ }
const tainted = segs.filter((s) => s.v).map((s) => s.v);
const base = joinAll(tainted);
const merged = mergeTextSegs(segs);
@@ -217,5 +251,5 @@ function within(v, chars) {
module.exports = {
CLEAN, constant, source, isTainted, join, joinAll, joinMaps, step, weaken, concat, segmentsOf,
- sanitize, excludes, within, unionChars, MAX_TRACE,
+ sanitize, excludes, within, unionChars, MAX_TRACE, alternatives,
};
diff --git a/langs/php/index.js b/langs/php/index.js
index a243e28..3222799 100644
--- a/langs/php/index.js
+++ b/langs/php/index.js
@@ -9,7 +9,7 @@
* runtime -> PHP/libxml versions, database password storage and version
*/
const path = require('path');
-const { analyzeFile } = require('./taint');
+const { analyzeProject } = require('./taint');
const { runAstRules } = require('./rules/ast-rules');
const textRules = require('./rules/text-rules');
const projectRules = require('./rules/project-rules');
@@ -126,6 +126,7 @@ module.exports = {
if (!config.quiet) console.log(ansi.paint(`Scanning ${project.files.length} files in ${project.root}`, 'cyan'));
+ const phpFiles = [];
for (const file of project.files) {
const isPhp = EXTENSIONS.includes(file.ext);
const needsText = isPhp || textRules.TEMPLATE_EXT.has(file.ext) || ['js', 'mjs', 'cjs', 'css'].includes(file.ext);
@@ -134,28 +135,36 @@ module.exports = {
if (text === null) continue;
const lines = cache.lines(file.abs);
stats.filesAnalyzed++;
- if (isPhp) {
- const res = analyzeFile(text, file.rel, options);
- stats.parse[res.status === 'failed' ? 'failed' : res.status]++;
- for (const hit of res.hits) {
- const meta = rule(hit.rule);
- raw.push(makeFinding(hit.rule, {
- file: file.rel, line: hit.line, column: hit.col, confidence: CONF[hit.conf] || 'low',
- message: taintMessage(meta, hit), trace: hit.trace,
- }, ctx));
- }
- if (res.ast) {
- for (const h of runAstRules(res.ast)) raw.push(makeFinding(h.ruleId, { ...h, file: file.rel }, ctx));
- } else {
- parseFailures.push(`${file.rel} (${res.error})`);
- for (const h of textRules.phpFallback(lines)) raw.push(makeFinding(h.ruleId, { ...h, file: file.rel }, ctx));
- }
- }
+ if (isPhp) phpFiles.push({ rel: file.rel, text });
for (const h of textRules.csrfForms(file, text)) raw.push(makeFinding(h.ruleId, { ...h, file: file.rel }, ctx));
for (const h of textRules.domRules(file, text)) raw.push(makeFinding(h.ruleId, { ...h, file: file.rel }, ctx));
for (const h of textRules.httpUrls(file, lines)) raw.push(makeFinding(h.ruleId, { ...h, file: file.rel, confidence: 'medium' }, ctx));
}
+ // PHP: parse every file once, run the structural rules, then follow data across the project
+ const taint = analyzeProject(phpFiles, options, (rel, ast, parsed) => {
+ stats.parse[parsed.status === 'failed' ? 'failed' : parsed.status]++;
+ if (ast) {
+ for (const h of runAstRules(ast)) raw.push(makeFinding(h.ruleId, { ...h, file: rel }, ctx));
+ } else {
+ parseFailures.push(`${rel} (${parsed.error})`);
+ for (const h of textRules.phpFallback(cache.lines(path.join(project.root, rel)) || [])) raw.push(makeFinding(h.ruleId, { ...h, file: rel }, ctx));
+ }
+ });
+ for (const hit of taint.hits) {
+ const meta = rule(hit.rule);
+ const finding = makeFinding(hit.rule, {
+ file: hit.file, line: hit.line, column: hit.col, confidence: CONF[hit.conf] || 'low',
+ message: taintMessage(meta, hit), trace: hit.trace,
+ }, ctx);
+ if (hit.entries && hit.entries.length) {
+ finding.entryPoints = hit.entries.slice(0, 200);
+ finding.message += ` Reached from ${hit.entries.slice(0, 3).join(', ')}${hit.entries.length > 3 ? ` and ${hit.entries.length - 3} more` : ''}.`;
+ }
+ raw.push(finding);
+ }
+ if (taint.exhausted) notices.add('info', `The analysis budget was reached for ${taint.exhausted} entry file(s); results for them may be incomplete.`);
+
const usesPhp = project.files.some((f) => EXTENSIONS.includes(f.ext));
for (const h of projectRules.exposedFiles(project)) raw.push(makeFinding(h.ruleId, h, ctx));
for (const h of projectRules.htaccessRules(project, { usesPhp })) raw.push(makeFinding(h.ruleId, h, ctx));
diff --git a/langs/php/rules/ast-rules.js b/langs/php/rules/ast-rules.js
index 433e8bf..68fad07 100644
--- a/langs/php/rules/ast-rules.js
+++ b/langs/php/rules/ast-rules.js
@@ -38,8 +38,18 @@ function callName(n) {
return null;
}
+const namesCache = new WeakMap();
+
/** Names mentioned in a subtree: variables, array string keys, properties, constants. */
function names(n) {
+ if (!isNode(n)) return [];
+ if (namesCache.has(n)) return namesCache.get(n);
+ const out = computeNames(n);
+ namesCache.set(n, out);
+ return out;
+}
+
+function computeNames(n) {
const out = [];
walk(n, (x) => {
if (x.kind === 'variable' && typeof x.name === 'string') out.push(x.name);
@@ -166,9 +176,9 @@ const TOKEN_RE = /token|secret|nonce|csrf|salt|reset|otp|verif|activation|api_?k
const WEAK_RANDOM = new Set(['rand', 'mt_rand', 'uniqid', 'lcg_value', 'microtime', 'array_rand', 'str_shuffle', 'mt_srand', 'srand']);
const SECRET_CMP_RE = /^(.*_)?(token|csrf\w*|hash|hashed\w*|signature|sig|hmac|secret|password|passwd|pwd|api_?key|nonce|otp|digest)(_\w*)?$/i;
-function cryptoRules(ast) {
+function cryptoRules(nodes) {
const hits = [];
- walk(ast, (n) => {
+ nodes.forEach((n) => {
if (n.kind === 'call') {
const name = callName(n);
const args = n.arguments || [];
@@ -206,11 +216,11 @@ function cryptoRules(ast) {
const SESSION_KEY_RE = /user|uid|login|logged|auth|admin|role|member|account|^id$/i;
-function sessionFixationRule(ast) {
+function sessionFixationRule(nodes) {
let checksPassword = false;
let regenerates = false;
const assignments = [];
- walk(ast, (n) => {
+ nodes.forEach((n) => {
if (n.kind === 'call') {
const name = callName(n);
if (name === 'password_verify' || name === 'ldap_bind' || name === 'crypt') checksPassword = true;
@@ -233,9 +243,9 @@ const TRUTHY = /^(1|on|true|yes|stdout|stderr)$/i;
const DB_ERROR_FNS = new Set(['mysqli_error', 'mysql_error', 'pg_last_error', 'pg_result_error', 'sqlsrv_errors', 'oci_error', 'db2_stmt_errormsg', 'odbc_errormsg', 'mysqli_connect_error', 'mysqli_stmt_error', '->geterrormessage']);
const EXC_METHODS = new Set(['->getmessage', '->gettraceasstring', '->errorinfo', '->gettrace']);
-function configRules(ast) {
+function configRules(nodes) {
const hits = [];
- walk(ast, (n) => {
+ nodes.forEach((n) => {
if (n.kind === 'call') {
const name = callName(n);
const args = n.arguments || [];
@@ -267,9 +277,9 @@ function configRules(ast) {
const XML_LOADERS = new Set(['->loadxml', '->loadhtml', '->load', '->loadhtmlfile', 'simplexml_load_string', 'simplexml_load_file', 'simplexml_import_dom', '->xml', '->open']);
-function xxeRules(ast) {
+function xxeRules(nodes) {
const hits = [];
- walk(ast, (n) => {
+ nodes.forEach((n) => {
if (n.kind === 'call') {
const name = callName(n);
if (XML_LOADERS.has(name) || (name && name.startsWith('new'))) {
@@ -301,13 +311,13 @@ const PLACEHOLDERS = /^(|password|passwd|your[_-]?password|changeme|change[_-]?m
const CONNECT_PASSWORD_ARG = { mysqli_connect: 2, mysql_connect: 2, mysql_pconnect: 2, mysqli_real_connect: 3, ldap_bind: 2, oci_connect: 1, odbc_connect: 2, db2_connect: 2 };
const NEW_PASSWORD_ARG = { mysqli: 2, pdo: 2 };
-function secretRules(ast) {
+function secretRules(nodes) {
const hits = [];
const check = (arg, n) => {
const s = arg && (arg.kind === 'string' || arg.kind === 'nowdoc') ? String(arg.value) : null;
if (s !== null && !PLACEHOLDERS.test(s.trim()) && s.length >= 4) hits.push({ ruleId: 'PHP-SECRET-001', line: lineOf(n), column: colOf(n) });
};
- walk(ast, (n) => {
+ nodes.forEach((n) => {
if (n.kind === 'call') {
const name = callName(n);
if (name && Object.prototype.hasOwnProperty.call(CONNECT_PASSWORD_ARG, name)) check((n.arguments || [])[CONNECT_PASSWORD_ARG[name]], n);
@@ -331,13 +341,15 @@ function secretRules(ast) {
/** Runs every structural rule on one file's AST. */
function runAstRules(ast) {
+ const nodes = [];
+ walk(ast, (n) => { nodes.push(n); });
return [
...earRule(ast),
- ...cryptoRules(ast),
- ...sessionFixationRule(ast),
- ...configRules(ast),
- ...xxeRules(ast),
- ...secretRules(ast),
+ ...cryptoRules(nodes),
+ ...sessionFixationRule(nodes),
+ ...configRules(nodes),
+ ...xxeRules(nodes),
+ ...secretRules(nodes),
];
}
diff --git a/langs/php/rules/text-rules.js b/langs/php/rules/text-rules.js
index 67c2fba..b603170 100644
--- a/langs/php/rules/text-rules.js
+++ b/langs/php/rules/text-rules.js
@@ -53,8 +53,9 @@ function csrfForms(file, text) {
/* ------------------------------------------------------------ DOM XSS */
-const DOM_SOURCE = /\b(location\s*\.\s*(hash|search|href|pathname)|location\b(?!\s*\.\s*(reload|assign|replace))|document\s*\.\s*(URL|documentURI|baseURI|referrer|cookie)|window\s*\.\s*name|URLSearchParams|\.searchParams|(event|evt|e|msg|message)\s*\.\s*data\b)/;
-const HTML_SINK = /(\.(?:innerHTML|outerHTML)\s*\+?=(?!=)|document\s*\.\s*write(?:ln)?\s*\(|\.insertAdjacentHTML\s*\(\s*[^,]+,|\$\s*\(\s*(?=[^'"`)])|\.(?:html|append|prepend|after|before|replaceWith)\s*\(\s*(?=[^'"`)\s]))/;
+const DOM_SOURCE = /(? 400;
+}
+
+function identifierMatcher(ids) {
+ if (ids.size === 0) return null;
+ const alt = [...ids].map((id) => id.replace(/[$]/g, '\\$')).join('|');
+ return new RegExp(`(? DOM_SOURCE.test(t) || (listensForMessages && MESSAGE_SOURCE.test(t));
const tainted = new Set();
// two passes so that later-declared derived variables are recognized
for (let pass = 0; pass < 2; pass++) {
+ let matcher = identifierMatcher(tainted);
for (const stmt of statements) {
const m = /(?:\b(?:var|let|const)\s+)?([A-Za-z_$][\w$]*)\s*=(?!=)([\s\S]*)/.exec(stmt);
- if (!m) continue;
+ if (!m || tainted.has(m[1])) continue;
const rhs = m[2];
- if (DOM_SOURCE.test(rhs) || [...tainted].some((id) => new RegExp(`\\b${id.replace(/\$/g, '\\$')}\\b`).test(rhs))) tainted.add(m[1]);
+ if (isSource(rhs) || (matcher && matcher.test(rhs))) {
+ tainted.add(m[1]);
+ matcher = identifierMatcher(tainted);
+ }
}
}
+ const matcher = identifierMatcher(tainted);
let pos = 0;
for (const stmt of statements) {
const idx = pos;
@@ -91,8 +114,8 @@ function domRules(file, text) {
const sm = re.exec(stmt);
if (!sm) continue;
const after = stmt.slice(sm.index + sm[0].length);
- const direct = DOM_SOURCE.test(after);
- const viaVar = [...tainted].some((id) => new RegExp(`\\b${id.replace(/\$/g, '\\$')}\\b`).test(after));
+ const direct = isSource(after);
+ const viaVar = Boolean(matcher && matcher.test(after));
if (!direct && !viaVar) continue;
hits.push({ ruleId, line: lineFromStarts(starts, offset + idx + sm.index), column: 1, confidence: direct ? 'high' : 'medium' });
}
diff --git a/langs/php/taint/index.js b/langs/php/taint/index.js
index 6d7cffe..e1a3ba3 100644
--- a/langs/php/taint/index.js
+++ b/langs/php/taint/index.js
@@ -1,6 +1,11 @@
'use strict';
/*
- * PHP taint analysis entry point: parse -> lower -> interpret.
+ * PHP taint analysis entry points.
+ *
+ * analyzeFile(text, rel) one file on its own (tests, quick checks)
+ * analyzeProject(files, ...) whole project: every file is parsed once, then each
+ * file is analyzed as an entry point with includes,
+ * functions and classes resolved across the project
*/
const { parsePhp } = require('./parse');
const { lower } = require('./lower');
@@ -11,7 +16,6 @@ const { Interpreter } = require('../../../core/taint/interpreter');
* @param {string} text PHP source
* @param {string} rel path relative to the scanned folder
* @param {{secondOrder?:boolean, assumeParamsTainted?:boolean, catalog?:object, budget?:number}} options
- * @returns {{status:string, error:string|null, ast:object|null, hits:Array, exhausted:boolean}}
*/
function analyzeFile(text, rel, options = {}) {
const parsed = parsePhp(text, rel);
@@ -29,8 +33,70 @@ function analyzeFile(text, rel, options = {}) {
} catch (err) {
return { status: parsed.status, error: `analysis: ${err.message}`, ast: parsed.ast, hits: [], exhausted: true };
}
- const hits = result.hits.map((h) => (parsed.status === 'recovered' ? { ...h, conf: 2 } : h));
+ const hits = result.hits.map((h) => ({ ...h, entries: [...h.entries], conf: parsed.status === 'recovered' ? 2 : h.conf }));
return { status: parsed.status, error: parsed.error, ast: parsed.ast, hits, exhausted: result.exhausted };
}
-module.exports = { analyzeFile };
+function push(map, key, value) {
+ if (!map.has(key)) map.set(key, []);
+ map.get(key).push(value);
+}
+
+/**
+ * @param {Array<{rel:string, text:string}>} files PHP files of the project
+ * @param {object} options interpreter options (secondOrder, catalog, ...)
+ * @param {(rel:string, ast:object|null, parsed:{status,error})=>void} [onParsed] called once per file
+ * @returns {{hits:Array, status:Map, exhausted:number}}
+ */
+function analyzeProject(files, options = {}, onParsed) {
+ const catalog = options.catalog || baseCatalog;
+ const status = new Map();
+ const project = { programs: new Map(), functions: new Map(), classes: new Map(), methodsByName: new Map() };
+
+ for (const { rel, text } of files) {
+ const parsed = parsePhp(text, rel);
+ let program = null;
+ let error = parsed.error;
+ if (parsed.ast) {
+ try {
+ program = lower(parsed.ast, rel);
+ } catch (err) {
+ error = `lowering: ${err.message}`;
+ }
+ }
+ status.set(rel, { status: program ? parsed.status : 'failed', error });
+ if (onParsed) onParsed(rel, parsed.ast || null, { status: program ? parsed.status : 'failed', error });
+ if (!program) continue;
+ project.programs.set(rel, program);
+ for (const [name, fn] of program.functions) push(project.functions, name, fn);
+ for (const [name, cls] of program.classes) push(project.classes, name, cls);
+ for (const [name, list] of program.methodsByName) for (const fn of list) push(project.methodsByName, name, fn);
+ }
+
+ const shared = { hits: new Map(), memo: new Map(), analyzed: new Set() };
+ let exhausted = 0;
+ for (const [rel, program] of project.programs) {
+ const interpreter = new Interpreter(program, catalog, { ...options, project, shared });
+ try {
+ if (interpreter.run({ standalone: false }).exhausted) exhausted++;
+ } catch (err) {
+ status.get(rel).error = `analysis: ${err.message}`;
+ }
+ }
+
+ // functions and methods that no entry point called (libraries, controllers, hooks)
+ const all = [...project.programs.values()].flatMap((p) => p.allFunctions);
+ const empty = { file: '', main: [], functions: new Map(), classes: new Map(), methodsByName: new Map(), allFunctions: all };
+ try {
+ new Interpreter(empty, catalog, { ...options, project, shared }).analyzeRemaining(all);
+ } catch (_) { /* best effort */ }
+
+ const hits = [...shared.hits.values()].map((h) => ({
+ ...h,
+ entries: [...h.entries].filter((e) => e && e !== h.file).sort(),
+ conf: status.get(h.file) && status.get(h.file).status === 'recovered' ? 2 : h.conf,
+ }));
+ return { hits, status, exhausted };
+}
+
+module.exports = { analyzeFile, analyzeProject };
diff --git a/langs/php/taint/lower.js b/langs/php/taint/lower.js
index 0543bf1..11fb94e 100644
--- a/langs/php/taint/lower.js
+++ b/langs/php/taint/lower.js
@@ -172,6 +172,7 @@ class Lowerer {
if (cls) this.currentClass = cls;
const fn = {
id: `${this.file}#${this.nextId++}`,
+ file: this.file,
name: name || '{closure}',
cls: cls || null,
line: lineOf(n),
@@ -299,7 +300,7 @@ class Lowerer {
case 'nullkeyword':
return { k: 'lit', value: null, line };
case 'magic':
- return { k: 'lit', value: `<${String(n.value || n.raw || 'magic')}>`, line };
+ return { k: 'magic', name: String(n.raw || n.value || '').toUpperCase(), line };
case 'encapsed': {
const parts = (n.value || []).map((p) => {
const x = p.kind === 'encapsedpart' ? p.expression : p;
@@ -354,6 +355,7 @@ class Lowerer {
case 'call': {
const w = n.what;
const args = this.args(n.arguments);
+ if (!w) return { k: 'unknown', parts: args, line };
if (w.kind === 'name') return { k: 'call', callee: `fn:${lastSegment(w.name).toLowerCase()}`, args, line, col: colOf(n) };
if ((w.kind === 'propertylookup' || w.kind === 'nullsafepropertylookup') && w.offset && w.offset.kind === 'identifier') {
return { k: 'call', callee: `m:${w.offset.name.toLowerCase()}`, recv: this.expr(w.what), args, line, col: colOf(n) };
@@ -389,7 +391,7 @@ class Lowerer {
case 'silent':
return this.expr(n.expr);
case 'include':
- return this.call('@include', [this.expr(n.target)], n);
+ return { ...this.call('@include', [this.expr(n.target)], n), once: Boolean(n.once), require: Boolean(n.require) };
case 'eval':
return this.call('@eval', [this.expr(n.source)], n);
case 'exit':
diff --git a/test/fixtures/php-crossfile/index.php b/test/fixtures/php-crossfile/index.php
new file mode 100644
index 0000000..af47741
--- /dev/null
+++ b/test/fixtures/php-crossfile/index.php
@@ -0,0 +1,7 @@
+query("SELECT name FROM users WHERE id = $id"); // @expect CWE-89
+ return $result->fetch_assoc();
+}
+
+function e($value)
+{
+ return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
+}
diff --git a/test/fixtures/php-crossfile/pages/home.php b/test/fixtures/php-crossfile/pages/home.php
new file mode 100644
index 0000000..f95bef3
--- /dev/null
+++ b/test/fixtures/php-crossfile/pages/home.php
@@ -0,0 +1 @@
+Home
diff --git a/test/fixtures/php-crossfile/tools.php b/test/fixtures/php-crossfile/tools.php
new file mode 100644
index 0000000..7553817
--- /dev/null
+++ b/test/fixtures/php-crossfile/tools.php
@@ -0,0 +1,10 @@
+' . e($_GET['name']) . '';
+echo '' . $_GET['raw'] . '
'; // @expect CWE-79
diff --git a/test/unit/php-fixtures.test.js b/test/unit/php-fixtures.test.js
index 9218170..eeeea97 100644
--- a/test/unit/php-fixtures.test.js
+++ b/test/unit/php-fixtures.test.js
@@ -63,3 +63,16 @@ test('--fail-on sets a non-zero exit code for CI', () => {
fs.rmSync(out, { recursive: true, force: true });
assert.strictEqual(r.status, 1);
});
+
+test('cross-file analysis: includes, define() paths, helpers in other files', () => {
+ const dir = path.join(REPO, 'test', 'fixtures', 'php-crossfile');
+ const { report, missing } = checkCorpus(dir);
+ assert.deepStrictEqual(missing.map((m) => `${m.file}:${m.line} ${m.cwes.join('|')}`), []);
+ const xss = report.findings.filter((f) => f.ruleId === 'PHP-XSS-001');
+ assert.deepStrictEqual(xss.map((f) => `${f.file}:${f.line}`), ['view.php:4'], 'e() from another file is recognized as escaping');
+ const sqli = report.findings.find((f) => f.ruleId === 'PHP-SQLI-001');
+ assert.strictEqual(sqli.file, 'lib/helpers.php');
+ assert.ok(sqli.entryPoints.includes('index.php'), 'sink in a helper is linked to the entry script');
+ const cmd = report.findings.find((f) => f.ruleId === 'PHP-CMDI-001');
+ assert.ok(cmd && cmd.trace.some((t) => /\$_GET\['dir'\]/.test(t.note)), 'value set in an included file reaches the sink');
+});
From 54262b55af7d20565b17bb5067b977d00d6f5961 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tar=C4=B1k=20Seyceri?=
Date: Fri, 13 Nov 2026 18:17:10 +0300
Subject: [PATCH 07/12] feat(php): Laravel, WordPress and Symfony framework
packs
- Automatic framework detection (composer.json/lock, WordPress core,
plugin and theme headers) with packs that extend the taint catalog:
request sources, escaping helpers, query builders, $wpdb, redirects
and HTTP clients.
- Template checks for raw Blade {!! !!} and Twig |raw / autoescape false.
- Mass assignment, framework debug mode (.env, config/app.php,
wp-config.php), CSRF exemptions and WordPress AJAX/admin-post
handlers without nonce and capability checks.
- Framework-aware CSRF token helpers; array_map() callback modelling.
- Guide sections and fixtures for each framework.
Co-Authored-By: Claude Opus 5.5
---
CHANGELOG.md | 2 +
core/taint/interpreter.js | 5 +-
langs/php/frameworks/index.js | 57 +++++++
langs/php/frameworks/laravel.js | 96 ++++++++++++
langs/php/frameworks/symfony.js | 60 ++++++++
langs/php/frameworks/wordpress.js | 140 ++++++++++++++++++
langs/php/guides/access-control.md | 19 +++
langs/php/guides/integrity.md | 14 ++
langs/php/guides/misconfiguration.md | 19 +++
langs/php/guides/xss.md | 17 +++
langs/php/index.js | 26 +++-
langs/php/rules/registry.js | 12 ++
langs/php/rules/text-rules.js | 7 +-
langs/php/taint/catalog.js | 11 +-
test/fixtures/laravel.expect.json | 4 +
test/fixtures/laravel/.env | 3 +
.../app/Http/Controllers/UserController.php | 25 ++++
.../app/Http/Middleware/VerifyCsrfToken.php | 12 ++
test/fixtures/laravel/app/Models/User.php | 10 ++
test/fixtures/laravel/composer.json | 7 +
.../laravel/resources/views/profile.blade.php | 10 ++
test/fixtures/symfony/composer.json | 8 +
.../src/Controller/ProductController.php | 19 +++
.../symfony/templates/product/show.html.twig | 2 +
test/fixtures/wordpress-plugin/my-plugin.php | 40 +++++
.../wordpress-plugin/views/settings-page.php | 6 +
test/unit/php-fixtures.test.js | 13 ++
27 files changed, 639 insertions(+), 5 deletions(-)
create mode 100644 langs/php/frameworks/index.js
create mode 100644 langs/php/frameworks/laravel.js
create mode 100644 langs/php/frameworks/symfony.js
create mode 100644 langs/php/frameworks/wordpress.js
create mode 100644 test/fixtures/laravel.expect.json
create mode 100644 test/fixtures/laravel/.env
create mode 100644 test/fixtures/laravel/app/Http/Controllers/UserController.php
create mode 100644 test/fixtures/laravel/app/Http/Middleware/VerifyCsrfToken.php
create mode 100644 test/fixtures/laravel/app/Models/User.php
create mode 100644 test/fixtures/laravel/composer.json
create mode 100644 test/fixtures/laravel/resources/views/profile.blade.php
create mode 100644 test/fixtures/symfony/composer.json
create mode 100644 test/fixtures/symfony/src/Controller/ProductController.php
create mode 100644 test/fixtures/symfony/templates/product/show.html.twig
create mode 100644 test/fixtures/wordpress-plugin/my-plugin.php
create mode 100644 test/fixtures/wordpress-plugin/views/settings-page.php
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 161968a..861e3ec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,8 @@ ASST 2.0 is a major upgrade built on the foundation of the original thesis relea
- New detections: server-side request forgery, open redirect, path traversal, XPath injection, insecure deserialization, variable extraction (`extract`/`parse_str`), log and mail-header injection, code injection through `eval`/`assert`/`create_function`, unsafe dynamic calls, execution after redirect, weak password hashing, predictable random tokens, loose comparison of secrets, session fixation, hard-coded credentials, errors and `phpinfo()` shown to visitors, database error disclosure, DOM-based XSS and JavaScript `eval`, and version-control folders, backups, keys and dumps inside the web root.
- Remediation guides in Markdown (`langs/php/guides/`), one section per rule, written for current PHP 8 practice and the OWASP Top 10:2025. The relevant section is shown under each finding in the HTML report and used as rule help in SARIF.
- Cross-file analysis: `include`/`require` targets are resolved (including `__DIR__`, `define()`d paths and file names chosen in a `switch`) and run in the including scope, and functions and classes are resolved across the whole project. A vulnerability inside a shared helper lists the entry scripts that reach it.
+- Framework packs for Laravel, WordPress and Symfony, detected automatically. Framework request objects, escaping helpers (`e()`, `esc_html()`, `esc_attr()`, `esc_url()`, `absint()`, `sanitize_*()`), query builders, `$wpdb` and HTTP clients are part of the data-flow analysis. New checks cover raw Blade (`{!! !!}`) and Twig (`|raw`, `autoescape false`) output, mass assignment (`$guarded = []` with `create($request->all())`), debug mode in `.env`, `config/app.php` and `wp-config.php`, CSRF exemptions in `VerifyCsrfToken`, `$wpdb` queries built without `prepare()`, and WordPress AJAX/admin-post handlers without nonce and capability checks. CSRF checks recognize `@csrf`, `csrf_field()`, `wp_nonce_field()` and Symfony `csrf_token()`. The report header lists the detected frameworks.
+- Callback-aware data flow for `array_map()` with built-in callbacks such as `intval` or `htmlspecialchars`.
- Findings are mapped to the OWASP Top 10:2025 (with the 2021 category) and to CWE, and carry a severity, a confidence level and a code snippet.
- Interactive HTML report: one self-contained file that works offline, with severity tiles, search, filters (severity, confidence, OWASP category), grouping by category/file/rule, code snippets with the line highlighted, data-flow traces, dark mode and print layout. Content is fully HTML-escaped and protected by a strict Content-Security-Policy.
- SARIF 2.1.0 output (`--format sarif`) for GitHub code scanning and IDE viewers, with CWE/OWASP tags, security-severity scores, stable fingerprints and data-flow code flows.
diff --git a/core/taint/interpreter.js b/core/taint/interpreter.js
index 7326fb0..4ed62b7 100644
--- a/core/taint/interpreter.js
+++ b/core/taint/interpreter.js
@@ -667,12 +667,15 @@ class Interpreter {
}
ctxApi(env, f) {
- return {
+ const api = {
env,
opts: this.opts,
evalExpr: (x) => this.eval(x, env, f),
readPath: (p) => this.read(p, env, f),
+ // lets catalogs apply another catalog function (e.g. an array_map callback)
+ callCatalog: (callee, argVals, line) => (this.cat.call ? this.cat.call(callee, argVals, { callee, args: [], line: line || 0 }, api) : null),
};
+ return api;
}
evalCall(e, env, f) {
diff --git a/langs/php/frameworks/index.js b/langs/php/frameworks/index.js
new file mode 100644
index 0000000..faf0d10
--- /dev/null
+++ b/langs/php/frameworks/index.js
@@ -0,0 +1,57 @@
+'use strict';
+/*
+ * Framework packs for the PHP plugin. Each pack may provide:
+ * detect(project, readText, composer) -> info | null
+ * call(...) -> taint catalog extension (sources, sinks, sanitizers)
+ * templateRules(file, text) -> findings in template files
+ * projectRules(phpFiles, envFiles) -> project-wide findings
+ * CSRF_HELPERS -> regex of template helpers that output a CSRF token
+ */
+const packs = {
+ wordpress: require('./wordpress'),
+ laravel: require('./laravel'),
+ symfony: require('./symfony'),
+};
+
+function readComposer(project, readText) {
+ const f = project.files.find((x) => x.rel === 'composer.json');
+ if (!f) return null;
+ try {
+ return JSON.parse(readText(f) || '{}');
+ } catch (_) {
+ return null;
+ }
+}
+
+/** @returns {Array<{id, pack, info}>} detected frameworks */
+function detect(project, readText) {
+ const composer = readComposer(project, readText);
+ const found = [];
+ for (const [id, pack] of Object.entries(packs)) {
+ let info = null;
+ try { info = pack.detect(project, readText, composer); } catch (_) { info = null; }
+ if (info) found.push({ id, pack, info });
+ }
+ return found;
+}
+
+/** Combined catalog extension for the detected frameworks. */
+function catalogPack(detected) {
+ const calls = detected.map((d) => d.pack.call).filter(Boolean);
+ if (!calls.length) return null;
+ return {
+ call(callee, args, e, ctx, helpers) {
+ for (const c of calls) {
+ const r = c(callee, args, e, ctx, helpers);
+ if (r) return r;
+ }
+ return null;
+ },
+ };
+}
+
+function csrfHelpers(detected) {
+ return detected.map((d) => d.pack.CSRF_HELPERS).filter(Boolean);
+}
+
+module.exports = { detect, catalogPack, csrfHelpers, packs };
diff --git a/langs/php/frameworks/laravel.js b/langs/php/frameworks/laravel.js
new file mode 100644
index 0000000..e3937e3
--- /dev/null
+++ b/langs/php/frameworks/laravel.js
@@ -0,0 +1,96 @@
+'use strict';
+/*
+ * Laravel pack: request sources, raw query builders, redirects and HTTP client for the
+ * taint engine; Blade raw output, mass assignment, debug mode and CSRF exemptions.
+ */
+
+const REQUEST_METHODS = new Set(['input', 'query', 'post', 'all', 'only', 'except', 'get', 'cookie', 'header', 'json', 'route', 'string', 'str', 'collect', 'validated', 'safe']);
+const RAW_SQL_METHODS = new Set(['whereraw', 'orwhereraw', 'havingraw', 'orhavingraw', 'orderbyraw', 'selectraw', 'groupbyraw', 'fromraw', 'joinraw']);
+const DB_STATIC = new Set(['raw', 'select', 'insert', 'update', 'delete', 'statement', 'unprepared', 'selectone', 'scalar']);
+
+function detect(project, readText, composer) {
+ const req = composer ? { ...(composer.require || {}), ...(composer['require-dev'] || {}) } : {};
+ if (req['laravel/framework']) return { version: String(req['laravel/framework']).replace(/[^\d.]/g, '') || null };
+ if (project.files.some((f) => f.rel === 'artisan') && project.files.some((f) => f.rel.startsWith('app/'))) return { version: null };
+ return null;
+}
+
+function isRequestReceiver(recv) {
+ return recv && recv.k === 'path' && /^(request|req|httpRequest)$/i.test(recv.base) && recv.segs.length === 0;
+}
+
+function call(callee, args, e, ctx, { V, S }) {
+ const line = e.line;
+ const method = callee.startsWith('m:') ? callee.slice(2) : null;
+ if (method && REQUEST_METHODS.has(method) && isRequestReceiver(e.recv)) {
+ return { value: V.source('src', `$request->${method}()`, line, method === 'validated' || method === 'safe' ? 1 : 0) };
+ }
+ if (callee === 'fn:request' && args.length > 0) return { value: V.source('src', 'request()', line, 0) };
+ if (callee === 'fn:old') return { value: V.source('src', 'old()', line, 1) };
+ if (/^sm:(request|input)::(input|get|all|query|only|except)$/.test(callee)) return { value: V.source('src', callee.slice(3), line, 0) };
+ if (callee === 'fn:e') return { value: V.sanitize(args[0], { enc: { html: true, htmlQuotes: true } }, line, 'e()') };
+ if (method && RAW_SQL_METHODS.has(method)) return { value: { t: false, obj: { cls: 'Builder', fields: new Map() } }, sinks: [S('PHP-SQLI-001', 0, 'sql')] };
+ const st = /^sm:db::(\w+)$/.exec(callee);
+ if (st && DB_STATIC.has(st[1])) return { value: V.CLEAN, sinks: [S('PHP-SQLI-001', 0, 'sql')] };
+ if (callee === 'fn:redirect' || /^sm:redirect::(to|away)$/.test(callee) || (method === 'away') || (method === 'to' && e.recv && e.recv.k === 'call' && e.recv.callee === 'fn:redirect')) {
+ return { value: V.CLEAN, sinks: args.length ? [S('PHP-REDIR-001', 0, 'urlControl')] : [] };
+ }
+ if (/^sm:http::(get|post|put|patch|delete|head)$/.test(callee)) return { value: V.CLEAN, sinks: [S('PHP-SSRF-001', 0, 'urlControl')] };
+ if (/^sm:storage::(get|put|delete|download|exists)$/.test(callee) || (method === 'download' && e.recv && e.recv.k === 'call' && e.recv.callee === 'fn:response')) {
+ return { value: V.CLEAN, sinks: [S('PHP-PATH-001', 0, 'path')] };
+ }
+ return null;
+}
+
+/** Blade templates: unescaped output. */
+function templateRules(file, text) {
+ if (!file.name.endsWith('.blade.php')) return [];
+ const hits = [];
+ text.split('\n').forEach((l, i) => {
+ const re = /\{!!\s*(.+?)\s*!!\}/g;
+ let m;
+ while ((m = re.exec(l)) !== null) {
+ const expr = m[1];
+ if (/^(csrf_field|method_field|\$__env|config\(|trans\(|__\(|json_encode|@json|Js::from)/.test(expr)) continue;
+ const direct = /request\(|\$request|old\(|\$_(GET|POST|REQUEST|COOKIE)|input\(/.test(expr);
+ hits.push({ ruleId: 'PHP-XSS-002', line: i + 1, column: m.index + 1, confidence: direct ? 'high' : 'medium', message: `Blade prints "${expr.slice(0, 60)}" without escaping ({!! !!}). Use {{ }} unless the value is trusted HTML that has been sanitized.` });
+ }
+ });
+ return hits;
+}
+
+/** Mass assignment, debug mode and CSRF exemptions. */
+function projectRules(phpFiles, envFiles) {
+ const hits = [];
+ for (const { rel, text } of phpFiles) {
+ text.split('\n').forEach((l, i) => {
+ if (/protected\s+\$guarded\s*=\s*(\[\s*\]|array\s*\(\s*\))\s*;/.test(l)) {
+ hits.push({ ruleId: 'PHP-MASS-001', file: rel, line: i + 1, confidence: 'medium', message: 'This model has an empty $guarded list, so every attribute can be mass-assigned. Use $fillable with the fields users may set.' });
+ }
+ if (/::(create|forceCreate|firstOrCreate|updateOrCreate)\s*\(\s*\$request->all\(\)|->(fill|update|forceFill)\s*\(\s*\$request->all\(\)/.test(l)) {
+ hits.push({ ruleId: 'PHP-MASS-001', file: rel, line: i + 1, confidence: 'high', message: 'All request fields are mass-assigned to a model. Pass $request->validated() or $request->only([...]) instead.' });
+ }
+ if (/(^|\/)config\/app\.php$/.test(rel) && /['"]debug['"]\s*=>\s*true\b/.test(l)) {
+ hits.push({ ruleId: 'PHP-CONF-003', file: rel, line: i + 1, message: "'debug' => true is hard-coded in config/app.php. Read it from APP_DEBUG and keep it false in production." });
+ }
+ });
+ if (/VerifyCsrfToken|ValidateCsrfToken/.test(text)) {
+ const m = /protected\s+\$except\s*=\s*\[([\s\S]*?)\]/.exec(text);
+ if (m && /['"]/.test(m[1])) {
+ const line = text.slice(0, m.index).split('\n').length;
+ hits.push({ ruleId: 'PHP-CSRF-002', file: rel, line, message: `CSRF protection is switched off for: ${m[1].replace(/\s+/g, ' ').trim().slice(0, 120)}. Make sure these routes do not change state for logged-in users.` });
+ }
+ }
+ }
+ for (const { rel, text } of envFiles) {
+ const debug = /^\s*APP_DEBUG\s*=\s*(true|1)\s*$/im.test(text);
+ const prod = /^\s*APP_ENV\s*=\s*prod(uction)?\s*$/im.test(text);
+ if (debug && (prod || !/\.(example|dist|sample|testing)$/.test(rel))) {
+ const line = text.split('\n').findIndex((l) => /^\s*APP_DEBUG\s*=/.test(l)) + 1;
+ hits.push({ ruleId: 'PHP-CONF-003', file: rel, line, severity: prod ? 'high' : 'medium', message: `APP_DEBUG is true${prod ? ' while APP_ENV is production' : ''}. Debug pages reveal code, configuration and secrets; set APP_DEBUG=false in production.` });
+ }
+ }
+ return hits;
+}
+
+module.exports = { name: 'Laravel', detect, call, templateRules, projectRules, CSRF_HELPERS: /@csrf|csrf_field\s*\(|csrf_token\s*\(/ };
diff --git a/langs/php/frameworks/symfony.js b/langs/php/frameworks/symfony.js
new file mode 100644
index 0000000..ec90fb8
--- /dev/null
+++ b/langs/php/frameworks/symfony.js
@@ -0,0 +1,60 @@
+'use strict';
+/*
+ * Symfony / Twig pack: request bags as sources, Doctrine raw SQL and DQL, redirects;
+ * Twig |raw output and disabled autoescaping.
+ */
+
+const BAGS = new Set(['query', 'request', 'cookies', 'headers', 'attributes', 'files', 'server']);
+
+function detect(project, readText, composer) {
+ const req = composer ? { ...(composer.require || {}), ...(composer['require-dev'] || {}) } : {};
+ const symfony = Object.keys(req).some((k) => k.startsWith('symfony/'));
+ const twig = Boolean(req['twig/twig']) || project.files.some((f) => f.ext === 'twig');
+ if (!symfony && !twig) return null;
+ return { symfony, twig, version: req['symfony/framework-bundle'] ? String(req['symfony/framework-bundle']).replace(/[^\d.]/g, '') || null : null };
+}
+
+function call(callee, args, e, ctx, { V, S }) {
+ const line = e.line;
+ const method = callee.startsWith('m:') ? callee.slice(2) : null;
+ // $request->query->get('x'), $request->request->all(), ...
+ if (method && ['get', 'all', 'getint', 'getalpha', 'getalnum', 'getdigits', 'getboolean', 'getstring'].includes(method) && e.recv && e.recv.k === 'path') {
+ const segs = e.recv.segs;
+ const bag = segs.length ? segs[segs.length - 1].prop : null;
+ if (/^(request|req)$/i.test(e.recv.base) && bag && BAGS.has(bag)) {
+ if (['getint', 'getdigits', 'getboolean'].includes(method)) return { value: { t: false, num: true } };
+ if (method === 'getalpha') return { value: V.sanitize(V.source('src', `$request->${bag}->getAlpha()`, line), { allowed: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' }, line, 'getAlpha()') };
+ if (method === 'getalnum') return { value: V.sanitize(V.source('src', `$request->${bag}->getAlnum()`, line), { allowed: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' }, line, 'getAlnum()') };
+ return { value: V.source('src', `$request->${bag}->${method}()`, line, 0) };
+ }
+ if (/^(request|req)$/i.test(e.recv.base) && segs.length === 0 && method === 'get') return { value: V.source('src', '$request->get()', line, 0) };
+ }
+ if (method === 'getcontent' && e.recv && e.recv.k === 'path' && /^(request|req)$/i.test(e.recv.base)) return { value: V.source('src', '$request->getContent()', line, 0) };
+ if (method && ['executequery', 'executestatement', 'executeupdate', 'fetchallassociative', 'fetchassociative', 'fetchone', 'fetchall'].includes(method)) {
+ return { value: V.CLEAN, sinks: [S('PHP-SQLI-001', 0, 'sql')] };
+ }
+ if (method === 'createquery' || method === 'createnativequery') return { value: { t: false, obj: { cls: 'Query', fields: new Map() } }, sinks: [S('PHP-SQLI-001', 0, 'sql')] };
+ if (method === 'redirect' && e.recv && e.recv.k === 'path' && e.recv.base === 'this') return { value: V.CLEAN, sinks: [S('PHP-REDIR-001', 0, 'urlControl')] };
+ if (callee === 'new:redirectresponse') return { value: V.CLEAN, sinks: [S('PHP-REDIR-001', 0, 'urlControl')] };
+ if (callee === 'new:response') return { value: V.CLEAN, sinks: [S('PHP-XSS-001', 0, 'html', { name: 'new Response()', confPenalty: 1 })] };
+ return null;
+}
+
+/** Twig templates: |raw and disabled autoescaping. */
+function templateRules(file, text) {
+ if (file.ext !== 'twig') return [];
+ const hits = [];
+ text.split('\n').forEach((l, i) => {
+ const re = /\{\{\s*([^}]*?)\|\s*raw\b[^}]*\}\}/g;
+ let m;
+ while ((m = re.exec(l)) !== null) {
+ hits.push({ ruleId: 'PHP-XSS-002', line: i + 1, column: m.index + 1, confidence: /app\.request|request\./.test(m[1]) ? 'high' : 'medium', message: `Twig prints "${m[1].trim().slice(0, 60)}" with the |raw filter, which turns off escaping.` });
+ }
+ if (/\{%\s*autoescape\s+false\s*%\}/.test(l)) {
+ hits.push({ ruleId: 'PHP-XSS-002', line: i + 1, column: 1, confidence: 'medium', message: 'Autoescaping is switched off for this block; every value inside is printed without escaping.' });
+ }
+ });
+ return hits;
+}
+
+module.exports = { name: 'Symfony/Twig', detect, call, templateRules, CSRF_HELPERS: /csrf_token\s*\(|form_rest\s*\(|form_end\s*\(|form_widget\s*\(/ };
diff --git a/langs/php/frameworks/wordpress.js b/langs/php/frameworks/wordpress.js
new file mode 100644
index 0000000..5a3da8e
--- /dev/null
+++ b/langs/php/frameworks/wordpress.js
@@ -0,0 +1,140 @@
+'use strict';
+/*
+ * WordPress pack: core/plugin/theme detection, $wpdb and escaping APIs for the taint
+ * engine, nonce-aware CSRF checks and AJAX/admin-post handler checks.
+ */
+
+const URL_SAFE = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~:/?#[]@!$&()*+,;=%';
+const KEY = 'abcdefghijklmnopqrstuvwxyz0123456789_-';
+const DB_SQL_METHODS = new Set(['m:query', 'm:get_results', 'm:get_var', 'm:get_row', 'm:get_col']);
+
+function detect(project, readText) {
+ const has = (rel) => project.files.some((f) => f.rel === rel || f.rel.endsWith(`/${rel}`));
+ if (has('wp-includes/version.php') || has('wp-config.php') || has('wp-config-sample.php')) {
+ const ver = project.files.find((f) => f.rel.endsWith('wp-includes/version.php'));
+ const m = ver ? /\$wp_version\s*=\s*'([^']+)'/.exec(readText(ver) || '') : null;
+ return { kind: 'core', version: m ? m[1] : null };
+ }
+ // plugin or theme folders
+ for (const f of project.files) {
+ if (f.ext === 'php' && !f.rel.includes('/')) {
+ const head = (readText(f) || '').slice(0, 2000);
+ if (/^\s*\*?\s*Plugin Name:/m.test(head)) return { kind: 'plugin', version: null };
+ }
+ if (f.name === 'style.css' && !f.rel.includes('/') && /Theme Name:/.test((readText(f) || '').slice(0, 2000))) return { kind: 'theme', version: null };
+ }
+ return null;
+}
+
+function isWpdb(e) {
+ return e.recv && e.recv.k === 'path' && e.recv.base === 'wpdb' && e.recv.segs.length === 0;
+}
+
+/** Catalog extension for the taint engine. */
+function call(callee, args, e, ctx, { V, S, propagate }) {
+ const a0 = args[0];
+ const line = e.line;
+ switch (callee) {
+ case 'fn:esc_html': case 'fn:esc_attr': case 'fn:esc_textarea': case 'fn:esc_html__': case 'fn:esc_attr__':
+ case 'fn:esc_html_e': case 'fn:esc_attr_e': case 'fn:wp_kses': case 'fn:wp_kses_post': case 'fn:wp_kses_data':
+ return { value: V.sanitize(a0, { enc: { html: true, htmlQuotes: true } }, line, `${callee.slice(3)}()`) };
+ case 'fn:esc_url': case 'fn:esc_url_raw': case 'fn:sanitize_url':
+ return { value: V.sanitize(a0, { allowed: URL_SAFE, enc: { url: true, html: true, htmlQuotes: true } }, line, `${callee.slice(3)}()`) };
+ case 'fn:esc_js':
+ return { value: V.sanitize(a0, { enc: { html: true, htmlQuotes: true }, removeChars: '\\\n\r' }, line, 'esc_js()') };
+ case 'fn:esc_sql':
+ return { value: V.sanitize(a0, { enc: { sql: true } }, line, 'esc_sql()') };
+ case 'fn:absint': case 'fn:wp_validate_boolean':
+ return { value: { t: false, num: true } };
+ case 'fn:sanitize_key': case 'fn:sanitize_title': case 'fn:sanitize_html_class':
+ return { value: V.sanitize(a0, { allowed: KEY }, line, `${callee.slice(3)}()`) };
+ case 'fn:sanitize_text_field': case 'fn:sanitize_textarea_field':
+ return { value: V.sanitize(a0, { removeChars: '<>\r\n' }, line, `${callee.slice(3)}()`) };
+ case 'fn:sanitize_email': case 'fn:is_email':
+ return { value: V.sanitize(a0, { allowed: `${KEY}ABCDEFGHIJKLMNOPQRSTUVWXYZ.@+` }, line, `${callee.slice(3)}()`) };
+ case 'fn:sanitize_file_name':
+ return { value: V.sanitize(a0, { removeChars: '/\\:' }, line, 'sanitize_file_name()') };
+ case 'fn:wp_unslash': case 'fn:stripslashes_deep': case 'fn:map_deep':
+ return { value: propagate(a0, line, `${callee.slice(3)}()`) };
+ case 'fn:get_query_var':
+ return { value: V.source('src', `get_query_var('${a0 && a0.str !== undefined ? a0.str : ''}')`, line, 1) };
+ case 'fn:wp_redirect':
+ return { value: V.CLEAN, sinks: [S('PHP-REDIR-001', 0, 'urlControl')] };
+ case 'fn:wp_remote_get': case 'fn:wp_remote_post': case 'fn:wp_remote_request': case 'fn:wp_remote_head':
+ return { value: V.CLEAN, sinks: [S('PHP-SSRF-001', 0, 'urlControl')] };
+ case 'fn:wp_safe_redirect': case 'fn:wp_safe_remote_get': case 'fn:wp_safe_remote_post':
+ return { value: V.CLEAN };
+ default:
+ break;
+ }
+ if (isWpdb(e)) {
+ if (callee === 'm:prepare') {
+ // the query template must be constant; values are escaped by prepare()
+ const out = { t: false };
+ return { value: out, sinks: [S('PHP-SQLI-001', 0, 'sql')] };
+ }
+ if (DB_SQL_METHODS.has(callee)) return { value: ctx.opts.secondOrder ? V.source('src2', `$wpdb->${callee.slice(2)}() result`, line, 1) : V.CLEAN, sinks: [S('PHP-SQLI-001', 0, 'sql')] };
+ if (callee === 'm:esc_like') return { value: V.sanitize(a0, { enc: { sql: true } }, line, 'esc_like()') };
+ }
+ return null;
+}
+
+const CSRF_HELPERS = /wp_nonce_field\s*\(|settings_fields\s*\(|wp_referer_field\s*\(|check_admin_referer\s*\(|wp_create_nonce\s*\(|_wpnonce/;
+
+/** AJAX / admin-post handlers registered without a nonce check. */
+function projectRules(phpFiles) {
+ const hits = [];
+ const bodies = new Map();
+ const fnRe = /function\s+&?\s*([A-Za-z_]\w*)\s*\([^)]*\)\s*(?::\s*\??[\w\\]+\s*)?\{/g;
+ for (const { rel, text } of phpFiles) {
+ let m;
+ fnRe.lastIndex = 0;
+ while ((m = fnRe.exec(text)) !== null) {
+ let depth = 1;
+ let i = fnRe.lastIndex;
+ for (; i < text.length && depth > 0; i++) {
+ if (text[i] === '{') depth++;
+ else if (text[i] === '}') depth--;
+ }
+ const entry = { rel, body: text.slice(fnRe.lastIndex, i) };
+ bodies.set(`${rel}::${m[1].toLowerCase()}`, entry);
+ if (!bodies.has(m[1].toLowerCase())) bodies.set(m[1].toLowerCase(), entry);
+ else bodies.set(m[1].toLowerCase(), null); // ambiguous name across files
+ }
+ }
+ const actionRe = /add_action\s*\(\s*['"]((?:wp_ajax_(?:nopriv_)?|admin_post_(?:nopriv_)?)[\w-]+)['"]\s*,\s*(?:['"]([\w\\]+)['"]|\[\s*\$this\s*,\s*['"](\w+)['"]\s*\]|array\s*\(\s*\$this\s*,\s*['"](\w+)['"]\s*\))/g;
+ for (const { rel, text } of phpFiles) {
+ let m;
+ actionRe.lastIndex = 0;
+ while ((m = actionRe.exec(text)) !== null) {
+ const hook = m[1];
+ // public (nopriv) endpoints have no logged-in session to forge requests for
+ if (/_nopriv_/.test(hook)) continue;
+ const handler = (m[2] || m[3] || m[4] || '').split('\\').pop().toLowerCase();
+ const isMethod = Boolean(m[3] || m[4]);
+ const def = bodies.get(`${rel}::${handler}`) || (isMethod ? null : bodies.get(handler));
+ if (!def) continue;
+ const hasNonce = /check_ajax_referer\s*\(|wp_verify_nonce\s*\(|check_admin_referer\s*\(/.test(def.body);
+ const hasCap = /current_user_can\s*\(/.test(def.body);
+ if (hasNonce && hasCap) continue;
+ const missing = [!hasNonce && 'a nonce check (check_ajax_referer / wp_verify_nonce)', !hasCap && 'a capability check (current_user_can)'].filter(Boolean).join(' and ');
+ const line = text.slice(0, m.index).split('\n').length;
+ hits.push({ ruleId: 'PHP-WP-001', file: rel, line, message: `The "${hook}" handler ${handler}() (${def.rel}) runs without ${missing}.` });
+ }
+ }
+ return hits;
+}
+
+/** WP_DEBUG / WP_DEBUG_DISPLAY switched on in configuration files. */
+function configRules(phpFiles) {
+ const hits = [];
+ for (const { rel, text } of phpFiles) {
+ if (!/(^|\/)wp-config\.php$/.test(rel)) continue;
+ text.split('\n').forEach((l, i) => {
+ if (/define\s*\(\s*['"]WP_DEBUG(_DISPLAY)?['"]\s*,\s*true\s*\)/i.test(l)) hits.push({ ruleId: 'PHP-CONF-003', file: rel, line: i + 1, message: 'WordPress debug output is enabled in wp-config.php. Set WP_DEBUG_DISPLAY to false in production (log with WP_DEBUG_LOG instead).' });
+ });
+ }
+ return hits;
+}
+
+module.exports = { name: 'WordPress', detect, call, projectRules, configRules, CSRF_HELPERS };
diff --git a/langs/php/guides/access-control.md b/langs/php/guides/access-control.md
index e71a3d7..b9253a4 100644
--- a/langs/php/guides/access-control.md
+++ b/langs/php/guides/access-control.md
@@ -112,3 +112,22 @@ if (!hash_equals($_SESSION['csrf_token'] ?? '', (string) ($_POST['csrf_token'] ?
Also set session cookies with `SameSite=Lax` (or `Strict`). Frameworks provide this out of the box (Laravel `@csrf`, Symfony forms, WordPress nonces).
References: [OWASP CSRF Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html).
+
+## WordPress nonces and capabilities {#wordpress-nonces}
+
+Every `wp_ajax_*` and `admin_post_*` handler must check that the request was intended (nonce) and that the user is allowed to perform it (capability):
+
+```php
+add_action('wp_ajax_myplugin_save', 'myplugin_save');
+
+function myplugin_save() {
+ check_ajax_referer('myplugin_save'); // dies on an invalid nonce
+ if (!current_user_can('manage_options')) {
+ wp_send_json_error('forbidden', 403);
+ }
+ update_option('myplugin_title', sanitize_text_field(wp_unslash($_POST['title'] ?? '')));
+ wp_send_json_success();
+}
+```
+
+In the form or script, send the nonce with `wp_nonce_field('myplugin_save')` or `wp_create_nonce('myplugin_save')`. Handlers registered with `wp_ajax_nopriv_*` are reachable by anyone, so validate their input carefully.
diff --git a/langs/php/guides/integrity.md b/langs/php/guides/integrity.md
index cbfc93a..c188091 100644
--- a/langs/php/guides/integrity.md
+++ b/langs/php/guides/integrity.md
@@ -37,3 +37,17 @@ parse_str($_SERVER['QUERY_STRING']);
$name = (string) ($_POST['name'] ?? '');
parse_str($_SERVER['QUERY_STRING'], $query);
```
+
+## Mass assignment {#mass-assignment}
+
+Passing all request fields to a model (`User::create($request->all())`) lets users set attributes they should not control, such as `is_admin`, `balance` or `user_id`.
+
+```php
+// Vulnerable
+class User extends Model { protected $guarded = []; }
+User::create($request->all());
+
+// Fixed: allow-list the fields and use validated data
+class User extends Model { protected $fillable = ['name', 'email']; }
+User::create($request->validated());
+```
diff --git a/langs/php/guides/misconfiguration.md b/langs/php/guides/misconfiguration.md
index f88e8bc..f8926aa 100644
--- a/langs/php/guides/misconfiguration.md
+++ b/langs/php/guides/misconfiguration.md
@@ -83,3 +83,22 @@ Header always set Content-Security-Policy "default-src 'self'; frame-ancestors '
```
References: [OWASP HTTP Headers Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html).
+
+## Framework debug mode {#debug-mode}
+
+Debug pages (Laravel/Ignition, Symfony profiler, WordPress `WP_DEBUG_DISPLAY`) show stack traces, configuration, environment variables and sometimes allow code execution. Keep them off in production:
+
+```ini
+# Laravel .env (production)
+APP_ENV=production
+APP_DEBUG=false
+```
+
+```php
+// WordPress wp-config.php (production)
+define('WP_DEBUG', false);
+define('WP_DEBUG_DISPLAY', false);
+define('WP_DEBUG_LOG', true); // if logging is needed
+```
+
+Never deploy `.env` files inside the web root, and never commit production `.env` files.
diff --git a/langs/php/guides/xss.md b/langs/php/guides/xss.md
index 76c939e..b2a5d12 100644
--- a/langs/php/guides/xss.md
+++ b/langs/php/guides/xss.md
@@ -52,3 +52,20 @@ el.textContent = 'Hi ' + decodeURIComponent(location.hash.slice(1));
Never pass such values to `eval()`, `new Function()` or string arguments of `setTimeout()`/`setInterval()`. If HTML must be inserted, sanitize it with a maintained library such as DOMPurify.
References: [OWASP DOM based XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html).
+
+## Template escaping {#template-escaping}
+
+Template engines escape output by default; their "raw" forms switch that protection off:
+
+- **Blade:** `{{ $value }}` escapes, `{!! $value !!}` does not.
+- **Twig:** `{{ value }}` escapes, `{{ value|raw }}` and `{% autoescape false %}` do not.
+
+```blade
+{{-- Vulnerable --}}
+{!! request('name') !!}
+
+{{-- Fixed --}}
+{{ request('name') }}
+```
+
+Use the raw forms only for HTML you generated yourself or sanitized with an HTML sanitizer (for example HTML Purifier or Symfony's HtmlSanitizer). Never use them for request data or database fields that users can edit.
diff --git a/langs/php/index.js b/langs/php/index.js
index 3222799..4c7f81f 100644
--- a/langs/php/index.js
+++ b/langs/php/index.js
@@ -18,6 +18,8 @@ const { phpRuntime, databaseChecks } = require('./runtime/checks');
const { PhpDatabase, normalizeDbConfig } = require('./runtime/db');
const manualReview = require('./notices');
const { loadGuides, pickGuides } = require('../../core/guides');
+const frameworks = require('./frameworks');
+const { extend: extendCatalog } = require('./taint/catalog');
const { createFinding, fingerprint, dedupe, compareFindings, atLeastSeverity, atLeastConfidence } = require('../../core/finding');
const { applyInlineSuppressions, loadBaseline, writeBaseline, compareWithBaseline } = require('../../core/suppress');
const { buildModel } = require('../../core/report/model');
@@ -126,6 +128,14 @@ module.exports = {
if (!config.quiet) console.log(ansi.paint(`Scanning ${project.files.length} files in ${project.root}`, 'cyan'));
+ // frameworks: detection, catalog extensions and template helpers
+ const readText = (f) => cache.text(f.abs);
+ const detected = frameworks.detect(project, readText);
+ const pack = frameworks.catalogPack(detected);
+ if (pack) options.catalog = extendCatalog(pack);
+ const csrfOptions = { helpers: frameworks.csrfHelpers(detected), fileWide: detected.some((d) => d.id === 'wordpress') };
+ if (detected.length && !config.quiet) console.log(ansi.paint(`Frameworks: ${detected.map((d) => d.pack.name + (d.info.version ? ` ${d.info.version}` : '')).join(', ')}`, 'cyan'));
+
const phpFiles = [];
for (const file of project.files) {
const isPhp = EXTENSIONS.includes(file.ext);
@@ -136,7 +146,11 @@ module.exports = {
const lines = cache.lines(file.abs);
stats.filesAnalyzed++;
if (isPhp) phpFiles.push({ rel: file.rel, text });
- for (const h of textRules.csrfForms(file, text)) raw.push(makeFinding(h.ruleId, { ...h, file: file.rel }, ctx));
+ for (const h of textRules.csrfForms(file, text, csrfOptions)) raw.push(makeFinding(h.ruleId, { ...h, file: file.rel }, ctx));
+ for (const d of detected) {
+ if (!d.pack.templateRules) continue;
+ for (const h of d.pack.templateRules(file, text)) raw.push(makeFinding(h.ruleId, { ...h, file: file.rel }, ctx));
+ }
for (const h of textRules.domRules(file, text)) raw.push(makeFinding(h.ruleId, { ...h, file: file.rel }, ctx));
for (const h of textRules.httpUrls(file, lines)) raw.push(makeFinding(h.ruleId, { ...h, file: file.rel, confidence: 'medium' }, ctx));
}
@@ -165,12 +179,22 @@ module.exports = {
}
if (taint.exhausted) notices.add('info', `The analysis budget was reached for ${taint.exhausted} entry file(s); results for them may be incomplete.`);
+ const envFiles = project.files.filter((f) => /^\.env(\.|$)/.test(f.name)).map((f) => ({ rel: f.rel, text: cache.text(f.abs) || '' }));
+ for (const d of detected) {
+ const hits = [
+ ...(d.pack.projectRules ? d.pack.projectRules(phpFiles, envFiles) : []),
+ ...(d.pack.configRules ? d.pack.configRules(phpFiles) : []),
+ ];
+ for (const h of hits) raw.push(makeFinding(h.ruleId, h, ctx));
+ }
+
const usesPhp = project.files.some((f) => EXTENSIONS.includes(f.ext));
for (const h of projectRules.exposedFiles(project)) raw.push(makeFinding(h.ruleId, h, ctx));
for (const h of projectRules.htaccessRules(project, { usesPhp })) raw.push(makeFinding(h.ruleId, h, ctx));
// runtime checks
const environment = {};
+ if (detected.length) environment.frameworks = Object.fromEntries(detected.map((d) => [d.pack.name, d.info.version || (d.info.kind ? d.info.kind : null)]));
const phpBin = resolvePhpBin(config, phpConfig);
const runtime = phpRuntime(phpBin, new Date());
if (runtime.notice) notices.add('warning', runtime.notice);
diff --git a/langs/php/rules/registry.js b/langs/php/rules/registry.js
index e12ca28..920cae9 100644
--- a/langs/php/rules/registry.js
+++ b/langs/php/rules/registry.js
@@ -110,6 +110,18 @@ const RULES = [
R('JS-CODE-001', 'JavaScript code built from untrusted data', 'CWE-95', 'A05', 'A03', 'high', 'xss#dom-xss', 'xss',
'eval(), new Function() or string timers execute data that comes from the URL or other untrusted input.'),
+ // framework rules
+ R('PHP-XSS-002', 'Unescaped template output', 'CWE-79', 'A05', 'A03', 'medium', 'xss#template-escaping', 'xss',
+ 'A template prints a value without escaping (Blade {!! !!}, Twig |raw or autoescape off).'),
+ R('PHP-CONF-003', 'Debug mode enabled', 'CWE-489', 'A02', 'A05', 'medium', 'misconfiguration#debug-mode', 'misconfig',
+ 'Framework debug mode is switched on; debug pages reveal source code, configuration values and secrets.'),
+ R('PHP-MASS-001', 'Mass assignment from request data', 'CWE-915', 'A08', 'A08', 'medium', 'integrity#mass-assignment', 'other',
+ 'Request data is assigned to model attributes without an allow-list, so users can set fields such as is_admin.'),
+ R('PHP-WP-001', 'WordPress action handler without nonce or capability check', 'CWE-352', 'A01', 'A01', 'high', 'access-control#wordpress-nonces', 'csrf',
+ 'An AJAX or admin-post handler changes data without verifying a nonce and the user\'s capabilities.'),
+ R('PHP-CSRF-002', 'CSRF protection disabled for routes', 'CWE-352', 'A01', 'A01', 'low', 'access-control#csrf', 'csrf',
+ 'Routes are excluded from CSRF verification. Make sure they cannot be used to change state for logged-in users.'),
+
// runtime rules
R('PHP-COMP-001', 'PHP version is end of life', 'CWE-1104', 'A03', 'A06', 'high', 'components#runtime-versions', 'components',
'The PHP version no longer receives security fixes.'),
diff --git a/langs/php/rules/text-rules.js b/langs/php/rules/text-rules.js
index b603170..ab7eaa9 100644
--- a/langs/php/rules/text-rules.js
+++ b/langs/php/rules/text-rules.js
@@ -34,8 +34,11 @@ function lineFromStarts(starts, index) {
const TOKEN_FIELD = /name\s*=\s*["']?[^"'\s>]*(csrf|xsrf|token|nonce|authenticity|_wpnonce|form_key|__requestverificationtoken)/i;
const TOKEN_HELPER = /@csrf|csrf_field\s*\(|csrf_token\s*\(|wp_nonce_field\s*\(|\{\{\s*csrf|form_token\s*\(|security->get_csrf|\$this->Form->|form_open\s*\(|->csrf|check_admin_referer|\bnonce\b|getCsrf|csrfToken|_token/i;
-function csrfForms(file, text) {
+function csrfForms(file, text, { helpers = [], fileWide = false } = {}) {
if (!TEMPLATE_EXT.has(file.ext) && !file.name.endsWith('.blade.php')) return [];
+ const extra = helpers.filter(Boolean);
+ // frameworks such as WordPress print nonce fields through helper calls elsewhere in the file
+ if (fileWide && extra.some((re) => re.test(text))) return [];
const hits = [];
const re = /', re.lastIndex);
const body = text.slice(re.lastIndex, end === -1 ? text.length : end);
- if (TOKEN_FIELD.test(body) || TOKEN_HELPER.test(body) || TOKEN_HELPER.test(attrs)) continue;
+ if (TOKEN_FIELD.test(body) || TOKEN_HELPER.test(body) || TOKEN_HELPER.test(attrs) || extra.some((re) => re.test(body))) continue;
hits.push({ ruleId: 'PHP-CSRF-001', line: lineAt(text, m.index), column: 1 });
}
return hits;
diff --git a/langs/php/taint/catalog.js b/langs/php/taint/catalog.js
index 1c7b672..cf96ef0 100644
--- a/langs/php/taint/catalog.js
+++ b/langs/php/taint/catalog.js
@@ -378,7 +378,16 @@ function call(callee, args, e, ctx) {
return { value: el.t ? V.step(V.join(el, glue && glue.t ? glue : null), line, name) : V.CLEAN };
}
if (name === 'explode' || name === 'str_split' || name === 'preg_split' || name === 'mb_str_split') return { value: arrayOf(name === 'explode' ? args[1] : a0, line, name) };
- if (name === 'array_map') return { value: arrayOf(elementOf(args[1]), line, 'array_map') };
+ if (name === 'array_map') {
+ // a named callback (e.g. 'intval', 'esc_html') is applied to every element
+ const cb = str(a0);
+ let element = elementOf(args[1]);
+ if (cb && element.t && ctx.callCatalog) {
+ const r = ctx.callCatalog(`fn:${cb.toLowerCase().replace(/^\\/, '')}`, [element], line);
+ if (r && r.value && !(r.sinks && r.sinks.length)) element = r.value;
+ }
+ return { value: element.t ? arrayOf(element, line, 'array_map') : { t: false, arr: new Map([['*', element]]) } };
+ }
if (ARRAY_FNS.includes(name)) {
const joined = V.joinAll(args.map((x) => (x && x.arr ? V.joinAll([...x.arr.values()]) : x || V.CLEAN)));
return { value: joined.t ? { ...propagate(joined, line, name), arr: new Map([['*', propagate(joined)]]) } : { t: false, arr: a0 && a0.arr ? new Map(a0.arr) : new Map() } };
diff --git a/test/fixtures/laravel.expect.json b/test/fixtures/laravel.expect.json
new file mode 100644
index 0000000..795a1fc
--- /dev/null
+++ b/test/fixtures/laravel.expect.json
@@ -0,0 +1,4 @@
+{
+ "files": { ".env": ["CWE-489", "CWE-538"] },
+ "project": []
+}
diff --git a/test/fixtures/laravel/.env b/test/fixtures/laravel/.env
new file mode 100644
index 0000000..a29aa7a
--- /dev/null
+++ b/test/fixtures/laravel/.env
@@ -0,0 +1,3 @@
+APP_NAME=Shop
+APP_ENV=production
+APP_DEBUG=true
diff --git a/test/fixtures/laravel/app/Http/Controllers/UserController.php b/test/fixtures/laravel/app/Http/Controllers/UserController.php
new file mode 100644
index 0000000..a97041c
--- /dev/null
+++ b/test/fixtures/laravel/app/Http/Controllers/UserController.php
@@ -0,0 +1,25 @@
+input('name');
+ $users = DB::select("SELECT * FROM users WHERE name = '$name'"); // @expect CWE-89
+ $sorted = User::query()->orderByRaw($request->query('sort'))->get(); // @expect CWE-89
+ $safe = DB::select('SELECT * FROM users WHERE name = ?', [$name]);
+ return view('users.index', ['users' => $users, 'safe' => $safe, 'sorted' => $sorted]);
+ }
+
+ public function store(Request $request)
+ {
+ $user = User::create($request->all()); // @expect CWE-915
+ return redirect($request->input('next')); // @expect CWE-601
+ }
+}
diff --git a/test/fixtures/laravel/app/Http/Middleware/VerifyCsrfToken.php b/test/fixtures/laravel/app/Http/Middleware/VerifyCsrfToken.php
new file mode 100644
index 0000000..a4bcd7b
--- /dev/null
+++ b/test/fixtures/laravel/app/Http/Middleware/VerifyCsrfToken.php
@@ -0,0 +1,12 @@
+{{ $user->name }}
+{!! $user->bio !!}
{{-- @expect CWE-79 --}}
+{!! request('q') !!}
{{-- @expect CWE-79 --}}
+
+
diff --git a/test/fixtures/symfony/composer.json b/test/fixtures/symfony/composer.json
new file mode 100644
index 0000000..1ffbae6
--- /dev/null
+++ b/test/fixtures/symfony/composer.json
@@ -0,0 +1,8 @@
+{
+ "require": {
+ "php": ">=8.2",
+ "symfony/framework-bundle": "^7.1",
+ "twig/twig": "^3.0",
+ "doctrine/dbal": "^4.0"
+ }
+}
diff --git a/test/fixtures/symfony/src/Controller/ProductController.php b/test/fixtures/symfony/src/Controller/ProductController.php
new file mode 100644
index 0000000..139bc58
--- /dev/null
+++ b/test/fixtures/symfony/src/Controller/ProductController.php
@@ -0,0 +1,19 @@
+query->get('category');
+ $rows = $conn->executeQuery("SELECT * FROM product WHERE category = '$category'"); // @expect CWE-89
+ $page = $request->query->getInt('page');
+ $more = $conn->executeQuery('SELECT * FROM product LIMIT 10 OFFSET ' . ($page * 10));
+ return new Response('' . $request->query->get('title') . '
'); // @expect CWE-79
+ }
+}
diff --git a/test/fixtures/symfony/templates/product/show.html.twig b/test/fixtures/symfony/templates/product/show.html.twig
new file mode 100644
index 0000000..3c34149
--- /dev/null
+++ b/test/fixtures/symfony/templates/product/show.html.twig
@@ -0,0 +1,2 @@
+{{ product.name }}
+{{ product.description|raw }}
{# @expect CWE-79 #}
diff --git a/test/fixtures/wordpress-plugin/my-plugin.php b/test/fixtures/wordpress-plugin/my-plugin.php
new file mode 100644
index 0000000..0258153
--- /dev/null
+++ b/test/fixtures/wordpress-plugin/my-plugin.php
@@ -0,0 +1,40 @@
+query("INSERT INTO {$wpdb->prefix}reviews (title) VALUES ('$title')"); // @expect CWE-89
+ wp_die();
+}
+
+function er_delete_review()
+{
+ check_ajax_referer('delete_review');
+ if (!current_user_can('manage_options')) {
+ wp_die();
+ }
+ global $wpdb;
+ $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}reviews WHERE id = %d", $_POST['id']));
+ wp_die();
+}
+
+function er_render_box()
+{
+ echo '' . esc_html($_GET['heading']) . '
';
+ echo 'Link';
+ echo '' . $_GET['note'] . '
'; // @expect CWE-79
+}
+
+function er_go()
+{
+ wp_redirect($_GET['to']); // @expect CWE-601
+ exit;
+}
diff --git a/test/fixtures/wordpress-plugin/views/settings-page.php b/test/fixtures/wordpress-plugin/views/settings-page.php
new file mode 100644
index 0000000..46dd27c
--- /dev/null
+++ b/test/fixtures/wordpress-plugin/views/settings-page.php
@@ -0,0 +1,6 @@
+
+
+
diff --git a/test/unit/php-fixtures.test.js b/test/unit/php-fixtures.test.js
index eeeea97..6135fa6 100644
--- a/test/unit/php-fixtures.test.js
+++ b/test/unit/php-fixtures.test.js
@@ -76,3 +76,16 @@ test('cross-file analysis: includes, define() paths, helpers in other files', ()
const cmd = report.findings.find((f) => f.ruleId === 'PHP-CMDI-001');
assert.ok(cmd && cmd.trace.some((t) => /\$_GET\['dir'\]/.test(t.note)), 'value set in an included file reaches the sink');
});
+
+for (const [name, framework] of [['laravel', 'Laravel'], ['wordpress-plugin', 'WordPress'], ['symfony', 'Symfony/Twig']]) {
+ test(`framework pack: ${framework}`, () => {
+ const dir = path.join(REPO, 'test', 'fixtures', name);
+ const { truth, report, missing } = checkCorpus(dir);
+ assert.deepStrictEqual(missing.map((m) => `${m.file}:${m.line} ${m.cwes.join('|')}`), []);
+ for (const e of truth.fileLevel) assert.ok(report.findings.some((f) => f.file === e.file && e.cwes.includes(f.cwe)), `${e.file} ${e.cwes}`);
+ assert.ok(report.environment.frameworks && Object.prototype.hasOwnProperty.call(report.environment.frameworks, framework), `${framework} detected`);
+ const unexpected = report.findings.filter((f) => f.file && f.line && ['PHP-SQLI-001', 'PHP-XSS-001', 'PHP-XSS-002', 'PHP-REDIR-001', 'PHP-CSRF-001'].includes(f.ruleId) &&
+ !truth.expectations.some((e) => e.file === f.file && e.line === f.line));
+ assert.deepStrictEqual(unexpected.map((f) => `${f.file}:${f.line} ${f.ruleId}`), [], 'no findings on protected code');
+ });
+}
From 74f511c665d3fec9c65a506e3d97418f1cb0e4e8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tar=C4=B1k=20Seyceri?=
Date: Fri, 13 Nov 2026 20:36:15 +0300
Subject: [PATCH 08/12] feat: dependency, secrets and runtime lifecycle checks
- Component inventory from composer.lock, package-lock.json (v1-v3) and
yarn.lock, plus JavaScript libraries copied into the project, shown in
a new Components section of every report.
- Bundled advisory data for common front-end libraries; --online checks
every package against OSV.dev (names and versions only, cached 24 h).
- End-of-life checks for frameworks and libraries, development packages
installed in production and abandoned Composer packages.
- Secrets detection for provider tokens, private keys, JWTs, connection
URLs and secret assignments in code and configuration files, masked
in every report format.
- Lifecycle data for more products, refreshable with --online or
npm run update-data.
Co-Authored-By: Claude Opus 5.5
---
.gitignore | 3 +
CHANGELOG.md | 16 +-
config.js | 1 +
core/http.js | 79 +
core/lifecycle.js | 40 +-
core/report/console.js | 2 +
core/report/html.js | 4 +
core/report/markdown.js | 5 +
core/report/model.js | 19 +-
core/rules/common.js | 23 +
core/secrets.js | 208 ++
core/supply/eol.js | 65 +
core/supply/index.js | 197 ++
core/supply/jslibs.js | 79 +
core/supply/lockfiles.js | 152 +
core/supply/osv.js | 143 +
core/supply/semver.js | 53 +
data/eol.json | 1251 +++++++-
data/js-libs.json | 2682 ++++++++++++++++++
langs/php/guides/authentication.md | 22 +
langs/php/guides/components.md | 10 +
langs/php/index.js | 36 +-
langs/php/rules/ast-rules.js | 4 +-
langs/php/rules/registry.js | 5 +
langs/php/runtime/checks.js | 8 +-
package.json | 3 +-
scripts/update-data.js | 46 +
test/fixtures/php-vulnerable-app.expect.json | 7 +-
test/unit/supply-secrets.test.js | 247 ++
29 files changed, 5380 insertions(+), 30 deletions(-)
create mode 100644 core/http.js
create mode 100644 core/rules/common.js
create mode 100644 core/secrets.js
create mode 100644 core/supply/eol.js
create mode 100644 core/supply/index.js
create mode 100644 core/supply/jslibs.js
create mode 100644 core/supply/lockfiles.js
create mode 100644 core/supply/osv.js
create mode 100644 core/supply/semver.js
create mode 100644 data/js-libs.json
create mode 100644 scripts/update-data.js
create mode 100644 test/unit/supply-secrets.test.js
diff --git a/.gitignore b/.gitignore
index 24c7a90..4c26204 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,3 +13,6 @@ Thumbs.db
report.html
# Benchmark datasets and scratch output (downloaded, never committed)
bench/.work/
+
+# ASST cache (--online lookups)
+.asst-cache/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 861e3ec..8d44069 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,13 +14,27 @@ ASST 2.0 is a major upgrade built on the foundation of the original thesis relea
- Cross-file analysis: `include`/`require` targets are resolved (including `__DIR__`, `define()`d paths and file names chosen in a `switch`) and run in the including scope, and functions and classes are resolved across the whole project. A vulnerability inside a shared helper lists the entry scripts that reach it.
- Framework packs for Laravel, WordPress and Symfony, detected automatically. Framework request objects, escaping helpers (`e()`, `esc_html()`, `esc_attr()`, `esc_url()`, `absint()`, `sanitize_*()`), query builders, `$wpdb` and HTTP clients are part of the data-flow analysis. New checks cover raw Blade (`{!! !!}`) and Twig (`|raw`, `autoescape false`) output, mass assignment (`$guarded = []` with `create($request->all())`), debug mode in `.env`, `config/app.php` and `wp-config.php`, CSRF exemptions in `VerifyCsrfToken`, `$wpdb` queries built without `prepare()`, and WordPress AJAX/admin-post handlers without nonce and capability checks. CSRF checks recognize `@csrf`, `csrf_field()`, `wp_nonce_field()` and Symfony `csrf_token()`. The report header lists the detected frameworks.
- Callback-aware data flow for `array_map()` with built-in callbacks such as `intval` or `htmlspecialchars`.
+- Software supply chain checks. Every report gets a Components section listing:
+ - the dependencies from `composer.lock`, `package-lock.json` (v1–v3) and `yarn.lock`;
+ - JavaScript libraries copied into the project: jQuery, jQuery UI, Bootstrap, AngularJS, Lodash, Underscore, Moment.js, Handlebars, Vue, DOMPurify, TinyMCE and Knockout.
+
+ Published advisories for these libraries ship with ASST. With `--online` (or `ONLINE_CHECKS: true`), every package is checked against OSV.dev. Only package names and versions are sent, and answers are cached for a day.
+- End-of-life checks for frameworks and libraries: Laravel, Symfony, Drupal, WordPress, jQuery, Bootstrap, AngularJS and Vue. Also new: detection of development packages installed in a production `vendor/` folder, and of abandoned Composer packages.
+- Secrets detection covers:
+ - API keys and tokens with well-known formats: AWS, GitHub, GitLab, Slack, Stripe, Google, SendGrid, npm, OpenAI and Anthropic;
+ - private keys and JSON Web Tokens;
+ - passwords in connection URLs;
+ - password, secret and key assignments in code, `.env` files and configuration files.
+
+ Secrets are masked everywhere in the reports, including the code snippets of other findings.
+- `npm run update-data` refreshes the bundled lifecycle and advisory data. `--online` also refreshes lifecycle dates from endoflife.date during a scan.
- Findings are mapped to the OWASP Top 10:2025 (with the 2021 category) and to CWE, and carry a severity, a confidence level and a code snippet.
- Interactive HTML report: one self-contained file that works offline, with severity tiles, search, filters (severity, confidence, OWASP category), grouping by category/file/rule, code snippets with the line highlighted, data-flow traces, dark mode and print layout. Content is fully HTML-escaped and protected by a strict Content-Security-Policy.
- SARIF 2.1.0 output (`--format sarif`) for GitHub code scanning and IDE viewers, with CWE/OWASP tags, security-severity scores, stable fingerprints and data-flow code flows.
- Markdown summary (`--format md`) for pull-request comments and CI job summaries.
- JSON report (`--format json`) with a versioned schema.
- Baseline comparison: `--update-baseline` records the current findings, and `--baseline` marks later findings as new or unchanged and lists fixed ones in every report format.
-- Up-to-date lifecycle data (`data/eol.json`) for PHP, MySQL and MariaDB; stored passwords are classified by hash format (bcrypt/argon2, fast hashes, plain text) and the database server version is checked against its support dates.
+- Up-to-date lifecycle data (`data/eol.json`) for PHP, MySQL, MariaDB, Node.js and the frameworks and libraries above; stored passwords are classified by hash format (bcrypt/argon2, fast hashes, plain text) and the database server version is checked against its support dates.
- New options: `--second-order` (treat session data, files, database rows and command output as untrusted), `--min-severity`, `--min-confidence`, `--fail-on` for CI, `--rules`/`--disable-rules`, `--baseline`/`--update-baseline`, and inline `asst-ignore[RULE-ID]` comments.
- Command-line options (`node main.js --help`): choose the folder to scan (`--path`), report location (`--out`), exclusions (`--exclude`), dependency folders (`--include-vendor`), PHP binary (`--php-bin`), skip database checks (`--no-db`), quiet and no-color modes. Running `node main.js` without options works exactly as before.
- `.asstignore` file and `EXCLUDE_PATHS` setting to skip paths; `YOUR_WEBAPP_DBMS_PORT` setting; `ASST_DB_PASSWORD` (and `ASST_DB_HOST`, `ASST_DB_USER`, `ASST_DB_NAME`, `ASST_DB_PORT`, `ASST_PHP_BIN`) environment variables so credentials do not have to be stored in a file.
diff --git a/config.js b/config.js
index de374eb..8774bca 100644
--- a/config.js
+++ b/config.js
@@ -9,4 +9,5 @@ module.exports = {
// Optional settings (ASST v2). They can stay as they are; command-line options override them (node main.js --help).
EXCLUDE_PATHS: [], // folders/files to skip, e.g. ["tests/**", "*.min.js"] // vendor/ and node_modules/ are skipped by default
+ ONLINE_CHECKS: false, // true = check dependencies on OSV.dev and refresh end-of-life dates from endoflife.date (only package names and versions are sent; same as --online)
};
diff --git a/core/http.js b/core/http.js
new file mode 100644
index 0000000..a438922
--- /dev/null
+++ b/core/http.js
@@ -0,0 +1,79 @@
+'use strict';
+/*
+ * Minimal HTTP(S) client on Node's built-in modules (no global fetch, which prints an
+ * experimental warning on Node 18). Timeouts, a response size cap and JSON helpers.
+ */
+const http = require('http');
+const https = require('https');
+const { URL } = require('url');
+
+const USER_AGENT = 'OWASP-ASST (+https://github.com/OWASP/ASST)';
+
+/**
+ * @param {string} url
+ * @param {{method?:string, headers?:object, body?:string|Buffer, timeoutMs?:number, maxBytes?:number, rejectUnauthorized?:boolean}} opts
+ * @returns {Promise<{status:number, headers:object, body:Buffer, url:string}>}
+ */
+function request(url, opts = {}) {
+ const u = new URL(url);
+ const mod = u.protocol === 'https:' ? https : u.protocol === 'http:' ? http : null;
+ if (!mod) return Promise.reject(new Error(`unsupported protocol ${u.protocol}`));
+ const method = (opts.method || 'GET').toUpperCase();
+ const timeoutMs = opts.timeoutMs || 15000;
+ const maxBytes = opts.maxBytes || 8 * 1024 * 1024;
+ const headers = { 'user-agent': USER_AGENT, accept: '*/*', ...(opts.headers || {}) };
+ if (opts.body !== undefined) headers['content-length'] = Buffer.byteLength(opts.body);
+ return new Promise((resolve, reject) => {
+ const req = mod.request(u, { method, headers, rejectUnauthorized: opts.rejectUnauthorized !== false }, (res) => {
+ const chunks = [];
+ let size = 0;
+ res.on('data', (c) => {
+ size += c.length;
+ if (size > maxBytes) {
+ req.destroy(new Error(`response from ${u.host} is larger than ${maxBytes} bytes`));
+ return;
+ }
+ chunks.push(c);
+ });
+ res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks), url: u.href }));
+ res.on('error', reject);
+ });
+ req.setTimeout(timeoutMs, () => req.destroy(new Error(`request to ${u.host} timed out after ${timeoutMs} ms`)));
+ req.on('error', reject);
+ if (opts.body !== undefined) req.write(opts.body);
+ req.end();
+ });
+}
+
+async function getJson(url, opts = {}) {
+ const res = await request(url, { ...opts, headers: { accept: 'application/json', ...(opts.headers || {}) } });
+ if (res.status < 200 || res.status >= 300) throw new Error(`${new URL(url).host} answered HTTP ${res.status}`);
+ return JSON.parse(res.body.toString('utf8'));
+}
+
+async function postJson(url, data, opts = {}) {
+ const res = await request(url, {
+ ...opts,
+ method: 'POST',
+ body: JSON.stringify(data),
+ headers: { accept: 'application/json', 'content-type': 'application/json', ...(opts.headers || {}) },
+ });
+ if (res.status < 200 || res.status >= 300) throw new Error(`${new URL(url).host} answered HTTP ${res.status}`);
+ return JSON.parse(res.body.toString('utf8'));
+}
+
+/** Runs async tasks with a concurrency limit, keeping result order. */
+async function mapLimit(items, limit, fn) {
+ const out = new Array(items.length);
+ let next = 0;
+ const worker = async () => {
+ while (next < items.length) {
+ const i = next++;
+ out[i] = await fn(items[i], i);
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
+ return out;
+}
+
+module.exports = { request, getJson, postJson, mapLimit, USER_AGENT };
diff --git a/core/lifecycle.js b/core/lifecycle.js
index a3fb541..018de47 100644
--- a/core/lifecycle.js
+++ b/core/lifecycle.js
@@ -1,6 +1,7 @@
'use strict';
/*
- * Software lifecycle lookups (end of life / security support) from data/eol.json.
+ * Software lifecycle lookups (end of life / security support) from data/eol.json,
+ * or from fresher data downloaded with --online (see core/supply/eol.js).
*/
const fs = require('fs');
const path = require('path');
@@ -9,16 +10,21 @@ const DATA_FILE = path.join(__dirname, '..', 'data', 'eol.json');
let cache = null;
function load(file = DATA_FILE) {
- if (!cache || file !== DATA_FILE) {
- const data = JSON.parse(fs.readFileSync(file, 'utf8'));
- if (file !== DATA_FILE) return data;
- cache = data;
- }
+ if (file !== DATA_FILE) return JSON.parse(fs.readFileSync(file, 'utf8'));
+ if (!cache) cache = JSON.parse(fs.readFileSync(DATA_FILE, 'utf8'));
return cache;
}
+/** Uses newer lifecycle data for the rest of the run (products missing from it keep the bundled data). */
+function useData(data) {
+ if (!data || !data.products) return;
+ const base = load();
+ if (data.asOf && base.asOf && data.asOf < base.asOf) return;
+ cache = { ...base, asOf: data.asOf || base.asOf, source: data.source || base.source, products: { ...base.products, ...data.products } };
+}
+
function cycleFor(list, version) {
- const parts = String(version).split(/[.-]/);
+ const parts = String(version).replace(/^v/, '').split(/[.-]/);
const candidates = [parts.slice(0, 2).join('.'), parts[0]];
for (const c of candidates) {
const hit = list.find((x) => x.cycle === c);
@@ -27,6 +33,18 @@ function cycleFor(list, version) {
return null;
}
+const isDate = (v) => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}/.test(v);
+
+/** eol: an ISO date, true (end of life reached), false (not reached) or null (unknown). */
+function eolReached(value, iso) {
+ return value === true || (isDate(value) && value <= iso);
+}
+
+/** support: an ISO date, true (still in active support), false (active support ended) or null. */
+function supportEnded(value, iso) {
+ return value === false || (isDate(value) && value <= iso);
+}
+
/**
* @returns {{product, version, cycle, eol, support, status:'eol'|'security-only'|'supported'|'unknown', asOf}}
*/
@@ -36,9 +54,9 @@ function lifecycle(product, version, today = new Date(), data = load()) {
const iso = today.toISOString().slice(0, 10);
if (!entry) return { product, version, cycle: null, eol: null, support: null, status: 'unknown', asOf: data.asOf };
let status = 'supported';
- if (entry.eol && entry.eol <= iso) status = 'eol';
- else if (entry.support && entry.support <= iso) status = 'security-only';
- return { product, version, cycle: entry.cycle, eol: entry.eol, support: entry.support, status, asOf: data.asOf };
+ if (eolReached(entry.eol, iso)) status = 'eol';
+ else if (supportEnded(entry.support, iso)) status = 'security-only';
+ return { product, version, cycle: entry.cycle, eol: entry.eol, support: entry.support, latest: entry.latest || null, status, asOf: data.asOf };
}
-module.exports = { lifecycle, load, DATA_FILE };
+module.exports = { lifecycle, load, useData, DATA_FILE };
diff --git a/core/report/console.js b/core/report/console.js
index b4c60b4..14f948d 100644
--- a/core/report/console.js
+++ b/core/report/console.js
@@ -24,6 +24,8 @@ function print(model, { quiet, reportFiles, maxListed = 15 }) {
}
const counts = SEVERITIES.filter((sev) => s.bySeverity[sev]).map((sev) => ansi.paint(`${s.bySeverity[sev]} ${sev}`, COLOR[sev], 'bold'));
out.push(`Findings: ${s.total}${counts.length ? ` (${counts.join(', ')})` : ''}`);
+ const inv = model.inventory && model.inventory.packages;
+ if (inv && inv.length) out.push(ansi.paint(`Components: ${inv.length} (${inv.filter((c) => c.advisories).length} with advisories, ${inv.filter((c) => c.lifecycle === 'eol').length} end of life; advisories from ${model.inventory.advisorySource})`, 'gray'));
if (s.hidden) out.push(ansi.paint(`${s.hidden} lower-confidence or lower-severity findings hidden (see --min-confidence / --min-severity).`, 'gray'));
if (s.suppressed) out.push(ansi.paint(`${s.suppressed} findings suppressed by asst-ignore comments.`, 'gray'));
if (s.fixed !== null) out.push(ansi.paint(`Compared with the baseline: ${model.findings.filter((f) => f.baseline === 'new').length} new, ${s.fixed} fixed.`, 'cyan'));
diff --git a/core/report/html.js b/core/report/html.js
index 789fb54..c4c1dae 100644
--- a/core/report/html.js
+++ b/core/report/html.js
@@ -185,6 +185,7 @@ footer { display:flex; flex-wrap:wrap; gap:12px; justify-content:space-between;
.panel li { margin:4px 0; }
.notice.warning { color:var(--medium); }
.fixed li { text-decoration:line-through; color:var(--muted); }
+.inv { width:100%; border-collapse:collapse; margin-top:8px; font-size:13px; } .inv th, .inv td { text-align:left; padding:3px 8px; border-bottom:1px solid var(--border); } .inv .where { margin:0; }
@media print { .bar, #theme, #expand { display:none; } .finding { break-inside:avoid; } a { color:inherit; } }
`;
@@ -203,6 +204,8 @@ function render(model) {
if (env.database) envRows.push(`Database: ${esc(env.database.version)}`);
for (const ps of env.passwordStorage || []) envRows.push(`Password storage in ${esc(ps.table)}: ${esc(ps.kind || ps.error)}`);
for (const [k, v] of Object.entries(env.frameworks || {})) envRows.push(`Framework: ${esc(k)}${v ? ` ${esc(v)}` : ''}`);
+ const inv = model.inventory && model.inventory.packages ? model.inventory.packages : [];
+ const invRows = inv.slice(0, 1000).map((c) => `| ${esc(c.name)} | ${esc(c.version)} | ${c.bundled ? 'bundled file' : c.dev ? 'dev dependency' : 'dependency'} | ${esc(c.file || '')} | ${c.advisories === null || c.advisories === undefined ? '-' : c.advisories ? `${esc(c.advisories)}` : '0'} | ${c.lifecycle === 'eol' ? 'end of life' : esc(c.lifecycle || '')} |
`).join('');
const notices = model.notices.map((n) => `${n.title ? `${esc(n.title)}: ` : ''}${esc(n.message)}${n.pdf ? ` Guide` : ''}`).join('');
const fixed = (model.fixed || []).map((f) => `${esc(f.title)} ${esc(f.file || '')}${f.line ? `:${esc(f.line)}` : ''} · ${esc(f.ruleId)}`).join('');
const catOptions = cats.map((c) => ``).join('');
@@ -242,6 +245,7 @@ ${byCat || 'No findings at the current reporting threshold.
'}