Skip to content

armgit / ARES

Public Imported from GitHub
0

ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.

40.7 KB
Raw Blame
"""
opsec.coverage_predictor - Real-Time Detection Probability Scoring

Analyzes all actions performed in a campaign and predicts how likely
the engagement has been detected, based on:

  - IOCs generated by each MITRE technique used
  - Sysmon/Windows Event IDs that each action would trigger
  - Time-of-day detection correlation patterns
  - OPSEC level of each module run
  - Known defender playbook mappings (MITRE D3FEND)

Output:
  - Overall detection probability score (0-100%)
  - Per-action risk breakdown with specific Event IDs
  - Recommended wait time before next lateral movement
  - Stealth improvement recommendations

MITRE: T1592 (Gather Victim Host Information - defensive analysis)
OPSEC: LOCAL (no network calls - pure data analysis)

Note: before_request() intentionally not called - this module performs
offline analysis of campaign data only. No network calls.
"""
from __future__ import annotations

import asyncio
import time
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any

from ares.core.campaign import Severity
from ares.core.logger import audit, get_logger
from ares.core.tracing import trace_module
from ares.modules.base import BaseModule, ModuleResult, OpsecLevel
from ares.modules.params import CoveragePredictorParams
from ares.sdk import (
    CircuitBreaker,
    EvidenceRecord,
    ProcessPermission,
    module_contract,
)

if TYPE_CHECKING:
    pass

logger = get_logger("ares.modules.opsec.coverage_predictor")

# ── Detection event database: MITRE technique → Windows/Linux event IDs ──────
# Each entry: (event_source, event_id, detection_probability_0_to_1, description)

_TECHNIQUE_DETECTION_MAP: dict[str, list[tuple[str, str, float, str]]] = {
    # Active Directory
    "T1558.003": [("Sysmon", "18", 0.75, "Kerberos TGS request - potential kerberoasting"),
                  ("Security", "4769", 0.80, "Kerberos Service Ticket Operation - RC4 encryption flag")],
    "T1558.004": [("Security", "4768", 0.70, "Kerberos Auth Ticket request - potential ASREPRoasting")],
    "T1003.006": [("Security", "4662", 0.95, "DCSync - DS-Replication-Get-Changes-All permission used"),
                  ("Security", "4929", 0.90, "AD replica source naming context removed")],
    "T1649":     [("Security", "4886", 0.60, "Certificate request - potential ADCS abuse"),
                  ("Security", "4887", 0.65, "Certificate issued - track enrollment patterns")],
    "T1187":     [("Security", "4624", 0.50, "Network logon - NTLM coercion incoming auth"),
                  ("Sysmon",   "3",    0.40, "Network connection - SMB to attacker IP")],
    "T1552.004": [("Security", "4661", 0.55, "SAM handle request - LAPS read attempt")],

    # Credential
    "T1003.001": [("Sysmon",   "10",   0.99, "LSASS process access - lsass_dump"),
                  ("Security", "4656", 0.90, "LSASS handle request with PROCESS_VM_READ"),
                  ("Defender", "ASR",  0.95, "Attack Surface Reduction rule: Block credential stealing from LSASS")],
    "T1003.002": [("Security", "4657", 0.80, "Registry value modification - SAM hive access"),
                  ("Sysmon",   "13",   0.75, "Registry value set - LSA secrets read")],
    "T1555.004": [("Sysmon",   "11",   0.50, "File creation - DPAPI blob decryption temp file"),
                  ("Security", "4663", 0.55, "File access - Chrome Login Data")],
    "T1110.003": [("Security", "4625", 0.85, "Account failed logon - potential spray pattern"),
                  ("Security", "4771", 0.80, "Kerberos pre-auth failed - spray via Kerberos")],
    "T1550.002": [("Security", "4624", 0.70, "Network logon type 3 - PTH pattern (no Kerberos TGT)"),
                  ("Security", "4648", 0.75, "Explicit credential logon - PTH indicator")],

    # Lateral Movement
    "T1569.002": [("System",  "7045", 0.90, "New service installed - PsExec service"),
                  ("Sysmon",  "1",    0.85, "Process creation - PSEXESVC.exe"),
                  ("Security","4697", 0.90, "Service installed in system")],
    "T1047":     [("Sysmon",  "20",   0.80, "WMI remote activity"),
                  ("Security","4688", 0.60, "Process creation - WMI provider host")],
    "T1021.006": [("Security","4624", 0.55, "Network logon - WinRM (port 5985/5986)"),
                  ("Microsoft-Windows-WinRM", "91", 0.60, "WSMan session created")],
    "T1021.001": [("Security","4624", 0.60, "Interactive/RemoteInteractive logon - RDP"),
                  ("Security","4778", 0.65, "Session reconnected to Window Station - RDP")],
    "T1505.001": [("SQLServer","18456",0.70, "MSSQL login failed - potential brute/spray"),
                  ("SQLServer","15457",0.85, "xp_cmdshell enabled - high-confidence IOC")],
    "T1021.003": [("Sysmon",  "3",    0.65, "DCOM network connection - WBEM/MMC"),
                  ("Security","4648", 0.55, "Explicit credential use - DCOM auth")],

    # Persistence
    "T1053.005": [("Security", "4698", 0.85, "Scheduled task created"),
                  ("Sysmon",   "1",    0.80, "Process creation - schtasks.exe")],
    "T1546.003": [("WMI",  "5860",  0.90, "WMI permanent subscription created"),
                  ("Sysmon", "19",   0.95, "WMI event filter activity")],
    "T1547.001": [("Sysmon", "13",   0.70, "Registry run key modification"),
                  ("Security","4657", 0.65, "Registry value set - HKCU/Run")],

    # Exfil
    "T1039":     [("Sysmon", "11",   0.40, "File creation - SMB share staging"),
                  ("Security","5140", 0.55, "Network share access - enumeration pattern")],
    "T1552":     [("Sysmon",  "1",   0.50, "Process creation - grep/findstr on credential files")],

    # Cloud
    "T1528":     [("AzureAD","Sign-in",0.60,"Azure AD OAuth token theft attempt")],
    "T1078.004": [("AzureAD","Sign-in",0.55,"Impossible travel or new IP for service principal")],
}

