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/verify_install.py

View on GitHub
#!/usr/bin/env python3
"""
verify_install.py - Skill Installation Integrity Verifier (v2)
Verifies that repo-forensics itself hasn't been tampered with.

Modes:
  --generate    Create checksums.json for all skill files (run at release time)
  --verify      Check current files against checksums.json (run at install/audit time)

Uses SHA256 checksums. Ed25519 signatures can be added when a signing key
is established for marketplace distribution.

Created by Alex Greenshpun
"""

import os
import sys
import json

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

sha256_file = core.sha256_file
SOURCE_ONLY_MANIFEST_FILES = {".agents/plugins/marketplace.json"}


def get_skill_root():
    """Get the root directory of the repo-forensics skill."""
    scripts_dir = os.path.dirname(os.path.abspath(__file__))
    return os.path.dirname(scripts_dir)  # skills/repo-forensics/


def get_repo_root(skill_root):
    """Get the repository root (two levels up from skill_root).

    skill_root is skills/repo-forensics/, so repo root is the parent of skills/.
    Used by symlink integrity tracking — top-level repo symlinks (like the
    backward-compat skill -> skills/repo-forensics symlink added in v2.4.1)
    live outside skill_root and are invisible to get_tracked_files, so they
    need a separate check to prevent tarball-poisoning attacks that replace
    the symlink target.
    """
    return os.path.dirname(os.path.dirname(skill_root))


def is_plugin_cache_layout(repo_root):
    """Return True when repo_root is an installed agent plugin cache payload."""
    parts = os.path.realpath(repo_root).split(os.sep)
    return any(
        parts[i] == "plugins" and i + 1 < len(parts) and parts[i + 1] == "cache"
        for i in range(len(parts))
    )


def is_marketplace_mirror_layout(repo_root):
    """The nested Codex plugin omits the source checkout's .agents catalog."""
    path = os.path.normpath(repo_root)
    return (os.path.basename(path) == "repo-forensics"
            and os.path.basename(os.path.dirname(path)) == "plugins"
            and os.path.isfile(os.path.join(path, ".codex-plugin", "plugin.json")))


def get_tracked_hook_files(repo_root):
    """Get load-bearing hook scripts at the repo-root hooks/ directory.

    These files live outside skill_root and are invisible to
    get_tracked_files, but they are invoked by the plugin's hooks.json at
    runtime. If an attacker tampers with hooks/first-run-nudge.sh or
    hooks/run_auto_scan.sh, the checksum registry (scoped to skill_root)
    would not detect the tamper.

    This function enumerates files in the repo-root hooks/ directory so
    their content hashes can be included in checksums.json under a
    separate repo_hooks field. Same rationale as get_tracked_symlinks:
    every load-bearing file invoked by the plugin manifest must be in
    the integrity registry, even if it lives outside skill_root.

    Walks SUBDIRECTORIES too (added with the Cursor adapter). The original
    implementation listed hooks/ one level deep and skipped anything that was
    not a regular file, so per-agent wrapper directories such as hooks/cursor/
    would have been silently exempt from the integrity registry — the exact gap
    class this function was written to close, reopened by a directory. Depth is
    bounded by the hooks tree itself, which holds only wrapper scripts.
    """
    hooks_dir = os.path.join(repo_root, "hooks")
    if not os.path.isdir(hooks_dir):
        return []

    tracked = []
    skip_files = {'.DS_Store'}
    skip_dirs = {'__pycache__', '.pytest_cache', 'node_modules', '.git'}

    for dirpath, dirnames, filenames in os.walk(hooks_dir):
        # Never follow a symlinked directory out of the hooks tree.
        dirnames[:] = sorted(
            d for d in dirnames
            if d not in skip_dirs and not os.path.islink(os.path.join(dirpath, d))
        )
        for entry in sorted(filenames):
            full_path = os.path.join(dirpath, entry)
            if not os.path.isfile(full_path):
                continue
            if os.path.islink(full_path):
                continue
            if entry in skip_files:
                continue
            rel = os.path.relpath(full_path, repo_root).replace(os.sep, "/")
            tracked.append(rel)
    return tracked


