Thuta Learning
AWS Advanced
Architecture & GovernanceDevOpsAdvanced

Advanced IAM — Policy Evaluation, Permission Boundaries, ABAC and Cross-Account Roles

AWS AdvancedLesson 450 min

What you'll walk away with

  • Trace the evaluation logic across explicit deny, SCPs, permission boundaries, session policies, identity and resource policies
  • Use permission boundaries for a delegated-admin pattern that lets developers create roles
  • Write ABAC policies with aws:PrincipalTag and aws:ResourceTag
  • Configure and assume a cross-account role with ExternalId, avoiding the confused deputy
  • Use IAM Access Analyzer for external access, unused access and policy validation

Explain it simply

Explain it simply

Imagine entering an office building past several guards. Building security can say 'nobody enters this floor', your manager can limit you to certain rooms, and the room's owner must also have your name on the door. If any guard says 'no', it does not matter what the others say.

In AWS Fundamentals you met identity policies and IAM roles. In real organizations several policy types check every request at once: SCPs, permission boundaries, session policies and resource policies. This lesson teaches how those guards combine, and how to grant access safely between accounts that trust each other.

Problem → Why → Solution

The problem — the confused deputy

Acme, a SaaS vendor, audits customers' AWS accounts. Each customer creates a role in their own account that trusts Acme's account (999988887777) and pastes the role ARN into Acme's website. Acme's backend then assumes that role for each customer.

Now an attacker signs up as an Acme customer and enters another customer's role ARN instead of their own. ARNs are not secrets — they leak through screenshots, logs or guessing. The victim's trust policy trusts Acme's account, so Acme successfully assumes the victim's role on the attacker's behalf and shows the attacker the victim's data. Acme has become a confused deputy.

create-vendor-role-vulnerable.sh
# Run in the CUSTOMER account, following the vendor's old setup guide
cat > trust-policy.json <<'EOF'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "TrustTheVendorAccount",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::999988887777:root" },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
aws iam create-role \
  --role-name AcmeAuditReadOnly \
  --assume-role-policy-document file://trust-policy.json

Why this trust policy is dangerous

This policy trusts any authorized principal in Acme's account, but nothing checks which customer Acme is acting for. A single vendor-side bug, or the ARN-swapping trick above, lets one customer see another customer's data.

Core concept — how IAM decides a request

Every request starts as an implicit deny: nothing is allowed until something allows it. IAM then gathers every applicable policy. If any policy of any type contains a matching explicit deny, the answer is deny, and no allow can override it.

Policy typeAttached toCan it grant?
Identity-basedUser, group, roleYes — the main grant
Resource-basedS3 bucket, KMS key, role trust policy, etc.Yes — especially cross-account
Permission boundaryUser or roleNo — ceiling only
Session policyPassed in an AssumeRole callNo — ceiling only
SCP (RCP)Organization root/OU/accountNo — ceiling only

With no deny, every ceiling must allow the action: the SCPs if the account is in an organization, the boundary if the principal has one, and the session policy if the session was created with one. Then a grant must exist. Within one account, an allow in either the identity policy or the resource policy is enough. Across accounts, both sides must allow: an identity policy in the caller's account and a resource policy (or role trust policy) in the target account.

For the ceilings, think intersection: effective permissions are only what the identity policy, boundary, session policy and SCPs all agree on. There are edge cases — for example when a resource policy names a role session directly — so use AWS's policy evaluation flowchart as the reference for unusual situations.

Session policies deserve their own note. When you call AssumeRole you can pass a policy as a parameter, and the resulting session can do only what both the role's permissions and that session policy allow. This is useful when a broker service hands out narrow, per-user sessions from one broad role. A role's trust policy is itself a resource policy: it decides who may assume the role, while the role's permission policies decide what the session can do afterwards.

text
POLICY EVALUATION (SIMPLIFIED)
------------------------------
  request
     |
     v
 [ explicit Deny in ANY policy? ] --yes--> DENY
     | no
     v
 [ SCPs allow? (in an organization) ] --no--> DENY
     | yes
     v
 [ resource policy allows? (same account) ] --yes--> ALLOW *
     | no
     v
 [ identity policy allows? ] --no--> DENY (implicit)
     | yes
     v
 [ permission boundary allows? (if set) ] --no--> DENY
     | yes
     v
 [ session policy allows? (if set) ] --no--> DENY
     | yes
     v
   ALLOW
 * cross-account: identity policy AND resource policy must both allow
