Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

18.7 KB
Raw Blame
"""
Pillar-1 Evaluation: MITRE ATT&CK Tactic — Substrate Self-Consistency Gate
==========================================================================
This test gates the substrate's tactic extractor against the synthetic
incident scenarios in `eval_data/synthetic_incidents.json` (200 cases
spanning 55 distinct templates as of v6.1).

It runs OFFLINE (no LLM calls, no DB) using a keyword-based tactic
extractor over the same synthetic descriptions that were generated to
contain those keywords. As a result, the resulting accuracy / precision /
recall / F1 numbers are a SUBSTRATE SELF-CONSISTENCY GATE — they detect
regressions in the extractor or the dataset relative to each other, NOT a
real LLM-agent tactic-detection accuracy score on adversarial / blind data.

Two regression floors are enforced:

* per-case  accuracy  ≥ 80% (200 cases — the headline figure)
* per-template accuracy ≥ 80% (55 templates, equally weighted) — exists
  because the substrate has no per-host code paths, so cycling templates
  3-4× would otherwise let a single broken template hide behind the
  averages (≈ 0.5% per-case dilution vs ≈ 1.8% per-template signal). When a
  template breaks, the per-template number drops sharply and the
  `failing_templates` list in the report names it directly.

See `apps/docs/docs/benchmark.md` for what each suite actually measures
and how it differs from a third-party leaderboard score.

Run:
    pytest services/agents/tests/test_mitre_accuracy.py -v
    # or via the public eval harness (writes a JSON report; dataset size is
    # fixed by eval_data/synthetic_incidents.json, so there is no --count):
    python scripts/run_evals.py --out eval_report.json
"""

from __future__ import annotations

import json
import sys
import unittest
from pathlib import Path
from typing import Any

# ---------------------------------------------------------------------------
# Load synthetic incidents from JSON dataset
# (deterministic — generated by scripts/generate_eval_incidents.py)
# ---------------------------------------------------------------------------

_TESTS_DIR = Path(__file__).parent
_DATASET_PATH = _TESTS_DIR / "eval_data" / "synthetic_incidents.json"


def _load_dataset() -> list[dict[str, Any]]:
    if not _DATASET_PATH.exists():
        raise FileNotFoundError(
            f"Synthetic incidents dataset missing at {_DATASET_PATH}. Run `python3 scripts/generate_eval_incidents.py` to regenerate."
        )
    with _DATASET_PATH.open() as f:
        return json.load(f)


SYNTHETIC_INCIDENTS_DATA: list[dict[str, Any]] = _load_dataset()


# Backwards-compatible 4-tuple list for any external callers
SYNTHETIC_INCIDENTS: list[tuple[str, list[str], list[str], str]] = [
    (
        inc["title"],
        inc["expected_tactics"],
        inc["expected_techniques"],
        inc["description"],
    )
    for inc in SYNTHETIC_INCIDENTS_DATA
]


# ATT&CK tactic ID → canonical name
_TACTIC_NAMES: dict[str, str] = {
    "TA0001": "Initial Access",
    "TA0002": "Execution",
    "TA0003": "Persistence",
    "TA0004": "Privilege Escalation",
    "TA0005": "Defense Evasion",
    "TA0006": "Credential Access",
    "TA0007": "Discovery",
    "TA0008": "Lateral Movement",
    "TA0009": "Collection",
    "TA0010": "Exfiltration",
    "TA0011": "Command and Control",
    "TA0040": "Impact",
}


# ---------------------------------------------------------------------------
# Keyword-based MITRE tactic extractor (offline, no LLM)
# ---------------------------------------------------------------------------

