SecurityPart 3: Cloud and infrastructure security
Chapter 9Cloud identity and access
In 2019 an attacker tricked a misconfigured firewall at Capital One into fetching cloud credentials whose role could read S3, and data on roughly 100 million people walked out without a single exploit against the provider. You will learn to read, write and attack cloud permissions well enough to find that over-permissioned identity before someone else does.
After this chapter you can
- Explain the shared responsibility model and which part of it is always yours
- Trace how AWS decides whether a request is allowed, step by step, and map that to Azure and GCP
- Replace long-lived access keys with role assumption and OIDC workload federation
- Find and fix the classic IAM misconfigurations, including privilege escalation paths and metadata abuse
- Apply guardrails (SCPs, permission boundaries) and explain what a CSPM tool adds
Shared responsibility and why identity is your job
Cloud providers secure the hardware, the hypervisor, the physical network and the managed service code. You secure everything you configure on top. The split moves with the service type, but one item never moves: identity and access are always yours.
| Layer | IaaS (EC2, VMs) | PaaS (Lambda, App Service) | SaaS (Microsoft 365) |
|---|---|---|---|
| Physical, hypervisor | Provider | Provider | Provider |
| Operating system patching | You | Provider | Provider |
| Application code | You | You | Provider |
| Network exposure settings | You | You (mostly) | Provider |
| Data classification | You | You | You |
| Identities, roles, policies | You | You | You |
That last row explains the breach statistics. Industry reports keep finding that most cloud incidents start with a misconfiguration or a stolen credential, not a provider flaw. In the cloud, every action is an API call, so whoever holds a credential with the right permissions controls your infrastructure. The perimeter is the API, and identity is the lock on it.
Principals, policies and the request context
Every cloud authorization decision has the same parts. A principal (who is asking) wants to perform an action (what) on a resource (on what), under some conditions (source IP, time, MFA, tags). A policy is a document that says which combinations are allowed or denied.
In AWS the principals are IAM users (long-lived identities with passwords or access keys), IAM roles (identities with no credentials of their own, which you assume to get temporary ones) and federated identities. Policies are JSON documents. Here is an identity-based policy that lets someone read objects under one prefix of one bucket:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadReports",
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::acme-reports/finance/*",
"Condition": {
"Bool": { "aws:SecureTransport": "true" }
}
}
]
}AWS has several policy types, and each plays a different role in the decision:
| Policy type | Attached to | Grants access? | Typical use |
|---|---|---|---|
| Identity-based | User, group or role | Yes | What this principal may do |
| Resource-based | Bucket, key, queue, role trust | Yes | Who may touch this resource, including other accounts |
| Permission boundary | User or role | No, only caps | Limit what delegated admins can grant |
| Session policy | One assumed-role session | No, only caps | Narrow a session further |
| Service control policy (SCP) | Account or OU | No, only caps | Organization-wide guardrails on principals |
| Resource control policy (RCP) | Account or OU | No, only caps | Organization-wide guardrails on resources |
A role's trust policy is a resource-based policy on the role itself. It answers "who may assume this role", while the role's permission policies answer "what can the role do once assumed". Mixing those two up is one of the most common review mistakes.
How AWS policy evaluation actually works
AWS starts from an implicit deny and looks for reasons to allow. An explicit Deny always wins: one in any applicable policy ends the evaluation immediately. Every guardrail type that applies (SCP, RCP, boundary, session policy) must also allow the action, because those types only ever subtract.
Three details trip up even experienced engineers:
- Resource policies can grant on their own within an account. If a bucket policy names a role session or IAM user directly, the request can succeed without any identity policy allowing it. A boundary or session policy may still limit grants made to a role's ARN, so read the AWS evaluation page carefully for the edge cases.
- Cross-account needs both sides. For a principal in account A to read a bucket in account B, account A's identity policy must allow it and account B's bucket policy must allow it.
- Conditions are part of the match. A statement whose condition is false simply does not apply. A
Denywith a condition such as "MFA not present" only denies when that condition is true.
The same ideas in Azure and GCP
The vocabulary differs, but the model is the same: identities, permission sets, a scope, and a deny-by-default engine with some form of deny override.
| Concept | AWS | Azure | Google Cloud |
|---|---|---|---|
| Human identity | IAM Identity Center users, IAM users | Entra ID users | Google accounts, Cloud Identity |
| Workload identity | IAM role (instance profile, EKS Pod Identity) | Managed identity | Service account |
| Permission set | Policy JSON with actions | Role definition | Role (bundle of permissions) |
| How access is granted | Attach policy to principal or resource | Role assignment at a scope | Allow policy binding on a resource |
| Hierarchy | Organization, OUs, accounts | Management groups, subscriptions, resource groups | Organization, folders, projects |
| Org-wide guardrail | SCPs and RCPs | Azure Policy, deny assignments | Organization policy constraints, IAM deny policies |
| Federation from outside | IAM OIDC provider, AssumeRoleWithWebIdentity | Workload identity federation | Workload Identity Federation |
The biggest practical difference is inheritance. Azure role assignments and GCP bindings flow down the hierarchy, so a grant high in the hierarchy silently applies to everything below. In AWS, the account is the hard isolation boundary, which is why mature AWS shops run dozens or hundreds of accounts.
Temporary credentials, role assumption and STS
A long-lived access key is a password that never expires and often ends up in a laptop's dotfiles, a CI variable or a public repo. The fix is to make credentials short-lived and obtained on demand. In AWS, the Security Token Service (STS) issues temporary credentials (an access key, a secret and a session token) that expire after minutes to hours.
The caller asks STS to assume a role
The caller already has some identity: an SSO session, an EC2 instance profile, or another role. It calls
sts:AssumeRolewith the target role ARN and a session name.STS checks both sides
The caller's own policies must allow
sts:AssumeRoleon that role, and the role's trust policy must name the caller. External ID and MFA conditions are checked here.STS returns temporary credentials
The response contains credentials tagged with the role and session name. CloudTrail records the session name on every later call, which gives you attribution.
The credentials expire
When they expire, the caller must assume the role again. A stolen copy has a short shelf life instead of an unlimited one.
Workload identity and OIDC federation
The best credential is one that never exists as a stored secret. Modern platforms prove a workload's identity with a signed OIDC token (OpenID Connect, an identity layer on top of OAuth 2.0), which the cloud exchanges for temporary credentials. GitHub Actions, GitLab CI, Kubernetes service accounts and other clouds can all mint these tokens.
The security lives entirely in the trust policy conditions. This one only lets the main branch of one repository assume the role:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": "repo:acme/shop-api:ref:refs/heads/main"
}
}
}
]
}The misconfigurations behind real breaches
Most cloud compromises reuse a small set of mistakes. Learn to spot each one in a policy diff.
| Misconfiguration | What it looks like | What an attacker does |
|---|---|---|
| Public storage | Bucket policy with "Principal": "*", or Block Public Access turned off | Downloads the data anonymously |
| Wildcard actions | "Action": "*" or "s3:*" on "Resource": "*" | Uses permissions nobody meant to grant |
| Escalation path | A low-privilege role can edit IAM | Grants itself admin |
| Metadata abuse | SSRF in an app on a VM with IMDSv1 enabled | Steals the instance role's credentials |
| Leaked static keys | Access keys in Git, CI logs, container images | Uses them from anywhere until revoked |
| Over-broad trust | Role trust policy allows a whole account or any OIDC subject | Assumes the role from outside |
Privilege escalation paths
A privilege escalation path is any permission that lets an identity gain more permissions than it was given. Rhino Security Labs catalogued more than twenty such paths in AWS. The pattern is always the same: some permission lets you write IAM, or lets you borrow a more powerful identity.
- Edit your own policy:
iam:CreatePolicyVersionoriam:SetDefaultPolicyVersionon a policy attached to you. Write a new version with"Action": "*". - Attach a policy:
iam:AttachRolePolicy,iam:PutRolePolicyor the user equivalents. AttachAdministratorAccessto yourself. - Borrow a role with PassRole:
iam:PassRolepluslambda:CreateFunctionandlambda:InvokeFunction. Create a function that runs as an admin role and have it do the work. - Change who can assume a role:
iam:UpdateAssumeRolePolicyon a powerful role. Add yourself to its trust policy. - Mint credentials for someone else:
iam:CreateAccessKeyoriam:CreateLoginProfileon another user.
iam:PassRole deserves special attention. It controls which roles you may hand to a service, and "Resource": "*" on it means "any role in the account, including admin".
Instance metadata abuse
Every EC2 instance can query http://169.254.169.254 for its role's temporary credentials. With IMDSv1, a single unauthenticated GET returns them, so any server-side request forgery (SSRF, covered in Web vulnerabilities) turns into credential theft. IMDSv2 requires a session token obtained with a PUT request and a custom header, which most SSRF bugs cannot produce.
aws ec2 modify-instance-metadata-options \
--instance-id i-0123456789abcdef0 \
--http-tokens required \
--http-put-response-hop-limit 1A hop limit of 1 stops the token response from leaving the instance, so containers on a bridge network cannot reach it. Raise it to 2 only when a container genuinely needs the instance role.
Guardrails, boundaries and continuous posture
Individual policies will always contain mistakes, so mature environments add layers that cap the damage. Each layer answers a different question.
A typical SCP denies actions nobody in the account should ever perform, no matter how much IAM power they gain:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ProtectAuditTrail",
"Effect": "Deny",
"Action": ["cloudtrail:StopLogging", "cloudtrail:DeleteTrail", "organizations:LeaveOrganization"],
"Resource": "*"
},
{
"Sid": "RequireIMDSv2",
"Effect": "Deny",
"Action": "ec2:RunInstances",
"Resource": "arn:aws:ec2:*:*:instance/*",
"Condition": { "StringNotEquals": { "ec2:MetadataHttpTokens": "required" } }
}
]
}Permission boundaries solve delegation. You want developers to create roles for their Lambda functions without being able to create an admin role. Give them iam:CreateRole only with a condition requiring a specific boundary, and the roles they create can never exceed that boundary.
Prevent (guardrails)
- SCPs and RCPs at the organization
- Permission boundaries on delegated roles
- IaC policy checks in CI before merge
Detect (posture)
- CSPM scans of live configuration
- IAM Access Analyzer for external and unused access
- CloudTrail alerts on IAM changes
Cloud security posture management (CSPM) tools continuously read your accounts through the provider APIs and flag drift from a baseline: public buckets, IMDSv1, unused admin roles, keys older than 90 days. Native options include AWS Security Hub, Microsoft Defender for Cloud and Google Security Command Center, and open-source scanners such as Prowler cover the same ground. A CSPM finding is only useful if someone owns fixing it, so route findings to the team that owns the account.
Key terms
- Shared responsibility model
- The split of security duties between the cloud provider and the customer, which varies by service type.
- Principal
- An identity that makes requests: a user, a role session, a service or a federated identity.
- Trust policy
- The resource-based policy on a role that says who is allowed to assume it.
- STS
- AWS Security Token Service, which issues temporary credentials for assumed roles and federated identities.
- Workload identity federation
- Exchanging a signed token from an external platform for short-lived cloud credentials, with no stored secret.
- Privilege escalation path
- A permission or chain of permissions that lets an identity grant itself more access than intended.
- IMDSv2
- The session-token version of the EC2 instance metadata service that blocks most SSRF-based credential theft.
- Service control policy
- An AWS Organizations policy that sets the maximum permissions for principals in an account or OU.
- Permission boundary
- A managed policy attached to a user or role that caps its effective permissions without granting any.
- CSPM
- Cloud security posture management: continuous scanning of live cloud configuration against a security baseline.
Write least-privilege IAM policies and close an escalation path
Goal: build a role with a hidden escalation path, exploit it yourself, then fix it with a corrected policy and a permission boundary.
You need: your own AWS account (IAM and STS are free of charge; this lab creates no billable resources), the AWS CLI v2 configured with an admin profile, and jq. Install with brew install awscli jq on macOS or your distribution's package manager on Linux. Work only in an account you own.
- Set up variables and a role that your admin identity can assume.
export ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
mkdir iam-lab && cd iam-lab
cat > trust.json <<EOF
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::${ACCOUNT}:root" },
"Action": "sts:AssumeRole"
}]
}
EOF
aws iam create-role --role-name lab-dev --assume-role-policy-document file://trust.json- Create the flawed policy. It grants read access to one report prefix, plus a "convenience" that lets developers update their own policy.
cat > dev-v1.json <<EOF
{
"Version": "2012-10-17",
"Statement": [
{ "Sid": "ReadReports", "Effect": "Allow", "Action": "s3:GetObject",
"Resource": "arn:aws:s3:::lab-reports-${ACCOUNT}/reports/*" },
{ "Sid": "SelfServicePolicy", "Effect": "Allow",
"Action": ["iam:GetPolicy", "iam:GetPolicyVersion", "iam:CreatePolicyVersion"],
"Resource": "arn:aws:iam::${ACCOUNT}:policy/lab-dev-policy" }
]
}
EOF
aws iam create-policy --policy-name lab-dev-policy --policy-document file://dev-v1.json
aws iam attach-role-policy --role-name lab-dev \
--policy-arn arn:aws:iam::${ACCOUNT}:policy/lab-dev-policy- Prove the read scope with the simulator. Expect
allowedfor the reports prefix andimplicitDenyfor everything else.
aws iam simulate-principal-policy \
--policy-source-arn arn:aws:iam::${ACCOUNT}:role/lab-dev \
--action-names s3:GetObject iam:ListUsers \
--resource-arns "arn:aws:s3:::lab-reports-${ACCOUNT}/reports/q1.csv" \
--query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output table- Become the developer. Assume the role in a new shell so your admin credentials stay untouched.
CREDS=$(aws sts assume-role --role-arn arn:aws:iam::${ACCOUNT}:role/lab-dev \
--role-session-name attacker --query Credentials --output json)
export AWS_ACCESS_KEY_ID=$(echo "$CREDS" | jq -r .AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo "$CREDS" | jq -r .SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo "$CREDS" | jq -r .SessionToken)
aws sts get-caller-identity # Arn ends in assumed-role/lab-dev/attacker
aws iam list-users # AccessDenied- Exploit the path. Write a new default version of your own policy that allows everything.
echo '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"*","Resource":"*"}]}' > admin.json
aws iam create-policy-version --set-as-default \
--policy-arn arn:aws:iam::${ACCOUNT}:policy/lab-dev-policy \
--policy-document file://admin.json
sleep 10 && aws iam list-users # now succeeds: you are adminNotice that you did not need new credentials. Identity policies are evaluated on every request, so the existing session gained admin rights within seconds.
- Fix it as admin. Open a fresh shell (or
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN), roll back, and remove the escalation.
P=arn:aws:iam::${ACCOUNT}:policy/lab-dev-policy
aws iam set-default-policy-version --policy-arn $P --version-id v1
aws iam delete-policy-version --policy-arn $P --version-id v2
jq 'del(.Statement[] | select(.Sid=="SelfServicePolicy"))' dev-v1.json > dev-v3.json
aws iam create-policy-version --policy-arn $P --policy-document file://dev-v3.json --set-as-default- Add a permission boundary so even a future mistake cannot exceed the intended scope.
cat > boundary.json <<EOF
{
"Version": "2012-10-17",
"Statement": [{ "Effect": "Allow",
"Action": ["s3:GetObject", "sts:GetCallerIdentity"],
"Resource": "*" }]
}
EOF
aws iam create-policy --policy-name lab-dev-boundary --policy-document file://boundary.json
aws iam put-role-permissions-boundary --role-name lab-dev \
--permissions-boundary arn:aws:iam::${ACCOUNT}:policy/lab-dev-boundary- Re-test: temporarily put the flawed
dev-v1.jsonback as a new default version, assume the role again as in step 4, and retry step 5. Thecreate-policy-versioncall now fails with AccessDenied, because the boundary does not allow anyiam:action.
Check your work: as the assumed role, aws iam list-users and aws iam create-policy-version both return AccessDenied even when the identity policy contains the flawed statement, while the simulator still reports allowed for s3:GetObject on the reports prefix.
Clean up: detach and delete both policies (delete non-default versions first with aws iam list-policy-versions and delete-policy-version), then aws iam delete-role --role-name lab-dev.
Stretch: run aws accessanalyzer validate-policy --policy-type IDENTITY_POLICY --policy-document file://admin.json and read its findings, then write an IAM policy for a delegated admin that may create roles only if they carry lab-dev-boundary, using the iam:PermissionsBoundary condition key.
Check yourself
A role's identity policy allows s3:DeleteObject on all buckets, and an SCP on its account allows all actions except a Deny on s3:DeleteObject. What happens when the role deletes an object?
A CI role has iam:PassRole on Resource star, plus lambda:CreateFunction and lambda:InvokeFunction. Why is this an escalation path?
An app on EC2 has an SSRF bug. Which change most directly stops the attacker from stealing the instance role's credentials through it?
Your GitHub OIDC trust policy checks that the audience is sts.amazonaws.com but has no condition on the sub claim. What is the risk?
Recap
- Identity and access configuration is always the customer's responsibility, whatever the service model.
- AWS evaluation starts at implicit deny, any explicit Deny wins, and SCPs, RCPs, boundaries and session policies can only subtract.
- Short-lived credentials from STS and OIDC federation remove the long-lived keys that cause so many breaches.
- Any permission that writes IAM or passes roles is a potential escalation path, so review those first.
- IMDSv2, SCP guardrails, permission boundaries and CSPM together turn single mistakes into contained ones.
Go deeper
- AWS IAM policy evaluation logic: the authoritative description of every policy type and how they combine.
- Permissions boundaries for IAM entities: worked examples of delegated administration with boundaries.
- Configuring OpenID Connect in Amazon Web Services: GitHub's guide to keyless deploys from Actions.
- AWS privilege escalation methods: Rhino Security Labs' catalogue of IAM escalation paths with mitigations.
- Hacking the Cloud: a community encyclopedia of offensive techniques across AWS, Azure and GCP.