Code Security

Guide to Cloud Pentesting: AWS, Azure, and GCP

Amartya | CodeAnt AI Code Review Platform
Sonali Sood

Founding GTM, CodeAnt AI

Cloud pentesting isn't traditional network pentesting with a cloud logo. When you're testing AWS IAM privilege escalation paths, Azure managed identity exploitation, or GCP service account key leakage, you're dealing with attack vectors that didn't exist five years ago.

Configuration scanners like Prowler catch obvious stuff, public S3 buckets, overly permissive security groups, but they can't chain an SSRF vulnerability through your application layer to the EC2 metadata service, steal IAM credentials, and demonstrate lateral movement to your production database.

This guide walks through cloud pentesting methodology that proves exploitability: reconnaissance and asset discovery, vulnerability identification and exploitation, post-compromise lateral movement, and evidence collection that maps to SOC 2 and ISO 27001 controls. You'll get platform-specific attack techniques for AWS, Azure, and GCP, with actual commands and exploit chains.

We'll cover the honest trade-offs between automated tools, manual pentesting firms, and hybrid approaches, including where grey box testing with code-level context finds attack paths that external-only scanning misses.

For the enterprise-level overview of why this matters and what to test, see AI Penetration Testing For Cloud Security; for the attack-path mechanics specifically, see Cloud Attack Path Testing.

Why Cloud Pentesting Demands a Different Playbook

Cloud environments fundamentally invert the assumptions that shaped traditional penetration testing. You're no longer testing a network perimeter, you're testing logical isolation boundaries, IAM permission chains, and API control planes where identity is the perimeter.

Identity Became the Attack Surface

In traditional pentesting, you mapped network topology and worked inward through firewall rules. Cloud flips this:

  • IAM-first security: Every API call authenticates against identity policies. A misconfigured s3:GetObject permission on a role is as exploitable as an open port, but harder to discover from the outside.

  • Ephemeral infrastructure: The EC2 host you scanned yesterday doesn't exist today, but the IAM role attached to it persists, and might be over-permissioned.

  • API control planes: Cloud providers expose management APIs that become the primary attack vector. You're testing REST endpoints, not TCP handshakes.

  • Federated identity: SSO integrations and OAuth flows create trust boundaries across organizational boundaries.

Real example: Traditional pentesting finds an exposed web app. Cloud pentesting chains that compromise through SSRF to the metadata service, steals IAM credentials, escalates privileges via iam:PassRole, assumes a cross-account role, and exfiltrates data from a different AWS account entirely.

Serverless and Managed Services Shift Testing Focus

Cloud providers abstract infrastructure, changing what you're actually testing:

  • Serverless functions (Lambda, Azure Functions, Cloud Run): No OS to patch, but event injection, environment variable leakage, and IAM over-permissions create new attack vectors.

  • Managed databases and storage: You can't SSH into RDS or DynamoDB. Testing focuses on access policies, encryption, and whether public exposure is intentional.

  • Container orchestration: EKS, AKS, GKE abstract Kubernetes management, but RBAC misconfigurations and service account token abuse remain your responsibility.

This means pentesting must validate logical isolation, whether your Lambda function can access another team's S3 bucket, whether a compromised container can escape to the node, whether cross-account roles are scoped correctly.

Cloud Logging Changes the Evidence Game

Traditional pentesting emphasized stealth. Cloud environments log everything by default: CloudTrail, Azure Activity Log, and GCP Cloud Audit Logs record every API call. You can't avoid creating evidence.

The pentesting shift: instead of avoiding detection, you're validating whether the organization notices malicious activity. Does their SIEM alert on privilege escalation? Do they detect cross-account role assumptions? Can they trace an exploit chain from initial compromise to data exfiltration?

Configuration Review vs Exploitation: What Actually Proves Risk

Configuration scanning tells you what's misconfigured. Exploitation proves what an attacker can actually do with it.

CSPM and configuration scanning tools (Prowler, Scout Suite, Checkov) excel at breadth. They enumerate your cloud resources and flag deviations: an S3 bucket with public read access, an IAM role with * permissions, a security group allowing 0.0.0.0/0 on port 22. These tools are essential for continuous monitoring.

Penetration testing validates exploitability. A public S3 bucket might contain only marketing assets (low risk), or it might contain hundreds of thousands of sensitive customer records (critical breach). Configuration scanning can't distinguish those two cases. It just reports that a public bucket exists.

Multi-Step Attack Chains Configuration Tools Miss

The real danger lies in attack chains that configuration tools miss because they evaluate controls in isolation:




