Skip to content

alexgreensh/repo-forensics / skills/repo-forensics

repo-forensics

Flagged

Security forensics for git repos, AI skills, and MCP servers. Audits dependencies, detects prompt injection, credential theft, runtime dynamism, manifest drift, known CVEs, CISA KEV (actively exploited) vulns, and 2026 attack patterns. Not for fixing vulnerabilities or pentesting.

FileKindSize
.gitignoreother193 B
SKILL.mdskill md43.4 KB
checksums.jsonconfig10.8 KB
checksums.json.sigother64 B
data/README.mdmarkdown1.3 KB
data/compromised_versions.jsonconfig188.3 KB
data/rule_ids.csvother35.3 KB
data/rulepacks/.gitkeepother221 B
data/rulepacks/dead_anchors.jsonconfig9.0 KB
data/rulepacks/mcp_security.jsonconfig31.2 KB
data/rulepacks/runtime_dynamism.jsonconfig46.7 KB
data/rulepacks/sast.jsonconfig107.6 KB
data/rulepacks/secrets.jsonconfig30.4 KB
data/rulepacks/shared.jsonconfig4.4 KB
data/rulepacks/skill_threats.jsonconfig95.4 KB
data/runtime_floors.jsonconfig2.3 KB
data/yara/cryptominers.yarother1.8 KB
data/yara/hacktools.yarother2.2 KB
data/yara/malware.yarother2.2 KB
data/yara/manifest.jsonconfig8.0 KB
data/yara/webshells.yarother2.5 KB
references/cursor-hook-contract.mdmarkdown5.6 KB
references/kernel_privesc_sandbox_pack.mdmarkdown5.0 KB
references/mcp-attack-patterns.mdmarkdown8.7 KB
references/research_sources.mdmarkdown8.0 KB
references/threat_patterns.mdmarkdown20.3 KB
scripts/_context_gate.pyscript21.7 KB
scripts/_ed25519.pyscript5.1 KB
scripts/_pyc_unmarshal.pyscript17.1 KB
scripts/_shared_patterns.pyscript4.8 KB
scripts/adjudication.pyscript16.4 KB
scripts/adjudication_bridge.pyscript1.0 KB
scripts/aggregate_json.pyscript69.2 KB
scripts/auto_scan.pyexecutablescript152.1 KB
scripts/corpus_sync.pyscript10.0 KB
scripts/cursor_pre_scan.pyscript22.5 KB
scripts/dast_sandbox.sbother1.6 KB
scripts/dead_anchors_extract.pyscript14.8 KB
scripts/dead_anchors_probe.pyscript27.1 KB
scripts/forensics_core.pyscript176.5 KB
scripts/gen_rule_ids.pyscript8.6 KB
scripts/hook_adapter.pyscript19.4 KB
scripts/ioc_manager.pyscript49.6 KB
scripts/parse_pnpm_lock.pyscript7.9 KB
scripts/pre_scan.pyscript143.5 KB
scripts/pypi_pins.pyscript8.1 KB
scripts/refresh_controller.pyexecutablescript48.4 KB
scripts/refresh_threat_dbs.pyexecutablescript19.4 KB
scripts/rule_loader.pyscript44.8 KB
scripts/rulepack_feed.pyscript26.4 KB
scripts/run_forensics.shexecutablescript20.3 KB
scripts/sarif_export.pyscript18.6 KB
scripts/scan_agent_skills.pyscript33.2 KB
scripts/scan_archive.pyscript29.1 KB
scripts/scan_ast.pyscript44.9 KB
scripts/scan_binary.pyscript10.9 KB
scripts/scan_bytecode.pyscript28.2 KB
scripts/scan_dast.pyscript28.8 KB
scripts/scan_dataflow.pyscript15.4 KB
scripts/scan_dead_anchors.pyscript15.9 KB
scripts/scan_decode.pyscript37.5 KB
scripts/scan_dependencies.pyscript124.5 KB
scripts/scan_devcontainer.pyscript8.5 KB
scripts/scan_entropy.pyscript15.6 KB
scripts/scan_entrypoint.pyscript34.3 KB
scripts/scan_git_config.pyscript96.3 KB
scripts/scan_git_forensics.pyscript24.1 KB
scripts/scan_history.pyscript14.5 KB
scripts/scan_infra.pyscript54.3 KB
scripts/scan_integrity.pyscript41.0 KB
scripts/scan_lifecycle.pyscript65.1 KB
scripts/scan_manifest_drift.pyscript47.0 KB
scripts/scan_mcp_security.pyscript42.3 KB
scripts/scan_oversize.pyscript11.7 KB
scripts/scan_post_incident.pyscript36.9 KB
scripts/scan_provenance.pyscript19.4 KB
scripts/scan_runtime_dynamism.pyscript23.5 KB
scripts/scan_runtime_floors.pyscript33.5 KB
scripts/scan_sast.pyscript59.1 KB
scripts/scan_secrets.pyscript11.9 KB
scripts/scan_skill_threats.pyscript102.4 KB
scripts/scan_splitstream.pyscript29.5 KB
scripts/scan_yara.pyscript19.7 KB
scripts/session_scan.pyscript54.1 KB
scripts/suppressions.pyscript15.4 KB
scripts/validate_manifests.pyscript13.7 KB
scripts/verify_install.pyscript26.2 KB
scripts/vuln_feed.pyscript31.1 KB
tests/conftest.pyscript13.4 KB
tests/corpus/DEAD_ANCHORS_CORPUS.mdmarkdown2.3 KB
tests/corpus/budgets.jsonconfig5.6 KB
tests/cursor_helpers.pyscript12.6 KB
tests/fixtures/legacy_main_blocks.jsonconfig10.3 KB
tests/fixtures/powershell_verdict_corpus.jsonconfig114.9 KB
tests/golden/parity_mcp_security.jsonconfig17.5 KB
tests/golden/parity_runtime_dynamism.jsonconfig31.7 KB
tests/golden/parity_sast.jsonconfig59.8 KB
tests/golden/parity_secrets.jsonconfig18.8 KB
tests/golden/parity_skill_threats.jsonconfig48.8 KB
tests/parity_corpus.pyscript6.3 KB
tests/powershell_hook.pyscript8.2 KB
tests/report_builders.pyscript5.0 KB
tests/schemas/sarif-schema-2.1.0.jsonconfig109.1 KB
tests/shell_compat.pyscript2.2 KB
tests/test_adjudication_bridge.pyscript832 B
tests/test_adjudication_containment.pyscript1.4 KB
tests/test_adjudication_output.pyscript20.0 KB
tests/test_adjudication_suppressions.pyscript18.7 KB
tests/test_advisory_adjudication.pyscript1.3 KB
tests/test_agent_relay_rules.pyscript7.8 KB
tests/test_aggregate_json.pyscript10.0 KB
tests/test_auto_scan_patterns.pyscript10.5 KB
tests/test_benign_corpus.pyscript16.4 KB
tests/test_benign_new_scanners.pyscript6.1 KB
tests/test_build_output_skip.pyscript10.6 KB
tests/test_capability_ledger.pyscript18.8 KB
tests/test_codex_install.pyscript10.0 KB
tests/test_codex_marketplace.pyscript3.3 KB
tests/test_comment_false_positives.pyscript2.2 KB
tests/test_composer_dependencies.pyscript4.0 KB
tests/test_compromised_versions.pyscript51.2 KB
tests/test_context_gate.pyscript32.4 KB
tests/test_coverage_status.pyscript7.6 KB
tests/test_css_compounding_shrink.pyscript20.8 KB
tests/test_cursor_adapter.pyscript7.8 KB
tests/test_cursor_benign.pyscript3.4 KB
tests/test_cursor_degrade.pyscript12.7 KB
tests/test_cursor_install.pyscript17.1 KB
tests/test_cursor_latency.pyscript7.2 KB
tests/test_cursor_parity.pyscript5.8 KB
tests/test_cursor_redteam_fn.pyscript4.9 KB
tests/test_cursor_tamper_modify.pyscript14.2 KB
tests/test_cursor_wiring.pyscript32.3 KB
tests/test_d1_yara_correlation.pyscript9.2 KB
tests/test_dead_anchors_extract.pyscript7.6 KB
tests/test_dead_anchors_probe.pyscript19.7 KB
tests/test_evidence_engine_parity.pyscript8.1 KB
tests/test_evidence_model.pyscript11.4 KB
tests/test_forensics_core.pyscript79.2 KB
tests/test_fp_hardening_r3.pyscript9.7 KB
tests/test_fp_hardening_r4.pyscript18.8 KB
tests/test_fp_regression_pairs.pyscript62.5 KB
tests/test_fp_structural.pyscript21.2 KB
tests/test_freshness.pyscript6.2 KB
tests/test_frontmatter_validity.pyscript7.0 KB
tests/test_gpg_rce_hotfix.pyscript4.8 KB
tests/test_hook_inert_data.pyscript6.1 KB
tests/test_hook_scripts.pyscript14.0 KB
tests/test_inspection_cpu_budget.pyscript11.6 KB
tests/test_ioc_manager.pyscript55.4 KB
tests/test_kernel_privesc_rules.pyscript27.8 KB
tests/test_legit_precision_regressions.pyscript6.8 KB
tests/test_lethal_trifecta.pyscript20.7 KB
tests/test_manifest_signature.pyscript1.5 KB
tests/test_manifest_validity.pyscript2.9 KB
tests/test_monotonic_trust_e2e.pyscript4.4 KB
tests/test_non_breaking_contract.pyscript22.7 KB
tests/test_openclaw_install.pyscript6.6 KB
tests/test_pack_parity.pyscript24.8 KB
tests/test_parse_pnpm_lock.pyscript10.7 KB
tests/test_plugin_checkout_provenance.pyscript11.1 KB
tests/test_powershell_hook_wire.pyscript10.6 KB
tests/test_powershell_verdict_corpus.pyscript6.2 KB
tests/test_pr44_hardening.pyscript6.5 KB
tests/test_pre_scan.pyscript19.6 KB
tests/test_pre_scan_composer.pyscript7.4 KB
tests/test_precondition_fields.pyscript4.6 KB
tests/test_provenance_offline.pyscript2.5 KB
tests/test_published_rulepack_feed_current.pyscript1.4 KB
tests/test_py38_compat.pyscript3.3 KB
tests/test_pypi_pinned_versions.pyscript19.3 KB
tests/test_pyproject_string_forms.pyscript2.2 KB
tests/test_redteam_fn_regression.pyscript32.5 KB
tests/test_reflective_fetch_execute.pyscript23.5 KB
tests/test_reflective_review_fixes.pyscript17.8 KB
tests/test_refresh_controller.pyscript19.9 KB
tests/test_refresh_rulepacks.pyscript12.4 KB
tests/test_review_gate_regressions.pyscript9.3 KB
tests/test_rule_loader.pyscript23.2 KB
tests/test_rulepack_feed.pyscript38.1 KB
tests/test_run_forensics_json.pyscript1012 B
tests/test_run_scanner_fail_loud.pyscript6.5 KB
tests/test_runtime_floors.pyscript19.8 KB
tests/test_sandbox_probing_rules.pyscript9.6 KB
tests/test_sarif_export.pyscript19.9 KB
tests/test_scan_agent_skills.pyscript31.3 KB
tests/test_scan_archive.pyscript11.6 KB
tests/test_scan_ast.pyscript12.8 KB
tests/test_scan_binary.pyscript15.3 KB
tests/test_scan_bytecode.pyscript21.5 KB
tests/test_scan_dast.pyscript32.1 KB
tests/test_scan_dataflow.pyscript7.1 KB
tests/test_scan_dead_anchors.pyscript11.5 KB
tests/test_scan_decode.pyscript28.0 KB
tests/test_scan_dependencies.pyscript37.8 KB
tests/test_scan_devcontainer.pyscript8.5 KB
tests/test_scan_entropy.pyscript11.2 KB
tests/test_scan_entrypoint.pyscript19.5 KB
tests/test_scan_git_config.pyscript58.5 KB
tests/test_scan_git_config_review_fixes.pyscript33.3 KB