Picture the guards in a row
  1. Explicit deny always wins
  2. Ceilings: SCP, boundary, session
  3. Grant: identity or resource policy
  4. Cross-account: both sides allow

Ceilings can only remove permissions. When a request is denied, the first question is: which ceiling cut it off?

Assuming a role with an ExternalId

bash
aws sts assume-role \
  --role-arn arn:aws:iam::111122223333:role/AcmeAuditReadOnly \
  --role-session-name acme-audit-contoso \
  --external-id acme-cust-7f3a9c2e \
  --duration-seconds 900 \
  --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' \
  --output text

The role ARN is the role in the target account, the session name identifies who did what in CloudTrail, and the external ID must match the trust policy's sts:ExternalId condition. The three returned credentials expire after 15 minutes. Adding a session policy with --policy narrows this session further.

A vendor assuming a customer role safely

The fix has two parts. Acme generates a unique external ID for each customer itself and stores it with the customer record — the customer never chooses it. The customer adds that ID as a requirement in their trust policy. If an attacker enters the victim's ARN, Acme still sends the attacker's external ID, which does not match the victim's trust policy, so AssumeRole fails. Creating the role with that trust policy in the customer's account looks like this.

create-vendor-role-fixed.sh
# Run in the CUSTOMER account (111122223333)
cat > trust-policy.json <<'EOF'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "TrustAcmeForThisCustomerOnly",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::999988887777:role/AcmeAuditor" },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": { "sts:ExternalId": "acme-cust-7f3a9c2e" }
      }
    }
  ]
}
EOF
aws iam create-role \
  --role-name AcmeAuditReadOnly \
  --assume-role-policy-document file://trust-policy.json
aws iam attach-role-policy \
  --role-name AcmeAuditReadOnly \
  --policy-arn arn:aws:iam::aws:policy/SecurityAudit

The principal is also narrowed from the account root to one specific Acme role. The Python below is Acme's backend side: it obtains a short-lived session for one customer and checks who it is acting as.

assume_customer_role.py
"""Assume a customer's cross-account role the way a SaaS vendor should."""
from __future__ import annotations

import boto3

CUSTOMER_ROLE_ARN = "arn:aws:iam::111122223333:role/AcmeAuditReadOnly"
# Generated by the vendor per customer and stored with the customer record.
EXTERNAL_ID = "acme-cust-7f3a9c2e"


def customer_session(role_arn: str, external_id: str, customer: str) -> boto3.Session:
    sts = boto3.client("sts")
    resp = sts.assume_role(
        RoleArn=role_arn,
        RoleSessionName=f"acme-audit-{customer}",
        ExternalId=external_id,
        DurationSeconds=900,  # 15 minutes: just long enough for one audit run
    )
    creds = resp["Credentials"]
    return boto3.Session(
        aws_access_key_id=creds["AccessKeyId"],
        aws_secret_access_key=creds["SecretAccessKey"],
        aws_session_token=creds["SessionToken"],
        region_name="us-east-1",
    )


if __name__ == "__main__":
    session = customer_session(CUSTOMER_ROLE_ARN, EXTERNAL_ID, "contoso")
    me = session.client("sts").get_caller_identity()
    print("account:", me["Account"])
    print("arn:", me["Arn"])

Not runnable in the browser

This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.

Code breakdown

  1. EXTERNAL_IDEXTERNAL_ID = "acme-cust-7f3a9c2e"

    The external ID is not a password; it is a unique value that tells customers apart. What matters is that the vendor generates it and the customer cannot choose it — otherwise an attacker could simply type in the victim's ID.

  2. RoleSessionNameRoleSessionName=f"acme-audit-{customer}"

    The session name appears as the last part of the assumed-role ARN in the customer's CloudTrail, so the customer can trace exactly what Acme did.

  3. DurationSecondsDurationSeconds=900

    900 seconds is the minimum duration, so leaked credentials expire within 15 minutes. The maximum is capped by the role's MaxSessionDuration setting.

  4. get_caller_identitysession.client("sts").get_caller_identity()

    This call needs no permissions, which makes it the ideal check that the credentials work and that you landed in the right account.

You should see
account: 111122223333
arn: arn:aws:sts::111122223333:assumed-role/AcmeAuditReadOnly/acme-audit-contoso
Cross-account AssumeRole flow
  1. Vendor role calls AssumeRole
  2. Vendor identity policy allows?
  3. Trust policy + ExternalId match?
  4. STS returns temp credentials

ExternalId matches

15-minute session

Swapped ARN, wrong ID

AccessDenied

Permission boundaries for delegated admin

