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: secure dpapi temp credential cleanup
Mafifriziccd67cc1d1a0
diff --git a/ares/modules/windows/dpapi.py b/ares/modules/windows/dpapi.pyindex 8de44db..59b84d1 100644--- a/ares/modules/windows/dpapi.py+++ b/ares/modules/windows/dpapi.py@@ -22,12 +22,11 @@ from __future__ import annotationsimport asyncioimport os-import tempfilefrom typing import Anyfrom ares.core.campaign import Finding, Severityfrom ares.core.logger import audit, get_logger-from ares.core.security import sanitize_hostname+from ares.core.security import sanitize_hostname, secure_mkstempfrom ares.modules.base import BaseModule, OpsecLevelfrom ares.core.tracing import trace_module@@ -95,6 +94,7 @@ class DPAPIModule(BaseModule):nt_hash = ctx.params.get("nt_hash", "") # for offline decryptionbackup_key = ctx.params.get("backup_key", "") # domain backup key PEMmode = ctx.params.get("mode", "auto") # auto|user|backup|offline+ campaign_id = getattr(ctx, "campaign_id", "")# Parse NTLM hash if password looks like onelmhash, nthash_login = "", ""@@ -110,7 +110,7 @@ class DPAPIModule(BaseModule):target=target, username=username, password=password,domain=domain, lmhash=lmhash, nthash_login=nthash_login,target_user=target_user, nt_hash=nt_hash,- backup_key=backup_key, mode=mode,+ backup_key=backup_key, mode=mode, campaign_id=campaign_id,)return ModuleResult(status="success" if findings else "partial",@@ -122,7 +122,8 @@ class DPAPIModule(BaseModule):async def run(self, target: str, username: str, password: str = "",domain: str = "", lmhash: str = "", nthash_login: str = "",target_user: str = "", nt_hash: str = "",- backup_key: str = "", mode: str = "auto", **kwargs: Any):+ backup_key: str = "", mode: str = "auto",+ campaign_id: str = "", **kwargs: Any):await self.before_request(target, "default")logger.info("dpapi_start", target=target, mode=mode, target_user=target_user)@@ -136,7 +137,8 @@ class DPAPIModule(BaseModule):local_files = await loop.run_in_executor(None,lambda: self._transfer_dpapi_files(- target, username, password, domain, lmhash, nthash_login, target_user+ target, username, password, domain, lmhash, nthash_login,+ target_user, campaign_id=campaign_id),)except Exception as exc:@@ -163,33 +165,36 @@ class DPAPIModule(BaseModule):# Decrypt blobscredentials: list[dict] = []- if mode in ("auto", "offline") and nt_hash:- creds = await loop.run_in_executor(- None,- lambda: self._decrypt_offline(local_files, nt_hash, target_user, domain),- )- credentials.extend(creds)+ try:+ if mode in ("auto", "offline") and nt_hash:+ creds = await loop.run_in_executor(+ None,+ lambda: self._decrypt_offline(local_files, nt_hash, target_user, domain),+ )+ credentials.extend(creds)- if mode in ("auto", "backup") and backup_key:- creds = await loop.run_in_executor(+ if mode in ("auto", "backup") and backup_key:+ creds = await loop.run_in_executor(+ None,+ lambda: self._decrypt_with_backup_key(local_files, backup_key),+ )+ credentials.extend(creds)++ # Chrome Login Data — special handling via sqlite3+ chrome_creds = await loop.run_in_executor(None,- lambda: self._decrypt_with_backup_key(local_files, backup_key),+ lambda: self._parse_chrome_logindata(+ local_files, nt_hash or nthash_login, campaign_id=campaign_id+ ),)- credentials.extend(creds)-- # Chrome Login Data — special handling via sqlite3- chrome_creds = await loop.run_in_executor(- None,- lambda: self._parse_chrome_logindata(local_files, nt_hash or nthash_login),- )- credentials.extend(chrome_creds)-- # Cleanup temp files- for fpath in local_files.values():- try:- os.unlink(fpath)- except Exception:- pass+ credentials.extend(chrome_creds)+ finally:+ # Cleanup transferred credential artifacts on success, parse failure, or cancellation.+ for fpath in local_files.values():+ try:+ os.unlink(fpath)+ except Exception:+ passlogger.info("dpapi_complete", found=len(credentials))@@ -249,7 +254,8 @@ class DPAPIModule(BaseModule):def _transfer_dpapi_files(self, target: str, username: str, password: str,domain: str, lmhash: str, nthash: str,- target_user: str) -> dict[str, str]:+ target_user: str,+ campaign_id: str = "") -> dict[str, str]:"""Transfer DPAPI-relevant files from target via SMB.Returns {logical_name: local_temp_path}.@@ -295,15 +301,30 @@ class DPAPIModule(BaseModule):for share, remote_path, name in targets:buf = io.BytesIO()+ local_path = ""+ fd: int | None = Nonetry:smb.getFile(share, remote_path, buf.write)- _fd, local_path = tempfile.mkstemp(prefix=f"ares_dpapi_{name}_")- os.close(_fd)+ local_path, fd = secure_mkstemp(+ prefix=f"ares_dpapi_{name}_", campaign_id=campaign_id+ )+ os.close(fd)+ fd = Nonewith open(local_path, "wb") as f:f.write(buf.getvalue())local_files[name] = local_pathlogger.debug("dpapi_file_transferred", name=name, size=len(buf.getvalue()))except Exception:+ if fd is not None:+ try:+ os.close(fd)+ except OSError:+ pass+ if local_path and local_path not in local_files.values():+ try:+ os.unlink(local_path)+ except OSError:+ passpass # file not found or no access — continuetry:@@ -365,7 +386,8 @@ class DPAPIModule(BaseModule):return []def _parse_chrome_logindata(self, local_files: dict[str, str],- nt_hash: str) -> list[dict]:+ nt_hash: str,+ campaign_id: str = "") -> list[dict]:"""Parse Chrome Login Data SQLite file.Chrome encrypts passwords with AES-256-GCM using a key stored in@@ -381,11 +403,16 @@ class DPAPIModule(BaseModule):return []creds: list[dict] = []+ tmp_db = ""+ fd: int | None = Nonetry:# Copy to avoid SQLite lock errors on the live DB fileimport shutil- _fd_tmp, tmp_db = tempfile.mkstemp(suffix=".db")- import os as _os_db; _os_db.close(_fd_tmp) # mkstemp opens fd — close before shutil.copy2 overwrites+ tmp_db, fd = secure_mkstemp(+ suffix=".db", prefix="ares_dpapi_login_", campaign_id=campaign_id+ )+ os.close(fd)+ fd = Noneshutil.copy2(login_path, tmp_db)conn = sqlite3.connect(tmp_db)@@ -404,12 +431,19 @@ class DPAPIModule(BaseModule):})finally:conn.close()- try:- os.unlink(tmp_db)- except Exception:- passexcept Exception as exc:logger.debug("chrome_parse_failed", error=str(exc)[:80])+ finally:+ if fd is not None:+ try:+ os.close(fd)+ except OSError:+ pass+ if tmp_db:+ try:+ os.unlink(tmp_db)+ except OSError:+ passreturn credsdiff --git a/tests/unit/test_hardening.py b/tests/unit/test_hardening.pyindex 197e616..6d2ee21 100644--- a/tests/unit/test_hardening.py+++ b/tests/unit/test_hardening.py@@ -311,6 +311,134 @@ class TestCredentialArtifactCleanup:assert has_unlink_in_finally, \"BLOCKER-002 FAIL: _auth_with_cert finally block doesn't unlink pfx_path"+ def test_dpapi_uses_secure_mkstemp_for_credential_tempfiles(self):+ """+ BLOCKER-002: windows.dpapi must use secure_mkstemp for credential artifacts.+ """+ source = Path("ares/modules/windows/dpapi.py").read_text(encoding="utf-8")+ assert "secure_mkstemp" in source, \+ "BLOCKER-002 FAIL: dpapi.py not using secure_mkstemp"+ assert "tempfile.mkstemp(" not in source, \+ "BLOCKER-002 FAIL: dpapi.py still uses raw tempfile.mkstemp"++ def test_dpapi_transfer_cleans_secure_temp_on_write_failure(self, tmp_path, monkeypatch):+ """+ BLOCKER-002: _transfer_dpapi_files must unlink a secure temp file if+ transfer succeeds but local persistence fails.+ """+ import builtins+ import types+ from ares.modules.windows import dpapi as dpapi_mod++ created = tmp_path / "dpapi-transfer.tmp"+ calls: dict[str, object] = {"count": 0, "campaign_id": ""}++ def fake_secure_mkstemp(suffix="", prefix="ares_", campaign_id=""):+ calls["count"] = int(calls["count"]) + 1+ calls["campaign_id"] = campaign_id+ fd = os.open(str(created), os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600)+ return str(created), fd++ cleanup_attempts: list[str] = []+ real_unlink = os.unlink++ def tracking_unlink(path):+ cleanup_attempts.append(os.fspath(path))+ real_unlink(path)++ real_open = builtins.open++ def failing_open(path, *args, **kwargs):+ mode = args[0] if args else kwargs.get("mode", "r")+ if os.fspath(path) == str(created) and mode == "wb":+ raise OSError("simulated write failure")+ return real_open(path, *args, **kwargs)++ class FakeSMB:+ def __init__(self, *args, **kwargs):+ self.getfile_calls = 0++ def login(self, *args, **kwargs):+ return None++ def getFile(self, share, remote_path, writer):+ self.getfile_calls += 1+ if self.getfile_calls == 1:+ writer(b"credential bytes")+ return None+ raise FileNotFoundError(remote_path)++ def logoff(self):+ return None++ fake_impacket = types.ModuleType("impacket")+ fake_smbconnection = types.ModuleType("impacket.smbconnection")+ fake_smbconnection.SMBConnection = FakeSMB+ fake_impacket.smbconnection = fake_smbconnection++ monkeypatch.setitem(sys.modules, "impacket", fake_impacket)+ monkeypatch.setitem(sys.modules, "impacket.smbconnection", fake_smbconnection)+ monkeypatch.setattr(dpapi_mod, "secure_mkstemp", fake_secure_mkstemp)+ monkeypatch.setattr(dpapi_mod.os, "unlink", tracking_unlink)+ monkeypatch.setattr(builtins, "open", failing_open)++ module = object.__new__(dpapi_mod.DPAPIModule)+ result = module._transfer_dpapi_files(+ "host", "user", "password", "", "", "", "user",+ campaign_id="campaign-123",+ )++ assert result == {}+ assert calls == {"count": 1, "campaign_id": "campaign-123"}+ assert cleanup_attempts == [str(created)]+ assert not created.exists()++ def test_dpapi_chrome_parse_cleans_secure_temp_on_copy_failure(self, tmp_path, monkeypatch):+ """+ BLOCKER-002: _parse_chrome_logindata must unlink its secure SQLite copy+ even if copying into the temp file fails before sqlite opens it.+ """+ import shutil+ from ares.modules.windows import dpapi as dpapi_mod++ login_path = tmp_path / "Login Data"+ login_path.write_bytes(b"not a real sqlite database")+ created = tmp_path / "dpapi-login-copy.db"+ calls: dict[str, object] = {"count": 0, "campaign_id": ""}++ def fake_secure_mkstemp(suffix="", prefix="ares_", campaign_id=""):+ calls["count"] = int(calls["count"]) + 1+ calls["campaign_id"] = campaign_id+ fd = os.open(str(created), os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600)+ return str(created), fd++ cleanup_attempts: list[str] = []+ real_unlink = os.unlink++ def tracking_unlink(path):+ cleanup_attempts.append(os.fspath(path))+ real_unlink(path)++ def failing_copy2(src, dst):+ assert src == str(login_path)+ assert dst == str(created)+ raise OSError("simulated copy failure")++ monkeypatch.setattr(dpapi_mod, "secure_mkstemp", fake_secure_mkstemp)+ monkeypatch.setattr(dpapi_mod.os, "unlink", tracking_unlink)+ monkeypatch.setattr(shutil, "copy2", failing_copy2)++ module = object.__new__(dpapi_mod.DPAPIModule)+ result = module._parse_chrome_logindata(+ {"chrome_login_data": str(login_path)}, "",+ campaign_id="campaign-123",+ )++ assert result == []+ assert calls == {"count": 1, "campaign_id": "campaign-123"}+ assert cleanup_attempts == [str(created)]+ assert not created.exists()+# ═══════════════════════════════════════════════════════════════════════════════# HIGH-001 PROOF: Subprocess Timeout + Kill