scripts/scan_runtime_floors.py

View on GitHub
#!/usr/bin/env python3
"""
scan_runtime_floors.py - Vulnerable language-runtime declaration scanner

Engine-level vulnerabilities are not malicious code and no package IOC catches
them: PHP2Shell (CVE-2026-109618 / CVE-2026-109619, disclosed 2026-10-21) is a
set of memory-safety bugs (use-after-free, OOM corruption) in the PHP engine
itself, exploitable on a clean "Hello World" deploy. What a repository CAN tell you is which runtime it declares. This
scanner reads those declarations and flags the ones pinned to - or capped
below - a patched floor:

  - composer.json        require / require-dev "php" constraints and
                         config.platform.php exact pins
  - composer.lock        platform / platform-overrides "php" entries
  - Dockerfile*          FROM php:<tag>, including ARG-resolved versions
                         (${VAR}, ${VAR:-default}, $VAR anywhere in the tag)
  - docker-compose*.yml  image: php:<tag> and <image>:...phpX.Y tags
  - .github/workflows/*  setup-php php-version pins and matrix php lists
                         (advisory severity - CI testing an old branch is
                         legitimate for libraries)

The floors are DATA (data/runtime_floors.json), keyed by advisory, so the
next engine-level event (any runtime) is a data edit, not a code change.

Severity posture (false-positive discipline). CRITICAL is reserved for what
actually deploys:
  - Dockerfile / docker-compose image tags on an end-of-life branch, or an
    exact patch tag below the floor: CRITICAL.
  - composer require / require-dev (and composer.lock platform) constraints
    that CANNOT resolve to any patched version: HIGH. A constraint is a
    declaration, not a deployment.
  - config.platform.php / platform-overrides (the runtime Composer emulates
    for dependency resolution, often a library's minimum): LOW below the
    floor, MEDIUM on an end-of-life branch.
  - setup-php: a direct single php-version pin on an EOL branch is MEDIUM
    (an exact pin below the floor is LOW); matrix entries are LOW, since a
    library testing old branches is legitimate.
  - Constraints that admit a patched version (e.g. ^8.2, >=7.4) or a branch
    newer than every listed floor (^9.0): silent.
  - Moving minor tags on maintained branches (php:8.2): low note to rebuild,
    because a cached pull from before the patch is still vulnerable.
  - Installed dependencies' metadata (vendor/**/composer.json|lock) says
    nothing about the runtime that executes the project: skipped.
  - Unparseable constraints and unresolved variables: silent. This scanner
    only flags what it is sure about.

Created by Alex Greenshpun
"""