# Detection probability modifier by OPSEC level
_OPSEC_MODIFIERS = {
    "local":       0.05,   # LOCAL - no network, very low detection risk
    "silent":      0.10,   # SILENT - highly obfuscated
    "low":         0.25,   # LOW - passive enumeration
    "medium":      0.55,   # MEDIUM - active but targeted
    "high_noise":  0.90,   # HIGH_NOISE - loud, likely detected
    "stealth":     0.15,   # STEALTH profile modifier
    "normal":      0.55,
    "aggressive":  0.85,
}

# Wait-time recommendations based on score (hours)
_WAIT_RECOMMENDATIONS = [
    (0.0,  0.20, 0,   "Continue - detection risk minimal"),
    (0.20, 0.40, 2,   "Low risk - optional 2hr pause before next lateral move"),
    (0.40, 0.60, 12,  "Moderate risk - recommended 12hr pause, switch technique"),
    (0.60, 0.75, 24,  "High risk - 24hr pause, consider abandoning noisy artifacts"),
    (0.75, 0.90, 72,  "Very high risk - 72hr pause or fresh compromise recommended"),
    (0.90, 1.01, 168, "Critical - assume detected. Full OPSEC reset required (7 days)"),
]



# ── Geographic SOC shift model ────────────────────────────────────────────────

import datetime

_SOC_COVERAGE: dict[str, dict] = {
    ".com":        {"tz": "US/Eastern",       "shift": (8, 18),  "weekend_factor": 0.30},
    ".org":        {"tz": "US/Eastern",       "shift": (8, 18),  "weekend_factor": 0.20},
    ".gov":        {"tz": "US/Eastern",       "shift": (8, 17),  "weekend_factor": 0.05},
    ".mil":        {"tz": "US/Eastern",       "shift": (0, 24),  "weekend_factor": 0.90},
    ".co.uk":      {"tz": "Europe/London",    "shift": (7, 19),  "weekend_factor": 0.20},
    ".de":         {"tz": "Europe/Berlin",    "shift": (7, 18),  "weekend_factor": 0.10},
    ".eu":         {"tz": "Europe/Berlin",    "shift": (7, 18),  "weekend_factor": 0.10},
    ".fr":         {"tz": "Europe/Paris",     "shift": (8, 19),  "weekend_factor": 0.10},
    ".au":         {"tz": "Australia/Sydney", "shift": (8, 17),  "weekend_factor": 0.20},
    ".nz":         {"tz": "Pacific/Auckland", "shift": (8, 17),  "weekend_factor": 0.20},
    ".jp":         {"tz": "Asia/Tokyo",       "shift": (9, 18),  "weekend_factor": 0.10},
    ".sg":         {"tz": "Asia/Singapore",   "shift": (8, 18),  "weekend_factor": 0.25},
    "financial":   {"tz": "US/Eastern",       "shift": (7, 21),  "weekend_factor": 0.70},
    "healthcare":  {"tz": "US/Eastern",       "shift": (0, 24),  "weekend_factor": 0.80},
    "default":     {"tz": "UTC",              "shift": (8, 18),  "weekend_factor": 0.30},
}


