Skip to content

armgit / ARES

Public Imported from GitHub
0

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

fix(resource): scheduled_task guaranteed teardown (MOD-046)

Mafifrizi327458b00a0d
diff --git a/ares/modules/persistence/scheduled_task.py b/ares/modules/persistence/scheduled_task.py
index fa92582..2dd5255 100644
--- a/ares/modules/persistence/scheduled_task.py
+++ b/ares/modules/persistence/scheduled_task.py
@@ -100,6 +100,37 @@ def _tsch_register_sync(target: str, username: str, password: str,
pass
+def _tsch_delete_sync(target: str, username: str, password: str,
+ domain: str, lmhash: str, nthash: str,
+ task_name: str) -> None:
+ """Delete a scheduled task via impacket tsch RPC. Sync - call from run_in_executor."""
+ from impacket.dcerpc.v5 import transport, tsch # type: ignore[import]
+
+ string_binding = f"ncacn_np:{target}[\\pipe\\atsvc]"
+ rpctransport = transport.DCERPCTransportFactory(string_binding)
+ rpctransport.set_credentials(username, password, domain, lmhash, nthash, None)
+ rpctransport.set_connect_timeout(15)
+
+ dce = rpctransport.get_dce_rpc()
+ dce.connect()
+ try:
+ dce.bind(tsch.MSRPC_UUID_TSCHS)
+ task_path = f"\\{task_name}"
+ del_fn = getattr(tsch, "hSchRpcDelete", None) or getattr(tsch, "hSchRpcDeleteTask", None)
+ if del_fn:
+ try:
+ resp = del_fn(dce, task_path, 0)
+ except TypeError:
+ resp = del_fn(dce, task_path)
+ if hasattr(resp, "checkError"):
+ resp.checkError()
+ finally:
+ try:
+ dce.disconnect()
+ except Exception:
+ pass
+
+
@module_contract(
permissions=[
NetworkPermission(ports=[135, 139, 445], protocols=["tcp"]),
@@ -363,6 +394,7 @@ class ScheduledTaskPersistence(BaseModule):
"dry_run": True,
"persistence_established": True,
"task_name": task_name,
+ "created_artifacts": [f"scheduled_task:\\{task_name}"],
"method": "scheduled_task",
"mitre": "T1053.005",
}
@@ -375,10 +407,19 @@ class ScheduledTaskPersistence(BaseModule):
if not username:
return [], {"error": "no_credential_username", "persistence_established": False}
+ raw: dict[str, Any] = {
+ "task_name": task_name,
+ "created_artifacts": [f"scheduled_task:\\{task_name}"],
+ "method": "scheduled_task",
+ "mitre": "T1053.005",
+ "persistence_established": False,
+ }
+
+ import asyncio as _asyncio
+ _loop = _asyncio.get_running_loop()
+
try:
await self.before_request(target, "default")
- import asyncio as _asyncio
- _loop = _asyncio.get_running_loop()
await _loop.run_in_executor(
None,
lambda: _tsch_register_sync(
@@ -387,14 +428,45 @@ class ScheduledTaskPersistence(BaseModule):
),
)
logger.info("scheduled_task_created", target=target, task=task_name)
- return [finding], {
- "persistence_established": True,
- "task_name": task_name,
- "method": "scheduled_task",
- "mitre": "T1053.005",
- }
+ raw["persistence_established"] = True
+ return [finding], raw
except Exception as exc:
raise self._classify_error(exc) from exc
+ finally:
+ 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],
+ )
+
+ async def teardown(self, target: str = "", username: str = "", password: str = "",
+ domain: str = "", lmhash: str = "", nthash: str = "",
+ task_name: str = "AresUpdater") -> bool:
+ """Explicit teardown method to delete scheduled task via RPC."""
+ if not target or not task_name:
+ return False
+ import asyncio as _asyncio
+ loop = _asyncio.get_running_loop()
+ try:
+ await loop.run_in_executor(
+ None,
+ lambda: _tsch_delete_sync(target, username, password, domain, lmhash, nthash, task_name),
+ )
+ return True
+ except Exception as exc:
+ logger.warning("scheduled_task_teardown_error", target=target, task=task_name, error=str(exc))
+ return False
# ── Registry Run Key ─────────────────────────────────────────────────────────
diff --git a/tests/unit/modules/test_scheduled_task_teardown.py b/tests/unit/modules/test_scheduled_task_teardown.py
new file mode 100644
index 0000000..dadab95
--- /dev/null
+++ b/tests/unit/modules/test_scheduled_task_teardown.py
@@ -0,0 +1,117 @@
+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.persistence.scheduled_task import (
+ ScheduledTaskPersistence,
+ _tsch_delete_sync,
+)
+
+
+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="Scheduled-Task-Teardown-Test",
+ operator="test_operator",
+ scope=[ScopeEntry(cidr="10.0.0.0/24")],
+ noise_profile=NoiseProfile.NORMAL,
+ )
+ noise = NoiseController(campaign)
+ return ScheduledTaskPersistence(settings=settings, campaign=campaign, noise=noise)
+
+
+async def test_scheduled_task_teardown_after_successful_run():
+ """MOD-046: task is deleted in finally and created_artifacts is populated after successful run."""
+ 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="AresTestTask",
+ command="calc.exe",
+ )
+
+ mock_register.assert_called_once()
+ mock_delete.assert_called_once_with(
+ "10.0.0.5", "admin", "pass", "corp.local", "", "", "AresTestTask"
+ )
+ assert raw["created_artifacts"] == [r"scheduled_task:\AresTestTask"]
+ assert raw["persistence_established"] is True
+
+
+async def test_scheduled_task_teardown_after_failure_in_middle():
+ """MOD-046: task delete is executed in finally even when task creation fails midway."""
+ mod = _make_module()
+
+ mock_register = MagicMock(side_effect=RuntimeError("RPC connection broke during task creation"))
+ 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):
+ with pytest.raises(Exception):
+ await mod.run(
+ target="10.0.0.5",
+ username="admin",
+ password="pass",
+ domain="corp.local",
+ task_name="AresTestTaskFail",
+ command="calc.exe",
+ )
+
+ # Delete must be called even though register failed midway
+ mock_delete.assert_called_once_with(
+ "10.0.0.5", "admin", "pass", "corp.local", "", "", "AresTestTaskFail"
+ )
+
+
+async def test_scheduled_task_explicit_teardown_method():
+ """MOD-046: explicit teardown() method delegates to _tsch_delete_sync and returns True."""
+ mod = _make_module()
+ mock_delete = MagicMock()
+
+ with patch("ares.modules.persistence.scheduled_task._tsch_delete_sync", mock_delete):
+ res = await mod.teardown(
+ target="10.0.0.5",
+ username="admin",
+ password="pass",
+ domain="corp.local",
+ task_name="ManualTask",
+ )
+
+ assert res is True
+ mock_delete.assert_called_once_with(
+ "10.0.0.5", "admin", "pass", "corp.local", "", "", "ManualTask"
+ )