import json
import os
import re
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import forensics_core as core  # noqa: E402

SCANNER_NAME = "runtime_floors"

DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         '..', 'data', 'runtime_floors.json')

MAX_READ_BYTES = core.MAX_FILE_SIZE_MB * 1024 * 1024


def load_runtime_floors(path=DATA_PATH):
    """Load the advisory database. Returns (runtimes_dict, error_str)."""
    try:
        with open(path, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except (OSError, UnicodeDecodeError, json.JSONDecodeError) as e:
        return {}, str(e)
    if not isinstance(data, dict):
        return {}, "top level is not an object"
    major = str(data.get('schema_version', '')).split('.')[0]
    if major != '1':
        return {}, "unsupported schema_version %r" % (data.get('schema_version'),)
    runtimes = data.get('runtimes')
    if not isinstance(runtimes, dict):
        return {}, "missing 'runtimes' object"
    for name, raw in runtimes.items():
        if not isinstance(raw, dict):
            return {}, "runtime %r is not an object" % (name,)
        advs = raw.get('advisories')
        if not isinstance(advs, list) or not all(isinstance(a, dict) for a in advs):
            return {}, "runtime %r has a malformed 'advisories' list" % (name,)
        for adv in advs:
            label = adv.get('id', '?')
            floors = adv.get('patched_floors') or {}
            if not isinstance(floors, dict) or not all(
                    isinstance(k, str) and isinstance(v, str) for k, v in floors.items()):
                return {}, "advisory %r has a malformed 'patched_floors' object" % (label,)
            for key in ('cves', 'references'):
                val = adv.get(key) or []
                if not isinstance(val, list) or not all(isinstance(x, str) for x in val):
                    return {}, "advisory %r has a malformed %r list" % (label, key)
    return runtimes, None


def parse_version(text):
    """Parse a version prefix like '8.1', 'v8.1.4', '8.1.4RC2' -> (8, 1, 4).
    Missing segments pad with 0. None when there is no numeric prefix."""
    if not isinstance(text, str):
        return None
    m = re.match(r'^\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?', text.strip())
    if not m:
        return None
    return (int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0))