def _compute_soc_activity_factor(
    target_domain: str = "",
    target_type: str = "default",
    now_utc: datetime.datetime | None = None,
) -> dict:
    """
    Compute current SOC analyst activity factor (0.0-1.0) based on
    target organization's likely timezone and shift hours.

    Returns dict with factor, optimal_window, and recommendation.
    """
    if now_utc is None:
        now_utc = datetime.datetime.utcnow()

    # Determine SOC profile
    profile = _SOC_COVERAGE.get(target_type, _SOC_COVERAGE["default"])
    if target_domain:
        for tld, prof in _SOC_COVERAGE.items():
            if target_domain.endswith(tld):
                profile = prof
                break

    shift_start, shift_end = profile["shift"]
    weekend_factor = profile["weekend_factor"]
    is_weekend = now_utc.weekday() >= 5  # 5=Sat, 6=Sun

    # Estimate current local hour (approximate without pytz)
    tz_offsets = {
        "US/Eastern": -5, "US/Pacific": -8, "US/Central": -6,
        "Europe/London": 0, "Europe/Berlin": 1, "Europe/Paris": 1,
        "Australia/Sydney": 10, "Pacific/Auckland": 12,
        "Asia/Tokyo": 9, "Asia/Singapore": 8, "UTC": 0,
    }
    offset = tz_offsets.get(profile["tz"], 0)
    local_hour = (now_utc.hour + offset) % 24

    # Activity factor
    if is_weekend:
        base_factor = weekend_factor
    elif shift_start <= local_hour < shift_end:
        # Peak hours: higher in middle of shift
        hours_into_shift = local_hour - shift_start
        shift_len = shift_end - shift_start
        # Bell curve approximation
        normalized = hours_into_shift / shift_len
        base_factor = 1.0 - 4 * (normalized - 0.5) ** 2  # peaks at 50%
        base_factor = max(base_factor, 0.5)  # minimum 50% during shift
    else:
        base_factor = 0.15  # off-hours

    # Optimal attack window: 02:00-05:00 local time (dead zone)
    optimal_local_hours = []
    for h in range(24):
        target_local = (now_utc.hour + offset + h) % 24
        in_shift = shift_start <= target_local < shift_end
        factor = weekend_factor if is_weekend else (0.9 if in_shift else 0.15)
        if factor < 0.2:
            optimal_local_hours.append(target_local)

    # Find best window
    best_window = f"{optimal_local_hours[0]:02d}:00-{optimal_local_hours[-1] if optimal_local_hours else optimal_local_hours[0]:02d}:59"         if optimal_local_hours else "No optimal window found (24/7 SOC)"

    recommendation = ""
    if base_factor > 0.7:
        recommendation = (
            f"HIGH SOC ACTIVITY ({base_factor:.0%}) - defer high-noise actions. "
            f"Optimal window: {best_window} local time."
        )
    elif base_factor > 0.4:
        recommendation = (
            f"MODERATE SOC ACTIVITY ({base_factor:.0%}) - use stealth techniques only. "
            f"Better window in {max(0, shift_end - local_hour)}h."
        )
    else:
        recommendation = (
            f"LOW SOC ACTIVITY ({base_factor:.0%}) - execute now. "
            f"Optimal window: {best_window} local time."
        )

    return {
        "soc_activity_factor": round(base_factor, 3),
        "local_hour_estimate": local_hour,
        "is_weekend":          is_weekend,
        "soc_profile":         profile["tz"],
        "optimal_window":      best_window,
        "recommendation":      recommendation,
    }


# ── SIEM correlation rules ────────────────────────────────────────────────────

@dataclass
class SIEMCorrelationRule:
    name:          str
    description:   str
    triggers:      list[str]   # MITRE technique IDs
    within_minutes: int        # time window for correlation
    threshold:     int         # number of events needed to trigger
    severity:      str
    common_in:     list[str]   # Splunk, Sentinel, Elastic, etc.


_SIEM_CORRELATION_RULES: list[SIEMCorrelationRule] = [
    SIEMCorrelationRule(
        name="Possible DCSync Attack",
        description="DS-Replication-Get-Changes-All permission usage detected",
        triggers=["T1003.006"],
        within_minutes=5, threshold=1, severity="critical",
        common_in=["Splunk", "Sentinel", "Elastic", "QRadar", "ArcSight"],
    ),
    SIEMCorrelationRule(
        name="Kerberoasting Pattern",
        description="Multiple Kerberos TGS requests for service accounts in short window",
        triggers=["T1558.003"],
        within_minutes=1, threshold=5, severity="medium",
        common_in=["Splunk", "Sentinel", "Elastic"],
    ),
    SIEMCorrelationRule(
        name="Credential Access then Lateral Movement",
        description="LSASS access or hash dump followed by remote login within 30 minutes",
        triggers=["T1003.001", "T1569.002"],
        within_minutes=30, threshold=1, severity="high",
        common_in=["Splunk", "Sentinel", "Elastic", "CrowdStrike Fusion"],
    ),
    SIEMCorrelationRule(
        name="Golden Ticket Usage",
        description="Kerberos TGT with unusually long lifetime or for non-existent user",
        triggers=["T1558.001"],
        within_minutes=60, threshold=1, severity="critical",
        common_in=["Splunk", "Sentinel", "Microsoft Defender XDR"],
    ),
    SIEMCorrelationRule(
        name="Password Spray Pattern",
        description="Multiple failed logins from single source across many accounts",
        triggers=["T1110.003"],
        within_minutes=5, threshold=10, severity="medium",
        common_in=["Splunk", "Sentinel", "Elastic", "Azure AD Identity Protection"],
    ),
    SIEMCorrelationRule(
        name="PsExec / Remote Service Creation",
        description="Remote service creation followed by process execution",
        triggers=["T1569.002"],
        within_minutes=2, threshold=1, severity="high",
        common_in=["Splunk", "Sentinel", "CrowdStrike", "Sysmon correlation"],
    ),
    SIEMCorrelationRule(
        name="ADCS ESC1 Certificate Enrollment Abuse",
        description="Unusual certificate enrollment for high-privilege template",
        triggers=["T1649"],
        within_minutes=30, threshold=1, severity="high",
        common_in=["Microsoft Defender XDR", "Sentinel"],
    ),
    SIEMCorrelationRule(
        name="WMI Persistence via Event Subscription",
        description="WMI event filter and consumer created - common persistence IOC",
        triggers=["T1546.003"],
        within_minutes=5, threshold=1, severity="high",
        common_in=["Splunk", "Sentinel", "Elastic", "Sysmon"],
    ),
    SIEMCorrelationRule(
        name="Pass-the-Hash Network Logon Pattern",
        description="Network logon (type 3) without Kerberos TGT - PTH indicator",
        triggers=["T1550.002"],
        within_minutes=10, threshold=1, severity="high",
        common_in=["Splunk", "Sentinel", "Microsoft Defender XDR"],
    ),
    SIEMCorrelationRule(
        name="LSASS Memory Access",
        description="Process accessing LSASS memory with PROCESS_VM_READ - credential theft",
        triggers=["T1003.001"],
        within_minutes=1, threshold=1, severity="critical",
        common_in=["CrowdStrike", "SentinelOne", "Defender ATP", "Sentinel"],
    ),
]