def get_tracked_runtime_manifest_files(repo_root):
    """Get load-bearing plugin manifest files under agent plugin dirs.

    Claude, Codex, Cursor, Kimi, and cross-agent marketplace manifests live
    outside skill_root but determine what hooks and skills the agent loads.
    Extending the integrity registry to cover them closes the same gap class
    as hook files (commit 64fbe57).

    `.cursor-plugin` was added with the Cursor adapter (PRD v3 O8) and
    `.kimi-plugin` with the Kimi Code adapter. A manifest that is not in this
    tuple is checksummed by nobody: it escapes both `--verify` and the
    pinned-key signature check, so a tampered manifest could re-point the
    hook commands with nothing to notice.
    """
    tracked = []
    for dirname in (".claude-plugin", ".codex-plugin", ".cursor-plugin",
                    ".kimi-plugin"):
        manifest_dir = os.path.join(repo_root, dirname)
        try:
            if not os.path.isdir(manifest_dir):
                continue
            entries = sorted(os.listdir(manifest_dir))
        except OSError:
            continue

        for entry in entries:
            full_path = os.path.join(manifest_dir, entry)
            if not os.path.isfile(full_path):
                continue
            if entry.endswith('.json'):
                tracked.append(f"{dirname}/{entry}")

    return tracked


def get_tracked_source_manifest_files(repo_root):
    """Get source-checkout-only marketplace manifests.

    Codex discovers local marketplaces from .agents/plugins/marketplace.json in
    the source checkout, but installed plugin cache payloads do not retain that
    catalog. Track it for release/source verification without making installed
    Codex cache verification fail on a file that is not runtime payload.
    """
    tracked = []
    agents_marketplace = os.path.join(repo_root, ".agents", "plugins", "marketplace.json")
    if os.path.isfile(agents_marketplace):
        tracked.append(".agents/plugins/marketplace.json")
    return tracked


def get_tracked_manifest_files(repo_root):
    """Get all plugin and marketplace manifest files for compatibility."""
    return get_tracked_runtime_manifest_files(repo_root) + get_tracked_source_manifest_files(repo_root)


def get_tracked_symlinks(repo_root, skill_root):
    """Get top-level repo symlinks whose targets point into skill_root.

    Caught by torture-room security-sentinel Finding 3: the backward-compat
    'skill' symlink at the repo root points into skills/repo-forensics/ but
    is outside what get_tracked_files walks, so verify_install cannot detect
    if an attacker (via tarball swap or compromised fork) replaces the
    symlink target with '/tmp/evil/' or any other attacker-controlled path.

    This function enumerates repo-root symlinks whose targets resolve into
    skill_root, so their target strings can be hashed and verified alongside
    regular files.

    Only top-level repo entries are considered (no recursion) because
    forensify's symlink contract is specifically for root-level backward-
    compat glue. Deep symlink farms would require a more sophisticated
    policy and are out of scope for this hardening.
    """
    if not os.path.isdir(repo_root):
        return {}

    skill_root_real = os.path.realpath(skill_root)
    symlinks = {}

    for entry in os.listdir(repo_root):
        full_path = os.path.join(repo_root, entry)
        if not os.path.islink(full_path):
            continue
        target = os.readlink(full_path)
        # Only track symlinks whose resolved target is inside skill_root.
        # Other symlinks are outside our security domain.
        resolved = os.path.realpath(full_path)
        if resolved != skill_root_real and not resolved.startswith(skill_root_real + os.sep):
            continue
        symlinks[entry] = _portable_link(target)

    return symlinks


def _portable_link(target, sep=None):
    """Symlink targets are recorded with '/'. Windows reads them back with
    backslashes, which would look like a retargeted link on every Windows
    install. A backslash is a legal filename character on POSIX, so only
    translate where it is the path separator."""
    sep = os.sep if sep is None else sep
    return target.replace(sep, "/") if sep == "\\" else target