def _branch_key(v):
    return (v[0], v[1])


def _next_branch(branch):
    return (branch[0], branch[1] + 1, 0)


class Advisory:
    """One runtime advisory: patched floors per maintained branch + EOL line."""

    def __init__(self, runtime, raw):
        self.runtime = runtime
        self.id = raw.get('id', 'unknown')
        self.title = raw.get('title', '')
        self.cves = list(raw.get('cves', []))
        self.disclosed = raw.get('disclosed', '')
        self.references = list(raw.get('references', []))
        self.eol_note = raw.get('eol_note', '')
        self.floors = {}
        for branch, floor in (raw.get('patched_floors') or {}).items():
            b = parse_version(branch)
            f = parse_version(floor)
            if b and f:
                self.floors[_branch_key(b)] = (f, floor)
        eb = parse_version(raw.get('eol_below', ''))
        self.eol_below = _branch_key(eb) if eb else None

    @property
    def cve_label(self):
        return ' / '.join(self.cves) if self.cves else self.id

    @property
    def reference(self):
        return self.references[0] if self.references else ''

    def check_pin(self, version_text):
        """Check one concrete version. Returns (severity, kind, detail) or None."""
        v = parse_version(version_text)
        if v is None:
            return None
        branch = _branch_key(v)
        if self.eol_below and branch < self.eol_below:
            return ('critical', 'eol',
                    "%s %d.%d is end-of-life and has no upstream release fixing %s. %s"
                    % (self.runtime, v[0], v[1], self.cve_label, self.eol_note))
        if branch in self.floors:
            floor, floor_text = self.floors[branch]
            if v < floor:
                return ('high', 'below-floor',
                        "%s %d.%d.%d is below the %s patched floor %s"
                        % (self.runtime, v[0], v[1], v[2], self.cve_label, floor_text))
        return None


# --- Composer constraint evaluation -----------------------------------------
#
# The only question asked of a constraint is "can it resolve to a patched
# release?". Each ||-alternative reduces to a coarse [lower, upper) interval.
# Intervals are deliberately approximate, and every ambiguity resolves toward
# SILENT, because a range that admits a patched release is not a vulnerable
# deployment.

_OPS = ['>=', '<=', '>', '<', '=']
_OP_RE = re.compile('^(' + '|'.join(_OPS) + r')\s*(\S+)$')


def _bump(version_tuple, segment):
    """Increment one segment of a version tuple, zeroing what follows.
    (8,1,4) seg1 -> (8,2,0)."""
    parts = list(version_tuple) + [0, 0, 0]
    parts[segment] += 1
    for i in range(segment + 1, 3):
        parts[i] = 0
    return tuple(parts[:3])


def _interval_of_token(token):
    """One comparator token -> (lower, upper) tuple bounds, lower-inclusive /
    upper-exclusive (None = unbounded). None when unrecognizable."""
    token = token.strip().rstrip(',')
    if not token:
        return None
    # 8.3.x-dev / 8.x-dev is the branch's dev head: same as the 8.3.* wildcard
    token = re.sub(r'(?i)^(v?\d+(?:\.\d+)*\.x)-dev$', r'\1', token)
    # wildcard ranges: 8.1.* / 8.1.x / 8.* / *
    if '*' in token or re.search(r'(?:^|\.)x$', token, re.IGNORECASE):
        parts = re.split(r'[.*]', token.lower())
        parts = [p for p in parts if p not in ('', 'x')]
        if not parts or not all(p.isdigit() for p in parts):
            return (None, None)  # bare '*' - everything
        if len(parts) == 1:
            base = (int(parts[0]), 0, 0)
            return (base, _bump(base, 0))
        base = (int(parts[0]), int(parts[1]), 0)
        return (base, _bump(base, 1))
    m = _OP_RE.match(token)
    if m:
        op, ver = m.group(1), m.group(2)
        v = parse_version(ver)
        if v is None:
            return None
        if op == '>=':
            return (v, None)
        if op == '>':
            return (_bump(v, 2), None)
        if op == '<=':
            return (None, _bump(v, 2))
        if op == '<':
            return (None, v)
        return (v, _bump(v, 2))  # '='
    m = re.match(r'^(\^|~)\s*(\S+)$', token)
    if m:
        op, ver = m.group(1), m.group(2)
        v = parse_version(ver)
        if v is None:
            return None
        if op == '^':
            # >=v, < next major (0.x: < next minor; 0.0.x: exact-ish)
            if v[0] > 0:
                upper = _bump(v, 0)
            elif v[1] > 0:
                upper = _bump(v, 1)
            else:
                upper = _bump(v, 2)
            return (v, upper)
        # '~': ~8.1 -> <9.0 (next major when no patch given);
        #      ~8.1.2 -> <8.2 (next minor when patch given)
        if re.match(r'^\s*v?\d+\.\d+\.\d+', ver):
            upper = _bump(v, 1)
        else:
            upper = _bump(v, 0)
        return (v, upper)
    # bare version: exact pin (composer normalizes 8.1 -> 8.1.0)
    v = parse_version(token)
    if v is None:
        return None
    return (v, _bump(v, 2))


