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.

18.5 KB
Raw Blame
"""
SNMP Enumeration - Community String Testing + OID Walk
MITRE: T1046, T1590

Tests common SNMP community strings (v1/v2c) and enumerates system information
via SNMP GET/WALK on standard OIDs:
  sysDescr, sysName, sysLocation, sysContact,
  ifTable (network interfaces), hrSWRunTable (running processes),
  hrStorageTable (disk info)

Flags:
  - Default community string "public" or "private" - HIGH severity
  - System info disclosure - MEDIUM
  - Network interface enumeration - INFO

Requires: pip install ares-redteam[network] (adds pysnmp)

OpSec: LOW - SNMP UDP is low-noise but creates log entries on managed devices.
"""
from __future__ import annotations

import asyncio
from typing import Any

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

logger = get_logger("ares.modules.network.snmp_enum")

# Community strings to test, ordered by likelihood
_COMMUNITY_STRINGS: list[str] = [
    "public", "private", "community", "manager",
    "admin", "cisco", "monitor", "snmp", "default",
    "read", "write", "access", "guest", "network",
    "security", "system", "secret", "pass", "1234",
]

# Standard OIDs for system enumeration
_OID_MAP: dict[str, str] = {
    "1.3.6.1.2.1.1.1.0":  "sysDescr",       # System description
    "1.3.6.1.2.1.1.3.0":  "sysUpTime",      # Uptime
    "1.3.6.1.2.1.1.4.0":  "sysContact",     # Admin contact
    "1.3.6.1.2.1.1.5.0":  "sysName",        # Hostname
    "1.3.6.1.2.1.1.6.0":  "sysLocation",    # Physical location
    "1.3.6.1.2.1.1.2.0":  "sysObjectID",    # Vendor OID
}

# OID prefixes for table walks
_WALK_OIDS: dict[str, str] = {
    "1.3.6.1.2.1.2.2.1.2":  "ifDescr",         # Interface names
    "1.3.6.1.2.1.2.2.1.3":  "ifType",           # Interface types
    "1.3.6.1.2.1.25.4.2.1.2": "hrSWRunName",   # Running processes
    "1.3.6.1.2.1.25.2.3.1.3": "hrStorageDescr", # Storage descriptions
}


def _snmp_get_sync(host: str, community: str, port: int,
                    oids: list[str], timeout: int = 3) -> dict[str, str]:
    """
    Synchronous pysnmp GET for a list of OIDs.
    Returns dict {oid_name: value}. Empty dict if community wrong or host unreachable.
    """
    try:
        from pysnmp.hlapi import (
            CommunityData,
            ContextData,
            ObjectIdentity,
            ObjectType,
            SnmpEngine,
            UdpTransportTarget,
            getCmd,
        )
    except ImportError:
        return {"_error": "pysnmp not installed - run: pip install pysnmp"}

    results: dict[str, str] = {}
    engine = SnmpEngine()
    for oid in oids:
        error_indication, error_status, _, var_binds = next(
            getCmd(
                engine,
                CommunityData(community, mpModel=1),  # mpModel=1 = SNMPv2c
                UdpTransportTarget((host, port), timeout=timeout, retries=0),
                ContextData(),
                ObjectType(ObjectIdentity(oid)),
            )
        )
        if error_indication or error_status:
            continue
        for var_bind in var_binds:
            label = _OID_MAP.get(oid, oid.split(".")[-1])
            results[label] = str(var_bind[1])
    return results


