Skip to content

Lesson 7 of 30Identity and security

IAM Policies in Depth

The full evaluation flow, cross-account roles, condition keys, boundaries and SCPs, with a runnable policy evaluator to test your own policies.

22 min read0/5 questions

A Lambda function in your data account must read last night's export from a bucket in the production account. The bucket is encrypted with a customer managed KMS key. You give the role s3:GetObject, deploy, and get AccessDenied. You add a bucket policy. Still denied. The fix needs a third policy in a service you never touched, and an SCP somewhere above both accounts could block it anyway. In the IAM lesson you learned the core rule: explicit deny wins, then allow, otherwise deny. This lesson is everything that sits around that rule, because that is where real AccessDenied tickets come from.

This unit goes a level deeper than Core services. If you are new to AWS, skim it on a first pass and come back when you hit your first cross-account AccessDenied.

Seven policy types, two jobs

Every policy type does one of two jobs. Some grant permissions. Others only cap them: they can never give access, they can only take it away.

Policy typeAttached toGrants or capsWritten by
Identity-basedUser, group, roleGrantsApp and platform teams
Resource-basedBucket, key, queue, secret, role (trust policy)GrantsResource owner
Permissions boundaryUser or roleCapsPlatform team
Session policyOne AssumeRole sessionCapsWhoever assumes the role
SCP (service control policy)Org root, OU or accountCaps principalsCloud platform team
RCP (resource control policy)Org root, OU or accountCaps resourcesCloud platform team
VPC endpoint policyA VPC endpointCapsNetwork team

Two facts surprise people. First, a role's trust policy is a resource-based policy. The role is the resource, sts:AssumeRole is the action. Second, SCPs and RCPs are not "allow lists" in the sense of granting anything. The default FullAWSAccess SCP only says "this layer does not object". You still need an identity or resource policy that grants the action.

SCPs limit principals in member accounts (including each member account's root user). RCPs, added in late 2024, limit resources in member accounts, no matter who calls them, even principals from outside your organization. Neither affects the management account or service-linked roles. RCPs cover a growing list of services, including S3, STS, KMS, SQS and Secrets Manager. Check the Organizations docs for the current list.

The full evaluation flow

When a request arrives, AWS gathers every policy that applies and walks through them. Step through the flow.

How AWS decides, within one account
Request: action + resource + contextRequestaction + resource + contextAny Deny?: all policy typesAny Deny?all policy typesRCPs, SCPs: every level must allowRCPs, SCPsevery level must allowResource policy: names the caller?Resource policynames the caller?Identity policy: allows it?Identity policyallows it?Boundary, session: also allow it?Boundary, sessionalso allow it?ALLOWALLOWDENYDENYyesnono allownames sessionall yesany no

AWS collects every applicable policy: identity, resource, boundary, session, SCPs and RCPs. It looks for a matching Deny in all of them first.

1/6

Read as set algebra, the usual path is: identity ∩ boundary ∩ session ∩ SCP ∩ RCP. Adding a boundary or SCP can only shrink the result. That is why platform teams like them: they are safe to add.

The same-account shortcut, precisely

Inside one account, a resource-based policy that names a principal can grant access even when no identity policy does. The details depend on which ARN it names:

  • An IAM user ARN: not limited by an implicit deny in the user's identity policy or boundary.
  • A role session ARN (arn:aws:sts::111111111111:assumed-role/app/session-1): not limited by identity policy, boundary or session policy.
  • A role ARN (arn:aws:iam::111111111111:role/app): does not need an identity policy, but is limited by the boundary and session policy.
  • The account (arn:aws:iam::111111111111:root): grants nothing by itself. It delegates to IAM, so identity policies decide.

Two resource types break the shortcut entirely: KMS key policies and role trust policies must explicitly allow access. An identity policy alone is never enough for them. The KMS lesson comes back to this.

Same account vs cross-account

Cross-account requests are evaluated twice: once in the caller's account, once in the resource's account. Both must allow.

  • The caller's account checks the identity policy, boundary, session policy and the caller's SCPs.
  • The resource's account checks the resource policy and the resource's RCPs.

So cross-account access always needs two policies, one on each side. A bucket policy that names a role in another account does nothing if that role's identity policy does not also allow s3:GetObject on the bucket. And an identity policy alone cannot reach into another account.

Quick check
A role in account A has s3:* on *. A bucket in account B has no bucket policy. The role calls GetObject on that bucket. What happens?
Need a nudge? A hint rules out a wrong answer.

Cross-account roles and the confused deputy

Most cross-account access is done with roles, not resource policies. Account B creates a role whose trust policy names account A. A principal in A calls sts:AssumeRole (its own identity policy must allow that), gets temporary credentials for B, and works in B with the role's permissions.

Third parties add a twist. A monitoring vendor assumes a role in hundreds of customer accounts. If the vendor's trust relationship is just "the vendor's account may assume this role", an attacker who is also a vendor customer could type your role ARN into their own settings page. The vendor, acting with its own trusted identity, would assume your role for them. That is the confused deputy problem: a privileged service tricked into acting for the wrong customer.

The fix is an external ID: a value the vendor generates per customer and always sends. Your trust policy requires it.

trust policy for a third-party vendor
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "AWS": "arn:aws:iam::333333333333:role/vendor-scanner" },
    "Action": "sts:AssumeRole",
    "Condition": { "StringEquals": { "sts:ExternalId": "acme-7f3a9c" } }
  }]
}
Why the external ID stops a confused deputy
AttackerVendorSTSYour rolemonitor role/acme-prodAssumeRole + ExternalId=globex-11check trust policyAccessDenied