def _interval_of_alternative(alt):
    """AND-combine one ||-alternative's tokens into a single [lower, upper).
    Returns None when any token is unrecognizable (caller treats as unknown)."""
    alt = alt.strip()
    if not alt:
        return None
    # hyphen range: "8.0 - 8.3" (partial upper widens: 8.0 - 8.3 = <8.4)
    hm = re.match(r'^(\S+)\s+-\s+(\S+)$', alt)
    if hm:
        lo = parse_version(hm.group(1))
        hi_text = hm.group(2)
        hi = parse_version(hi_text)
        if lo is None or hi is None:
            return None
        if re.match(r'^\s*v?\d+\.\d+\.\d+', hi_text):
            upper = _bump(hi, 2)  # inclusive of the patch
        elif re.match(r'^\s*v?\d+\.\d+$', hi_text):
            upper = _bump(hi, 1)
        else:
            upper = _bump(hi, 0)
        return (lo, upper)
    lower, upper = None, None
    for token in re.split(r'[\s,]+', alt):
        if not token:
            continue
        iv = _interval_of_token(token)
        if iv is None:
            return None
        lo, hi = iv
        if lo is not None and (lower is None or lo > lower):
            lower = lo
        if hi is not None and (upper is None or hi < upper):
            upper = hi
    return (lower, upper)


def _intersects(interval, lo, hi):
    """Does [lower, upper) intersect [lo, hi)? None bounds are open."""
    lower, upper = interval
    if upper is not None and lo is not None and upper <= lo:
        return False
    if lower is not None and hi is not None and lower >= hi:
        return False
    return True


def check_constraint(constraint, advisory):
    """Check a composer `php` constraint against one advisory.

    Returns (severity, kind, detail) or None. SILENT unless NO alternative can
    resolve to a patched release:
      - no alternative reaches any maintained (or newer) branch -> 'eol' high
      - some alternative reaches a maintained branch but always below that
        branch's floor -> 'below-floor' high
    A constraint is a declaration, not a deployment, so it never goes above
    HIGH; the concrete image pins carry CRITICAL.
    Anything else (admits a patched release, or unparseable) -> None.
    """
    if not isinstance(constraint, str) or not constraint.strip():
        return None
    alternatives = re.split(r'\|\|?', constraint)
    intervals = []
    for alt in alternatives:
        iv = _interval_of_alternative(alt)
        if iv is None:
            return None  # unknown syntax: say nothing rather than guess
        intervals.append(iv)

    # A constraint that admits a branch NEWER than every listed floor (e.g.
    # ^8.6 or >=9.0 once those ship) can resolve to a release cut after the
    # fix: never flag it.
    if advisory.floors:
        beyond = _next_branch(max(advisory.floors))
        if any(_intersects(iv, beyond, None) for iv in intervals):
            return None

    reaches_maintained = False
    for iv in intervals:
        for branch in advisory.floors:
            if _intersects(iv, branch + (0,), _next_branch(branch)):
                reaches_maintained = True
                break
        if reaches_maintained:
            break

    if not reaches_maintained:
        if advisory.eol_below is not None:
            return ('high', 'eol',
                    "constraint '%s' cannot resolve to any maintained %s branch; "
                    "every version it permits is end-of-life and unpatched for %s. %s"
                    % (constraint.strip(), advisory.runtime, advisory.cve_label,
                       advisory.eol_note))
        return None

    for iv in intervals:
        for branch, (floor, floor_text) in advisory.floors.items():
            if _intersects(iv, floor, _next_branch(branch)):
                return None  # some patched release satisfies the constraint
    return ('high', 'below-floor',
            "constraint '%s' permits maintained %s branches but always below the "
            "%s patched floor (%s)"
            % (constraint.strip(), advisory.runtime, advisory.cve_label,
               ', '.join(sorted(set(t for _, t in advisory.floors.values())))))


# --- Finding helpers ----------------------------------------------------------

def _read_text(filepath):
    try:
        with open(filepath, 'rb') as f:
            raw = f.read(MAX_READ_BYTES + 1)
    except OSError:
        return None
    if len(raw) > MAX_READ_BYTES:
        raw = raw[:MAX_READ_BYTES]
    return raw.decode('utf-8-sig', errors='replace')  # utf-8-sig strips a BOM


def _finding(severity, title, description, rel_path, line, snippet, confidence=0.9):
    return core.Finding(
        scanner=SCANNER_NAME, severity=severity, title=title,
        description=description, file=rel_path, line=line,
        snippet=(snippet or '')[:120], category='vulnerable-runtime',
        confidence=confidence,
    )


def _pin_finding(advisory, version_text, source_desc, rel_path, line, snippet,
                 severity_by_kind=None):
    hit = advisory.check_pin(version_text)
    if hit is None:
        return None
    severity, kind, detail = hit
    if severity_by_kind:
        severity = severity_by_kind.get(kind, severity)
    return _finding(
        severity,
        "%s runtime pin vulnerable to %s: %s" % (advisory.runtime, advisory.cve_label,
                                                 version_text.strip()),
        "%s (%s). %s. Update to a patched release. Reference: %s"
        % (detail, source_desc, advisory.title, advisory.reference),
        rel_path, line, snippet)


def _constraint_finding(advisory, constraint, source_desc, rel_path, line, snippet):
    hit = check_constraint(constraint, advisory)
    if hit is None:
        return None
    severity, kind, detail = hit
    return _finding(
        severity,
        "%s version constraint excludes every %s patch: %s"
        % (advisory.runtime, advisory.cve_label, constraint.strip()[:40]),
        "%s (%s). %s. Reference: %s"
        % (detail, source_desc, advisory.title, advisory.reference),
        rel_path, line, snippet)


# --- composer.json / composer.lock -------------------------------------------

# config.platform.php / platform-overrides.php is the runtime Composer EMULATES
# when resolving dependencies. Libraries routinely set it to their minimum
# supported version, so it is a weak deployment signal.
_PLATFORM_SEVERITY = {'eol': 'medium', 'below-floor': 'low'}

def _find_php_line(content, section_hint):
    """Best-effort line number of the "php" key for attribution."""
    for i, line in enumerate(content.split('\n'), 1):
        if '"php"' in line:
            return i, line.strip()
    return 0, section_hint


