SuperAPI AI Directory

aws-pentesting

Security & auditing

View repository

Updated 10-16 07:23

About this skill

AWS Cloud Environment Penetration Testing Methodology

AWS is the world's largest public cloud platform, hosting a large number of enterprises' core business systems. Its more than 200 services constitute a massive attack surface—issues such as IAM policy misconfigurations, exposed S3 Buckets, EC2 metadata leaks, and unauthenticated Lambda function URLs frequently appear in actual assessments. This skill uses attack phases as the main thread, organizing the complete penetration path from "zero credentials" to "full control," and guides to specialized skills for deeper dives through decision trees.

In-depth reference

After identifying the specific attack phase, load the corresponding reference document to obtain complete technical details:

Phase 0: Attack Surface Determination

After obtaining an AWS-related target, first determine the type of asset currently in hand to decide which attack phase to enter:

当前持有什么?
├── 无任何凭据
│   ├── 有目标域名/IP → Phase 1(未授权枚举)
│   ├── 有 SSRF 漏洞 → 直接打元数据服务获取凭据 → Phase 2
│   └── 仅知道组织名称 → OSINT + Phase 1
│
├── 有 AWS AK/SK(AKIA 开头 = 长期密钥)
│   └── → Phase 2(凭据验证与权限评估)
│
├── 有临时凭据(ASIA 开头 + SessionToken)
│   └── → Phase 2(注意:有效期通常 1-12 小时,需快速行动)
│
├── 在 EC2/Lambda/ECS 实例内部
│   └── → 通过元数据获取绑定的 IAM Role 凭据 → Phase 2
│
└── 有 AWS SSO Token / IAM Identity Center 会话
    └── → Phase 2(需额外确认可访问的账户和角色)

AWS Credential Type Quick Reference

Credential Type Identifying Characteristics Validity Period Acquisition Method
Long-term AK/SK AccessKeyId starts with AKIA , 20 characters Permanent (until rotation) Created in console / obtained through leakage
Temporary STS credentials AccessKeyId starts with ASIA prefix + SessionToken 15 minutes ~ 36 hours AssumeRole / GetSessionToken
IAM Role (instance-bound) Obtained via 169.254.169.254 Automatically rotated EC2/Lambda/ECS metadata
SSO Token JSON format, containing an accessToken field Usually 8 hours ~/.aws/sso/cache/
Cognito Token JWT-format Identity/Access Token 1 hour Cognito Identity Pool

Canary Token Detection

Before using obtained credentials, first determine whether they are honeypot tokens (Canary Tokens). Using honeypot credentials will immediately trigger an alert. Common characteristics:

  • The AccessKeyId matches the format of known honeypot services (such as Thinkst Canaries, SpaceCrab)
  • Comes from abnormal channels (intentionally exposed configuration files, overly obvious leak points)
  • You can use aws sts get-access-key-info --access-key-id AKIA... to query the owning account and compare it with known honeypot accounts

Phase 1: Unauthenticated Enumeration

Without any AWS credentials, a large amount of information can still be collected on the target. More than 25 AWS services have unauthenticated enumeration surfaces.

High-value Enumeration Targets

Target Attack Method Value
S3 Bucket Domain enumeration + brute-force guessing + DNS CNAME Data leakage, obtaining credential files
Lambda Function URL https://{id}.lambda-url.{region}.on.aws/ Web vulnerability exploitation
Cognito User Pool Attempt to register a new user Obtain an authenticated identity → IAM Role
Cognito Identity Pool Obtain an unauthenticated IAM Role Directly obtain AWS credentials
EC2 public ports Nmap + service fingerprinting SSRF → metadata → IAM credentials
Public AMI / EBS snapshots describe-images --executable-users all Extract hardcoded credentials
API Gateway https://{id}.execute-api.{region}.amazonaws.com/ API exploitation
CloudFront distributions https://{id}.cloudfront.net Origin discovery, cache poisoning

S3 quick enumeration workflow

# 1. 检查 Bucket 是否存在并可列出
aws s3 ls s3://TARGET-BUCKET --no-sign-request

# 2. 如果可列出,递归下载敏感文件
aws s3 cp s3://TARGET-BUCKET/ ./loot/ --recursive --no-sign-request \
  --exclude "*" --include "*.env" --include "*.pem" --include "*.key" \
  --include "*credentials*" --include "*config*"

# 3. 通过 Bucket 反查 Account ID
pip install s3-account-search
s3-account-search arn:aws:iam::YOUR_ACCT:role/YOUR_ROLE s3://TARGET-BUCKET

Cognito quick exploitation

# 如果发现 Identity Pool ID(格式:region:guid),获取未认证凭据
aws cognito-identity get-id --identity-pool-id "us-east-1:xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx"
aws cognito-identity get-credentials-for-identity --identity-id "us-east-1:yyyyy"

# 如果发现 User Pool Client ID,尝试注册
aws cognito-idp sign-up --client-id CLIENT_ID --username test@test.com --password 'P@ssw0rd123!'