The attacker is a customer of the same vendor and enters your role ARN in their settings.

1/4

AWS services hit the same problem. When S3 publishes events to your SNS topic, the topic policy trusts s3.amazonaws.com, which could be acting for any bucket in any account. Pin it with aws:SourceArn (the exact bucket) and aws:SourceAccount (your account ID) in the condition. Whenever a resource policy trusts a service principal, add those two keys.

Condition keys that matter

Conditions are where policies get precise, and where most subtle bugs live.

KeyWhat it checksTypical use
aws:PrincipalOrgIDCaller's organization IDBucket policy: "anyone in my org" without listing accounts
aws:SecureTransportRequest used TLSDeny plain HTTP to S3
aws:RequestedRegionRegion the call targetsSCP region lock
aws:SourceIpCaller's public IPOffice-only access. Not present for calls through a VPC endpoint
aws:SourceVpceVPC endpoint IDBucket reachable only from your VPC
aws:PrincipalTag/K, aws:ResourceTag/KTags on caller and targetABAC
aws:MultiFactorAuthPresentMFA used for the sessionProtect destructive actions
aws:SourceArn, aws:SourceAccountResource that made a service callConfused deputy protection

The operators have rules of their own:

  • StringEquals is exact. StringLike allows * and ? wildcards. Using StringEquals with a * in the value is a common bug: it matches only a literal asterisk.
  • Several values for one key are OR. Several keys or operators in one block are AND.
  • When a key is missing from the request, a normal operator is false, a negated one (StringNotEquals) is true, and the IfExists variants are true. Null tests presence directly.
  • aws:MultiFactorAuthPresent is missing entirely for long-term access keys. So "Bool": {"aws:MultiFactorAuthPresent": "false"} does not catch them. AWS recommends a Deny with BoolIfExists set to false instead.
  • ForAllValues and ForAnyValue are for multivalued keys like aws:TagKeys. ForAllValues returns true when the key is absent, so an Allow that meant "only these tag keys" also allows a request with no tags at all. Pair it with "Null": {"aws:TagKeys": "false"}. Never use these qualifiers on single-valued keys.
Match the pairs0/5 matched

Match each requirement to the condition key that enforces it.

Choose an item, then its match on the other side.

ABAC: permissions from tags

Role-based access control writes one policy per team and resource. Attribute-based access control (ABAC) writes one policy that compares tags:

one policy for every team
{
  "Effect": "Allow",
  "Action": ["ec2:StartInstances", "ec2:StopInstances"],
  "Resource": "*",
  "Condition": {
    "StringEquals": { "aws:ResourceTag/team": "${aws:PrincipalTag/team}" }
  }
}

${aws:PrincipalTag/team} is a policy variable, filled from the caller's tag at request time. A new team needs no new policy, just tags. Tags on a role session can come from the identity provider as session tags, so your Okta or Entra ID department attribute can drive AWS permissions directly.

The catch: ABAC is only as strong as control over tags. If engineers can retag an instance or their own role, they can grant themselves access. Deny ec2:CreateTags and ec2:DeleteTags on the team key for everyone but the platform role, and do not let people tag their own principals.

Test it yourself: a policy evaluator

Here is a working model of the evaluation flow. It handles explicit deny, Allow, NotAction, wildcards, policy variables, common condition operators with IfExists, Null, ForAllValues and ForAnyValue, SCP levels, RCPs, boundaries, session policies and the cross-account two-sided check. It is a model, not AWS: real evaluation has more operators and service-specific rules. But it gets the logic right, and you can paste in your own policies.

