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.

12.8 KB
Raw Blame
"""
ARES Exfil Module - SMB Share Enumeration & Staging (T1039 / T1021.002)

Enumerates accessible SMB shares with impacket SMBConnection:
  1. connect() to target on port 445
  2. listShares() - get all share names
  3. listPath(share, "*") - recursively scan each share for sensitive filenames
  4. logoff() - clean disconnect

MITRE ATT&CK:
  T1039  - Data from Network Shared Drive
  T1021.002 - Remote Services: SMB/Windows Admin Shares
"""
from __future__ import annotations

import fnmatch
from typing import Any

from ares.core.campaign import Finding, Severity
from ares.core.logger import audit, get_logger
from ares.core.tracing import trace_module
from ares.modules.base import BaseModule, OpsecLevel
from ares.modules.params import SmbSharesParams
from ares.sdk import (
    EvidenceRecord,
    LockoutCircuitBreaker,
    ModuleResult,
    NetworkPermission,
    ProcessPermission,
    module_contract,
)

logger = get_logger("ares.modules.exfil.smb_shares")

_SENSITIVE_PATTERNS: list[str] = [
    "*.config", "web.config", "appsettings*.json",
    "*.kdbx", "*.pfx", "*.key", "*.pem", "*.p12",
    "id_rsa", "id_ecdsa", "id_ed25519",
    "password*", "passwords*", "credential*", "creds*",
    "secret*", "secrets*", "*.env", ".env",
    "NTDS.dit", "SAM", "SYSTEM", "SECURITY",
    "*.rdp", "*.ppk", "*.ovpn",
]
_SKIP_SHARES: set[str] = {"IPC$", "PRINT$", "print$"}


def _is_sensitive(filename: str) -> bool:
    name = filename.lower()
    return any(fnmatch.fnmatch(name, p.lower()) for p in _SENSITIVE_PATTERNS)


def _list_share_recursive(conn: Any, share: str, path: str = "*",
                           max_depth: int = 4, depth: int = 0) -> list[str]:
    if depth > max_depth:
        return []
    hits: list[str] = []
    try:
        entries = conn.listPath(share, path)
    except Exception:
        return hits
    for entry in entries:
        name = entry.get_longname()
        if name in (".", ".."):
            continue
        if entry.is_directory() and depth < max_depth:
            sub = path.rstrip("*").rstrip("\\") + f"\\{name}\\*"
            hits.extend(_list_share_recursive(conn, share, sub, max_depth, depth + 1))
        elif not entry.is_directory() and _is_sensitive(name):
            base = path.rstrip("*").rstrip("\\")
            hits.append(f"\\\\{conn.getRemoteName()}\\{share}{base}\\{name}")
    return hits


