Production hardening: security fixes, code quality, 724 skills complete

- Fix 25 shell=True subprocess calls with list-based commands
- Fix 49 verify=False in defensive skills (env-var override)
- Add timeout to 231 HTTP/subprocess/socket calls
- Fix 6 SQL injection patterns with whitelist validation
- Replace 8 __import__() with standard imports
- Remove 701 unused imports across 442 files
- Add authorized-testing disclaimers to all offensive skills
- Complete 11 incomplete skill directories
- Expand 10 stub SKILL.md files with full content
- Fix 2 YAML parse errors in frontmatter
- Fix 5 pre-existing syntax errors
- Convert 22 hardcoded paths/ports to environment variables
- Back up 21 redundant skill pairs to .bak
- Fix 2 global declaration errors
- 724/724 skills with full folder anatomy (SKILL.md + agent.py + api-reference.md + LICENSE)
- 0 compile errors across all 724 agent.py files
This commit is contained in:
mukul975
2026-03-19 13:26:49 +01:00
parent 63b442d347
commit c47eed6a64
900 changed files with 23085 additions and 2720 deletions
@@ -0,0 +1,201 @@
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.
@@ -0,0 +1,194 @@
---
name: performing-cloud-penetration-testing
description: >
Performs authorized penetration testing of cloud environments across AWS, Azure, and GCP to
identify IAM misconfigurations, exposed storage buckets, overly permissive security groups,
serverless function vulnerabilities, and cloud-specific attack paths from initial access to
account compromise. The tester uses cloud-native tools and specialized frameworks like Pacu
and ScoutSuite to enumerate and exploit cloud infrastructure. Activates for requests involving
cloud pentest, AWS security assessment, Azure penetration testing, or cloud infrastructure
security testing.
domain: cybersecurity
subdomain: penetration-testing
tags: [cloud-pentest, AWS-security, Azure-security, IAM-exploitation, cloud-infrastructure]
version: 1.0.0
author: mahipal
license: Apache-2.0
---
# Performing Cloud Penetration Testing
## When to Use
- Assessing the security posture of cloud infrastructure before or after migration from on-premises
- Testing IAM policies, security groups, and network ACLs for overly permissive configurations
- Evaluating the security of serverless architectures (Lambda, Azure Functions, Cloud Functions)
- Identifying exposed cloud storage (S3 buckets, Azure Blob containers, GCS buckets) containing sensitive data
- Testing the effectiveness of cloud security controls (GuardDuty, Defender for Cloud, Security Command Center)
**Do not use** without both written authorization from the cloud account owner AND compliance with the cloud provider's penetration testing policy (AWS requires no prior approval for most services; Azure and GCP require notification or approval for certain test types).
## Prerequisites
- Written authorization specifying target cloud accounts, regions, and services in scope
- Compliance with cloud provider penetration testing policies (AWS Penetration Testing Policy, Azure Penetration Testing Rules, GCP Acceptable Use Policy)
- Cloud credentials at various privilege levels (read-only, developer, admin) for testing authorization boundaries
- Pacu (AWS), PowerZure (Azure), or GCP-specific exploitation frameworks installed
- ScoutSuite or Prowler for automated cloud security posture assessment
- AWS CLI, Azure CLI, and/or gcloud CLI configured with test credentials
## Workflow
### Step 1: Cloud Reconnaissance and Enumeration
Enumerate the cloud environment to map the attack surface:
**AWS Enumeration:**
- `aws sts get-caller-identity` - Verify current identity and account
- `aws iam list-users` - List all IAM users
- `aws iam list-roles` - List all IAM roles and their trust policies
- `aws s3 ls` - List all S3 buckets
- `aws ec2 describe-instances --region us-east-1` - List EC2 instances
- `aws lambda list-functions` - List Lambda functions
- `aws rds describe-db-instances` - List RDS databases
- Use Pacu for automated enumeration: `run iam__enum_permissions`, `run iam__enum_users_roles_policies_groups`
**Azure Enumeration:**
- `az account list` - List subscriptions
- `az ad user list` - List Azure AD users
- `az vm list` - List virtual machines
- `az storage account list` - List storage accounts
- `az keyvault list` - List key vaults
- `az webapp list` - List web applications
**Cross-Cloud:**
- Run ScoutSuite for comprehensive posture assessment: `scout aws --profile <profile>` or `scout azure --cli`
- Run Prowler for AWS CIS benchmark compliance: `prowler aws`
### Step 2: IAM and Identity Exploitation
Test IAM policies for privilege escalation paths:
**AWS IAM Escalation:**
- Check for overpermissive policies: `aws iam get-user-policy`, `aws iam list-attached-user-policies`
- Test known IAM escalation paths:
- `iam:CreatePolicyVersion` - Create a new policy version granting admin access
- `iam:SetDefaultPolicyVersion` - Set an older, more permissive policy version as default
- `iam:PassRole` + `lambda:CreateFunction` + `lambda:InvokeFunction` - Create a Lambda with a high-privilege role
- `iam:AttachUserPolicy` - Attach AdministratorAccess to the current user
- `sts:AssumeRole` - Assume a higher-privilege role if trust policy allows
- Use Pacu for automated escalation: `run iam__privesc_scan`
**Azure Identity Escalation:**
- Enumerate role assignments: `az role assignment list --assignee <user>`
- Check for Contributor/Owner roles at subscription level
- Test Azure AD privilege escalation through application registrations, service principals, and managed identities
- Check for Global Administrator assignments in Azure AD
### Step 3: Storage and Data Exposure
Test cloud storage services for data exposure:
- **S3 bucket security**: Test each bucket for:
- Public access: `aws s3 ls s3://<bucket> --no-sign-request`
- ACL misconfigurations: `aws s3api get-bucket-acl --bucket <bucket>`
- Bucket policy: `aws s3api get-bucket-policy --bucket <bucket>`
- Versioning (access deleted data): `aws s3api list-object-versions --bucket <bucket>`
- **Azure Blob exposure**: Test for public container access and shared access signature (SAS) token leakage
- **Secrets in storage**: Search storage contents for credentials, API keys, database connection strings, and PII
- **Database exposure**: Check for RDS/Azure SQL instances with public endpoints, default credentials, or security groups allowing 0.0.0.0/0 access
### Step 4: Compute and Serverless Exploitation
Test compute resources for vulnerabilities:
- **EC2 instance metadata**: From a compromised instance, query `http://169.254.169.254/latest/meta-data/iam/security-credentials/` to extract IAM role credentials
- **IMDSv1 exploitation**: Test if IMDSv2 is enforced. IMDSv1 is vulnerable to SSRF-based credential theft.
- **Lambda function analysis**: Download Lambda function code (`aws lambda get-function --function-name <name>`) and review for hardcoded credentials, insecure dependencies, and injection vulnerabilities
- **Container security**: Test ECS/EKS for pod-level privilege escalation, container breakout, and service account token abuse
- **User data scripts**: `aws ec2 describe-instance-attribute --instance-id <id> --attribute userData` to find credentials in startup scripts
### Step 5: Network and Security Group Assessment
Test network controls for misconfigurations:
- **Security group analysis**: Identify groups allowing 0.0.0.0/0 ingress on sensitive ports (SSH/22, RDP/3389, database ports)
- **VPC flow logs**: Check if VPC flow logs are enabled for forensic capability
- **Cross-account access**: Test for overly permissive resource policies that allow access from other AWS accounts
- **VPC peering**: Identify VPC peering connections and test if peered VPCs have access to sensitive resources
- **VPN and Direct Connect**: Identify hybrid connectivity and test if cloud-to-on-premises access controls are enforced
## Key Concepts
| Term | Definition |
|------|------------|
| **IAM Privilege Escalation** | Exploiting overly permissive IAM policies to elevate from limited access to administrative control over the cloud account |
| **Instance Metadata Service (IMDS)** | An HTTP endpoint (169.254.169.254) on cloud instances that provides instance configuration and IAM role credentials, exploitable via SSRF |
| **Assumed Role** | An IAM role that a user or service temporarily assumes to gain its permissions, governed by trust policies that define who can assume the role |
| **SCPs (Service Control Policies)** | Organization-level policies in AWS Organizations that set permission boundaries for accounts, overriding IAM policies |
| **Managed Identity** | Azure's equivalent of AWS IAM roles for services, providing automatic credential management for Azure resources |
| **Resource Policy** | Access control policy attached to a cloud resource (S3 bucket, Lambda function, SQS queue) that defines cross-account and public access |
## Tools & Systems
- **Pacu**: Open-source AWS exploitation framework supporting IAM enumeration, privilege escalation, data exfiltration, and persistence
- **ScoutSuite**: Multi-cloud security auditing tool that assesses security posture across AWS, Azure, GCP, and Oracle Cloud against security best practices
- **Prowler**: AWS and Azure security assessment tool covering CIS benchmarks, PCI-DSS, HIPAA, and GDPR compliance checks
- **CloudFox**: Tool for identifying exploitable attack paths in cloud infrastructure by analyzing IAM roles, permissions, and trust relationships
- **Steampipe**: SQL-based query engine for cloud infrastructure that enables complex queries across cloud provider APIs
## Common Scenarios
### Scenario: AWS Cloud Penetration Test for a SaaS Company
**Context**: A SaaS company hosts its entire platform on AWS across 3 accounts (production, staging, development). The tester is given read-only IAM credentials in the development account. The goal is to determine if the development account can be used to pivot to production.
**Approach**:
1. Enumerate the development account with Pacu: discover 45 Lambda functions, 12 EC2 instances, 8 S3 buckets, and 23 IAM roles
2. Find that the developer role can invoke Lambda functions; one Lambda function has a role with S3 full access and STS assume-role permissions
3. Modify the Lambda function code to assume a cross-account role in the production account (trust policy allows the Lambda role)
4. From the assumed production role, enumerate S3 buckets and discover customer data in an unencrypted bucket
5. Find that the production EC2 instances use IMDSv1, which combined with an SSRF vulnerability in the web application could allow credential theft
6. Document the complete attack path from development read-only to production data access
**Pitfalls**:
- Not checking the cloud provider's penetration testing policy and accidentally triggering automated abuse detection
- Focusing only on IaaS (EC2, VMs) while ignoring serverless functions, managed services, and storage that contain the most sensitive data
- Missing cross-account trust relationships that provide lateral movement between cloud accounts
- Not testing IMDSv2 enforcement, which is the most common cloud-specific vulnerability
## Output Format
```
## Finding: Cross-Account Role Trust Allows Development-to-Production Pivot
**ID**: CLOUD-002
**Severity**: Critical (CVSS 9.6)
**Cloud Provider**: AWS
**Affected Account**: Production (111222333444)
**Exploited From**: Development (555666777888)
**Description**:
The production account IAM role "ProdDataAccess" has a trust policy that allows
the Lambda execution role "LambdaDevRole" in the development account to assume
it. This cross-account trust, combined with the developer's ability to modify
Lambda function code, creates a path from development read-only access to
production data access.
**Attack Chain**:
1. Enumerate Lambda functions in dev: aws lambda list-functions
2. Identify LambdaDevRole has sts:AssumeRole permission
3. Modify Lambda to assume ProdDataAccess: aws sts assume-role --role-arn arn:aws:iam::111222333444:role/ProdDataAccess
4. From assumed role: aws s3 ls s3://prod-customer-data -> 2.3 million customer records
**Impact**:
An attacker compromising any developer credential can access production
customer data (2.3 million records) without directly attacking the production
account.
**Remediation**:
1. Restrict the ProdDataAccess trust policy to specific production roles only
2. Remove sts:AssumeRole from the LambdaDevRole policy
3. Implement AWS Organizations SCPs to prevent cross-account role assumption from development
4. Enable CloudTrail alerts for cross-account AssumeRole events
5. Encrypt S3 bucket with KMS key that the development account cannot access
```
@@ -0,0 +1,56 @@
# API Reference: Performing Cloud Penetration Testing
## AWS S3 API (boto3)
| Method | Description |
|--------|-------------|
| `s3.list_buckets()` | Enumerate all S3 buckets in account |
| `s3.get_bucket_acl(Bucket)` | Check bucket ACL for public grants |
| `s3.get_bucket_policy(Bucket)` | Get bucket policy for public access |
| `s3.get_bucket_encryption(Bucket)` | Check default encryption status |
## AWS EC2 API
| Method | Description |
|--------|-------------|
| `ec2.describe_security_groups()` | Enumerate security groups and ingress rules |
| `ec2.describe_instances()` | List instances with metadata options (IMDSv1/v2) |
| `ec2.describe_network_interfaces()` | Enumerate ENIs and public IPs |
## AWS Lambda API
| Method | Description |
|--------|-------------|
| `lambda.list_functions()` | Enumerate Lambda functions |
| `lambda.get_function(FunctionName)` | Get function config including env vars |
| `lambda.get_policy(FunctionName)` | Get resource-based policy |
## AWS IAM API
| Method | Description |
|--------|-------------|
| `iam.list_users()` | Enumerate IAM users |
| `iam.list_roles()` | Enumerate IAM roles and trust policies |
| `iam.get_policy_version()` | Analyze policy documents |
## Key Libraries
- **boto3** (`pip install boto3`): AWS SDK for all service enumeration
- **ScoutSuite** (`pip install scoutsuite`): Multi-cloud security auditing tool
- **prowler**: AWS/Azure/GCP security best practices assessment
- **cloudfox**: Cloud penetration testing enumeration
## Configuration
| Variable | Description |
|----------|-------------|
| `AWS_PROFILE` | AWS CLI profile with test credentials |
| `AWS_DEFAULT_REGION` | Target AWS region |
## References
- [AWS Penetration Testing Policy](https://aws.amazon.com/security/penetration-testing/)
- [ScoutSuite GitHub](https://github.com/nccgroup/ScoutSuite)
- [Prowler](https://github.com/prowler-cloud/prowler)
- [CloudFox](https://github.com/BishopFox/cloudfox)
- [HackTricks Cloud](https://cloud.hacktricks.xyz/)
@@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""
Cloud Penetration Testing Agent — AUTHORIZED TESTING ONLY
Performs authorized cloud infrastructure security assessment across AWS
by enumerating IAM, S3, EC2, and Lambda for misconfigurations.
WARNING: Only use with explicit written authorization on approved accounts.
"""
import json
import sys
from datetime import datetime, timezone
import boto3
from botocore.exceptions import ClientError
def enumerate_s3_buckets() -> list[dict]:
"""Enumerate S3 buckets and check for public access misconfigurations."""
s3 = boto3.client("s3")
findings = []
try:
buckets = s3.list_buckets()["Buckets"]
except ClientError as e:
return [{"error": str(e)}]
for bucket in buckets:
name = bucket["Name"]
finding = {"bucket": name, "issues": []}
try:
acl = s3.get_bucket_acl(Bucket=name)
for grant in acl.get("Grants", []):
grantee = grant.get("Grantee", {})
if grantee.get("URI") in (
"http://acs.amazonaws.com/groups/global/AllUsers",
"http://acs.amazonaws.com/groups/global/AuthenticatedUsers",
):
finding["issues"].append({
"type": "PUBLIC_ACL",
"severity": "HIGH",
"detail": f"Bucket grants {grant['Permission']} to {grantee['URI']}",
})
except ClientError:
pass
try:
policy = s3.get_bucket_policy(Bucket=name)
policy_doc = json.loads(policy["Policy"])
for stmt in policy_doc.get("Statement", []):
if stmt.get("Effect") == "Allow" and stmt.get("Principal") in ("*", {"AWS": "*"}):
finding["issues"].append({
"type": "PUBLIC_POLICY",
"severity": "HIGH",
"detail": f"Policy allows public access: {stmt.get('Action')}",
})
except ClientError:
pass
try:
encryption = s3.get_bucket_encryption(Bucket=name)
except ClientError:
finding["issues"].append({
"type": "NO_ENCRYPTION",
"severity": "MEDIUM",
"detail": "Bucket does not have default encryption enabled",
})
findings.append(finding)
return findings
def enumerate_security_groups(region: str = "us-east-1") -> list[dict]:
"""Enumerate EC2 security groups for overly permissive rules."""
ec2 = boto3.client("ec2", region_name=region)
findings = []
sgs = ec2.describe_security_groups()["SecurityGroups"]
for sg in sgs:
sg_issues = []
for perm in sg.get("IpPermissions", []):
for ip_range in perm.get("IpRanges", []):
if ip_range.get("CidrIp") == "0.0.0.0/0":
port = perm.get("FromPort", "all")
proto = perm.get("IpProtocol", "all")
severity = "CRITICAL" if port in (22, 3389, 3306, 5432) else "HIGH"
sg_issues.append({
"type": "OPEN_INGRESS",
"severity": severity,
"detail": f"Port {port}/{proto} open to 0.0.0.0/0",
})
if sg_issues:
findings.append({
"sg_id": sg["GroupId"],
"sg_name": sg.get("GroupName", ""),
"vpc_id": sg.get("VpcId", ""),
"issues": sg_issues,
})
return findings
def enumerate_lambda_functions(region: str = "us-east-1") -> list[dict]:
"""Enumerate Lambda functions for security misconfigurations."""
lam = boto3.client("lambda", region_name=region)
findings = []
try:
functions = lam.list_functions()["Functions"]
except ClientError as e:
return [{"error": str(e)}]
for func in functions:
func_finding = {"function_name": func["FunctionName"], "issues": []}
env_vars = func.get("Environment", {}).get("Variables", {})
sensitive_patterns = ["password", "secret", "key", "token", "api_key"]
for var_name in env_vars:
if any(p in var_name.lower() for p in sensitive_patterns):
func_finding["issues"].append({
"type": "SENSITIVE_ENV_VAR",
"severity": "HIGH",
"detail": f"Potentially sensitive env var: {var_name}",
})
if not func.get("VpcConfig", {}).get("VpcId"):
func_finding["issues"].append({
"type": "NO_VPC",
"severity": "LOW",
"detail": "Function not in VPC - has internet access",
})
if func_finding["issues"]:
findings.append(func_finding)
return findings
def check_imds_v1(region: str = "us-east-1") -> list[dict]:
"""Check EC2 instances for IMDSv1 (vulnerable to SSRF attacks)."""
ec2 = boto3.client("ec2", region_name=region)
findings = []
instances = ec2.describe_instances()
for reservation in instances["Reservations"]:
for inst in reservation["Instances"]:
metadata_options = inst.get("MetadataOptions", {})
if metadata_options.get("HttpTokens") != "required":
findings.append({
"instance_id": inst["InstanceId"],
"state": inst["State"]["Name"],
"severity": "HIGH",
"detail": "IMDSv1 enabled - vulnerable to SSRF credential theft",
})
return findings
def generate_report(s3: list, sgs: list, lambdas: list, imds: list) -> str:
"""Generate cloud penetration testing report."""
total_issues = (
sum(len(b.get("issues", [])) for b in s3) +
sum(len(s.get("issues", [])) for s in sgs) +
sum(len(l.get("issues", [])) for l in lambdas) +
len(imds)
)
lines = [
"CLOUD PENETRATION TESTING REPORT — AUTHORIZED TESTING ONLY",
"=" * 60,
f"Date: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}",
f"Total Findings: {total_issues}",
"",
f"S3 BUCKETS ({len(s3)} scanned):",
]
for b in s3:
if b.get("issues"):
for issue in b["issues"]:
lines.append(f" [{issue['severity']}] {b['bucket']}: {issue['detail']}")
lines.append(f"\nSECURITY GROUPS ({len(sgs)} with issues):")
for sg in sgs:
for issue in sg["issues"]:
lines.append(f" [{issue['severity']}] {sg['sg_id']}: {issue['detail']}")
lines.append(f"\nLAMBDA FUNCTIONS ({len(lambdas)} with issues):")
for l in lambdas:
for issue in l["issues"]:
lines.append(f" [{issue['severity']}] {l['function_name']}: {issue['detail']}")
lines.append(f"\nIMDSv1 INSTANCES ({len(imds)} vulnerable):")
for i in imds:
lines.append(f" [{i['severity']}] {i['instance_id']}: {i['detail']}")
return "\n".join(lines)
if __name__ == "__main__":
print("[!] CLOUD PENETRATION TESTING — AUTHORIZED TESTING ONLY\n")
region = sys.argv[1] if len(sys.argv) > 1 else "us-east-1"
print("[*] Enumerating S3 buckets...")
s3_findings = enumerate_s3_buckets()
print("[*] Enumerating security groups...")
sg_findings = enumerate_security_groups(region)
print("[*] Enumerating Lambda functions...")
lambda_findings = enumerate_lambda_functions(region)
print("[*] Checking IMDSv1 exposure...")
imds_findings = check_imds_v1(region)
report = generate_report(s3_findings, sg_findings, lambda_findings, imds_findings)
print(report)
output = f"cloud_pentest_{datetime.now(timezone.utc).strftime('%Y%m%d')}.json"
with open(output, "w") as f:
json.dump({"s3": s3_findings, "security_groups": sg_findings,
"lambda": lambda_findings, "imds": imds_findings}, f, indent=2)
print(f"\n[*] Results saved to {output}")