→ Complete 25+ service enumeration checklist, read references/unauthenticated-enum.md

Phase 2: Credential validation and permission assessment

After obtaining credentials, the first step is to verify their validity and assess the scope of permissions.

2.1 Credential validation

# 身份确认(最基础的检查)
aws sts get-caller-identity

# 返回示例:
# Account: 123456789012
# UserId: AIDA...
# Arn: arn:aws:iam::123456789012:user/developer

# 判断凭据类型
aws sts get-access-key-info --access-key-id AKIA...

2.2 Permission enumeration

# 方法一:直接查询 IAM 策略(需要 iam 读权限)
aws iam get-user
aws iam list-attached-user-policies --user-name USERNAME
aws iam list-user-policies --user-name USERNAME
aws iam list-groups-for-user --user-name USERNAME

# 方法二:如果是 Role
aws iam list-attached-role-policies --role-name ROLENAME
aws iam list-role-policies --role-name ROLENAME

# 方法三:暴力枚举权限(无需 IAM 读权限)
# enumerate-iam 工具会尝试调用大量 API 来探测可用权限
pip install enumerate-iam
enumerate-iam --access-key AKIA... --secret-key ...

2.3 Permission assessment decision tree

当前身份权限如何?
├── 有 iam:* 或 AdministratorAccess → 已是管理员,直接 Phase 4
├── 有 iam 读权限但无写权限 → 枚举所有用户/角色/策略,寻找提权路径 → Phase 3
├── 有特定服务权限(如 s3:*、ec2:*、lambda:*)
│   ├── 检查是否有 iam:PassRole → 可能通过 PassRole 提权 → Phase 3
│   ├── 有 ec2:RunInstances + iam:PassRole → EC2 提权 → Phase 3
│   └── 可直接利用当前权限进行后渗透 → Phase 4
└── 权限极低 → 尝试暴力枚举更多权限,或回到 Phase 1 寻找更多入口

Refer to aws-iam-policy-analysis skill for in-depth policy analysis

Refer to cloud-iam-audit skill for cross-cloud IAM auditing

Refer to cloud-aksk-exploit skill to obtain the complete AK/SK exploitation chain

2.4 Automated auditing tools

Tool Purpose Command
enumerate-iam Brute-force enumerate available permissions enumerate-iam --access-key ... --secret-key ...
Pacu AWS exploitation framework (enumeration + privilege escalation + post-exploitation) pacu → import_keys → exec iam__enum_permissions
ScoutSuite Multi-cloud security audit report scout aws -p PROFILE
Prowler AWS security best practices check prowler aws --profile PROFILE
CloudFox Attack path discovery cloudfox aws --profile PROFILE all-checks
PMapper IAM privilege escalation path graph analysis pmapper --profile PROFILE graph create

Phase 3: Privilege escalation

The core idea of AWS privilege escalation: use current permissions to obtain higher permissions. AWS has hundreds of permissions, and many combinations of them can form privilege escalation paths.

Overview of common privilege escalation paths

Privilege escalation path Key permissions Principle
iam:CreatePolicyVersion Create a new policy version Create a new policy version with Admin permissions and set it as default
iam:AttachUserPolicy / AttachRolePolicy Attach a managed policy Directly attach AdministratorAccess to yourself
iam:PutUserPolicy / PutRolePolicy Set an inline policy Write an Allow * policy for yourself
iam:PassRole + ec2:RunInstances PassRole to EC2 Launch an EC2 instance bound to a high-privilege Role
iam:PassRole + lambda:CreateFunction PassRole to Lambda Create and execute a Lambda bound to a high-privilege Role
sts:AssumeRole Role chain Switch to a higher-privilege Role
iam:CreateLoginProfile Create a console password for a user Take over another user's console access
iam:UpdateAssumeRolePolicy Modify the role trust policy Enable yourself to AssumeRole into a high-privilege role

PassRole privilege escalation principle

iam:PassRole is one of the most core permissions in AWS privilege escalation. It allows a user to "pass" an IAM Role to an AWS service. If a user has iam:PassRole plus the creation permission for a certain service (such as ec2:RunInstances、lambda:CreateFunction), they can create a resource bound to a high-privilege Role, and then indirectly obtain high privileges through that resource.

攻击者拥有: iam:PassRole + lambda:CreateFunction + lambda:InvokeFunction
    │
    ├─ 1. 创建 Lambda 函数,绑定一个拥有 AdministratorAccess 的 Role
    ├─ 2. Lambda 代码中调用 IAM API 给攻击者账户添加 Admin 策略
    └─ 3. 调用该 Lambda → 攻击者获得管理员权限

Refer to aws-iam-privesc skill to obtain detailed privilege escalation paths for 46 services

Phase 4: Post-exploitation and persistence

After obtaining higher privileges, enter the post-exploitation phase. The goals are data acquisition, lateral movement, and establishing persistence.

4.1 Data discovery and acquisition