_TACTIC_KEYWORDS: dict[str, list[str]] = {
    "TA0001": [
        "initial access",
        "phishing",
        "spear-phish",
        "exploit",
        "watering hole",
        "supply chain",
        "valid account",
        "external remote service",
        "drive-by",
        "usb",
        "spear",
        "oauth consent",
        "social engineering",
        "social-engineering",
        "vpn login",
        "new geography",
        "compromised npm",
        "container image",
        "wire transfer",
    ],
    "TA0002": [
        "execution",
        "powershell",
        "cmd.exe",
        "script",
        "macro",
        "python",
        "node",
        "certutil",
        "wmi",
        "wmic",
        "mshta",
        "process hollow",
        "process create",
        "npm",
        "post-install",
        "container with",
        "docker run",
        "javascript",
        "stage-2 payload",
        "vba",
        "browser exploitation",
        "drive-by",
    ],
    "TA0003": [
        "persistence",
        "registry run",
        "scheduled task",
        "startup",
        "service",
        "implant",
        "backdoor",
        "rootkit",
        "firmware",
        "uefi",
        "cron",
        "wmi event",
        "permanent wmi",
        "office add-in",
        "vsto",
        "outlook startup",
    ],
    "TA0004": [
        "privilege escalation",
        "escalation",
        "escalate",
        "container escape",
        "privileged pod",
        "bypass",
        "elevation",
        "sudo",
        "uac bypass",
        "uac",
        "fodhelper",
        "suid",
        "metadata service",
    ],
    "TA0005": [
        "defense evasion",
        "obfuscat",
        "fileless",
        "memory-only",
        "memory only",
        "hollowing",
        "side-load",
        "dll",
        "certutil",
        "masquerad",
        "encode",
        "pack",
        "log cleared",
        "wevtutil",
        "journalctl",
        "vacuum",
        "indicator removal",
        "tampering",
        "stop defender",
        "stop crowdstrike",
        "stop sysmon",
        "secure boot",
    ],
    "TA0006": [
        "credential",
        "brute force",
        "brute-force",
        "kerberoast",
        "dcsync",
        "lsass",
        "minidump",
        "dump",
        "harvest",
        "password reset",
        "password spray",
        "credential spray",
        "saml",
        "oauth",
        "ntlm",
        "mimikatz",
        "pat",
        "personal access token",
        "refresh token",
        "imds",
        "session token",
        "stolen session",
        "tgs",
    ],
    "TA0007": [
        "discovery",
        "enumerat",
        "scan",
        "account discovery",
        "network share",
        "recon",
        "replication",
        "ldap",
        "bloodhound",
        "smb share",
        "share enum",
        "system info",
    ],
    "TA0008": [
        "lateral movement",
        "lateral",
        "rdp",
        "pass-the-hash",
        "pass the hash",
        "remote service",
        "pivoting",
        "ssh",
        "smb scan",
        "wmic /node",
        "wmi remote",
    ],
    "TA0009": [
        "collection",
        "data from local",
        "screenshot",
        "keylog",
        "clipboard",
        "bulk download",
        "pii",
        "customer record",
        "mailbox export",
        "pst",
        "private repo",
        "private repos",
    ],
    "TA0010": [
        "exfiltrat",
        "c2 channel",
        "cloud storage",
        "dns tunnel",
        "ftp",
        "upload",
        "egress",
        "google drive",
        "drive upload",
        "personal drive",
        "transfer to",
        "s3 bucket",
        "s3://",
        "data egress",
    ],
    "TA0011": [
        "command and control",
        "c2",
        "beacon",
        "c&c",
        "dga",
        "domain generation",
        "dns query",
        "covert channel",
        "cobalt strike",
        "https beacon",
        "ja3",
    ],
    "TA0040": [
        "impact",
        "ransom",
        "encrypt",
        "wipe",
        "destroy",
        "disrupt",
        "defacement",
        "miner",
        "cryptomine",
        "xmrig",
        "ddos",
        "syn flood",
        "wire transfer",
        "$250",
        "bec",
    ],
}


def extract_tactics_from_text(text: str) -> set[str]:
    """Return set of ATT&CK tactic IDs inferred from keyword matching."""
    low = text.lower()
    found: set[str] = set()
    for tactic_id, kws in _TACTIC_KEYWORDS.items():
        if any(kw in low for kw in kws):
            found.add(tactic_id)
    return found


# ---------------------------------------------------------------------------
# Accuracy evaluation
# ---------------------------------------------------------------------------