def scan_composer_json(filepath, rel_path, advisories):
    findings = []
    content = _read_text(filepath)
    if content is None:
        return findings
    try:
        data = json.loads(content)
    except (json.JSONDecodeError, RecursionError):
        return findings
    if not isinstance(data, dict):
        return findings
    line, snippet = _find_php_line(content, 'composer.json "php"')
    for section in ('require', 'require-dev'):
        reqs = data.get(section)
        if not isinstance(reqs, dict):
            continue
        constraint = reqs.get('php')
        if isinstance(constraint, str):
            for adv in advisories:
                f = _constraint_finding(adv, constraint,
                                        'composer.json %s.php' % section,
                                        rel_path, line, snippet)
                if f:
                    findings.append(f)
    platform = data.get('config', {}).get('platform') if isinstance(data.get('config'), dict) else None
    if isinstance(platform, dict):
        pin = platform.get('php')
        if isinstance(pin, str):
            for adv in advisories:
                f = _pin_finding(adv, pin, 'composer.json config.platform.php '
                                 '(the runtime Composer emulates for dependency '
                                 'resolution; libraries often set it to their '
                                 'minimum supported version)', rel_path, line,
                                 snippet, severity_by_kind=_PLATFORM_SEVERITY)
                if f:
                    findings.append(f)
    return findings


def scan_composer_lock(filepath, rel_path, advisories):
    findings = []
    content = _read_text(filepath)
    if content is None:
        return findings
    try:
        data = json.loads(content)
    except (json.JSONDecodeError, RecursionError):
        return findings
    if not isinstance(data, dict):
        return findings
    line, snippet = _find_php_line(content, 'composer.lock platform php')
    for key in ('platform', 'platform-overrides'):
        section = data.get(key)
        if not isinstance(section, dict):
            continue
        value = section.get('php')
        if not isinstance(value, str):
            continue
        for adv in advisories:
            if key == 'platform-overrides':
                f = _pin_finding(adv, value, 'composer.lock platform-overrides.php '
                                 '(the runtime Composer emulates)', rel_path, line,
                                 snippet, severity_by_kind=_PLATFORM_SEVERITY)
            else:
                f = _constraint_finding(adv, value, 'composer.lock platform.php',
                                        rel_path, line, snippet)
            if f:
                findings.append(f)
    return findings


# --- Dockerfile / docker-compose ----------------------------------------------
#
# Every regex here runs on attacker-controlled lines (up to the 10 MB file
# cap), so each one is linear: no two adjacent unbounded runs that can both
# consume the same character. The compose `<image>:...phpX.Y` form is split
# by hand instead of by regex (a two-run pattern was O(n^2) on colon floods).

_TAG_VERSION_RE = re.compile(r'^v?(\d+(?:\.\d+){0,2})((?:[-+].*)?)$')
_ARG_RE = re.compile(r'^\s*ARG\s+([A-Za-z_][A-Za-z0-9_]*)(?:=(\S+))?\s*$')
_FROM_PHP_RE = re.compile(
    r'^\s*FROM\s+(?:--platform=\S+\s+)?["\']?(?:[\w.-]+(?::\d+)?/)*(?:library/)?php:([^\s"\']+)',
    re.IGNORECASE)
# ${VAR}, ${VAR:-default}, ${VAR-default}, $VAR anywhere inside a tag
_VAR_REF_RE = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}$]*))?\}|\$([A-Za-z_][A-Za-z0-9_]*)')
# compose image references: php:<tag> directly, or any <image>:<tag> whose tag
# carries phpX.Y (wordpress:php8.1-apache etc.)
_IMAGE_PHP_RE = re.compile(
    r'^\s*image:\s*["\']?(?:[\w.-]+(?::\d+)?/)*(?:library/)?php:([^\s"\']+)',
    re.IGNORECASE)
_IMAGE_REF_RE = re.compile(r'^\s*image:\s*["\']?([^\s"\']+)', re.IGNORECASE)
_PHP_IN_TAG_RE = re.compile(r'php(\d+(?:\.\d+){0,2})', re.IGNORECASE)


def _strip_quotes(value):
    if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
        return value[1:-1]
    return value


def _resolve_tag_vars(tag, args):
    """Substitute ARG references anywhere in a FROM tag (php:${V}-fpm,
    php:$V, php:${V:-8.2}) using collected ARG defaults. Returns the resolved
    literal, or None when any reference stays unresolved (a `$` remains):
    the version is unknowable from the repo alone."""
    if '$' not in tag:
        return tag

    def sub(m):
        name = m.group(1) or m.group(3)
        default = m.group(2)
        if args.get(name):
            return args[name]
        if default:
            return default
        return m.group(0)  # leave it; the '$' check below rejects the tag

    resolved = _VAR_REF_RE.sub(sub, tag)
    if '$' in resolved:
        return None
    return resolved