Each individual step might pass configuration review:

  • Web application has WAF enabled

  • IAM role follows least-privilege (scoped to specific S3 buckets)

  • S3 bucket is private (not publicly accessible)

  • CloudTrail logging enabled

But the chain is exploitable. The SSRF vulnerability (application-layer issue) becomes the entry point. The IMDSv1 metadata service provides credentials. The IAM role's AssumeRole trust policy enables privilege escalation.

This is the same failure mode CodeAnt's own IDOR research keeps surfacing at the application layer: individual checks that each look fine reviewed in isolation, and an exploitable path that only shows up once someone actually walks the chain end to end.

CodeAnt's Liquid Network hack writeup is a non-cloud example of exactly this pattern.

The Hybrid Reality

Smart organizations use both approaches strategically:

Approach

Strengths

Best Use Case

Configuration Scanning

Fast, comprehensive coverage; catches known misconfigurations; runs continuously

Continuous monitoring, compliance baselines, catching obvious mistakes

Penetration Testing

Proves real-world exploitability; chains vulnerabilities; demonstrates business impact

Validating defense-in-depth, compliance audits, understanding actual risk

Code-Aware Grey Box Testing

Combines scanning breadth with exploitation depth; understands application logic and data flows

DevOps environments with frequent deployments; continuous validation beyond config checks

Configuration scanning answers: What security controls are misconfigured?

Penetration testing answers: What can an attacker actually accomplish?

Code-aware grey box testing answers: Which misconfigurations are exploitable given our application's actual logic and data flows?

Cloud-Specific Attack Vectors Traditional Pentests Miss

Metadata Services and Identity Token Theft

Cloud metadata services (AWS IMDSv1 at 169.254.169.254, Azure IMDS, GCP metadata server) expose temporary credentials to compute instances. SSRF vulnerabilities in web applications become critical because they provide a direct path to IAM credentials.

Exploitation example:

# SSRF payload targeting AWS metadata service
curl http://vulnerable-app.com/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/

# Returns temporary AWS credentials with instance role permissions
# SSRF payload targeting AWS metadata service
curl http://vulnerable-app.com/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/

# Returns temporary AWS credentials with instance role permissions
# SSRF payload targeting AWS metadata service
curl http://vulnerable-app.com/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/

# Returns temporary AWS credentials with instance role permissions

Defense:

  • Enforce IMDSv2 (session-oriented) on all EC2 instances

  • Network egress filtering to block 169.254.169.254 from application layers

  • Runtime monitoring for unusual metadata service access

  • Least privilege IAM roles attached to compute instances

IAM Privilege Escalation Patterns

Cloud IAM systems enable complex permission chains that create privilege escalation paths invisible to traditional pentests.

High-yield escalation paths:

Technique

Platform

Required Permission

Impact

PassRole + CreateFunction

AWS

iam:PassRole, lambda:CreateFunction

Execute code with any IAM role

UpdateAssumeRolePolicy

AWS

iam:UpdateAssumeRolePolicy

Assume privileged roles

Add-AzRoleAssignment

Azure

Microsoft.Authorization/roleAssignments/write

Grant self any Azure role

SetIamPolicy

GCP

setIamPolicy on projects

Modify project-level permissions

Defense:

  • Permission boundary policies limiting maximum permissions

  • Service Control Policies (SCPs) denying dangerous actions org-wide

  • CloudTrail/Azure Activity Log monitoring for escalation indicators

  • Regular IAM access analysis using AWS IAM Access Analyzer

  • Separation of duties ensuring no single role has both policy creation and role assumption

Serverless Event Injection and Function Exploitation

Serverless functions process events from multiple sources: API gateways, message queues, storage triggers. Attackers can inject malicious payloads into event sources or exploit insecure deserialisation and command injection vulnerabilities.

Defense:

  • Input validation and sanitization for all event data

  • Avoid shell=True in subprocess calls

  • Function-level IAM roles with minimal permissions

  • Runtime security monitoring (AWS GuardDuty for Lambda)

  • Code review for injection vulnerabilities in event handlers

Secrets in CI/CD Pipelines and Build Artifacts

CI/CD systems handle cloud credentials, API keys, and deployment tokens. Hardcoded secrets in code, exposed environment variables in build logs, or overly permissive service account keys create persistent access.

Common exposures:

  • Hardcoded AWS keys in application code or IaC templates

  • Environment variables logged in CI/CD output

  • Long-lived service account keys checked into repositories

  • Overprivileged deployment credentials with full admin access