Developers want to create an IAM role for every new Lambda function, but unrestricted iam:CreateRole lets them create a role with AdministratorAccess and escalate to admin. A permission boundary solves this: developers may create roles only if they attach AppBoundary. Whatever policies they then put on the role, it can never exceed the boundary.

developer-delegated-iam.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "CreateAndEditAppRolesOnlyWithBoundary",
      "Effect": "Allow",
      "Action": [
        "iam:CreateRole",
        "iam:PutRolePermissionsBoundary",
        "iam:AttachRolePolicy",
        "iam:PutRolePolicy"
      ],
      "Resource": "arn:aws:iam::111122223333:role/app/*",
      "Condition": {
        "StringEquals": {
          "iam:PermissionsBoundary": "arn:aws:iam::111122223333:policy/AppBoundary"
        }
      }
    },
    {
      "Sid": "PassOnlyAppRoles",
      "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "arn:aws:iam::111122223333:role/app/*"
    },
    {
      "Sid": "NoRemovingTheBoundary",
      "Effect": "Deny",
      "Action": "iam:DeleteRolePermissionsBoundary",
      "Resource": "arn:aws:iam::111122223333:role/app/*"
    },
    {
      "Sid": "NoEditingTheBoundaryPolicy",
      "Effect": "Deny",
      "Action": [
        "iam:CreatePolicyVersion",
        "iam:DeletePolicy",
        "iam:DeletePolicyVersion",
        "iam:SetDefaultPolicyVersion"
      ],
      "Resource": "arn:aws:iam::111122223333:policy/AppBoundary"
    }
  ]
}

The last two statements are the part people forget. If developers could remove the boundary from a role, or rewrite the boundary policy with a new version, they could escape it. The role/app/ path also keeps developer-created roles separate from platform roles.

ABAC with tags

With role-based access control (RBAC) every new project needs new policies. Attribute-based access control (ABAC) compares the principal's tags with the resource's tags. The single policy below allows starting and stopping only instances whose project tag matches the caller's, and it does not change when you have 50 projects. The principal tags can come from IdP attributes through Identity Center.

abac-ec2.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "OperateOwnProjectInstances",
      "Effect": "Allow",
      "Action": ["ec2:StartInstances", "ec2:StopInstances", "ec2:RebootInstances"],
      "Resource": "arn:aws:ec2:*:111122223333:instance/*",
      "Condition": {
        "StringEquals": {
          "aws:ResourceTag/project": "${aws:PrincipalTag/project}"
        }
      }
    },
    {
      "Sid": "NobodyRetagsTheProjectKey",
      "Effect": "Deny",
      "Action": ["ec2:CreateTags", "ec2:DeleteTags"],
      "Resource": "*",
      "Condition": {
        "ForAnyValue:StringEquals": { "aws:TagKeys": ["project"] }
      }
    }
  ]
}

Protect the tags themselves

In ABAC a tag becomes a permission. If people can retag an instance into another project, or edit their own principal tags, ABAC collapses. Always pair it with a tag-change guardrail like the second Deny statement.

IAM Access Analyzer

Once there are many policies, human review stops being enough. IAM Access Analyzer has three main features. The external access analyzer reports resources — S3 buckets, IAM roles, KMS keys and more — shared with principals outside your zone of trust (the organization or account). The unused access analyzer finds unused roles, access keys and permissions so you can shrink toward least privilege. Policy validation checks a policy for grammar errors and security warnings before deployment, which is why teams run it in CI pipelines.

access-analyzer.sh
# External access across the whole organization (run in the delegated admin)
aws accessanalyzer create-analyzer \
  --analyzer-name org-external-access \
  --type ORGANIZATION

# Unused access: roles, keys and permissions unused for 90 days
aws accessanalyzer create-analyzer \
  --analyzer-name account-unused-access \
  --type ACCOUNT_UNUSED_ACCESS \
  --configuration '{"unusedAccess": {"unusedAccessAge": 90}}'

# Validate a policy before it ships (great as a CI step)
aws accessanalyzer validate-policy \
  --policy-type IDENTITY_POLICY \
  --policy-document file://developer-delegated-iam.json \
  --query 'findings[].[findingType,issueCode]' --output text

In production

In real production

In real multi-account environments, humans sign in through Identity Center permission sets and workloads use IAM roles; long-lived access keys should be the exception. CI/CD pipelines assume roles through an OIDC provider such as GitHub Actions instead of storing keys. Third-party vendors such as monitoring tools and security scanners ask for cross-account roles with an ExternalId — that is the industry standard, and a vendor that does not ask for one is a red flag.

Platform teams build permission boundaries into account vending, so developers create their own roles without opening a ticket. That speeds delivery without weakening security. Every IAM policy change is checked by Access Analyzer validation in the pull request, and unused-access findings are reviewed quarterly to remove dead roles and permissions. When AWS services call your resources (for example S3 publishing to an SNS topic), resource policies add aws:SourceArn and aws:SourceAccount conditions to prevent the service-level version of the confused deputy.

Common mistakes

Common mistakes

Letting the customer choose the external ID

Some vendors ask customers to type in their own external ID. Then an attacker can enter both the victim's ARN and the victim's ID, and the protection disappears. The vendor must generate a unique ID per customer account and never let it be edited.

Not protecting the boundary itself

Developers are allowed to create roles only with the boundary, but nobody denies iam:DeleteRolePermissionsBoundary or iam:CreatePolicyVersion on the boundary policy — so they create the role and immediately strip the boundary. Close every escalation path.

Adding allows to fix a ceiling denial

On every AccessDenied, people add broader allows with * to the identity policy. If the denial comes from an SCP, a boundary or a session policy, no amount of allows changes anything — the policy just gets wider. Read the error message carefully; it often names the policy type that blocked the request.

💰 Cost & Cleanup

IAM, STS and permission boundaries are free. In IAM Access Analyzer, external access analysis and policy validation are free, but the unused access analyzer is charged per IAM role or user analyzed per month, and custom policy checks (such as check-no-new-access) are charged per API call — check the pricing page for current rates. After the lab, delete the unused access analyzer and any test roles and policies you created.

Clean up when you are done

bash
aws accessanalyzer delete-analyzer --analyzer-name account-unused-access
aws accessanalyzer delete-analyzer --analyzer-name org-external-access
# If you created test roles under the app/ path, detach their policies first:
aws iam detach-role-policy \
  --role-name app-orders-fn \
  --policy-arn arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess
aws iam delete-role --role-name app-orders-fn

Mini challenge

Team-scoped DynamoDB access with ABAC

Ten teams share DynamoDB tables in one account. Write one ABAC policy so that adding a new team never requires a policy change.

  • Allow GetItem, PutItem and Query only on tables whose `team` tag matches the caller's
  • Scope the table ARN to account `111122223333`
  • Deny tagging or untagging the `team` key on tables

Expected: A role tagged `team=payments` can read and write the `team=payments` table and gets AccessDenied on the `team=search` table. Attempts to change a table's team tag are denied.

Show hint

Compare `aws:ResourceTag/team` with `${aws:PrincipalTag/team}`. The DynamoDB tag actions are `dynamodb:TagResource` and `dynamodb:UntagResource`.

Show solution
abac-dynamodb.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "OwnTeamTablesOnly",
      "Effect": "Allow",
      "Action": ["dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Query"],
      "Resource": "arn:aws:dynamodb:*:111122223333:table/*",
      "Condition": {
        "StringEquals": {
          "aws:ResourceTag/team": "${aws:PrincipalTag/team}"
        }
      }
    },
    {
      "Sid": "ProtectTeamTag",
      "Effect": "Deny",
      "Action": ["dynamodb:TagResource", "dynamodb:UntagResource"],
      "Resource": "*",
      "Condition": {
        "ForAnyValue:StringEquals": { "aws:TagKeys": ["team"] }
      }
    }
  ]
}

Quick quiz 1 / 3

A role's identity policy allows `s3:*` and its permission boundary allows only `s3:GetObject`. What happens when the role calls `s3:PutObject`?

Quick quiz 2 / 3

What is the main purpose of an `sts:ExternalId` condition in a cross-account role's trust policy?

Quick quiz 3 / 3

What does an IAM Access Analyzer external access finding mean?

What to remember

  • Explicit deny always wins; SCPs, boundaries and session policies are ceilings (intersection)
  • Cross-account requests need both the caller's identity policy and the target's resource or trust policy
  • Permission boundaries let developers create roles, but the boundary itself must be protected
  • ABAC turns tags into permissions, so it always needs a tag-change guardrail
  • A vendor-generated ExternalId stops the confused deputy; Access Analyzer audits external and unused access

IAM policy evaluation logic — AWS Documentation

The confused deputy problem — AWS Documentation

Using AWS IAM Access Analyzer — AWS Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Advanced IAM — Policy Evaluation, Permission Boundaries, ABAC and Cross-Account Roles | Thuta Learning