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(security): Fase 3 - scope enforcement secondary targets Grup D (MASTER_FIX_PLAN.md)
Mafifrizicc2e980d3709
diff --git a/ares/modules/ad/adcs.py b/ares/modules/ad/adcs.pyindex db1c7ae..caa3c82 100644--- a/ares/modules/ad/adcs.py+++ b/ares/modules/ad/adcs.py@@ -1152,8 +1152,7 @@ class ADCSModule(BaseModule[ADCSParams, ModuleResult]):except OSError:pass- @staticmethod- def _submit_csr_to_ca(ca_host: str, ca_name: str, template_name: str,+ def _submit_csr_to_ca(self, ca_host: str, ca_name: str, template_name: str,csr_pem: bytes, username: str, password: str,domain: str) -> bytes:"""@@ -1163,6 +1162,9 @@ class ADCSModule(BaseModule[ADCSParams, ModuleResult]):Returns PEM certificate bytes on success, empty bytes on failure.Uses NTLM authentication (same credentials used for LDAP)."""+ if hasattr(self, "noise") and hasattr(self.noise, "scope_guard"):+ self.noise.scope_guard.assert_in_scope(ca_host)+try:import httpxfrom base64 import b64encodediff --git a/ares/modules/ad/coerce.py b/ares/modules/ad/coerce.pyindex 443df01..8775e6b 100644--- a/ares/modules/ad/coerce.py+++ b/ares/modules/ad/coerce.py@@ -219,6 +219,8 @@ class CoerceModule(BaseModule[CoerceParams, ModuleResult]):listener_ip = sanitize_hostname(listener_ip)await self.before_request(dc, "default")+ if listener_ip:+ await self.before_request(listener_ip, "smb")logger.warning("coerce_start",target=dc, listener=listener_ip, method=method,msg="HIGH_NOISE - TRIGGERS_MDI")diff --git a/ares/modules/ad/sccm.py b/ares/modules/ad/sccm.pyindex bdff48c..e2f035b 100644--- a/ares/modules/ad/sccm.py+++ b/ares/modules/ad/sccm.py@@ -229,6 +229,12 @@ class SCCMModule(BaseModule[SCCMParams, ModuleResult]):sccm_host = sccm_info["site_servers"][0]site_code = sccm_info.get("site_code", "")+ if sccm_host and sccm_host != dc:+ try:+ await self.before_request(sccm_host, "rpc")+ except Exception as exc:+ logger.warning("sccm_host_out_of_scope", sccm_host=sccm_host, error=str(exc))+self.finding(title=f"SCCM Infrastructure Found: {sccm_host} (Site: {site_code})",description=(@@ -271,9 +277,18 @@ class SCCMModule(BaseModule[SCCMParams, ModuleResult]):# ── Step 3: Enumerate NAA via WMI (requires admin on SCCM client) ─naa_target = target or sccm_host- naa_info = await loop.run_in_executor(- None, lambda: self._extract_naa(naa_target, domain, username, password)- )+ if naa_target and naa_target != dc:+ try:+ await self.before_request(naa_target, "wmi")+ except Exception as exc:+ logger.warning("sccm_naa_target_out_of_scope", target=naa_target, error=str(exc))+ naa_target = ""++ naa_info: dict[str, Any] = {}+ if naa_target:+ naa_info = await loop.run_in_executor(+ None, lambda: self._extract_naa(naa_target, domain, username, password)+ )raw["naa"] = naa_infoif naa_info.get("naa_username"):@@ -559,6 +574,16 @@ class SCCMModule(BaseModule[SCCMParams, ModuleResult]):try:import socketfor dp in distribution_points[:10]:+ if hasattr(self, "campaign") and self.campaign and hasattr(self.campaign, "is_in_scope"):+ if not self.campaign.is_in_scope(dp):+ logger.warning("sccm_dp_out_of_scope_skipped", dp=dp)+ continue+ if hasattr(self, "noise") and hasattr(self.noise, "scope_guard"):+ try:+ self.noise.scope_guard.assert_in_scope(dp)+ except Exception as exc:+ logger.warning("sccm_dp_scope_blocked", dp=dp, error=str(exc))+ continuetry:sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)sock.settimeout(3)diff --git a/ares/modules/credential/reuse.py b/ares/modules/credential/reuse.pyindex 3a31aee..95d8e7d 100644--- a/ares/modules/credential/reuse.py+++ b/ares/modules/credential/reuse.py@@ -53,13 +53,24 @@ def _audit_oauth_posture_sync(target: str) -> dict[str, Any]:ctx.verify_mode = ssl.CERT_NONEprobe_urls: list[str] = []- if "microsoftonline.com" in clean_target:+ # MOD-032: Do not probe public login.microsoftonline.com if target is private/internal RFC1918 IP+ import ipaddress+ is_private_ip = False+ try:+ ip_obj = ipaddress.ip_address(clean_target)+ is_private_ip = ip_obj.is_private or ip_obj.is_loopback or ip_obj.is_link_local+ except ValueError:+ pass++ if is_private_ip:+ 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: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")+ probe_urls.append(f"https://{clean_target}/oauth2/v2.0/devicecode")for url in probe_urls:try:diff --git a/ares/modules/lateral/mssql.py b/ares/modules/lateral/mssql.pyindex 79c61b8..56111ca 100644--- a/ares/modules/lateral/mssql.py+++ b/ares/modules/lateral/mssql.py@@ -294,12 +294,21 @@ class MSSQLModule(BaseModule):# Linked server hopelif technique == "linked" and (linked or info.get("linked_servers")):linked_server = linked or info["linked_servers"][0]- linked_output = await loop.run_in_executor(- None,- lambda: self._linked_server_sync(- target, username, password, port, linked_server, command,- ),- )+ if linked_server:+ try:+ await self.before_request(linked_server, "mssql")+ except Exception as exc:+ logger.warning("mssql_linked_server_out_of_scope", server=linked_server, error=str(exc))+ linked_server = ""++ linked_output = ""+ if linked_server:+ linked_output = await loop.run_in_executor(+ None,+ lambda: self._linked_server_sync(+ target, username, password, port, linked_server, command,+ ),+ )if linked_output:self.finding(title = f"MSSQL Linked Server RCE: {linked_server}",@@ -319,10 +328,18 @@ class MSSQLModule(BaseModule):# UNC path NTLM coercion via xp_dirtreeelif technique == "unc_coerce" and listener:- coerced = await loop.run_in_executor(- None,- lambda: self._unc_coerce_sync(target, username, password, port, listener),- )+ try:+ await self.before_request(listener, "smb")+ except Exception as exc:+ logger.warning("mssql_listener_out_of_scope", listener=listener, error=str(exc))+ listener = ""++ coerced = False+ if listener:+ coerced = await loop.run_in_executor(+ None,+ lambda: self._unc_coerce_sync(target, username, password, port, listener),+ )if coerced:self.finding(title = f"MSSQL NTLM Coercion to {listener} from {target}",diff --git a/ares/modules/lateral/ntlm_relay.py b/ares/modules/lateral/ntlm_relay.pyindex e355a68..92e1778 100644--- a/ares/modules/lateral/ntlm_relay.py+++ b/ares/modules/lateral/ntlm_relay.py@@ -484,6 +484,16 @@ class NTLMRelayModule(BaseModule):results: list[RelayTarget] = []for host in targets[:50]: # cap to prevent excessive scanning+ if hasattr(self, "campaign") and self.campaign and hasattr(self.campaign, "is_in_scope"):+ if not self.campaign.is_in_scope(host):+ logger.warning("ntlm_relay_target_out_of_scope_skipped", host=host)+ continue+ try:+ await self.before_request(host, "smb")+ except Exception as exc:+ logger.warning("ntlm_relay_target_scope_blocked", host=host, error=str(exc))+ continue+rt = RelayTarget(host=host)# Check SMB signingdiff --git a/ares/modules/lateral/smb_relay.py b/ares/modules/lateral/smb_relay.pyindex f7b99ef..f73d284 100644--- a/ares/modules/lateral/smb_relay.py+++ b/ares/modules/lateral/smb_relay.py@@ -329,6 +329,22 @@ class SMBRelayAuditModule(BaseModule):targets = [sanitize_hostname(t) for t in targets if t]+ scoped_targets: list[str] = []+ for t in targets:+ if hasattr(self, "campaign") and self.campaign and hasattr(self.campaign, "is_in_scope"):+ if not self.campaign.is_in_scope(t):+ logger.warning("smb_relay_target_out_of_scope_skipped", target=t)+ continue+ try:+ await self.before_request(t, "smb")+ scoped_targets.append(t)+ except Exception as exc:+ logger.warning("smb_relay_target_scope_blocked", target=t, error=str(exc))+ continue+ targets = scoped_targets+ if not targets:+ return [], {"error": "no in-scope targets to audit"}+logger.info("smb_relay_audit_start", targets=len(targets))audit("smb_relay_audit", actor="operator", source="operator",target=",".join(targets[:5]), technique="T1082")diff --git a/ares/modules/network/dns_enum.py b/ares/modules/network/dns_enum.pyindex 0e6e050..6d7ed28 100644--- a/ares/modules/network/dns_enum.py+++ b/ares/modules/network/dns_enum.py@@ -268,6 +268,16 @@ class DnsEnumModule(BaseModule):for ns in ns_servers[:3]:ns_clean = ns.rstrip(".")+ if hasattr(self, "campaign") and self.campaign and hasattr(self.campaign, "is_in_scope"):+ if not self.campaign.is_in_scope(ns_clean):+ logger.warning("dns_axfr_nameserver_out_of_scope_skipped", nameserver=ns_clean)+ continue+ try:+ await self.before_request(ns_clean, "dns")+ except Exception as exc:+ logger.warning("dns_axfr_nameserver_scope_blocked", nameserver=ns_clean, error=str(exc))+ continue+records = await loop.run_in_executor(None, _try_axfr, ns_clean)if records:zone_transfer_data = recordsdiff --git a/ares/modules/network/http_fingerprint.py b/ares/modules/network/http_fingerprint.pyindex 32f95e3..a6beb31 100644--- a/ares/modules/network/http_fingerprint.py+++ b/ares/modules/network/http_fingerprint.py@@ -251,10 +251,30 @@ class HttpFingerprintModule(BaseModule):try:async with httpx.AsyncClient(timeout=6.0, verify=False,- follow_redirects=True,+ follow_redirects=False,headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"},) as client:r = await client.get(f"{base_url}/")+ if r.is_redirect and r.headers.get("location"):+ from urllib.parse import urljoin, urlparse+ target_loc = r.headers["location"]+ abs_url = urljoin(f"{base_url}/", target_loc)+ parsed = urlparse(abs_url)+ redirect_host = parsed.hostname or target+ is_in_scope = True+ if hasattr(self, "campaign") and self.campaign and hasattr(self.campaign, "is_in_scope"):+ is_in_scope = self.campaign.is_in_scope(redirect_host)+ if is_in_scope:+ try:+ r = await client.get(abs_url)+ except Exception:+ pass+ else:+ logger.warning(+ "http_fingerprint_redirect_out_of_scope_skipped",+ redirect_host=redirect_host,+ destination=abs_url,+ )except Exception:continuediff --git a/ares/modules/network/pivot.py b/ares/modules/network/pivot.pyindex 48b5c0d..0725fc9 100644--- a/ares/modules/network/pivot.py+++ b/ares/modules/network/pivot.py@@ -266,6 +266,18 @@ class PivotModule(BaseModule):await self.before_request(target, "default")+ # Validate reachable_subnets against campaign scope+ valid_subnets: list[str] = []+ for subnet in (reachable_subnets or []):+ clean_sub = subnet.strip()+ if hasattr(self, "campaign") and self.campaign and hasattr(self.campaign, "is_in_scope"):+ sample_host = clean_sub.split("/")[0]+ if not self.campaign.is_in_scope(sample_host):+ logger.warning("pivot_reachable_subnet_out_of_scope_skipped", subnet=clean_sub)+ continue+ valid_subnets.append(clean_sub)+ reachable_subnets = valid_subnets+# Get or create campaign-level PivotManagerif campaign_id not in _PIVOT_MANAGERS:_PIVOT_MANAGERS[campaign_id] = PivotManager(operator="ares")diff --git a/tests/unit/test_scope_enforcement_grup_d.py b/tests/unit/test_scope_enforcement_grup_d.pynew file mode 100644index 0000000..efd8193--- /dev/null+++ b/tests/unit/test_scope_enforcement_grup_d.py@@ -0,0 +1,328 @@+"""+Unit tests for Grup D - Scope Enforcement on Secondary Targets (MOD-004, MOD-009, MOD-010, MOD-011, MOD-014, MOD-015, MOD-017, MOD-032, MOD-058, MOD-059).+Verifies:+1. ad.coerce enforces scope on listener_ip.+2. ad.sccm skips out-of-scope secondary hosts cleanly.+3. ad.adcs checks ca_host in _submit_csr_to_ca.+4. lateral.ntlm_relay filters out-of-scope targets in _check_relay_targets.+5. lateral.smb_relay filters out-of-scope targets before negotiation.+6. lateral.mssql skips out-of-scope listener and linked_server.+7. network.pivot filters out-of-scope reachable_subnets.+8. credential.reuse isolates Microsoft cloud OAuth probes for RFC1918 internal targets.+9. network.dns_enum checks scope on nameservers before AXFR.+10. network.http_fingerprint blocks out-of-scope HTTP redirects.+"""+from __future__ import annotations++import asyncio+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry+from ares.core.config import AresSettings+from ares.core.context import ExecutionContext+from ares.core.noise import NoiseController, ScopeViolationError+from ares.modules.ad.adcs import ADCSModule+from ares.modules.ad.coerce import CoerceModule+from ares.modules.ad.sccm import SCCMModule+from ares.modules.credential.reuse import CredentialReuseModule, _audit_oauth_posture_sync+from ares.modules.lateral.mssql import MSSQLModule+from ares.modules.lateral.ntlm_relay import NTLMRelayModule+from ares.modules.lateral.smb_relay import SMBRelayAuditModule+from ares.modules.network.dns_enum import DnsEnumModule+from ares.modules.network.http_fingerprint import HttpFingerprintModule+from ares.modules.network.pivot import PivotModule+from ares.modules.params import (+ ADCSParams,+ CoerceParams,+ CredentialReuseParams,+ DNSEnumParams,+ HTTPFingerprintParams,+ MSSQLParams,+ NTLMRelayParams,+ PivotParams,+ SCCMParams,+ SMBRelayParams,+)+++def _make_fixture(scope_cidr: str = "10.0.0.0/24") -> tuple[AresSettings, Campaign, NoiseController]:+ settings = AresSettings(+ ares_secret_key="secret-key-32-chars-minimum-len!",+ ares_encryption_key="enc-key-32-chars-minimum-length!",+ )+ campaign = Campaign(+ name="test-scope",+ client="test-client",+ scope=[ScopeEntry(cidr=scope_cidr)],+ noise_profile=NoiseProfile.NORMAL,+ )+ noise = NoiseController(campaign)+ noise.jitter.sleep = AsyncMock()+ return settings, campaign, noise+++async def test_coerce_listener_ip_scope_enforcement():+ """MOD-004: ad.coerce must enforce scope on listener_ip."""+ settings, campaign, noise = _make_fixture("10.0.0.0/24")+ mod = CoerceModule(settings=settings, campaign=campaign, noise=noise)++ # In-scope DC, but OUT-OF-SCOPE listener_ip (8.8.8.8)+ ctx = ExecutionContext(+ execution_id="exec-coerce-scope",+ campaign_id=campaign.id,+ target="10.0.0.1",+ params=CoerceParams(+ dc="10.0.0.1",+ domain="corp.local",+ username="admin",+ password="Password123!",+ listener_ip="8.8.8.8",+ ),+ settings=settings,+ campaign=campaign,+ noise=noise,+ dry_run=False,+ )++ with pytest.raises(ScopeViolationError):+ await mod.execute(ctx)+++async def test_sccm_secondary_targets_scope_enforcement():+ """MOD-010: ad.sccm skips out-of-scope site_server and NAA target without crashing."""+ settings, campaign, noise = _make_fixture("10.0.0.0/24")+ mod = SCCMModule(settings=settings, campaign=campaign, noise=noise)++ # Mock LDAP discovery to return out-of-scope site_server (192.168.1.100)+ fake_discovery = {+ "site_servers": ["192.168.1.100"],+ "site_code": "PS1",+ "management_points": [],+ "distribution_points": ["192.168.1.200"],+ }++ with patch.object(mod, "_discover_sccm", return_value=fake_discovery), \+ patch.object(mod, "_enum_client_push", return_value={}), \+ patch.object(mod, "_extract_naa", return_value={}), \+ patch.object(mod, "_check_pxe", return_value={}), \+ patch.object(mod, "_enum_task_sequences", return_value={}):++ ctx = ExecutionContext(+ execution_id="exec-sccm-scope",+ campaign_id=campaign.id,+ target="10.0.0.1",+ params=SCCMParams(+ dc="10.0.0.1",+ domain="corp.local",+ username="admin",+ password="Password123!",+ ),+ settings=settings,+ campaign=campaign,+ noise=noise,+ dry_run=False,+ )+ res = await mod.execute(ctx)+ # Module should complete and record findings without raising unhandled ScopeViolationError+ assert res.status in ("partial", "success")+++def test_adcs_ca_host_scope_enforcement():+ """MOD-009: ad.adcs _submit_csr_to_ca asserts ca_host in scope."""+ settings, campaign, noise = _make_fixture("10.0.0.0/24")+ mod = ADCSModule(settings=settings, campaign=campaign, noise=noise)++ # ca_host 192.168.99.1 is out of scope 10.0.0.0/24+ with pytest.raises(ScopeViolationError):+ mod._submit_csr_to_ca(+ ca_host="192.168.99.1",+ ca_name="Corp-CA",+ template_name="User",+ csr_pem=b"fake-csr",+ username="user",+ password="pwd",+ domain="corp.local",+ )+++async def test_ntlm_relay_check_relay_targets_scope_enforcement():+ """MOD-011: lateral.ntlm_relay skips out-of-scope targets in _check_relay_targets."""+ settings, campaign, noise = _make_fixture("10.0.0.0/24")+ mod = NTLMRelayModule(settings=settings, campaign=campaign, noise=noise)++ # 10.0.0.5 is in-scope, 172.16.1.5 is out-of-scope+ targets = ["10.0.0.5", "172.16.1.5"]++ loop = asyncio.get_running_loop()++ async def fake_executor(executor, func, *args):+ return "not_required"++ with patch.object(loop, "run_in_executor", side_effect=fake_executor):+ results = await mod._check_relay_targets(targets, "10.0.0.1", "corp.local", "user", "pwd")+ # Only the in-scope target (10.0.0.5) should be in results+ result_hosts = [r.host for r in results]+ assert "10.0.0.5" in result_hosts+ assert "172.16.1.5" not in result_hosts+++async def test_smb_relay_targets_scope_enforcement():+ """MOD-015: lateral.smb_relay filters out-of-scope targets before negotiation."""+ settings, campaign, noise = _make_fixture("10.0.0.0/24")+ mod = SMBRelayAuditModule(settings=settings, campaign=campaign, noise=noise)++ # Targets include in-scope and out-of-scope+ ctx = ExecutionContext(+ execution_id="exec-smb-relay-scope",+ campaign_id=campaign.id,+ target="10.0.0.10",+ params=SMBRelayParams(targets=["10.0.0.10", "192.168.5.5"]),+ settings=settings,+ campaign=campaign,+ noise=noise,+ dry_run=False,+ )++ with patch(+ "ares.modules.lateral.smb_relay._check_smb_signing",+ new_callable=AsyncMock,+ return_value={+ "signing_required": False,+ "signing_enabled": False,+ "dialect": "SMB2 0x0210",+ "security_mode": 1,+ "error": "",+ },+ ):+ res = await mod.execute(ctx)+ assert res.status in ("partial", "success")+ per_host = res.raw.get("per_host_results", {})+ assert "10.0.0.10" in per_host+ assert "192.168.5.5" not in per_host+++async def test_mssql_linked_and_listener_scope_enforcement():+ """MOD-014: lateral.mssql checks scope on linked_server and listener."""+ settings, campaign, noise = _make_fixture("10.0.0.0/24")+ mod = MSSQLModule(settings=settings, campaign=campaign, noise=noise)++ # Test out-of-scope unc_coerce listener+ with patch.object(mod, "_enum_server_sync", return_value={"version": "SQL2019", "linked_servers": []}), \+ patch.object(mod, "_unc_coerce_sync") as mock_unc:+ findings, raw = await mod.run(+ target="10.0.0.15",+ username="sa",+ password="pwd",+ technique="unc_coerce",+ listener="172.16.10.10", # Out of scope+ )+ assert not mock_unc.called++ # Test out-of-scope linked_server+ with patch.object(mod, "_enum_server_sync", return_value={"version": "SQL2019", "linked_servers": ["172.16.20.20"]}), \+ patch.object(mod, "_linked_server_sync") as mock_linked:+ findings, raw = await mod.run(+ target="10.0.0.15",+ username="sa",+ password="pwd",+ technique="linked",+ linked="172.16.20.20", # Out of scope+ command="whoami",+ )+ assert not mock_linked.called+++async def test_pivot_reachable_subnets_scope_enforcement():+ """MOD-017: network.pivot filters out-of-scope reachable_subnets."""+ from ares.pivot.infrastructure import TunnelState+ settings, campaign, noise = _make_fixture("10.0.0.0/16")+ mod = PivotModule(settings=settings, campaign=campaign, noise=noise)++ mock_tunnel = MagicMock()+ mock_tunnel.state = TunnelState.ACTIVE+ mock_tunnel.tunnel_id = "tun-123"+ mock_tunnel.proxy_url = "socks5://127.0.0.1:1080"+ mock_tunnel.local_port = 1080++ mock_pm = MagicMock()+ mock_pm.establish_socks5 = AsyncMock(return_value=mock_tunnel)+ mock_pm.generate_proxychains_config.return_value = ""++ with patch.dict("ares.modules.network.pivot._PIVOT_MANAGERS", {"test-camp": mock_pm}):+ # 10.0.1.0/24 is in-scope, 192.168.1.0/24 is out-of-scope+ findings, raw = await mod.run(+ target="10.0.0.50",+ username="operator",+ secret="pwd",+ reachable_subnets=["10.0.1.0/24", "192.168.1.0/24"],+ campaign_id="test-camp",+ )+ call_kwargs = mock_pm.establish_socks5.call_args[1]+ assert "10.0.1.0/24" in call_kwargs["reachable_subnets"]+ assert "192.168.1.0/24" not in call_kwargs["reachable_subnets"]+++def test_credential_reuse_rfc1918_probe_isolation():+ """MOD-032: credential.reuse does not probe login.microsoftonline.com for private RFC1918 IPs."""+ with patch("urllib.request.urlopen") as mock_urlopen:+ mock_resp = MagicMock()+ mock_resp.getcode.return_value = 200+ mock_resp.read.return_value = b'{"device_code": "xyz"}'+ mock_urlopen.return_value.__enter__.return_value = mock_resp++ result = _audit_oauth_posture_sync("10.0.0.5")+ assert mock_urlopen.called+ req_arg = mock_urlopen.call_args[0][0]+ assert "login.microsoftonline.com" not in req_arg.full_url+ assert "10.0.0.5" in req_arg.full_url+ assert result["checked_endpoint"] == "https://10.0.0.5/oauth2/v2.0/devicecode"+++async def test_dns_enum_axfr_nameserver_scope_enforcement():+ """MOD-058: network.dns_enum enforces scope before attempting AXFR on nameservers."""+ settings, campaign, noise = _make_fixture("10.0.0.0/24")+ mod = DnsEnumModule(settings=settings, campaign=campaign, noise=noise)++ mock_resolver = MagicMock()+ mock_resolver.resolve.return_value = ["8.8.8.8."]++ with patch("dns.resolver.Resolver", return_value=mock_resolver), \+ patch("dns.query.xfr") as mock_xfr:++ findings, raw = await mod.run(target="10.0.0.1", domain="corp.local", brute_force=False)+ assert not mock_xfr.called+ assert not any("Zone Transfer" in f.title for f in findings)+++async def test_http_fingerprint_redirect_scope_enforcement():+ """MOD-059: network.http_fingerprint prevents following redirects to out-of-scope hosts."""+ settings, campaign, noise = _make_fixture("10.0.0.0/24")+ mod = HttpFingerprintModule(settings=settings, campaign=campaign, noise=noise)++ # Create mock response redirecting to external out-of-scope host+ mock_resp = MagicMock()+ mock_resp.status_code = 302+ mock_resp.is_redirect = True+ mock_resp.headers = {"location": "https://external-auth.evil.com/login", "server": "nginx"}+ mock_resp.text = "Redirecting..."++ mock_client = MagicMock()+ mock_client.get = AsyncMock(return_value=mock_resp)+ mock_client.head = AsyncMock(return_value=MagicMock(status_code=404))+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)+ mock_client.__aexit__ = AsyncMock(return_value=None)++ with patch("httpx.AsyncClient", return_value=mock_client):+ findings, raw = await mod.run(target="10.0.0.20", ports=[80])+ # External host was not queried second time because it was out of scope+ assert mock_client.get.call_count == 1