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.

15.7 KB
Raw Blame
"""
AWS IAM Privilege Escalation
MITRE: T1078.004, T1548 (Abuse Elevation Control)

Checks for IAM privilege escalation paths using current credentials:
  - PassRole abuse (iam:PassRole + ec2/lambda/etc CreateFunction)
  - AssumeRole with overly permissive trust policies
  - Inline policy with iam:CreatePolicyVersion / iam:SetDefaultPolicyVersion
  - Attached admin policies on accessible roles

Based on Rhino Security Labs IAM privesc research.
"""
from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ares.modules.base import ModuleResult


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 AWSPrivescParams
from ares.sdk import (
    CircuitBreaker,
    EvidenceRecord,
    NetworkPermission,
    ProcessPermission,
    module_contract,
)

logger = get_logger("ares.modules.cloud.aws_privesc")

# IAM actions that indicate privilege escalation paths
_PRIVESC_ACTIONS: list[tuple[str, str, str]] = [
    ("iam:CreatePolicyVersion",        "Create new policy version with admin perms", "T1548"),
    ("iam:SetDefaultPolicyVersion",    "Revert to older policy version with more perms", "T1548"),
    ("iam:CreateAccessKey",            "Create new access key for any user", "T1098"),
    ("iam:CreateLoginProfile",         "Set password for user without console access", "T1098"),
    ("iam:UpdateLoginProfile",         "Change password for any user", "T1098"),
    ("iam:AttachUserPolicy",           "Attach admin policy to self", "T1548"),
    ("iam:AttachGroupPolicy",          "Attach admin policy to own group", "T1548"),
    ("iam:AttachRolePolicy",           "Attach admin policy to role", "T1548"),
    ("iam:PutUserPolicy",              "Create inline admin policy on self", "T1548"),
    ("iam:AddUserToGroup",             "Add self to privileged group", "T1078"),
    ("iam:PassRole",                   "Pass privileged role to compute service", "T1548"),
    ("sts:AssumeRole",                 "Assume another role - check trust policy", "T1550.001"),
    ("lambda:CreateFunction",          "Create Lambda with privileged execution role", "T1648"),
    ("ec2:RunInstances",               "Launch EC2 with privileged instance profile", "T1578.002"),
    ("cloudformation:CreateStack",     "Deploy stack with privileged service role", "T1578"),
    ("glue:CreateDevEndpoint",         "Create Glue endpoint with admin role", "T1578"),
]