Defense:

  • Pre-commit secret scanning using git-secrets or TruffleHog

  • Secrets management services (AWS Secrets Manager, Azure Key Vault)

  • OIDC federation for CI/CD authentication (eliminating static credentials)

  • Build log sanitization

  • Regular credential rotation

Platform-Specific Attack Vectors

AWS: IAM, S3, Lambda, IMDS

IAM Privilege Escalation via PassRole:

# Create Lambda with privileged role (if PassRole allowed)
aws lambda create-function --function-name escalate \
  --role arn:aws:iam::123456789012:role/AdminRole \
  --runtime python3.9 --handler index.handler --zip-file

# Create Lambda with privileged role (if PassRole allowed)
aws lambda create-function --function-name escalate \
  --role arn:aws:iam::123456789012:role/AdminRole \
  --runtime python3.9 --handler index.handler --zip-file

# Create Lambda with privileged role (if PassRole allowed)
aws lambda create-function --function-name escalate \
  --role arn:aws:iam::123456789012:role/AdminRole \
  --runtime python3.9 --handler index.handler --zip-file

S3 Exposure Beyond Public ACLs:

Test for bucket policies with Principal: "*" and insufficient condition keys, cross-account access without external ID, and versioning without lifecycle policies.

# Enumerate with compromised credentials
aws s3api list-buckets
aws s3api get-bucket-policy --bucket

# Enumerate with compromised credentials
aws s3api list-buckets
aws s3api get-bucket-policy --bucket

# Enumerate with compromised credentials
aws s3api list-buckets
aws s3api get-bucket-policy --bucket

Lambda Event Injection:

Functions often have broad IAM permissions and process untrusted input. Test environment variable exposure:

aws lambda get-function-configuration --function-name sensitive-function \
  --query 'Environment.Variables'
aws lambda get-function-configuration --function-name sensitive-function \
  --query 'Environment.Variables'
aws lambda get-function-configuration --function-name sensitive-function \
  --query 'Environment.Variables'

IMDS v1 vs v2:

IMDSv1 allows simple HTTP GET requests; IMDSv2 requires a session token via PUT. Many SSRF vulnerabilities can't make PUT requests, so IMDSv2 blocks the attack, but test whether your SSRF allows full HTTP control.

Azure: Entra ID, Storage, Managed Identities

Entra ID as Primary Attack Surface:

Application registrations with overly permissive API permissions (Directory.ReadWrite.All, RoleManagement.ReadWrite.Directory) can modify directory objects or assign roles.

# Enumerate app registrations and permissions
az ad app list --query "[].{name:displayName, appId:appId}" -o table
az ad app permission list --id

# Enumerate app registrations and permissions
az ad app list --query "[].{name:displayName, appId:appId}" -o table
az ad app permission list --id

# Enumerate app registrations and permissions
az ad app list --query "[].{name:displayName, appId:appId}" -o table
az ad app permission list --id

Managed Identity Exploitation:

Azure VMs and App Services expose managed identity tokens via IMDS:

# Retrieve managed identity token from compromised VM
curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/' -H

# Retrieve managed identity token from compromised VM
curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/' -H

# Retrieve managed identity token from compromised VM
curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/' -H

Storage Account Key Exposure:

Storage account keys provide full access to all data. Look for keys in application configuration, connection strings with embedded keys, and rotation failures leaving multiple valid credentials active.

Cross-Tenant Guest Risk:

External users invited as guests inherit permissions in the host tenant. Test for guests with admin roles, resource access via groups, and conditional access bypass.

GCP: Cloud IAM, Storage, Service Accounts

Service Account Key Hygiene:

Unlike AWS IAM roles that leverage temporary credentials, GCP service account keys are long-lived JSON files. User-managed keys don't rotate automatically.

# List service accounts and check for user-managed keys
gcloud iam service-accounts list --project=target-project
gcloud iam service-accounts keys list \
  --iam-account

# List service accounts and check for user-managed keys
gcloud iam service-accounts list --project=target-project
gcloud iam service-accounts keys list \
  --iam-account

# List service accounts and check for user-managed keys
gcloud iam service-accounts list --project=target-project
gcloud iam service-accounts keys list \
  --iam-account

IAM Role Privilege Escalation:

GCP permissions are cumulative and inherited across organization, folder, project, and resource levels.

# Get IAM policy for project
gcloud projects get-iam-policy target-project --flatten="bindings[].members"
# Get IAM policy for project
gcloud projects get-iam-policy target-project --flatten="bindings[].members"
# Get IAM policy for project
gcloud projects get-iam-policy target-project --flatten="bindings[].members"