class MitreAccuracyResult:
    def __init__(self) -> None:
        self.total = 0
        self.correct = 0
        self.precision_sum = 0.0
        self.recall_sum = 0.0
        self.details: list[dict[str, Any]] = []

    @property
    def accuracy(self) -> float:
        return self.correct / self.total if self.total else 0.0

    @property
    def precision(self) -> float:
        return self.precision_sum / self.total if self.total else 0.0

    @property
    def recall(self) -> float:
        return self.recall_sum / self.total if self.total else 0.0

    @property
    def f1(self) -> float:
        p, r = self.precision, self.recall
        return (2 * p * r / (p + r)) if (p + r) > 0 else 0.0

    def per_template_summary(self) -> dict[str, Any]:
        """Aggregate accuracy by `template_id` so duplicate scenarios cannot
        average a broken template into oblivion.

        Returns a dict with:
          * `templates`: per-template accuracy (sorted, worst first)
          * `template_count`: number of distinct templates
          * `template_macro_accuracy`: equally weighted across templates
          * `failing_templates`: templates with <80% accuracy
        """
        buckets: dict[str, dict[str, Any]] = {}
        for row in self.details:
            tpl = row.get("template_id") or "unknown"
            bucket = buckets.setdefault(tpl, {"correct": 0, "total": 0})
            bucket["total"] += 1
            if row["correct"]:
                bucket["correct"] += 1

        templates: list[dict[str, Any]] = []
        for tpl, b in buckets.items():
            acc = b["correct"] / b["total"] if b["total"] else 0.0
            templates.append(
                {
                    "template_id": tpl,
                    "cases": b["total"],
                    "correct": b["correct"],
                    "accuracy": round(acc, 4),
                }
            )
        templates.sort(key=lambda t: (t["accuracy"], -t["cases"]))

        macro = sum(t["accuracy"] for t in templates) / len(templates) if templates else 0.0
        failing = [t for t in templates if t["accuracy"] < 0.80]
        return {
            "templates": templates,
            "template_count": len(templates),
            "template_macro_accuracy": round(macro, 4),
            "failing_templates": failing,
        }

    def to_json(self) -> str:
        return json.dumps(
            {
                "total": self.total,
                "correct": self.correct,
                "accuracy": round(self.accuracy, 4),
                "accuracy_pct": f"{self.accuracy * 100:.1f}%",
                "precision": round(self.precision, 4),
                "recall": round(self.recall, 4),
                "f1": round(self.f1, 4),
                "per_template": self.per_template_summary(),
                "details": self.details,
            },
            indent=2,
        )


def evaluate_mitre_accuracy(threshold: float = 0.80) -> MitreAccuracyResult:
    """
    For each synthetic incident, check whether the keyword extractor
    (proxy for LLM output) identifies ≥1 of the expected MITRE tactics.

    A case is considered "correct" if the predicted tactic set has at
    least one overlap with the expected tactic set. Precision, recall,
    and F1 are also reported as per-case averages over the expected
    tactic sets.
    """
    result = MitreAccuracyResult()

    for inc in SYNTHETIC_INCIDENTS_DATA:
        result.total += 1
        title = inc["title"]
        description = inc["description"]
        expected_tactics = inc["expected_tactics"]
        combined_text = f"{title}\n{description}"
        predicted = extract_tactics_from_text(combined_text)
        expected_set = set(expected_tactics)
        overlap = predicted & expected_set
        correct = len(overlap) > 0
        if correct:
            result.correct += 1

        precision = len(overlap) / len(predicted) if predicted else 0.0
        recall = len(overlap) / len(expected_set) if expected_set else 0.0
        result.precision_sum += precision
        result.recall_sum += recall

        result.details.append(
            {
                "incident_id": inc.get("id"),
                "template_id": inc.get("template_id"),
                "template_index": inc.get("template_index"),
                "incident": title[:80],
                "expected": sorted(expected_set),
                "predicted": sorted(predicted),
                "overlap": sorted(overlap),
                "correct": correct,
                "precision": round(precision, 3),
                "recall": round(recall, 3),
            }
        )

    return result


# ---------------------------------------------------------------------------
# pytest tests
# ---------------------------------------------------------------------------