def get_tracked_files(skill_root):
    """Get all files that should be integrity-checked."""
    skip_dirs = {'.git', '__pycache__', '.pytest_cache', 'tests', '.cache', '.ruff_cache'}
    skip_files = {'.DS_Store', '.forensics-baseline.json', '.forensics-iocs.json',
                  'checksums.json', 'checksums.json.sig'}

    # In a git repo, use git ls-files to avoid local-only artifacts. Routed
    # through the hardened runner: ls-files refreshes the index and so honors
    # core.fsmonitor, an exec-capable config key that a hostile tree could set
    # to run code during verification.
    try:
        result = core.run_git_hardened(skill_root, 'ls-files', '--cached', timeout=5)
        if result is not None and result.returncode == 0 and result.stdout.strip():
            git_files = []
            for rel in result.stdout.strip().splitlines():
                if any(rel.startswith(d + '/') or rel.startswith(d + os.sep) for d in skip_dirs):
                    continue
                if os.path.basename(rel) in skip_files:
                    continue
                if rel.endswith(('.pyc', '.pyo')):
                    continue
                fp = os.path.join(skill_root, rel)
                if os.path.islink(fp) or not os.path.isfile(fp):
                    continue
                git_files.append(rel)
            return sorted(git_files)
    except Exception:
        pass

    # Fallback for non-git installs (marketplace/plugin path)
    tracked = []
    for root, dirs, files in os.walk(skill_root, followlinks=False):
        dirs[:] = [d for d in dirs if d not in skip_dirs]
        for f in files:
            if f in skip_files:
                continue
            if f.endswith(('.pyc', '.pyo')):
                continue
            fp = os.path.join(root, f)
            if os.path.islink(fp):
                continue
            # Normalize to forward slashes so checksum keys match the shipped
            # manifest on Windows (os.path.relpath yields backslashes there,
            # which would fail integrity verification during marketplace/plugin
            # installs — the non-git code path). No-op on POSIX.
            rel = os.path.relpath(fp, skill_root).replace(os.sep, '/')
            tracked.append(rel)

    return sorted(tracked)


def generate_checksums(skill_root):
    """Generate checksums.json for skill files + root symlinks + repo hooks."""
    files = get_tracked_files(skill_root)
    checksums = {}
    for rel in files:
        fp = os.path.join(skill_root, rel)
        checksums[rel] = sha256_file(fp)

    repo_root = get_repo_root(skill_root)
    symlinks = get_tracked_symlinks(repo_root, skill_root)

    # Hash repo-root hook scripts that the plugin manifest invokes. These
    # files live outside skill_root but are load-bearing — tampering would
    # compromise the plugin without being detected by the skill-local
    # integrity check.
    hook_files = get_tracked_hook_files(repo_root)
    hook_checksums = {}
    for rel in hook_files:
        fp = os.path.join(repo_root, rel)
        hook_checksums[rel] = sha256_file(fp)

    manifest_files = get_tracked_runtime_manifest_files(repo_root)
    manifest_checksums = {}
    for rel in manifest_files:
        fp = os.path.join(repo_root, rel)
        manifest_checksums[rel] = sha256_file(fp)

    source_manifest_files = get_tracked_source_manifest_files(repo_root)
    source_manifest_checksums = {}
    for rel in source_manifest_files:
        fp = os.path.join(repo_root, rel)
        source_manifest_checksums[rel] = sha256_file(fp)

    output = {
        'version': '2',
        'generator': 'repo-forensics/verify_install',
        'file_count': len(checksums),
        'files': checksums,
    }
    if symlinks:
        output['repo_symlinks'] = symlinks
        output['symlink_count'] = len(symlinks)
    if hook_checksums:
        output['repo_hooks'] = hook_checksums
        output['hook_count'] = len(hook_checksums)
    if manifest_checksums:
        output['repo_manifests'] = manifest_checksums
        output['manifest_count'] = len(manifest_checksums)
    if source_manifest_checksums:
        output['repo_source_manifests'] = source_manifest_checksums
        output['source_manifest_count'] = len(source_manifest_checksums)

    out_path = os.path.join(skill_root, 'checksums.json')
    with open(out_path, 'w', encoding='utf-8') as f:
        json.dump(output, f, indent=2)
        f.write('\n')

    extras = []
    if symlinks:
        extras.append(f"{len(symlinks)} symlinks")
    if hook_checksums:
        extras.append(f"{len(hook_checksums)} hook files")
    if manifest_checksums:
        extras.append(f"{len(manifest_checksums)} manifest files")
    if source_manifest_checksums:
        extras.append(f"{len(source_manifest_checksums)} source manifest files")
    extras_msg = f" + {' + '.join(extras)}" if extras else ""
    print(f"[+] Generated checksums.json: {len(checksums)} files tracked{extras_msg}")
    return out_path