Test for iam.serviceAccountKeyAdmin, iam.serviceAccountTokenCreator, and resourcemanager.projects.setIamPolicy permissions.

Cloud Storage Bucket Exposure:

# Check bucket IAM policy
gsutil iam get gs://target-bucket-name

# Test authenticated access with compromised service account
gsutil -i app-backend@target-project.iam.gserviceaccount.com ls

# Check bucket IAM policy
gsutil iam get gs://target-bucket-name

# Test authenticated access with compromised service account
gsutil -i app-backend@target-project.iam.gserviceaccount.com ls

# Check bucket IAM policy
gsutil iam get gs://target-bucket-name

# Test authenticated access with compromised service account
gsutil -i app-backend@target-project.iam.gserviceaccount.com ls

Common misconfigurations include roles/storage.objectViewer granted to allAuthenticatedUsers and signed URLs with excessive expiration.

Choosing Your Testing Approach

Black Box vs Grey Box vs White Box

Black box testing simulates an external adversary with zero prior knowledge, enumerating subdomains, probing exposed APIs, analyzing JavaScript bundles. It validates public attack surface but misses authenticated attack paths, authorization flaws, and privilege escalation chains.

Grey box testing provides authenticated access (valid credentials at multiple privilege levels) with partial code context. This is the sweet spot for cloud pentesting because:

  • Identity is the perimeter, so testing with valid credentials lets you probe authorization boundaries

  • Exploit chains require context: understanding authentication middleware and authorization logic reveals multi-step attack paths

  • Practical efficiency: it avoids the overhead of full white box access while catching the authorization flaws that matter most

White box testing provides complete access: source code, architecture diagrams, IAM policies, credentials for all environments. It delivers comprehensive coverage but requires significant time investment (3-6 weeks), high cost ($30K-$100K+), and creates a point-in-time snapshot outdated the moment your next deployment ships.

CodeAnt's guide to the three pentest types covers this same trade-off in more general terms, outside the cloud context specifically.

Continuous vs Point-in-Time Testing

Annual pentests made sense when teams deployed quarterly. They don't work when you're shipping dozens of times a day.

Why annual pentests fail:

  • A team deploying 200 times per month and pentesting once a year is testing a tiny fraction of its production changes against anything offensive

  • Stale findings, because infrastructure evolves significantly during report delivery

  • No validation of fixes without expensive retest engagements

  • Compliance theater over real security

The hybrid operating model:

  • Continuous automated discovery: runs on every deployment, covering reconnaissance, configuration scanning, and safe exploit validation

  • Quarterly human-led deep dives: expert pentesters find novel attack chains, business logic flaws, sophisticated privilege escalation paths

  • Frequent re-scans: fix an issue and trigger a retest the same day rather than waiting for the next scheduled engagement

This catches common issues immediately while reserving expensive manual expertise for sophisticated scenarios. CodeAnt's continuous versus annual pentesting guide goes deeper into exactly this trade-off, including how to measure the gap your own release cadence creates.

Where CodeAnt AI Fits: Code-Aware Offensive Testing

Most platforms force you to choose between defensive tooling that catches vulnerabilities in pull requests or offensive platforms that probe your infrastructure from outside. CodeAnt AI connects both through the same code intelligence layer.

  • Code-aware reconnaissance: The platform doesn't blindly fuzz endpoints. It analyzes JavaScript bundles to extract API routes, parses authentication middleware to identify bypass opportunities, and maps data flows through source code to spot BOLA and IDOR vulnerabilities before launching exploits, the same class covered in depth in CodeAnt's IDOR guide.

  • Authenticated attack simulation: Grey box testing with real session context. The engine authenticates as different user roles, then systematically tests privilege boundaries, horizontal access controls, and cross-tenant isolation, attack vectors external-only scanners miss.

  • Exploit chain construction: 500+ autonomous exploit agents don't just find individual issues. They chain vulnerabilities (SSRF to metadata service to IAM credential theft to lateral movement) to demonstrate real business impact.

On the configuration side specifically, CodeAnt's Cloud Security Posture Management feature connects to AWS, GCP, and Azure through a read-only role (no write, create, or delete permissions, the same least-privilege principle this article recommends for every IAM role you grant).

A full account scan typically finishes in minutes and evaluates the configuration against CIS, SOC 2, ISO 27001, HIPAA, PCI DSS, NIST 800-53, and several other frameworks in the same pass.