def _check_siem_correlations(
    techniques_executed: list[str],
    execution_timestamps: dict[str, float] | None = None,
) -> list[dict]:
    """
    Check which SIEM correlation rules would fire given executed techniques.
    Returns list of triggered rules with timing analysis.
    """
    if not techniques_executed:
        return []

    triggered = []
    tech_set = set(techniques_executed)

    for rule in _SIEM_CORRELATION_RULES:
        # Check if any trigger technique was executed
        rule_techniques = set(rule.triggers)
        matched = tech_set & rule_techniques

        if not matched:
            continue

        # Check if ALL required techniques for multi-technique rules are present
        all_required_present = all(
            any(t.startswith(req.rstrip("*")) for t in tech_set)
            for req in rule.triggers
        )

        if not all_required_present and len(rule.triggers) > 1:
            continue

        # Estimate time-to-detection
        time_to_detect = rule.within_minutes + (rule.threshold * 0.5)

        triggered.append({
            "rule":             rule.name,
            "description":      rule.description,
            "severity":         rule.severity,
            "triggered_by":     list(matched),
            "time_to_detect_min": time_to_detect,
            "common_in":        rule.common_in,
            "recommendation":   (
                f"Add {rule.within_minutes}+ minute gap between "
                f"{' and '.join(list(matched)[:2])} to avoid this rule."
            ),
        })

    return sorted(triggered, key=lambda x: x["time_to_detect_min"])



def _apply_dwell_time_decay(
    base_score:          float,
    campaign_start_time: float,
    now:                 float | None = None,
) -> float:
    """
    Longer undetected dwell = lower probability next technique triggers detection.
    Logic: if EDR hasn't caught us after N days, signatures may not match.

    Decay schedule:
      < 1 day:   0%  reduction (fresh compromise - full risk)
      1-3 days:  10% reduction
      3-7 days:  20% reduction
      1-2 weeks: 35% reduction
      2-4 weeks: 50% reduction
      1 month+:  60% reduction
    """
    now = now or time.time()
    dwell_days = max(0.0, (now - campaign_start_time) / 86400.0)

    if dwell_days < 1:
        return base_score
    elif dwell_days < 3:
        return base_score * 0.90
    elif dwell_days < 7:
        return base_score * 0.80
    elif dwell_days <= 14 + (1 / 86400):
        return base_score * 0.65
    elif dwell_days < 30:
        return base_score * 0.50
    else:
        return base_score * 0.40


@dataclass
class ActionRisk:
    module_id:    str
    technique:    str
    event_source: str
    event_id:     str
    probability:  float
    description:  str
    timestamp:    float = field(default_factory=time.monotonic)


@dataclass
class CoveragePrediction:
    overall_score:         float             # 0.0 - 1.0
    action_risks:          list[ActionRisk]
    highest_risk_action:   ActionRisk | None
    wait_hours:            int
    wait_reason:           str
    recommendations:       list[str]
    modules_analyzed:      int
    techniques_triggered:  list[str]
    soc_activity:          dict = field(default_factory=dict)  # SOC shift analysis
    siem_correlations:     list[dict] = field(default_factory=list)  # triggered SIEM rules