def _snmp_walk_sync(host: str, community: str, port: int,
                     oid_prefix: str, label: str,
                     max_rows: int = 30, timeout: int = 3) -> list[str]:
    """
    Synchronous pysnmp WALK for a table OID prefix.
    Returns list of string values (up to max_rows).
    """
    try:
        from pysnmp.hlapi import (
            CommunityData,
            ContextData,
            ObjectIdentity,
            ObjectType,
            SnmpEngine,
            UdpTransportTarget,
            nextCmd,
        )
    except ImportError:
        return ["_error: pysnmp not installed"]

    rows: list[str] = []
    engine = SnmpEngine()
    for error_indication, error_status, _, var_binds in nextCmd(
        engine,
        CommunityData(community, mpModel=1),
        UdpTransportTarget((host, port), timeout=timeout, retries=0),
        ContextData(),
        ObjectType(ObjectIdentity(oid_prefix)),
        lexicographicMode=False,
    ):
        if error_indication or error_status:
            break
        for var_bind in var_binds:
            rows.append(str(var_bind[1]))
            if len(rows) >= max_rows:
                break
        if len(rows) >= max_rows:
            break
    return rows


@module_contract(
    permissions=[
        NetworkPermission(ports=[161, 162], protocols=["udp"]),
        ProcessPermission(allow_subprocesses=False),
    ],
    circuit_breaker=LockoutCircuitBreaker(),
    params_model=SNMPEnumParams,
)
class SnmpEnumModule(BaseModule):
    """
    network.snmp_enum - Test common SNMP community strings and enumerate system info via OID walk - identifies default credentials, system details, interfaces, and running processes

    OPSEC: LOW
    MITRE: "T1046", "T1590"
    OUTPUTS:  "snmp_findings", "system_info"
    """
    MODULE_ID          = "network.snmp_enum"
    MODULE_NAME        = "SNMP Enumeration"
    MODULE_CATEGORY    = "network"
    MODULE_DESCRIPTION = (
        "Test common SNMP community strings and enumerate system info via OID walk - "
        "identifies default credentials, system details, interfaces, and running processes"
    )
    MODULE_AUTHOR      = "ARES Team <[email protected]>"
    OPSEC_LEVEL        = OpsecLevel.LOW
    REQUIRES           = []
    OUTPUTS            = ["snmp_findings", "system_info", "valid_credentials"]
    MITRE_TECHNIQUES   = ["T1046", "T1590"]
    PARAMS_MODEL       = SNMPEnumParams

    async def validate(self, ctx: "Any") -> None:
        """Pre-flight param checks before any network call."""
        from ares.core.context import ExecutionContext
        from ares.core.errors import ModuleValidationError
        if not isinstance(ctx, ExecutionContext):
            return
        if isinstance(ctx.params, dict):
            if not ctx.params.get("target") and getattr(ctx, "target", None):
                ctx.params["target"] = ctx.target
        target = getattr(ctx, "target", "") or (ctx.params.get("target", "") if isinstance(ctx.params, dict) else getattr(ctx.params, "target", ""))
        if not target:
            raise ModuleValidationError(
                f"{self.MODULE_ID} requires 'target' - IP or hostname.",
                module_id=self.MODULE_ID, field="target",
            )
        await super().validate(ctx)

    async def execute(self, ctx: "Any") -> "ModuleResult":
        """ExecutionContext-based entry point (v0.9.0+).
        Thin adapter: extract params from ctx → call run() → return ModuleResult.
        """
        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,
                                     "target": getattr(ctx, "target", "")})
        target = getattr(ctx, "target", "")
        port = 161
        communities = None
        extra_params: dict[str, Any] = {}

        params = getattr(ctx, "params", {})
        if isinstance(params, SNMPEnumParams):
            target = params.target or target
            port = params.port or port
            communities = params.communities
        elif isinstance(params, dict):
            target = params.get("target") or target
            port = int(params.get("port") or params.get("snmp_port", 161))
            communities = params.get("communities")
            extra_params = {k: v for k, v in params.items() if k not in ("target", "port", "snmp_port", "communities")}

        kwargs: dict[str, Any] = {"target": target, "port": port, "ctx": ctx, "vault": getattr(ctx, "vault", None), **extra_params}
        if communities is not None:
            kwargs["communities"] = communities

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

        # Cryptographic Evidence Records with SHA-256 Merkle Provenance
        evidence_chain: list[EvidenceRecord] = []
        for finding in findings:
            ev = EvidenceRecord(
                artifact_id=f"snmp-{target.replace('.', '-')}",
                source_target=target,
                collected_by=self.MODULE_ID,
                data={
                    "target": target,
                    "title": finding.title,
                    "severity": str(finding.severity),
                },
                tags=["network", "snmp_enum"],
            )
            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 - SNMP Community String Brute-Force & Walk\n"
            "NetworkSession\n"
            "| where TimeGenerated > ago(1h)\n"
            "| where DestinationPort in (161, 162) and NetworkProtocol =~ \"UDP\"\n"
            "| summarize RequestCount = count(), UniqueDestinations = dcount(DestinationIp) by SourceIp, bin(TimeGenerated, 5m)\n"
            "| where RequestCount >= 10\n"
            "| project TimeGenerated, SourceIp, RequestCount, UniqueDestinations"
        )
        sigma_rule = (
            "title: SNMP Community String Enumeration and Polling\n"
            "id: f1a2b3c4-d5e6-47a8-b9c0-d1e2f3a4b5c6\n"
            "status: experimental\n"
            "description: Detects rapid UDP port 161 SNMP polling indicative of community string brute force or OID walking\n"
            "references:\n"
            "    - https://attack.mitre.org/techniques/T1046/\n"
            "author: ARES Purple Team Modernization\n"
            "date: 2026-03-30\n"
            "logsource:\n"
            "    category: network_traffic\n"
            "detection:\n"
            "    selection:\n"
            "        DestinationPort: 161\n"
            "        Protocol: udp\n"
            "    condition: selection | count() by SourceIp > 10\n"
            "level: medium\n"
            "tags:\n"
            "    - attack.discovery\n"
            "    - attack.t1046"
        )
        raw.setdefault("loot", {})
        raw["loot"]["detection_kql"] = kql_rule
        raw["loot"]["detection_sigma"] = sigma_rule
        raw["snmp_v1_v2c_exposed"] = bool(raw.get("valid_communities"))
        raw["default_community_detected"] = any(
            c in ["public", "private", "community"] for c in raw.get("valid_communities", [])
        )
        raw["snmp_write_access_detected"] = "private" in raw.get("valid_communities", [])
        raw["snmp_enumeration_audited"] = True

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

    @trace_module("network.snmp_enum")
    async def run(self, **kwargs: Any) -> tuple[list[Finding], dict[str, Any]]:
        target      = kwargs.get("target", "")
        port        = int(kwargs.get("port") or kwargs.get("snmp_port", 161))
        dry_run     = kwargs.get("dry_run", False)
        communities = kwargs.get("communities") or _COMMUNITY_STRINGS
        do_walk     = kwargs.get("walk", True)    # Walk tables for deeper enum
        vault       = kwargs.get("vault")
        ctx         = kwargs.get("ctx")
        _vault      = vault or getattr(getattr(self, "campaign", None), "_vault", None) or (getattr(ctx, "vault", None) if ctx else None)

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

        await self.before_request(target, "snmp")  # scope check + jitter

        logger.info("snmp_enum_start", target=target, port=port,
                    community_count=len(communities))
        await self.noise.rate_limiter.acquire("network_scan")
        await self.noise.jitter.sleep()

        loop = asyncio.get_running_loop()
        valid_communities: list[dict[str, Any]] = []
        system_info: dict[str, Any] = {}

        # ── Test each community string ─────────────────────────────────────────
        for community in communities:
            await self.noise.jitter.sleep()
            result = await loop.run_in_executor(
                None,
                lambda c=community: _snmp_get_sync(
                    target, c, port, list(_OID_MAP.keys())
                )
            )

            if result.get("_error"):
                # pysnmp not installed - stop here
                return [], {"error": result["_error"]}

            if not result:
                continue  # Community string wrong or host unreachable

            # Valid community string found
            entry: dict[str, Any] = {
                "community":   community,
                "system_info": result,
            }

            # ── Walk tables for deeper enumeration ─────────────────────────────
            if do_walk:
                for oid_prefix, label in _WALK_OIDS.items():
                    rows = await loop.run_in_executor(
                        None,
                        lambda op=oid_prefix, lbl=label, comm=community: _snmp_walk_sync(
                            target, comm, port, op, lbl
                        )
                    )
                    if rows:
                        entry[label] = rows

            valid_communities.append(entry)
            system_info = result  # Use last valid community's info for summary
            logger.info("snmp_valid_community",
                        target=target, community=community,
                        sys_name=result.get("sysName", "?"))

            # Store to AresVault if available (Gate 6 compliant)
            if _vault:
                from ares.credential.vault import Credential, CredentialType, PrivilegeLevel
                try:
                    cred = Credential(
                        username="snmp",
                        domain=target,
                        cred_type=CredentialType.CLEARTEXT,
                        privilege=PrivilegeLevel.LOCAL_ADMIN if community.lower() in ("private", "write") else PrivilegeLevel.LOCAL_USER,
                        source_module=self.MODULE_ID,
                        target_host=target,
                    )
                    _vault.store(cred, community)
                except Exception as exc:
                    logger.debug("snmp_vault_store_failed", target=target, community=community, error=str(exc)[:60])

            # Emit finding
            is_default = community.lower() in ("public", "private")
            sev = Severity.HIGH if is_default else Severity.MEDIUM
            self.finding(
                title=f"SNMP Valid Community String '{community}' on {target}:{port}",
                description=(
                    f"SNMP community string '{community}' is accepted by {target}. "
                    f"{'This is a DEFAULT community string.' if is_default else ''} "
                    f"System: {result.get('sysName', 'unknown')} - "
                    f"{result.get('sysDescr', '')[:150]}"
                ),
                severity=sev,
                mitre_technique="T1046",
                mitre_tactic="Discovery",
                evidence={
                    "host":        target,
                    "port":        port,
                    "community":   community,
                    "is_default":  is_default,
                    "system_info": result,
                },
                remediation=(
                    "Change all SNMP community strings from default values. "
                    "Use long random strings (20+ chars). "
                    "Upgrade to SNMPv3 with authentication and privacy (AES). "
                    "Restrict SNMP access by source IP via ACL. "
                    "If SNMP is not needed, disable the service entirely."
                ),
                host=target,
                confidence=1.0,
            )

            # Don't spray all community strings if we found one
            # (stay low-noise - operator can re-run with specific communities if needed)
            break

        # ── System info finding if sysLocation/sysContact found ───────────────
        if system_info.get("sysLocation") or system_info.get("sysContact"):
            self.finding(
                title=f"SNMP System Information Disclosed: {system_info.get('sysName', target)}",
                description=(
                    "SNMP enumeration revealed system details that assist in targeting. "
                    f"Name: {system_info.get('sysName', 'unknown')} | "
                    f"Location: {system_info.get('sysLocation', 'unknown')} | "
                    f"Contact: {system_info.get('sysContact', 'unknown')}"
                ),
                severity=Severity.LOW,
                mitre_technique="T1590",
                mitre_tactic="Reconnaissance",
                evidence={"host": target, "system_info": system_info},
                remediation=(
                    "Remove sysLocation and sysContact from SNMP configuration if not required. "
                    "Ensure sysDescr does not disclose OS version or vendor information."
                ),
                host=target,
                confidence=0.95,
            )

        valid_creds = [
            {
                "username": "snmp",
                "password": e["community"],
                "target": target,
                "port": port,
                "method": "snmp_community",
                "protocol": "snmp",
                "privilege": "local_admin" if e["community"].lower() in ("private", "write") else "user",
                "domain": target,
            }
            for e in valid_communities
        ]

        raw = {
            "target":             target,
            "port":               port,
            "valid_communities":  valid_communities,
            "system_info":        system_info,
            "communities_tested": len(communities),
            "valid_credentials":  valid_creds,
        }
        raw["snmp_findings"] = [
            f.model_dump() if hasattr(f, "model_dump") else (f.dict() if hasattr(f, "dict") else vars(f))
            for f in self._findings
        ]
        return self._findings[:], raw