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 2 - hash masking in Finding.evidence Grup B (MOD-027, MOD-042 + systematic grep)
Mafifrizie94533bfae1f
diff --git a/ares/core/security.py b/ares/core/security.pyindex fb4ae8e..a65d997 100644--- a/ares/core/security.py+++ b/ares/core/security.py@@ -721,3 +721,24 @@ def cleanup_all_credential_artifacts() -> int:for scope in all_scopes:total += cleanup_credential_artifacts(scope)return total+++def mask_secret_hash(hash_str: str | Any) -> str:+ """Mask hash for evidence display. Full hash stays in vault/raw."""+ if not hash_str or not isinstance(hash_str, str):+ return "***"+ if ":" in hash_str:+ parts = hash_str.split(":")+ if len(parts) >= 4:+ masked_parts = list(parts)+ for i in range(2, min(4, len(parts))):+ if masked_parts[i] and len(masked_parts[i]) >= 10:+ masked_parts[i] = f"{masked_parts[i][:6]}...{masked_parts[i][-4:]}"+ elif masked_parts[i]:+ masked_parts[i] = "***"+ return ":".join(masked_parts)+ if len(hash_str) < 10:+ return "***"+ return f"{hash_str[:6]}...{hash_str[-4:]}"++diff --git a/ares/modules/ad/dcsync.py b/ares/modules/ad/dcsync.pyindex 26ac7f8..ce2cabd 100644--- a/ares/modules/ad/dcsync.py+++ b/ares/modules/ad/dcsync.py@@ -9,7 +9,7 @@ from ares.core.logger import get_loggerlogger = get_logger("ares.modules.ad.dcsync")from ares.core.campaign import Finding, Severity, NoiseProfile-from ares.core.security import sanitize_hostname, sanitize_ldap+from ares.core.security import mask_secret_hash, sanitize_hostname, sanitize_ldapfrom ares.core.tracing import trace_modulefrom ares.core.errors import ModuleValidationErrorfrom ares.modules.params import DCSyncParams@@ -352,6 +352,6 @@ class DCSyncModule(BaseModule[DCSyncParams, ModuleResult]):+ ("krbtgt obtained - Golden Ticket possible. " if krbtgt else "")),severity=Severity.CRITICAL, mitre_technique="T1003.006", mitre_tactic="Credential Access",evidence={"hash_count":len(hashes),"target":target,"krbtgt_obtained":bool(krbtgt),- "sample":[f"{h['username']}:::{h['nt_hash']}" for h in hashes[:3]]},+ "sample":[f"{h['username']}:::{mask_secret_hash(h['nt_hash'])}" for h in hashes[:3]]},remediation=("1. Reset krbtgt TWICE 24h apart. 2. Investigate replication rights. ""3. Enable Microsoft Defender for Identity."))\ No newline at end of filediff --git a/ares/modules/linux/samba_secrets.py b/ares/modules/linux/samba_secrets.pyindex 209a1fa..962794d 100644--- a/ares/modules/linux/samba_secrets.py+++ b/ares/modules/linux/samba_secrets.py@@ -16,6 +16,7 @@ from typing import Anyfrom ares.core.campaign import Finding, Severityfrom ares.core.errors import ModuleValidationErrorfrom ares.core.logger import audit, get_logger+from ares.core.security import mask_secret_hashfrom ares.core.tracing import trace_modulefrom ares.modules.linux._parsers import TDBParser, compute_ntlm_hashfrom ares.modules.params import SambaSecretsParams@@ -187,6 +188,8 @@ class SambaSecretsModule(BaseModule[SambaSecretsParams, ModuleResult]):evidence_chain: list[EvidenceRecord] = []for sec in extracted_secrets:+ raw_ntlm = sec.get("ntlm_hash")+ masked_ntlm = mask_secret_hash(raw_ntlm)ev = EvidenceRecord(artifact_id=f"samba-secret-{sec.get('domain', 'ad')}",source_target=target,@@ -194,7 +197,7 @@ class SambaSecretsModule(BaseModule[SambaSecretsParams, ModuleResult]):data={"domain": sec.get("domain"),"account": sec.get("account_name"),- "ntlm_hash": sec.get("ntlm_hash"),+ "ntlm_hash": masked_ntlm,},tags=["samba", "secrets", "ntlm"],)@@ -213,7 +216,7 @@ class SambaSecretsModule(BaseModule[SambaSecretsParams, ModuleResult]):"secrets_path": secrets_tdb_path,"domain": sec.get("domain"),"account_name": sec.get("account_name"),- "ntlm_hash": sec.get("ntlm_hash"),+ "ntlm_hash": masked_ntlm,},remediation=("Enforce strict permissions on /var/lib/samba/private/secrets.tdb (chmod 0600). "diff --git a/ares/modules/windows/lsa_secrets.py b/ares/modules/windows/lsa_secrets.pyindex 67077bb..c94ab03 100644--- a/ares/modules/windows/lsa_secrets.py+++ b/ares/modules/windows/lsa_secrets.py@@ -16,9 +16,9 @@ import asyncioimport refrom typing import Any-from ares.core.logger import get_logger, auditfrom ares.core.campaign import Finding, Severity-from ares.core.security import sanitize_hostname+from ares.core.logger import get_logger, audit+from ares.core.security import mask_secret_hash, sanitize_hostnamefrom ares.modules.base import BaseModule, OpsecLevelfrom ares.modules.params import LSASecretsParamsfrom ares.core.tracing import trace_module@@ -369,6 +369,7 @@ class LSASecretsModule(BaseModule):errors = result["errors"]if sam_hashes:+ masked_sam = [mask_secret_hash(h) for h in sam_hashes]self.finding(title=f"SAM Database Dumped - {len(sam_hashes)} Local Account Hash(es) from {target}",description=(@@ -380,7 +381,7 @@ class LSASecretsModule(BaseModule):mitre_technique="T1003.002",mitre_tactic="Credential Access",evidence={"target": target, "hash_count": len(sam_hashes),- "hashes": sam_hashes},+ "hashes": masked_sam},remediation=("Enable Windows Credential Guard to protect credential material. ""Rotate all local administrator passwords immediately. "@@ -417,6 +418,7 @@ class LSASecretsModule(BaseModule):)if cached_creds:+ masked_cached = [mask_secret_hash(h) for h in cached_creds]self.finding(title=f"Cached Domain Credentials (DCC2) Found on {target}",description=(@@ -428,7 +430,7 @@ class LSASecretsModule(BaseModule):mitre_technique="T1003.005",mitre_tactic="Credential Access",evidence={"target": target, "count": len(cached_creds),- "hashes": cached_creds},+ "hashes": masked_cached},remediation=("Set CachedLogonsCount registry value to 0 to disable credential caching ""on non-laptop machines. Use SCCM/Intune offline domain join instead."diff --git a/tests/unit/test_hash_masking_grup_b.py b/tests/unit/test_hash_masking_grup_b.pynew file mode 100644index 0000000..081357e--- /dev/null+++ b/tests/unit/test_hash_masking_grup_b.py@@ -0,0 +1,219 @@+"""+Unit tests for Grup B - Hash Masking in Finding.evidence and EvidenceRecord.data (MOD-027, MOD-042).+Verifies:+1. mask_secret_hash() correctly masks raw and colon-separated hashes.+2. samba_secrets masks ntlm_hash in evidence and EvidenceRecord, but preserves full hash in vault and raw.+3. lsa_secrets masks sam_hashes and cached_creds in evidence, but preserves full hashes in raw.+4. dcsync masks NTLM hash sample in evidence.+"""+from __future__ import annotations++import asyncio+import os+import tempfile+from unittest.mock import AsyncMock, MagicMock++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+from ares.core.security import mask_secret_hash+from ares.modules.ad.dcsync import DCSyncModule+from ares.modules.linux.samba_secrets import SambaSecretsModule+from tests.unit.modules.test_linux_ad_tradecraft import _synthesize_tdb+from ares.modules.params import DCSyncParams, LSASecretsParams, SambaSecretsParams+from ares.modules.windows.lsa_secrets import LSASecretsModule+++def test_mask_secret_hash_behavior():+ # Empty or short+ assert mask_secret_hash("") == "***"+ assert mask_secret_hash(None) == "***"+ assert mask_secret_hash("short") == "***"++ # Standard raw hash (e.g. 32-char hex NTLM hash)+ raw_ntlm = "31d6cfe0d16ae931b73c59d7e0c089c0"+ masked = mask_secret_hash(raw_ntlm)+ assert masked == "31d6cf...89c0"+ assert raw_ntlm not in masked++ # Colon-separated pwdump format: user:rid:lmhash:nthash:::+ pwdump = "Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::"+ masked_pwdump = mask_secret_hash(pwdump)+ assert masked_pwdump == "Administrator:500:aad3b4...04ee:31d6cf...89c0:::"+ assert "aad3b435b51404eeaad3b435b51404ee" not in masked_pwdump+ assert "31d6cfe0d16ae931b73c59d7e0c089c0" not in masked_pwdump+++async def test_samba_secrets_hash_masking(monkeypatch):+ """MOD-042: samba_secrets must mask ntlm_hash in evidence and EvidenceRecord, but keep full in vault & raw."""+ settings = AresSettings(+ ares_secret_key="secret-key-32-chars-minimum-len!",+ ares_encryption_key="enc-key-32-chars-minimum-length!",+ )+ campaign = Campaign(+ name="test",+ client="test",+ scope=[ScopeEntry(cidr="192.168.1.0/24")],+ noise_profile=NoiseProfile.NORMAL,+ )+ noise = NoiseController(campaign)+ mod = SambaSecretsModule(settings=settings, campaign=campaign, noise=noise)+ mock_vault = MagicMock()++ with tempfile.NamedTemporaryFile(suffix=".tdb", delete=False) as f:+ tdb_path = f.name+ records = [+ (b"SECRETS/MACHINE_PASSWORD/CORP", b"P@ssw0rdMachine!\x00"),+ ]+ f.write(_synthesize_tdb(records))++ try:+ ctx = ExecutionContext(+ execution_id="exec-samba-mask",+ campaign_id=campaign.id,+ target="192.168.1.50",+ params=SambaSecretsParams(secrets_tdb_path=tdb_path),+ settings=settings,+ campaign=campaign,+ noise=noise,+ vault=mock_vault,+ dry_run=False,+ )+ res = await mod.execute(ctx)+ assert res.status == "success"+ assert len(res.findings) >= 1++ finding = res.findings[0]+ # Evidence in finding MUST be masked+ evidence_hash = finding.evidence.get("ntlm_hash")+ assert evidence_hash is not None+ assert "..." in evidence_hash+ assert len(evidence_hash) < 32++ # Vault MUST retain full 32-char hash+ assert mock_vault.store.called+ _, stored_val = mock_vault.store.call_args[0]+ assert len(stored_val) == 32+ assert stored_val.startswith(evidence_hash[:6])+ assert stored_val.endswith(evidence_hash[-4:])++ # Raw output MUST retain full 32-char hash+ assert len(res.raw["secrets"]) == 1+ raw_secret_hash = res.raw["secrets"][0]["ntlm_hash"]+ assert len(raw_secret_hash) == 32+ assert raw_secret_hash == stored_val+ finally:+ if os.path.exists(tdb_path):+ os.remove(tdb_path)+++async def test_lsa_secrets_hash_masking(monkeypatch):+ """MOD-027: lsa_secrets must mask sam_hashes and cached_creds in evidence, but keep full in raw."""+ settings = AresSettings(+ ares_secret_key="secret-key-32-chars-minimum-len!",+ ares_encryption_key="enc-key-32-chars-minimum-length!",+ )+ campaign = Campaign(+ name="test",+ client="test",+ scope=[ScopeEntry(cidr="192.168.1.0/24")],+ noise_profile=NoiseProfile.NORMAL,+ )+ noise = NoiseController(campaign)+ mod = LSASecretsModule(settings=settings, campaign=campaign, noise=noise)++ sample_sam = [+ "Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::",+ ]+ sample_cached = [+ "$DCC2$10240#testuser#31d6cfe0d16ae931b73c59d7e0c089c0",+ ]++ async def fake_dump(self_mod, *args, **kwargs):+ pass++ ctx = ExecutionContext(+ execution_id="exec-lsa-mask",+ campaign_id=campaign.id,+ target="192.168.1.50",+ params=LSASecretsParams(target="192.168.1.50", username="Admin", password="Password123!"),+ settings=settings,+ campaign=campaign,+ noise=noise,+ dry_run=False,+ )++ import sys+ impacket_mock = MagicMock()+ monkeypatch.setitem(sys.modules, "impacket", impacket_mock)+ monkeypatch.setitem(sys.modules, "impacket.examples", impacket_mock)+ monkeypatch.setitem(sys.modules, "impacket.examples.secretsdump", impacket_mock)+ monkeypatch.setitem(sys.modules, "impacket.smbconnection", impacket_mock)++ # Mock loop.run_in_executor to return sample sam & cached hashes+ loop = asyncio.get_running_loop()+ async def mock_run_in_executor(executor, func, *args):+ return {+ "sam": sample_sam,+ "lsa": ["_SC_Service:SecretVal"],+ "cached": sample_cached,+ "errors": [],+ }+ monkeypatch.setattr(loop, "run_in_executor", mock_run_in_executor)++ res = await mod.execute(ctx)+ assert res.status in ("partial", "success")++ # Find SAM finding and Cached finding+ sam_finding = next((f for f in res.findings if "SAM Database Dumped" in f.title), None)+ assert sam_finding is not None+ assert "..." in sam_finding.evidence["hashes"][0]+ assert "31d6cfe0d16ae931b73c59d7e0c089c0" not in sam_finding.evidence["hashes"][0]++ cached_finding = next((f for f in res.findings if "Cached Domain Credentials" in f.title), None)+ assert cached_finding is not None+ assert "..." in cached_finding.evidence["hashes"][0]+ assert "31d6cfe0d16ae931b73c59d7e0c089c0" not in cached_finding.evidence["hashes"][0]++ # Raw output MUST have full unmasked hashes+ assert res.raw["sam_hashes"] == sample_sam+ assert res.raw["cached_credentials"] == sample_cached+ assert res.raw["ntlm_hashes"] == sample_sam+++async def test_dcsync_hash_masking():+ """Verify DCSync masks sample NTLM hash in finding evidence."""+ settings = AresSettings(+ ares_secret_key="secret-key-32-chars-minimum-len!",+ ares_encryption_key="enc-key-32-chars-minimum-length!",+ )+ campaign = Campaign(+ name="test",+ client="test",+ scope=[ScopeEntry(cidr="192.168.1.0/24")],+ noise_profile=NoiseProfile.NORMAL,+ )+ noise = NoiseController(campaign)+ mod = DCSyncModule(settings=settings, campaign=campaign, noise=noise)++ raw_output = {+ "ntlm_hashes": [+ {"username": "krbtgt", "rid": "502", "nt_hash": "31d6cfe0d16ae931b73c59d7e0c089c0"},+ {"username": "Administrator", "rid": "500", "nt_hash": "8846f7eaee8fb117ad06bdd830b7586c"},+ ]+ }+ mod._analyze(raw_output, "192.168.1.10")+ assert len(mod._findings) == 1+ finding = mod._findings[0]+ sample = finding.evidence["sample"]+ assert len(sample) == 2+ assert "31d6cfe0d16ae931b73c59d7e0c089c0" not in sample[0]+ assert "..." in sample[0]+ assert "8846f7eaee8fb117ad06bdd830b7586c" not in sample[1]+ assert "..." in sample[1]