@module_contract(
    permissions=[
        NetworkPermission(ports=[443], protocols=["tcp"]),
        ProcessPermission(allow_subprocesses=False),
    ],
    circuit_breaker=CircuitBreaker(name="cloud.aws_privesc", failure_threshold=5),
    params_model=AWSPrivescParams,
)
class AWSPrivescModule(BaseModule):
    """
    cloud.aws_privesc - Enumerate current IAM permissions and identify privilege escalation paths - PassRole abuse, Assu

    OPSEC: LOW
    MITRE: "T1078.004", "T1548", "T1098"
    OUTPUTS:  "aws_privesc_paths", "iam_privesc_paths"
    """
    MODULE_ID          = "cloud.aws_privesc"
    MODULE_NAME        = "AWS IAM Privilege Escalation"
    MODULE_CATEGORY    = "cloud"
    MODULE_DESCRIPTION = (
        "Enumerate current IAM permissions and identify privilege escalation paths - "
        "PassRole abuse, AssumeRole, policy manipulation techniques"
    )
    MODULE_AUTHOR      = "ARES Team <[email protected]>"
    OPSEC_LEVEL        = OpsecLevel.LOW
    REQUIRES           = []
    OUTPUTS            = ["aws_privesc_paths", "iam_privesc_paths"]
    MITRE_TECHNIQUES   = ["T1078.004", "T1548", "T1098"]
    PARAMS_MODEL       = AWSPrivescParams

    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
        params = getattr(ctx, "params", {})
        if isinstance(params, AWSPrivescParams):
            pdict = params.model_dump()
        elif isinstance(params, dict):
            pdict = dict(params)
        else:
            pdict = {}
        has_key = bool(pdict.get("access_key") or
                       pdict.get("aws_access_key") or
                       pdict.get("profile") or
                       __import__("os").environ.get("AWS_ACCESS_KEY_ID"))
        if not has_key:
            raise ModuleValidationError(
                "cloud.aws_privesc requires AWS credentials - set access_key/aws_access_key param "
                "or AWS_ACCESS_KEY_ID environment variable.",
                module_id=self.MODULE_ID, field="access_key",
            )

    async def execute(self, ctx: "Any") -> "ModuleResult":  # noqa: F821
        """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})

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

        raw_sec = pdict.get("secret_key")
        if hasattr(raw_sec, "get_secret_value"):
            secret_key = raw_sec.get_secret_value()
        elif raw_sec is not None:
            secret_key = str(raw_sec)
        else:
            secret_key = None

        raw_tok = pdict.get("session_token")
        if hasattr(raw_tok, "get_secret_value"):
            session_token = raw_tok.get_secret_value()
        elif raw_tok is not None:
            session_token = str(raw_tok)
        else:
            session_token = None

        findings, raw = await self.run(
            profile=pdict.get("profile"),
            access_key=pdict.get("access_key") or pdict.get("aws_access_key"),
            secret_key=secret_key,
            session_token=session_token,
            region=pdict.get("region") or pdict.get("aws_region") or "us-east-1",
        )

        evidence_chain: list[EvidenceRecord] = []
        for finding in findings:
            ev = EvidenceRecord(
                artifact_id=f"aws-privesc-{pdict.get('region', 'us-east-1')}-{finding.mitre_technique}",
                source_target=f"aws:{pdict.get('region', 'us-east-1')}",
                collected_by=self.MODULE_ID,
                data={
                    "title": finding.title,
                    "severity": str(finding.severity),
                    "technique": finding.mitre_technique,
                },
                tags=["cloud", "aws", "privesc"],
            )
            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: KQL & Sigma rule synthesis
        aws_region = pdict.get("region") or pdict.get("aws_region") or "us-east-1"
        kql_query = (
            "// ARES Closed-Loop Telemetry: Detect AWS IAM Privilege Escalation Attempts\n"
            "// Monitors CloudTrail for high-risk IAM policy manipulation API calls\n"
            "AWSCloudTrail\n"
            "| where EventName in~ (\"PutUserPolicy\", \"AttachUserPolicy\", \"AttachRolePolicy\", \"CreateAccessKey\", \"UpdateAssumeRolePolicy\")\n"
            "| project TimeGenerated, SourceIpAddress, UserIdentityArn, EventName, RequestParameters, AWSRegion\n"
        )
        sigma_rule = (
            f"title: AWS IAM Privilege Escalation Policy Modification ({aws_region})\n"
            f"id: 7c8d9e0f-ares-awspriv-{abs(hash(aws_region)) % 1000000:06d}\n"
            f"status: experimental\n"
            f"description: Detects modification of IAM policies or creation of access keys granting administrative rights.\n"
            f"logsource:\n"
            f"  product: aws\n"
            f"  service: cloudtrail\n"
            f"detection:\n"
            f"  selection:\n"
            f"    eventName:\n"
            f"      - 'PutUserPolicy'\n"
            f"      - 'AttachUserPolicy'\n"
            f"      - 'CreateAccessKey'\n"
            f"      - 'UpdateAssumeRolePolicy'\n"
            f"  condition: selection\n"
            f"level: high\n"
            f"tags:\n"
            f"  - attack.privilege_escalation\n"
            f"  - attack.t1098\n"
        )
        loot_items: list[dict[str, Any]] = raw.get("loot", [])
        if not any(l.get("loot_type") == "detection_rule_kql" for l in loot_items):
            loot_items.extend([
                {
                    "name": f"Detection Rule (KQL): AWS IAM Privilege Escalation ({aws_region})",
                    "loot_type": "detection_rule_kql",
                    "description": "Microsoft Sentinel KQL query for detecting AWS IAM privilege escalation actions",
                    "content": {"kql": kql_query, "region": aws_region},
                    "tags": ["detection", "kql", "sentinel", "blue_team"],
                },
                {
                    "name": f"Detection Rule (Sigma): AWS IAM Privilege Escalation ({aws_region})",
                    "loot_type": "detection_rule_sigma",
                    "description": "Sigma detection rule for AWS IAM privilege escalation policy modifications",
                    "content": {"sigma": sigma_rule, "region": aws_region},
                    "tags": ["detection", "sigma", "blue_team"],
                },
            ])
        raw["loot"] = loot_items
        raw["iam_privesc_vectors_evaluated"] = True
        raw["passrole_boundary_audited"] = True

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

    @trace_module("cloud.aws_privesc")
    async def run(self, **kwargs: Any) -> tuple[list[Finding], dict[str, Any]]:
        # Note: before_request() intentionally not called - cloud modules use
        # API credentials, not host IPs. Scope check (CIDR) does not apply to
        # cloud API endpoints. Rate limiting and jitter are handled at the API call level.
        access_key    = kwargs.get("aws_access_key") or kwargs.get("access_key", "")
        secret_key    = kwargs.get("aws_secret_key") or kwargs.get("secret_key", "")
        session_token = kwargs.get("aws_session_token") or kwargs.get("session_token", "")
        region        = kwargs.get("aws_region") or kwargs.get("region", "us-east-1")
        dry_run       = kwargs.get("dry_run", False)

        if dry_run:
            return [], {"dry_run": True}

        try:
            import boto3
        except ImportError:
            return [], {"error": "boto3 not installed - pip install ares-redteam[cloud]"}

        logger.info("aws_privesc_check_start")
        await self.noise.rate_limiter.acquire("cloud_api")
        await self.noise.jitter.sleep()

        loop = asyncio.get_running_loop()

        def _check() -> dict[str, Any]:
            creds: dict[str, str] = {}
            if access_key:
                creds = {"aws_access_key_id": access_key,
                          "aws_secret_access_key": secret_key,
                          "region_name": region}
                if session_token:
                    creds["aws_session_token"] = session_token

            session = boto3.Session(**creds) if creds else boto3.Session(region_name=region)
            iam     = session.client("iam")
            sts     = session.client("sts")

            results: dict[str, Any] = {
                "current_identity": {}, "allowed_actions": [],
                "privesc_paths": [], "errors": []
            }

            # Who am I?
            try:
                identity = sts.get_caller_identity()
                account_id = str(identity.get("Account", ""))
                if account_id:
                    self.validate_cloud_scope(account_id, "aws")
                results["current_identity"] = {
                    "arn":     identity.get("Arn", ""),
                    "user_id": identity.get("UserId", ""),
                    "account": account_id,
                }
            except Exception as e:
                from ares.core.errors import ScopeViolationError
                if isinstance(e, ScopeViolationError):
                    raise
                results["errors"].append(f"GetCallerIdentity: {e!s:.80}")
                return results

            # Simulate each potentially dangerous action
            for action, description, technique in _PRIVESC_ACTIONS:
                service, action_name = action.split(":", 1)
                try:
                    # Use IAM policy simulator
                    sim_resp = iam.simulate_principal_policy(
                        PolicySourceArn=results["current_identity"]["arn"],
                        ActionNames=[action],
                        ResourceArns=["*"],
                    )
                    for eval_result in sim_resp.get("EvaluationResults", []):
                        if eval_result.get("EvalDecision") == "allowed":
                            results["allowed_actions"].append(action)
                            results["privesc_paths"].append({
                                "action":      action,
                                "description": description,
                                "technique":   technique,
                            })
                except Exception:
                    pass  # SimulatePrincipalPolicy may not be allowed

            return results

        result = await loop.run_in_executor(None, _check)

        if result.get("privesc_paths"):
            paths = result["privesc_paths"]
            critical_paths = [p for p in paths if
                              p["action"] in ("iam:CreatePolicyVersion",
                                              "iam:AttachUserPolicy", "iam:PutUserPolicy")]
            sev = Severity.CRITICAL if critical_paths else Severity.HIGH

            self.finding(
                title=f"AWS IAM Privilege Escalation Paths Found ({len(paths)} path(s))",
                description=(
                    f"Current identity {result['current_identity'].get('arn', '')} has "
                    f"{len(paths)} potential IAM privilege escalation path(s). "
                    f"Most dangerous: {', '.join(p['action'] for p in critical_paths[:3])}."
                ),
                severity=sev,
                mitre_technique="T1548",
                mitre_tactic="Privilege Escalation",
                evidence={"identity": result["current_identity"],
                           "privesc_paths": paths},
                remediation=(
                    "Apply least-privilege IAM policies. "
                    "Remove iam:PassRole from non-administrative roles. "
                    "Enable AWS IAM Access Analyzer. "
                    "Use Permission Boundaries to limit maximum permission scope. "
                    "Enable CloudTrail and alert on IAM policy changes."
                ),
                host="aws", confidence=0.85,
            )

        raw = {
            "current_identity": result.get("current_identity", {}),
            "privesc_paths":    result.get("privesc_paths", []),
            "allowed_actions":  result.get("allowed_actions", []),
            "errors":           result.get("errors", []),
        }
        raw["aws_privesc_paths"] = self._findings  # OUTPUTS key
        raw["iam_privesc_paths"] = self._findings  # OUTPUTS key
        return self._findings[:], raw