Pythonpolicy_eval.py
import ipaddressimport re def as_list(x): return x if isinstance(x, list) else [x] def wild(pattern, value, ignore_case=False): rx = "".join(".*" if c == "*" else "." if c == "?" else re.escape(c) for c in pattern) return re.fullmatch(rx, value, re.I if ignore_case else 0) is not None def fill(text, ctx): # Policy variables such as ${aws:PrincipalTag/team}. A missing key never matches. return re.sub(r"\$\{([^}]+)\}", lambda m: str(ctx.get(m.group(1), "\0missing")), text) NEGATED = {"StringNotEquals": "StringEquals", "StringNotLike": "StringLike", "ArnNotLike": "ArnLike", "NotIpAddress": "IpAddress"} def compare(op, have, want): if op == "StringEquals": return str(have) == want if op == "StringEqualsIgnoreCase": return str(have).lower() == want.lower() if op in ("StringLike", "ArnLike", "ArnEquals"): return wild(want, str(have)) if op == "Bool": return str(have).lower() == want.lower() if op == "IpAddress": return ipaddress.ip_address(have) in ipaddress.ip_network(want) if op == "NumericLessThan": return float(have) < float(want) raise ValueError("operator not modelled: " + op) def condition_holds(full_op, key, values, ctx): qualifier, op = full_op.split(":", 1) if ":" in full_op else (None, full_op) if_exists = op.endswith("IfExists") op = op[:-8] if if_exists else op wants = [fill(str(v), ctx) for v in as_list(values)] present = ctx.get(key) not in (None, []) if op == "Null": return (not present) == (wants[0].lower() == "true") negated, base = op in NEGATED, NEGATED.get(op, op) if qualifier in ("ForAllValues", "ForAnyValue"): if not present: return qualifier == "ForAllValues" # empty set: ForAll is TRUE hits = [any(compare(base, v, w) for w in wants) for v in as_list(ctx[key])] hits = [not h for h in hits] if negated else hits return all(hits) if qualifier == "ForAllValues" else any(hits) if not present: return if_exists or negated hit = any(compare(base, ctx[key], w) for w in wants) return not hit if negated else hit def principal_kind(st, req): p = st.get("Principal") if p == "*": return "direct" names = as_list(p.get("AWS", [])) + as_list(p.get("Service", [])) kind = None for n in names: if n in ("*", req["principal"]): return "direct" if n == req.get("role"): kind = "role" elif n in (f"arn:aws:iam::{req['account']}:root", req["account"]): kind = kind or "account" return kind def applies(st, req, resource_policy): ctx = req.get("context", {}) act, res = req["action"], req["resource"] if "Action" in st and not any(wild(a, act, True) for a in as_list(st["Action"])): return None if "NotAction" in st and any(wild(a, act, True) for a in as_list(st["NotAction"])): return None if "Resource" in st and not any(wild(fill(r, ctx), res) for r in as_list(st["Resource"])): return None if "NotResource" in st and any(wild(fill(r, ctx), res) for r in as_list(st["NotResource"])): return None kind = principal_kind(st, req) if resource_policy else "direct" if kind is None: return None for op, pairs in st.get("Condition", {}).items(): for key, values in pairs.items(): if not condition_holds(op, key, values, ctx): return None return kind def scan(docs, req, resource_policy=False): """Return (explicit_deny, set of allow kinds) for a list of policy documents.""" kinds = set() for doc in docs: for st in as_list(doc["Statement"]): kind = applies(st, req, resource_policy) if kind and st["Effect"] == "Deny": return True, set() if kind: kinds.add(kind) return False, kinds def evaluate(req, identity=(), resource=None, scps=None, rcps=None, boundary=None, session=None, resource_must_allow=False): act = req["action"] layers = [("identity-based", list(identity), False)] if resource: layers.append(("resource-based", [resource], True)) if boundary: layers.append(("permissions boundary", [boundary], False)) if session: layers.append(("session", [session], False)) for level in scps or []: layers.append(("service control", level, False)) for level in rcps or []: layers.append(("resource control", level, False)) # 1. An explicit Deny in ANY policy type ends it. found = {} for name, docs, is_rbp in layers: deny, kinds = scan(docs, req, is_rbp) if deny: return f"DENY explicit deny in a {name} policy" found.setdefault(name, []).append(kinds) # 2. Org guardrails: every level (root, OU, account) must allow. for name in ("resource control", "service control"): if any(not k for k in found.get(name, [])): return f"DENY no {name} policy allows {act}" ok = lambda name: name not in found or bool(found[name][0]) rbp = found.get("resource-based", [set()])[0] caps = ok("permissions boundary") and ok("session") principal_side = bool(found["identity-based"][0]) and caps if req["account"] != req["resource_account"]: # 3a. Cross-account: BOTH accounts must say yes. if not rbp: return f"DENY no resource-based policy allows {act}" if not principal_side: return f"DENY caller's own account does not allow {act}" return "ALLOW cross-account, both sides allow" # 3b. Same account. if "direct" in rbp: return "ALLOW resource policy names this exact principal" if "role" in rbp and caps: return "ALLOW resource policy names the role" if resource_must_allow and not rbp: return f"DENY no resource-based policy allows {act}" for name in ("identity-based", "permissions boundary", "session"): if not ok(name): return f"DENY no {name} policy allows {act}" return "ALLOW" # ---------- scenarios: edit these and re-run ----------A, B = "111111111111", "222222222222"ROLE = f"arn:aws:iam::{A}:role/report-lambda"SESSION = f"arn:aws:sts::{A}:assumed-role/report-lambda/fn-session" def request(action, resource, resource_account=A, **context): return {"principal": SESSION, "role": ROLE, "account": A, "action": action, "resource": resource, "resource_account": resource_account, "context": {"aws:RequestedRegion": "eu-west-1", **context}} read_reports = {"Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::reports-*/*"}]}full_access = {"Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}]}region_lock = {"Statement": [{"Effect": "Deny", "NotAction": ["iam:*", "sts:*"], "Resource": "*", "Condition": {"StringNotEquals": {"aws:RequestedRegion": ["eu-west-1"]}}}]}org_scps = [[full_access], [full_access, region_lock]] # root level, then OU level r = request("s3:GetObject", "arn:aws:s3:::reports-eu/q3.csv")print("1", evaluate(r, identity=[read_reports], scps=org_scps)) r2 = request("s3:GetObject", "arn:aws:s3:::reports-eu/q3.csv", **{"aws:RequestedRegion": "us-east-1"})print("2", evaluate(r2, identity=[read_reports], scps=org_scps)) x = request("s3:GetObject", "arn:aws:s3:::reports-b/q3.csv", resource_account=B)print("3", evaluate(x, identity=[read_reports]))bucket_policy = {"Statement": [{"Effect": "Allow", "Principal": {"AWS": ROLE}, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::reports-b/*"}]}print("4", evaluate(x, identity=[read_reports], resource=bucket_policy)) boundary = {"Statement": [{"Effect": "Allow", "Action": ["s3:Get*", "logs:*"], "Resource": "*"}]}put = request("s3:PutObject", "arn:aws:s3:::reports-eu/q4.csv")print("5", evaluate(put, identity=[full_access], boundary=boundary)) abac = {"Statement": [{"Effect": "Allow", "Action": "ec2:StopInstances", "Resource": "*", "Condition": {"StringEquals": {"aws:ResourceTag/team": "${aws:PrincipalTag/team}"}}}]}mine = request("ec2:StopInstances", f"arn:aws:ec2:eu-west-1:{A}:instance/i-1", **{"aws:PrincipalTag/team": "payments", "aws:ResourceTag/team": "payments"})theirs = request("ec2:StopInstances", f"arn:aws:ec2:eu-west-1:{A}:instance/i-2", **{"aws:PrincipalTag/team": "payments", "aws:ResourceTag/team": "search"})print("6", evaluate(mine, identity=[abac]), "|", evaluate(theirs, identity=[abac])) tags_only = {"Statement": [{"Effect": "Allow", "Action": "ec2:RunInstances", "Resource": "*", "Condition": {"ForAllValues:StringEquals": {"aws:TagKeys": ["team", "env"]}}}]}untagged = request("ec2:RunInstances", "*")print("7", evaluate(untagged, identity=[tags_only]))
Output
Press Run (⌘ Enter) to see what happens.