def verify_checksums(skill_root):
    """Verify current files against checksums.json.
    Returns (passed: bool, report: list[str])."""
    checksum_path = os.path.join(skill_root, 'checksums.json')
    if not os.path.exists(checksum_path):
        return False, ["checksums.json not found. Run --generate first or download from release."]

    try:
        with open(checksum_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except (OSError, json.JSONDecodeError) as e:
        return False, [f"Failed to read checksums.json: {e}"]

    expected = data.get('files', {})
    report = []
    tampered = []
    missing = []
    extra = []

    skill_root_real = os.path.realpath(skill_root)

    # Validate file_count matches actual entries
    declared_count = data.get('file_count', -1)
    if declared_count != len(expected):
        report.append(f"  WARNING: file_count mismatch (manifest says {declared_count}, dict has {len(expected)} entries)")

    # Check all expected files
    for rel, expected_hash in expected.items():
        fp = os.path.realpath(os.path.join(skill_root, rel))
        if not fp.startswith(skill_root_real + os.sep):
            tampered.append(rel)
            report.append(f"  REJECTED: {rel} (path traversal attempt)")
            continue
        if not isinstance(expected_hash, str):
            tampered.append(rel)
            report.append(f"  REJECTED: {rel} (invalid hash type in manifest)")
            continue
        actual_hash = sha256_file(fp)
        if actual_hash is None:
            missing.append(rel)
            report.append(f"  UNREADABLE: {rel} (missing or permission denied)")
            continue
        if actual_hash != expected_hash:
            tampered.append(rel)
            report.append(f"  TAMPERED: {rel} (expected {expected_hash[:12]}..., got {actual_hash[:12]}...)")

    # Check for unexpected new files
    current_files = set(get_tracked_files(skill_root))
    expected_files = set(expected.keys())
    new_files = current_files - expected_files
    for rel in sorted(new_files):
        extra.append(rel)
        report.append(f"  NEW FILE: {rel} (not in checksums.json)")

    # Check repo-level hook files against manifest. Load-bearing hook
    # scripts at the repo-root hooks/ directory live outside skill_root but
    # are invoked by plugin manifest at runtime. Tampering would compromise
    # the plugin without being detected by the skill-local check.
    expected_hooks = data.get('repo_hooks', {})
    repo_root = get_repo_root(skill_root)
    repo_root_real = os.path.realpath(repo_root)
    plugin_cache_layout = is_plugin_cache_layout(repo_root)
    tampered_hooks = []
    missing_hooks = []
    for rel, expected_hash in expected_hooks.items():
        fp = os.path.realpath(os.path.join(repo_root, rel))
        if not fp.startswith(repo_root_real + os.sep):
            tampered_hooks.append(rel)
            report.append(f"  HOOK REJECTED: {rel} (path traversal attempt)")
            continue
        actual_hash = sha256_file(fp)
        if actual_hash is None:
            missing_hooks.append(rel)
            report.append(f"  HOOK MISSING: {rel} (not found on disk)")
            continue
        if actual_hash != expected_hash:
            tampered_hooks.append(rel)
            report.append(f"  HOOK TAMPERED: {rel} (expected {expected_hash[:12]}..., got {actual_hash[:12]}...)")

    # Detect NEW untracked hook files. #41 landed the enumeration half of the
    # "hooks/ subdirectories escaped the registry" fix (get_tracked_hook_files
    # now recurses), but not the verification half: a wrapper planted under
    # hooks/ or hooks/cursor/ would otherwise pass audit as VERIFIED because
    # every *claimed* file still matches. An audit that says CLEAN while a
    # malicious wrapper sits on disk is the exact failure the registry exists to
    # prevent. Folded into all_extra so the summary drops from VERIFIED to
    # PARTIAL (same posture as new skill files / symlinks).
    extra_hooks = []
    current_hook_files = set(get_tracked_hook_files(repo_root))
    for rel in sorted(current_hook_files - set(expected_hooks)):
        extra_hooks.append(rel)
        report.append(f"  NEW HOOK FILE: {rel} (not in checksums.json)")

    # Check repo-level symlinks against manifest. Caught by torture-room
    # security-sentinel Finding 3 — the backward-compat skill symlink at
    # repo root points into skills/repo-forensics/, but it lives outside
    # skill_root and would otherwise be invisible to verification.
    expected_symlinks = data.get('repo_symlinks', {})
    current_symlinks = get_tracked_symlinks(repo_root, skill_root)

    tampered_symlinks = []
    missing_symlinks = []
    extra_symlinks = []
    skipped_symlinks = []

    for name, expected_target in expected_symlinks.items():
        if name not in current_symlinks:
            if plugin_cache_layout:
                skipped_symlinks.append(name)
                report.append(
                    f"  SYMLINK SKIPPED: {name} "
                    "(agent plugin cache layout does not preserve root compatibility symlinks)"
                )
                continue
            missing_symlinks.append(name)
            report.append(f"  SYMLINK MISSING: {name} (declared in manifest, not found on disk)")
            continue
        if current_symlinks[name] != expected_target:
            tampered_symlinks.append(name)
            report.append(
                f"  SYMLINK TAMPERED: {name} "
                f"(expected target '{expected_target}', got '{current_symlinks[name]}')"
            )

    for name in sorted(set(current_symlinks) - set(expected_symlinks)):
        extra_symlinks.append(name)
        report.append(f"  NEW SYMLINK: {name} -> {current_symlinks[name]} (not in checksums.json)")

    # Check agent plugin manifest files
    expected_manifests_raw = data.get('repo_manifests', {})
    expected_manifests = {}
    compat_source_manifests = {}
    for rel, expected_hash in expected_manifests_raw.items():
        if rel in SOURCE_ONLY_MANIFEST_FILES:
            compat_source_manifests[rel] = expected_hash
        else:
            expected_manifests[rel] = expected_hash
    expected_source_manifests = {
        **compat_source_manifests,
        **data.get('repo_source_manifests', {}),
    }
    tampered_manifests = []
    missing_manifests = []
    for rel, expected_hash in expected_manifests.items():
        fp = os.path.realpath(os.path.join(repo_root, rel))
        if not fp.startswith(repo_root_real + os.sep):
            tampered_manifests.append(rel)
            report.append(f"  MANIFEST REJECTED: {rel} (path traversal attempt)")
            continue
        actual_hash = sha256_file(fp)
        if actual_hash is None:
            missing_manifests.append(rel)
            report.append(f"  MANIFEST MISSING: {rel} (not found on disk)")
            continue
        if actual_hash != expected_hash:
            tampered_manifests.append(rel)
            report.append(f"  MANIFEST TAMPERED: {rel} (expected {expected_hash[:12]}..., got {actual_hash[:12]}...)")

    tampered_source_manifests = []
    missing_source_manifests = []
    skipped_source_manifests = []
    for rel, expected_hash in expected_source_manifests.items():
        fp = os.path.realpath(os.path.join(repo_root, rel))
        if not fp.startswith(repo_root_real + os.sep):
            tampered_source_manifests.append(rel)
            report.append(f"  SOURCE MANIFEST REJECTED: {rel} (path traversal attempt)")
            continue
        actual_hash = sha256_file(fp)
        if actual_hash is None:
            if plugin_cache_layout or is_marketplace_mirror_layout(repo_root):
                skipped_source_manifests.append(rel)
                report.append(
                    f"  SOURCE MANIFEST SKIPPED: {rel} "
                    "(plugin package layout does not include source marketplace catalogs)"
                )
                continue
            missing_source_manifests.append(rel)
            report.append(f"  SOURCE MANIFEST MISSING: {rel} (not found on disk)")
            continue
        if actual_hash != expected_hash:
            tampered_source_manifests.append(rel)
            report.append(
                f"  SOURCE MANIFEST TAMPERED: {rel} "
                f"(expected {expected_hash[:12]}..., got {actual_hash[:12]}...)"
            )

    # Summary
    all_tampered = (
        len(tampered) + len(tampered_symlinks) + len(tampered_hooks) +
        len(tampered_manifests) + len(tampered_source_manifests)
    )
    all_missing = (
        len(missing) + len(missing_symlinks) + len(missing_hooks) +
        len(missing_manifests) + len(missing_source_manifests)
    )
    all_extra = len(extra) + len(extra_symlinks) + len(extra_hooks)
    passed = all_tampered == 0 and all_missing == 0
    total_tracked = (
        len(expected) + len(expected_symlinks) + len(expected_hooks) +
        len(expected_manifests) + len(expected_source_manifests)
    )
    if passed and all_extra == 0:
        extras_note = []
        if expected_symlinks:
            checked_symlinks = len(expected_symlinks) - len(skipped_symlinks)
            if checked_symlinks:
                extras_note.append(f"{checked_symlinks} symlinks")
            if skipped_symlinks:
                extras_note.append(f"{len(skipped_symlinks)} cache-optional symlinks skipped")
        if expected_hooks:
            extras_note.append(f"{len(expected_hooks)} hooks")
        if expected_manifests:
            extras_note.append(f"{len(expected_manifests)} manifests")
        if expected_source_manifests:
            checked_source = len(expected_source_manifests) - len(skipped_source_manifests)
            if checked_source:
                extras_note.append(f"{checked_source} source manifests")
            if skipped_source_manifests:
                extras_note.append(f"{len(skipped_source_manifests)} source manifests skipped")
        extras_str = f" (+{', '.join(extras_note)})" if extras_note else ""
        report.insert(0, f"[+] VERIFIED: All {len(expected)} files{extras_str} match checksums.json (v{data.get('version', '?')})")
    elif passed:
        report.insert(0, f"[~] PARTIAL: All {total_tracked} tracked entries OK, but {all_extra} untracked entry/entries found")
    else:
        report.insert(0, f"[!] FAILED: {all_tampered} tampered, {all_missing} missing out of {total_tracked} tracked entries")

    return passed, report


def verify_manifest_signature(skill_root):
    """Check that checksums.json matches its Ed25519 signature.

    ``--verify`` compares files *against* checksums.json; this checks that
    checksums.json is itself signed by the pinned release key, so a regenerated
    manifest that was never re-signed is caught. Returns (passed, message).
    """
    import importlib.util
    controller = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                              "refresh_controller.py")
    if not os.path.isfile(controller):
        return False, "refresh_controller.py not found; cannot verify signature"
    spec = importlib.util.spec_from_file_location("_rf_refresh_controller", controller)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)

    manifest = os.path.join(skill_root, "checksums.json")
    signature = os.path.join(skill_root, "checksums.json.sig")
    for path in (manifest, signature):
        if not os.path.isfile(path):
            return False, "missing {}".format(os.path.basename(path))
    with open(manifest, "rb") as handle:
        manifest_raw = handle.read()
    with open(signature, "rb") as handle:
        signature_raw = handle.read()
    verifier = module._trusted_ed25519()
    if not verifier.verify(signature_raw, manifest_raw,
                           bytes.fromhex(module.CHECKSUMS_PUBKEY_HEX)):
        return False, "checksums.json signature does not verify against the pinned release key"
    return True, "checksums.json signature verified"


def main():
    import argparse
    parser = argparse.ArgumentParser(description="repo-forensics Installation Verifier")
    parser.add_argument('--generate', action='store_true', help="Generate checksums.json (release-time)")
    parser.add_argument('--verify', action='store_true', help="Verify installation integrity")
    parser.add_argument('--verify-signature', action='store_true',
                        dest='verify_signature',
                        help="Verify checksums.json is signed by the pinned release key")
    args = parser.parse_args()

    skill_root = get_skill_root()

    if args.generate:
        generate_checksums(skill_root)
        sys.exit(0)

    if args.verify_signature:
        passed, message = verify_manifest_signature(skill_root)
        print("{} {}".format("[+]" if passed else "[!]", message))
        sys.exit(0 if passed else 1)

    if args.verify:
        passed, report = verify_checksums(skill_root)
        for line in report:
            print(line)
        sys.exit(0 if passed else 1)

    parser.print_help()


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