class TestMitreAccuracy(unittest.TestCase):
    """Offline MITRE tactic accuracy evaluation across the synthetic dataset."""

    def test_accuracy_above_threshold(self) -> None:
        result = evaluate_mitre_accuracy()
        print(
            f"\n[eval] MITRE accuracy: {result.correct}/{result.total} = "
            f"{result.accuracy * 100:.1f}% (P={result.precision:.2f} "
            f"R={result.recall:.2f} F1={result.f1:.2f})"
        )
        self.assertGreaterEqual(
            result.accuracy,
            0.80,
            f"MITRE tactic accuracy {result.accuracy:.1%} is below the 80% threshold.\n" + result.to_json()[:4000],
        )

    def test_dataset_minimum_size(self) -> None:
        """The eval dataset must contain at least 200 incidents (Phase-1C target)."""
        self.assertGreaterEqual(
            len(SYNTHETIC_INCIDENTS_DATA),
            200,
            f"Eval dataset has only {len(SYNTHETIC_INCIDENTS_DATA)} incidents; need ≥200 for Phase-1C.",
        )

    def test_each_incident_has_expected_tactics(self) -> None:
        for inc in SYNTHETIC_INCIDENTS_DATA:
            title = inc["title"]
            tactic_ids = inc["expected_tactics"]
            self.assertGreater(
                len(tactic_ids),
                0,
                f"Incident '{title[:60]}' has no expected tactic IDs.",
            )
            for t in tactic_ids:
                self.assertIn(
                    t,
                    _TACTIC_NAMES,
                    f"Unknown tactic ID '{t}' in incident '{title[:60]}'.",
                )

    def test_no_duplicate_incident_ids(self) -> None:
        ids = [inc["id"] for inc in SYNTHETIC_INCIDENTS_DATA]
        self.assertEqual(len(ids), len(set(ids)), "Duplicate incident ids detected.")

    def test_severity_values_valid(self) -> None:
        valid = {"critical", "high", "medium", "low"}
        for inc in SYNTHETIC_INCIDENTS_DATA:
            self.assertIn(inc["severity"], valid, f"Bad severity: {inc['severity']}")

    def test_response_class_values_valid(self) -> None:
        valid = {
            "isolate_host",
            "disable_account",
            "block_indicator",
            "rollback_change",
            "escalate",
            "monitor",
        }
        for inc in SYNTHETIC_INCIDENTS_DATA:
            self.assertIn(
                inc["response_class"],
                valid,
                f"Bad response_class: {inc['response_class']}",
            )

    def test_tactic_coverage(self) -> None:
        """Dataset should cover at least 10 of 12 tracked tactics."""
        all_tactics: set[str] = set()
        for inc in SYNTHETIC_INCIDENTS_DATA:
            all_tactics.update(inc["expected_tactics"])
        self.assertGreaterEqual(
            len(all_tactics & set(_TACTIC_NAMES)),
            10,
            f"Only {len(all_tactics)} tactics covered: {sorted(all_tactics)}",
        )

    def test_per_template_accuracy(self) -> None:
        """Macro-average accuracy across distinct `template_id`s must be ≥80%.

        This is the regression-signal gate: with 200 cases drawn from 55
        templates, a single broken template moves per-case accuracy by only
        ~0.5% (3-4 / 200) but moves per-template accuracy by ~1.8% (1 / 55).
        Equal-weighting templates ensures the substrate cannot regress on a
        whole class of behavior and hide behind the duplicates.
        """
        result = evaluate_mitre_accuracy()
        summary = result.per_template_summary()
        print(
            f"\n[eval] MITRE per-template macro accuracy: "
            f"{summary['template_macro_accuracy'] * 100:.1f}% "
            f"({summary['template_count']} distinct templates, "
            f"{len(summary['failing_templates'])} below 80%)"
        )
        self.assertGreaterEqual(
            summary["template_count"],
            50,
            f"Only {summary['template_count']} distinct templates in dataset; expected ≥50.",
        )
        self.assertGreaterEqual(
            summary["template_macro_accuracy"],
            0.80,
            f"Per-template MITRE accuracy below 80%.\nFailing templates: {summary['failing_templates']}",
        )

    def test_each_incident_has_template_id(self) -> None:
        """Every incident must carry the `template_id` it was generated from."""
        for inc in SYNTHETIC_INCIDENTS_DATA:
            self.assertIn("template_id", inc, f"Missing template_id on {inc.get('id')}")
            self.assertTrue(
                isinstance(inc["template_id"], str) and inc["template_id"],
                f"Empty template_id on {inc.get('id')}",
            )
            self.assertIn(
                "template_index",
                inc,
                f"Missing template_index on {inc.get('id')}",
            )

    def test_template_distribution_balanced(self) -> None:
        """No single template may account for >5% of the dataset.

        Keeps the per-case headline number from being dominated by any one
        template if the cycle changes.
        """
        counts: dict[str, int] = {}
        for inc in SYNTHETIC_INCIDENTS_DATA:
            tpl = inc["template_id"]
            counts[tpl] = counts.get(tpl, 0) + 1
        worst = max(counts.items(), key=lambda kv: kv[1])
        self.assertLessEqual(
            worst[1],
            max(4, int(len(SYNTHETIC_INCIDENTS_DATA) * 0.05)),
            f"Template '{worst[0]}' appears {worst[1]} times (>{int(len(SYNTHETIC_INCIDENTS_DATA) * 0.05)} = 5% of dataset).",
        )


if __name__ == "__main__":
    # Also allow running standalone to print a detailed report
    res = evaluate_mitre_accuracy()
    print(res.to_json())
    passed = res.accuracy >= 0.80
    print(f"\n{'PASS' if passed else 'FAIL'}: {res.accuracy * 100:.1f}% accuracy (threshold: 80%)")
    sys.exit(0 if passed else 1)