Walk through the output. Scenario 2 is the SCP region lock: the Deny matches because us-east-1 is not in the list. Scenario 3 fails on account B's side, and scenario 4 fixes it with a bucket policy. Scenario 5 shows a boundary capping an admin policy. Scenario 7 is the ForAllValues trap: an untagged launch slips through a policy that was meant to require tags.

Predict the outputPython

Add this line to the end of the evaluator and run it. What does it print?

print(evaluate(put, identity=[read_reports], boundary=boundary,
             session={"Statement": [{"Effect": "Deny", "Action": "s3:*", "Resource": "*"}]}))
Need a nudge? Hints walk you through it.

Permission boundaries: letting developers create roles

Platform teams face a dilemma. Developers need to create roles for their Lambdas without a ticket. But iam:CreateRole plus iam:AttachRolePolicy is a path to admin: create a role with AdministratorAccess, assume it, done.

A permissions boundary solves it. You allow role creation only when the new role carries a boundary you control:

developer-iam.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "CreateRolesOnlyWithBoundary",
      "Effect": "Allow",
      "Action": ["iam:CreateRole", "iam:PutRolePermissionsBoundary",
                 "iam:AttachRolePolicy", "iam:PutRolePolicy"],
      "Resource": "arn:aws:iam::111111111111:role/app-*",
      "Condition": {
        "StringEquals": {
          "iam:PermissionsBoundary": "arn:aws:iam::111111111111:policy/app-boundary"
        }
      }
    },
    {
      "Sid": "NeverRemoveOrEditTheBoundary",
      "Effect": "Deny",
      "Action": ["iam:DeleteRolePermissionsBoundary", "iam:CreatePolicyVersion",
                 "iam:SetDefaultPolicyVersion", "iam:DeletePolicy"],
      "Resource": ["arn:aws:iam::111111111111:role/*",
                   "arn:aws:iam::111111111111:policy/app-boundary"]
    },
    {
      "Sid": "PassOnlyAppRoles",
      "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "arn:aws:iam::111111111111:role/app-*"
    }
  ]
}