class CoveragePredictor:
    """
    Offline scoring engine - no network calls.
    Reads campaign findings and audit data to compute detection probability.
    """

    def predict(
        self,
        campaign_findings: list[dict],
        modules_run:       list[dict],   # list of {module_id, mitre_techniques, opsec_level, timestamp}
        noise_profile:     str = "normal",
        **kwargs: Any,
    ) -> CoveragePrediction:
        """
        Compute detection probability from campaign execution history.

        Args:
            campaign_findings: Finding dicts from campaign.findings
            modules_run:       List of modules that ran with their metadata
            noise_profile:     Campaign noise profile (stealth/normal/aggressive)

        Returns:
            CoveragePrediction with overall score and per-action breakdown
        """
        action_risks: list[ActionRisk] = []
        techniques_seen: set[str] = set()

        noise_mod = _OPSEC_MODIFIERS.get(noise_profile, 0.55)

        for mod_entry in modules_run:
            module_id  = mod_entry.get("module_id", "")
            techniques = mod_entry.get("mitre_techniques", [])
            opsec_lvl  = mod_entry.get("opsec_level", "medium").lower()
            ts         = mod_entry.get("timestamp", time.monotonic())

            opsec_mod  = _OPSEC_MODIFIERS.get(opsec_lvl, 0.55)

            for technique in techniques:
                techniques_seen.add(technique)
                events = _TECHNIQUE_DETECTION_MAP.get(technique, [])
                for evt_source, evt_id, base_prob, desc in events:
                    # Adjust probability by OPSEC level and noise profile
                    adjusted = min(base_prob * opsec_mod * noise_mod * 1.4, 1.0)
                    action_risks.append(ActionRisk(
                        module_id=module_id,
                        technique=technique,
                        event_source=evt_source,
                        event_id=evt_id,
                        probability=adjusted,
                        description=desc,
                        timestamp=ts,
                    ))

        # Compute overall score - weighted by highest individual risks
        # Apply dwell time decay - longer undetected = lower score
        campaign_start = kwargs.get("campaign_start_time")
        if campaign_start is None:
            campaign_obj = kwargs.get("campaign")
            if campaign_obj:
                raw_start = getattr(campaign_obj, "created_at", None)
                if raw_start:
                    if hasattr(raw_start, "timestamp"):
                        campaign_start = raw_start.timestamp()  # datetime → epoch
                    elif isinstance(raw_start, (int, float)):
                        campaign_start = float(raw_start)
                    else:
                        try:
                            campaign_start = float(raw_start)
                        except (TypeError, ValueError):
                            campaign_start = None  # give up gracefully
        if campaign_start and action_risks:
            for ar in action_risks:
                ar.probability = _apply_dwell_time_decay(ar.probability, campaign_start)

        if not action_risks:
            overall = 0.0
        else:
            # Use expected value formula: P(detected) = 1 - ∏(1 - p_i)
            prob_not_detected = 1.0
            for ar in action_risks:
                prob_not_detected *= (1.0 - ar.probability)
            overall = 1.0 - prob_not_detected
            overall = min(overall, 1.0)

        # Highest risk action
        highest = max(action_risks, key=lambda x: x.probability) if action_risks else None

        # Wait time recommendation
        wait_hours = 0
        wait_reason = "Continue - detection risk minimal"
        for lo, hi, hours, reason in _WAIT_RECOMMENDATIONS:
            if lo <= overall < hi:
                wait_hours = hours
                wait_reason = reason
                break

        # Generate recommendations
        recommendations = self._build_recommendations(overall, action_risks, noise_profile)

        # SOC shift analysis
        soc_activity = _compute_soc_activity_factor(
            target_domain=kwargs.get("target_domain", ""),
            target_type=kwargs.get("target_type", "default"),
        )

        # SIEM correlation analysis
        siem_hits = _check_siem_correlations(list(techniques_seen))

        # Adjust score upward if SIEM correlation rules triggered
        if siem_hits:
            critical_siem = [h for h in siem_hits if h["severity"] == "critical"]
            if critical_siem:
                overall = min(overall + 0.15, 1.0)
            elif siem_hits:
                overall = min(overall + 0.08, 1.0)

        # Adjust wait time if SOC is active
        soc_factor = soc_activity.get("soc_activity_factor", 0.5)
        if action_risks and soc_factor > 0.7 and wait_hours < 8:
            wait_hours = max(wait_hours, 8)
            wait_reason += f" (SOC currently at {soc_factor:.0%} activity)"

        # Re-run recommendations with new data
        recommendations = self._build_recommendations(
            overall, action_risks, noise_profile,
            soc_activity=soc_activity, siem_hits=siem_hits,
        )

        return CoveragePrediction(
            overall_score=overall,
            action_risks=sorted(action_risks, key=lambda x: x.probability, reverse=True),
            highest_risk_action=highest,
            wait_hours=wait_hours,
            wait_reason=wait_reason,
            recommendations=recommendations,
            modules_analyzed=len(modules_run),
            techniques_triggered=sorted(techniques_seen),
            soc_activity=soc_activity,
            siem_correlations=siem_hits,
        )

    def _build_recommendations(
        self,
        score:         float,
        risks:         list[ActionRisk],
        noise_profile: str,
        soc_activity:  dict | None = None,
        siem_hits:     list[dict] | None = None,
    ) -> list[str]:
        recs = []

        if score > 0.9:
            recs.append("CRITICAL: Assume detected. Stop all operations and reset OPSEC posture.")
            recs.append("Rotate all implants, change C2 infrastructure, use fresh credentials.")

        if score > 0.6:
            recs.append("Switch from direct lateral movement to living-off-the-land techniques.")
            recs.append("Use existing scheduled tasks or WMI instead of creating new ones.")

        if noise_profile == "aggressive" and score > 0.4:
            recs.append("Switch noise profile to NORMAL or STEALTH to reduce IOC density.")

        # Flag highest-risk techniques
        high_risk = [r for r in risks if r.probability > 0.8]
        if high_risk:
            techniques = list({r.technique for r in high_risk})
            recs.append(f"High-risk techniques detected: {', '.join(techniques[:3])}. "
                        "Consider alternative approach or accept detection risk.")

        # LSASS-specific
        if any("LSASS" in r.description for r in risks):
            recs.append("LSASS access detected - CrowdStrike/Defender ATP almost certainly alerted. "
                        "Use DPAPI or LAPS enumeration as credential alternatives.")

        # DCSync-specific
        if any("DCSync" in r.description for r in risks):
            recs.append("DCSync detected - high-confidence SIEM alert expected. "
                        "Verify krbtgt rotation has not occurred before using harvested hashes.")

        if not recs:
            recs.append("Current detection risk is acceptable. Maintain current OPSEC profile.")

        # SOC activity recommendations
        if soc_activity:
            soc_factor = soc_activity.get("soc_activity_factor", 0.0)
            if soc_factor > 0.6:
                recs.append(soc_activity.get("recommendation", ""))

        # SIEM correlation recommendations
        if siem_hits:
            fastest = siem_hits[0]
            common_rules = ", ".join(fastest["common_in"][:3])
            recs.append(
                f"SIEM ALERT: '{fastest['rule']}' would fire in ~{fastest['time_to_detect_min']} min "
                f"in {common_rules}. "
                f"{fastest['recommendation']}"
            )

        return recs