优先搜索哪些数据源?
├── S3 Bucket → 文档、备份、日志、配置文件
├── RDS / DynamoDB → 业务数据库
├── Secrets Manager / Parameter Store → 凭据和配置
├── EBS 快照 → 挂载后可读取完整文件系统
├── CloudWatch Logs → 应用日志中的敏感信息
└── CodeCommit → 代码仓库

4.2 Lateral movement

Lateral movement in AWS environments mainly occurs in two dimensions:

Cross-account movement:

  • Use OrganizationAccountAccessRole(management account → member account)
  • Use cross-account role trust policies (sts:AssumeRole)
  • Use shared resources (S3 Bucket Policy, KMS Key Policy)

Cross-service movement:

  • SSM Agent on EC2 instances → SSM RunCommand lateral movement to other instances
  • ECS/EKS task role → container escape to host
  • Lambda function role → modify function code to execute arbitrary operations

4.3 Overview of Persistence Techniques

Service Persistence Method Stealthiness
IAM Create backdoor users/roles, add Access Keys, modify trust policies Low (IAM changes are easily audited)
Lambda Layer backdoor, Extension injection, version/alias weight allocation, asynchronous self-loop High
EC2 UserData backdoor, AMI backdoor, SSH Key injection, security group connection tracking Medium
STS Role Chain Juggling (role chain cyclic renewal) High
CloudFormation CDK Bootstrap trusts external accounts Medium
Cognito Add external identity providers, modify risky configurations High
SSM CreateAssociation scheduled command execution Medium
EventBridge Scheduled rules trigger malicious Lambda/ECS tasks Medium
SNS/SQS Add external subscribers to continuously exfiltrate messages High
ECR Repository policy backdoor, image poisoning High

→ Complete list of persistence techniques for 22+ services, read references/persistence-techniques.md

Refer to aws-post-exploit skill for an in-depth guide on data exfiltration and lateral movement

Appendix: AWS Quick Reference

Common AWS CLI Commands

# 身份与权限
aws sts get-caller-identity                           # 当前身份
aws iam get-user                                      # 当前 IAM 用户信息
aws iam list-attached-user-policies --user-name USER  # 附加的策略
aws iam list-roles                                    # 列出所有角色
aws organizations list-accounts                       # 列出组织内所有账户

# 枚举资源
aws s3 ls                                             # 列出所有 S3 Bucket
aws ec2 describe-instances --region REGION             # 列出 EC2 实例
aws lambda list-functions --region REGION              # 列出 Lambda 函数
aws rds describe-db-instances --region REGION           # 列出 RDS 实例
aws secretsmanager list-secrets --region REGION         # 列出 Secrets

# 凭据操作
aws sts assume-role --role-arn ARN --role-session-name s   # 切换角色
aws sts get-session-token --duration-seconds 43200         # 获取临时凭据

# 元数据服务(从 EC2 实例内部)
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/

AWS Service Abbreviation Reference Table

Abbreviation Full Name Attack Surface Keywords
IAM Identity and Access Management Permission policies, role trust, privilege escalation
STS Security Token Service Temporary credentials, AssumeRole
EC2 Elastic Compute Cloud Instances, metadata, security groups, AMI
S3 Simple Storage Service Bucket policies, ACLs, public access
Lambda Lambda (Serverless) Function URL, Layer, environment variables
RDS Relational Database Service Public access, snapshot leakage
EKS Elastic Kubernetes Service RBAC、ServiceAccount
ECS Elastic Container Service Task definition, IAM Role
ECR Elastic Container Registry Image repository policy
CloudFront CloudFront (CDN) Origin exposure, cache rules
SNS Simple Notification Service Topic policy, subscribers
SQS Simple Queue Service Queue policy, message theft
SSM Systems Manager RunCommand、Parameter Store
KMS Key Management Service Key Policy、Grant
Cognito Cognito User Pool、Identity Pool

Precautions

CloudTrail audit awareness: Almost all AWS API calls are recorded by CloudTrail. The following operations generate highly visible log events:

  • IAM changes (CreateUser, AttachPolicy, CreateAccessKey)
  • Role switching (AssumeRole)
  • Cross-region operations

Some APIs are "data events" in CloudTrail (such as S3 GetObject); they are not logged by default, but organizations may have enabled them.

GuardDuty detection risk: GuardDuty detects the following behaviors:

  • Credentials used from anomalous IPs/regions
  • EC2 instances communicating with known malicious IPs
  • Large-scale S3 data export
  • Anomalous IAM permission changes
  • DNS tunnel traffic

Rate limiting: AWS APIs have rate limits (typically 5-20 calls per second); when brute-force enumerating, be mindful of throttling, otherwise it will trigger ThrottlingException and may raise alerts.

Regional differences: AWS resources are region-isolated. When enumerating, you need to traverse all enabled regions (aws ec2 describe-regions), do not only check us-east-1. Global services (IAM, Route53, CloudFront, STS) are not restricted by region.