def _check_docker_tag(advisory, tag, source_desc, rel_path, line_no, line_text):
    """Check one image tag; returns a Finding or None.

    An image tag is what actually deploys, so it carries the only CRITICAL:
      - any tag on an end-of-life branch, including major-only tags on an
        EOL major (php:7, php:7.4-apache): CRITICAL
      - an exact patch tag below the floor (php:8.3.30): CRITICAL
      - a moving minor tag on a maintained branch (php:8.3): LOW rebuild note
      - non-version tags (latest/cli/fpm), patched tags, and major-only tags
        on a maintained major (php:8 resolves to the newest 8.x): silent."""
    tag = tag.split('@', 1)[0]  # drop digest pins (image:tag@sha256:...)
    m = _TAG_VERSION_RE.match(tag)
    if not m:
        return None  # latest / cli / fpm-alpine etc: no version to judge
    version_text = m.group(1)
    v = parse_version(version_text)
    if v is None:
        return None
    segments = len(version_text.split('.'))
    branch = _branch_key(v)
    eol_hit = False
    if advisory.eol_below:
        if segments == 1:
            # php:7 is a moving MAJOR tag resolving to the newest 7.x. It is
            # EOL only when the WHOLE major sits below the EOL line.
            eol_hit = v[0] < advisory.eol_below[0]
        else:
            eol_hit = branch < advisory.eol_below
    if eol_hit:
        label = ('%d' % v[0]) if segments == 1 else ('%d.%d' % (v[0], v[1]))
        return _finding(
            'critical',
            "%s image tag on end-of-life %s %s: php:%s"
            % (advisory.runtime, advisory.runtime, label, tag),
            ("%s %s is end-of-life and has no upstream release fixing %s. %s (%s). "
             "Reference: %s")
            % (advisory.runtime, label, advisory.cve_label,
               advisory.eol_note, source_desc, advisory.reference),
            rel_path, line_no, line_text.strip())
    if segments == 1:
        return None  # php:8 -> newest 8.x, which is patched
    if branch in advisory.floors:
        floor, floor_text = advisory.floors[branch]
        if segments >= 3 and v < floor:
            # Exact patch pin below the floor: a concrete vulnerable deploy.
            return _finding(
                'critical',
                "%s image tag vulnerable to %s: php:%s"
                % (advisory.runtime, advisory.cve_label, tag),
                ("%s %d.%d.%d is below the %s patched floor %s (%s). %s. "
                 "Rebuild on a patched tag. Reference: %s")
                % (advisory.runtime, v[0], v[1], v[2], advisory.cve_label,
                   floor_text, source_desc, advisory.title, advisory.reference),
                rel_path, line_no, line_text.strip())
        if segments == 2 and floor[2] > 0:
            # Moving MINOR tag on a maintained branch: resolves to the newest
            # patch on rebuild, but a cached pull from before it is vulnerable.
            # (A branch whose first release already carries the fix, floor
            # X.Y.0, never had a vulnerable GA image: nothing to rebuild.)
            return _finding(
                'low',
                "Moving %s image tag php:%s - rebuild to pull the %s patch"
                % (advisory.runtime, tag, advisory.cve_label),
                ("The moving tag php:%s resolves to the latest %d.%d.x, patched "
                 "at %s since %s, but an image pulled before then stays "
                 "vulnerable. Rebuild with --pull and verify the resolved "
                 "version. Reference: %s")
                % (tag, v[0], v[1], floor_text, advisory.disclosed,
                   advisory.reference),
                rel_path, line_no, line_text.strip(), confidence=0.6)
    return None


def scan_dockerfile(filepath, rel_path, advisories):
    findings = []
    content = _read_text(filepath)
    if content is None:
        return findings
    args = {}
    for line_no, line in enumerate(content.split('\n'), 1):
        am = _ARG_RE.match(line)
        if am:
            if am.group(2):
                args[am.group(1)] = _strip_quotes(am.group(2))
            continue
        fm = _FROM_PHP_RE.match(line)
        if not fm:
            continue
        raw_tag = _strip_quotes(fm.group(1).strip())
        tag = _resolve_tag_vars(raw_tag, args)
        if tag is None:
            continue  # unresolved variable: version unknowable here
        for adv in advisories:
            f = _check_docker_tag(adv, tag, 'Dockerfile FROM', rel_path, line_no, line)
            if f:
                findings.append(f)
    return findings


def _compose_php_version(line):
    """The PHP version text an `image:` line deploys, or None. Linear time."""
    m = _IMAGE_PHP_RE.match(line)
    if m:
        return m.group(1)  # image is php:<tag>: the tag itself carries it
    rm = _IMAGE_REF_RE.match(line)
    if not rm:
        return None
    ref = rm.group(1).split('@', 1)[0]
    colon = ref.rfind(':')
    if colon <= ref.rfind('/'):
        return None  # no tag (a registry port colon sits before the last '/')
    pm = _PHP_IN_TAG_RE.search(ref[colon + 1:])
    return pm.group(1) if pm else None


def scan_compose(filepath, rel_path, advisories):
    findings = []
    content = _read_text(filepath)
    if content is None:
        return findings
    for line_no, line in enumerate(content.split('\n'), 1):
        version_text = _compose_php_version(line)
        if version_text is None:
            continue
        for adv in advisories:
            f = _check_docker_tag(adv, version_text, 'docker-compose image',
                                  rel_path, line_no, line)
            if f:
                findings.append(f)
    return findings


# --- GitHub workflows (setup-php) ---------------------------------------------
#
# Advisory severity only: a library CI matrix that tests old PHP branches is
# legitimate. Matrix entries are LOW; a direct single php-version pin is MEDIUM
# on an EOL branch (it is what this job runs on) and LOW below the floor. The
# finding text says why it may not apply.

_PHP_VERSION_KEY_RE = re.compile(r'^\s*php-version:\s*["\']?([\d.]+)["\']?\s*$', re.IGNORECASE)
_MATRIX_PHP_KEY_RE = re.compile(r'^\s*php:\s*\[(.*?)\]\s*$', re.IGNORECASE)
_MATRIX_PHP_BLOCK_RE = re.compile(r'^(\s*)php:\s*$', re.IGNORECASE)
_MATRIX_ITEM_RE = re.compile(r'^\s*-\s*["\']?([\d.]+)["\']?\s*$')