# ── Module ─────────────────────────────────────────────────────────────────────

@module_contract(
    permissions=[
        ProcessPermission(allow_subprocesses=False),
    ],
    circuit_breaker=CircuitBreaker(name="opsec.coverage_predictor", failure_threshold=5),
    params_model=CoveragePredictorParams,
)
class CoveragePredictorModule(BaseModule):
    """
    opsec.coverage_predictor - Real-time detection probability scoring

    OPSEC: LOCAL (offline analysis - no network calls)
    MITRE: T1592 (informational - analyzes existing campaign data)
    REQUIRES: active_campaign
    OUTPUTS:  detection_score, action_risks, wait_recommendation
    """
    MODULE_ID          = "opsec.coverage_predictor"
    MODULE_NAME        = "OPSEC Coverage Predictor"
    MODULE_CATEGORY    = "opsec"
    MODULE_DESCRIPTION = "Predict detection probability from campaign actions. Outputs score, per-action Event IDs, and wait-time recommendations."
    MODULE_AUTHOR      = "ARES Team <[email protected]>"
    OPSEC_LEVEL        = OpsecLevel.LOCAL
    REQUIRES           = []
    OUTPUTS            = ["detection_score", "action_risks", "wait_recommendation", "recommendations"]
    MITRE_TECHNIQUES   = ["T1592"]
    MODULE_TIMEOUT_SECONDS: int | None = 30
    PARAMS_MODEL       = CoveragePredictorParams

    async def validate(self, ctx: "Any") -> None:
        """Pre-flight: campaign must be active."""
        await super().validate(ctx)
        campaign = getattr(ctx, "campaign", None)
        if not campaign:
            from ares.core.errors import ModuleValidationError
            raise ModuleValidationError(
                "opsec.coverage_predictor requires an active campaign.",
                module_id=self.MODULE_ID, field="campaign",
            )

    async def execute(self, ctx: "Any") -> ModuleResult:
        """ExecutionContext-based entry point (v0.9.0+).
        Thin adapter: extract params from ctx → call run() → return ModuleResult.
        """
        if getattr(ctx, "dry_run", False):
            return ModuleResult(
                status="dry_run", module_id=self.MODULE_ID,
                raw={"dry_run": True, "note": "Would analyze campaign execution history"},
            )
        params = getattr(ctx, "params", {})
        if isinstance(params, CoveragePredictorParams):
            pdict = params.model_dump()
        elif isinstance(params, dict):
            pdict = dict(params)
        else:
            pdict = {}

        noise_profile = pdict.get("noise_profile") or "normal"
        findings, raw = await self.run(
            campaign=getattr(ctx, "campaign", None),
            noise_profile=noise_profile,
        )

        # Cryptographic Evidence Records with SHA-256 Merkle Provenance
        evidence_chain: list[EvidenceRecord] = []
        for risk in raw.get("action_risks", [])[:20]:
            tech = risk.get("technique", "T1592")
            ev = EvidenceRecord(
                artifact_id=f"opsec-risk-{tech}-{risk.get('event', '')}",
                source_target="campaign",
                collected_by=self.MODULE_ID,
                data={
                    "technique": tech,
                    "event": risk.get("event"),
                    "probability": risk.get("probability"),
                    "description": risk.get("description"),
                },
                tags=["opsec", "coverage_predictor", "detection_risk"],
            )
            evidence_chain.append(ev)

        raw["evidence_chain"] = [e.data for e in evidence_chain]
        raw["evidence_integrity"] = [e.record_hash for e in evidence_chain]

        # Closed-loop Purple Telemetry Synthesis (Sentinel KQL + Sigma YAML)
        kql_rule = (
            "// Microsoft Sentinel - Multi-Technique Attack Campaign Correlation & Detection Scoring\n"
            "SecurityAlert\n"
            "| where TimeGenerated > ago(24h)\n"
            "| extend Techniques = parse_json(Techniques)\n"
            "| mv-expand Techniques\n"
            "| summarize UniqueTechniques = dcount(to_string(Techniques)), AlertCount = count(), Severities = make_set(AlertSeverity) by CompromisedEntity, bin(TimeGenerated, 1h)\n"
            "| where UniqueTechniques >= 3 or AlertCount >= 5\n"
            "| project TimeGenerated, CompromisedEntity, UniqueTechniques, AlertCount, Severities"
        )
        sigma_rule = (
            "title: Correlated Multi-Stage Adversary Activity Detection\n"
            "id: e1f2a3b4-c5d6-47e8-f9a0-b1c2d3e4f5a6\n"
            "status: experimental\n"
            "description: Correlates multiple distinct MITRE ATT&CK tactical alerts against a single host or identity\n"
            "references:\n"
            "    - https://attack.mitre.org/techniques/T1592/\n"
            "author: ARES Purple Team Modernization\n"
            "date: 2026-03-30\n"
            "logsource:\n"
            "    category: alert\n"
            "detection:\n"
            "    selection:\n"
            "        AlertSeverity:\n"
            "            - high\n"
            "            - critical\n"
            "    condition: selection | count() by CompromisedEntity > 3\n"
            "level: high\n"
            "tags:\n"
            "    - attack.defense_evasion\n"
            "    - attack.t1592"
        )
        raw.setdefault("loot", {})
        raw["loot"]["detection_kql"] = kql_rule
        raw["loot"]["detection_sigma"] = sigma_rule
        raw["overall_detection_probability"] = float(raw.get("detection_score", 0.0))
        raw["siem_correlations_identified"] = bool(raw.get("siem_correlations"))
        raw["recommended_wait_hours"] = int(raw.get("wait_hours", 0))
        raw["opsec_coverage_audited"] = True

        return ModuleResult(
            status="success" if (findings or raw.get("detection_score", 0) >= 0) else "partial",
            findings=findings, raw=raw, module_id=self.MODULE_ID,
            execution_id=getattr(ctx, "execution_id", ""),
        )

    @trace_module("opsec.coverage_predictor")
    async def run(
        self,
        campaign: "Any" = None,
        noise_profile: str = "normal",
        **kwargs: Any,
    ) -> tuple[list, dict]:
        # Note: before_request() intentionally not called - LOCAL module, no network.

        loop = asyncio.get_running_loop()
        prediction = await loop.run_in_executor(
            None, lambda: self._analyze(campaign, noise_profile)
        )

        audit("opsec_coverage_prediction", actor="operator",
              technique="T1592", source="operator",
              target="campaign", detail=f"score={prediction.overall_score:.2f}")

        logger.info("coverage_prediction_complete",
                    score=f"{prediction.overall_score:.1%}",
                    wait_hours=prediction.wait_hours,
                    modules_analyzed=prediction.modules_analyzed)

        # Generate findings based on risk level
        findings = []  # noqa: F841
        score_pct = int(prediction.overall_score * 100)

        if prediction.overall_score >= 0.9:
            sev = Severity.CRITICAL
        elif prediction.overall_score >= 0.6:
            sev = Severity.HIGH
        elif prediction.overall_score >= 0.4:
            sev = Severity.MEDIUM
        elif prediction.overall_score >= 0.2:
            sev = Severity.LOW
        else:
            sev = Severity.INFO

        if prediction.overall_score > 0.05:
            self.finding(
                title=f"Detection Probability: {score_pct}% - {prediction.wait_reason}",
                description=(
                    f"Based on {prediction.modules_analyzed} modules executed and "
                    f"{len(prediction.techniques_triggered)} MITRE techniques triggered, "
                    f"estimated detection probability is {score_pct}%. "
                    f"Highest-risk action: {prediction.highest_risk_action.description if prediction.highest_risk_action else 'N/A'}. "
                    f"Recommended wait before next action: {prediction.wait_hours} hours."
                ),
                severity=sev,
                mitre_technique="T1592",
                mitre_tactic="Reconnaissance",
                evidence={
                    "detection_score":      round(prediction.overall_score, 4),
                    "wait_hours":           prediction.wait_hours,
                    "techniques_triggered": prediction.techniques_triggered,
                    "top_risk_events": [
                        {"event": f"{r.event_source}:{r.event_id}",
                         "probability": round(r.probability, 3),
                         "description": r.description}
                        for r in prediction.action_risks[:5]
                    ],
                },
                remediation="\n".join(prediction.recommendations),
                host="campaign",
                confidence=0.75,
            )

        raw = {
            "detection_score":    round(prediction.overall_score, 4),
            "score_percent":      score_pct,
            "wait_recommendation": {
                "hours":  prediction.wait_hours,
                "reason": prediction.wait_reason,
            },
            "action_risks": [
                {
                    "module_id":    r.module_id,
                    "technique":    r.technique,
                    "event":        f"{r.event_source} Event {r.event_id}",
                    "probability":  round(r.probability, 3),
                    "description":  r.description,
                }
                for r in prediction.action_risks[:20]
            ],
            "recommendations":       prediction.recommendations,
            "modules_analyzed":      prediction.modules_analyzed,
            "techniques_triggered":  prediction.techniques_triggered,
            "soc_activity":          prediction.soc_activity,
            "siem_correlations":     prediction.siem_correlations,
        }

        return self._findings[:], raw


    def predict_planned_actions(
        self,
        planned_modules:  list[str],
        current_score:    float,
        campaign:         Any = None,
    ) -> dict:
        """
        Pre-execution: predict how much detection score will rise if plan executes.
        Operator can reject plan BEFORE it runs.
        Used by StrategyEngine between plan generation and execution.
        """
        from ares.technique.library import _MODULE_TECHNIQUE_MAP

        # HIGH_NOISE modules - verified against OPSEC_LEVEL in module definitions
        # lateral.wmiexec removed (MEDIUM, not HIGH_NOISE)
        # ad.coerce + windows.lsa_secrets added (confirmed HIGH_NOISE)
        _KNOWN_HIGH_NOISE = {
            "ad.dcsync",
            "ad.coerce",
            "lateral.psexec",
            "lateral.rdp",
            "windows.lsass_dump",
            "windows.lsa_secrets",
        }

        additional  = 0.0
        warnings:   list[str] = []
        breakdowns: list[dict] = []

        for mid in planned_modules:
            module_addition = 0.0
            techniques = _MODULE_TECHNIQUE_MAP.get(mid, [])

            for technique in techniques:
                events = _TECHNIQUE_DETECTION_MAP.get(technique, [])
                for _, _, prob, _desc in events:
                    module_addition += prob * 0.08  # weighted contribution

            if mid in _KNOWN_HIGH_NOISE:
                module_addition += 0.20
                warnings.append(f"{mid} is HIGH_NOISE (+20% detection contribution)")

            additional += module_addition
            breakdowns.append({"module": mid, "contribution": round(module_addition, 3)})

        projected = min(current_score + additional, 1.0)
        safe = projected < 0.60

        return {
            "current_score":    round(current_score, 3),
            "additional":       round(additional, 3),
            "projected_score":  round(projected, 3),
            "safe_to_execute":  safe,
            "warnings":         warnings,
            "module_breakdown": sorted(breakdowns, key=lambda x: -x["contribution"]),
            "recommendation": (
                "SAFE - proceed" if safe else
                f"DANGEROUS - this plan will raise detection to {projected:.0%}. "
                "Revise to stealthier techniques."
            ),
        }

    def _analyze(self, campaign: "Any", noise_profile: str) -> CoveragePrediction:
        """Build modules_run list from campaign data and compute prediction."""
        predictor = CoveragePredictor()

        # Extract module execution history from campaign findings
        modules_run = []
        findings_dicts = []

        if campaign:
            # Build modules_run from campaign findings metadata
            seen_modules: set[str] = set()
            for finding in getattr(campaign, "findings", []):
                f_dict = finding if isinstance(finding, dict) else {}
                if hasattr(finding, "__dict__"):
                    f_dict = finding.__dict__
                findings_dicts.append(f_dict)

                # Extract module info from finding metadata
                mid = f_dict.get("module_id") or f_dict.get("source_module", "")
                if mid and mid not in seen_modules:
                    seen_modules.add(mid)
                    # Look up MITRE techniques from technique library
                    from ares.technique.library import _MODULE_TECHNIQUE_MAP
                    techniques = _MODULE_TECHNIQUE_MAP.get(mid, [])
                    # Get OPSEC level from module class if available
                    modules_run.append({
                        "module_id":        mid,
                        "mitre_techniques": techniques,
                        "opsec_level":      "medium",   # default - refined below
                        "timestamp":        time.monotonic(),
                    })

        return predictor.predict(
            campaign_findings=findings_dicts,
            modules_run=modules_run,
            noise_profile=noise_profile,
        )