ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
fix(core): remediate logic bugs, graph pathfinding, service intel scope, and test suites
Mafifrizi6f9bc8ffb1ba
diff --git a/ares/api/server.py b/ares/api/server.pyindex dd9dde7..7890a5f 100644--- a/ares/api/server.py+++ b/ares/api/server.py@@ -2724,7 +2724,7 @@ async def run_module(# Check privilege escalation and foothold statusis_privesc_escalated = (- module_id in ("linux.privesc", "windows.token_impersonation")+ module_id in ("linux.privesc", "windows.lsa_secrets")or bool(raw.get("escalated"))or bool(raw.get("root_access"))or raw.get("privilege") == "root"@@ -3925,6 +3925,63 @@ async def campaign_attack_paths("path": graph.path_to_report(path),}+ # Query paths starting from a specific source node+ if source and not target:+ da_report = graph.shortest_path_to_da(source)+ if da_report:+ return {+ "campaign_id": campaign_id,+ "source": source,+ "target": da_report.get("end", "Domain Admin"),+ "path": da_report,+ }+ return {+ "campaign_id": campaign_id,+ "source": source,+ "target": None,+ "path": None,+ "message": f"No attack path found originating from '{source}'",+ }++ # Query paths leading to a specific target node+ if target and not source:+ tgt_id = graph._find_node_by_label(target)+ if not tgt_id:+ return {+ "campaign_id": campaign_id,+ "source": None,+ "target": target,+ "path": None,+ "message": f"Target '{target}' not found in attack graph",+ }+ import networkx as _nx+ best_path = None+ best_cost = float("inf")+ for src_node, data in graph._g.nodes(data=True):+ if src_node == tgt_id or data.get("is_target"):+ continue+ try:+ cost = _nx.shortest_path_length(graph._g, src_node, tgt_id, weight="weight")+ if cost < best_cost:+ best_cost = cost+ best_path = _nx.shortest_path(graph._g, src_node, tgt_id, weight="weight")+ except (_nx.NetworkXNoPath, _nx.NodeNotFound):+ continue+ if best_path:+ return {+ "campaign_id": campaign_id,+ "source": graph._nodes[best_path[0]].label if best_path[0] in graph._nodes else best_path[0],+ "target": target,+ "path": graph.path_to_report(best_path),+ }+ return {+ "campaign_id": campaign_id,+ "source": None,+ "target": target,+ "path": None,+ "message": f"No attack path found leading to '{target}'",+ }+# Top-N paths to high-value nodestop = graph.top_paths(n=top_n)return {diff --git a/ares/checkpoint/manager.py b/ares/checkpoint/manager.pyindex f3a83cd..f025ce9 100644--- a/ares/checkpoint/manager.py+++ b/ares/checkpoint/manager.py@@ -143,7 +143,9 @@ class CheckpointManager:from cryptography.hazmat.primitives import hashes as _hashes# Normalise to bytes- if isinstance(encryption_key, str):+ if hasattr(encryption_key, "get_secret_value"):+ key_bytes = encryption_key.get_secret_value().encode()+ elif isinstance(encryption_key, str):key_bytes = encryption_key.encode()elif isinstance(encryption_key, (bytes, bytearray)):key_bytes = bytes(encryption_key)diff --git a/ares/cli/_store.py b/ares/cli/_store.pyindex 026666a..9c685fd 100644--- a/ares/cli/_store.py+++ b/ares/cli/_store.py@@ -115,12 +115,22 @@ class CampaignStore:# ── Checkpoint management ─────────────────────────────────────────────def save_checkpoint(self, campaign_partial_id: str, notes: str = "") -> dict | None:- """Snapshot a campaign state as a checkpoint. Returns checkpoint meta."""- import json, time+ """Snapshot a campaign state as an AES-256-GCM encrypted checkpoint."""+ import json, time, osc = load_campaign(campaign_partial_id)if not c:return None+ from ares.core.config import get_settings+ from ares.checkpoint.manager import CheckpointManager++ settings = get_settings()+ enc_key = getattr(settings, "ares_encryption_key", "") or getattr(settings, "ares_secret_key", "")+ if not enc_key:+ enc_key = "ares-default-local-checkpoint-key-32b"++ mgr = CheckpointManager(enc_key)+cp_dir = campaigns_dir() / "checkpoints" / c["id"]cp_dir.mkdir(parents=True, exist_ok=True)@@ -133,22 +143,30 @@ class CampaignStore:"notes": notes,"state": c,}+ raw_bytes = json.dumps(checkpoint, indent=2, default=str).encode("utf-8")+ nonce = os.urandom(mgr._GCM_NONCE_LEN)+ ct = mgr._aesgcm.encrypt(nonce, raw_bytes, None)+ encrypted = mgr._V2_MAGIC + nonce + ct+cp_path = cp_dir / f"{cp_id}.json"- cp_path.write_text(json.dumps(checkpoint, indent=2, default=str), encoding="utf-8")+ cp_path.write_bytes(encrypted)# Mark campaign as pausedfor p in campaigns_dir().glob("*.json"):- data = json.loads(p.read_text(encoding="utf-8"))- if data["id"] == c["id"]:- data["status"] = "paused"- data["last_checkpoint"] = cp_id- p.write_text(json.dumps(data, indent=2), encoding="utf-8")- break+ try:+ data_raw = json.loads(p.read_text(encoding="utf-8"))+ if data_raw.get("id") == c["id"]:+ data_raw["status"] = "paused"+ data_raw["last_checkpoint"] = cp_id+ p.write_text(json.dumps(data_raw, indent=2), encoding="utf-8")+ break+ except Exception:+ continuereturn {"checkpoint_id": cp_id, "path": str(cp_path), "saved_at": checkpoint["saved_at"]}def load_checkpoint(self, campaign_partial_id: str, cp_id: str = "latest") -> dict | None:- """Load a checkpoint. cp_id='latest' returns the most recent."""+ """Load an AES-256-GCM encrypted checkpoint. cp_id='latest' returns the most recent."""import jsonc = load_campaign(campaign_partial_id)if not c:@@ -168,7 +186,22 @@ class CampaignStore:matches = [p for p in checkpoints if cp_id in p.name]target = matches[0] if matches else checkpoints[0]- return json.loads(target.read_text(encoding="utf-8"))+ data_bytes = target.read_bytes()+ from ares.core.config import get_settings+ from ares.checkpoint.manager import CheckpointManager++ settings = get_settings()+ enc_key = getattr(settings, "ares_encryption_key", "") or getattr(settings, "ares_secret_key", "")+ if not enc_key:+ enc_key = "ares-default-local-checkpoint-key-32b"++ mgr = CheckpointManager(enc_key)+ try:+ decrypted = mgr._decrypt_checkpoint(data_bytes)+ return json.loads(decrypted.decode("utf-8"))+ except Exception:+ # Fallback: legacy unencrypted JSON+ return json.loads(data_bytes.decode("utf-8"))def list_reports(self, campaign_partial_id: str = "") -> list[dict]:"""List generated report files from ~/.ares/reports/."""diff --git a/ares/collab/manager.py b/ares/collab/manager.pyindex 1227119..7af5b5b 100644--- a/ares/collab/manager.py+++ b/ares/collab/manager.py@@ -401,7 +401,12 @@ class CollaborationManager:if lock:op = self._operators.get(lock.operator_id)if op and lock.target_host in op.active_targets:- op.active_targets.remove(lock.target_host)+ has_other_lock = any(+ l.operator_id == lock.operator_id and l.target_host == lock.target_host and not l.is_expired+ for l in self._locks.values()+ )+ if not has_other_lock:+ op.active_targets.remove(lock.target_host)return bool(to_del)def _evict_expired_locks(self) -> None:diff --git a/ares/core/engine.py b/ares/core/engine.pyindex 6dae395..feee78c 100644--- a/ares/core/engine.py+++ b/ares/core/engine.py@@ -1859,7 +1859,7 @@ CAMPAIGN_TEMPLATES: dict[str, dict] = {"name": "post_exploit","modules": ["windows.lsass_dump",- "windows.dpapi",+ "windows.lsa_secrets","exfil.smb_shares","exfil.secrets_scan",],diff --git a/ares/credential/vault.py b/ares/credential/vault.pyindex 18da181..ee725ab 100644--- a/ares/credential/vault.py+++ b/ares/credential/vault.py@@ -257,8 +257,13 @@ def _validate_type_coherence(secret: str, cred_type: CredentialType) -> bool:))if cred_type == CredentialType.CLEARTEXT:- # Cleartext must not look like a Unix crypt hash or exceeds reasonable length- return not secret.startswith("$") and len(secret) < 256+ # Cleartext must not look like a Unix crypt / Kerberos hash prefix or exceed reasonable length+ _CRYPT_HASH_PREFIXES = (+ "$6$", "$5$", "$1$", "$2a$", "$2b$", "$2y$", "$y$",+ "$argon2id$", "$argon2i$", "$apr1$", "$krb5",+ "$NT$", "$DCC2$", "$MSCACHE2$"+ )+ return not secret.startswith(_CRYPT_HASH_PREFIXES) and len(secret) < 256if cred_type == CredentialType.NTLM:if ":" in secret:parts = secret.split(":")diff --git a/ares/execution/executor.py b/ares/execution/executor.pyindex d3692b7..72ba215 100644--- a/ares/execution/executor.py+++ b/ares/execution/executor.py@@ -293,7 +293,7 @@ class RemoteExecutor:from ares.core.campaign import Campaign, NoiseProfile, ScopeEntryfrom ares.core.config import get_settingsfrom ares.core.noise import NoiseController- _c = Campaign(name="_exec", operator=self.operator)+ _c = self.campaign if self.campaign is not None else Campaign(name="_exec", operator=self.operator)lateral = PsExecLateral(settings=get_settings(), campaign=_c, noise=NoiseController(_c))result = await lateral.execute(target=target, username=username,@@ -320,7 +320,7 @@ class RemoteExecutor:from ares.core.campaign import Campaignfrom ares.core.config import get_settingsfrom ares.core.noise import NoiseController- _c = Campaign(name="_exec", operator=self.operator)+ _c = self.campaign if self.campaign is not None else Campaign(name="_exec", operator=self.operator)lateral = WinRMLateral(settings=get_settings(), campaign=_c, noise=NoiseController(_c))result = await lateral.move(target=target,@@ -353,7 +353,7 @@ class RemoteExecutor:from ares.core.campaign import Campaignfrom ares.core.config import get_settingsfrom ares.core.noise import NoiseController- _c = Campaign(name="_exec", operator=self.operator)+ _c = self.campaign if self.campaign is not None else Campaign(name="_exec", operator=self.operator)lateral = WMIExecLateral(settings=get_settings(), campaign=_c, noise=NoiseController(_c))result = await lateral.execute(target=target, username=username,diff --git a/ares/goal/planner.py b/ares/goal/planner.pyindex de1ab36..0a3639e 100644--- a/ares/goal/planner.py+++ b/ares/goal/planner.py@@ -320,24 +320,25 @@ class AttackPlanner:if module_id == "windows.lsass_dump":defense_multiplier *= 0.05defense_note = "Target enforces Credential Guard: LSASS memory dump penalized"- elif module_id == "windows.dpapi":- defense_multiplier *= 1.35- defense_note = "Target enforces Credential Guard: DPAPI boosted as primary bypass"+ elif module_id == "windows.lsa_secrets":+ defense_multiplier *= 1.2+ defense_note = "Target enforces Credential Guard: LSA secrets boosted as bypass"# 2. LSA Protection (PPL)if host_state.has_defense("lsa_protection") or host_state.has_defense("ppl"):if module_id == "windows.lsass_dump":defense_multiplier *= 0.15defense_note = "Target enforces LSA Protection: LSASS dump penalized"- elif module_id in ("windows.dpapi", "windows.token_impersonation"):+ elif module_id == "windows.lsa_secrets":defense_multiplier *= 1.25+ defense_note = "Target enforces LSA Protection: alternative credential extraction boosted"# 3. Microsoft Defender for Identity / DRSUAPI monitoringif host_state.has_defense("mde_identity") or host_state.has_defense("drsuapi_monitoring"):if module_id == "ad.dcsync":defense_multiplier *= 0.1defense_note = "Target DC has MDI / DRSUAPI monitoring: DCSync penalized"- elif module_id in ("ad.adcs", "ad.shadow_credentials"):+ elif module_id in ("ad.adcs", "ad.kerberoast"):defense_multiplier *= 1.3- defense_note = "Target DC has MDI: ADCS / Shadow Credentials boosted as evasion route"+ defense_note = "Target DC has MDI: ADCS / Kerberoasting boosted as evasion route"# 4. Service Creation Monitoring / EDR on lateral movementif host_state.has_defense("service_creation_monitoring") or host_state.has_defense("edr"):if module_id == "lateral.psexec":diff --git a/ares/graph/attack_graph.py b/ares/graph/attack_graph.pyindex a7468a1..4fb00a4 100644--- a/ares/graph/attack_graph.py+++ b/ares/graph/attack_graph.py@@ -725,28 +725,31 @@ class AttackGraph:elabel = data.get("label", "").replace('"', '\\"')lines.append(f' "{src}" -> "{tgt}" [label="{elabel}"];')lines.append("}")- with open(path, "w") as f:+ with open(path, "w", encoding="utf-8") as f:f.write("\n".join(lines))logger.info("graph_exported_dot", path=path)# ── Bloodhound JSON Ingest ────────────────────────────────────────────────+ # ── Bloodhound Ingest Pipeline (Two-Pass Architecture) ────────────────────+def ingest_bloodhound(self, json_path: str) -> dict[str, int]:"""- Import BloodHound/SharpHound JSON collection into the ARES attack graph.+ Import BloodHound/SharpHound collection into the ARES attack graph.- Supports BloodHound CE (v5+) and legacy (v4) JSON formats.- Parses: computers, users, groups, domains, sessions, ACLs.- After ingest, use find_path() / top_paths() to compute attack paths.+ Supports BloodHound CE (v5+), legacy (v4) JSON formats, and SharpHound .zip archives.+ Parses: computers, users, groups, domains, sessions, LocalAdmins, and ACLs/ACEs.+ Uses a two-pass resolution pipeline to prevent SID vs. Name split-brain disconnection.+ After ingest, use find_path() / top_paths() / shortest_path_to_da() to compute attack paths.Args:- json_path: Path to BloodHound JSON file (computers.json, users.json, etc.)- or a directory containing multiple .json files.+ json_path: Path to BloodHound JSON file, .zip archive, or directory containing JSON files.Returns:dict with counts: {"nodes_added": N, "edges_added": N, "file_count": N}"""import json as _json+ import zipfilefrom pathlib import Pathif not _NX_AVAILABLE:@@ -754,136 +757,215 @@ class AttackGraph:return {"nodes_added": 0, "edges_added": 0, "error": "networkx not installed"}p = Path(json_path)- files: list[Path] = []- if p.is_dir():- files = sorted(p.glob("*.json"))+ raw_payloads: list[tuple[str, dict]] = []++ if p.is_file() and (p.suffix.lower() == ".zip" or zipfile.is_zipfile(p)):+ try:+ with zipfile.ZipFile(p, "r") as zf:+ for name in sorted(zf.namelist()):+ if name.lower().endswith(".json") and not name.startswith("__MACOSX"):+ try:+ with zf.open(name) as fh:+ data = _json.loads(fh.read().decode("utf-8", errors="replace"))+ raw_payloads.append((name, data))+ except Exception as exc:+ logger.warning("bloodhound_zip_member_error", member=name, error=str(exc)[:100])+ except Exception as exc:+ logger.warning("bloodhound_zip_read_error", file=str(p), error=str(exc)[:100])+ return {"nodes_added": 0, "edges_added": 0, "error": f"Failed to read zip archive: {str(exc)[:100]}"}++ elif p.is_dir():+ for fp in sorted(p.glob("*.json")):+ try:+ with open(fp, "r", encoding="utf-8", errors="replace") as fh:+ raw_payloads.append((fp.name, _json.load(fh)))+ except Exception as exc:+ logger.warning("bloodhound_parse_error", file=str(fp), error=str(exc)[:100])+elif p.is_file():- files = [p]+ try:+ with open(p, "r", encoding="utf-8", errors="replace") as fh:+ raw_payloads.append((p.name, _json.load(fh)))+ except Exception as exc:+ logger.warning("bloodhound_parse_error", file=str(p), error=str(exc)[:100])+ return {"nodes_added": 0, "edges_added": 0, "error": f"Failed to parse JSON file: {str(exc)[:100]}"}+else:return {"nodes_added": 0, "edges_added": 0, "error": f"Path not found: {json_path}"}+ if not raw_payloads:+ return {"nodes_added": 0, "edges_added": 0, "file_count": 0}+nodes_before = self._g.number_of_nodes()edges_before = self._g.number_of_edges()- for fp in files:- try:- with open(fp) as fh:- data = _json.load(fh)- self._parse_bloodhound_json(data)- except Exception as exc:- logger.warning("bloodhound_parse_error", file=str(fp), error=str(exc)[:100])+ # Two-pass parsing across all collected payloads+ self._parse_bloodhound_datasets(raw_payloads)nodes_added = self._g.number_of_nodes() - nodes_beforeedges_added = self._g.number_of_edges() - edges_before- logger.info("bloodhound_ingest_complete",- nodes=nodes_added, edges=edges_added, files=len(files))- return {"nodes_added": nodes_added, "edges_added": edges_added,- "file_count": len(files)}+ logger.info(+ "bloodhound_ingest_complete",+ nodes=nodes_added,+ edges=edges_added,+ files=len(raw_payloads),+ )+ return {+ "nodes_added": nodes_added,+ "edges_added": edges_added,+ "file_count": len(raw_payloads),+ }def _parse_bloodhound_json(self, data: dict) -> None:- """Parse a single BloodHound JSON file (computers, users, groups, etc.)."""- # BloodHound CE format: {"data": [...], "meta": {"type": "computers"}}- # Legacy format: {"computers": [...]} or {"users": [...]}- meta = data.get("meta", {})- bh_type = meta.get("type", "").lower()- items = data.get("data", [])-- # Legacy fallback: detect type from top-level keys- if not items:- for key in ("computers", "users", "groups", "domains", "sessions", "ous", "gpos"):- if key in data:- items = data[key]- bh_type = key- break-- if not items:- return+ """Backward-compatible single-payload ingest helper."""+ self._parse_bloodhound_datasets([("data.json", data)])++ def _parse_bloodhound_datasets(self, raw_payloads: list[tuple[str, dict]]) -> None:+ """Two-pass ingestion of BloodHound datasets to eliminate SID vs. Name split-brain."""+ sid_to_id: dict[str, str] = {}+ name_to_id: dict[str, str] = {}+ normalized_items: list[tuple[str, dict]] = []++ # ── PASS 1: Identify all entities, index SIDs and canonical Names ───────────+ for _fname, data in raw_payloads:+ if not isinstance(data, dict):+ continue+ meta = data.get("meta") or {}+ bh_type = str(meta.get("type") or "").strip().lower()+ items = data.get("data")++ # Legacy fallback: top-level key detection+ if items is None:+ for key in ("computers", "users", "groups", "domains", "sessions", "ous", "gpos"):+ if key in data and isinstance(data[key], list):+ items = data[key]+ bh_type = key+ break++ if not items or not isinstance(items, list):+ continue- for item in items:- props = item.get("Properties", item.get("properties", {}))- aces = item.get("Aces", item.get("aces", []))- members = item.get("Members", item.get("members", []))+ for item in items:+ if not isinstance(item, dict):+ continue+ normalized_items.append((bh_type, item))+ props = item.get("Properties") or item.get("properties") or {}+ raw_name = str(props.get("name") or item.get("name") or "").strip()+ name = raw_name.upper()++ # Extract SIDs / ObjectIdentifiers+ oid = str(+ item.get("ObjectIdentifier")+ or props.get("objectid")+ or props.get("domainsid")+ or ""+ ).strip().upper()++ # Normalize category+ entity_type = "object"+ if bh_type in ("computers", "computer"):+ entity_type = "computer"+ elif bh_type in ("users", "user"):+ entity_type = "user"+ elif bh_type in ("groups", "group"):+ entity_type = "group"+ elif bh_type in ("domains", "domain"):+ entity_type = "domain"+ elif bh_type in ("ous", "ou"):+ entity_type = "ou"+ elif bh_type in ("gpos", "gpo"):+ entity_type = "gpo"+ elif bh_type in ("sessions", "session"):+ continue++ canonical_id = f"{entity_type}:{name}" if name else (f"{entity_type}:{oid}" if oid else "")+ if not canonical_id:+ continue++ if oid:+ sid_to_id[oid] = canonical_id+ sid_to_id[f"{entity_type}:{oid}"] = canonical_id+ if name:+ name_to_id[name] = canonical_id+ name_to_id[f"{entity_type}:{name}"] = canonical_id+ if "@" in name:+ name_to_id[name.split("@")[0]] = canonical_id+ if "." in name:+ name_to_id[name.split(".")[0]] = canonical_id++ # Register canonical node in GraphNode dictionary and NetworkX+ is_target = False+ label = raw_name or oid+ node_type = entity_type++ if entity_type == "computer":+ is_dc = bool(props.get("isdc", props.get("isDC", False)))+ node_type = "domain_controller" if is_dc else "host"+ is_target = is_dc+ elif entity_type == "user":+ is_admin = bool(props.get("admincount", False))+ is_target = is_admin or ("ADMIN" in name)+ elif entity_type == "group":+ is_da = "DOMAIN ADMINS" in name or "ENTERPRISE ADMINS" in name or "ADMINISTRATORS" in name+ is_target = is_da+ elif entity_type == "domain":+ is_target = True- if bh_type in ("computers", "computer"):- self._bh_add_computer(props, aces)- elif bh_type in ("users", "user"):- self._bh_add_user(props, aces)- elif bh_type in ("groups", "group"):- self._bh_add_group(props, aces, members)- elif bh_type in ("domains", "domain"):- self._bh_add_domain(props, aces)-- def _bh_add_computer(self, props: dict, aces: list) -> None:- name = props.get("name", "").upper()- if not name:- return- node_id = f"computer:{name}"- is_dc = props.get("isdc", props.get("isDC", False))- self._g.add_node(node_id, label=name, node_type="host",- is_target=is_dc,- os=props.get("operatingsystem", ""),- enabled=props.get("enabled", True))- # Domain membership- domain = props.get("domain", "")- if domain:- dom_id = f"domain:{domain.upper()}"- self._g.add_node(dom_id, label=domain.upper(), node_type="domain",- is_target=True)- self._g.add_edge(dom_id, node_id, label="has_host", weight=0.1)- self._bh_process_aces(node_id, aces)-- def _bh_add_user(self, props: dict, aces: list) -> None:- name = props.get("name", "").upper()- if not name:- return- node_id = f"user:{name}"- is_admin = props.get("admincount", False)- self._g.add_node(node_id, label=name, node_type="user",- is_target=is_admin,- enabled=props.get("enabled", True),- has_spn=props.get("hasspn", False),- no_preauth=props.get("dontreqpreauth", False))- # Mark kerberoastable users- if props.get("hasspn", False):- self._g.add_edge(node_id, f"technique:kerberoast:{name}",- label="kerberoastable", weight=0.3)- if props.get("dontreqpreauth", False):- self._g.add_edge(node_id, f"technique:asreproast:{name}",- label="asreproastable", weight=0.2)- domain = props.get("domain", "")- if domain:- dom_id = f"domain:{domain.upper()}"- self._g.add_edge(dom_id, node_id, label="has_user", weight=0.1)- self._bh_process_aces(node_id, aces)-- def _bh_add_group(self, props: dict, aces: list, members: list) -> None:- name = props.get("name", "").upper()- if not name:- return- node_id = f"group:{name}"- is_da = "DOMAIN ADMINS" in name or "ENTERPRISE ADMINS" in name- self._g.add_node(node_id, label=name, node_type="group",- is_target=is_da)- for member in members:- mid = member.get("MemberId", member.get("ObjectIdentifier", ""))- mtype = member.get("MemberType", member.get("ObjectType", "")).lower()- if mid:- member_node = f"{mtype}:{mid}" if ":" not in mid else mid- self._g.add_edge(member_node, node_id, label="member_of",- weight=0.1)- self._bh_process_aces(node_id, aces)-- def _bh_add_domain(self, props: dict, aces: list) -> None:- name = props.get("name", "").upper()- if not name:- return- node_id = f"domain:{name}"- self._g.add_node(node_id, label=name, node_type="domain",- is_target=True)- self._bh_process_aces(node_id, aces)+ self._add_node(GraphNode(+ node_id=canonical_id,+ label=label,+ node_type=node_type,+ properties={+ "name": raw_name,+ "sid": oid,+ "domain": str(props.get("domain") or "").upper(),+ "enabled": props.get("enabled", True),+ "has_spn": props.get("hasspn", False),+ "no_preauth": props.get("dontreqpreauth", False),+ "os": props.get("operatingsystem", ""),+ },+ risk_score=5.0 if is_target else 1.0,+ is_target=is_target,+ ))++ # Helper to resolve any SID, Name, or typed reference to canonical node ID+ def _resolve_node(ref: Any, default_type: str = "object") -> str:+ if not ref or not isinstance(ref, (str, int)):+ return ""+ r_str = str(ref).strip()+ r_upper = r_str.upper()++ if r_upper in sid_to_id:+ return sid_to_id[r_upper]+ if r_upper in name_to_id:+ return name_to_id[r_upper]++ if ":" in r_str:+ _pfx, rest = r_str.split(":", 1)+ rest_upper = rest.strip().upper()+ if rest_upper in sid_to_id:+ return sid_to_id[rest_upper]+ if rest_upper in name_to_id:+ return name_to_id[rest_upper]+ else:+ for pfx in ("user", "computer", "group", "domain"):+ pfx_key = f"{pfx}:{r_upper}"+ if pfx_key in sid_to_id:+ return sid_to_id[pfx_key]+ if pfx_key in name_to_id:+ return name_to_id[pfx_key]++ # If not in registry, create dummy canonical node to preserve graph connectivity+ fallback_id = r_str.lower() if ":" in r_str else f"{default_type}:{r_str}".lower()+ if fallback_id not in self._nodes and fallback_id not in self._g:+ self._add_node(GraphNode(+ node_id=fallback_id,+ label=r_str,+ node_type=default_type or "object",+ is_target=False,+ ))+ return fallback_id- def _bh_process_aces(self, target_id: str, aces: list) -> None:- """Convert BloodHound ACEs to graph edges."""_DANGEROUS_RIGHTS = {"GenericAll", "GenericWrite", "WriteOwner", "WriteDacl","AllExtendedRights", "ForceChangePassword", "AddMember",@@ -891,62 +973,205 @@ class AttackGraph:"Owns", "AddSelf", "AddAllowedToAct",}_RIGHT_WEIGHTS = {- "GenericAll": 0.9, "WriteOwner": 0.8, "WriteDacl": 0.8,- "DCSync": 1.0, "ForceChangePassword": 0.7, "AddMember": 0.6,- "ReadLAPSPassword": 0.5, "ReadGMSAPassword": 0.5,- "AddAllowedToAct": 0.7, "Owns": 0.8,+ "DCSync": 0.1,+ "GenericAll": 0.15,+ "WriteOwner": 0.2,+ "WriteDacl": 0.2,+ "Owns": 0.2,+ "ForceChangePassword": 0.25,+ "AddMember": 0.25,+ "AllExtendedRights": 0.3,+ "ReadLAPSPassword": 0.35,+ "ReadGMSAPassword": 0.35,+ "GenericWrite": 0.4,+ "AddSelf": 0.4,+ "AddAllowedToAct": 0.45,}- for ace in aces:- right = ace.get("RightName", ace.get("rightname", ""))- principal = ace.get("PrincipalSID", ace.get("principalsid", ""))- ptype = ace.get("PrincipalType", ace.get("principaltype", "")).lower()- if right in _DANGEROUS_RIGHTS and principal:- src = f"{ptype}:{principal}" if ":" not in principal else principal- w = _RIGHT_WEIGHTS.get(right, 0.5)- self._g.add_edge(src, target_id, label=right.lower(),- weight=w,- properties={"right": right, "inherited": ace.get("IsInherited", False)})-- def shortest_path_to_da(self, start_node: str | None = None) -> list[dict]:++ # ── PASS 2: Stitch all edges across resolved canonical nodes ────────────────+ for bh_type, item in normalized_items:+ props = item.get("Properties") or item.get("properties") or {}+ raw_name = str(props.get("name") or item.get("name") or "").strip()+ name = raw_name.upper()+ oid = str(item.get("ObjectIdentifier") or props.get("objectid") or "").strip().upper()++ entity_type = "computer" if bh_type in ("computers", "computer") else (+ "user" if bh_type in ("users", "user") else (+ "group" if bh_type in ("groups", "group") else (+ "domain" if bh_type in ("domains", "domain") else "object"+ )+ )+ )+ target_node = _resolve_node(oid or name, default_type=entity_type)+ domain_name = str(props.get("domain") or "").strip().upper()+ domain_node = _resolve_node(domain_name, default_type="domain") if domain_name else ""++ # Domain hierarchy edges+ if domain_node and target_node and domain_node != target_node:+ rel_label = f"has_{entity_type}"+ self._add_edge(GraphEdge(+ source=domain_node,+ target=target_node,+ edge_type=rel_label,+ label=rel_label,+ weight=0.1,+ ))++ # 1. Access Control Entries (ACEs)+ aces = item.get("Aces") or item.get("aces") or []+ for ace in aces:+ if not isinstance(ace, dict):+ continue+ right = ace.get("RightName") or ace.get("rightname") or ""+ principal_sid = ace.get("PrincipalSID") or ace.get("principalsid") or ""+ ptype = str(ace.get("PrincipalType") or ace.get("principaltype") or "user").lower()++ if right in _DANGEROUS_RIGHTS and principal_sid:+ src_node = _resolve_node(principal_sid, default_type=ptype)+ if src_node and target_node and src_node != target_node:+ w = _RIGHT_WEIGHTS.get(right, 0.5)+ self._add_edge(GraphEdge(+ source=src_node,+ target=target_node,+ edge_type=EdgeType.ACE,+ label=right.lower(),+ weight=w,+ properties={"right": right, "inherited": ace.get("IsInherited", False)},+ ))++ # 2. Group Membership+ if bh_type in ("groups", "group"):+ members = item.get("Members") or item.get("members") or []+ for m in members:+ if not isinstance(m, dict):+ continue+ m_ref = m.get("MemberId") or m.get("ObjectIdentifier") or ""+ m_type = str(m.get("MemberType") or m.get("ObjectType") or "user").lower()+ src_member = _resolve_node(m_ref, default_type=m_type)+ if src_member and target_node and src_member != target_node:+ self._add_edge(GraphEdge(+ source=src_member,+ target=target_node,+ edge_type=EdgeType.MEMBER_OF,+ label="member_of",+ weight=0.05,+ ))++ # 3. Computer Local Admins & Permissions+ if bh_type in ("computers", "computer"):+ def _process_comp_members(data_field: str, rel_type: str, weight: float) -> None:+ raw_block = item.get(data_field)+ entries = raw_block.get("Results", []) if isinstance(raw_block, dict) else (+ raw_block if isinstance(raw_block, list) else []+ )+ for entry in entries:+ if not isinstance(entry, dict):+ continue+ e_ref = entry.get("ObjectIdentifier") or entry.get("MemberId") or ""+ e_type = str(entry.get("ObjectType") or entry.get("MemberType") or "user").lower()+ src = _resolve_node(e_ref, default_type=e_type)+ if src and target_node and src != target_node:+ self._add_edge(GraphEdge(+ source=src,+ target=target_node,+ edge_type=rel_type,+ label=rel_type,+ weight=weight,+ ))++ _process_comp_members("LocalAdmins", "admin_to", 0.2)+ _process_comp_members("RemoteDesktopUsers", "can_rdp", 0.4)+ _process_comp_members("DcomUsers", "execute_dcom", 0.4)++ # Computer Sessions (Inside computer item)+ raw_sess = item.get("Sessions")+ sess_entries = raw_sess.get("Results", []) if isinstance(raw_sess, dict) else (+ raw_sess if isinstance(raw_sess, list) else []+ )+ for s in sess_entries:+ if not isinstance(s, dict):+ continue+ u_ref = s.get("UserId") or s.get("UserName") or ""+ user_node = _resolve_node(u_ref, default_type="user")+ if target_node and user_node and target_node != user_node:+ # Compromising computer yields user credential session+ self._add_edge(GraphEdge(+ source=target_node,+ target=user_node,+ edge_type=EdgeType.HAS_SESSION,+ label="has_session",+ weight=0.3,+ ))++ # 4. Standalone Sessions File+ if bh_type in ("sessions", "session"):+ c_ref = item.get("ComputerId") or item.get("ComputerName") or ""+ u_ref = item.get("UserId") or item.get("UserName") or ""+ c_node = _resolve_node(c_ref, default_type="computer")+ u_node = _resolve_node(u_ref, default_type="user")+ if c_node and u_node and c_node != u_node:+ self._add_edge(GraphEdge(+ source=c_node,+ target=u_node,+ edge_type=EdgeType.HAS_SESSION,+ label="has_session",+ weight=0.3,+ ))++ def shortest_path_to_da(self, start_node: str | None = None) -> dict[str, Any] | None:"""Compute shortest attack path from start_node (or any user) to Domain Admins group.Uses Dijkstra with edge weights (lower = easier to exploit).- Returns list of steps with edge labels (attack technique at each hop).+ Returns structured report dict with steps, weights, and techniques, or None if no path exists."""if not _NX_AVAILABLE or not self._g.nodes:- return []+ return None# Find DA group node- da_nodes = [n for n, d in self._g.nodes(data=True)- if d.get("is_target") and "DOMAIN ADMINS" in d.get("label", "").upper()]+ da_nodes = [+ n for n, d in self._g.nodes(data=True)+ if d.get("is_target") and any(+ term in d.get("label", "").upper()+ for term in ("DOMAIN ADMINS", "ENTERPRISE ADMINS", "ADMINISTRATORS")+ )+ ]if not da_nodes:- da_nodes = [n for n in self._g.nodes if "domain admin" in n.lower()]+ da_nodes = [n for n in self._g.nodes if "domain admin" in str(n).lower()]if not da_nodes:- return []-- da_target = da_nodes[0]+ return None- # If no start specified, try all user nodes and return shortest+ # If start specified, resolve it via registry or labelsif start_node:- start_nodes = [start_node]+ resolved_start = start_node+ if start_node not in self._g:+ # Try finding by label or suffix+ for n, d in self._g.nodes(data=True):+ if d.get("label") == start_node or str(n).upper() == start_node.upper():+ resolved_start = n+ break+ start_nodes = [resolved_start] if resolved_start in self._g else []else:- start_nodes = [n for n, d in self._g.nodes(data=True)- if d.get("node_type") == "user" and not d.get("is_target")]+ start_nodes = [+ n for n, d in self._g.nodes(data=True)+ if d.get("node_type") == "user" and not d.get("is_target")+ ]best_path: list = []- best_len = float("inf")+ best_cost = float("inf")- for src in start_nodes[:50]: # cap to avoid excessive computation- try:- path = nx.shortest_path(self._g, src, da_target, weight="weight")- if len(path) < best_len:- best_len = len(path)- best_path = path- except (nx.NetworkXNoPath, nx.NodeNotFound):- continue+ for src in start_nodes[:50]:+ for da_target in da_nodes:+ try:+ cost = nx.shortest_path_length(self._g, src, da_target, weight="weight")+ if cost < best_cost:+ path = nx.shortest_path(self._g, src, da_target, weight="weight")+ best_cost = cost+ best_path = path+ except (nx.NetworkXNoPath, nx.NodeNotFound):+ continueif not best_path:- return []+ return Nonereturn self.path_to_report(best_path)diff --git a/ares/knowledge/base.py b/ares/knowledge/base.pyindex 0b7b53d..8610296 100644--- a/ares/knowledge/base.py+++ b/ares/knowledge/base.py@@ -138,17 +138,17 @@ _KB_ENTRIES: list[KBEntry] = [severity="critical",),KBEntry(- entry_id="kb-dpapi",- title="DPAPI Protected Credential Extraction",+ entry_id="kb-lsa-secrets",+ title="LSA Secrets & SAM Hive Credential Extraction",description=(- "When user context or NT hash is available, DPAPI blobs can be decrypted "- "to recover Chrome/Edge saved passwords, WiFi PSK, Windows Credential Manager "- "entries, and RDP saved credentials."+ "When administrator context or SYSTEM access is available, local SAM hashes "+ "and LSA secrets (cached domain credentials, service passwords) can be extracted "+ "via remote registry without requiring an LSASS memory dump."),category="credential_access",- applies_when=["user_context_windows"],- attack_modules=["windows.dpapi"],- mitre_ids=["T1555.004", "T1555.003"],+ applies_when=["local_admin_windows"],+ attack_modules=["windows.lsa_secrets"],+ mitre_ids=["T1003.002", "T1003.004"],severity="high",),]diff --git a/ares/marketplace/installer.py b/ares/marketplace/installer.pyindex 0ea2ab1..4d208e1 100644--- a/ares/marketplace/installer.py+++ b/ares/marketplace/installer.py@@ -174,10 +174,10 @@ _BUNDLED_INDEX: "dict" = {"opsec": "low", "requires": [], "outputs": ["snmp_findings","system_info"],"mitre": ["T1046","T1590"], "builtin": True},# ── Windows modules ──- {"id": "windows.token_impersonation","name": "Token Impersonation","category": "windows",- "description": "Detect SeImpersonatePrivilege - prerequisite for Potato-family LPE",- "opsec": "medium", "requires": ["lateral_session"], "outputs": ["privesc_vectors"],- "mitre": ["T1134.001", "T1134.002"], "builtin": True},+ {"id": "windows.lsass_dump", "name": "LSASS Memory Dump", "category": "windows",+ "description": "Dump LSASS memory for credentials via procdump, comsvcs, or nanodump",+ "opsec": "high_noise", "requires": ["local_admin_creds"], "outputs": ["ntlm_hashes", "kerberos_tickets"],+ "mitre": ["T1003.001"], "builtin": True},{"id": "windows.lsa_secrets", "name": "LSA Secrets & SAM Dump", "category": "windows","description": "Extract local account hashes (SAM) and LSA secrets via impacket secretsdump","opsec": "high_noise", "requires": ["local_admin_creds"], "outputs": ["ntlm_hashes", "lsa_secrets"],@@ -725,7 +725,7 @@ class ModuleInstaller:mod = importlib.util.module_from_spec(spec)try:spec.loader.exec_module(mod) # type: ignore[attr-defined]- except (ImportError, AttributeError, OSError):+ except Exception:return ModuleManifest(id=path.stem, name=path.stem, description="", source_url=source_url)from ares.modules.base import BaseModulediff --git a/ares/mcp/tools.py b/ares/mcp/tools.pyindex cba26c5..151f635 100644--- a/ares/mcp/tools.py+++ b/ares/mcp/tools.py@@ -438,6 +438,18 @@ class McpToolRegistry:async def _handle_query_attack_graph(self, args: dict[str, Any]) -> CallToolResult:campaign_id = args["campaign_id"]target_node = args.get("target_node", "Domain Admins")++ if self.db and hasattr(self.db, "get_attack_graph"):+ try:+ g = await self.db.get_attack_graph(campaign_id, target_goal=target_node)+ if g:+ clean_data = McpTaintSanitizer.sanitize(g)+ return CallToolResult(+ content=[TextContent(type="text", text=json.dumps(clean_data, indent=2))]+ )+ except Exception as exc:+ logger.warning("mcp_query_attack_graph_failed", error=str(exc))+graph_data = {"campaign_id": campaign_id,"target_goal": target_node,@@ -445,7 +457,7 @@ class McpToolRegistry:{"step": 1, "node": "WS01.corp.local", "type": "host", "status": "compromised"},{"step": 2, "node": "CORP\\jdoe", "type": "user", "status": "credentials_dumped"},{"step": 3, "node": "Server02.corp.local", "type": "host", "relation": "AdminTo"},- {"step": 4, "node": "CORP\\svc_backup", "type": "user", "relation": "TokenImpersonation"},+ {"step": 4, "node": "CORP\\svc_backup", "type": "user", "relation": "Kerberoast"},{"step": 5, "node": "DC01.corp.local", "type": "host", "relation": "DCSync"},{"step": 6, "node": "Domain Admins", "type": "group", "status": "unlocked"},],diff --git a/ares/modules/ad/adcs.py b/ares/modules/ad/adcs.pyindex caa3c82..f91bbd0 100644--- a/ares/modules/ad/adcs.py+++ b/ares/modules/ad/adcs.py@@ -151,7 +151,7 @@ class ADCSModule(BaseModule[ADCSParams, ModuleResult]):recommendations.append("ad.enum_spn")if host_state.has_defense("edr_active") or host_state.has_defense("crowdstrike"):risk = "medium"- recommendations.append("ad.shadow_credentials")+ recommendations.append("ad.kerberoast")exploit_esc1 = getattr(ctx, "params", {}).get("exploit_esc1", False)if exploit_esc1:diff --git a/ares/modules/ad/coerce.py b/ares/modules/ad/coerce.pyindex 8775e6b..5c5fe78 100644--- a/ares/modules/ad/coerce.py+++ b/ares/modules/ad/coerce.py@@ -309,18 +309,11 @@ class CoerceModule(BaseModule[CoerceParams, ModuleResult]):host = dc, confidence = 0.95,)else:- self.finding(- title = f"Coercion Attempted on {dc} - No Confirmation",- description = (- "Authentication coercion RPC call sent but no confirmation received. "- "Check lateral.smb_relay for captured credentials."- ),- severity = Severity.MEDIUM,- mitre_technique = "T1187",- mitre_tactic = "Credential Access",- evidence = {"target": dc, "listener": listener_ip, "error": result.get("error")},- remediation = "Monitor DC event logs for MS-EFSRPC/MS-RPRN calls.",- host = dc, confidence = 0.5,+ logger.warning(+ "coercion_all_methods_failed",+ target=dc,+ listener=listener_ip,+ last_error=result.get("error"),)raw = {diff --git a/ares/modules/ad/dcsync.py b/ares/modules/ad/dcsync.pyindex ce2cabd..03df979 100644--- a/ares/modules/ad/dcsync.py+++ b/ares/modules/ad/dcsync.py@@ -87,7 +87,7 @@ class DCSyncModule(BaseModule[DCSyncParams, ModuleResult]):score = 0.05risk = "critical_alarm"recommendations.append("ad.adcs")- recommendations.append("ad.shadow_credentials")+ recommendations.append("ad.kerberoast")session = getattr(ctx, "session", None)if session and hasattr(session, "get_host") and target_host:@@ -97,7 +97,7 @@ class DCSyncModule(BaseModule[DCSyncParams, ModuleResult]):risk = "critical_alarm"score -= 0.4recommendations.append("ad.adcs")- recommendations.append("ad.shadow_credentials")+ recommendations.append("ad.kerberoast")feasible = len(blockers) == 0 and score >= 0.4return FeasibilityReport(@@ -106,7 +106,7 @@ class DCSyncModule(BaseModule[DCSyncParams, ModuleResult]):risk_level=risk,blockers=blockers,recommended_alternatives=recommendations,- opsec_tuning={"suggested_alternatives": ["ad.adcs", "ad.shadow_credentials"] if risk == "critical_alarm" else []},+ opsec_tuning={"suggested_alternatives": ["ad.adcs", "ad.kerberoast"] if risk == "critical_alarm" else []},details={"target_user": getattr(ctx, "params", {}).get("target_user", "krbtgt")},)diff --git a/ares/modules/ad/delegation_abuse.py b/ares/modules/ad/delegation_abuse.pyindex 538e3f1..81961df 100644--- a/ares/modules/ad/delegation_abuse.py+++ b/ares/modules/ad/delegation_abuse.py@@ -442,7 +442,7 @@ class DelegationAbuseModule(BaseModule[DelegationAbuseParams, ModuleResult]):f"{target_service}/{target_computer}",type=constants.PrincipalNameType.NT_SRV_INST.value,)- final_tgs, _, _, _ = getKerberosTGS(+ final_tgs, cipher, old_key, new_key = getKerberosTGS(serverName=spn_target,domain=domain_upper,kdcHost=dc,@@ -457,13 +457,15 @@ class DelegationAbuseModule(BaseModule[DelegationAbuseParams, ModuleResult]):os.close(_fd)cc = CCache()+ if hasattr(cc, "fromTGS"):+ cc.fromTGS(final_tgs, old_key, new_key)cc.saveFile(ccache_path)logger.info("rbcd_ticket_saved", path=ccache_path,warning="Credential artifact on disk - delete after use")return ccache_pathexcept Exception as exc:- raise self._classify_error(exc, target=target) from exc+ raise self._classify_error(exc, target=target_computer) from excdef _s4u_attack_sync(self, dc: str, domain: str, username: str, password: str,constrained_acct: dict, impersonate_user: str) -> str:@@ -490,7 +492,7 @@ class DelegationAbuseModule(BaseModule[DelegationAbuseParams, ModuleResult]):spn = Principal(targets[0],type=constants.PrincipalNameType.NT_SRV_INST.value)- tgs, _, _, _ = getKerberosTGS(+ tgs, cipher, old_key, new_key = getKerberosTGS(serverName=spn, domain=domain_upper,kdcHost=dc, tgt=tgt, cipher=cipher, sessionKey=session_key,)@@ -498,6 +500,8 @@ class DelegationAbuseModule(BaseModule[DelegationAbuseParams, ModuleResult]):ccache_path, _fd = secure_mkstemp(suffix=".ccache", prefix="ares_s4u_")os.close(_fd)cc = CCache()+ if hasattr(cc, "fromTGS"):+ cc.fromTGS(tgs, old_key, new_key)cc.saveFile(ccache_path)return ccache_pathexcept Exception as exc:diff --git a/ares/modules/cloud/identity_federation.py b/ares/modules/cloud/identity_federation.pyindex 471f000..618272d 100644--- a/ares/modules/cloud/identity_federation.py+++ b/ares/modules/cloud/identity_federation.py@@ -106,6 +106,13 @@ class CloudIdentityFederationModule(BaseModule):module_id=self.MODULE_ID, field="credentials",)+ if pdict.get("tenant_id"):+ self.validate_cloud_scope(pdict.get("tenant_id"), "azure_ad")+ if pdict.get("project_id"):+ self.validate_cloud_scope(pdict.get("project_id"), "gcp")+ if pdict.get("account_id"):+ self.validate_cloud_scope(pdict.get("account_id"), "aws")+async def execute(self, ctx: "Any") -> ModuleResult:"""ExecutionContext-based entry point (v0.9.0+).Thin adapter: extract params from ctx → call run() → return ModuleResult.@@ -268,6 +275,13 @@ class CloudIdentityFederationModule(BaseModule):technique="T1606.002", source="operator", target="cloud_federation",detail=f"mode={mode} tenant={tenant_id[:8] + '...' if tenant_id else 'none'}")+ if tenant_id:+ self.validate_cloud_scope(tenant_id, "azure_ad")+ if kwargs.get("project_id"):+ self.validate_cloud_scope(kwargs.get("project_id"), "gcp")+ if kwargs.get("account_id"):+ self.validate_cloud_scope(kwargs.get("account_id"), "aws")+logger.info("federation_abuse_start", mode=mode, has_azure=bool(tenant_id),has_aws=bool(access_key), has_ad=bool(adfs_url or krbtgt_hash))diff --git a/ares/modules/credential/reuse.py b/ares/modules/credential/reuse.pyindex 95d8e7d..3a2f1ad 100644--- a/ares/modules/credential/reuse.py+++ b/ares/modules/credential/reuse.py@@ -62,11 +62,17 @@ def _audit_oauth_posture_sync(target: str) -> dict[str, Any]:except ValueError:pass- if is_private_ip:+ _INTERNAL_TLDS = (+ ".local", ".internal", ".corp", ".lan", ".home",+ ".lab", ".test", ".priv", ".intranet", ".arpa", ".domain",+ )+ is_internal_name = any(clean_target.endswith(tld) for tld in _INTERNAL_TLDS) or "." not in clean_target++ if is_private_ip or is_internal_name:probe_urls.append(f"https://{clean_target}/oauth2/v2.0/devicecode")elif "microsoftonline.com" in clean_target:probe_urls.append(f"https://{clean_target}/common/oauth2/v2.0/devicecode")- elif "." in clean_target:+ elif clean_target.endswith(".onmicrosoft.com"):probe_urls.append(f"https://login.microsoftonline.com/{clean_target}/oauth2/v2.0/devicecode")probe_urls.append(f"https://{clean_target}/oauth2/v2.0/devicecode")else:diff --git a/ares/modules/network/port_scan.py b/ares/modules/network/port_scan.pyindex bb435db..5fbefbc 100644--- a/ares/modules/network/port_scan.py+++ b/ares/modules/network/port_scan.py@@ -101,13 +101,13 @@ _SERVICE_INTELLIGENCE: dict[int, dict[str, Any]] = {"description": ("LDAP over TLS (LDAPS) is listening on {target}:636. Indicates a Domain Controller supporting ""encrypted directory queries and ADCS certificate enrollment. "- "Target for AD enumeration (ad.enum_users, ad.enum_computers) and ADCS escalation (ad.adcs, ad.ghost_forge)."+ "Target for AD enumeration (ad.enum_users, ad.enum_computers) and ADCS escalation (ad.adcs)."),"remediation": ("Enforce LDAP channel binding (LdapEnforceChannelBinding=2), require LDAP signing, ""and restrict LDAPS inbound traffic to authorized administrative jump hosts."),- "next_modules": ["ad.enum_users", "ad.adcs", "ad.ghost_forge"],+ "next_modules": ["ad.enum_users", "ad.enum_computers", "ad.adcs"],},389: {"title": "Active Directory LDAP Directory Service Exposed on Port 389",diff --git a/ares/modules/persistence/scheduled_task.py b/ares/modules/persistence/scheduled_task.pyindex 2dd5255..305878a 100644--- a/ares/modules/persistence/scheduled_task.py+++ b/ares/modules/persistence/scheduled_task.py@@ -433,22 +433,26 @@ class ScheduledTaskPersistence(BaseModule):except Exception as exc:raise self._classify_error(exc) from excfinally:- try:- await _loop.run_in_executor(- None,- lambda: _tsch_delete_sync(- target, username, password, domain,- lmhash, nthash, task_name,- ),- )- logger.info("scheduled_task_teardown_complete", target=target, task=task_name)- except Exception as _teardown_exc:- logger.warning(- "scheduled_task_teardown_failed",- target=target,- task=task_name,- error=str(_teardown_exc)[:100],- )+ should_cleanup = not ctx.get("persist", False) and ctx.get("cleanup", True)+ if should_cleanup:+ try:+ await _loop.run_in_executor(+ None,+ lambda: _tsch_delete_sync(+ target, username, password, domain,+ lmhash, nthash, task_name,+ ),+ )+ logger.info("scheduled_task_teardown_complete", target=target, task=task_name)+ except Exception as _teardown_exc:+ logger.warning(+ "scheduled_task_teardown_failed",+ target=target,+ task=task_name,+ error=str(_teardown_exc)[:100],+ )+ else:+ logger.info("scheduled_task_retained_for_persistence", target=target, task=task_name)async def teardown(self, target: str = "", username: str = "", password: str = "",domain: str = "", lmhash: str = "", nthash: str = "",diff --git a/ares/modules/windows/lsa_secrets.py b/ares/modules/windows/lsa_secrets.pyindex c94ab03..8ede44b 100644--- a/ares/modules/windows/lsa_secrets.py+++ b/ares/modules/windows/lsa_secrets.py@@ -71,7 +71,7 @@ class LSASecretsModule(BaseModule):"""Pre-flight Defense Feasibility Assessment:Evaluates registry auditing, local admin access, noise constraints,- and recommends ad.dcsync if target is a DC, or windows.dpapi if in stealth.+ and recommends ad.dcsync if target is a DC, or ad.kerberoast if in stealth."""from ares.modules.base import FeasibilityReportfrom ares.core.campaign import NoiseProfile@@ -101,7 +101,7 @@ class LSASecretsModule(BaseModule):blockers.append("Blocked in STEALTH profile: remote registry SAM/LSA hive dumping generates Sysmon Event 12/13 alerts")score = 0.1risk = "critical_alarm"- recommendations.extend(["windows.dpapi", "ad.dcsync"])+ recommendations.extend(["ad.dcsync", "ad.kerberoast"])session = getattr(ctx, "session", None)if session and hasattr(session, "get_host") and target:@@ -110,7 +110,7 @@ class LSASecretsModule(BaseModule):if host_state.has_defense("registry_auditing") or host_state.has_defense("sysmon_id12"):risk = "critical_alarm"score -= 0.3- recommendations.append("windows.dpapi")+ recommendations.append("ad.dcsync")is_dc = (getattr(host_state, "is_dc", False)or getattr(host_state, "domain_role", "") == "domain_controller"diff --git a/ares/modules/windows/lsass_dump.py b/ares/modules/windows/lsass_dump.pyindex a99d9ac..e215cfc 100644--- a/ares/modules/windows/lsass_dump.py+++ b/ares/modules/windows/lsass_dump.py@@ -112,14 +112,14 @@ class LsassDumpModule(BaseModule):if not username:blockers.append("No local administrator credentials provided or found in vault")score -= 0.4- recommendations.extend(["windows.token_impersonation", "ad.kerberoast"])+ recommendations.extend(["windows.token_impersonation", "ad.kerberoast", "ad.asreproast"])noise = getattr(getattr(ctx, "campaign", None), "noise_profile", None)if noise == NoiseProfile.STEALTH:blockers.append("Blocked in STEALTH profile: LSASS process access triggers Sysmon Event ID 10 and EDR process handles")score = 0.05risk = "critical_alarm"- recommendations.extend(["windows.dpapi", "ad.kerberoast"])+ recommendations.extend(["windows.dpapi", "ad.kerberoast", "windows.lsa_secrets"])session = getattr(ctx, "session", None)if session and hasattr(session, "get_host") and target:@@ -133,7 +133,7 @@ class LsassDumpModule(BaseModule):)score = min(score, 0.05)risk = "critical_alarm"- recommendations.extend(["windows.dpapi", "windows.token_impersonation", "ad.kerberoast"])+ recommendations.extend(["windows.dpapi", "windows.token_impersonation", "ad.kerberoast", "windows.lsa_secrets"])# 2. Check LSA Protection (RunAsPPL)if host_state.has_defense("lsa_protection") or host_state.has_defense("ppl"):@@ -142,7 +142,7 @@ class LsassDumpModule(BaseModule):)score = min(score, 0.15)risk = "critical_alarm"- recommendations.extend(["windows.dpapi", "windows.token_impersonation", "ad.kerberoast"])+ recommendations.extend(["windows.dpapi", "windows.token_impersonation", "ad.kerberoast", "windows.lsa_secrets"])# 3. Check EDR / Sysmon ID 10edr_detected = host_state.defense_profile.get("edr") or host_state.has_defense("sysmon_id10") or host_state.has_defense("edr")@@ -387,10 +387,9 @@ class LsassDumpModule(BaseModule):remediation=("Target is compliant with modern credential protection standards. ""To test alternative attack paths that do not touch LSASS memory: "- "1. Evaluate DPAPI secrets via windows.dpapi. "- "2. Audit token impersonation vectors via windows.token_impersonation. "- "3. Perform offline registry extraction (SAM/SECURITY) via windows.lsa_secrets. "- "4. Execute Kerberoasting via ad.kerberoast."+ "1. Perform offline registry extraction (SAM/SECURITY) via windows.lsa_secrets. "+ "2. Execute Kerberoasting via ad.kerberoast. "+ "3. Perform AS-REP Roasting via ad.asreproast."),host=target,confidence=1.0,diff --git a/ares/network/model.py b/ares/network/model.pyindex 384fd03..e364688 100644--- a/ares/network/model.py+++ b/ares/network/model.py@@ -263,6 +263,14 @@ class NetworkModel:G = nx.DiGraph()for host in self.all_hosts():G.add_node(host.ip_address)+ can_pivot = (+ host.ip_address == source_ip+ or host.is_pivot+ or host.is_router+ or host.ip_address in self._pivots+ )+ if not can_pivot:+ continuefor reachable in host.reachable:G.add_edge(host.ip_address, reachable)# Same-subnet hosts are mutually reachable@@ -290,6 +298,9 @@ class NetworkModel:host = self.get_host(node)if not host:continue+ # Intermediate nodes must be pivots or routers to forward traffic+ if node != source and not (host.is_pivot or host.is_router or node in self._pivots):+ continueneighbors = list(host.reachable)subnet = self.subnet_for(node)if subnet:diff --git a/ares/normalize/artifacts.py b/ares/normalize/artifacts.pyindex 0daeb02..4164c33 100644--- a/ares/normalize/artifacts.py+++ b/ares/normalize/artifacts.py@@ -930,9 +930,16 @@ class ArtifactNormalizer:count = 0for t in tickets:if isinstance(t, str):+ user = (+ raw.get("forged_as")+ or raw.get("impersonated")+ or raw.get("username")+ or "unknown"+ )+ dom = raw.get("domain") or ""artifact = CredentialArtifact(- username = "unknown",- domain = "",+ username = user,+ domain = dom,cred_type = "kerberos_ticket",secret = t,)diff --git a/ares/replay/engine.py b/ares/replay/engine.pyindex 351ab7e..b714a94 100644--- a/ares/replay/engine.py+++ b/ares/replay/engine.py@@ -164,18 +164,37 @@ class CampaignReplay:"""Build ordered event timeline from history + findings."""events: list[ReplayEvent] = []- # Build finding lookup by module_id- finding_map: dict[str, Any] = {}+ # Index findings by (module_id, host) and (module_id, "") for unassigned findings+ finding_map: dict[tuple[str, str], list[Any]] = {}+ unassigned_map: dict[str, list[Any]] = {}for f in self.findings:- fid = getattr(f, "module_id", "")- finding_map.setdefault(fid, []).append(f)+ fid = str(getattr(f, "module_id", "") or "")+ fhost = str(getattr(f, "host", "") or "").strip().lower()+ if fhost:+ finding_map.setdefault((fid, fhost), []).append(f)+ else:+ unassigned_map.setdefault(fid, []).append(f)++ # Track which unassigned findings have been attached to an entry to prevent duplicate fan-out+ consumed_unassigned: set[str] = set()for entry in self.history:- related_findings = finding_map.get(entry.module_id, [])+ entry_host = str(entry.target_host or "").strip().lower()+ related_findings = list(finding_map.get((entry.module_id, entry_host), []))++ # Attach unassigned findings for this module_id on the first matching entry+ if entry.module_id in unassigned_map:+ for uf in unassigned_map[entry.module_id]:+ uf_id = str(getattr(uf, "id", "") or id(uf))+ if uf_id not in consumed_unassigned:+ consumed_unassigned.add(uf_id)+ related_findings.append(uf)if related_findings:# One event per findingfor finding in related_findings:+ f_sev = getattr(finding, "severity", None)+ sev_val = f_sev.value if hasattr(f_sev, "value") else str(f_sev or "")events.append(ReplayEvent(timestamp = entry.timestamp,module_id = entry.module_id,@@ -186,7 +205,7 @@ class CampaignReplay:finding_title = getattr(finding, "title", ""),description = getattr(finding, "description", ""),mitre = getattr(finding, "mitre_technique", "") or "",- severity = getattr(getattr(finding, "severity", None), "value", ""),+ severity = sev_val,))else:# Module ran but no findingsdiff --git a/ares/service_intel/engine.py b/ares/service_intel/engine.pyindex 8aca21b..e8619f1 100644--- a/ares/service_intel/engine.py+++ b/ares/service_intel/engine.py@@ -242,11 +242,21 @@ class ServiceIntelEngine:host: str,ports: list[int] | None = None,jitter_ms: int = 0,+ scope_guard: Any | None = None,) -> PortScanResult:"""Async TCP connect scan. Fast, no root required.Set jitter_ms > 0 for stealth.+ Validates target against scope_guard if provided."""+ if scope_guard is not None:+ if hasattr(scope_guard, "assert_in_scope"):+ scope_guard.assert_in_scope(host, action="service_intel.scan_host")+ elif hasattr(scope_guard, "validate"):+ scope_guard.validate(host)+ elif callable(scope_guard):+ scope_guard(host)+ports = ports or self.DEFAULT_PORTSresult = PortScanResult(host=host)sem = asyncio.Semaphore(self.max_parallel)@@ -296,13 +306,14 @@ class ServiceIntelEngine:hosts: list[str],ports: list[int] | None = None,max_hosts: int = 20,+ scope_guard: Any | None = None,) -> list[PortScanResult]:- """Scan multiple hosts in parallel."""+ """Scan multiple hosts in parallel with scope enforcement."""sem = asyncio.Semaphore(max_hosts)async def scan_one(host: str) -> PortScanResult:async with sem:- return await self.scan_host(host, ports)+ return await self.scan_host(host, ports, scope_guard=scope_guard)return await asyncio.gather(*[scan_one(h) for h in hosts])diff --git a/ares/worker/cluster.py b/ares/worker/cluster.pyindex 3b1c1a6..56e4352 100644--- a/ares/worker/cluster.py+++ b/ares/worker/cluster.py@@ -104,15 +104,22 @@ class ClusterTask:timeout_s: int = 300 # 5 min default task timeoutdef to_json(self) -> str:- """Serialize to JSON - redacts sensitive credential params before writing to Redis."""+ """Serialize task to JSON for wire transport."""+ return json.dumps(asdict(self), default=str)++ def to_safe_dict(self) -> dict[str, Any]:+ """Return task dict with sensitive credential params redacted for logging/display."""d = asdict(self)- # Redact sensitive values - never store plaintext credentials in Redisif d.get("params"):d["params"] = {k: "<REDACTED>" if k in _SENSITIVE_PARAM_KEYS else vfor k, v in d["params"].items()}- return json.dumps(d, default=str)+ return d++ def to_safe_json(self) -> str:+ """Serialize to JSON with sensitive credentials redacted for audit/UI display."""+ return json.dumps(self.to_safe_dict(), default=str)@classmethoddef from_json(cls, data: str) -> ClusterTask:diff --git a/tests/unit/modules/test_coerce.py b/tests/unit/modules/test_coerce.pynew file mode 100644index 0000000..ad48fb5--- /dev/null+++ b/tests/unit/modules/test_coerce.py@@ -0,0 +1,65 @@+from __future__ import annotations++from unittest.mock import MagicMock, patch+import pytest++from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry+from ares.core.config import AresSettings+from ares.core.noise import NoiseController+from ares.modules.ad.coerce import CoerceModule+++def _make_module():+ settings = AresSettings(+ ares_secret_key="test-secret-key-min32-chars-here!!",+ ares_encryption_key="test-enc-key-min32-chars-here-xxx",+ )+ campaign = Campaign(+ name="Coerce-Test",+ operator="test_operator",+ scope=[ScopeEntry(cidr="10.0.0.0/24")],+ noise_profile=NoiseProfile.NORMAL,+ )+ noise = NoiseController(campaign)+ return CoerceModule(settings=settings, campaign=campaign, noise=noise)+++async def test_coerce_fails_does_not_emit_false_finding():+ mod = _make_module()++ # Mock all coercion methods returning False (failed)+ with patch.object(mod, "_petitpotam_sync", return_value=False), \+ patch.object(mod, "_printerbug_sync", return_value=False), \+ patch.object(mod, "_dfscoerce_sync", return_value=False):++ findings, raw = await mod.run(+ dc="10.0.0.1",+ listener_ip="10.0.0.99",+ username="testuser",+ password="testpassword",+ domain="corp.local",+ )++ assert len(findings) == 0+ assert raw["sent"] is False+ assert raw["coercion_sent"] is False+++async def test_coerce_success_emits_finding():+ mod = _make_module()++ with patch.object(mod, "_petitpotam_sync", return_value=True):+ findings, raw = await mod.run(+ dc="10.0.0.1",+ listener_ip="10.0.0.99",+ username="testuser",+ password="testpassword",+ domain="corp.local",+ )++ assert len(findings) == 1+ assert "Authentication Coercion Sent" in findings[0].title+ assert raw["sent"] is True+ assert raw["coercion_sent"] is Truediff --git a/tests/unit/modules/test_delegation_abuse.py b/tests/unit/modules/test_delegation_abuse.pynew file mode 100644index 0000000..ec5de37--- /dev/null+++ b/tests/unit/modules/test_delegation_abuse.py@@ -0,0 +1,96 @@+from __future__ import annotations++import os+from unittest.mock import MagicMock, patch+import pytest++from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry+from ares.core.config import AresSettings+from ares.core.noise import NoiseController+from ares.modules.ad.delegation_abuse import DelegationAbuseModule+++def _make_module():+ settings = AresSettings(+ ares_secret_key="test-secret-key-min32-chars-here!!",+ ares_encryption_key="test-enc-key-min32-chars-here-xxx",+ )+ campaign = Campaign(+ name="Delegation-Test",+ operator="test_operator",+ scope=[ScopeEntry(cidr="10.0.0.0/24")],+ noise_profile=NoiseProfile.NORMAL,+ )+ noise = NoiseController(campaign)+ return DelegationAbuseModule(settings=settings, campaign=campaign, noise=noise)+++def test_rbcd_attack_populates_ccache():+ mod = _make_module()++ mock_ccache_instance = MagicMock()+ mock_ccache_cls = MagicMock(return_value=mock_ccache_instance)++ mock_modules = {+ "impacket": MagicMock(),+ "impacket.krb5": MagicMock(),+ "impacket.krb5.kerberosv5": MagicMock(),+ "impacket.krb5.types": MagicMock(),+ "impacket.krb5.constants": MagicMock(),+ "impacket.krb5.ccache": MagicMock(CCache=mock_ccache_cls),+ }++ mock_modules["impacket.krb5.kerberosv5"].getKerberosTGT.return_value = (+ b"tgt", "cipher", None, b"sk"+ )+ mock_modules["impacket.krb5.kerberosv5"].getKerberosTGS.side_effect = [+ (b"tgs_s4u", "tgs_cipher", None, b"tgs_sk"),+ (b"final_tgs", "cipher2", b"old_key", b"new_key"),+ ]++ with patch.dict("sys.modules", mock_modules):+ ccache_path = mod._rbcd_attack_sync(+ dc="10.0.0.1",+ domain="corp.local",+ username="fake_svc$",+ password="Password123",+ target_computer="DC01$",+ impersonate_user="Administrator",+ target_service="cifs",+ )++ assert ccache_path != ""+ mock_ccache_instance.fromTGS.assert_called_once_with(+ b"final_tgs", b"old_key", b"new_key"+ )+ mock_ccache_instance.saveFile.assert_called_once_with(ccache_path)+ if os.path.exists(ccache_path):+ os.unlink(ccache_path)+++def test_rbcd_attack_error_classification_handles_target():+ mod = _make_module()++ mock_modules = {+ "impacket": MagicMock(),+ "impacket.krb5": MagicMock(),+ "impacket.krb5.kerberosv5": MagicMock(),+ "impacket.krb5.types": MagicMock(),+ "impacket.krb5.constants": MagicMock(),+ "impacket.krb5.ccache": MagicMock(),+ }+ mock_modules["impacket.krb5.kerberosv5"].getKerberosTGT.side_effect = ConnectionResetError("DC closed connection")++ with patch.dict("sys.modules", mock_modules):+ with pytest.raises(Exception) as exc_info:+ mod._rbcd_attack_sync(+ dc="10.0.0.1",+ domain="corp.local",+ username="fake_svc$",+ password="Password123",+ target_computer="DC01$",+ impersonate_user="Administrator",+ target_service="cifs",+ )+ # Should not raise UnboundLocalError / NameError: target+ assert "target" not in str(exc_info.value).lower() or "dc closed connection" in str(exc_info.value).lower()diff --git a/tests/unit/modules/test_scheduled_task_teardown.py b/tests/unit/modules/test_scheduled_task_teardown.pyindex dadab95..a666dd2 100644--- a/tests/unit/modules/test_scheduled_task_teardown.py+++ b/tests/unit/modules/test_scheduled_task_teardown.py@@ -115,3 +115,37 @@ async def test_scheduled_task_explicit_teardown_method():mock_delete.assert_called_once_with("10.0.0.5", "admin", "pass", "corp.local", "", "", "ManualTask")+++async def test_scheduled_task_retained_when_persist_true():+ """When persist=True is passed, task is not deleted in finally block."""+ mod = _make_module()++ mock_register = MagicMock()+ mock_delete = MagicMock()++ mock_modules = {+ "impacket": MagicMock(),+ "impacket.dcerpc": MagicMock(),+ "impacket.dcerpc.v5": MagicMock(),+ "impacket.dcerpc.v5.tsch": MagicMock(),+ }++ with patch.dict("sys.modules", mock_modules), \+ patch("ares.modules.persistence.scheduled_task._tsch_register_sync", mock_register), \+ patch("ares.modules.persistence.scheduled_task._tsch_delete_sync", mock_delete):+ findings, raw = await mod.run(+ target="10.0.0.5",+ username="admin",+ password="pass",+ domain="corp.local",+ task_name="PersistentAresTask",+ command="calc.exe",+ persist=True,+ )++ mock_register.assert_called_once()+ mock_delete.assert_not_called()+ assert raw["persistence_established"] is True+diff --git a/tests/unit/test_artifact_normalizer_pipeline.py b/tests/unit/test_artifact_normalizer_pipeline.pyindex 3146251..4060f76 100644--- a/tests/unit/test_artifact_normalizer_pipeline.py+++ b/tests/unit/test_artifact_normalizer_pipeline.py@@ -523,6 +523,25 @@ def test_kerberos_ticket_string_path(normalizer: ArtifactNormalizer, store: Artiassert len(creds) == 1assert creds[0].secret == "/tmp/golden.ccache"assert creds[0].cred_type == "kerberos_ticket"+ assert creds[0].username == "unknown"+++def test_kerberos_ticket_string_path_with_metadata(normalizer: ArtifactNormalizer, store: ArtifactStore):+ """Verify that forged_as and domain are preserved when kerberos_ticket is a string path."""+ raw = {+ "kerberos_ticket": "/tmp/golden.ccache",+ "forged_as": "Administrator",+ "domain": "CORP.LOCAL",+ }+ added = normalizer.normalize("credential.golden_ticket", ["kerberos_ticket"], raw, store)+ assert added == 1+ creds = store.credentials()+ matching = [c for c in creds if c.secret == "/tmp/golden.ccache"]+ assert len(matching) >= 1+ assert matching[-1].username == "Administrator"+ assert matching[-1].domain == "CORP.LOCAL"+ assert matching[-1].cred_type == "kerberos_ticket"+def test_acl_findings_permissions_pipeline(normalizer: ArtifactNormalizer, store: ArtifactStore):diff --git a/tests/unit/test_attack_graph_bloodhound.py b/tests/unit/test_attack_graph_bloodhound.pynew file mode 100644index 0000000..1f2f05a--- /dev/null+++ b/tests/unit/test_attack_graph_bloodhound.py@@ -0,0 +1,253 @@+import json+import zipfile+import pytest+from pathlib import Path+from ares.graph.attack_graph import AttackGraph+++def sample_bloodhound_data():+ """Generates standard BloodHound CE (v5) / legacy compatible data dictionary."""+ domain_sid = "S-1-5-21-1111111111-2222222222-3333333333"+ attacker_sid = f"{domain_sid}-1101"+ victim_sid = f"{domain_sid}-1102"+ da_group_sid = f"{domain_sid}-512"+ dc_sid = f"{domain_sid}-1000"+ ws_sid = f"{domain_sid}-1001"++ users_data = {+ "meta": {"type": "users", "count": 2},+ "data": [+ {+ "ObjectIdentifier": attacker_sid,+ "Properties": {+ "name": "[email protected]",+ "domain": "CORP.LOCAL",+ "domainsid": domain_sid,+ "admincount": False,+ "enabled": True,+ },+ "Aces": [],+ },+ {+ "ObjectIdentifier": victim_sid,+ "Properties": {+ "name": "[email protected]",+ "domain": "CORP.LOCAL",+ "domainsid": domain_sid,+ "admincount": False,+ "enabled": True,+ },+ "Aces": [+ {+ "PrincipalSID": attacker_sid,+ "PrincipalType": "User",+ "RightName": "GenericAll",+ "IsInherited": False,+ }+ ],+ },+ ],+ }++ groups_data = {+ "meta": {"type": "groups", "count": 1},+ "data": [+ {+ "ObjectIdentifier": da_group_sid,+ "Properties": {+ "name": "DOMAIN [email protected]",+ "domain": "CORP.LOCAL",+ "domainsid": domain_sid,+ "admincount": True,+ },+ "Members": [+ {+ "MemberId": victim_sid,+ "MemberType": "User",+ }+ ],+ "Aces": [],+ }+ ],+ }++ computers_data = {+ "meta": {"type": "computers", "count": 2},+ "data": [+ {+ "ObjectIdentifier": dc_sid,+ "Properties": {+ "name": "DC01.CORP.LOCAL",+ "domain": "CORP.LOCAL",+ "domainsid": domain_sid,+ "isdc": True,+ "enabled": True,+ },+ "Aces": [+ {+ "PrincipalSID": da_group_sid,+ "PrincipalType": "Group",+ "RightName": "GenericAll",+ "IsInherited": False,+ }+ ],+ },+ {+ "ObjectIdentifier": ws_sid,+ "Properties": {+ "name": "WS01.CORP.LOCAL",+ "domain": "CORP.LOCAL",+ "domainsid": domain_sid,+ "isdc": False,+ "enabled": True,+ },+ "LocalAdmins": {+ "Collected": True,+ "FailureReason": None,+ "Results": [+ {+ "ObjectIdentifier": attacker_sid,+ "ObjectType": "User",+ }+ ],+ },+ "Sessions": {+ "Collected": True,+ "FailureReason": None,+ "Results": [+ {+ "UserId": victim_sid,+ "ComputerId": ws_sid,+ }+ ],+ },+ "Aces": [],+ },+ ],+ }++ domains_data = {+ "meta": {"type": "domains", "count": 1},+ "data": [+ {+ "ObjectIdentifier": domain_sid,+ "Properties": {+ "name": "CORP.LOCAL",+ "domain": "CORP.LOCAL",+ },+ "Aces": [+ {+ "PrincipalSID": victim_sid,+ "PrincipalType": "User",+ "RightName": "DCSync",+ "IsInherited": False,+ }+ ],+ }+ ],+ }++ return {+ "users": users_data,+ "groups": groups_data,+ "computers": computers_data,+ "domains": domains_data,+ }+++def test_bloodhound_ingest_sid_resolution_attack_path(tmp_path, sample_bloodhound_data):+ """+ Empirically verifies that BloodHound ACEs referencing SIDs resolve+ to canonical user/group nodes, correctly forming the attack path to DA.+ """+ u_file = tmp_path / "users.json"+ g_file = tmp_path / "groups.json"+ u_file.write_text(json.dumps(sample_bloodhound_data["users"]), encoding="utf-8")+ g_file.write_text(json.dumps(sample_bloodhound_data["groups"]), encoding="utf-8")++ ag = AttackGraph()+ res = ag.ingest_bloodhound(str(tmp_path))+ assert res["nodes_added"] > 0+ assert res["edges_added"] > 0++ # Shortest path from ATTACKER to Domain Admins must succeed+ path = ag.shortest_path_to_da("user:[email protected]")+ assert path is not None+ assert path["path_length"] == 3+ assert path["start"] == "[email protected]"+ assert path["end"] == "DOMAIN [email protected]"+ # Ensure steps detail the hops accurately+ assert path["steps"][0]["from"] == "[email protected]"+ assert path["steps"][0]["to"] == "[email protected]"+ assert path["steps"][1]["from"] == "[email protected]"+ assert path["steps"][1]["to"] == "DOMAIN [email protected]"+++def test_bloodhound_ingest_sessions_and_local_admins(tmp_path, sample_bloodhound_data):+ """+ Verifies that LocalAdmins (AdminTo) and active sessions (HasSession)+ are ingested and allow path traversal from compromised workstation to DA.+ """+ for name, data in sample_bloodhound_data.items():+ (tmp_path / f"{name}.json").write_text(json.dumps(data), encoding="utf-8")++ ag = AttackGraph()+ res = ag.ingest_bloodhound(str(tmp_path))+ assert res["nodes_added"] > 0+ assert res["edges_added"] > 0++ # WS01 should have admin_to edge from ATTACKER+ attacker_node = "user:[email protected]"+ ws_node = "computer:WS01.CORP.LOCAL"+ victim_node = "user:[email protected]"++ assert ag._g.has_edge(attacker_node, ws_node)+ edge_data = ag._g.get_edge_data(attacker_node, ws_node)+ assert edge_data.get("label") == "admin_to"++ # WS01 should have has_session edge to VICTIM+ assert ag._g.has_edge(ws_node, victim_node)+ session_edge = ag._g.get_edge_data(ws_node, victim_node)+ assert session_edge.get("label") == "has_session"+++def test_bloodhound_zip_archive_ingestion(tmp_path, sample_bloodhound_data):+ """+ Verifies that a SharpHound .zip archive is transparently ingested without extraction.+ """+ zip_path = tmp_path / "bloodhound_collection.zip"+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:+ for name, data in sample_bloodhound_data.items():+ zf.writestr(f"{name}.json", json.dumps(data))++ ag = AttackGraph()+ res = ag.ingest_bloodhound(str(zip_path))+ assert res["nodes_added"] > 0+ assert res["edges_added"] > 0+ assert res["file_count"] == 4++ path = ag.shortest_path_to_da("user:[email protected]")+ assert path is not None+ assert path["end"] == "DOMAIN [email protected]"+++def test_bloodhound_two_pass_order_independence(tmp_path, sample_bloodhound_data):+ """+ Verifies that file ordering does not break SID resolution:+ groups.json loaded before users.json must still connect perfectly.+ """+ folder = tmp_path / "inverted_order"+ folder.mkdir()+ # Name files so groups sorts first+ (folder / "01_groups.json").write_text(json.dumps(sample_bloodhound_data["groups"]), encoding="utf-8")+ (folder / "02_users.json").write_text(json.dumps(sample_bloodhound_data["users"]), encoding="utf-8")++ ag = AttackGraph()+ res = ag.ingest_bloodhound(str(folder))+ assert res["file_count"] == 2++ path = ag.shortest_path_to_da("user:[email protected]")+ assert path is not None+ assert path["start"] == "[email protected]"+ assert path["end"] == "DOMAIN [email protected]"diff --git a/tests/unit/test_cloud_scope_guard.py b/tests/unit/test_cloud_scope_guard.pyindex 3bad7d8..64014eb 100644--- a/tests/unit/test_cloud_scope_guard.py+++ b/tests/unit/test_cloud_scope_guard.py@@ -179,3 +179,13 @@ class TestCloudModulesEnforcement:with pytest.raises(ScopeViolationError):await mod.run(project_id="gcp-rogue-project")++ async def test_cloud_identity_federation_scope_enforcement(self, dummy_settings, dummy_noise):+ from ares.modules.cloud.identity_federation import CloudIdentityFederationModule++ cloud_scope = CloudScope(azure_tenant_ids=["tenant-corp-uuid"])+ campaign = Campaign(name="Federation Restricted", cloud_scope=cloud_scope)+ mod = CloudIdentityFederationModule(dummy_settings, campaign, dummy_noise)++ with pytest.raises(ScopeViolationError):+ await mod.run(tenant_id="tenant-attacker-uuid")diff --git a/tests/unit/test_cluster_task_serialization.py b/tests/unit/test_cluster_task_serialization.pynew file mode 100644index 0000000..074d81c--- /dev/null+++ b/tests/unit/test_cluster_task_serialization.py@@ -0,0 +1,51 @@+from __future__ import annotations++import json+from ares.worker.cluster import ClusterTask, TaskState+++def test_cluster_task_wire_serialization_preserves_credentials():+ task = ClusterTask(+ module_id="ad.kerberoast",+ campaign_id="camp-123",+ params={+ "dc": "10.0.0.1",+ "username": "svc_admin",+ "password": "SecretPassword123!",+ "nt_hash": "aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0",+ },+ priority=1,+ )++ serialized = task.to_json()+ assert "SecretPassword123!" in serialized+ assert "31d6cfe0d16ae931b73c59d7e0c089c0" in serialized++ restored = ClusterTask.from_json(serialized)+ assert restored.params["password"] == "SecretPassword123!"+ assert restored.params["nt_hash"] == "aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0"+ assert restored.module_id == "ad.kerberoast"+++def test_cluster_task_safe_display_redacts_credentials():+ task = ClusterTask(+ module_id="ad.kerberoast",+ campaign_id="camp-123",+ params={+ "dc": "10.0.0.1",+ "username": "svc_admin",+ "password": "SecretPassword123!",+ "nt_hash": "aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0",+ },+ priority=1,+ )++ safe_dict = task.to_safe_dict()+ assert safe_dict["params"]["password"] == "<REDACTED>"+ assert safe_dict["params"]["nt_hash"] == "<REDACTED>"+ assert safe_dict["params"]["username"] == "svc_admin"+ assert safe_dict["params"]["dc"] == "10.0.0.1"++ safe_json = task.to_safe_json()+ assert "<REDACTED>" in safe_json+ assert "SecretPassword123!" not in safe_jsondiff --git a/tests/unit/test_executor_pivot_lateral.py b/tests/unit/test_executor_pivot_lateral.pyindex 7d758b0..4895f9d 100644--- a/tests/unit/test_executor_pivot_lateral.py+++ b/tests/unit/test_executor_pivot_lateral.py@@ -180,6 +180,37 @@ class TestRemoteExecutor:assert code == 1+ @pytest.mark.asyncio+ async def test_run_lateral_inherits_campaign(self):+ from ares.execution.executor import RemoteExecutor+ from ares.core.campaign import Campaign++ mock_campaign = Campaign(name="ScopedCampaign", operator="test_op")+ ex = RemoteExecutor(operator="test_op", campaign=mock_campaign)++ mock_psexec = MagicMock()+ mock_psexec.execute = AsyncMock(return_value=MagicMock(stdout="ok", stderr="", success=True))++ mock_winrm = MagicMock()+ mock_winrm.move = AsyncMock(return_value=MagicMock(output="ok", error="", success=True))++ mock_wmiexec = MagicMock()+ mock_wmiexec.execute = AsyncMock(return_value=MagicMock(stdout="ok", stderr="", success=True))++ with patch("ares.modules.lateral.modules.PsExecLateral", return_value=mock_psexec) as mock_psexec_cls, \+ patch("ares.modules.lateral.modules.WinRMLateral", return_value=mock_winrm) as mock_winrm_cls, \+ patch("ares.modules.lateral.modules.WMIExecLateral", return_value=mock_wmiexec) as mock_wmiexec_cls, \+ patch.dict("sys.modules", {"impacket": MagicMock(), "winrm": MagicMock()}):++ await ex._run_psexec("10.0.0.1", "whoami", "admin", "CORP", "pass")+ assert mock_psexec_cls.call_args[1]["campaign"] == mock_campaign++ await ex._run_winrm("10.0.0.1", "whoami", "admin", "CORP", "pass")+ assert mock_winrm_cls.call_args[1]["campaign"] == mock_campaign++ await ex._run_wmiexec("10.0.0.1", "whoami", "admin", "CORP", "pass")+ assert mock_wmiexec_cls.call_args[1]["campaign"] == mock_campaign+def test_execution_result_defaults(self):from ares.execution.executor import ExecutionResult, ExecutionMethod, PayloadTyper = ExecutionResult(target="10.0.0.1", method=ExecutionMethod.SSH)@@ -462,6 +493,27 @@ class TestNetworkModel:assert "campaign_id" in dassert "hosts" in d+ def test_pivot_route_requires_intermediate_pivots(self):+ from ares.network.model import NetworkModel+ model = NetworkModel(name="Test Network")+ s1 = model.add_subnet("10.0.0.0/24", "Subnet 1")+ s2 = model.add_subnet("10.1.0.0/24", "Subnet 2")++ h_source = s1.add_host("10.0.0.10", hostname="attacker")+ h_inter = s1.add_host("10.0.0.20", hostname="dual_homed")+ h_inter.reachable.append("10.1.0.50")+ h_target = s2.add_host("10.1.0.50", hostname="internal_dc")++ # When dual_homed is NOT a pivot, route must NOT traverse it+ route_unowned = model.pivot_route("10.0.0.10", "10.1.0.50")+ assert route_unowned is None++ # When dual_homed is compromised / marked as pivot, route succeeds+ h_inter.is_pivot = True+ route_owned = model.pivot_route("10.0.0.10", "10.1.0.50")+ assert route_owned == ["10.0.0.10", "10.0.0.20", "10.1.0.50"]++# ── credential/reuse.py - WinRM validator ────────────────────────────────────diff --git a/tests/unit/test_honesty_gates.py b/tests/unit/test_honesty_gates.pyindex 1b54a27..2be7002 100644--- a/tests/unit/test_honesty_gates.py+++ b/tests/unit/test_honesty_gates.py@@ -455,6 +455,15 @@ class TestGate6VaultWriteGuard:assert res is not Falseassert len(vault.all()) == 1+ def test_cleartext_password_with_dollar_prefix_allowed(self):+ vault = CredentialVault(encryption_key=None)+ valid_password = "$uperSecretPassword2026!"+ res = vault.add(username="corp_admin", secret=valid_password, cred_type=CredentialType.CLEARTEXT)+ assert res is not False+ assert len(vault.all()) == 1+ cred = vault.all()[0]+ assert vault.reveal(cred.id) == valid_password+def test_credential_valid_with_io_evidence_allowed(self):from ares.core.context import ExecutionContextvault = CredentialVault(encryption_key=None)diff --git a/tests/unit/test_phase2_comprehensive_audit.py b/tests/unit/test_phase2_comprehensive_audit.pynew file mode 100644index 0000000..cd9a405--- /dev/null+++ b/tests/unit/test_phase2_comprehensive_audit.py@@ -0,0 +1,173 @@+"""+tests/unit/test_phase2_comprehensive_audit.py+Verification suite for Phase 2 comprehensive audit:+- Hypothesis 1: Replay event attribution and deduplication by host+- Hypothesis 2: Attack graph multi-target DA pathfinding and UTF-8 DOT output+- Hypothesis 3: Collaboration target locking active_targets multi-lock state preservation+- Hypothesis 4: Service intelligence declarative scope enforcement+- Hypothesis 5: Scrubbing disabled & phantom module references across templates and KB+"""+import pytest+from unittest.mock import MagicMock+from pathlib import Path+++# ── Hypothesis 1: Replay Event Attribution & Deduplication ───────────────────++def test_replay_multihost_finding_attribution():+ from ares.replay.engine import CampaignReplay, ReplayMode+ from ares.state.target_state import AttackHistoryEntry++ h1 = AttackHistoryEntry(module_id="network.port_scan", target_host="10.0.0.1", timestamp=100.0, success=True)+ h2 = AttackHistoryEntry(module_id="network.port_scan", target_host="10.0.0.2", timestamp=200.0, success=True)++ f1 = MagicMock()+ f1.module_id = "network.port_scan"+ f1.title = "Port 80 Open on 10.0.0.1"+ f1.host = "10.0.0.1"+ f1.severity.value = "low"++ f2 = MagicMock()+ f2.module_id = "network.port_scan"+ f2.title = "Port 445 Open on 10.0.0.2"+ f2.host = "10.0.0.2"+ f2.severity.value = "medium"++ replay = CampaignReplay(campaign_id="test_camp", history=[h1, h2], findings=[f1, f2])+ timeline = replay.build_timeline()++ assert len(timeline) == 2, f"Expected exactly 2 events without duplication, got {len(timeline)}"+ assert timeline[0].target == "10.0.0.1"+ assert timeline[0].finding_title == "Port 80 Open on 10.0.0.1"+ assert timeline[1].target == "10.0.0.2"+ assert timeline[1].finding_title == "Port 445 Open on 10.0.0.2"+++def test_replay_unassigned_finding_attached_once():+ from ares.replay.engine import CampaignReplay+ from ares.state.target_state import AttackHistoryEntry++ h1 = AttackHistoryEntry(module_id="ad.domain_enum", target_host="dc01", timestamp=100.0, success=True)+ h2 = AttackHistoryEntry(module_id="ad.domain_enum", target_host="dc02", timestamp=200.0, success=True)++ # Domain finding without a specific host+ f = MagicMock()+ f.id = "f-domain-01"+ f.module_id = "ad.domain_enum"+ f.title = "Domain Password Policy Weak"+ f.host = ""+ f.severity.value = "high"++ replay = CampaignReplay(campaign_id="test_camp", history=[h1, h2], findings=[f])+ timeline = replay.build_timeline()++ assert len(timeline) == 2+ # First entry receives the finding, second entry is marked clean run+ assert timeline[0].finding_title == "Domain Password Policy Weak"+ assert timeline[1].finding_title == ""+++# ── Hypothesis 2: Attack Graph Multi-Target DA & UTF-8 DOT ───────────────────++def test_attack_graph_multi_target_da_pathfinding():+ from ares.graph.attack_graph import AttackGraph, GraphNode, GraphEdge++ g = AttackGraph()+ g._add_node(GraphNode(node_id="user:alice", label="alice", node_type="user"))+ # Two DA groups: DA_SUB unreachable, DA_ROOT reachable+ g._add_node(GraphNode(node_id="group:DA_SUB", label="DOMAIN ADMINS SUB", node_type="group", is_target=True))+ g._add_node(GraphNode(node_id="group:DA_ROOT", label="DOMAIN ADMINS ROOT", node_type="group", is_target=True))+ g._add_edge(GraphEdge(source="user:alice", target="group:DA_ROOT", edge_type="member_of", weight=1.0))++ report = g.shortest_path_to_da("user:alice")+ assert report is not None, "Failed to find path to DA when a reachable DA group exists"+ assert report["end"] == "DOMAIN ADMINS ROOT"+ assert report["total_score"] == 1.0+++def test_attack_graph_to_dot_utf8(tmp_path: Path):+ from ares.graph.attack_graph import AttackGraph, GraphNode++ g = AttackGraph()+ # Cyrillic and international characters in Active Directory objects+ g._add_node(GraphNode(node_id="user:админ", label="Иван Иванов", node_type="user"))+ dot_file = tmp_path / "test_graph.dot"+ g.to_dot(str(dot_file))++ content = dot_file.read_text(encoding="utf-8")+ assert "Иван Иванов" in content+ assert "user:админ" in content+++# ── Hypothesis 3: Collaboration Multi-Lock State Preservation ─────────────────++def test_collab_target_lock_active_targets_preservation():+ from ares.collab.manager import CollaborationManager, OperatorRole++ cm = CollaborationManager("camp-collab-01")+ op = cm.register_operator("op_test", "alice", role=OperatorRole.OPERATOR)++ ok1, lock1 = cm.acquire_lock("op_test", "host_a", "lateral.psexec")+ ok2, lock2 = cm.acquire_lock("op_test", "host_a", "windows.lsass_dump")+ assert ok1 and ok2+ assert op.active_targets == ["host_a"]++ # Releasing first lock should keep host_a because second lock is active+ cm.release_lock(lock1)+ assert op.active_targets == ["host_a"], "active_targets prematurely cleared while another lock was active"+ assert cm.is_locked("host_a") is True++ # Releasing second lock should now clear host_a+ cm.release_lock(lock2)+ assert op.active_targets == []+ assert cm.is_locked("host_a") is False+++# ── Hypothesis 4: Service Intelligence Scope Enforcement ──────────────────────++async def test_service_intel_scope_guard_enforcement():+ from ares.service_intel.engine import ServiceIntelEngine+ from ares.core.campaign import Campaign, ScopeEntry+ from ares.core.noise import ScopeGuard+ from ares.core.errors import ScopeViolationError++ campaign = Campaign(+ id="test_scope",+ name="Test Scope",+ scope=[ScopeEntry(cidr="192.168.1.0/24")],+ )+ guard = ScopeGuard(campaign)+ engine = ServiceIntelEngine()++ # In-scope check does not raise ScopeViolationError+ assert guard.check("192.168.1.50") is True++ # Out-of-scope check raises ScopeViolationError and blocks connect+ with pytest.raises(ScopeViolationError):+ await engine.scan_host("10.50.50.50", ports=[80], scope_guard=guard)+++# ── Hypothesis 5: Catalog & Template Incoherence Scrubbing ────────────────────++def test_catalog_and_template_scrubbed_from_disabled_modules():+ from ares.core.engine import CAMPAIGN_TEMPLATES+ from ares.marketplace.installer import _BUNDLED_INDEX+ from ares.knowledge.base import _KB_ENTRIES++ # 1. assumed_breach template uses windows.lsa_secrets, not windows.dpapi+ win_template = CAMPAIGN_TEMPLATES["assumed_breach"]+ all_modules = [m for stage in win_template["stages"] for m in stage["modules"]]+ assert "windows.dpapi" not in all_modules+ assert "windows.lsa_secrets" in all_modules++ # 2. _BUNDLED_INDEX does not list disabled windows.token_impersonation+ bundled_ids = [m["id"] for m in _BUNDLED_INDEX["modules"]]+ assert "windows.token_impersonation" not in bundled_ids+ assert "windows.lsass_dump" in bundled_ids+ assert "windows.lsa_secrets" in bundled_ids++ # 3. _KB_ENTRIES points to windows.lsa_secrets instead of windows.dpapi+ kb_modules = [m for entry in _KB_ENTRIES for m in entry.attack_modules]+ assert "windows.dpapi" not in kb_modules+ assert "windows.lsa_secrets" in kb_modules