def scan_workflow(filepath, rel_path, advisories):
    findings = []
    content = _read_text(filepath)
    if content is None:
        return findings
    versions = []  # (line_no, version_text, line, is_matrix)
    in_php_block = False
    php_block_indent = 0
    for line_no, line in enumerate(content.split('\n'), 1):
        if in_php_block:
            indent = len(line) - len(line.lstrip())
            im = _MATRIX_ITEM_RE.match(line)
            if line.strip() and indent > php_block_indent and im:
                versions.append((line_no, im.group(1), line, True))
                continue
            in_php_block = False
        m = _PHP_VERSION_KEY_RE.match(line)
        if m:
            versions.append((line_no, m.group(1), line, False))
            continue
        m = _MATRIX_PHP_KEY_RE.match(line)
        if m:
            for tok in re.split(r'[,]', m.group(1)):
                tok = tok.strip().strip('\'"')
                if re.match(r'^\d+(\.\d+){0,2}$', tok):
                    versions.append((line_no, tok, line, True))
            continue
        m = _MATRIX_PHP_BLOCK_RE.match(line)
        if m:
            in_php_block = True
            php_block_indent = len(m.group(1))
    for line_no, version_text, line, is_matrix in versions:
        # A minor-only CI pin (php-version: '8.3') is a MOVING tag: setup-php
        # resolves it to the newest 8.3.x on every run, so it picks up the
        # patch by itself. Only EOL pins and exact patch pins below the floor
        # carry signal in CI.
        for adv in advisories:
            hit = adv.check_pin(version_text)
            if hit is None:
                continue
            severity, kind, detail = hit
            if kind == 'below-floor':
                vm = re.match(r'^v?(\d+\.\d+)(?:\.(\d+))?', version_text)
                if vm is not None and vm.group(2) is None:
                    continue  # moving minor pin on a maintained branch
            severity = 'medium' if (kind == 'eol' and not is_matrix) else 'low'
            findings.append(_finding(
                severity,
                "CI workflow pins %s %s, vulnerable to %s"
                % (adv.runtime, version_text, adv.cve_label),
                ("%s (GitHub Actions setup-php %s). Testing against an old branch "
                 "in CI is legitimate for libraries; act on this only if the "
                 "workflow deploys or publishes from that runtime. %s. Reference: %s")
                % (detail, 'matrix entry' if is_matrix else 'php-version pin',
                   adv.title, adv.reference),
                rel_path, line_no, line.strip(), confidence=0.5))
    return findings


# --- Driver --------------------------------------------------------------------

_DOCKERFILE_RE = re.compile(r'^(Dockerfile(\..+|-.+)?|.+\.Dockerfile)$', re.IGNORECASE)
_COMPOSE_RE = re.compile(r'^(docker-)?compose(-.+)?\.ya?ml$', re.IGNORECASE)


def _target_kind(rel_path):
    base = os.path.basename(rel_path)
    if base == 'composer.json':
        return 'composer.json'
    if base == 'composer.lock':
        return 'composer.lock'
    if _DOCKERFILE_RE.match(base):
        return 'dockerfile'
    if _COMPOSE_RE.match(base):
        return 'compose'
    norm = rel_path.replace(os.sep, '/')
    if norm.startswith('.github/workflows/') and base.endswith(('.yml', '.yaml')):
        return 'workflow'
    return None


def main():
    import argparse
    parser = argparse.ArgumentParser(
        description="Flag declared language runtimes pinned below a patched "
                    "vulnerability floor (data: runtime_floors.json)")
    parser.add_argument('path', help='Repository path to scan')
    parser.add_argument('--format', default='text', choices=['text', 'json'])
    args = parser.parse_args()

    repo_path = os.path.abspath(args.path)
    if not os.path.isdir(repo_path):
        print("[!] Path is not a directory: %s" % repo_path, file=sys.stderr)
        sys.exit(2)

    runtimes, err = load_runtime_floors()
    findings = []
    if err:
        # A gate that cannot run denies: no silent clean when the floor data
        # is missing or corrupt.
        findings.append(_finding(
            'medium',
            "Runtime-floor data unavailable",
            "data/runtime_floors.json could not be loaded (%s); vulnerable-"
            "runtime declarations were NOT checked. Restore the data file."
            % err,
            '', 0, '', confidence=0.0))
    else:
        advisories = []
        for runtime, raw in runtimes.items():
            for adv in (raw or {}).get('advisories', []):
                advisories.append(Advisory(raw.get('name', runtime), adv))

        ignore_patterns = core.load_ignore_patterns(repo_path)
        for file_path, rel_path in core.walk_repo(repo_path, ignore_patterns,
                                                  skip_binary=True,
                                                  skip_lockfiles=False):
            kind = _target_kind(rel_path)
            if kind in ('composer.json', 'composer.lock') and \
                    '/vendor/' in '/' + rel_path.replace(os.sep, '/'):
                # Installed dependency metadata: a library's `php` requirement
                # says nothing about the runtime that executes this project.
                # (scan_dependencies still reads vendor/ for package IOCs.)
                continue
            if kind == 'composer.json':
                findings.extend(scan_composer_json(file_path, rel_path, advisories))
            elif kind == 'composer.lock':
                findings.extend(scan_composer_lock(file_path, rel_path, advisories))
            elif kind == 'dockerfile':
                findings.extend(scan_dockerfile(file_path, rel_path, advisories))
            elif kind == 'compose':
                findings.extend(scan_compose(file_path, rel_path, advisories))
            elif kind == 'workflow':
                findings.extend(scan_workflow(file_path, rel_path, advisories))

    core.output_findings(findings, args.format, SCANNER_NAME)


if __name__ == '__main__':
    main()
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall