mirror of
https://github.com/elicpeter/nyx.git
synced 2026-06-12 19:55:14 +02:00
Release/0.5.0 (#35)
* feat: Introduce function-scoped variable interning for state analysis with new tests and fixtures * feat: Add Phase 26 symbolic execution enhancements with bitwise operator support, abstract interpretation refinements, and new taint analysis tests * feat: Refine state analysis to handle factory-pattern resource returns with mixed-path tests and leak detection enhancements * feat: Add Phase 27 debug views with symbolic execution, abstract interpretation, SSA, and call graph viewers; integrate with debug layout and styles * feat: Add Phase 31 type-qualified symbolic resolution with receiver-based callee disambiguation and testing * feat: Extend symbolic execution with state iteration, enhanced debug views, and debounced input handling * feat: Add Phase 13 resource and auth pattern extensions with new tests and fixtures * feat: Introduce CFG debug graph renderer with compact mode, toolbar, and DAG layout integration * feat: Add Phase 28 encoding and decoding transform modeling with structural symex enhancements and new taint analysis tests * feat: Extend abstract interpretation with type facts and constant value tracking in debug views and server logic * feat: Add linear path handling and witness extraction to symbolic execution with Phase 28 transform mismatch detection * feat: Refine Go auth and sanitizer handling with enhanced rules, state updates, and benchmark improvements * feat: Enable auth-state analysis by default and update relevant tests in benchmark config * test: Update state_tests to reflect default enablement of auth-state analysis and add auth suppression test * docs: update CHANGELOG.md * feat: Introduce per-index taint tracking in `HeapState` with `HeapSlot`, overflow handling, and revised SSA transfers * feat: Introduce C/C++ language labels and refine heap state tracking in SSA transfers * feat: Implement per-index array slot tracking in symbolic heap with overflow collapse * feat: Add implicit definition handling for uninitialized declarations in SSA value allocation * feat: Refactor function parameters and constants for improved clarity and maintainability * refactor: Reorder module imports and improve formatting for consistency * refactor: Fix formatting erorrs * refactor: Fix clippy warnings * refactor: Fix fmt warnings (again) * chore: Update dependencies and improve feature configuration * Add comprehensive tests for undertested modules (#36) (COPILOT) * Add comprehensive tests for undertested modules Co-authored-by: elicpeter <54954007+elicpeter@users.noreply.github.com> Agent-Logs-Url: https://github.com/elicpeter/nyx/sessions/f3fc877e-f386-49ba-9793-fc93d3805083 * Add comprehensive tests for ext, project, walk, and errors modules Co-authored-by: elicpeter <54954007+elicpeter@users.noreply.github.com> Agent-Logs-Url: https://github.com/elicpeter/nyx/sessions/f3fc877e-f386-49ba-9793-fc93d3805083 --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: elicpeter <54954007+elicpeter@users.noreply.github.com> * chore: Update dependencies and improve feature configuration * fix: formatting errors in new tests * chore: Update license list in about.toml * chore: made functions input inline * chore: updated cfg graph to take up the full page * chore: add Prettier configuration and update code formatting * Add frontend test suite with Vitest (111 tests) (#37) * Add Vitest test suite for frontend - 111 tests across utils, components, hooks, and graph utilities Co-authored-by: elicpeter <54954007+elicpeter@users.noreply.github.com> Agent-Logs-Url: https://github.com/elicpeter/nyx/sessions/7cf0dba2-ecff-4740-ba4d-92717e74a0b7 * ci: add frontend test step to CI workflow Co-authored-by: elicpeter <54954007+elicpeter@users.noreply.github.com> Agent-Logs-Url: https://github.com/elicpeter/nyx/sessions/5bc0ac9f-0a32-4d03-9cb7-7a15aea53fca --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: elicpeter <54954007+elicpeter@users.noreply.github.com> * chore: simplify array initialization in test files for consistency * ran typecheck * feat: add AnalysisWorkspace component and integrate it into CfgViewerPage * feat: update routing in AppLayout and improve empty state message in ExplorerPage * feat: enhance scan progress tracking with additional metrics and stages * feat: update license information and add license check script * feat: implement cross-file symbolic execution with callee body persistence * feat: replace dagre graphs with Graphology + ELK + Sigma for more advanced call stack and cfg rendering * feat: ensure CFG function view is scoped to the selected function, preventing bleed into sibling functions * feat: enhance resource tracking with proxy method summaries and improve finding extraction * feat: add terminal function exit detection for accurate resource leak analysis * feat: add warnings for loops and functions without bodies to improve error recovery * feat: update lambda expression handling to ensure proper function classification and control flow * feat: remove bounded formatting/string ops and add JSON.parse sanitizer for improved data handling * feat: add inline return taint analysis and regression tests for improved security checks * feat: add engine version management and migration handling for database schema updates * feat: enhance first_call_ident to skip nested function bodies and add regression tests * feat: enhance callee name resolution with two-segment normalization and disambiguation * feat: add cross-file context flags and debug assertions for taint analysis * feat: refactor taint analysis structure to unify context handling and improve clarity * feat: enhance dead code elimination to preserve Sink, Source, and Sanitizer labels with new tests * docs: updated CHANGELOG.md * fmt: formatting fixes * fix: fixed frontend formatting and lint warnings * fix: optimized ci * fix: optimized ci * Add comprehensive multi-file test coverage to Nyx (#38) * Initial checklist for multi-file test suite expansion Agent-Logs-Url: https://github.com/elicpeter/nyx/sessions/e550cb88-9767-4442-94d4-101bf5bb0e23 Co-authored-by: elicpeter <54954007+elicpeter@users.noreply.github.com> * Add 12 new multi-file test fixtures with TP/TN/near-miss coverage Agent-Logs-Url: https://github.com/elicpeter/nyx/sessions/e550cb88-9767-4442-94d4-101bf5bb0e23 Co-authored-by: elicpeter <54954007+elicpeter@users.noreply.github.com> * deleted root repo * rebuilt to test for regressions --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: elicpeter <54954007+elicpeter@users.noreply.github.com> Co-authored-by: elipeter <elicpeter@gmail.com> * feat: enhance import alias resolution and taint tracking * feat: implement security hardening with CSRF protection and path validation * feat: add support for import alias bindings in Python, PHP, and Rust * feat: enhance CFG analysis modes and improve code readability * feat: add detection for parameterized SQL queries to enhance security * feat: add safe internal redirect handling and enhance session destroy validation * feat: implement security improvements by addressing vulnerabilities in execAsync, session management, and file downloads * feat: enhance taint detection by adding support for inline source member expressions in call arguments * feat: implement pre-emission of Source nodes for inline source member expressions in call arguments * feat: add support for Throw statement in control flow and error handling * feat: add debug and echo endpoints with potential information leakage * feat: implement internal redirect suppression and enhance taint detection * feat: implement module alias tracking for dynamic dispatch in JS/TS * feat: add authorization analysis module with Express support * feat: add authorization analysis module with Express support * feat: add tests for admin guard requirements and clean checks in authorization analysis * feat: integrate Koa and Fastify frameworks into authorization analysis * feat: add Flask and Django support to authorization analysis module * feat: add support for Rails and Sinatra frameworks in authorization analysis * feat: add support for Axum, ActixWeb, and Rocket frameworks in authorization analysis * feat: add support for ActixWeb, Axum, and Rocket frameworks in authorization analysis * feat: add support for Rails and Sinatra in authorization analysis * chore: add .DS_Store to .gitignore * refactor: simplify conditional checks and improve readability in multiple files * refactor: update usage of Option methods for improved clarity and consistency * refactor: improve code readability by simplifying conditional checks and formatting * refactor: improve code formatting and readability by simplifying conditional checks * refactor: simplify conditional checks and improve readability in multiple files * refactor: simplify conditional checks in axum.rs for improved readability * feat: add CodeQL analysis configuration for enhanced security scanning * test: add comprehensive tests for `src/output.rs` SARIF builder (#39) * chore: start test coverage improvement work Agent-Logs-Url: https://github.com/elicpeter/nyx/sessions/cd7ff398-134e-4728-a5e7-0353a0744423 Co-authored-by: elicpeter <54954007+elicpeter@users.noreply.github.com> * test: add comprehensive tests for src/output.rs SARIF builder Agent-Logs-Url: https://github.com/elicpeter/nyx/sessions/cd7ff398-134e-4728-a5e7-0353a0744423 Co-authored-by: elicpeter <54954007+elicpeter@users.noreply.github.com> * refactor: improve code formatting and readability in output.rs --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: elicpeter <54954007+elicpeter@users.noreply.github.com> Co-authored-by: elipeter <elicpeter@gmail.com> * refactor: improve code formatting and readability in output.rs * Potential fix for code scanning alert no. 210: Uncontrolled data used in path expression Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> * Potential fix for code scanning alert no. 211: Uncontrolled data used in path expression Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> * refactor: enhance triage file path handling with improved error management and validation * refactor: updated func summaries for richer detail * refactor: update SSA summary extraction to use canonical FuncKey for distinct entries * refactor: enhance callee metadata structure to support arity, receiver, and qualifier for better overload resolution * refactor: add support for keyword arguments in function calls and enhance receiver extraction for method-style calls * refactor: implement new Flask routes for safe and unsafe shell command execution * refactor: separate receiver handling in SSA operations and enhance taint propagation * refactor: improve arity handling by using arg_uses for positional argument count and enhance witness scoring for tainted arguments * refactor: implement auth decorator extraction and classification for multiple languages * refactor: enhance Rust module path resolution and use map handling for cross-file disambiguation * refactor: introduce CalleeQuery struct for structured callee resolution and enhance resolver logic * refactor: implement same-file identity collision handling for `runTask` to ensure correct resolver behavior * refactor: standardize default struct initialization across multiple files * feat: add scripts for formatting checks and auto-fixes with test summaries * refactor: simplify character splitting and enhance namespace qualifier handling * refactor: improve documentation clarity and enhance code readability in resolver logic * refactor: replace default struct initialization with explicit field assignments for clarity * feat: enhance anonymous function naming by deriving context-based bindings * refactor: streamline match expressions for improved readability and performance * refactor: streamline match expressions for improved readability and performance * refactor: replace loop with while let for improved clarity and performance * feat: add SSA constant propagation support to analysis context for improved accuracy * feat: add SSA constant propagation support to analysis context for improved accuracy * feat: implement shell metacharacter validation and bounded-length checks in Rust analysis * feat: add static map analysis for command injection suppression and type safety * refactor: simplify match statements and reduce line breaks for improved readability * feat(summary): phase 1/5 SinkSite data model for primary sink-location attribution Introduce SinkSite (file_rel, line, col, snippet, cap) carrying the primary sink source-location through function summaries. Swap SsaFuncSummary.param_to_sink and FuncSummary.param_to_sink from a coarse Cap map to a deduped SmallVec<[SinkSite; 1]> per parameter, with a backward-compatible cap_sites() helper and serde defaults so pre-phase-1 on-disk rows continue to deserialise cleanly. Extraction: SinkSiteLocator bundles the tree/bytes/file_rel needed by extract_ssa_func_summary; ParsedFile::extract_ssa_artifacts wires the locator in for the persisted pass-1 path, while pass-2 intra-file transient summaries fall back to cap-only sites (behavior unchanged). Merge: GlobalSummaries::insert now unions sink sites with (file_rel, line, col, cap) dedup via shared union_param_sink_sites helper. Database: JSON-serialised summary columns carry the new shape automatically; no schema change needed. Phase 2 will consume SinkSite in build_taint_diag() to overwrite the caller-site Finding.line with the callee's sink line when resolved via summary. Phase 1 keeps behavior unchanged: scanning tests/benchmark/corpus/rust/cmdi/cmdi_indirect.rs still produces the same (wrong) line 10 finding. Adds round-trip tests covering SinkSite solo, SsaFuncSummary with sink sites, legacy-JSON default handling for both summary types, and merge dedup. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(taint): phase 2/5 thread SinkSite into SsaTaintEvent and Finding Plumb Phase 1's SinkSite through the event pipeline into Findings, no output change yet. SsaTaintEvent gains `primary_sink_site: Option<SinkSite>`; when the main or callback sink-emission path has non-empty `param_to_sink_sites`, filter to sites whose `(line != 0) && (cap ∩ sink_caps != ∅)` and emit one event per distinct site — the multi-primary collapse keeps each downstream Finding single-primary. Resolution: ResolvedSummary and SinkInfo gain mirror `param_to_sink_sites` fields, populated from `SsaFuncSummary.param_to_sink` (SSA + callback paths) and `FuncSummary.param_to_sink` (global paths). Label, local-summary, and interop resolution paths leave the field empty — they only ever had cap-level info to begin with. Finding: new `primary_location: Option<SinkLocation>` with `file_rel/line/col`. `ssa_events_to_findings` maps `event.primary_sink_site` → `Finding.primary_location`, filtering cap-only sites (`line == 0`) to `None` so the (0,0) sentinel never leaks to formatters. Dedup key extended with the primary location so multi-site events aren't collapsed back together. Invariants (debug_assert!): * every SinkSite reaching emission has `line != 0 && cap ∩ sink_caps != ∅` — enforced by the pick_primary_sink_sites* filters; * every populated Finding.primary_location has `line != 0` AND non-empty `file_rel` — the cap-only → None translation upstream guarantees this. Deliberately independent of `uses_summary`: that flag tracks whether the *taint chain* used a summary, whereas primary attribution requires only that the *sink* itself was summary-resolved. A local source reaching a cross-file sink produces `uses_summary=false` alongside a populated primary_location — documented on Finding.primary_location, covered by `cross_file_sink_finding_carries_primary_location`. build_taint_diag, SARIF/JSON/explanation formatters, and the benchmark scorer remain untouched: finding.line still comes from `cfg_graph[finding.sink]`, so cmdi_indirect.rs still reports line 10 and the benchmark's rs-cmdi-003 row still shows FN in the LOC column. Tests: `cross_file_sink_finding_carries_primary_location` (proves plumbing via a synthetic FuncSummary carrying a SinkSite at 42:5) and `cross_file_sink_cap_only_site_leaves_primary_location_none` (regression guard against cap-only sites surfacing). All 1566 lib tests + integration tests pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(output): phase 3/5 consume primary sink location in diag + SARIF When a finding's primary_location (populated in phase 2 from a callee summary's SinkSite) names the dangerous instruction inside a callee body, attribute the diagnostic line to that location instead of the caller's call site. The call site is demoted to a Call step in flow_steps, and a synthetic Sink step at the primary location is appended so analysts still see the full trace. Changes: - Add scan_root parameter to build_taint_diag so file_rel can be resolved back to an absolute path via a shared resolve_file_rel helper. Empty file_rel (single-file scans where namespace == "") resolves to the file under analysis. - Extend SinkLocation with snippet, carried from the upstream SinkSite so the formatter needs no second file read. - Relax the ssa_events_to_findings debug_assert to allow empty file_rel, which is valid when scan root equals the file itself. - SARIF: emit data-flow as codeFlows[0].threadFlows[0].locations[]; locations[0] already reflects the primary sink position via the updated diag line/col. Acceptance: scan on tests/benchmark/corpus/rust/cmdi/cmdi_indirect.rs now reports line 5 (Command::new) as the primary sink, with the call site at line 10 visible in flow_steps. Two expect.json fixtures updated (must_match line_range widened): - javascript/taint/context_sensitive_call: 12-14 -> 7-14 (line 8 is the real sink inside run()). - rust/cfg/closure_async: 10-10 -> 10-11 (line 11 is Command::new inside the closure). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(bench): phase 4/5 validate primary sink attribution across corpus Extend the benchmark scorer and ground truth to lock in phase 3's primary-location behavior, and add fixtures that exercise the new capability end-to-end. Scorer (tests/benchmark_test.rs): - Add optional `expected_call_site_lines: Option<Vec<[usize; 2]>>` on Case. When present, score_location_level additionally requires at least one flow_step in the finding's evidence trace to fall within ±2 of the call-site range. When absent, the check is skipped — fully forward-compatible with existing fixtures. - Retain ±2 tolerance on expected_sink_lines (compared against the now-primary Diag.line post-phase-3). Ground truth edits: - rs-cmdi-cross-001: expected_sink_lines [8,8] -> [9,9]. Line 8 is the transform::wrap call site (a cross-file propagator, not a sink); line 9 is Command::new, the real sink. The ±2 tolerance happened to mask this stale attribution but it was semantically wrong — phase 4 is the right time to correct it. Also adds expected_call_site_lines [8,8] so the new field is exercised on an existing cross-file case. - rs-cmdi-003: adds expected_call_site_lines [10,10] (run_cmd call). This fixture's sink (Command::new inside run_cmd at line 5) was the motivating case for phases 1-3; adding the call-site assertion guards against regression to caller-line attribution. New fixtures: - rust/cmdi/cmdi_indirect_multisink.rs (rs-cmdi-009): helper run_both takes two tainted params and invokes two Command sinks on consecutive lines. Locks in that primary line lands inside the helper (lines 5-6), not at the caller (line 12). Notes document that SinkSite is currently one-per-callee so both findings today collapse onto the first sink; expected_sink_lines=[5,6] and expected_call_site_lines=[12,12] stay valid either way. - python/cmdi/cross_indirect_sink/{app.py,helper.py} (py-cmdi-cross- 004): sink os.system lives in helper.py (cross-file), caller in app.py reads env source and calls run_cmd. Verifies phase 3's cross-file primary attribution: Diag.path = helper.py, Diag.line = 5, with app.py:7 recorded in flow_steps as a Call step. Acceptance: - `cargo test --test benchmark_test -- --ignored --nocapture` passes. - rs-cmdi-003 is TP/TP/TP (the target flip FN->TP at LOC). All pre-existing TP/TP/TP fixtures remain TP/TP/TP; 2 new fixtures are TP/TP/TP. - Aggregate rule-level: TP=158 FP=10 FN=1 TN=97, P=0.940 R=0.994 F1=0.966 on the 266-case corpus (was TP=156 FP=10 FN=1 TN=97 on 264 pre-phase-4, delta is the +2 new cases both resolving TP). - Full `cargo test` green (1566 lib tests + all integration tests). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(taint): phase 5/5 lock Finding.primary_location contract via regression test Add a regression test in src/taint/ssa_transfer.rs that wires up a synthetic SsaFuncSummary with a SinkSite at other.rs:42:10 and drives the three emission stages (pick_primary_sink_sites → emit_ssa_taint_events → ssa_events_to_findings) against a minimal caller SSA body. Asserts the resulting Finding.primary_location is exactly that triple. The existing integration tests in src/taint/tests.rs cover the coarse FuncSummary path end-to-end through analyse_file. This test locks in the lower-level SSA-side plumbing so a future refactor that silently drops the site between pick → emit → findings fails here rather than only at the benchmark layer. Also refreshes tests/benchmark/results/latest.json (timestamp only; rs-cmdi-003 remains TP/TP/TP and the aggregate P/R/F1 are unchanged from phase 4). Closes the primary sink-location attribution feature (phases 1-5/5): * Phase 1 — SinkSite data model on summaries. * Phase 2 — SinkSite threaded into SsaTaintEvent and Finding. * Phase 3 — diag + SARIF consume primary_location. * Phase 4 — benchmark validates primary_call_site_lines across corpus. * Phase 5 — regression test locks the event→finding contract. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * refactor: clean up formatting and improve readability in multiple files * refactor: simplify type definition for deduplication key in findings * test(harness): add must_not_match expectation for FP regression guards Extends ExpectedFinding with must_not_match field that asserts a diagnostic must NOT fire — presence is a hard failure. Non-consuming scan so it coexists with must_match entries on the same rule_id. Adds forbidden_violations accumulator and updates summary line. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(regression): update expectations to ensure must_not_match for various taint and resource leak rules * feat: implement auto-seeding for JS/TS handler parameters to enhance taint tracking * feat: update switch statement handling to improve control flow analysis * feat: implement promisify alias handling for JS/TS to enhance taint tracking * feat: enhance taint tracking by refining expectation handling and adding mode filtering * feat: refine SQL handling in stream processing and enhance auto-seeding for handler parameters * feat: update taint tracking rules to enforce full mode matching and improve flow analysis * feat: enhance Ruby subshell handling to improve taint tracking and flow analysis * feat: update xss_response expectations to refine taint flow analysis and enhance regression guarding * feat: refine framework detection and update expectation handling for Echo and Sinatra * feat: implement max_count for taint tracking expectations and deduplicate findings * feat: add strict_unexpected handling for taint-unsanitised-flow in expectation files * feat: enhance deduplication of taint-unsanitised-flow findings by collapsing based on line and severity * feat: add strict_unexpected handling for taint-unsanitised-flow in multiple expectation files * feat: add structural invariant checks for SSA bodies * feat: ensure deterministic phi emission order using BTreeSet * feat: enhance handling of terminators to ensure authoritative flow through successor edges * feat: enhance Goto terminator handling to ensure all successors are marked executable * feat: refactor code for improved readability and organization * feat: simplify predicate checks and enhance readability in SSA handling * feat: implement per-file parse timeout and enhance file size handling * feat: migrate analysis engine toggles from environment variables to configuration file * feat: remove unnecessary whitespace in hostile_input_tests.rs * feat: remove unnecessary whitespace in hostile_input_tests.rs * feat: update dependencies and enhance documentation on language maturity * feat: enhance security headers and improve request body limits * feat: implement sink capability bits for deduplication and enhance evidence tagging * feat: implement dynamic activation handling for gated sinks and enhance validation logic * feat: enhance configuration documentation and clarify inline analysis cache behavior * feat: implement panic recovery during analysis to continue scans past errors * feat: add expectations configuration for taint analysis and performance metrics * feat: enhance error handling and logging during file reading and mutex locking * feat: add cross-file body loading tests and plumbing for CF-1 phase * feat: implement cross-file k=1 context-sensitive inline taint analysis with new tests and fixtures * feat: implement indexed-scan parity in cross-file inline analysis with new dropdown and copy functionality * feat: enhance classification span handling in CFG and AST for improved source attribution * feat: add new Express routes for handling user input and telemetry data * feat: implement ternary expression handling in CFG with diamond structure for JS/TS * feat: implement Phase CF-3 abstract-domain transfer channels in summaries * feat: add support for string-prefix transfer in cross-file calls and update tests * docs: reduce RESULTS.md doc size * feat: implement Phase CF-4 per-return-path summary decomposition with tests * feat: update parameter handling in pass1 and refactor SsaFuncSummary initialization * feat: implement Phase CF-5 for cross-file SCC joint fixed-point convergence with new flags and tests * feat: implement Phase CF-6 with parameter-granularity points-to summaries and associated tests * refactor: update comments and documentation for clarity and consistency * style: format code for consistency and readability * refactor: simplify verdict handling and improve edge checking logic * refactor: optimize path and identifier collection by avoiding unnecessary cloning * chore: update Cargo.toml for Rust version 1.85 and add ignored files; modify CHANGELOG and README for clarity on state analysis defaults * refactor: update documentation and improve clarity in configuration files * refactor: update documentation and improve clarity in configuration files * feat: add JS/TS pass-2 convergence tests and expectations configuration * feat: add Phase 5 regression tests for inline cache origin attribution and update related logic * feat: implement Phase 7 deduplication and alternative path linking for taint findings * feat: implement structural DFS index for anonymous functions and update naming conventions * feat: add Phase 8 regression tests for container-element taint in JS and Python * feat: add engine-depth profiles and explain-engine option for CLI * feat: update expectations and add new README fixtures for multi-file scan regression * feat: implement Phase 11 callback-alias and factory patterns with regression tests * feat: implement Terminator::Switch for multi-way dispatch and add regression tests * feat: add real-CVE benchmark fixtures for CVE-2023-48022, CVE-2019-14939, and CVE-2023-26159 with corresponding patched variants * refactor: extract cfg and ssa_transfer to submodules * refactor: cargo fmt * refactor: remove unnecessary blank line in cfg_tests.rs * refactor: remove unnecessary planning file * chore: update Rust version to 1.88 and bump dependencies in Cargo files * feat: enhance triage UI with new layout and controls, update README for clarity * feat: enhance triage UI with new layout and controls, update README for clarity * chore: remove outdated section from README for version 0.5.0 * docs: improve clarity and consistency in README content * chore: add "GPL-3.0-or-later" to license options in about.toml * chore: update license handling in about.toml and check-licenses.mjs * style: format code for improved readability in TriagePage component * style: format code for improved readability in TriagePage component * chore: enhance license handling and improve body_id scoping in seed lookup * feat: introduce owner and parent body IDs for enhanced seed scoping * feat: implement direction-aware engine provenance with new CLI flag for strict CI gating * feat: add Undef SSA operation for improved control-flow handling * style: improve code formatting for consistency and readability in multiple files * feat: add 16-function chain SCC across multiple files for enhanced analysis * style: simplify code formatting for improved readability in multiple files * fix: update CapHitReason default implementation and improve README clarity * docs: enhance README with detailed explanations of taint analysis and limitations * docs: refine README for clarity and consistency in taint analysis section * style: improve code formatting for better readability in NewScanModal and scans * fix: update cargo-about command to use --offline for deterministic license generation * fix: update cargo-about command to use --offline for deterministic license generation * ci: add step to prime cargo registry cache for deterministic license generation * feat: add support for non-sink collections in authorization analysis * feat: enhance authorization checks with row-level ownership equality and binding tracking * feat: implement self-scoped user handling and enhance ownership checks * refactor: simplify assertions and formatting in authorization analysis tests * fix: normalize line endings in THIRDPARTY-LICENSES.html generation and update README with AI disclosure * docs: update AI disclosure section for clarity and conciseness * feat: add AI Contribution Policy and update contributing guidelines for AI assistance disclosure * feat: enhance authorization analysis with SSA-derived variable type classification * feat: implement auth_finding_to_diag function for enhanced security diagnostics * feat: add args_value_refs to CallSite struct for enhanced argument tracking * feat: add args_value_refs to CallSite struct for enhanced argument tracking * feat: add direction-aware engine provenance with LossDirection classification and new CLI flag * feat: simplify strip_cap_from_call_args call by removing unnecessary line breaks * feat: enhance error message handling in cli_validation_tests for better Windows compatibility * feat: optimize release profile settings in Cargo.toml and update CodeQL configuration * feat: enhance release build process with SBOM generation and SLSA provenance * feat: update actions/checkout and actions/setup-node to v6, enhance CLI options, and improve auth-check summaries * feat: introduce PathFact handling for path safety checks and rejection logic * feat: introduce PathFact handling for path safety checks and rejection logic * feat: update benchmark data and enhance path sanitization logic with new safety checks * feat: document AI assistance in frontend UI development and human review process * feat: add return path facts for enhanced path safety checks and update documentation * chore: update release date for version 0.5.0 in CHANGELOG.md * chore: clean up ci.yml by removing outdated comments and clarifying steps * feat: implement cross-language path sanitizers and validators for enhanced security * feat: enhance SSA value usage tracking by including block terminators and improve path safety checks * feat: enhance switch statement handling by adding per-case path constraints and support for exclusive cases * refactor: simplify conditional formatting and improve code readability in executor and lower modules * feat: add vulnerable examples for various languages demonstrating authentication and sanitization issues * feat: enhance actor context recognition for self-actor identifiers and add support for global non-sink receivers * feat: enhance actor context recognition for self-actor identifiers and add support for global non-sink receivers * feat: add transform classifiers for Java, Go, and Ruby with corresponding tests * refactor: clarify comments on reassign-to-constant idiom and sink behavior in guards.rs --------- Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
parent
c4ce08b452
commit
41128177d2
2144 changed files with 201812 additions and 8927 deletions
|
|
@ -15,13 +15,13 @@ pub struct AuthGap;
|
|||
/// Shell execution, file I/O, and similar sensitive operations.
|
||||
fn is_privileged_sink(info: &crate::cfg::NodeInfo) -> bool {
|
||||
use crate::labels::Cap;
|
||||
match info.label {
|
||||
Some(DataLabel::Sink(caps)) => {
|
||||
// Shell execution or file I/O are privileged
|
||||
info.taint.labels.iter().any(|l| {
|
||||
if let DataLabel::Sink(caps) = l {
|
||||
caps.intersects(Cap::SHELL_ESCAPE | Cap::FILE_IO)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Web handler parameter patterns by language.
|
||||
|
|
@ -31,7 +31,7 @@ fn has_web_handler_params(ctx: &AnalysisContext, func_name: &str) -> bool {
|
|||
let param_names: Vec<&str> = ctx
|
||||
.func_summaries
|
||||
.values()
|
||||
.filter(|s| ctx.cfg[s.entry].enclosing_func.as_deref() == Some(func_name))
|
||||
.filter(|s| ctx.cfg[s.entry].ast.enclosing_func.as_deref() == Some(func_name))
|
||||
.flat_map(|s| s.param_names.iter().map(|p| p.as_str()))
|
||||
.collect();
|
||||
|
||||
|
|
@ -138,7 +138,7 @@ fn is_web_entrypoint(ctx: &AnalysisContext, func_name: &str) -> bool {
|
|||
fn find_web_entry_point_functions(ctx: &AnalysisContext) -> Vec<String> {
|
||||
let mut entry_funcs = Vec::new();
|
||||
for idx in ctx.cfg.node_indices() {
|
||||
if let Some(func_name) = &ctx.cfg[idx].enclosing_func
|
||||
if let Some(func_name) = &ctx.cfg[idx].ast.enclosing_func
|
||||
&& is_web_entrypoint(ctx, func_name)
|
||||
&& !entry_funcs.contains(func_name)
|
||||
{
|
||||
|
|
@ -162,6 +162,18 @@ impl CfgAnalysis for AuthGap {
|
|||
}
|
||||
|
||||
fn run(&self, ctx: &AnalysisContext) -> Vec<CfgFinding> {
|
||||
// Decorator/annotation/attribute auth on the body declaration
|
||||
// already gates every sink in the body — skip the
|
||||
// structural-call dominance check entirely when the framework
|
||||
// enforces auth at the declaration level. Mirrors the
|
||||
// `classify_auth_decorators` lookup the state engine uses to
|
||||
// seed the AuthLevel of the body's initial state, so both
|
||||
// analyses agree on which decorators count.
|
||||
let body_auth_level = crate::state::classify_auth_decorators(ctx.lang, ctx.auth_decorators);
|
||||
if body_auth_level >= crate::state::domain::AuthLevel::Authed {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let doms = dominators::compute_dominators(ctx.cfg, ctx.entry);
|
||||
let entry_funcs = find_web_entry_point_functions(ctx);
|
||||
let auth_nodes = find_auth_nodes(ctx);
|
||||
|
|
@ -181,7 +193,7 @@ impl CfgAnalysis for AuthGap {
|
|||
}
|
||||
|
||||
// Only check nodes inside web entry point functions
|
||||
let func_name = match &info.enclosing_func {
|
||||
let func_name = match &info.ast.enclosing_func {
|
||||
Some(name) if entry_funcs.contains(name) => name.clone(),
|
||||
_ => continue,
|
||||
};
|
||||
|
|
@ -202,14 +214,14 @@ impl CfgAnalysis for AuthGap {
|
|||
.any(|&auth_idx| dominates(&doms, auth_idx, idx));
|
||||
|
||||
if !has_auth {
|
||||
let callee_desc = info.callee.as_deref().unwrap_or("(sensitive op)");
|
||||
let callee_desc = info.call.callee.as_deref().unwrap_or("(sensitive op)");
|
||||
|
||||
findings.push(CfgFinding {
|
||||
rule_id: "cfg-auth-gap".to_string(),
|
||||
title: "Missing auth check".to_string(),
|
||||
severity: Severity::High,
|
||||
confidence: Confidence::Medium,
|
||||
span: info.span,
|
||||
span: info.ast.span,
|
||||
message: format!(
|
||||
"Sensitive operation `{callee_desc}` in web handler `{func_name}` \
|
||||
has no dominating authentication check"
|
||||
|
|
|
|||
|
|
@ -38,7 +38,13 @@ pub fn find_exit_node(cfg: &Cfg) -> Option<NodeIndex> {
|
|||
/// Find all nodes that are sinks (have DataLabel::Sink).
|
||||
pub fn find_sink_nodes(cfg: &Cfg) -> Vec<NodeIndex> {
|
||||
cfg.node_indices()
|
||||
.filter(|&idx| matches!(cfg[idx].label, Some(DataLabel::Sink(_))))
|
||||
.filter(|&idx| {
|
||||
cfg[idx]
|
||||
.taint
|
||||
.labels
|
||||
.iter()
|
||||
.any(|l| matches!(l, DataLabel::Sink(_)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
|
@ -102,7 +108,7 @@ pub fn find_call_nodes_matching(cfg: &Cfg, matchers: &[&str]) -> Vec<NodeIndex>
|
|||
if cfg[idx].kind != StmtKind::Call {
|
||||
return false;
|
||||
}
|
||||
if let Some(callee) = &cfg[idx].callee {
|
||||
if let Some(callee) = &cfg[idx].call.callee {
|
||||
let callee_lower = callee.to_ascii_lowercase();
|
||||
matchers.iter().any(|m| {
|
||||
let ml = m.to_ascii_lowercase();
|
||||
|
|
|
|||
|
|
@ -4,6 +4,69 @@ use crate::patterns::Severity;
|
|||
use petgraph::graph::NodeIndex;
|
||||
use petgraph::visit::EdgeRef;
|
||||
|
||||
/// Does the condition text contain a unary `!` (logical-not, NOT `!=`)
|
||||
/// applied to an identifier or member chain whose name contains "err"?
|
||||
///
|
||||
/// Used by the error-fallthrough rule to skip happy-path checks
|
||||
/// like `if (!data.error && Array.isArray(results))` whose TRUE branch
|
||||
/// is the success path and is not expected to return. The original
|
||||
/// rule fires on `if (err) { warn(); } sink_after()` — a positive
|
||||
/// error check whose body forgets to early-return.
|
||||
fn contains_negated_err_identifier(text: &str) -> bool {
|
||||
let bytes = text.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] != b'!' {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// Skip the `!=` / `!==` operators — those are comparisons, not
|
||||
// logical-not. Only treat a `!` followed by whitespace or an
|
||||
// identifier-leading char as logical negation.
|
||||
if i + 1 < bytes.len() && bytes[i + 1] == b'=' {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut j = i + 1;
|
||||
while j < bytes.len() && (bytes[j] == b' ' || bytes[j] == b'\t') {
|
||||
j += 1;
|
||||
}
|
||||
// Allow a leading `(` for `!(expr)` shapes — peek past one open
|
||||
// paren and continue capturing the identifier chain.
|
||||
if j < bytes.len() && bytes[j] == b'(' {
|
||||
j += 1;
|
||||
while j < bytes.len() && (bytes[j] == b' ' || bytes[j] == b'\t') {
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
let start = j;
|
||||
while j < bytes.len() {
|
||||
let b = bytes[j];
|
||||
if b.is_ascii_alphanumeric() || b == b'_' || b == b'.' || b == b'$' {
|
||||
j += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if j > start {
|
||||
// Lowercase compare without allocating a full lowercase
|
||||
// copy: walk byte-by-byte.
|
||||
let mut k = start;
|
||||
while k + 2 < j {
|
||||
if (bytes[k] | 0x20) == b'e'
|
||||
&& (bytes[k + 1] | 0x20) == b'r'
|
||||
&& (bytes[k + 2] | 0x20) == b'r'
|
||||
{
|
||||
return true;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
i = if j > i { j } else { i + 1 };
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub struct IncompleteErrorHandling;
|
||||
|
||||
/// Check if the true branch of an If node terminates (has Return/Break/Continue).
|
||||
|
|
@ -47,7 +110,7 @@ fn terminates_on_all_paths(
|
|||
|
||||
let info = &cfg[current];
|
||||
match info.kind {
|
||||
StmtKind::Return | StmtKind::Break | StmtKind::Continue => {
|
||||
StmtKind::Return | StmtKind::Throw | StmtKind::Break | StmtKind::Continue => {
|
||||
// This path terminates
|
||||
continue;
|
||||
}
|
||||
|
|
@ -89,7 +152,7 @@ fn find_post_if_sinks(cfg: &crate::cfg::Cfg, if_node: NodeIndex) -> Vec<NodeInde
|
|||
}
|
||||
|
||||
let info = &cfg[current];
|
||||
if is_sink(info) || (info.kind == StmtKind::Call && info.callee.is_some()) {
|
||||
if is_sink(info) || (info.kind == StmtKind::Call && info.call.callee.is_some()) {
|
||||
sinks_after.push(current);
|
||||
}
|
||||
|
||||
|
|
@ -117,12 +180,20 @@ impl CfgAnalysis for IncompleteErrorHandling {
|
|||
for idx in ctx.cfg.node_indices() {
|
||||
let info = &ctx.cfg[idx];
|
||||
|
||||
// Look for If nodes whose condition involves "err" or "error"
|
||||
// Look for If nodes whose CONDITION involves "err" or "error".
|
||||
// `info.taint.uses` for an If node contains identifiers from the
|
||||
// whole if statement (condition + body) — see
|
||||
// `cfg::literals::extract_defs_uses_extra_defs` Kind::If branch
|
||||
// — so checking it would misfire on `if (!res.ok) { ... const
|
||||
// err = await … ; return … }` shapes whose body happens to
|
||||
// mention `err` even though the condition doesn't. Use
|
||||
// `info.condition_vars`, which is populated strictly from the
|
||||
// condition subtree (`extract_condition_raw`).
|
||||
if info.kind != StmtKind::If {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mentions_err = info.uses.iter().any(|u| {
|
||||
let mentions_err = info.condition_vars.iter().any(|u| {
|
||||
let lower = u.to_ascii_lowercase();
|
||||
lower == "err" || lower == "error" || lower.contains("err")
|
||||
});
|
||||
|
|
@ -131,6 +202,28 @@ impl CfgAnalysis for IncompleteErrorHandling {
|
|||
continue;
|
||||
}
|
||||
|
||||
// Polarity gate: only fire when the condition POSITIVELY
|
||||
// checks for an error. `if (!data.error && other)` is a
|
||||
// happy-path check — the TRUE branch is the success branch
|
||||
// and is not expected to terminate. Detect by scanning the
|
||||
// condition text for any `!` (logical-not, distinct from
|
||||
// `!=`) preceding an identifier whose name contains "err".
|
||||
//
|
||||
// This is the polarity-aware complement to
|
||||
// `condition_negated` (which only catches the top-level
|
||||
// unary `!`); compound conditions with embedded
|
||||
// `!response.error` legitimately fall outside the rule's
|
||||
// intended target shape (Go `if err != nil { non-return }`
|
||||
// / JS `if (err) { warn(); }`).
|
||||
if let Some(text) = info.condition_text.as_deref()
|
||||
&& contains_negated_err_identifier(text)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if info.condition_negated {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check: does the true branch terminate?
|
||||
if branch_terminates(ctx.cfg, idx) {
|
||||
continue;
|
||||
|
|
@ -146,7 +239,7 @@ impl CfgAnalysis for IncompleteErrorHandling {
|
|||
title: "Error check without return".to_string(),
|
||||
severity: Severity::Medium,
|
||||
confidence: Confidence::Medium,
|
||||
span: info.span,
|
||||
span: info.ast.span,
|
||||
message: "Error check does not terminate on error; \
|
||||
execution falls through to dangerous operations"
|
||||
.to_string(),
|
||||
|
|
@ -159,3 +252,40 @@ impl CfgAnalysis for IncompleteErrorHandling {
|
|||
findings
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod negation_tests {
|
||||
use super::contains_negated_err_identifier;
|
||||
|
||||
#[test]
|
||||
fn detects_simple_negated_err() {
|
||||
assert!(contains_negated_err_identifier("!err"));
|
||||
assert!(contains_negated_err_identifier("!error"));
|
||||
assert!(contains_negated_err_identifier("! err"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_negated_member_err() {
|
||||
assert!(contains_negated_err_identifier("!data.error"));
|
||||
assert!(contains_negated_err_identifier(
|
||||
"data && !data.error && Array.isArray(results)"
|
||||
));
|
||||
assert!(contains_negated_err_identifier(
|
||||
"!response.errorMsg && response.ok"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_match_inequality() {
|
||||
assert!(!contains_negated_err_identifier("err != nil"));
|
||||
assert!(!contains_negated_err_identifier("error !== null"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_match_positive_err_checks() {
|
||||
assert!(!contains_negated_err_identifier("err"));
|
||||
assert!(!contains_negated_err_identifier("err != null"));
|
||||
assert!(!contains_negated_err_identifier("response.error"));
|
||||
assert!(!contains_negated_err_identifier("hasError(x)"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,20 @@
|
|||
#![allow(clippy::collapsible_if)]
|
||||
|
||||
use super::dominators::{self, dominates};
|
||||
use super::rules;
|
||||
use super::{AnalysisContext, CfgAnalysis, CfgFinding, Confidence, is_entry_point_func};
|
||||
use super::{
|
||||
AnalysisContext, BodyConstFacts, CfgAnalysis, CfgFinding, Confidence, is_entry_point_func,
|
||||
};
|
||||
use crate::callgraph::callee_leaf_name;
|
||||
use crate::cfg::StmtKind;
|
||||
use crate::labels::{Cap, DataLabel, RuntimeLabelRule};
|
||||
use crate::patterns::Severity;
|
||||
use crate::ssa::const_prop::ConstLattice;
|
||||
use crate::ssa::type_facts::TypeFactResult;
|
||||
use crate::ssa::{SsaOp, SsaValue};
|
||||
use crate::taint::path_state::{PredicateKind, classify_condition};
|
||||
use petgraph::graph::NodeIndex;
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub struct UnguardedSink;
|
||||
|
||||
|
|
@ -12,52 +22,566 @@ pub struct UnguardedSink;
|
|||
/// variable flows). Extends the inline callee-part check by tracing one hop
|
||||
/// through the CFG: if a used variable is defined by a node that itself has
|
||||
/// empty `uses` and no Source label, the definition is treated as a constant
|
||||
/// binding (e.g. `let cmd = "git"; Command::new(cmd)`).
|
||||
/// binding (e.g. `let cmd = "git"; Command::new(cmd)`). When SSA
|
||||
/// [`BodyConstFacts`] are available, falls back to walking the sink's
|
||||
/// `SsaOp::Call` operands and consulting `OptimizeResult.const_values` for
|
||||
/// any operand the syntactic trace can't classify (e.g. a chained method-call
|
||||
/// receiver recorded as a compound identifier rather than a named binding).
|
||||
fn is_all_args_constant(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
|
||||
// Fast path: syntactic literal detection from CFG construction.
|
||||
// Strictly weaker than the one-hop trace below — serves as an
|
||||
// optimization for the common case of inline literal arguments.
|
||||
if ctx.cfg[sink].all_args_literal {
|
||||
return true;
|
||||
}
|
||||
let sink_info = &ctx.cfg[sink];
|
||||
let callee_desc = sink_info.callee.as_deref().unwrap_or("");
|
||||
let callee_parts: Vec<&str> = callee_desc.split(['.', ':']).collect();
|
||||
let sink_func = sink_info.enclosing_func.as_deref();
|
||||
let callee_desc = sink_info.call.callee.as_deref().unwrap_or("");
|
||||
// Split callee description into parts and strip parenthesized arg portions.
|
||||
// e.g. `exec.Command("echo", "health-ok").Run` → ["exec", "Command", "Run"]
|
||||
let callee_parts: Vec<&str> = callee_desc
|
||||
.split(['.', ':'])
|
||||
.map(|p| p.split('(').next().unwrap_or(p))
|
||||
.collect();
|
||||
// When the callee was overridden by an inner call (e.g. `db.query` inside
|
||||
// `Promise.all([db.query(...)])`), the outer callee's parts (e.g. "Promise",
|
||||
// "all") also belong to the callee machinery, not to arguments.
|
||||
let outer_parts: Vec<&str> = sink_info
|
||||
.call
|
||||
.outer_callee
|
||||
.as_deref()
|
||||
.map(|oc| {
|
||||
oc.split(['.', ':'])
|
||||
.map(|p| p.split('(').next().unwrap_or(p))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let sink_func = sink_info.ast.enclosing_func.as_deref();
|
||||
|
||||
sink_info.uses.iter().all(|u| {
|
||||
// Part of the callee name itself → constant
|
||||
if callee_parts.contains(&u.as_str()) {
|
||||
sink_info.taint.uses.iter().all(|u| {
|
||||
// Part of the callee name itself → not an argument, skip
|
||||
// Check both individual parts and the full dotted callee path
|
||||
if callee_parts.contains(&u.as_str())
|
||||
|| u == callee_desc
|
||||
|| outer_parts.contains(&u.as_str())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
// One-hop trace: find the defining node in the same function
|
||||
for idx in ctx.cfg.node_indices() {
|
||||
let info = &ctx.cfg[idx];
|
||||
if info.enclosing_func.as_deref() != sink_func {
|
||||
if info.ast.enclosing_func.as_deref() != sink_func {
|
||||
continue;
|
||||
}
|
||||
if info.defines.as_deref() == Some(u.as_str()) {
|
||||
if info.taint.defines.as_deref() == Some(u.as_str()) {
|
||||
// If the defining node has no uses (pure constant) and is not
|
||||
// a Source, the variable is constant.
|
||||
if info.uses.is_empty() && !matches!(info.label, Some(DataLabel::Source(_))) {
|
||||
if info.taint.uses.is_empty()
|
||||
&& !info
|
||||
.taint
|
||||
.labels
|
||||
.iter()
|
||||
.any(|l| matches!(l, DataLabel::Source(_)))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}) || ssa_all_sink_operands_constant(ctx, sink, callee_desc, &callee_parts, &outer_parts)
|
||||
}
|
||||
|
||||
/// SSA-backed fallback for `is_all_args_constant`. Looks up the sink CFG
|
||||
/// node in `cfg_node_map`, expects an `SsaOp::Call`, and checks that every
|
||||
/// operand (positional args and receiver) either names a callee fragment or
|
||||
/// resolves to a concrete `ConstLattice` literal.
|
||||
fn ssa_all_sink_operands_constant(
|
||||
ctx: &AnalysisContext,
|
||||
sink: NodeIndex,
|
||||
callee_desc: &str,
|
||||
callee_parts: &[&str],
|
||||
outer_parts: &[&str],
|
||||
) -> bool {
|
||||
let Some(facts) = ctx.body_const_facts else {
|
||||
return false;
|
||||
};
|
||||
let Some(&sink_val) = facts.ssa.cfg_node_map.get(&sink) else {
|
||||
return false;
|
||||
};
|
||||
let Some(inst) = find_inst(&facts.ssa, sink_val) else {
|
||||
return false;
|
||||
};
|
||||
let SsaOp::Call { args, receiver, .. } = &inst.op else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let operand_const = |v: SsaValue| -> bool {
|
||||
ssa_operand_constant(v, facts, callee_desc, callee_parts, outer_parts)
|
||||
};
|
||||
let args_ok = args
|
||||
.iter()
|
||||
.all(|group| group.iter().all(|v| operand_const(*v)));
|
||||
let receiver_ok = receiver.is_none_or(operand_const);
|
||||
args_ok && receiver_ok
|
||||
}
|
||||
|
||||
/// SSA-backed reassign-aware safety probe: every operand of the sink
|
||||
/// resolves to a constant, callee fragment, OR a function parameter that
|
||||
/// is not itself a Source. Used at the cfg-unguarded-sink site under
|
||||
/// `!has_taint` — the taint engine has already proved no source-tainted
|
||||
/// data reaches the sink, so a non-source Param at operand position is
|
||||
/// inert payload-wise (e.g. HTTP writer in `Fprintf(w, "<h1>", "Guest")`).
|
||||
///
|
||||
/// Gated on the function body actually exhibiting the reassign-to-constant
|
||||
/// signature — at least one named SSA def whose RHS is a literal Const
|
||||
/// (`name = "Guest"`). In a thin wrapper without a same-block named
|
||||
/// const assignment (`fn wrap(p) { sink(p) }`, or C `popen(buf, "r")` where
|
||||
/// `buf` is filled in-place by `sprintf` with no Const Assign on `buf`),
|
||||
/// the bare Param at operand position IS the payload and the suppression's
|
||||
/// rationale does not apply — `cfg-unguarded-sink` must still fire.
|
||||
fn ssa_all_sink_operands_const_or_param(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
|
||||
let Some(facts) = ctx.body_const_facts else {
|
||||
return false;
|
||||
};
|
||||
let Some(&sink_val) = facts.ssa.cfg_node_map.get(&sink) else {
|
||||
return false;
|
||||
};
|
||||
let Some(inst) = find_inst(&facts.ssa, sink_val) else {
|
||||
return false;
|
||||
};
|
||||
let SsaOp::Call { args, receiver, .. } = &inst.op else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if !func_body_has_named_const_assign(facts) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let operand_safe = |v: SsaValue| -> bool { ssa_operand_const_or_param(v, facts, ctx.cfg) };
|
||||
let args_ok = args
|
||||
.iter()
|
||||
.all(|group| group.iter().all(|v| operand_safe(*v)));
|
||||
let receiver_ok = receiver.is_none_or(operand_safe);
|
||||
args_ok && receiver_ok
|
||||
}
|
||||
|
||||
/// Return true if the SSA body contains a *named* variable whose definition
|
||||
/// is a constant — the SSA signature of an explicit `name = "literal"`
|
||||
/// reassignment. Used as the gate for the broader operand-Param suppression:
|
||||
/// the suppression's purpose is the reassign-to-constant idiom, which by
|
||||
/// definition has at least one named const assignment. In a thin wrapper
|
||||
/// (`fn wrap(p) { sink(p) }` or `popen(buf, "r")` where `buf` is filled by
|
||||
/// `sprintf`), no such named const assignment exists and the suppression's
|
||||
/// rationale doesn't apply — so the bare-Param structural finding fires.
|
||||
fn func_body_has_named_const_assign(facts: &BodyConstFacts) -> bool {
|
||||
for block in &facts.ssa.blocks {
|
||||
for inst in &block.body {
|
||||
if inst.var_name.is_none() {
|
||||
continue;
|
||||
}
|
||||
let rhs_const = match &inst.op {
|
||||
SsaOp::Const(_) => true,
|
||||
SsaOp::Assign(vals) => vals.iter().all(|v| {
|
||||
matches!(
|
||||
facts.const_values.get(v),
|
||||
Some(
|
||||
ConstLattice::Str(_)
|
||||
| ConstLattice::Int(_)
|
||||
| ConstLattice::Bool(_)
|
||||
| ConstLattice::Null
|
||||
)
|
||||
)
|
||||
}),
|
||||
_ => false,
|
||||
};
|
||||
if rhs_const {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Variant of [`ssa_operand_constant`] that also accepts non-Source Params.
|
||||
/// Stricter than `ssa_operand_constant` on Source (always false) but
|
||||
/// looser on bare Params (always true unless they are Source-labeled).
|
||||
fn ssa_operand_const_or_param(
|
||||
root: SsaValue,
|
||||
facts: &BodyConstFacts,
|
||||
cfg: &crate::cfg::Cfg,
|
||||
) -> bool {
|
||||
let mut visited: HashSet<SsaValue> = HashSet::new();
|
||||
let mut stack = vec![root];
|
||||
while let Some(v) = stack.pop() {
|
||||
if !visited.insert(v) {
|
||||
continue;
|
||||
}
|
||||
match facts.const_values.get(&v) {
|
||||
Some(ConstLattice::Str(_))
|
||||
| Some(ConstLattice::Int(_))
|
||||
| Some(ConstLattice::Bool(_))
|
||||
| Some(ConstLattice::Null) => continue,
|
||||
_ => {}
|
||||
}
|
||||
let Some(inst) = find_inst(&facts.ssa, v) else {
|
||||
return false;
|
||||
};
|
||||
// CFG-node-level Source label: when an SSA `Call` corresponds to a
|
||||
// Source-labeled CFG node (e.g. `env::var(...)` whose callee
|
||||
// matches a `LabelRule` Source matcher), the call's result is
|
||||
// tainted user input — refuse, regardless of how the SSA
|
||||
// happened to lower. Catches the `SsaOp::Call` lowering of
|
||||
// labeled Source functions, which the `SsaOp::Source` arm only
|
||||
// sees for callee-less pure sources like PHP `$_GET`.
|
||||
let cfg_node = inst.cfg_node;
|
||||
if cfg
|
||||
.node_weight(cfg_node)
|
||||
.map(|info| {
|
||||
info.taint
|
||||
.labels
|
||||
.iter()
|
||||
.any(|l| matches!(l, DataLabel::Source(_)))
|
||||
})
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
match &inst.op {
|
||||
SsaOp::Const(_) => {}
|
||||
SsaOp::Assign(vals) => stack.extend(vals.iter().copied()),
|
||||
SsaOp::Phi(ops) => stack.extend(ops.iter().map(|(_, v)| *v)),
|
||||
SsaOp::Call { args, receiver, .. } => {
|
||||
for group in args {
|
||||
stack.extend(group.iter().copied());
|
||||
}
|
||||
if let Some(r) = receiver {
|
||||
stack.push(*r);
|
||||
}
|
||||
}
|
||||
SsaOp::Param { .. } | SsaOp::SelfParam | SsaOp::CatchParam => {
|
||||
// Bare parameters are accepted: at the call site the
|
||||
// taint engine has already concluded no source data
|
||||
// reaches this sink (`!has_taint` gate). A Param that
|
||||
// is not source-tainted contributes only its caller-
|
||||
// bound value, which the gate above already filtered.
|
||||
}
|
||||
SsaOp::Source => return false,
|
||||
SsaOp::Nop | SsaOp::Undef => {}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Return true if this SSA operand is a compile-time-known literal, a callee
|
||||
/// fragment pseudo-use (not a real runtime value), or transitively composed
|
||||
/// of such operands. Returns false for sources, parameters with non-callee
|
||||
/// names, `Varying` const-prop facts, and any unresolved definition.
|
||||
fn ssa_operand_constant(
|
||||
root: SsaValue,
|
||||
facts: &BodyConstFacts,
|
||||
callee_desc: &str,
|
||||
callee_parts: &[&str],
|
||||
outer_parts: &[&str],
|
||||
) -> bool {
|
||||
let mut visited: HashSet<SsaValue> = HashSet::new();
|
||||
let mut stack = vec![root];
|
||||
while let Some(v) = stack.pop() {
|
||||
if !visited.insert(v) {
|
||||
continue;
|
||||
}
|
||||
match facts.const_values.get(&v) {
|
||||
Some(ConstLattice::Str(_))
|
||||
| Some(ConstLattice::Int(_))
|
||||
| Some(ConstLattice::Bool(_))
|
||||
| Some(ConstLattice::Null) => continue,
|
||||
Some(ConstLattice::Varying) => {
|
||||
// Fall through: a Varying lattice entry may still correspond
|
||||
// to a callee-fragment pseudo-name that the SSA models as a
|
||||
// Param. The per-op check below filters those out.
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let Some(inst) = find_inst(&facts.ssa, v) else {
|
||||
return false;
|
||||
};
|
||||
match &inst.op {
|
||||
SsaOp::Const(_) => {}
|
||||
SsaOp::Assign(vals) => stack.extend(vals.iter().copied()),
|
||||
SsaOp::Phi(ops) => stack.extend(ops.iter().map(|(_, v)| *v)),
|
||||
SsaOp::Call { args, receiver, .. } => {
|
||||
for group in args {
|
||||
stack.extend(group.iter().copied());
|
||||
}
|
||||
if let Some(r) = receiver {
|
||||
stack.push(*r);
|
||||
}
|
||||
}
|
||||
SsaOp::Param { .. } | SsaOp::SelfParam | SsaOp::CatchParam | SsaOp::Source => {
|
||||
// Only acceptable when the param's `var_name` is a callee
|
||||
// fragment — i.e. an identifier that only appears because
|
||||
// the CFG recorded name components of the dotted/chained
|
||||
// callee as uses. Real parameters and sources are dynamic.
|
||||
let name = inst.var_name.as_deref().unwrap_or("");
|
||||
if matches!(inst.op, SsaOp::Source) {
|
||||
return false;
|
||||
}
|
||||
if !is_callee_fragment(name, callee_desc, callee_parts, outer_parts) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
SsaOp::Nop => {}
|
||||
// Undef is a non-user, non-dynamic sentinel — treat like Const
|
||||
// (no additional operands to trace).
|
||||
SsaOp::Undef => {}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn is_callee_fragment(
|
||||
name: &str,
|
||||
callee_desc: &str,
|
||||
callee_parts: &[&str],
|
||||
outer_parts: &[&str],
|
||||
) -> bool {
|
||||
if name.is_empty() {
|
||||
return true;
|
||||
}
|
||||
if callee_parts.contains(&name) || outer_parts.contains(&name) || name == callee_desc {
|
||||
return true;
|
||||
}
|
||||
// Chained-receiver prefix: the name is a strict prefix of `callee_desc`
|
||||
// terminating at a `.` or `::` boundary (e.g. name =
|
||||
// `Command::new("sh").arg("-c").arg(cmd)` for callee_desc ending in
|
||||
// `.status().unwrap`). These are the outer callee's receiver chain,
|
||||
// not user-supplied arguments.
|
||||
if callee_desc.len() > name.len() && callee_desc.starts_with(name) {
|
||||
let rest = &callee_desc[name.len()..];
|
||||
if rest.starts_with('.') || rest.starts_with("::") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn find_inst(ssa: &crate::ssa::SsaBody, v: SsaValue) -> Option<&crate::ssa::SsaInst> {
|
||||
let def = ssa.value_defs.get(v.0 as usize)?;
|
||||
let block = ssa.blocks.get(def.block.0 as usize)?;
|
||||
block
|
||||
.phis
|
||||
.iter()
|
||||
.chain(block.body.iter())
|
||||
.find(|inst| inst.value == v)
|
||||
}
|
||||
|
||||
/// Check whether every operand SSA value of the sink's Call instruction is
|
||||
/// proven by type-fact analysis to be non-injectable for `sink_caps`.
|
||||
///
|
||||
/// Used to suppress `cfg-unguarded-sink` when all arguments are typed safe
|
||||
/// (e.g. Rust `port: u16` flowing into `Command::new(…).arg(port.to_string())`).
|
||||
/// Returns `false` when any required fact is missing so the structural finding
|
||||
/// is preserved whenever typing is ambiguous.
|
||||
fn sink_args_typed_safe(ctx: &AnalysisContext, sink: NodeIndex, sink_caps: Cap) -> bool {
|
||||
let Some(facts) = ctx.body_const_facts else {
|
||||
return false;
|
||||
};
|
||||
let Some(type_facts) = ctx.type_facts else {
|
||||
return false;
|
||||
};
|
||||
let Some(&sink_val) = facts.ssa.cfg_node_map.get(&sink) else {
|
||||
return false;
|
||||
};
|
||||
let Some(inst) = find_inst(&facts.ssa, sink_val) else {
|
||||
return false;
|
||||
};
|
||||
let SsaOp::Call { args, receiver, .. } = &inst.op else {
|
||||
return false;
|
||||
};
|
||||
|
||||
// Chained Rust/JS calls record the whole dotted path as a single Call node.
|
||||
// Its SSA operands include pseudo-uses for every identifier segment of the
|
||||
// callee (e.g. `Command`, `new`, `arg`, `status`, `unwrap`) plus string
|
||||
// literal arguments to intermediate calls. Filter those out so the
|
||||
// is-Int check runs only against real argument values.
|
||||
let sink_info = &ctx.cfg[sink];
|
||||
let callee_desc = sink_info.call.callee.as_deref().unwrap_or("");
|
||||
let callee_parts: Vec<&str> = callee_desc
|
||||
.split(['.', ':'])
|
||||
.map(|p| p.split('(').next().unwrap_or(p))
|
||||
.collect();
|
||||
let outer_parts: Vec<&str> = sink_info
|
||||
.call
|
||||
.outer_callee
|
||||
.as_deref()
|
||||
.map(|oc| {
|
||||
oc.split(['.', ':'])
|
||||
.map(|p| p.split('(').next().unwrap_or(p))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let is_real_arg = |v: SsaValue| -> bool {
|
||||
let Some(def) = find_inst(&facts.ssa, v) else {
|
||||
return true;
|
||||
};
|
||||
// Callee-fragment pseudo-uses appear as `Param { .. }` with a
|
||||
// var_name that is a segment of the callee text. SelfParam and
|
||||
// CatchParam cover `self`/exception bindings that cannot be the
|
||||
// implicit callee chain.
|
||||
match &def.op {
|
||||
SsaOp::Param { .. } => {
|
||||
let name = def.var_name.as_deref().unwrap_or("");
|
||||
!is_callee_fragment(name, callee_desc, &callee_parts, &outer_parts)
|
||||
}
|
||||
// Constant string literals used as inline args (e.g. `"listener"`,
|
||||
// `"-c"`) are not user-controlled — treat as non-real for the
|
||||
// "all int-typed" test so they don't block suppression.
|
||||
SsaOp::Const(_) => false,
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
|
||||
let mut values: Vec<SsaValue> = Vec::new();
|
||||
if let Some(r) = receiver {
|
||||
if is_real_arg(*r) {
|
||||
values.push(*r);
|
||||
}
|
||||
}
|
||||
for group in args {
|
||||
for v in group.iter() {
|
||||
if is_real_arg(*v) {
|
||||
values.push(*v);
|
||||
}
|
||||
}
|
||||
}
|
||||
type_facts_suppress(&values, sink_caps, type_facts)
|
||||
}
|
||||
|
||||
/// Thin wrapper around [`crate::ssa::type_facts::is_type_safe_for_sink`] kept
|
||||
/// local so the unit tests here can exercise the exact predicate used at the
|
||||
/// `cfg-unguarded-sink` emission site.
|
||||
fn type_facts_suppress(values: &[SsaValue], sink_caps: Cap, type_facts: &TypeFactResult) -> bool {
|
||||
crate::ssa::type_facts::is_type_safe_for_sink(values, sink_caps, type_facts)
|
||||
}
|
||||
|
||||
/// Suppress a `cfg-unguarded-sink` finding when every real argument SSA
|
||||
/// value resolves to a finite set of metacharacter-free literals, as proved
|
||||
/// by the static-map analysis. Runs in lock-step with the SSA taint
|
||||
/// suppression so both findings paths agree on when a provably-bounded
|
||||
/// lookup idiom (e.g. `map.get(x).unwrap_or("safe")` over literal inserts)
|
||||
/// should clear a command-injection sink.
|
||||
///
|
||||
/// Only fires for `Cap::SHELL_ESCAPE` — SQL / path suppression from this
|
||||
/// domain would require stronger reasoning (literal keys can still carry
|
||||
/// SQL tokens if the inserts themselves contain them).
|
||||
fn sink_args_static_map_safe(ctx: &AnalysisContext, sink: NodeIndex, sink_caps: Cap) -> bool {
|
||||
if !sink_caps.intersects(Cap::SHELL_ESCAPE) {
|
||||
return false;
|
||||
}
|
||||
let Some(facts) = ctx.body_const_facts else {
|
||||
return false;
|
||||
};
|
||||
let Some(&sink_val) = facts.ssa.cfg_node_map.get(&sink) else {
|
||||
return false;
|
||||
};
|
||||
let Some(inst) = find_inst(&facts.ssa, sink_val) else {
|
||||
return false;
|
||||
};
|
||||
let SsaOp::Call { args, receiver, .. } = &inst.op else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let sm =
|
||||
crate::ssa::static_map::analyze(&facts.ssa, ctx.cfg, Some(ctx.lang), &facts.const_values);
|
||||
if sm.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Skip callee-fragment pseudo-uses the same way `sink_args_typed_safe`
|
||||
// does so only real runtime arg values participate in the check.
|
||||
let sink_info = &ctx.cfg[sink];
|
||||
let callee_desc = sink_info.call.callee.as_deref().unwrap_or("");
|
||||
let callee_parts: Vec<&str> = callee_desc
|
||||
.split(['.', ':'])
|
||||
.map(|p| p.split('(').next().unwrap_or(p))
|
||||
.collect();
|
||||
let outer_parts: Vec<&str> = sink_info
|
||||
.call
|
||||
.outer_callee
|
||||
.as_deref()
|
||||
.map(|oc| {
|
||||
oc.split(['.', ':'])
|
||||
.map(|p| p.split('(').next().unwrap_or(p))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let is_real_arg = |v: SsaValue| -> bool {
|
||||
let Some(def) = find_inst(&facts.ssa, v) else {
|
||||
return true;
|
||||
};
|
||||
match &def.op {
|
||||
SsaOp::Param { .. } => {
|
||||
let name = def.var_name.as_deref().unwrap_or("");
|
||||
!is_callee_fragment(name, callee_desc, &callee_parts, &outer_parts)
|
||||
}
|
||||
SsaOp::Const(_) => false,
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
|
||||
let mut values: Vec<SsaValue> = Vec::new();
|
||||
if let Some(r) = receiver {
|
||||
if is_real_arg(*r) {
|
||||
values.push(*r);
|
||||
}
|
||||
}
|
||||
for group in args {
|
||||
for v in group.iter() {
|
||||
if is_real_arg(*v) {
|
||||
values.push(*v);
|
||||
}
|
||||
}
|
||||
}
|
||||
if values.is_empty() {
|
||||
return false;
|
||||
}
|
||||
values.iter().all(|v| match sm.finite_string_values.get(v) {
|
||||
Some(set) if !set.is_empty() => set
|
||||
.iter()
|
||||
.all(|s| crate::abstract_interp::string_domain::is_shell_safe_literal(s)),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Check if a callee matches any of the runtime label rules that are sanitizers.
|
||||
fn match_config_sanitizer(callee: &str, extra: &[RuntimeLabelRule]) -> Option<Cap> {
|
||||
let callee_lower = callee.to_ascii_lowercase();
|
||||
// Lazily compute lowercased callee only when a case-insensitive rule is hit.
|
||||
let mut callee_lower: Option<String> = None;
|
||||
|
||||
for rule in extra {
|
||||
let cap = match rule.label {
|
||||
DataLabel::Sanitizer(c) => c,
|
||||
_ => continue,
|
||||
};
|
||||
for m in &rule.matchers {
|
||||
let ml = m.to_ascii_lowercase();
|
||||
if ml.ends_with('_') {
|
||||
if callee_lower.starts_with(&ml) {
|
||||
if rule.case_sensitive {
|
||||
if m.ends_with('_') {
|
||||
if callee.starts_with(m.as_str()) {
|
||||
return Some(cap);
|
||||
}
|
||||
} else if callee.ends_with(m.as_str()) {
|
||||
return Some(cap);
|
||||
}
|
||||
} else {
|
||||
let cl = callee_lower.get_or_insert_with(|| callee.to_ascii_lowercase());
|
||||
let ml = m.to_ascii_lowercase();
|
||||
if ml.ends_with('_') {
|
||||
if cl.starts_with(&ml) {
|
||||
return Some(cap);
|
||||
}
|
||||
} else if cl.ends_with(&ml) {
|
||||
return Some(cap);
|
||||
}
|
||||
} else if callee_lower.ends_with(&ml) {
|
||||
return Some(cap);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -75,10 +599,55 @@ fn find_guard_nodes(ctx: &AnalysisContext) -> Vec<(NodeIndex, Cap)> {
|
|||
|
||||
for idx in ctx.cfg.node_indices() {
|
||||
let info = &ctx.cfg[idx];
|
||||
|
||||
// If-condition guards: allowlist checks, type checks, validation
|
||||
// calls, shell-metachar rejections, and bounded-length checks in
|
||||
// branch conditions act as guards for downstream sinks.
|
||||
if info.kind == StmtKind::If {
|
||||
if let Some(cond_text) = &info.condition_text {
|
||||
let kind = classify_condition(cond_text);
|
||||
if matches!(
|
||||
kind,
|
||||
PredicateKind::AllowlistCheck
|
||||
| PredicateKind::TypeCheck
|
||||
| PredicateKind::ValidationCall
|
||||
) {
|
||||
result.push((idx, Cap::all()));
|
||||
} else if matches!(
|
||||
kind,
|
||||
PredicateKind::ShellMetaValidated | PredicateKind::BoundedLength
|
||||
) {
|
||||
// Shell-metachar rejection and bounded-length checks only
|
||||
// guard shell-family sinks. Keep scope tight so unrelated
|
||||
// sinks (SQL, XSS) aren't silenced when a shell gate
|
||||
// happens to sit upstream.
|
||||
result.push((idx, Cap::SHELL_ESCAPE | Cap::CODE_EXEC));
|
||||
} else {
|
||||
// Path-traversal rejection guard. When the condition
|
||||
// matches a path-rejection idiom recognised by
|
||||
// `classify_path_rejection_axes` (`strstr(p, "..")`
|
||||
// / `.contains("..")` / `strings.Contains(p, "..")`
|
||||
// / `p[0] == '/'` / `path.is_absolute()` / etc.),
|
||||
// it acts as a guard for FILE_IO sinks. Catches
|
||||
// the C/C++ `if (strstr(p, "..") != NULL)` shape
|
||||
// whose `!= NULL` wrapper otherwise falls through
|
||||
// to NullCheck classification and never registers
|
||||
// as a guard. Scope kept to FILE_IO so unrelated
|
||||
// sinks aren't silenced.
|
||||
let axes = crate::abstract_interp::path_domain::classify_path_rejection_axes(
|
||||
cond_text,
|
||||
);
|
||||
if !axes.is_empty() {
|
||||
result.push((idx, Cap::FILE_IO));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if info.kind != StmtKind::Call {
|
||||
continue;
|
||||
}
|
||||
if let Some(callee) = &info.callee {
|
||||
if let Some(callee) = &info.call.callee {
|
||||
// Check config sanitizer rules first
|
||||
if let Some(cap) = match_config_sanitizer(callee, config_rules) {
|
||||
result.push((idx, cap));
|
||||
|
|
@ -116,10 +685,10 @@ fn taint_confirms_sink(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
|
|||
/// Source node in the same function (via simple def-use chain).
|
||||
fn sink_arg_is_source_derived(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
|
||||
let sink_info = &ctx.cfg[sink];
|
||||
let sink_func = sink_info.enclosing_func.as_deref();
|
||||
let sink_func = sink_info.ast.enclosing_func.as_deref();
|
||||
|
||||
// Collect all variables the sink reads
|
||||
let sink_uses = &sink_info.uses;
|
||||
let sink_uses = &sink_info.taint.uses;
|
||||
if sink_uses.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
|
@ -128,14 +697,19 @@ fn sink_arg_is_source_derived(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
|
|||
// one of the variables the sink uses.
|
||||
for idx in ctx.cfg.node_indices() {
|
||||
let info = &ctx.cfg[idx];
|
||||
if info.enclosing_func.as_deref() != sink_func {
|
||||
if info.ast.enclosing_func.as_deref() != sink_func {
|
||||
continue;
|
||||
}
|
||||
if !matches!(info.label, Some(DataLabel::Source(_))) {
|
||||
if !info
|
||||
.taint
|
||||
.labels
|
||||
.iter()
|
||||
.any(|l| matches!(l, DataLabel::Source(_)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// Source node defines a variable that the sink reads → source-derived
|
||||
if let Some(def) = &info.defines
|
||||
if let Some(def) = &info.taint.defines
|
||||
&& sink_uses.iter().any(|u| u == def)
|
||||
{
|
||||
return true;
|
||||
|
|
@ -148,9 +722,9 @@ fn sink_arg_is_source_derived(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
|
|||
/// (i.e. this function is a thin wrapper around the sink).
|
||||
fn sink_arg_is_parameter_only(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
|
||||
let sink_info = &ctx.cfg[sink];
|
||||
let sink_func = sink_info.enclosing_func.as_deref();
|
||||
let sink_func = sink_info.ast.enclosing_func.as_deref();
|
||||
|
||||
let sink_uses = &sink_info.uses;
|
||||
let sink_uses = &sink_info.taint.uses;
|
||||
if sink_uses.is_empty() {
|
||||
// No identifiable arguments — could be a constant call like Command::new("ls")
|
||||
return true; // treat as non-dangerous (constant arg)
|
||||
|
|
@ -162,7 +736,7 @@ fn sink_arg_is_parameter_only(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
|
|||
.values()
|
||||
.filter(|s| {
|
||||
// Match by function entry being in the same function
|
||||
ctx.cfg[s.entry].enclosing_func.as_deref() == sink_func
|
||||
ctx.cfg[s.entry].ast.enclosing_func.as_deref() == sink_func
|
||||
})
|
||||
.flat_map(|s| s.param_names.iter().map(|p| p.as_str()))
|
||||
.collect();
|
||||
|
|
@ -175,10 +749,60 @@ fn sink_arg_is_parameter_only(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
|
|||
sink_uses.iter().all(|u| param_names.contains(&u.as_str()))
|
||||
}
|
||||
|
||||
/// Check if the source bytes at a given span contain a redirect call whose
|
||||
/// argument starts with a path prefix (`/...`), indicating a server-relative
|
||||
/// path rather than an attacker-controlled URL.
|
||||
///
|
||||
/// Reused by both `cfg-unguarded-sink` suppression and taint finding filtering.
|
||||
pub(crate) fn has_redirect_path_prefix(source_bytes: &[u8], span: (usize, usize)) -> bool {
|
||||
let (start, end) = span;
|
||||
if start >= source_bytes.len() || end > source_bytes.len() {
|
||||
return false;
|
||||
}
|
||||
let text = &source_bytes[start..end];
|
||||
// Search for the argument portion after the first '('
|
||||
if let Some(paren_pos) = text.iter().position(|&b| b == b'(') {
|
||||
let after_paren = &text[paren_pos + 1..];
|
||||
let trimmed = after_paren
|
||||
.iter()
|
||||
.skip_while(|&&b| b == b' ' || b == b'\n' || b == b'\t')
|
||||
.copied()
|
||||
.collect::<Vec<_>>();
|
||||
// Template literal: `/ ...
|
||||
if trimmed.starts_with(b"`/") {
|
||||
return true;
|
||||
}
|
||||
// String literal: "/ ... or '/ ...
|
||||
if trimmed.starts_with(b"\"/") || trimmed.starts_with(b"'/") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Check if this sink is an internal redirect — a `res.redirect` (SSRF sink)
|
||||
/// whose argument is a template literal or string starting with `/`, indicating
|
||||
/// a server-relative path rather than an attacker-controlled URL.
|
||||
fn is_internal_redirect(ctx: &AnalysisContext, sink: NodeIndex, sink_caps: Cap) -> bool {
|
||||
if !sink_caps.contains(Cap::SSRF) {
|
||||
return false;
|
||||
}
|
||||
let sink_info = &ctx.cfg[sink];
|
||||
let callee = match &sink_info.call.callee {
|
||||
Some(c) => c.as_str(),
|
||||
None => return false,
|
||||
};
|
||||
// Only applies to redirect calls
|
||||
if !callee.ends_with("redirect") && !callee.ends_with("Redirect") {
|
||||
return false;
|
||||
}
|
||||
has_redirect_path_prefix(ctx.source_bytes, sink_info.ast.span)
|
||||
}
|
||||
|
||||
/// Check if the enclosing function qualifies as an entrypoint.
|
||||
fn sink_in_entrypoint(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
|
||||
let sink_info = &ctx.cfg[sink];
|
||||
if let Some(func_name) = &sink_info.enclosing_func {
|
||||
if let Some(func_name) = &sink_info.ast.enclosing_func {
|
||||
is_entry_point_func(func_name, ctx.lang)
|
||||
} else {
|
||||
false
|
||||
|
|
@ -199,17 +823,23 @@ impl CfgAnalysis for UnguardedSink {
|
|||
|
||||
for sink in &sink_nodes {
|
||||
let sink_info = &ctx.cfg[*sink];
|
||||
let sink_caps = match sink_info.label {
|
||||
Some(DataLabel::Sink(caps)) => caps,
|
||||
_ => continue,
|
||||
};
|
||||
let sink_caps = sink_info.taint.labels.iter().fold(Cap::empty(), |acc, l| {
|
||||
if let DataLabel::Sink(caps) = l {
|
||||
acc | *caps
|
||||
} else {
|
||||
acc
|
||||
}
|
||||
});
|
||||
if sink_caps.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let sink_func = sink_info.enclosing_func.as_deref();
|
||||
let sink_func = sink_info.ast.enclosing_func.as_deref();
|
||||
|
||||
// Check: does any applicable guard dominate this sink?
|
||||
// Guards must be in the same function to be relevant.
|
||||
let is_guarded = guard_nodes.iter().any(|(guard_idx, guard_caps)| {
|
||||
let guard_func = ctx.cfg[*guard_idx].enclosing_func.as_deref();
|
||||
let guard_func = ctx.cfg[*guard_idx].ast.enclosing_func.as_deref();
|
||||
(*guard_caps & sink_caps) != Cap::empty()
|
||||
&& guard_func == sink_func
|
||||
&& dominates(&doms, *guard_idx, *sink)
|
||||
|
|
@ -217,21 +847,37 @@ impl CfgAnalysis for UnguardedSink {
|
|||
|
||||
// Also check if an inline sanitizer dominates this sink (same function).
|
||||
let has_sanitizer = ctx.cfg.node_indices().any(|idx| {
|
||||
let node_func = ctx.cfg[idx].enclosing_func.as_deref();
|
||||
if let Some(DataLabel::Sanitizer(san_caps)) = ctx.cfg[idx].label {
|
||||
(san_caps & sink_caps) != Cap::empty()
|
||||
&& node_func == sink_func
|
||||
&& dominates(&doms, idx, *sink)
|
||||
let node_func = ctx.cfg[idx].ast.enclosing_func.as_deref();
|
||||
ctx.cfg[idx].taint.labels.iter().any(|l| {
|
||||
if let DataLabel::Sanitizer(san_caps) = l {
|
||||
(*san_caps & sink_caps) != Cap::empty()
|
||||
&& node_func == sink_func
|
||||
&& dominates(&doms, idx, *sink)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
// Interprocedural sanitizer: check if any arg_callee resolves to a
|
||||
// function with sanitizer caps that cover this sink's caps.
|
||||
let has_interprocedural_sanitizer = sink_info.arg_callees.iter().any(|mc| {
|
||||
if let Some(callee) = mc {
|
||||
let leaf = callee_leaf_name(callee);
|
||||
// Check local function summaries
|
||||
ctx.func_summaries.iter().any(|(k, s)| {
|
||||
k.name == leaf && (s.sanitizer_caps & sink_caps) != Cap::empty()
|
||||
})
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
|
||||
if is_guarded || has_sanitizer {
|
||||
if is_guarded || has_sanitizer || has_interprocedural_sanitizer {
|
||||
continue;
|
||||
}
|
||||
|
||||
let callee_desc = sink_info.callee.as_deref().unwrap_or("(unknown sink)");
|
||||
let callee_desc = sink_info.call.callee.as_deref().unwrap_or("(unknown sink)");
|
||||
|
||||
// ── Severity classification ───────────────────────────────
|
||||
//
|
||||
|
|
@ -244,7 +890,53 @@ impl CfgAnalysis for UnguardedSink {
|
|||
|
||||
// If sink args are all constants (including one-hop constant bindings)
|
||||
// and taint didn't confirm, this is a false positive — skip it.
|
||||
if is_all_args_constant(ctx, *sink) && !has_taint && !source_derived {
|
||||
if is_all_args_constant(ctx, *sink) && !has_taint {
|
||||
continue;
|
||||
}
|
||||
|
||||
// SSA latest-def suppression: when the taint engine has already
|
||||
// proved no source-tainted data reaches this sink (`!has_taint`)
|
||||
// and every SSA operand resolves to a constant, callee-fragment
|
||||
// pseudo-name, OR a function parameter that is not a Source —
|
||||
// the sink's actual arguments cannot carry an injection payload.
|
||||
// Catches the reassign-to-constant idiom (`name := req.x; name =
|
||||
// "Guest"; sink(name)`) where the latest SSA def is a literal
|
||||
// and a non-payload parameter (e.g. an HTTP writer / receiver)
|
||||
// is the only other operand. The simpler `is_all_args_constant`
|
||||
// check above rejects that mixed shape because it forbids real
|
||||
// parameters in operand position.
|
||||
if !has_taint && ssa_all_sink_operands_const_or_param(ctx, *sink) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Type-aware suppression: when all SSA operand values of the sink
|
||||
// are proven to carry non-injectable types (e.g. integers parsed
|
||||
// from a raw source), the arguments cannot form a payload for
|
||||
// SHELL/SQL/FILE sinks. Skip the structural finding — the taint
|
||||
// engine already covers the source→sink flow via type-aware
|
||||
// suppression. Unknown-typed or mixed operands fall through.
|
||||
if !has_taint && sink_args_typed_safe(ctx, *sink, sink_caps) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Static-map suppression: the SSA value flowing into the sink is
|
||||
// proved by the static-HashMap-lookup idiom detector to be a
|
||||
// finite set of literals free of shell metacharacters. Mirrors
|
||||
// the SSA-taint finite-domain suppression so both paths agree.
|
||||
if !has_taint && sink_args_static_map_safe(ctx, *sink, sink_caps) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Parameterized SQL queries: arg 0 is a string literal with
|
||||
// placeholders ($1, ?, %s, :name) and a params argument exists.
|
||||
// These are safe by construction — the driver handles escaping.
|
||||
if sink_info.parameterized_query {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Internal redirects: res.redirect(`/path/...`) with a path-prefix
|
||||
// argument are server-relative — not attacker-controlled URLs.
|
||||
if is_internal_redirect(ctx, *sink, sink_caps) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -252,19 +944,45 @@ impl CfgAnalysis for UnguardedSink {
|
|||
let in_entrypoint = sink_in_entrypoint(ctx, *sink);
|
||||
|
||||
let (severity, confidence) = if has_taint || source_derived {
|
||||
// Taint-confirmed or directly source-derived → HIGH
|
||||
(Severity::High, Confidence::High)
|
||||
} else if param_only && !in_entrypoint {
|
||||
// Wrapper function consuming only parameters → LOW
|
||||
// Wrapper function with param-only args — zero signal. Suppress.
|
||||
continue;
|
||||
} else if !ctx.taint_active {
|
||||
// AST-only / cfg-only mode — preserve as LOW (unchanged)
|
||||
(Severity::Low, Confidence::Low)
|
||||
} else if !ctx.taint_active && !source_derived {
|
||||
// CFG-only mode without taint confirmation → LOW
|
||||
(Severity::Low, Confidence::Low)
|
||||
} else if in_entrypoint && !param_only {
|
||||
// Entrypoint with non-parameter args but no taint confirmation → MEDIUM
|
||||
(Severity::Medium, Confidence::Medium)
|
||||
} else {
|
||||
// Generic structural finding → MEDIUM
|
||||
// taint_active=true but found nothing.
|
||||
// Keep high-risk sinks (SHELL_ESCAPE, CODE_EXEC, SQL_QUERY, DESERIALIZE)
|
||||
// as structural backup. Suppress low-risk sinks (FILE_IO, SSRF, etc.).
|
||||
let high_risk =
|
||||
Cap::SHELL_ESCAPE | Cap::CODE_EXEC | Cap::SQL_QUERY | Cap::DESERIALIZE;
|
||||
if (sink_caps & high_risk).is_empty() {
|
||||
continue; // FILE_IO, SSRF, FMT_STRING etc. without taint → noise
|
||||
}
|
||||
// If the function containing the sink has no Source-labeled
|
||||
// nodes AND no parameters (through which taint could flow
|
||||
// from callers), taint ran and found nothing because there
|
||||
// is nothing to find. Suppress — the structural finding
|
||||
// is noise.
|
||||
let sink_func = sink_info.ast.enclosing_func.as_deref();
|
||||
let has_sources = ctx.cfg.node_indices().any(|n| {
|
||||
let info = &ctx.cfg[n];
|
||||
info.ast.enclosing_func.as_deref() == sink_func
|
||||
&& info
|
||||
.taint
|
||||
.labels
|
||||
.iter()
|
||||
.any(|l| matches!(l, DataLabel::Source(_)))
|
||||
});
|
||||
let has_params = ctx.func_summaries.values().any(|s| {
|
||||
s.entry.index() < ctx.cfg.node_count()
|
||||
&& ctx.cfg[s.entry].ast.enclosing_func.as_deref() == sink_func
|
||||
&& !s.param_names.is_empty()
|
||||
});
|
||||
if !has_sources && !has_params {
|
||||
continue; // No sources or params in scope → noise
|
||||
}
|
||||
(Severity::Medium, Confidence::Medium)
|
||||
};
|
||||
|
||||
|
|
@ -273,7 +991,7 @@ impl CfgAnalysis for UnguardedSink {
|
|||
title: "Unguarded sink".to_string(),
|
||||
severity,
|
||||
confidence,
|
||||
span: sink_info.span,
|
||||
span: sink_info.ast.span,
|
||||
message: format!("Sink `{callee_desc}` has no dominating guard or sanitizer"),
|
||||
evidence: vec![*sink],
|
||||
score: None,
|
||||
|
|
|
|||
|
|
@ -12,11 +12,43 @@ pub mod unreachable;
|
|||
use crate::cfg::{FuncSummaries, NodeInfo, StmtKind};
|
||||
use crate::labels::{DataLabel, LangAnalysisRules};
|
||||
use crate::patterns::Severity;
|
||||
use crate::ssa::const_prop::ConstLattice;
|
||||
use crate::ssa::type_facts::TypeFactResult;
|
||||
use crate::ssa::{SsaBody, SsaValue};
|
||||
use crate::summary::GlobalSummaries;
|
||||
use crate::symbol::Lang;
|
||||
use crate::taint;
|
||||
use petgraph::graph::NodeIndex;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Per-body SSA facts used by structural analyses for finer-grained
|
||||
/// constancy checks. Produced once per body in `run_cfg_analyses` and
|
||||
/// passed via `AnalysisContext::body_const_facts`.
|
||||
pub struct BodyConstFacts {
|
||||
pub ssa: SsaBody,
|
||||
pub const_values: HashMap<SsaValue, ConstLattice>,
|
||||
pub type_facts: TypeFactResult,
|
||||
}
|
||||
|
||||
/// Lower a body to SSA and run constant propagation. Returns `None` when
|
||||
/// lowering fails (empty CFG, invalid entry) — callers treat absence as
|
||||
/// "no SSA facts available" and fall back to the syntactic path.
|
||||
pub fn build_body_const_facts(body: &crate::cfg::BodyCfg, lang: Lang) -> Option<BodyConstFacts> {
|
||||
let mut ssa = crate::ssa::lower_to_ssa_with_params(
|
||||
&body.graph,
|
||||
body.entry,
|
||||
body.meta.name.as_deref(),
|
||||
body.meta.parent_body_id.is_none(),
|
||||
&body.meta.params,
|
||||
)
|
||||
.ok()?;
|
||||
let opt = crate::ssa::optimize_ssa(&mut ssa, &body.graph, Some(lang));
|
||||
Some(BodyConstFacts {
|
||||
ssa,
|
||||
const_values: opt.const_values,
|
||||
type_facts: opt.type_facts,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Confidence {
|
||||
|
|
@ -55,6 +87,24 @@ pub struct AnalysisContext<'a> {
|
|||
/// existed and taint engine ran). When false, structural findings without
|
||||
/// taint confirmation should be treated with lower confidence.
|
||||
pub taint_active: bool,
|
||||
/// Optional per-body SSA + constant-propagation facts. When present,
|
||||
/// structural analyses can use SSA const-prop to prove that all argument
|
||||
/// flows into a sink resolve to literal constants, suppressing false
|
||||
/// positives that the one-hop CFG trace alone cannot.
|
||||
pub body_const_facts: Option<&'a BodyConstFacts>,
|
||||
/// Optional per-body type-fact result produced by `optimize_ssa`.
|
||||
/// Structural analyses use it to suppress findings when a sink's argument
|
||||
/// SSA values are proven to carry non-injectable types (e.g. integers
|
||||
/// parsed from a raw source can't form SHELL/SQL/path payloads). Sourced
|
||||
/// from `body_const_facts` when present — keep both pointers coherent.
|
||||
pub type_facts: Option<&'a TypeFactResult>,
|
||||
/// Decorators / annotations / attributes attached to the body's
|
||||
/// declaration (e.g. Python `@login_required`, Java `@PreAuthorize`,
|
||||
/// Symfony `#[IsGranted(...)]`). Consumed by the AuthGap analysis to
|
||||
/// suppress `cfg-auth-gap` when the framework already enforces auth at
|
||||
/// the function-declaration level — the gap only matters when the
|
||||
/// auth call has to live inside the body.
|
||||
pub auth_decorators: &'a [String],
|
||||
}
|
||||
|
||||
pub trait CfgAnalysis {
|
||||
|
|
@ -79,7 +129,7 @@ pub fn run_all(ctx: &AnalysisContext) -> Vec<CfgFinding> {
|
|||
let taint_spans: HashSet<(usize, usize)> = ctx
|
||||
.taint_findings
|
||||
.iter()
|
||||
.map(|f| ctx.cfg[f.sink].span)
|
||||
.map(|f| ctx.cfg[f.sink].ast.span)
|
||||
.collect();
|
||||
|
||||
findings.retain(|f| {
|
||||
|
|
@ -123,7 +173,7 @@ pub(crate) fn is_guard_call(
|
|||
if info.kind != StmtKind::Call {
|
||||
return false;
|
||||
}
|
||||
if let Some(callee) = &info.callee {
|
||||
if let Some(callee) = &info.call.callee {
|
||||
// Check config sanitizer rules
|
||||
if let Some(extras) = analysis_rules {
|
||||
let callee_lower = callee.to_ascii_lowercase();
|
||||
|
|
@ -168,7 +218,7 @@ pub(crate) fn is_auth_call(info: &NodeInfo, lang: Lang) -> bool {
|
|||
if info.kind != StmtKind::Call {
|
||||
return false;
|
||||
}
|
||||
if let Some(callee) = &info.callee {
|
||||
if let Some(callee) = &info.call.callee {
|
||||
let auth_rules = rules::auth_rules(lang);
|
||||
let callee_lower = callee.to_ascii_lowercase();
|
||||
for rule in auth_rules {
|
||||
|
|
@ -209,5 +259,8 @@ pub(crate) fn is_entry_point_func(func_name: &str, lang: Lang) -> bool {
|
|||
|
||||
/// Helper: check if a node is a sink.
|
||||
pub(crate) fn is_sink(info: &NodeInfo) -> bool {
|
||||
matches!(info.label, Some(DataLabel::Sink(_)))
|
||||
info.taint
|
||||
.labels
|
||||
.iter()
|
||||
.any(|l| matches!(l, DataLabel::Sink(_)))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
use super::dominators;
|
||||
use super::rules;
|
||||
use super::{AnalysisContext, CfgAnalysis, CfgFinding, Confidence};
|
||||
use crate::cfg::StmtKind;
|
||||
use crate::cfg::{EdgeKind, StmtKind};
|
||||
use crate::patterns::Severity;
|
||||
use petgraph::graph::NodeIndex;
|
||||
use petgraph::visit::EdgeRef;
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub struct ResourceMisuse;
|
||||
|
|
@ -22,7 +23,7 @@ fn find_acquire_nodes(
|
|||
if info.kind != StmtKind::Call {
|
||||
return false;
|
||||
}
|
||||
if let Some(callee) = &info.callee {
|
||||
if let Some(callee) = &info.call.callee {
|
||||
let callee_lower = callee.to_ascii_lowercase();
|
||||
// Check exclusions first — if the callee matches an exclude
|
||||
// pattern, it is NOT an acquire even if it also matches an
|
||||
|
|
@ -54,7 +55,7 @@ fn find_release_nodes(ctx: &AnalysisContext, release_patterns: &[&str]) -> Vec<N
|
|||
if info.kind != StmtKind::Call {
|
||||
return false;
|
||||
}
|
||||
if let Some(callee) = &info.callee {
|
||||
if let Some(callee) = &info.call.callee {
|
||||
let callee_lower = callee.to_ascii_lowercase();
|
||||
release_patterns.iter().any(|p| {
|
||||
let pl = p.to_ascii_lowercase();
|
||||
|
|
@ -68,6 +69,14 @@ fn find_release_nodes(ctx: &AnalysisContext, release_patterns: &[&str]) -> Vec<N
|
|||
}
|
||||
|
||||
/// Check if a release node is on all paths from acquire to every exit.
|
||||
///
|
||||
/// Treats null-guard-false edges as not-applicable: when control reaches an
|
||||
/// `if (acquire_var)` (or `if (!acquire_var)`) and the edge represents
|
||||
/// "acquire_var is null", the resource was never actually produced on that
|
||||
/// path, so a release is unnecessary. This closes the canonical
|
||||
/// `FILE *f = fopen(...); if (f) fclose(f);` idiom — without this rule the
|
||||
/// false edge of the null check provides a path acquire→exit that misses
|
||||
/// the release, producing a may-leak FP.
|
||||
fn release_on_all_exit_paths(
|
||||
ctx: &AnalysisContext,
|
||||
acquire: NodeIndex,
|
||||
|
|
@ -83,18 +92,65 @@ fn release_on_all_exit_paths(
|
|||
}
|
||||
}
|
||||
|
||||
// Fall back to path enumeration via DFS
|
||||
// Check if all paths from acquire to exit pass through a release
|
||||
// Fall back to path enumeration with null-guard pruning.
|
||||
let acquire_var = ctx.cfg[acquire].taint.defines.as_deref();
|
||||
let release_set: HashSet<_> = release_nodes.iter().copied().collect();
|
||||
all_paths_pass_through(ctx, acquire, exit, &release_set)
|
||||
all_paths_pass_through(ctx, acquire, exit, &release_set, acquire_var)
|
||||
}
|
||||
|
||||
/// Check if all paths from `from` to `to` pass through at least one node in `through`.
|
||||
/// Identify whether a CFG edge is the "null-guard false edge" for the named
|
||||
/// acquired variable. Returns `true` for the edge that, if traversed, means
|
||||
/// the resource handle is null/falsy and therefore not actually acquired.
|
||||
///
|
||||
/// Recognises:
|
||||
/// * `if (var)` — false edge means `var` is null
|
||||
/// * `if (!var)` — true edge means `var` is null
|
||||
///
|
||||
/// Rejects comparisons (`if (var != NULL)`), method calls
|
||||
/// (`if (var.is_valid())`), and composite conditions (`if (var && cond)`).
|
||||
fn is_null_guard_false_edge(
|
||||
ctx: &AnalysisContext,
|
||||
src: NodeIndex,
|
||||
edge_kind: EdgeKind,
|
||||
acquire_var: &str,
|
||||
) -> bool {
|
||||
let info = &ctx.cfg[src];
|
||||
if info.kind != StmtKind::If {
|
||||
return false;
|
||||
}
|
||||
if info.condition_vars.len() != 1 || info.condition_vars[0] != acquire_var {
|
||||
return false;
|
||||
}
|
||||
let Some(text) = info.condition_text.as_deref() else {
|
||||
return false;
|
||||
};
|
||||
let stripped = text
|
||||
.trim()
|
||||
.trim_start_matches('!')
|
||||
.trim()
|
||||
.trim_matches(|c: char| c == '(' || c == ')')
|
||||
.trim();
|
||||
if stripped != acquire_var {
|
||||
return false;
|
||||
}
|
||||
// Choose the null edge: false for plain truth check, true for negated.
|
||||
let null_edge = if info.condition_negated {
|
||||
EdgeKind::True
|
||||
} else {
|
||||
EdgeKind::False
|
||||
};
|
||||
edge_kind == null_edge
|
||||
}
|
||||
|
||||
/// Check if all paths from `from` to `to` pass through at least one node in `through`,
|
||||
/// pruning null-guard-false edges for the acquired variable so the canonical
|
||||
/// `if (var) release(var);` idiom is recognised as a complete release.
|
||||
fn all_paths_pass_through(
|
||||
ctx: &AnalysisContext,
|
||||
from: NodeIndex,
|
||||
to: NodeIndex,
|
||||
through: &HashSet<NodeIndex>,
|
||||
acquire_var: Option<&str>,
|
||||
) -> bool {
|
||||
use std::collections::VecDeque;
|
||||
|
||||
|
|
@ -116,7 +172,15 @@ fn all_paths_pass_through(
|
|||
continue;
|
||||
}
|
||||
|
||||
for succ in ctx.cfg.neighbors(node) {
|
||||
for edge in ctx.cfg.edges(node) {
|
||||
// Prune null-guard-false edges: those represent "var is null",
|
||||
// a path on which the resource was never actually acquired.
|
||||
if let Some(var) = acquire_var
|
||||
&& is_null_guard_false_edge(ctx, node, *edge.weight(), var)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let succ = edge.target();
|
||||
let new_passed = passed || through.contains(&succ);
|
||||
let state = (succ, new_passed);
|
||||
if visited.insert(state) {
|
||||
|
|
@ -137,7 +201,7 @@ fn all_paths_pass_through(
|
|||
/// If the variable is transferred, there is no leak — the receiving struct is
|
||||
/// responsible for the lifetime.
|
||||
fn is_ownership_transferred(ctx: &AnalysisContext, acquire: NodeIndex) -> bool {
|
||||
let acquired_var = match &ctx.cfg[acquire].defines {
|
||||
let acquired_var = match &ctx.cfg[acquire].taint.defines {
|
||||
Some(v) => v.clone(),
|
||||
None => return false,
|
||||
};
|
||||
|
|
@ -155,12 +219,16 @@ fn is_ownership_transferred(ctx: &AnalysisContext, acquire: NodeIndex) -> bool {
|
|||
|
||||
while let Some(node) = queue.pop_front() {
|
||||
let info = &ctx.cfg[node];
|
||||
let (start, end) = info.span;
|
||||
let (start, end) = info.ast.span;
|
||||
|
||||
// Check the source text at this node's span for the acquired variable
|
||||
// appearing in a struct-field store context.
|
||||
let references_var = info.uses.iter().any(|u| u == &acquired_var)
|
||||
|| info.defines.as_ref().is_some_and(|d| d == &acquired_var);
|
||||
let references_var = info.taint.uses.iter().any(|u| u == &acquired_var)
|
||||
|| info
|
||||
.taint
|
||||
.defines
|
||||
.as_ref()
|
||||
.is_some_and(|d| d == &acquired_var);
|
||||
|
||||
if references_var && start < end && end <= ctx.source_bytes.len() {
|
||||
let span_text = &ctx.source_bytes[start..end];
|
||||
|
|
@ -177,7 +245,12 @@ fn is_ownership_transferred(ctx: &AnalysisContext, acquire: NodeIndex) -> bool {
|
|||
// If the variable is truly redefined (not a field write), stop
|
||||
// following this path. A true redefinition is when `defines` matches
|
||||
// but the span doesn't contain `->` or `.field =` patterns.
|
||||
if info.defines.as_ref().is_some_and(|d| d == &acquired_var) {
|
||||
if info
|
||||
.taint
|
||||
.defines
|
||||
.as_ref()
|
||||
.is_some_and(|d| d == &acquired_var)
|
||||
{
|
||||
let is_field_write = if start < end && end <= ctx.source_bytes.len() {
|
||||
let span_text = &ctx.source_bytes[start..end];
|
||||
span_text.windows(2).any(|w| w == b"->") || has_dot_field_assignment(span_text)
|
||||
|
|
@ -242,7 +315,7 @@ fn is_consumed_by_owner(ctx: &AnalysisContext, acquire: NodeIndex) -> bool {
|
|||
"make_response",
|
||||
];
|
||||
|
||||
let acquired_var = match &ctx.cfg[acquire].defines {
|
||||
let acquired_var = match &ctx.cfg[acquire].taint.defines {
|
||||
Some(v) => v.clone(),
|
||||
None => return false,
|
||||
};
|
||||
|
|
@ -261,19 +334,19 @@ fn is_consumed_by_owner(ctx: &AnalysisContext, acquire: NodeIndex) -> bool {
|
|||
|
||||
// Check Call nodes with callee that matches a consuming sink
|
||||
if info.kind == StmtKind::Call
|
||||
&& let Some(callee) = &info.callee
|
||||
&& let Some(callee) = &info.call.callee
|
||||
{
|
||||
let callee_lower = callee.to_ascii_lowercase();
|
||||
let is_consuming = CONSUMING_SINKS.iter().any(|s| callee_lower.ends_with(s));
|
||||
if is_consuming && info.uses.iter().any(|u| u == &acquired_var) {
|
||||
if is_consuming && info.taint.uses.iter().any(|u| u == &acquired_var) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Also check the span text for consuming calls — handles cases where
|
||||
// the call is embedded in a return statement (e.g. `return FileResponse(f)`)
|
||||
if info.uses.iter().any(|u| u == &acquired_var) {
|
||||
let (start, end) = info.span;
|
||||
if info.taint.uses.iter().any(|u| u == &acquired_var) {
|
||||
let (start, end) = info.ast.span;
|
||||
if start < end && end <= ctx.source_bytes.len() {
|
||||
let span_lower: Vec<u8> = ctx.source_bytes[start..end]
|
||||
.iter()
|
||||
|
|
@ -302,7 +375,7 @@ fn is_consumed_by_owner(ctx: &AnalysisContext, acquire: NodeIndex) -> bool {
|
|||
/// exists on the acquired variable in the CFG. If only the constructor
|
||||
/// (e.g. `threading.Lock()`) is observed without acquire, skip the finding.
|
||||
fn has_explicit_lock_acquire(ctx: &AnalysisContext, acquire: NodeIndex) -> bool {
|
||||
let acquired_var = match &ctx.cfg[acquire].defines {
|
||||
let acquired_var = match &ctx.cfg[acquire].taint.defines {
|
||||
Some(v) => v.clone(),
|
||||
None => return false,
|
||||
};
|
||||
|
|
@ -312,12 +385,12 @@ fn has_explicit_lock_acquire(ctx: &AnalysisContext, acquire: NodeIndex) -> bool
|
|||
if info.kind != StmtKind::Call {
|
||||
continue;
|
||||
}
|
||||
if let Some(callee) = &info.callee {
|
||||
if let Some(callee) = &info.call.callee {
|
||||
let callee_lower = callee.to_ascii_lowercase();
|
||||
let is_lock_call = callee_lower.ends_with(".acquire")
|
||||
|| callee_lower.ends_with(".lock")
|
||||
|| callee_lower == "pthread_mutex_lock";
|
||||
if is_lock_call && info.uses.iter().any(|u| u == &acquired_var) {
|
||||
if is_lock_call && info.taint.uses.iter().any(|u| u == &acquired_var) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -345,6 +418,22 @@ impl CfgAnalysis for ResourceMisuse {
|
|||
let release_nodes = find_release_nodes(ctx, pair.release);
|
||||
|
||||
for &acquire in &acquire_nodes {
|
||||
// Suppress resources inside managed cleanup scopes
|
||||
// (Python `with`, Java try-with-resources).
|
||||
if ctx.cfg[acquire].managed_resource {
|
||||
continue;
|
||||
}
|
||||
// Suppress resources with a deferred release (Go `defer f.Close()`).
|
||||
// Defer guarantees cleanup on all exit paths including early returns.
|
||||
if let Some(acquired_var) = ctx.cfg[acquire].taint.defines.as_deref() {
|
||||
let has_deferred_release = release_nodes.iter().any(|&r| {
|
||||
ctx.cfg[r].in_defer
|
||||
&& ctx.cfg[r].taint.uses.iter().any(|u| u == acquired_var)
|
||||
});
|
||||
if has_deferred_release {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if !release_on_all_exit_paths(ctx, acquire, &release_nodes, exit)
|
||||
&& !is_ownership_transferred(ctx, acquire)
|
||||
&& !is_consumed_by_owner(ctx, acquire)
|
||||
|
|
@ -354,7 +443,7 @@ impl CfgAnalysis for ResourceMisuse {
|
|||
continue;
|
||||
}
|
||||
let info = &ctx.cfg[acquire];
|
||||
let callee_desc = info.callee.as_deref().unwrap_or("(acquire)");
|
||||
let callee_desc = info.call.callee.as_deref().unwrap_or("(acquire)");
|
||||
|
||||
findings.push(CfgFinding {
|
||||
rule_id: if pair.resource_name == "mutex" {
|
||||
|
|
@ -365,7 +454,7 @@ impl CfgAnalysis for ResourceMisuse {
|
|||
title: format!("{} may leak", pair.resource_name),
|
||||
severity: Severity::Medium,
|
||||
confidence: Confidence::Medium,
|
||||
span: info.span,
|
||||
span: info.ast.span,
|
||||
message: format!(
|
||||
"`{callee_desc}` acquires {} but not all exit paths \
|
||||
release it",
|
||||
|
|
|
|||
|
|
@ -25,6 +25,10 @@ pub struct ResourcePair {
|
|||
/// but should NOT be treated as acquisitions.
|
||||
pub exclude_acquire: &'static [&'static str],
|
||||
pub resource_name: &'static str,
|
||||
/// Callee patterns that read/write/operate on this specific resource type,
|
||||
/// triggering use-after-close if the handle is closed. Checked before the
|
||||
/// global `RESOURCE_USE_PATTERNS` fallback.
|
||||
pub use_patterns: &'static [&'static str],
|
||||
}
|
||||
|
||||
// ── Guard rules ─────────────────────────────────────────────────────────
|
||||
|
|
@ -82,6 +86,12 @@ static COMMON_AUTH: &[AuthRule] = &[AuthRule {
|
|||
"check_auth",
|
||||
"verify_token",
|
||||
"validate_token",
|
||||
// Additional patterns
|
||||
"ensureAuthenticated",
|
||||
"ensureAuth",
|
||||
"requireAuth",
|
||||
"hasPermission",
|
||||
"requireRole",
|
||||
],
|
||||
}];
|
||||
|
||||
|
|
@ -99,6 +109,12 @@ static GO_AUTH: &[AuthRule] = &[AuthRule {
|
|||
"validate_token",
|
||||
"middleware.auth",
|
||||
"auth.required",
|
||||
// Additional patterns
|
||||
"ensureAuthenticated",
|
||||
"ensureAuth",
|
||||
"requireAuth",
|
||||
"hasPermission",
|
||||
"requireRole",
|
||||
],
|
||||
}];
|
||||
|
||||
|
|
@ -118,6 +134,163 @@ static JAVA_AUTH: &[AuthRule] = &[AuthRule {
|
|||
"checkPermission",
|
||||
"hasAuthority",
|
||||
"hasRole",
|
||||
// Additional patterns
|
||||
"ensureAuthenticated",
|
||||
"ensureAuth",
|
||||
"requireAuth",
|
||||
"hasPermission",
|
||||
"requireRole",
|
||||
// Spring Security / JAX-RS annotation names (used by decorator
|
||||
// detection — see `extract_auth_decorators` in src/cfg.rs).
|
||||
"PreAuthorize",
|
||||
"PostAuthorize",
|
||||
"Secured",
|
||||
"RolesAllowed",
|
||||
"DenyAll",
|
||||
"Authenticated",
|
||||
],
|
||||
}];
|
||||
|
||||
static JS_AUTH: &[AuthRule] = &[AuthRule {
|
||||
matchers: &[
|
||||
"is_authenticated",
|
||||
"require_auth",
|
||||
"check_permission",
|
||||
"is_admin",
|
||||
"authorize",
|
||||
"authenticate",
|
||||
"require_login",
|
||||
"check_auth",
|
||||
"verify_token",
|
||||
"validate_token",
|
||||
// JS/TS middleware & JWT
|
||||
"ensureAuthenticated",
|
||||
"ensureAuth",
|
||||
"requireAuth",
|
||||
"hasPermission",
|
||||
"requireRole",
|
||||
"checkRole",
|
||||
"passport.authenticate",
|
||||
"jwt.verify",
|
||||
// NestJS-style decorators and guard class names (seeded by decorator
|
||||
// arg extraction in `extract_auth_decorators`). `UseGuards` alone is
|
||||
// too generic — we still match on guard *argument* identifiers here.
|
||||
"Authenticated",
|
||||
"AuthGuard",
|
||||
"JwtAuthGuard",
|
||||
"JwtGuard",
|
||||
"RolesGuard",
|
||||
"SessionGuard",
|
||||
"PassportAuthGuard",
|
||||
],
|
||||
}];
|
||||
|
||||
static PYTHON_AUTH: &[AuthRule] = &[AuthRule {
|
||||
matchers: &[
|
||||
"is_authenticated",
|
||||
"require_auth",
|
||||
"check_permission",
|
||||
"is_admin",
|
||||
"authorize",
|
||||
"authenticate",
|
||||
"require_login",
|
||||
"check_auth",
|
||||
"verify_token",
|
||||
"validate_token",
|
||||
// Python-specific
|
||||
"ensureAuthenticated",
|
||||
"ensureAuth",
|
||||
"requireAuth",
|
||||
"hasPermission",
|
||||
"requireRole",
|
||||
"login_required",
|
||||
"permission_required",
|
||||
"has_permission",
|
||||
"check_permissions",
|
||||
// Common decorator names used by Flask-Login / Django / custom views
|
||||
// (consumed by `extract_auth_decorators` on function_definition nodes).
|
||||
"admin_required",
|
||||
"staff_member_required",
|
||||
"user_passes_test",
|
||||
],
|
||||
}];
|
||||
|
||||
static RUBY_AUTH: &[AuthRule] = &[AuthRule {
|
||||
matchers: &[
|
||||
"is_authenticated",
|
||||
"require_auth",
|
||||
"check_permission",
|
||||
"is_admin",
|
||||
"authorize",
|
||||
"authenticate",
|
||||
"require_login",
|
||||
"check_auth",
|
||||
"verify_token",
|
||||
"validate_token",
|
||||
// Devise / Rails controller-filter idioms (consumed by `before_action`
|
||||
// decorator extraction).
|
||||
"authenticate_user",
|
||||
"authenticate_admin",
|
||||
"require_user",
|
||||
"require_admin",
|
||||
"current_user",
|
||||
],
|
||||
}];
|
||||
|
||||
static PHP_AUTH: &[AuthRule] = &[AuthRule {
|
||||
matchers: &[
|
||||
"is_authenticated",
|
||||
"require_auth",
|
||||
"check_permission",
|
||||
"is_admin",
|
||||
"authorize",
|
||||
"authenticate",
|
||||
"require_login",
|
||||
"check_auth",
|
||||
"verify_token",
|
||||
"validate_token",
|
||||
// Symfony Security attributes (`#[IsGranted(..)]`, `#[Security(..)]`)
|
||||
// and common guard idioms.
|
||||
"IsGranted",
|
||||
"Security",
|
||||
],
|
||||
}];
|
||||
|
||||
static CPP_AUTH: &[AuthRule] = &[AuthRule {
|
||||
matchers: &[
|
||||
"is_authenticated",
|
||||
"require_auth",
|
||||
"check_permission",
|
||||
"is_admin",
|
||||
"authorize",
|
||||
"authenticate",
|
||||
"require_login",
|
||||
"check_auth",
|
||||
"verify_token",
|
||||
"validate_token",
|
||||
// Custom C++ attributes — framework-defined, bare-name match.
|
||||
"authenticated",
|
||||
"require_auth",
|
||||
"admin_only",
|
||||
],
|
||||
}];
|
||||
|
||||
static RUST_AUTH: &[AuthRule] = &[AuthRule {
|
||||
matchers: &[
|
||||
"is_authenticated",
|
||||
"require_auth",
|
||||
"check_permission",
|
||||
"is_admin",
|
||||
"authorize",
|
||||
"authenticate",
|
||||
"require_login",
|
||||
"check_auth",
|
||||
"verify_token",
|
||||
"validate_token",
|
||||
// Custom proc-macro attributes — framework-defined, bare-name match.
|
||||
"authenticated",
|
||||
"require_auth",
|
||||
"admin_only",
|
||||
],
|
||||
}];
|
||||
|
||||
|
|
@ -125,6 +298,12 @@ pub fn auth_rules(lang: Lang) -> &'static [AuthRule] {
|
|||
match lang {
|
||||
Lang::Go => GO_AUTH,
|
||||
Lang::Java => JAVA_AUTH,
|
||||
Lang::JavaScript | Lang::TypeScript => JS_AUTH,
|
||||
Lang::Python => PYTHON_AUTH,
|
||||
Lang::Ruby => RUBY_AUTH,
|
||||
Lang::Php => PHP_AUTH,
|
||||
Lang::Cpp => CPP_AUTH,
|
||||
Lang::Rust => RUST_AUTH,
|
||||
_ => COMMON_AUTH,
|
||||
}
|
||||
}
|
||||
|
|
@ -183,24 +362,68 @@ static C_RESOURCES: &[ResourcePair] = &[
|
|||
release: &["free"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "memory",
|
||||
use_patterns: &[],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["fopen", "fdopen", "curlx_fopen", "curlx_fdopen"],
|
||||
release: &["fclose", "curlx_fclose"],
|
||||
exclude_acquire: &["freopen", "curlx_freopen"],
|
||||
resource_name: "file handle",
|
||||
use_patterns: &[],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["open"],
|
||||
release: &["close"],
|
||||
exclude_acquire: &["freopen", "curlx_freopen"],
|
||||
resource_name: "file descriptor",
|
||||
use_patterns: &[],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["pthread_mutex_lock"],
|
||||
release: &["pthread_mutex_unlock"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "mutex",
|
||||
use_patterns: &[],
|
||||
},
|
||||
];
|
||||
|
||||
static CPP_RESOURCES: &[ResourcePair] = &[
|
||||
// Inherited from C
|
||||
ResourcePair {
|
||||
acquire: &["malloc", "calloc", "realloc"],
|
||||
release: &["free"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "memory",
|
||||
use_patterns: &[],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["fopen", "fdopen", "curlx_fopen", "curlx_fdopen"],
|
||||
release: &["fclose", "curlx_fclose"],
|
||||
exclude_acquire: &["freopen", "curlx_freopen"],
|
||||
resource_name: "file handle",
|
||||
use_patterns: &[],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["open"],
|
||||
release: &["close"],
|
||||
exclude_acquire: &["freopen", "curlx_freopen"],
|
||||
resource_name: "file descriptor",
|
||||
use_patterns: &[],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["pthread_mutex_lock"],
|
||||
release: &["pthread_mutex_unlock"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "mutex",
|
||||
use_patterns: &[],
|
||||
},
|
||||
// C++ new/delete (callee normalized to "new"/"delete" in cfg.rs)
|
||||
ResourcePair {
|
||||
acquire: &["new"],
|
||||
release: &["delete"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "heap object",
|
||||
use_patterns: &[],
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -210,12 +433,29 @@ static GO_RESOURCES: &[ResourcePair] = &[
|
|||
release: &[".Close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "file handle",
|
||||
use_patterns: &[],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &[".Lock"],
|
||||
release: &[".Unlock"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "mutex",
|
||||
use_patterns: &[],
|
||||
},
|
||||
// Additional patterns
|
||||
ResourcePair {
|
||||
acquire: &["sql.Open"],
|
||||
release: &[".Close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "db connection",
|
||||
use_patterns: &[".Query", ".Exec", ".Prepare", ".Begin"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["net.Listen"],
|
||||
release: &[".Close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "listener",
|
||||
use_patterns: &[".Accept", ".Addr"],
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -226,20 +466,86 @@ static RUST_RESOURCES: &[ResourcePair] = &[
|
|||
release: &["dealloc"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "raw memory",
|
||||
use_patterns: &[],
|
||||
},
|
||||
];
|
||||
|
||||
static JAVA_RESOURCES: &[ResourcePair] = &[ResourcePair {
|
||||
acquire: &[
|
||||
"new FileInputStream",
|
||||
"new FileOutputStream",
|
||||
"new BufferedReader",
|
||||
"openConnection",
|
||||
],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "stream/connection",
|
||||
}];
|
||||
static JAVA_RESOURCES: &[ResourcePair] = &[
|
||||
ResourcePair {
|
||||
acquire: &[
|
||||
"FileInputStream",
|
||||
"FileOutputStream",
|
||||
"BufferedReader",
|
||||
"openConnection",
|
||||
],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "stream/connection",
|
||||
use_patterns: &[".read", ".write", ".flush", ".available"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["DriverManager.getConnection", "getConnection"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "db connection",
|
||||
use_patterns: &[
|
||||
".executeQuery",
|
||||
".executeUpdate",
|
||||
".createStatement",
|
||||
".prepareStatement",
|
||||
],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["Socket"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "socket",
|
||||
use_patterns: &[".getInputStream", ".getOutputStream", ".connect"],
|
||||
},
|
||||
// Additional patterns
|
||||
ResourcePair {
|
||||
acquire: &["prepareStatement"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "prepared statement",
|
||||
use_patterns: &[".executeQuery", ".executeUpdate", ".setString", ".setInt"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["executeQuery"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "result set",
|
||||
use_patterns: &[".next", ".getString", ".getInt", ".getBoolean"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["ServerSocket"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "server socket",
|
||||
use_patterns: &[".accept", ".bind"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["DatagramSocket"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "datagram socket",
|
||||
use_patterns: &[".send", ".receive"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["RandomAccessFile"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "random access file",
|
||||
use_patterns: &[".read", ".write", ".seek", ".length"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["Channel.open", "FileChannel.open", "SocketChannel.open"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "NIO channel",
|
||||
use_patterns: &[".read", ".write", ".position"],
|
||||
},
|
||||
];
|
||||
|
||||
static PYTHON_RESOURCES: &[ResourcePair] = &[
|
||||
ResourcePair {
|
||||
|
|
@ -247,45 +553,135 @@ static PYTHON_RESOURCES: &[ResourcePair] = &[
|
|||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "file handle",
|
||||
use_patterns: &[],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["socket.socket", "socket"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "socket",
|
||||
use_patterns: &[],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["connect", "cursor"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &["signal.connect", "event.connect", ".register"],
|
||||
resource_name: "db connection",
|
||||
use_patterns: &[],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["threading.Lock", "threading.RLock"],
|
||||
release: &[".release"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "mutex",
|
||||
use_patterns: &[],
|
||||
},
|
||||
// Additional patterns
|
||||
ResourcePair {
|
||||
acquire: &["urllib.request.urlopen", "urlopen"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "url handle",
|
||||
use_patterns: &[".read", ".readline", ".readlines"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &[
|
||||
"http.client.HTTPConnection",
|
||||
"HTTPConnection",
|
||||
"HTTPSConnection",
|
||||
],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "http connection",
|
||||
use_patterns: &[".request", ".getresponse"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["sqlite3.connect"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "sqlite connection",
|
||||
use_patterns: &[".execute", ".cursor", ".commit"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["tempfile.NamedTemporaryFile", "NamedTemporaryFile"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "temp file",
|
||||
use_patterns: &[".write", ".read", ".seek"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["zipfile.ZipFile", "ZipFile"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "zip file",
|
||||
use_patterns: &[".read", ".write", ".extractall", ".namelist"],
|
||||
},
|
||||
];
|
||||
|
||||
static RUBY_RESOURCES: &[ResourcePair] = &[
|
||||
ResourcePair {
|
||||
acquire: &["File.open", "open"],
|
||||
acquire: &["File.open", "File.new", "open"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "file handle",
|
||||
use_patterns: &[
|
||||
".read",
|
||||
".write",
|
||||
".gets",
|
||||
".puts",
|
||||
".each_line",
|
||||
".readline",
|
||||
".readlines",
|
||||
".sysread",
|
||||
".syswrite",
|
||||
],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["TCPSocket.new", "UDPSocket.new"],
|
||||
acquire: &[
|
||||
"TCPSocket.new",
|
||||
"UDPSocket.new",
|
||||
"TCPServer.new",
|
||||
"UNIXSocket.new",
|
||||
],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "socket",
|
||||
use_patterns: &[".read", ".write", ".send", ".recv", ".gets", ".puts"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &[".lock"],
|
||||
release: &[".unlock"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "mutex",
|
||||
use_patterns: &[],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &[
|
||||
"PG.connect",
|
||||
"PG::Connection.new",
|
||||
"Sequel.connect",
|
||||
"Mysql2::Client.new",
|
||||
"SQLite3::Database.new",
|
||||
],
|
||||
release: &[".close", ".disconnect"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "db connection",
|
||||
use_patterns: &[".exec", ".query", ".exec_params", ".prepare", ".execute"],
|
||||
},
|
||||
// Additional patterns
|
||||
ResourcePair {
|
||||
acquire: &["Net::HTTP.start"],
|
||||
release: &[".finish"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "http connection",
|
||||
use_patterns: &[".get", ".post", ".request"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["Tempfile.new", "Tempfile.open"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "temp file",
|
||||
use_patterns: &[".write", ".read", ".path"],
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -295,18 +691,43 @@ static PHP_RESOURCES: &[ResourcePair] = &[
|
|||
release: &["fclose"],
|
||||
exclude_acquire: &["freopen"],
|
||||
resource_name: "file handle",
|
||||
use_patterns: &[],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["mysqli_connect"],
|
||||
release: &["mysqli_close"],
|
||||
acquire: &["mysqli_connect", "mysqli"],
|
||||
release: &["mysqli_close", ".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "db connection",
|
||||
use_patterns: &["mysqli_query", "mysqli_fetch_array", ".query", ".fetch"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["curl_init"],
|
||||
release: &["curl_close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "curl handle",
|
||||
use_patterns: &["curl_exec", "curl_getinfo", "curl_setopt"],
|
||||
},
|
||||
// Additional patterns
|
||||
ResourcePair {
|
||||
acquire: &["pg_connect"],
|
||||
release: &["pg_close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "pg connection",
|
||||
use_patterns: &["pg_query", "pg_fetch_array", "pg_fetch_row"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["fsockopen", "pfsockopen"],
|
||||
release: &["fclose"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "socket",
|
||||
use_patterns: &["fwrite", "fread", "fgets"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["stream_socket_client"],
|
||||
release: &["fclose"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "stream socket",
|
||||
use_patterns: &["fwrite", "fread", "stream_get_contents"],
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -316,19 +737,63 @@ static JS_RESOURCES: &[ResourcePair] = &[
|
|||
release: &["fs.close", "fs.closeSync"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "file descriptor",
|
||||
use_patterns: &[
|
||||
"fs.readSync",
|
||||
"fs.writeSync",
|
||||
"fs.fstatSync",
|
||||
"fs.ftruncateSync",
|
||||
"fs.fsyncSync",
|
||||
],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["createReadStream", "createWriteStream"],
|
||||
release: &[".close", ".destroy"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "stream",
|
||||
use_patterns: &[".pipe", ".resume", ".write", ".read", ".push"],
|
||||
},
|
||||
// Additional patterns
|
||||
ResourcePair {
|
||||
acquire: &["net.createConnection", "net.connect"],
|
||||
release: &[".end", ".destroy"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "net socket",
|
||||
use_patterns: &[".write", ".read", ".pipe"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["http.request", "https.request"],
|
||||
release: &[".end", ".destroy"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "http request",
|
||||
use_patterns: &[".write"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["WebSocket"],
|
||||
release: &[".close"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "websocket",
|
||||
use_patterns: &[".send"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["mysql.createConnection", "mysql.createPool"],
|
||||
release: &[".end", ".destroy"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "mysql connection",
|
||||
use_patterns: &[".query", ".execute"],
|
||||
},
|
||||
ResourcePair {
|
||||
acquire: &["pg.Pool", "pg.Client"],
|
||||
release: &[".end", ".release"],
|
||||
exclude_acquire: &[],
|
||||
resource_name: "pg connection",
|
||||
use_patterns: &[".query"],
|
||||
},
|
||||
];
|
||||
|
||||
pub fn resource_pairs(lang: Lang) -> &'static [ResourcePair] {
|
||||
match lang {
|
||||
Lang::C => C_RESOURCES,
|
||||
Lang::Cpp => C_RESOURCES,
|
||||
Lang::Cpp => CPP_RESOURCES,
|
||||
Lang::Go => GO_RESOURCES,
|
||||
Lang::Rust => RUST_RESOURCES,
|
||||
Lang::Java => JAVA_RESOURCES,
|
||||
|
|
|
|||
|
|
@ -14,19 +14,25 @@ fn parse_and_analyse<A: CfgAnalysis>(
|
|||
let mut parser = tree_sitter::Parser::new();
|
||||
parser.set_language(&ts_lang).unwrap();
|
||||
let tree = parser.parse(src, None).unwrap();
|
||||
let (cfg, entry, summaries) = build_cfg(&tree, src, lang_str, "test.rs", None);
|
||||
let file_cfg = build_cfg(&tree, src, lang_str, "test.rs", None);
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
let entry = file_cfg.first_body().entry;
|
||||
let summaries = &file_cfg.summaries;
|
||||
let lang = Lang::from_slug(lang_str).unwrap();
|
||||
let ctx = AnalysisContext {
|
||||
cfg: &cfg,
|
||||
cfg,
|
||||
entry,
|
||||
lang,
|
||||
file_path: "test.rs",
|
||||
source_bytes: src,
|
||||
func_summaries: &summaries,
|
||||
func_summaries: summaries,
|
||||
global_summaries: None,
|
||||
taint_findings: &[],
|
||||
analysis_rules: None,
|
||||
taint_active: true,
|
||||
body_const_facts: None,
|
||||
type_facts: None,
|
||||
auth_decorators: &[],
|
||||
};
|
||||
analysis.run(&ctx)
|
||||
}
|
||||
|
|
@ -36,19 +42,25 @@ fn parse_and_run_all(src: &[u8], lang_str: &str, ts_lang: Language) -> Vec<CfgFi
|
|||
let mut parser = tree_sitter::Parser::new();
|
||||
parser.set_language(&ts_lang).unwrap();
|
||||
let tree = parser.parse(src, None).unwrap();
|
||||
let (cfg, entry, summaries) = build_cfg(&tree, src, lang_str, "test.rs", None);
|
||||
let file_cfg = build_cfg(&tree, src, lang_str, "test.rs", None);
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
let entry = file_cfg.first_body().entry;
|
||||
let summaries = &file_cfg.summaries;
|
||||
let lang = Lang::from_slug(lang_str).unwrap();
|
||||
let ctx = AnalysisContext {
|
||||
cfg: &cfg,
|
||||
cfg,
|
||||
entry,
|
||||
lang,
|
||||
file_path: "test.rs",
|
||||
source_bytes: src,
|
||||
func_summaries: &summaries,
|
||||
func_summaries: summaries,
|
||||
global_summaries: None,
|
||||
taint_findings: &[],
|
||||
analysis_rules: None,
|
||||
taint_active: true,
|
||||
body_const_facts: None,
|
||||
type_facts: None,
|
||||
auth_decorators: &[],
|
||||
};
|
||||
run_all(&ctx)
|
||||
}
|
||||
|
|
@ -63,19 +75,25 @@ fn parse_and_run_all_with_taint(
|
|||
let mut parser = tree_sitter::Parser::new();
|
||||
parser.set_language(&ts_lang).unwrap();
|
||||
let tree = parser.parse(src, None).unwrap();
|
||||
let (cfg, entry, summaries) = build_cfg(&tree, src, lang_str, "test.rs", None);
|
||||
let file_cfg = build_cfg(&tree, src, lang_str, "test.rs", None);
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
let entry = file_cfg.first_body().entry;
|
||||
let summaries = &file_cfg.summaries;
|
||||
let lang = Lang::from_slug(lang_str).unwrap();
|
||||
let ctx = AnalysisContext {
|
||||
cfg: &cfg,
|
||||
cfg,
|
||||
entry,
|
||||
lang,
|
||||
file_path: "test.rs",
|
||||
source_bytes: src,
|
||||
func_summaries: &summaries,
|
||||
func_summaries: summaries,
|
||||
global_summaries: None,
|
||||
taint_findings,
|
||||
analysis_rules: None,
|
||||
taint_active: true,
|
||||
body_const_facts: None,
|
||||
type_facts: None,
|
||||
auth_decorators: &[],
|
||||
};
|
||||
run_all(&ctx)
|
||||
}
|
||||
|
|
@ -150,10 +168,12 @@ fn unreachable_detects_orphaned_nodes() {
|
|||
.set_language(&Language::from(tree_sitter_rust::LANGUAGE))
|
||||
.unwrap();
|
||||
let tree = parser.parse(src as &[u8], None).unwrap();
|
||||
let (cfg, entry, _) = build_cfg(&tree, src, "rust", "test.rs", None);
|
||||
let file_cfg = build_cfg(&tree, src, "rust", "test.rs", None);
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
let entry = file_cfg.first_body().entry;
|
||||
|
||||
// All nodes in linear code should be reachable
|
||||
let reachable = dominators::reachable_set(&cfg, entry);
|
||||
let reachable = dominators::reachable_set(cfg, entry);
|
||||
assert_eq!(
|
||||
reachable.len(),
|
||||
cfg.node_count(),
|
||||
|
|
@ -161,6 +181,103 @@ fn unreachable_detects_orphaned_nodes() {
|
|||
);
|
||||
}
|
||||
|
||||
/// Like `parse_and_analyse` but also plumbs per-body SSA + const-prop facts
|
||||
/// into the analysis context. Used by tests that exercise the SSA-backed
|
||||
/// branch of `is_all_args_constant`.
|
||||
fn parse_and_analyse_with_ssa<A: CfgAnalysis>(
|
||||
analysis: &A,
|
||||
src: &[u8],
|
||||
lang_str: &str,
|
||||
ts_lang: Language,
|
||||
) -> Vec<CfgFinding> {
|
||||
let mut parser = tree_sitter::Parser::new();
|
||||
parser.set_language(&ts_lang).unwrap();
|
||||
let tree = parser.parse(src, None).unwrap();
|
||||
let file_cfg = build_cfg(&tree, src, lang_str, "test.rs", None);
|
||||
let body = file_cfg.first_body();
|
||||
let lang = Lang::from_slug(lang_str).unwrap();
|
||||
let facts = build_body_const_facts(body, lang);
|
||||
let ctx = AnalysisContext {
|
||||
cfg: &body.graph,
|
||||
entry: body.entry,
|
||||
lang,
|
||||
file_path: "test.rs",
|
||||
source_bytes: src,
|
||||
func_summaries: &file_cfg.summaries,
|
||||
global_summaries: None,
|
||||
taint_findings: &[],
|
||||
analysis_rules: None,
|
||||
taint_active: true,
|
||||
body_const_facts: facts.as_ref(),
|
||||
type_facts: facts.as_ref().map(|f| &f.type_facts),
|
||||
auth_decorators: &[],
|
||||
};
|
||||
analysis.run(&ctx)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ssa_const_prop_suppresses_sink_on_unused_source() {
|
||||
// rs-safe-003 regression: a tainted source binds a variable that is
|
||||
// never used; the sink's arg is a constant reassigned through a local
|
||||
// `let`. SSA const-prop resolves `cmd` to a string literal, so the
|
||||
// structural finding must be suppressed.
|
||||
let src = br#"
|
||||
use std::env;
|
||||
use std::process::Command;
|
||||
fn main() {
|
||||
let _input = env::var("USER_CMD").unwrap();
|
||||
let cmd = "echo safe";
|
||||
Command::new("sh").arg("-c").arg(cmd).status().unwrap();
|
||||
}"#;
|
||||
|
||||
let findings = parse_and_analyse_with_ssa(
|
||||
&guards::UnguardedSink,
|
||||
src,
|
||||
"rust",
|
||||
Language::from(tree_sitter_rust::LANGUAGE),
|
||||
);
|
||||
|
||||
let guard_findings: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| f.rule_id == "cfg-unguarded-sink")
|
||||
.collect();
|
||||
assert!(
|
||||
guard_findings.is_empty(),
|
||||
"SSA const-prop should suppress sink with only constant args, got {guard_findings:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ssa_const_prop_preserves_sink_on_dynamic_source_arg() {
|
||||
// Positive case: even with SSA facts available, a sink whose argument
|
||||
// flows from a source must still raise the structural finding.
|
||||
let src = br#"
|
||||
use std::env;
|
||||
use std::process::Command;
|
||||
fn main() {
|
||||
let shell = "sh";
|
||||
let flag = "-c";
|
||||
let user_cmd = env::var("USER_CMD").unwrap();
|
||||
Command::new(shell).arg(flag).arg(&user_cmd).status().unwrap();
|
||||
}"#;
|
||||
|
||||
let findings = parse_and_analyse_with_ssa(
|
||||
&guards::UnguardedSink,
|
||||
src,
|
||||
"rust",
|
||||
Language::from(tree_sitter_rust::LANGUAGE),
|
||||
);
|
||||
|
||||
let guard_findings: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| f.rule_id == "cfg-unguarded-sink")
|
||||
.collect();
|
||||
assert!(
|
||||
!guard_findings.is_empty(),
|
||||
"Structural finding must still fire when a sink arg is source-derived"
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Guard validation tests ───────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
|
|
@ -475,9 +592,11 @@ fn reachable_set_contains_all_connected_nodes() {
|
|||
.set_language(&Language::from(tree_sitter_rust::LANGUAGE))
|
||||
.unwrap();
|
||||
let tree = parser.parse(src as &[u8], None).unwrap();
|
||||
let (cfg, entry, _) = build_cfg(&tree, src, "rust", "test.rs", None);
|
||||
let file_cfg = build_cfg(&tree, src, "rust", "test.rs", None);
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
let entry = file_cfg.first_body().entry;
|
||||
|
||||
let reachable = dominators::reachable_set(&cfg, entry);
|
||||
let reachable = dominators::reachable_set(cfg, entry);
|
||||
|
||||
// All nodes in a simple straight-line function should be reachable
|
||||
assert_eq!(
|
||||
|
|
@ -499,9 +618,10 @@ fn find_exit_node_exists() {
|
|||
.set_language(&Language::from(tree_sitter_rust::LANGUAGE))
|
||||
.unwrap();
|
||||
let tree = parser.parse(src as &[u8], None).unwrap();
|
||||
let (cfg, _, _) = build_cfg(&tree, src, "rust", "test.rs", None);
|
||||
let file_cfg = build_cfg(&tree, src, "rust", "test.rs", None);
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
|
||||
let exit = dominators::find_exit_node(&cfg);
|
||||
let exit = dominators::find_exit_node(cfg);
|
||||
assert!(exit.is_some(), "Should find an exit node");
|
||||
}
|
||||
|
||||
|
|
@ -518,10 +638,12 @@ fn shortest_distance_basic() {
|
|||
.set_language(&Language::from(tree_sitter_rust::LANGUAGE))
|
||||
.unwrap();
|
||||
let tree = parser.parse(src as &[u8], None).unwrap();
|
||||
let (cfg, entry, _) = build_cfg(&tree, src, "rust", "test.rs", None);
|
||||
let file_cfg = build_cfg(&tree, src, "rust", "test.rs", None);
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
let entry = file_cfg.first_body().entry;
|
||||
|
||||
let exit = dominators::find_exit_node(&cfg).unwrap();
|
||||
let dist = dominators::shortest_distance(&cfg, entry, exit);
|
||||
let exit = dominators::find_exit_node(cfg).unwrap();
|
||||
let dist = dominators::shortest_distance(cfg, entry, exit);
|
||||
assert!(dist.is_some(), "Should find a path from entry to exit");
|
||||
assert!(dist.unwrap() > 0, "Distance should be positive");
|
||||
}
|
||||
|
|
@ -662,27 +784,42 @@ fn taint_and_unguarded_sink_deduped() {
|
|||
.set_language(&Language::from(tree_sitter_rust::LANGUAGE))
|
||||
.unwrap();
|
||||
let tree = parser.parse(src as &[u8], None).unwrap();
|
||||
let (cfg_graph, entry, _summaries) = build_cfg(&tree, src, "rust", "test.rs", None);
|
||||
let file_cfg = build_cfg(&tree, src, "rust", "test.rs", None);
|
||||
let cfg_graph = &file_cfg.first_body().graph;
|
||||
let entry = file_cfg.first_body().entry;
|
||||
let _lang = Lang::from_slug("rust").unwrap();
|
||||
|
||||
// Find a sink node to create a synthetic taint finding
|
||||
let sink_node = cfg_graph
|
||||
.node_indices()
|
||||
.find(|&idx| {
|
||||
matches!(
|
||||
cfg_graph[idx].label,
|
||||
Some(crate::labels::DataLabel::Sink(_))
|
||||
)
|
||||
cfg_graph[idx]
|
||||
.taint
|
||||
.labels
|
||||
.iter()
|
||||
.any(|l| matches!(l, crate::labels::DataLabel::Sink(_)))
|
||||
})
|
||||
.expect("test code should have a sink node");
|
||||
|
||||
let fake_taint = vec![taint::Finding {
|
||||
body_id: crate::cfg::BodyId(0),
|
||||
sink: sink_node,
|
||||
source: entry,
|
||||
path: vec![entry, sink_node],
|
||||
source_kind: crate::labels::SourceKind::UserInput,
|
||||
path_validated: false,
|
||||
guard_kind: None,
|
||||
hop_count: 0,
|
||||
cap_specificity: 1,
|
||||
uses_summary: false,
|
||||
flow_steps: vec![],
|
||||
symbolic: None,
|
||||
source_span: None,
|
||||
primary_location: None,
|
||||
engine_notes: smallvec::SmallVec::new(),
|
||||
path_hash: 0,
|
||||
finding_id: String::new(),
|
||||
alternative_finding_ids: smallvec::SmallVec::new(),
|
||||
}];
|
||||
|
||||
let findings = parse_and_run_all_with_taint(
|
||||
|
|
@ -825,28 +962,26 @@ fn js_throw_terminates_block() {
|
|||
let mut parser = tree_sitter::Parser::new();
|
||||
parser.set_language(&ts_lang).unwrap();
|
||||
let tree = parser.parse(src as &[u8], None).unwrap();
|
||||
let (cfg, entry, _) = build_cfg(&tree, src, "javascript", "test.js", None);
|
||||
let file_cfg = build_cfg(&tree, src, "javascript", "test.js", None);
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
let entry = file_cfg.first_body().entry;
|
||||
|
||||
// Verify throw creates a Return-kind node
|
||||
// Verify throw creates a Throw-kind node
|
||||
let throw_nodes: Vec<_> = cfg
|
||||
.node_indices()
|
||||
.filter(|&idx| {
|
||||
cfg[idx].kind == crate::cfg::StmtKind::Return
|
||||
&& cfg[idx].span.0 > 0
|
||||
&& src[cfg[idx].span.0..].starts_with(b"throw")
|
||||
})
|
||||
.filter(|&idx| cfg[idx].kind == crate::cfg::StmtKind::Throw)
|
||||
.collect();
|
||||
|
||||
assert!(
|
||||
!throw_nodes.is_empty(),
|
||||
"throw statement should create a Return-kind node"
|
||||
"throw statement should create a Throw-kind node"
|
||||
);
|
||||
|
||||
// eval after throw should be unreachable
|
||||
let reachable = crate::cfg_analysis::dominators::reachable_set(&cfg, entry);
|
||||
let reachable = crate::cfg_analysis::dominators::reachable_set(cfg, entry);
|
||||
let eval_nodes: Vec<_> = cfg
|
||||
.node_indices()
|
||||
.filter(|&idx| cfg[idx].callee.as_deref().is_some_and(|c| c == "eval"))
|
||||
.filter(|&idx| cfg[idx].call.callee.as_deref().is_some_and(|c| c == "eval"))
|
||||
.collect();
|
||||
|
||||
// eval might not even be in the CFG, or if it is, it should be unreachable
|
||||
|
|
@ -872,19 +1007,22 @@ fn configured_terminator_stops_flow() {
|
|||
extra_labels: vec![],
|
||||
terminators: vec!["process.exit".into()],
|
||||
event_handlers: vec![],
|
||||
frameworks: vec![],
|
||||
};
|
||||
|
||||
let mut parser = tree_sitter::Parser::new();
|
||||
parser.set_language(&ts_lang).unwrap();
|
||||
let tree = parser.parse(src as &[u8], None).unwrap();
|
||||
let (cfg, entry, _) = build_cfg(&tree, src, "javascript", "test.js", Some(&rules));
|
||||
let file_cfg = build_cfg(&tree, src, "javascript", "test.js", Some(&rules));
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
let entry = file_cfg.first_body().entry;
|
||||
|
||||
let reachable = crate::cfg_analysis::dominators::reachable_set(&cfg, entry);
|
||||
let reachable = crate::cfg_analysis::dominators::reachable_set(cfg, entry);
|
||||
|
||||
// eval should be unreachable since process.exit is a terminator
|
||||
let eval_nodes: Vec<_> = cfg
|
||||
.node_indices()
|
||||
.filter(|&idx| cfg[idx].callee.as_deref().is_some_and(|c| c == "eval"))
|
||||
.filter(|&idx| cfg[idx].call.callee.as_deref().is_some_and(|c| c == "eval"))
|
||||
.collect();
|
||||
|
||||
if !eval_nodes.is_empty() {
|
||||
|
|
@ -911,11 +1049,16 @@ fn location_href_assignment_is_sink() {
|
|||
let mut parser = tree_sitter::Parser::new();
|
||||
parser.set_language(&ts_lang).unwrap();
|
||||
let tree = parser.parse(src as &[u8], None).unwrap();
|
||||
let (cfg, _entry, _summaries) = build_cfg(&tree, src, "javascript", "test.js", None);
|
||||
let file_cfg = build_cfg(&tree, src, "javascript", "test.js", None);
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
|
||||
let has_sink = cfg
|
||||
.node_indices()
|
||||
.any(|idx| matches!(cfg[idx].label, Some(crate::labels::DataLabel::Sink(_))));
|
||||
let has_sink = cfg.node_indices().any(|idx| {
|
||||
cfg[idx]
|
||||
.taint
|
||||
.labels
|
||||
.iter()
|
||||
.any(|l| matches!(l, crate::labels::DataLabel::Sink(_)))
|
||||
});
|
||||
assert!(has_sink, "location.href = url should produce a Sink node");
|
||||
}
|
||||
|
||||
|
|
@ -931,11 +1074,16 @@ fn a_href_assignment_is_not_sink() {
|
|||
let mut parser = tree_sitter::Parser::new();
|
||||
parser.set_language(&ts_lang).unwrap();
|
||||
let tree = parser.parse(src as &[u8], None).unwrap();
|
||||
let (cfg, _entry, _summaries) = build_cfg(&tree, src, "javascript", "test.js", None);
|
||||
let file_cfg = build_cfg(&tree, src, "javascript", "test.js", None);
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
|
||||
let has_sink = cfg
|
||||
.node_indices()
|
||||
.any(|idx| matches!(cfg[idx].label, Some(crate::labels::DataLabel::Sink(_))));
|
||||
let has_sink = cfg.node_indices().any(|idx| {
|
||||
cfg[idx]
|
||||
.taint
|
||||
.labels
|
||||
.iter()
|
||||
.any(|l| matches!(l, crate::labels::DataLabel::Sink(_)))
|
||||
});
|
||||
assert!(
|
||||
!has_sink,
|
||||
"el.href = '/about' should NOT produce a Sink node"
|
||||
|
|
@ -963,27 +1111,35 @@ fn config_sanitizer_suppresses_unguarded_sink() {
|
|||
extra_labels: vec![crate::labels::RuntimeLabelRule {
|
||||
matchers: vec!["escapeHtml".into()],
|
||||
label: crate::labels::DataLabel::Sanitizer(crate::labels::Cap::HTML_ESCAPE),
|
||||
case_sensitive: false,
|
||||
}],
|
||||
terminators: vec![],
|
||||
event_handlers: vec![],
|
||||
frameworks: vec![],
|
||||
};
|
||||
|
||||
let mut parser = tree_sitter::Parser::new();
|
||||
parser.set_language(&ts_lang).unwrap();
|
||||
let tree = parser.parse(src as &[u8], None).unwrap();
|
||||
let (cfg, entry, summaries) = build_cfg(&tree, src, lang_str, "test.rs", Some(&rules));
|
||||
let file_cfg = build_cfg(&tree, src, lang_str, "test.rs", Some(&rules));
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
let entry = file_cfg.first_body().entry;
|
||||
let summaries = &file_cfg.summaries;
|
||||
let lang = Lang::from_slug(lang_str).unwrap();
|
||||
let ctx = AnalysisContext {
|
||||
cfg: &cfg,
|
||||
cfg,
|
||||
entry,
|
||||
lang,
|
||||
file_path: "test.rs",
|
||||
source_bytes: src,
|
||||
func_summaries: &summaries,
|
||||
func_summaries: summaries,
|
||||
global_summaries: None,
|
||||
taint_findings: &[],
|
||||
analysis_rules: Some(&rules),
|
||||
taint_active: true,
|
||||
body_const_facts: None,
|
||||
type_facts: None,
|
||||
auth_decorators: &[],
|
||||
};
|
||||
let findings = run_all(&ctx);
|
||||
|
||||
|
|
@ -1318,9 +1474,11 @@ void process() {
|
|||
let mut parser = tree_sitter::Parser::new();
|
||||
parser.set_language(&ts_lang).unwrap();
|
||||
let tree = parser.parse(src as &[u8], None).unwrap();
|
||||
let (cfg, entry, _) = build_cfg(&tree, src, "c", "test.c", None);
|
||||
let file_cfg = build_cfg(&tree, src, "c", "test.c", None);
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
let entry = file_cfg.first_body().entry;
|
||||
|
||||
let reachable = dominators::reachable_set(&cfg, entry);
|
||||
let reachable = dominators::reachable_set(cfg, entry);
|
||||
|
||||
// All nodes should be reachable — the preproc recovery should prevent
|
||||
// the dangling-else from orphaning downstream code.
|
||||
|
|
@ -1351,9 +1509,11 @@ void process() {
|
|||
let mut parser = tree_sitter::Parser::new();
|
||||
parser.set_language(&ts_lang).unwrap();
|
||||
let tree = parser.parse(src as &[u8], None).unwrap();
|
||||
let (cfg, entry, _) = build_cfg(&tree, src, "c", "test.c", None);
|
||||
let file_cfg = build_cfg(&tree, src, "c", "test.c", None);
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
let entry = file_cfg.first_body().entry;
|
||||
|
||||
let reachable = dominators::reachable_set(&cfg, entry);
|
||||
let reachable = dominators::reachable_set(cfg, entry);
|
||||
|
||||
// All nodes should be reachable — break exits the loop and post-loop
|
||||
// code (free(x)) should be connected.
|
||||
|
|
@ -1439,19 +1599,25 @@ fn cfg_only_no_taint_produces_low_severity() {
|
|||
let mut parser = tree_sitter::Parser::new();
|
||||
parser.set_language(&ts_lang).unwrap();
|
||||
let tree = parser.parse(src as &[u8], None).unwrap();
|
||||
let (cfg, entry, summaries) = build_cfg(&tree, src, "rust", "test.rs", None);
|
||||
let file_cfg = build_cfg(&tree, src, "rust", "test.rs", None);
|
||||
let cfg = &file_cfg.first_body().graph;
|
||||
let entry = file_cfg.first_body().entry;
|
||||
let summaries = &file_cfg.summaries;
|
||||
let lang = Lang::from_slug("rust").unwrap();
|
||||
let ctx = AnalysisContext {
|
||||
cfg: &cfg,
|
||||
cfg,
|
||||
entry,
|
||||
lang,
|
||||
file_path: "test.rs",
|
||||
source_bytes: src,
|
||||
func_summaries: &summaries,
|
||||
func_summaries: summaries,
|
||||
global_summaries: None,
|
||||
taint_findings: &[],
|
||||
analysis_rules: None,
|
||||
taint_active: false, // cfg-only mode
|
||||
body_const_facts: None,
|
||||
type_facts: None,
|
||||
auth_decorators: &[],
|
||||
};
|
||||
let findings = guards::UnguardedSink.run(&ctx);
|
||||
|
||||
|
|
@ -1556,3 +1722,353 @@ def setup():
|
|||
leak_findings
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Literal-argument taint sink suppression tests ─────────────────
|
||||
|
||||
#[test]
|
||||
fn python_literal_os_system_no_finding() {
|
||||
// os.system("ls -la") with string literal arg should produce no finding
|
||||
let src = br#"
|
||||
import os
|
||||
|
||||
def run():
|
||||
os.system("ls -la")
|
||||
"#;
|
||||
|
||||
let findings = parse_and_run_all(src, "python", Language::from(tree_sitter_python::LANGUAGE));
|
||||
|
||||
let unguarded: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| f.rule_id == "cfg-unguarded-sink")
|
||||
.collect();
|
||||
assert!(
|
||||
unguarded.is_empty(),
|
||||
"os.system with string literal arg should not be flagged; got {:?}",
|
||||
unguarded
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_literal_exec_command_no_finding() {
|
||||
// exec.Command("echo", "hello") with multiple string literal args should produce no finding
|
||||
let src = br#"
|
||||
package main
|
||||
|
||||
import "os/exec"
|
||||
|
||||
func run() {
|
||||
exec.Command("echo", "hello")
|
||||
}
|
||||
"#;
|
||||
|
||||
let findings = parse_and_run_all(src, "go", Language::from(tree_sitter_go::LANGUAGE));
|
||||
|
||||
let unguarded: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| f.rule_id == "cfg-unguarded-sink")
|
||||
.collect();
|
||||
assert!(
|
||||
unguarded.is_empty(),
|
||||
"exec.Command with string literal args should not be flagged; got {:?}",
|
||||
unguarded
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_literal_subprocess_list_no_finding() {
|
||||
// subprocess.run(["ls", "-la"]) with array of string literals should produce no finding
|
||||
let src = br#"
|
||||
import subprocess
|
||||
|
||||
def run():
|
||||
subprocess.run(["ls", "-la"])
|
||||
"#;
|
||||
|
||||
let findings = parse_and_run_all(src, "python", Language::from(tree_sitter_python::LANGUAGE));
|
||||
|
||||
let unguarded: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| f.rule_id == "cfg-unguarded-sink")
|
||||
.collect();
|
||||
assert!(
|
||||
unguarded.is_empty(),
|
||||
"subprocess.run with list of string literals should not be flagged; got {:?}",
|
||||
unguarded
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_literal_subprocess_multiple_list_items_no_finding() {
|
||||
// subprocess.run(["ls", "-la", "-h"]) with list of multiple literals should produce no finding
|
||||
let src = br#"
|
||||
import subprocess
|
||||
|
||||
def run():
|
||||
subprocess.run(["ls", "-la", "-h"])
|
||||
"#;
|
||||
|
||||
let findings = parse_and_run_all(src, "python", Language::from(tree_sitter_python::LANGUAGE));
|
||||
|
||||
let unguarded: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| f.rule_id == "cfg-unguarded-sink")
|
||||
.collect();
|
||||
assert!(
|
||||
unguarded.is_empty(),
|
||||
"subprocess.run with list of multiple literals should not be flagged; got {:?}",
|
||||
unguarded
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn js_template_literal_no_interpolation_no_finding() {
|
||||
// exec(`ls -la`) with static template string should produce no finding
|
||||
let src = br#"
|
||||
const { exec } = require('child_process');
|
||||
|
||||
function run() {
|
||||
exec(`ls -la`);
|
||||
}
|
||||
"#;
|
||||
|
||||
let findings = parse_and_run_all(
|
||||
src,
|
||||
"javascript",
|
||||
Language::from(tree_sitter_javascript::LANGUAGE),
|
||||
);
|
||||
|
||||
let unguarded: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| f.rule_id == "cfg-unguarded-sink")
|
||||
.collect();
|
||||
assert!(
|
||||
unguarded.is_empty(),
|
||||
"exec with static template string should not be flagged; got {:?}",
|
||||
unguarded
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Adversarial tests: must still report findings ─────────────────
|
||||
|
||||
#[test]
|
||||
fn python_tainted_var_os_system_produces_finding() {
|
||||
// os.system(user_input) with tainted variable must report
|
||||
let src = br#"
|
||||
import os
|
||||
import sys
|
||||
|
||||
def run():
|
||||
user_input = sys.argv[1]
|
||||
os.system(user_input)
|
||||
"#;
|
||||
|
||||
let findings = parse_and_run_all(src, "python", Language::from(tree_sitter_python::LANGUAGE));
|
||||
|
||||
let sink_findings: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| {
|
||||
f.rule_id == "cfg-unguarded-sink" && f.severity == crate::patterns::Severity::High
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
!sink_findings.is_empty(),
|
||||
"os.system with tainted variable should produce a HIGH finding"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_one_hop_constant_still_suppressed() {
|
||||
// cmd = "ls"; os.system(cmd) — `all_args_literal` is false (identifier arg),
|
||||
// but should still be suppressed via existing one-hop constant trace in cfg_analysis.
|
||||
let src = br#"
|
||||
import os
|
||||
|
||||
def run():
|
||||
cmd = "ls"
|
||||
os.system(cmd)
|
||||
"#;
|
||||
|
||||
let findings = parse_and_run_all(src, "python", Language::from(tree_sitter_python::LANGUAGE));
|
||||
|
||||
let unguarded: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| f.rule_id == "cfg-unguarded-sink")
|
||||
.collect();
|
||||
assert!(
|
||||
unguarded.is_empty(),
|
||||
"One-hop constant binding should suppress cfg-unguarded-sink via existing trace; got {:?}",
|
||||
unguarded
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn js_template_literal_with_interpolation_produces_finding() {
|
||||
// exec(`ls ${dir}`) with interpolation must report
|
||||
let src = br#"
|
||||
const { exec } = require('child_process');
|
||||
|
||||
function run() {
|
||||
const dir = process.env.DIR;
|
||||
exec(`ls ${dir}`);
|
||||
}
|
||||
"#;
|
||||
|
||||
let findings = parse_and_run_all(
|
||||
src,
|
||||
"javascript",
|
||||
Language::from(tree_sitter_javascript::LANGUAGE),
|
||||
);
|
||||
|
||||
let sink_findings: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| {
|
||||
f.rule_id == "cfg-unguarded-sink" && f.severity == crate::patterns::Severity::High
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
!sink_findings.is_empty(),
|
||||
"exec with interpolated template string should produce a HIGH finding"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_array_with_tainted_element_produces_finding() {
|
||||
// subprocess.run([user_input, "-la"], shell=True) with one tainted element must report
|
||||
let src = br#"
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
def run():
|
||||
user_input = sys.argv[1]
|
||||
subprocess.run([user_input, "-la"], shell=True)
|
||||
"#;
|
||||
|
||||
let findings = parse_and_run_all(src, "python", Language::from(tree_sitter_python::LANGUAGE));
|
||||
|
||||
let sink_findings: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| {
|
||||
f.rule_id == "cfg-unguarded-sink" && f.severity == crate::patterns::Severity::High
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
!sink_findings.is_empty(),
|
||||
"subprocess.run with tainted array element should produce a HIGH finding"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_constant_receiver_tainted_arg_produces_finding() {
|
||||
// safe_obj.system(user_input) — constant receiver is irrelevant, tainted arg must report
|
||||
let src = br#"
|
||||
import os
|
||||
import sys
|
||||
|
||||
def run():
|
||||
user_input = sys.argv[1]
|
||||
os.system(user_input)
|
||||
"#;
|
||||
|
||||
let findings = parse_and_run_all(src, "python", Language::from(tree_sitter_python::LANGUAGE));
|
||||
|
||||
let sink_findings: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| {
|
||||
f.rule_id == "cfg-unguarded-sink" && f.severity == crate::patterns::Severity::High
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
!sink_findings.is_empty(),
|
||||
"Tainted argument to sink must produce a HIGH finding regardless of receiver"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn php_encapsed_string_with_interpolation_produces_finding() {
|
||||
// system("ls $dir") with PHP interpolation must report
|
||||
let src = br#"<?php
|
||||
function run() {
|
||||
$dir = $_GET['dir'];
|
||||
system("ls $dir");
|
||||
}
|
||||
"#;
|
||||
|
||||
let findings = parse_and_run_all(src, "php", Language::from(tree_sitter_php::LANGUAGE_PHP));
|
||||
|
||||
let sink_findings: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| {
|
||||
f.rule_id == "cfg-unguarded-sink" && f.severity == crate::patterns::Severity::High
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
!sink_findings.is_empty(),
|
||||
"PHP system() with interpolated string should produce a HIGH finding"
|
||||
);
|
||||
}
|
||||
|
||||
// ── Type-fact sink suppression (rs-safe-011 regression) ────────────────
|
||||
|
||||
#[test]
|
||||
fn type_facts_suppress_int_typed_shell_arg() {
|
||||
// rs-safe-011 fixture: a u16-typed port (parsed from env) flows into
|
||||
// Command::new("listener").arg(port.to_string()). The taint engine
|
||||
// already suppresses the flow via type-aware analysis; the structural
|
||||
// cfg-unguarded-sink must also honour the type fact and stay silent.
|
||||
let src = br#"
|
||||
use std::env;
|
||||
use std::process::Command;
|
||||
fn main() {
|
||||
let raw = env::var("PORT").unwrap();
|
||||
let port: u16 = raw.parse().expect("invalid port");
|
||||
Command::new("listener").arg(port.to_string()).status().unwrap();
|
||||
}"#;
|
||||
|
||||
let findings = parse_and_analyse_with_ssa(
|
||||
&guards::UnguardedSink,
|
||||
src,
|
||||
"rust",
|
||||
Language::from(tree_sitter_rust::LANGUAGE),
|
||||
);
|
||||
|
||||
let guard_findings: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| f.rule_id == "cfg-unguarded-sink")
|
||||
.collect();
|
||||
assert!(
|
||||
guard_findings.is_empty(),
|
||||
"Int-typed sink argument should suppress cfg-unguarded-sink, got: {:?}",
|
||||
guard_findings
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_facts_preserve_untyped_string_shell_arg() {
|
||||
// Companion negative test: env::var() flows directly into a Command arg
|
||||
// with no int typing. The sink argument is a String of unknown content,
|
||||
// so the structural finding must still fire. Guards against the
|
||||
// suppression helper over-reaching into cases without an Int fact.
|
||||
let src = br#"
|
||||
use std::env;
|
||||
use std::process::Command;
|
||||
fn main() {
|
||||
let cmd = env::var("USER_CMD").unwrap();
|
||||
Command::new("sh").arg("-c").arg(cmd).status().unwrap();
|
||||
}"#;
|
||||
|
||||
let findings = parse_and_analyse_with_ssa(
|
||||
&guards::UnguardedSink,
|
||||
src,
|
||||
"rust",
|
||||
Language::from(tree_sitter_rust::LANGUAGE),
|
||||
);
|
||||
|
||||
let guard_findings: Vec<_> = findings
|
||||
.iter()
|
||||
.filter(|f| f.rule_id == "cfg-unguarded-sink")
|
||||
.collect();
|
||||
assert!(
|
||||
!guard_findings.is_empty(),
|
||||
"Untyped String shell argument must still produce cfg-unguarded-sink"
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ fn event_handler_callbacks(ctx: &AnalysisContext) -> HashSet<String> {
|
|||
if info.kind != StmtKind::Call {
|
||||
continue;
|
||||
}
|
||||
if let Some(callee) = &info.callee {
|
||||
if let Some(callee) = &info.call.callee {
|
||||
let callee_lower = callee.to_ascii_lowercase();
|
||||
let is_handler = handlers
|
||||
.iter()
|
||||
|
|
@ -28,7 +28,7 @@ fn event_handler_callbacks(ctx: &AnalysisContext) -> HashSet<String> {
|
|||
if is_handler {
|
||||
// The callback function is typically used within the call — any function
|
||||
// that appears as `uses` of this call node is a potential callback.
|
||||
for u in &info.uses {
|
||||
for u in &info.taint.uses {
|
||||
callbacks.insert(u.clone());
|
||||
}
|
||||
}
|
||||
|
|
@ -60,51 +60,72 @@ impl CfgAnalysis for UnreachableCode {
|
|||
}
|
||||
|
||||
// Suppress findings for nodes inside event handler callbacks
|
||||
if let Some(func_name) = &info.enclosing_func
|
||||
if let Some(func_name) = &info.ast.enclosing_func
|
||||
&& handler_callbacks.contains(func_name)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let (rule_id, title, severity) = match info.label {
|
||||
Some(DataLabel::Sanitizer(_)) => (
|
||||
// Check labels in priority order: Sink > Sanitizer > Source
|
||||
let label_classification = if info
|
||||
.taint
|
||||
.labels
|
||||
.iter()
|
||||
.any(|l| matches!(l, DataLabel::Sink(_)))
|
||||
{
|
||||
Some(("cfg-unreachable-sink", "Unreachable sink", Severity::Medium))
|
||||
} else if info
|
||||
.taint
|
||||
.labels
|
||||
.iter()
|
||||
.any(|l| matches!(l, DataLabel::Sanitizer(_)))
|
||||
{
|
||||
Some((
|
||||
"cfg-unreachable-sanitizer",
|
||||
"Unreachable sanitizer",
|
||||
Severity::Medium,
|
||||
),
|
||||
Some(DataLabel::Sink(_)) => {
|
||||
("cfg-unreachable-sink", "Unreachable sink", Severity::Medium)
|
||||
}
|
||||
Some(DataLabel::Source(_)) => (
|
||||
))
|
||||
} else if info
|
||||
.taint
|
||||
.labels
|
||||
.iter()
|
||||
.any(|l| matches!(l, DataLabel::Source(_)))
|
||||
{
|
||||
Some((
|
||||
"cfg-unreachable-source",
|
||||
"Unreachable source",
|
||||
Severity::Low,
|
||||
),
|
||||
_ => {
|
||||
// Check if it's a guard/auth call
|
||||
if super::is_guard_call(info, ctx.lang, ctx.analysis_rules)
|
||||
|| super::is_auth_call(info, ctx.lang)
|
||||
{
|
||||
(
|
||||
"cfg-unreachable-guard",
|
||||
"Unreachable guard/auth check",
|
||||
Severity::Medium,
|
||||
)
|
||||
} else {
|
||||
// Plain unreachable code — low severity
|
||||
continue;
|
||||
}
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let (rule_id, title, severity) = if let Some(lc) = label_classification {
|
||||
lc
|
||||
} else {
|
||||
// Check if it's a guard/auth call
|
||||
if super::is_guard_call(info, ctx.lang, ctx.analysis_rules)
|
||||
|| super::is_auth_call(info, ctx.lang)
|
||||
{
|
||||
(
|
||||
"cfg-unreachable-guard",
|
||||
"Unreachable guard/auth check",
|
||||
Severity::Medium,
|
||||
)
|
||||
} else {
|
||||
// Plain unreachable code — low severity
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let callee_desc = info.callee.as_deref().unwrap_or("(unknown)");
|
||||
let callee_desc = info.call.callee.as_deref().unwrap_or("(unknown)");
|
||||
|
||||
findings.push(CfgFinding {
|
||||
rule_id: rule_id.to_string(),
|
||||
title: title.to_string(),
|
||||
severity,
|
||||
confidence: Confidence::High,
|
||||
span: info.span,
|
||||
span: info.ast.span,
|
||||
message: format!("{title}: `{callee_desc}` is unreachable and will never execute"),
|
||||
evidence: vec![idx],
|
||||
score: None,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue