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
feat(identity): implement Wave 4 Fine-Grained Password Policies, OAuth device code audit, and cloud LOTS exfiltration resilience
Mafifrizi42baf792b73b
diff --git a/ares/modules/credential/pass_spray.py b/ares/modules/credential/pass_spray.pyindex 3cdc63d..9e4e1e4 100644--- a/ares/modules/credential/pass_spray.py+++ b/ares/modules/credential/pass_spray.py@@ -102,11 +102,17 @@ def query_password_policy(except (ValueError, TypeError):return 30 # safe default- threshold = int(str(entry.lockoutThreshold)) if hasattr(entry, "lockoutThreshold") else 0- duration = _ad_duration_to_minutes(entry.lockoutDuration) if hasattr(entry, "lockoutDuration") else 30- window = _ad_duration_to_minutes(entry.lockOutObservationWindow) if hasattr(entry, "lockOutObservationWindow") else 30- min_len = int(str(entry.minPwdLength)) if hasattr(entry, "minPwdLength") else 7- history = int(str(entry.pwdHistoryLength)) if hasattr(entry, "pwdHistoryLength") else 24+ def _safe_int(val: Any, default: int = 0) -> int:+ try:+ return int(str(val))+ except (ValueError, TypeError):+ return default++ threshold = _safe_int(getattr(entry, "lockoutThreshold", 0), 0)+ duration = _ad_duration_to_minutes(getattr(entry, "lockoutDuration", 30))+ window = _ad_duration_to_minutes(getattr(entry, "lockOutObservationWindow", 30))+ min_len = _safe_int(getattr(entry, "minPwdLength", 7), 7)+ history = _safe_int(getattr(entry, "pwdHistoryLength", 24), 24)# Calculate safe spray parametersif threshold == 0:@@ -127,6 +133,72 @@ def query_password_policy("safe_spray_delay_s": round(safe_delay, 1),"safe_attempts_per_user": safe_attempts,})++ # Check Fine-Grained Password Policies (PSO)+ pso_policies: list[dict[str, Any]] = []+ try:+ pso_dn = f"CN=Password Settings Objects,CN=System,{base_dn}"+ conn.search(+ pso_dn,+ "(objectClass=msDS-PasswordSettings)",+ search_scope=ldap3.SUBTREE,+ attributes=[+ "cn",+ "msDS-LockoutThreshold",+ "msDS-LockoutDuration",+ "msDS-LockoutObservationWindow",+ "msDS-MinimumPasswordLength",+ "msDS-PasswordSettingsPrecedence",+ ],+ )+ for pso_entry in conn.entries:+ p_name = str(getattr(pso_entry, "cn", "PSO"))+ p_thresh = _safe_int(getattr(pso_entry, "msDS-LockoutThreshold", 0), 0)+ p_dur = _ad_duration_to_minutes(getattr(pso_entry, "msDS-LockoutDuration", 0))+ p_win = _ad_duration_to_minutes(getattr(pso_entry, "msDS-LockoutObservationWindow", 0))+ p_min_len = _safe_int(getattr(pso_entry, "msDS-MinimumPasswordLength", 7), 7)+ pso_policies.append({+ "name": p_name,+ "lockout_threshold": p_thresh,+ "lockout_duration_min": p_dur,+ "observation_window_min": p_win,+ "min_password_length": p_min_len,+ })+ except Exception:+ pso_policies = []++ # Check Entra ID / Azure AD Hybrid Identity Synchronization+ hybrid_sync_detected = False+ try:+ conn.search(+ base_dn,+ "(&(objectClass=user)(msDS-ExternalDirectoryObjectId=*))",+ search_scope=ldap3.SUBTREE,+ attributes=["sAMAccountName", "msDS-ExternalDirectoryObjectId"],+ size_limit=5,+ )+ if conn.entries:+ hybrid_sync_detected = True+ except Exception:+ hybrid_sync_detected = False++ if pso_policies:+ min_pso_threshold = min(+ (p["lockout_threshold"] for p in pso_policies if p["lockout_threshold"] > 0),+ default=0,+ )+ if min_pso_threshold > 0:+ effective_threshold = min(threshold, min_pso_threshold) if threshold > 0 else min_pso_threshold+ safe_attempts = max(1, effective_threshold - 2)+ safe_delay = (window * 60 * 1.5) / max(safe_attempts, 1)+ result["safe_attempts_per_user"] = safe_attempts+ result["safe_spray_delay_s"] = round(safe_delay, 1)++ result.update({+ "pso_policies": pso_policies,+ "pso_enforced": bool(pso_policies),+ "hybrid_sync_detected": hybrid_sync_detected,+ })conn.unbind()except ImportError:result["error"] = "ldap3 not installed"@@ -499,6 +571,60 @@ class PassSprayModule(BaseModule[PassSprayParams, ModuleResult]):attempts = 0lockout_detected = False+ # Pre-flight Fine-Grained Password Policy & Hybrid Sync Posture Check+ policy_info = kwargs.get("policy_info")+ if policy_info is None and domain and target and kwargs.get("query_policy", False):+ try:+ policy_info = query_password_policy(+ target, domain, kwargs.get("policy_user", ""), kwargs.get("policy_password", "")+ )+ except Exception:+ policy_info = None++ if policy_info and policy_info.get("pso_enforced"):+ pso_list = policy_info.get("pso_policies", [])+ min_thresh = min(+ (p["lockout_threshold"] for p in pso_list if p["lockout_threshold"] > 0),+ default=0,+ )+ self.finding(+ title=f"Fine-Grained Password Policy (PSO) Enforced on Domain {domain}",+ description=(+ f"Active Directory Fine-Grained Password Policy (PSO) detected on {domain} "+ f"with lockout threshold of {min_thresh} attempt(s). "+ "Spray pacing dynamically throttled to prevent accidental account lockouts."+ ),+ severity=Severity.LOW,+ mitre_technique="T1110.003",+ mitre_tactic="Credential Access",+ evidence={"target": target, "domain": domain, "pso_policies": pso_list},+ remediation=(+ "Maintain strict Fine-Grained Password Policies on administrative groups. "+ "Ensure service accounts and standard users are segregated with dedicated PSOs."+ ),+ host=target,+ confidence=0.95,+ )++ if policy_info and policy_info.get("hybrid_sync_detected"):+ self.finding(+ title=f"Entra ID Hybrid Sync & Cloud Smart Lockout Active on {domain}",+ description=(+ f"Hybrid identity synchronization detected on domain {domain}. "+ "Cloud-synced accounts are protected by Entra ID Smart Lockout and Identity Protection."+ ),+ severity=Severity.LOW,+ mitre_technique="T1110.003",+ mitre_tactic="Credential Access",+ evidence={"target": target, "domain": domain, "hybrid_sync": True},+ remediation=(+ "Ensure Entra ID Password Protection is deployed to on-premises Domain Controllers "+ "to block known compromised passwords across hybrid infrastructure."+ ),+ host=target,+ confidence=0.9,+ )+for password in passwords:if lockout_detected:break@@ -658,5 +784,11 @@ class PassSprayModule(BaseModule[PassSprayParams, ModuleResult]):],"locked_accounts": locked_accounts,"lockout_detected": lockout_detected,+ "pso_enforced": bool(policy_info and policy_info.get("pso_enforced")),+ "pso_policies": policy_info.get("pso_policies", []) if policy_info else [],+ "hybrid_sync_detected": bool(policy_info and policy_info.get("hybrid_sync_detected")),+ "safe_attempts_per_user": (+ policy_info.get("safe_attempts_per_user", max_per_user) if policy_info else max_per_user+ ),}return self._findings[:], rawdiff --git a/ares/modules/credential/reuse.py b/ares/modules/credential/reuse.pyindex cb902b9..ad1eae9 100644--- a/ares/modules/credential/reuse.py+++ b/ares/modules/credential/reuse.py@@ -10,6 +10,7 @@ MITRE ATT&CK:"""from __future__ import annotations+import asynciofrom typing import Anyfrom ares.core.campaign import Finding, Severity@@ -31,6 +32,64 @@ from ares.core.tracing import trace_modulelogger = get_logger("ares.modules.credential.reuse")+def _audit_oauth_posture_sync(target: str) -> dict[str, Any]:+ """+ Non-destructive probe of OAuth 2.0 Device Code Flow / Identity Posture.+ Checks whether target exposes or permits unrestricted Device Authorization Grant (T1528 / T1550).+ """+ import urllib.request+ import urllib.error+ import ssl++ result: dict[str, Any] = {+ "device_code_endpoint_active": False,+ "device_code_permitted": False,+ "checked_endpoint": None,+ }++ clean_target = target.strip().lower()+ ctx = ssl.create_default_context()+ ctx.check_hostname = False+ ctx.verify_mode = ssl.CERT_NONE++ probe_urls: list[str] = []+ if "microsoftonline.com" in clean_target:+ probe_urls.append(f"https://{clean_target}/common/oauth2/v2.0/devicecode")+ elif "." in clean_target:+ 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:+ probe_urls.append(f"https://login.microsoftonline.com/{clean_target}/oauth2/v2.0/devicecode")++ for url in probe_urls:+ try:+ req = urllib.request.Request(+ url,+ headers={"User-Agent": "ARES-Identity-Posture/2026.1"},+ data=b"client_id=04b07795-8ddb-461a-bbee-02f9e1bf7b46&scope=openid",+ method="POST",+ )+ with urllib.request.urlopen(req, timeout=3, context=ctx) as resp:+ status = resp.getcode()+ if status in (200, 400):+ body = resp.read().decode("utf-8", errors="ignore")+ result["checked_endpoint"] = url+ result["device_code_endpoint_active"] = True+ if "device_code" in body or "user_code" in body or "error" in body:+ result["device_code_permitted"] = True+ break+ except urllib.error.HTTPError as exc:+ if exc.code in (400, 405):+ result["checked_endpoint"] = url+ result["device_code_endpoint_active"] = True+ result["device_code_permitted"] = True+ break+ except Exception:+ continue++ return result++@module_contract(permissions=[NetworkPermission(ports=[22, 389, 445, 636, 3389, 5985, 5986], protocols=["tcp"]),@@ -194,6 +253,31 @@ class CredentialReuseModule(BaseModule[CredentialReuseParams, ModuleResult]):if vault is None:return [], {"error": "no_vault_provided"}+ # Audit OAuth 2.0 Device Code Flow / Modern Identity Posture+ loop = asyncio.get_running_loop()+ oauth_audit_func = kwargs.get("oauth_audit_func") or _audit_oauth_posture_sync+ oauth_data = await loop.run_in_executor(None, oauth_audit_func, target)++ if oauth_data.get("device_code_permitted"):+ self.finding(+ title=f"OAuth 2.0 Device Code Flow Vector Permitted on {target}",+ description=(+ f"OAuth 2.0 Device Authorization Grant (Device Code Flow) endpoint is active and "+ f"reachable for target {target} ({oauth_data.get('checked_endpoint')}). "+ "Unrestricted Device Code Flow exposes the tenant to device code phishing attacks "+ "(T1528 / T1550) that can bypass traditional MFA."+ ),+ severity=Severity.MEDIUM,+ confidence=0.9,+ host=target,+ mitre_technique="T1528",+ mitre_tactic="Credential Access",+ remediation=(+ "Implement Conditional Access policy to block Device Code Flow for non-compliant "+ "or unmanaged devices. Restrict device authorization grants to corporate IP ranges."+ ),+ )+try:from ares.credential.reuse import ReuseEngine, ReuseProtocolengine = ReuseEngine(vault=vault)@@ -222,6 +306,8 @@ class CredentialReuseModule(BaseModule[CredentialReuseParams, ModuleResult]):"valid_credentials": valid,"owned_hosts": [target] if valid else [],"total_attempts": len(results),+ "oauth_device_code_permitted": oauth_data.get("device_code_permitted", False),+ "oauth_device_code_endpoint": oauth_data.get("checked_endpoint"),}except Exception as exc:diff --git a/ares/modules/exfil/staged_collection.py b/ares/modules/exfil/staged_collection.pyindex 118656f..a13fc93 100644--- a/ares/modules/exfil/staged_collection.py+++ b/ares/modules/exfil/staged_collection.py@@ -41,6 +41,54 @@ _COLLECTION_PATTERNS = ["*wallet.dat", "*.wallet",]+def _audit_lots_egress_sync(target: str) -> dict[str, Any]:+ """+ Non-destructive audit of Living-off-the-Trusted-Services (LOTS) cloud egress paths+ and enterprise Tenant Restrictions enforcement (T1567.002).+ """+ import urllib.request+ import urllib.error+ import ssl++ cloud_endpoints = {+ "m365_graph": "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",+ "aws_s3": "https://s3.amazonaws.com",+ "azure_blob": "https://blob.core.windows.net",+ }++ result: dict[str, Any] = {+ "lots_routes_open": [],+ "tenant_restrictions_enforced": False,+ "checked_endpoints": list(cloud_endpoints.keys()),+ }++ ctx = ssl.create_default_context()+ ctx.check_hostname = False+ ctx.verify_mode = ssl.CERT_NONE++ for service_name, url in cloud_endpoints.items():+ try:+ req = urllib.request.Request(+ url,+ headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ARES-Egress-Audit/2026.1"},+ method="HEAD",+ )+ with urllib.request.urlopen(req, timeout=3, context=ctx) as resp:+ headers_dict = dict(resp.headers)+ for header_key in headers_dict:+ hl = header_key.lower()+ if "restrict-access" in hl or "sec-ms-gpo" in hl or "tenant" in hl:+ result["tenant_restrictions_enforced"] = True+ result["lots_routes_open"].append(service_name)+ except urllib.error.HTTPError as exc:+ if exc.code in (400, 401, 403, 405):+ result["lots_routes_open"].append(service_name)+ except Exception:+ continue++ return result++@module_contract(permissions=[NetworkPermission(ports=[22, 135, 445], protocols=["tcp"]),@@ -305,8 +353,38 @@ class StagedCollectionModule(BaseModule):host=target, confidence=0.9,)- raw = {"target": target, "files_found": hits,- "search_paths": search_paths, "total": len(hits)}+ lots_audit_func = kwargs.get("lots_audit_func") or _audit_lots_egress_sync+ lots_data = await loop.run_in_executor(None, lots_audit_func, target)++ if lots_data.get("lots_routes_open") and not lots_data.get("tenant_restrictions_enforced"):+ self.finding(+ title=f"Cloud LOTS Exfiltration Route Open (Missing Tenant Restrictions) on {target}",+ description=(+ f"Outbound egress to trusted cloud infrastructure ({', '.join(lots_data['lots_routes_open'])}) "+ f"is permitted from {target} without corporate Tenant Restrictions. "+ "Attackers staging sensitive data can exfiltrate directly to external/attacker-controlled "+ "cloud tenants (T1567.002) bypassing perimeter network defenses."+ ),+ severity=Severity.HIGH,+ confidence=0.85,+ host=target,+ mitre_technique="T1567.002",+ mitre_tactic="Exfiltration",+ remediation=(+ "Implement TLS inspection on corporate egress gateways and configure Tenant Restriction v2 "+ "headers ('Restrict-Access-To-Tenants' and 'Restrict-Access-Context') to block unauthorized "+ "data exfiltration to external cloud tenants."+ ),+ )++ raw = {+ "target": target,+ "files_found": hits,+ "search_paths": search_paths,+ "total": len(hits),+ "lots_routes_open": lots_data.get("lots_routes_open", []),+ "tenant_restrictions_enforced": lots_data.get("tenant_restrictions_enforced", False),+ }raw["sensitive_file_paths"] = raw.get("files_staged", []) # OUTPUTS keyraw["collection_inventory"] = raw.get("files_staged", []) # OUTPUTS keyreturn self._findings[:], rawdiff --git a/tests/unit/test_identity_exfil_resilience.py b/tests/unit/test_identity_exfil_resilience.pynew file mode 100644index 0000000..86a3909--- /dev/null+++ b/tests/unit/test_identity_exfil_resilience.py@@ -0,0 +1,408 @@+"""+Unit test suite for Wave 4: Modern Identity & Adaptive Exfiltration (2026 - 2031).+Validates:+ - Active Directory Fine-Grained Password Policies (FGPP / PSO via msDS-PasswordSettings).+ - Entra ID Hybrid Identity synchronization and Smart Lockout detection.+ - Safe spray attempts calculation and throttling under strict PSOs.+ - OAuth 2.0 Device Code Flow posture audit (T1528 / T1550).+ - Cloud Living-off-the-Trusted-Services (LOTS) egress path audit and Tenant Restrictions enforcement (T1567.002).+"""+from __future__ import annotations++import asyncio+from unittest.mock import AsyncMock, MagicMock, patch+import pytest++from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry, Severity+from ares.core.config import AresSettings+from ares.core.noise import NoiseController+from ares.modules.credential.pass_spray import (+ PassSprayModule,+ query_password_policy,+)+from ares.modules.credential.reuse import (+ CredentialReuseModule,+ _audit_oauth_posture_sync,+)+from ares.modules.exfil.staged_collection import (+ StagedCollectionModule,+ _audit_lots_egress_sync,+)+++def _make_module(cls):+ settings = AresSettings(+ ares_secret_key="test-secret-key-min32-chars-here!!",+ ares_encryption_key="test-enc-key-min32-chars-here-xxx",+ )+ campaign = Campaign(+ name="Test-Wave4-Identity-Exfil",+ scope=[ScopeEntry(cidr="10.0.0.0/8"), ScopeEntry(cidr="192.168.1.0/24")],+ noise_profile=NoiseProfile.NORMAL,+ )+ noise = NoiseController(campaign)+ return cls(settings=settings, campaign=campaign, noise=noise)+++# ---------------------------------------------------------------------------+# 1. Fine-Grained Password Policies (FGPP / PSO) & Hybrid Sync+# ---------------------------------------------------------------------------++class TestFineGrainedPasswordPolicies:+ """Validates AD PSO querying, safe pacing calculation, and hybrid sync detection."""++ def test_query_password_policy_with_pso_calculates_stricter_safe_attempts(self):+ """When PSOs exist with lower thresholds, safe_attempts_per_user must tighten."""+ fake_conn = MagicMock()+ fake_conn.bind.return_value = True++ # Default domain policy entries+ domain_entry = MagicMock()+ domain_entry.lockoutThreshold = 10+ domain_entry.lockoutDuration = -18000000000 # 30 mins+ domain_entry.lockOutObservationWindow = -18000000000 # 30 mins+ domain_entry.minPwdLength = 8+ domain_entry.pwdHistoryLength = 24++ # PSO entry with strict lockout threshold (e.g. 5 attempts)+ pso_entry = MagicMock()+ pso_entry.cn = "Strict-Admins-PSO"+ setattr(pso_entry, "msDS-LockoutThreshold", 5)+ setattr(pso_entry, "msDS-LockoutDuration", -18000000000)+ setattr(pso_entry, "msDS-LockoutObservationWindow", -18000000000)+ setattr(pso_entry, "msDS-MinimumPasswordLength", 16)+ setattr(pso_entry, "msDS-PasswordSettingsPrecedence", 10)++ # Hybrid user entry+ hybrid_entry = MagicMock()+ hybrid_entry.sAMAccountName = "cloudsync_user"+ setattr(hybrid_entry, "msDS-ExternalDirectoryObjectId", "11111111-2222-3333-4444-555555555555")++ # Mock search responses for successive queries+ def fake_search(dn, filter_str, search_scope=None, attributes=None, size_limit=None):+ if "msDS-PasswordSettings" in filter_str:+ fake_conn.entries = [pso_entry]+ elif "msDS-ExternalDirectoryObjectId" in filter_str:+ fake_conn.entries = [hybrid_entry]+ else:+ fake_conn.entries = [domain_entry]+ return True++ fake_conn.search.side_effect = fake_search++ fake_server = MagicMock()+ fake_ldap3 = MagicMock()+ fake_ldap3.Server.return_value = fake_server+ fake_ldap3.Connection.return_value = fake_conn+ fake_ldap3.SUBTREE = 2++ with patch.dict("sys.modules", {"ldap3": fake_ldap3}):+ res = query_password_policy("10.0.0.1", "CORP.LOCAL", "admin", "Secret123!")++ assert res["lockout_threshold"] == 10+ assert res["pso_enforced"] is True+ assert len(res["pso_policies"]) == 1+ assert res["pso_policies"][0]["name"] == "Strict-Admins-PSO"+ assert res["pso_policies"][0]["lockout_threshold"] == 5+ # Effective threshold is min(10, 5) = 5 -> safe_attempts = max(1, 5 - 2) = 3+ assert res["safe_attempts_per_user"] == 3+ assert res["hybrid_sync_detected"] is True++ def test_query_password_policy_no_pso_uses_default_threshold(self):+ """When no PSOs exist, default domain lockout threshold is used."""+ fake_conn = MagicMock()+ fake_conn.bind.return_value = True++ domain_entry = MagicMock()+ domain_entry.lockoutThreshold = 10+ domain_entry.lockoutDuration = -18000000000+ domain_entry.lockOutObservationWindow = -18000000000+ domain_entry.minPwdLength = 8+ domain_entry.pwdHistoryLength = 24++ def fake_search(dn, filter_str, search_scope=None, attributes=None, size_limit=None):+ if "msDS-PasswordSettings" in filter_str or "msDS-ExternalDirectoryObjectId" in filter_str:+ fake_conn.entries = []+ else:+ fake_conn.entries = [domain_entry]+ return True++ fake_conn.search.side_effect = fake_search++ fake_ldap3 = MagicMock()+ fake_ldap3.Server.return_value = MagicMock()+ fake_ldap3.Connection.return_value = fake_conn+ fake_ldap3.SUBTREE = 2++ with patch.dict("sys.modules", {"ldap3": fake_ldap3}):+ res = query_password_policy("10.0.0.1", "CORP.LOCAL", "admin", "Secret123!")++ assert res["lockout_threshold"] == 10+ assert res["pso_enforced"] is False+ assert res["pso_policies"] == []+ assert res["hybrid_sync_detected"] is False+ # max(1, 10 - 2) = 8+ assert res["safe_attempts_per_user"] == 8++ def test_pass_spray_run_emits_pso_and_hybrid_findings(self):+ """PassSprayModule.run generates structured findings for PSO and Entra ID sync."""+ mod = _make_module(PassSprayModule)+ policy_info = {+ "lockout_threshold": 10,+ "pso_enforced": True,+ "pso_policies": [{+ "name": "Strict-Tier0-PSO",+ "lockout_threshold": 3,+ "lockout_duration_min": 60,+ "observation_window_min": 60,+ "min_password_length": 18,+ }],+ "hybrid_sync_detected": True,+ "safe_attempts_per_user": 1,+ "safe_spray_delay_s": 5400.0,+ }++ fake_ldap3 = MagicMock()+ fake_conn = MagicMock()+ fake_conn.bind.return_value = False+ fake_ldap3.Connection.return_value = fake_conn++ with patch.dict("sys.modules", {"ldap3": fake_ldap3}):+ findings, raw = asyncio.run(mod.run(+ target="10.0.0.5",+ domain="CORP.LOCAL",+ users=["alice"],+ passwords=["Summer2026!"],+ protocol="ldap",+ policy_info=policy_info,+ ))++ titles = [f.title for f in findings]+ assert any("Fine-Grained Password Policy (PSO) Enforced" in t for t in titles)+ assert any("Entra ID Hybrid Sync & Cloud Smart Lockout Active" in t for t in titles)++ pso_finding = next(f for f in findings if "Fine-Grained Password Policy" in f.title)+ assert pso_finding.severity == Severity.LOW+ assert pso_finding.mitre_technique == "T1110.003"+ assert pso_finding.confidence == 0.95++ hybrid_finding = next(f for f in findings if "Entra ID Hybrid Sync" in f.title)+ assert hybrid_finding.severity == Severity.LOW+ assert hybrid_finding.mitre_technique == "T1110.003"++ assert raw["pso_enforced"] is True+ assert raw["safe_attempts_per_user"] == 1+ assert raw["hybrid_sync_detected"] is True+++# ---------------------------------------------------------------------------+# 2. OAuth 2.0 Device Code Flow / Modern Identity Posture Assessment+# ---------------------------------------------------------------------------++class TestOAuthPostureAssessment:+ """Validates non-destructive OAuth 2.0 device code endpoint assessment (T1528 / T1550)."""++ def test_audit_oauth_posture_sync_detects_permitted(self):+ """Device authorization endpoint returning code/tokens marks device_code_permitted."""+ mock_resp = MagicMock()+ mock_resp.getcode.return_value = 200+ mock_resp.read.return_value = b'{"device_code": "xyz123", "user_code": "ABCD-EFGH"}'+ mock_resp.__enter__.return_value = mock_resp++ with patch("urllib.request.urlopen", return_value=mock_resp):+ res = _audit_oauth_posture_sync("contoso.onmicrosoft.com")++ assert res["device_code_endpoint_active"] is True+ assert res["device_code_permitted"] is True+ assert "contoso.onmicrosoft.com" in res["checked_endpoint"]++ def test_audit_oauth_posture_sync_handles_blocked(self):+ """When device code endpoint fails or refuses connections, permitted is False."""+ with patch("urllib.request.urlopen", side_effect=Exception("Connection refused")):+ res = _audit_oauth_posture_sync("contoso.local")++ assert res["device_code_endpoint_active"] is False+ assert res["device_code_permitted"] is False++ def test_credential_reuse_emits_oauth_finding_when_permitted(self):+ """CredentialReuseModule.run creates MEDIUM finding when device code flow is open."""+ mod = _make_module(CredentialReuseModule)+ fake_vault = MagicMock()++ mock_oauth_audit = MagicMock(return_value={+ "device_code_endpoint_active": True,+ "device_code_permitted": True,+ "checked_endpoint": "https://login.microsoftonline.com/contoso.com/oauth2/v2.0/devicecode",+ })++ with patch("ares.credential.reuse.ReuseEngine") as MockEngine:+ mock_engine_inst = MagicMock()+ mock_engine_inst.spray = AsyncMock(return_value=[])+ MockEngine.return_value = mock_engine_inst++ findings, raw = asyncio.run(mod.run(+ target="10.0.0.50",+ vault=fake_vault,+ oauth_audit_func=mock_oauth_audit,+ ))++ titles = [f.title for f in findings]+ assert any("OAuth 2.0 Device Code Flow Vector Permitted on 10.0.0.50" in t for t in titles)++ oauth_finding = next(f for f in findings if "OAuth 2.0 Device Code Flow" in f.title)+ assert oauth_finding.severity == Severity.MEDIUM+ assert oauth_finding.mitre_technique == "T1528"+ assert oauth_finding.mitre_tactic == "Credential Access"+ assert oauth_finding.confidence == 0.9++ assert raw["oauth_device_code_permitted"] is True+ assert "devicecode" in raw["oauth_device_code_endpoint"]++ def test_credential_reuse_no_oauth_finding_when_restricted(self):+ """When device code endpoint is restricted or offline, no finding is raised."""+ mod = _make_module(CredentialReuseModule)+ fake_vault = MagicMock()++ mock_oauth_audit = MagicMock(return_value={+ "device_code_endpoint_active": False,+ "device_code_permitted": False,+ "checked_endpoint": None,+ })++ with patch("ares.credential.reuse.ReuseEngine") as MockEngine:+ mock_engine_inst = MagicMock()+ mock_engine_inst.spray = AsyncMock(return_value=[])+ MockEngine.return_value = mock_engine_inst++ findings, raw = asyncio.run(mod.run(+ target="10.0.0.60",+ vault=fake_vault,+ oauth_audit_func=mock_oauth_audit,+ ))++ assert not any("OAuth 2.0 Device Code Flow" in f.title for f in findings)+ assert raw["oauth_device_code_permitted"] is False+++# ---------------------------------------------------------------------------+# 3. Cloud LOTS Egress & Tenant Restrictions Assessment+# ---------------------------------------------------------------------------++class TestCloudLOTSEgressAssessment:+ """Validates Living-off-the-Trusted-Services cloud egress audit and Tenant Restrictions (T1567.002)."""++ def test_audit_lots_egress_sync_detects_open_routes_without_restrictions(self):+ """Outbound connection succeeds to trusted cloud services without restriction headers."""+ mock_resp = MagicMock()+ mock_resp.headers = {"Server": "Microsoft-IIS/10.0", "Content-Length": "0"}+ mock_resp.__enter__.return_value = mock_resp++ with patch("urllib.request.urlopen", return_value=mock_resp):+ res = _audit_lots_egress_sync("10.0.0.1")++ assert len(res["lots_routes_open"]) == 3+ assert "m365_graph" in res["lots_routes_open"]+ assert "aws_s3" in res["lots_routes_open"]+ assert "azure_blob" in res["lots_routes_open"]+ assert res["tenant_restrictions_enforced"] is False++ def test_audit_lots_egress_sync_detects_tenant_restrictions_enforced(self):+ """When enterprise proxy injects or enforces Tenant Restrictions, flag is set."""+ mock_resp = MagicMock()+ mock_resp.headers = {+ "Restrict-Access-To-Tenants": "contoso.com",+ "Restrict-Access-Context": "guid-here",+ }+ mock_resp.__enter__.return_value = mock_resp++ with patch("urllib.request.urlopen", return_value=mock_resp):+ res = _audit_lots_egress_sync("10.0.0.1")++ assert res["tenant_restrictions_enforced"] is True++ def test_staged_collection_emits_lots_finding_when_unrestricted(self):+ """StagedCollectionModule.run generates HIGH finding when LOTS routes are open without restrictions."""+ mod = _make_module(StagedCollectionModule)++ mock_lots_audit = MagicMock(return_value={+ "lots_routes_open": ["m365_graph", "azure_blob"],+ "tenant_restrictions_enforced": False,+ "checked_endpoints": ["m365_graph", "aws_s3", "azure_blob"],+ })++ mock_ssh = MagicMock()+ mock_stdout = MagicMock()+ mock_stdout.read.return_value = b""+ mock_ssh.exec_command.return_value = (MagicMock(), mock_stdout, MagicMock())++ with patch("paramiko.SSHClient", return_value=mock_ssh):+ findings, raw = asyncio.run(mod.run(+ target="10.0.0.10",+ username="admin",+ search_paths=["/var/log"],+ lots_audit_func=mock_lots_audit,+ ))++ titles = [f.title for f in findings]+ assert any("Cloud LOTS Exfiltration Route Open (Missing Tenant Restrictions)" in t for t in titles)++ lots_finding = next(f for f in findings if "Cloud LOTS Exfiltration Route" in f.title)+ assert lots_finding.severity == Severity.HIGH+ assert lots_finding.mitre_technique == "T1567.002"+ assert lots_finding.mitre_tactic == "Exfiltration"+ assert lots_finding.confidence == 0.85++ assert raw["lots_routes_open"] == ["m365_graph", "azure_blob"]+ assert raw["tenant_restrictions_enforced"] is False++ def test_staged_collection_no_lots_finding_when_restrictions_present(self):+ """When Tenant Restrictions are active, no LOTS exfiltration finding is emitted."""+ mod = _make_module(StagedCollectionModule)++ mock_lots_audit = MagicMock(return_value={+ "lots_routes_open": ["m365_graph"],+ "tenant_restrictions_enforced": True,+ "checked_endpoints": ["m365_graph", "aws_s3", "azure_blob"],+ })++ mock_ssh = MagicMock()+ mock_stdout = MagicMock()+ mock_stdout.read.return_value = b""+ mock_ssh.exec_command.return_value = (MagicMock(), mock_stdout, MagicMock())++ with patch("paramiko.SSHClient", return_value=mock_ssh):+ findings, raw = asyncio.run(mod.run(+ target="10.0.0.10",+ username="admin",+ search_paths=["/var/log"],+ lots_audit_func=mock_lots_audit,+ ))++ assert not any("Cloud LOTS Exfiltration Route" in f.title for f in findings)+ assert raw["tenant_restrictions_enforced"] is True++ def test_staged_collection_no_lots_finding_when_egress_blocked(self):+ """When host is completely airgapped / no cloud egress routes, no finding is emitted."""+ mod = _make_module(StagedCollectionModule)++ mock_lots_audit = MagicMock(return_value={+ "lots_routes_open": [],+ "tenant_restrictions_enforced": False,+ "checked_endpoints": ["m365_graph", "aws_s3", "azure_blob"],+ })++ mock_ssh = MagicMock()+ mock_stdout = MagicMock()+ mock_stdout.read.return_value = b""+ mock_ssh.exec_command.return_value = (MagicMock(), mock_stdout, MagicMock())++ with patch("paramiko.SSHClient", return_value=mock_ssh):+ findings, raw = asyncio.run(mod.run(+ target="10.0.0.10",+ username="admin",+ search_paths=["/var/log"],+ lots_audit_func=mock_lots_audit,+ ))++ assert not any("Cloud LOTS Exfiltration Route" in f.title for f in findings)+ assert raw["lots_routes_open"] == []