@module_contract(
    permissions=[
        NetworkPermission(ports=[139, 445], protocols=["tcp"]),
        ProcessPermission(allow_subprocesses=False),
    ],
    circuit_breaker=LockoutCircuitBreaker(),
    params_model=SmbSharesParams,
)
class SmbSharesExfil(BaseModule):
    """
    exfil.smb_shares - Enumerate accessible SMB shares and scan for sensitive files including configs, keys, and credential

    OPSEC: MEDIUM
    MITRE: "T1039", "T1021.002"
    REQUIRES: "target", "credential"
    OUTPUTS:  "file_share_list", "sensitive_file_paths"
    """
    MODULE_ID        = "exfil.smb_shares"
    MODULE_NAME      = "SMB Share Enumeration"
    MODULE_CATEGORY  = "exfil"
    MODULE_DESCRIPTION = "Enumerate accessible SMB shares and scan for sensitive files including configs, keys, and credentials"
    MODULE_AUTHOR      = "ARES Team <[email protected]>"
    REQUIRES         = ["target", "credential"]
    OUTPUTS          = ["file_share_list", "sensitive_file_paths"]
    MITRE_TECHNIQUES = ["T1039", "T1021.002"]
    PARAMS_MODEL     = SmbSharesParams

    OPSEC_LEVEL      = OpsecLevel.MEDIUM

    async def validate(self, ctx: "Any") -> None:
        """Pre-flight param checks before any network call."""
        await super().validate(ctx)
        from ares.core.context import ExecutionContext
        from ares.core.errors import ModuleValidationError
        if not isinstance(ctx, ExecutionContext):
            return
        target = getattr(ctx, "target", "") or ctx.params.get("target", "")
        if not target:
            raise ModuleValidationError(
                "exfil.smb_shares requires 'target' - IP of Windows/Samba host.",
                module_id=self.MODULE_ID, field="target",
            )

    async def execute(self, ctx: "Any") -> "ModuleResult":
        """ExecutionContext-based entry point (v0.9.0+)."""
        from ares.modules.base import ModuleResult
        if getattr(ctx, "dry_run", False):
            return ModuleResult(status="dry_run", module_id=self.MODULE_ID,
                                raw={"dry_run": True})

        params = getattr(ctx, "params", {})
        if isinstance(params, SmbSharesParams):
            kwargs = params.model_dump()
        elif isinstance(params, dict):
            kwargs = dict(params)
        else:
            kwargs = {}

        raw_pwd = kwargs.get("password") or getattr(ctx, "password", "")
        if hasattr(raw_pwd, "get_secret_value"):
            kwargs["password"] = raw_pwd.get_secret_value()
        elif raw_pwd is not None:
            kwargs["password"] = str(raw_pwd)
        else:
            kwargs["password"] = ""

        if not kwargs.get("target") and getattr(ctx, "target", ""):
            kwargs["target"] = ctx.target

        findings, raw = await self.run(**kwargs)

        # Cryptographic Evidence Records with SHA-256 Merkle Provenance
        evidence_chain: list[EvidenceRecord] = []
        for file_path in raw.get("sensitive_file_paths", [])[:20]:
            file_name = file_path.rsplit("\\", 1)[-1]
            ev = EvidenceRecord(
                artifact_id=f"smb-file-{file_name.lower().replace('.', '-')}",
                source_target=getattr(ctx, "target", kwargs.get("target", "")),
                collected_by=self.MODULE_ID,
                data={
                    "file_path": file_path,
                    "target": getattr(ctx, "target", kwargs.get("target", "")),
                },
                tags=["exfil", "smb_shares", "t1039"],
            )
            evidence_chain.append(ev)

        raw["evidence_chain"] = [e.data for e in evidence_chain]
        raw["evidence_integrity"] = [e.record_hash for e in evidence_chain]

        # Closed-loop Purple Telemetry Synthesis (Sentinel KQL + Sigma YAML)
        kql_rule = (
            "// Microsoft Sentinel - Extensive SMB Network Share Enumeration & Access\n"
            "SecurityEvent\n"
            "| where TimeGenerated > ago(2h)\n"
            "| where EventID in (5140, 5145)\n"
            "| summarize AccessedShares = dcount(ShareName), AccessCount = count() by Account, IpAddress, bin(TimeGenerated, 10m)\n"
            "| where AccessedShares >= 3 or (ShareName has_any (\"C$\", \"ADMIN$\", \"IPC$\") and AccessCount > 10)\n"
            "| project TimeGenerated, Account, IpAddress, AccessedShares, AccessCount"
        )
        sigma_rule = (
            "title: Network Share Enumeration and Administrative Share Access\n"
            "id: c3d4e5f6-a7b8-49c0-d1e2-f3a4b5c6d7e8\n"
            "status: experimental\n"
            "description: Detects enumeration of multiple network shares or administrative shares (C$, ADMIN$) via SMB\n"
            "references:\n"
            "    - https://attack.mitre.org/techniques/T1039/\n"
            "    - https://attack.mitre.org/techniques/T1135/\n"
            "author: ARES Purple Team Modernization\n"
            "date: 2026-03-30\n"
            "logsource:\n"
            "    product: windows\n"
            "    service: security\n"
            "detection:\n"
            "    selection:\n"
            "        EventID: 5140\n"
            "    condition: selection | count(ShareName) by Account, IpAddress > 2\n"
            "level: medium\n"
            "tags:\n"
            "    - attack.discovery\n"
            "    - attack.collection\n"
            "    - attack.t1039\n"
            "    - attack.t1135"
        )
        raw.setdefault("loot", {})
        raw["loot"]["detection_kql"] = kql_rule
        raw["loot"]["detection_sigma"] = sigma_rule
        shares = [s.get("name", "") if isinstance(s, dict) else str(s) for s in raw.get("file_share_list", [])]
        raw["administrative_shares_accessible"] = any("ADMIN$" in s or "C$" in s for s in shares)
        raw["anonymous_share_read_allowed"] = any("READ" in str(s).upper() for s in raw.get("file_share_list", []))
        raw["sensitive_files_discovered"] = bool(raw.get("sensitive_file_paths"))
        raw["smb_share_audit_complete"] = True

        return ModuleResult(
            status="success" if (findings or raw.get("file_share_list")) else "partial",
            findings=findings, raw=raw, module_id=self.MODULE_ID,
            execution_id=getattr(ctx, "execution_id", ""),
        )

    @trace_module("exfil.smb_shares")
    async def run(self, **kwargs: Any) -> tuple[list[Finding], dict[str, Any]]:
        ctx       = kwargs.get("ctx") or kwargs
        target    = ctx.get("target", "")
        dry_run   = ctx.get("dry_run", False)   # Fixed: was True
        username  = ctx.get("username", "")
        password  = ctx.get("password", "")
        domain    = ctx.get("domain", "")
        max_depth = int(ctx.get("max_depth", 3))

        if not target:
            return [], {"error": "no_target"}

        logger.info("smb_shares_enum", target=target, dry_run=dry_run)
        audit("smb_shares_enum", actor=username or "operator", source="operator",
              target=target, technique="T1039")

        if dry_run:
            # Dry-run must NOT fabricate findings. Returning a hardcoded HIGH
            # "sensitive files on SMB" finding with invented share/file paths
            # poisons the validated-findings pipeline. (AUDIT run-1 H13)
            return [], {"dry_run": True}

        try:
            from impacket.smbconnection import SMBConnection
        except ImportError:
            return [], {"error": "impacket_not_installed"}

        if not username:
            return [], {"error": "no_credential_username"}

        await self.before_request(target, "smb")

        import asyncio as _asyncio
        loop = _asyncio.get_running_loop()

        def _smb_enum_sync() -> tuple[list[str], list[str]]:
            """
            All blocking SMB operations in one sync function - runs in executor.
            Wrapping in run_in_executor prevents freezing the event loop during
            SMBConnection.login(), listShares(), and recursive listPath() calls.
            """
            conn = None
            try:
                conn = SMBConnection(target, target, sess_port=445, timeout=10)
                conn.login(username, password, domain)

                share_list: list[str] = []
                try:
                    for s in conn.listShares():
                        share_list.append(s["shi1_netname"][:-1])
                except Exception as exc:
                    logger.warning("smb_list_shares_failed", target=target,
                                   error=str(exc)[:80])

                all_hits: list[str] = []
                for share in share_list:
                    if share in _SKIP_SHARES:
                        continue
                    try:
                        hits = _list_share_recursive(conn, share, "*",
                                                     max_depth=max_depth)
                        all_hits.extend(hits)
                        logger.debug("smb_share_scanned", share=share, hits=len(hits))
                    except Exception as exc:
                        logger.debug("smb_share_scan_error", share=share,
                                     error=str(exc)[:80])

                return share_list, all_hits
            finally:
                if conn:
                    try:
                        conn.logoff()
                    except Exception:
                        pass

        try:
            share_list, all_hits = await loop.run_in_executor(None, _smb_enum_sync)
        except Exception as exc:
            raise self._classify_error(exc) from exc

        if all_hits:
            self.finding(
                title       = f"Sensitive files on SMB shares ({target})",
                description = (
                    f"Enumerated {len(share_list)} shares. "
                    f"Found {len(all_hits)} sensitive file(s):\n"
                    + "\n".join(all_hits[:20])
                    + (f"\n...and {len(all_hits)-20} more" if len(all_hits) > 20 else "")
                ),
                severity=Severity.HIGH, confidence=0.90,
                mitre_technique="T1039", mitre_tactic="Collection",
                evidence={"sensitive_files": all_hits[:50]},
                remediation=(
                    "Restrict share permissions. Enable SMB auditing. "
                    "Rotate any credentials found in config files."
                ),
                host=target,
            )

        return self._findings[:], {
            "file_share_list":      share_list,
            "sensitive_file_paths": all_hits,
            "sensitive_data_found": bool(all_hits),
            "shares_scanned":       len(share_list),
            "files_found":          len(all_hits),
        }