Now a developer can attach AdministratorAccess to an app-* role, and it does not matter: the role's effective permissions are the intersection with app-boundary. The Deny stops them from removing or rewriting the boundary, and the name prefix keeps them away from platform roles.

Dangerous patterns to catch in review

  • NotAction with Allow. "NotAction": "iam:*" with Allow on * grants everything except IAM, including every service AWS launches next year. NotAction belongs in Deny statements (like the region lock).
  • Write actions on "Resource": "*". Fine for Describe* and List*. Not fine for s3:DeleteObject or dynamodb:DeleteTable.
  • Wildcard principals. "Principal": "*" in a bucket, queue or key policy is public unless a condition such as aws:PrincipalOrgID or aws:SourceVpce narrows it.
  • NotPrincipal with Deny. It behaves badly with boundaries and sessions. AWS recommends ArnNotEquals on aws:PrincipalArn instead.
  • Trust policies that trust a whole account when one role would do.
Quick check
A CI role has lambda:CreateFunction, lambda:InvokeFunction and iam:PassRole on *. Nothing else. Why is this a security finding?
Need a nudge? A hint rules out a wrong answer.

Tools: reading denials and proving policies

Read the error. AccessDenied messages for many services now name the policy type, and sometimes its ARN:

User: arn:aws:sts::111111111111:assumed-role/report-lambda/fn is not authorized to perform:
s3:GetObject on resource: arn:aws:s3:::reports-b/q3.csv
with an explicit deny in a service control policy

"with an explicit deny in a X policy" means find the Deny. "because no X policy allows" means an Allow is missing in that layer. When several layers deny, only one is named.

IAM Access Analyzer does four jobs worth knowing:

  • Policy validation: grammar errors, security warnings and suggestions, in the console editor or the CLI. Run it in CI.
  • Custom policy checks: check-no-new-access compares a changed policy with the old one, check-access-not-granted fails if a policy grants actions you list (like iam:PassRole), and check-no-public-access catches public resource policies. These are how teams block risky policy changes in pull requests.
  • External and unused access findings: resources shared outside your account or org, and roles, keys and permissions nobody has used.
  • Policy generation: builds a starting policy from what a role actually called, using CloudTrail.
aws accessanalyzer validate-policy --policy-type IDENTITY_POLICY --policy-document file://developer-iam.jsonaws iam simulate-principal-policy --policy-source-arn arn:aws:iam::111111111111:role/report-lambda --action-names s3:GetObject --resource-arns arn:aws:s3:::reports-eu/q3.csv

The policy simulator (simulate-principal-policy) evaluates the identity policies and boundary of a real principal against an action. It does not cover everything (for example, cross-account resource policies need extra input), so treat it as one signal alongside CloudTrail.

Put it in order5 steps

Put the layers of a same-account evaluation in the order AWS considers them.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
permissions boundary
A managed policy set on a user or role that caps what its identity policies can grant. Grants nothing itself.
SCP
Service control policy. An Organizations policy that caps what principals in member accounts can do. Never grants.
RCP
Resource control policy. An Organizations policy that caps what anyone can do to resources in member accounts.
session policy
A policy passed in an AssumeRole call that narrows that one session's permissions.
confused deputy
A trusted service tricked into using its access on behalf of the wrong party. Prevented with an external ID or aws:SourceArn.
ABAC
Attribute-based access control: one policy that compares principal tags with resource tags.
external ID
A per-customer value a third party must send when assuming your role, checked with the sts:ExternalId condition.