That CSPM layer is the configuration-scanning half of this article. The offensive pentest is what chains a finding it surfaces, like an over-broad IAM role or a public bucket, into a proven exploit path rather than leaving it as an isolated flag.

The defensive feedback loop: When offensive testing discovers a working exploit, the defensive engine can be updated to catch that pattern in future code changes, closing the loop between the offensive and defensive sides of the platform.

What this delivers:

  • Continuous offensive testing aligned with deployment velocity

  • Compliance-grade evidence (SOC 2, ISO 27001, PCI-DSS, HIPAA) with CVSS scoring and reproducible PoC exploits

  • Code-level remediation guidance: exact source locations and suggested fixes

  • Performance-based model: no working exploit, no payment

Where you still need humans: Novel zero-days requiring deep research, niche domain expertise (Kubernetes runtime escapes, advanced cryptographic implementations), and sophisticated social engineering still benefit from specialized manual pentesting.

Practical Implementation: 30/60/90-Day Program

Days 1-30: Establish Baseline

Week 1:

  • Enumerate cloud footprint using Scout Suite or Prowler, or connect a read-only CSPM scan as described above

  • Map IAM boundaries and identify crown jewels

  • Document public attack surface

Weeks 2-4:

  • Deploy continuous configuration scanning

  • Fix top 10 critical findings (public S3 buckets, IMDSv1 instances)

  • Establish baseline metrics (MTTR, critical findings resolved)

Target: Eliminate publicly accessible storage with sensitive data, migrate to IMDSv2.

Days 31-60: Introduce Grey Box Testing

Weeks 5-6:

  • Select 2-3 critical applications handling sensitive data

  • Provide authenticated access and code context

  • Define success criteria (exploit chains demonstrating business impact)

Weeks 7-8:

  • Run grey box pentesting

  • Validate findings with working PoCs (curl commands proving exploitability)

  • Map findings to compliance controls

  • Prioritize by attack chain depth

Milestone: Deliver an audit-grade report with CVSS scoring and control mappings.

Days 61-90: Establish Retest Cadence

Weeks 9-10:

  • Feed findings into issue tracker (Jira, Linear, GitHub)

  • Implement a frequent re-scan policy for fast fix validation

  • Add security gates to CI/CD

  • Integrate IaC scanning (Terraform, CloudFormation)

Weeks 11-12:

  • Continuous automated testing on every deployment

  • Quarterly grey box pentesting for critical applications

  • Annual manual expert assessment for sophisticated scenarios

  • Track security posture over time

Success metric: By day 90, documented testing cadence, CI/CD security gates, and a measurable reduction in exploitable vulnerabilities reaching production.

Conclusion: Ship Secure Cloud Infrastructure

Cloud pentesting is fundamentally about identity, control planes, and proving exploit chains, not just collecting misconfiguration findings. Real security value comes from demonstrating how an SSRF chains to metadata service access, escalates IAM privileges, and reaches production data.

Your next steps:

  1. Map your attack surface using platform-native tools

  2. Choose grey box testing for code-level exploit chain analysis

  3. Operationalize retesting by integrating findings into CI/CD

  4. Reference the MITRE ATT&CK Cloud Matrix and provider security documentation

Traditional pentesting firms deliver point-in-time reports. Your cloud infrastructure changes with every deployment. CodeAnt AI Pentesting runs autonomous offensive security across black box, grey box, and white box modes, chaining 500+ exploit agents with code-aware intelligence to find real attack paths, with audit-grade reports, CVSS scoring, and compliance mapping (SOC 2, ISO 27001). Retests are available after fixes ship. No working exploit, no payment.

Start 14-day free trial and see how continuous, code-aware pentesting complements your existing security program.

Related reading on CodeAnt AI: AI Penetration Testing For Cloud Security for the enterprise-level overview this guide's methodology sits underneath, Cloud Attack Path Testing for more on validating exploit chains specifically, Continuous Penetration Testing vs Annual Pentesting for the release-cadence argument in full, 3 Types of Penetration Testing for how black, grey, and white box differ outside the cloud-specific context, and the IDOR guide for the application-layer authorization bugs that most often show up as the first link in a cloud attack chain.

FAQs

How do I prove a cloud misconfiguration is actually exploitable?

What's the difference between grey box and black box cloud pentesting?

Can automated tools replace manual pentesting?

How often should I run cloud pentests?

What cloud-specific attack vectors should I prioritize?

Start Your 14-Day Free Trial

AI code reviews, security and quality trusted by modern engineering teams.

Table of Content
No headings found on page
Ship clean & secure code faster

Get Pentest Report

NO CC REQUIRED