Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 02 · 50 minutes

Read a policy and decide a request the way the provider does

After this lesson you can
  • Name the principals of an account and the five elements of a policy statement
  • Apply the evaluation order of explicit deny, allow and implicit deny
  • Run a small policy evaluator over a list of requests and explain each decision
Lab files of this lesson (4)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

A developer at Larkfield, Chloe, opens a ticket: "I am an administrator. Why can I not stop the audit trail for maintenance?" The same day the backup job fails from a new server with "access denied". Your lead says: "Both answers are in the policies. Read them, and show me the decision for each request, not a guess." To answer, you need the policy language and the order in which AWS reads it.

Recall

Lesson 1: what are the six parts of an ARN?

arn, the partition, the service, the region, the account and the resource, separated by colons. The region is empty for a global service such as IAM.

Lesson 1: why is identity called the perimeter of a cloud account?

Because the control plane is reachable from the whole internet. The only check between a stranger and the account is who signed the request and what that identity may do.

The idea

A principal is whoever sends a request. AWS Identity and Access Management (IAM) knows these kinds.

PrincipalWhat it is
Root userThe owner of the account, with every right. It is for a few account tasks only, never for daily work.
IAM userAn identity for one person or one program, with long-lived credentials: a password, or access keys (lesson 4).
RoleAn identity with no credentials of its own. A principal assumes the role and gets temporary credentials. A role has a trust policy that says who may assume it.
GroupA set of users that share policies. A group cannot send a request, so it is not a principal.

A policy is a JSON document with a list of statements. Each statement has up to five elements.

ElementMeaningExample
EffectAllow or Deny"Deny"
ActionThe API calls, as service:Operation. * stands for any text."s3:GetObject", "ec2:Describe*"
ResourceThe ARNs that the statement is about"arn:aws:s3:::larkfield-orders/*"
ConditionExtra tests on the request, as operator, key and value{"IpAddress": {"aws:SourceIp": "192.0.2.0/24"}}
PrincipalWho the statement is for. Only in policies that are attached to a resource.{"AWS": "arn:aws:iam::111122223333:user/dmitri.volkov"}

An identity-based policy is attached to a user, a group or a role: "this identity may do X". A resource-based policy is attached to a resource, for example to a bucket: "these principals may do X with me". The trust policy of a role is a resource-based policy.

AWS decides each request in this order.

How one request is decided
RequestAny matching Deny?Explicit denyAny matching Allow?AllowImplicit denycollect every statement that matchesyes, it ends herenoyesno, nothingallowed itRequestAny matching Deny?Explicit denyAny matching Allow?AllowImplicit deny12345
  1. Request → Any matching Deny?: collect every statement that matches
  2. Any matching Deny? → Explicit deny: yes, it ends here
  3. Any matching Deny? → Any matching Allow?: no
  4. Any matching Allow? → Allow: yes
  5. Any matching Allow? → Implicit deny: no, nothing allowed it
  • The start is deny. Nothing is allowed until a statement allows it. This is the implicit deny.
  • One matching Deny in any policy wins over every Allow. This is the explicit deny.
  • Inside one account, an Allow in the identity-based policies or in the policy of the resource is enough. When the principal and the resource are in different accounts, both sides must allow.

Other policy types can only take rights away. A permissions boundary is the most that one user or role can get. A service control policy (SCP) of an organisation is the most that a whole account can get: it never grants anything. A session policy limits one session of a role. A boundary and a session policy limit what the identity's own policies can grant, and an SCP limits the whole account. A boundary does not limit a resource policy that names the user itself. The IAM User Guide has the full table. You will meet these by name at work. This lesson evaluates the two types that grant.

A condition key that is missing from the request makes the test fail. Put IfExists after the operator to let a missing key pass. This matters for MFA (multi-factor authentication, from "Security fundamentals", lesson 3): the key aws:MultiFactorAuthPresent is not in a request that is signed with long-lived access keys. Step 5 shows what that does.

Same idea, other namesAWSMicrosoft AzureGoogle Cloud
A rule that grants rightsPolicy statement with AllowRole assignment: a security principal, a role definition and a scopeRole binding in an allow policy
A rule that takes rights awayStatement with DenyDeny assignment (created and managed by Azure)Deny policy, checked before the allow policies
An identity for a workloadRoleManaged identityService account

Worked example

1. Read two policies of the snapshot

account/iam.json holds the users, groups, roles and policies of the account. The wrapper is our own shape. The policy documents inside have the real form of AWS.

python3 -c "
import json
iam = json.load(open('account/iam.json'))
for name in ('GuardRails', 'BackupWrite'):
    print(name, json.dumps(iam['policies'][name]['Statement']))
print([(g['name'], g['policies']) for g in iam['groups']])
print([(u['name'], u['groups'], u['policies']) for u in iam['users'][:3]])"
GuardRails [{"Effect": "Deny", "Action": ["s3:DeleteBucket", "cloudtrail:StopLogging", "cloudtrail:DeleteTrail"], "Resource": "*"}]
BackupWrite [{"Effect": "Allow", "Action": "s3:PutObject", "Resource": "arn:aws:s3:::larkfield-backups/*", "Condition": {"IpAddress": {"aws:SourceIp": "192.0.2.0/24"}}}]
[('Admins', ['AdminAll']), ('Developers', ['DevCompute', 'GuardRails']), ('Auditors', ['ReadOnlyAudit'])]
[('alice.morgan', ['Admins'], []), ('ben.okafor', ['Developers'], ['HelpdeskKeys']), ('chloe.tan', ['Developers', 'Admins'], [])]

GuardRails is one Deny statement for three actions on every resource. It is attached to the group Developers. BackupWrite allows one action on one bucket, and only when the request comes from the office network.

2. Decide three requests by hand

account/requests.json holds 40 requests, each with a principal, an action, a resource and a context (facts about the request, such as the source address).

  • R03: Chloe calls cloudtrail:StopLogging. She is in Admins (the policy AdminAll allows * on *) and in Developers (GuardRails denies that action). An Allow matches and a Deny matches. The Deny wins: explicit deny. That is the answer to her ticket.
  • R05: backup-bot calls s3:PutObject on the backup bucket from 192.0.2.21. The action and the resource match BackupWrite, and the address is inside 192.0.2.0/24: allow.
  • R06: the same request from 203.0.113.9. The condition fails, so the statement does not match. Nothing else allows it: implicit deny. The new server is outside the office network.

3. Save the evaluator

policy_eval.py does the same in code. It is a teaching tool: it knows five condition operators and no NotAction, no policy variables and no boundaries. The real evaluator of AWS knows many more. Two functions hold the logic. statement_matches asks whether one statement speaks about a request: the action, the resource and the condition must all fit. fnmatch.fnmatchcase(text, pattern) is a function of the standard library that compares a text with a pattern in which * stands for any text and ? for one character.

def statement_matches(statement, request):
    """Does one statement speak about this request? Action, Resource and Condition must all fit."""
    return (any(like(a, request["action"]) for a in as_list(statement["Action"]))
            and any(like(res, request["resource"]) for res in as_list(statement["Resource"]))
            and condition_ok(statement.get("Condition", {}), request.get("context", {})))

decide collects the matching statements of all policies and applies the order of the diagram.

def decide(policies, request):
    """The decision for one request: 'explicit deny', 'allow' or 'implicit deny'."""
    matched = [st for policy in policies for st in as_list(policy["Statement"]) if statement_matches(st, request)]
    if any(st["Effect"] == "Deny" for st in matched):
        return "explicit deny"
    if any(st["Effect"] == "Allow" for st in matched):
        return "allow"
    return "implicit deny"

The rest of the file reads a condition (condition_ok) and finds the policies of a principal: a user gets its own policies and those of its groups (policy_names). ipaddress.ip_address(a) in ipaddress.ip_network(n) tests whether an address is inside a network, and removesuffix cuts a known ending from a text. next(x for x in items if test) returns the first item that passes the test. Open the block and save the file.

The finished file: policy_eval.py

policy_eval.py

"""policy_eval.py: decide a request against identity-based policies.

    python3 policy_eval.py [folder]        decide every request of folder/requests.json (default folder: account)
"""
import fnmatch
import ipaddress
import json
import sys
from collections import Counter


def as_list(value):
    """A policy may give one value or a list of values. Always work with a list."""
    return value if isinstance(value, list) else [value]


def like(pattern, text):
    """True when the text fits the pattern. * stands for any text and ? for one character."""
    return fnmatch.fnmatchcase(text, pattern)


TESTS = {
    "StringEquals": lambda have, want: have == want,
    "StringLike": lambda have, want: like(want, have),
    "Bool": lambda have, want: str(have).lower() == str(want).lower(),
    "IpAddress": lambda have, want: ipaddress.ip_address(have) in ipaddress.ip_network(want),
    "DateLessThan": lambda have, want: have < want,  # both are UTC times in the same text form, so text order is time order
}


def condition_ok(condition, context):
    """Every operator and every key must hold. For one key, one of its values is enough."""
    for operator, pairs in condition.items():
        if_exists = operator.endswith("IfExists")
        name = operator.removesuffix("IfExists")
        if name not in TESTS:
            raise ValueError(f"the operator {operator} is not supported by this evaluator")
        for key, wanted in pairs.items():
            if key not in context:
                if if_exists:
                    continue  # ...IfExists: a missing key does not fail the test
                return False
            if not any(TESTS[name](context[key], want) for want in as_list(wanted)):
                return False
    return True


def statement_matches(statement, request):
    """Does one statement speak about this request? Action, Resource and Condition must all fit."""
    return (any(like(a, request["action"]) for a in as_list(statement["Action"]))
            and any(like(res, request["resource"]) for res in as_list(statement["Resource"]))
            and condition_ok(statement.get("Condition", {}), request.get("context", {})))


def decide(policies, request):
    """The decision for one request: 'explicit deny', 'allow' or 'implicit deny'."""
    matched = [st for policy in policies for st in as_list(policy["Statement"]) if statement_matches(st, request)]
    if any(st["Effect"] == "Deny" for st in matched):
        return "explicit deny"
    if any(st["Effect"] == "Allow" for st in matched):
        return "allow"
    return "implicit deny"


def policy_names(iam, arn):
    """The names of the policies that apply to a user (its own and those of its groups) or to a role."""
    kind, name = arn.split(":")[-1].split("/", 1)
    if kind == "role":
        return next(x["policies"] for x in iam["roles"] if x["name"] == name)
    user = next(u for u in iam["users"] if u["name"] == name)
    names = list(user["policies"])
    for group in iam["groups"]:
        if group["name"] in user["groups"]:
            names += group["policies"]
    return names


def policies_of(iam, arn):
    return [iam["policies"][name] for name in policy_names(iam, arn)]


def load(folder, name):
    with open(f"{folder}/{name}") as src:
        return json.load(src)


if __name__ == "__main__":
    folder = sys.argv[1] if len(sys.argv) > 1 else "account"
    iam, count = load(folder, "iam.json"), Counter()
    for request in load(folder, "requests.json"):
        decision = decide(policies_of(iam, request["principal"]), request)
        count[decision] += 1
        who = request["principal"].split(":")[-1]
        print(f"{request['id']} {decision:13s} {who:23s} {request['action']:24s} {request['resource'].split(':')[-1][:34]}")
    print(", ".join(f"{name} {n}" for name, n in sorted(count.items())))

4. Run it over the requests

head -n 6 shows the first six lines of the output, and tail -n 1 the last line.

python3 policy_eval.py | head -n 6
python3 policy_eval.py | tail -n 1
R01 allow         user/alice.morgan       s3:DeleteBucket          larkfield-orders
R02 allow         user/ben.okafor         ec2:StopInstances        instance/i-0a11b22c33d44e551
R03 explicit deny user/chloe.tan          cloudtrail:StopLogging   trail/larkfield-trail
R04 implicit deny user/dmitri.volkov      s3:PutObject             larkfield-orders/2026/11/orders.cs
R05 allow         user/backup-bot         s3:PutObject             larkfield-backups/db/2026-11-20.du
R06 implicit deny user/backup-bot         s3:PutObject             larkfield-backups/db/2026-11-20.du
allow 22, explicit deny 2, implicit deny 16

The first six are the ones you can check by hand. R04 is the auditor: his policy allows reading, and writing an object matches nothing, so the answer is an implicit deny.

5. See the MFA trap

A common guard is "deny everything when the caller has no MFA". Write it two ways and test it with a request that carries no MFA key at all, as a request with long-lived access keys does.

python3 -c "
from policy_eval import decide
allow_all = {'Statement': [{'Effect': 'Allow', 'Action': '*', 'Resource': '*'}]}
def guard(operator):
    return {'Statement': [{'Effect': 'Deny', 'Action': '*', 'Resource': '*',
                           'Condition': {operator: {'aws:MultiFactorAuthPresent': 'false'}}}]}
with_key = {'action': 'iam:CreateUser', 'resource': '*', 'context': {}}
console_no_mfa = {'action': 'iam:CreateUser', 'resource': '*', 'context': {'aws:MultiFactorAuthPresent': 'false'}}
for operator in ('Bool', 'BoolIfExists'):
    print(operator, '| access key:', decide([allow_all, guard(operator)], with_key),
          '| console without MFA:', decide([allow_all, guard(operator)], console_no_mfa))"
Bool | access key: allow | console without MFA: explicit deny
BoolIfExists | access key: explicit deny | console without MFA: explicit deny

With Bool, the guard stops a console session without MFA and lets a stolen access key through, because the key is missing and the Deny does not match. BoolIfExists treats the missing key as a match and denies both. The AWS documentation recommends the second form for this guard.

6. Decide one request between two accounts by hand

Your turn uses a file of a new shape. account/cross.json has three keys: the account of the bucket, the policy of the bucket and a list of requests. Print the first request and the three statements of the bucket policy.

python3 -c "
import json
case = json.load(open('account/cross.json'))
print(list(case), case['resource_account'])
x = case['requests'][0]
print(x['id'], x['principal'], x['principal_account'], x['action'], x['resource'])
print(json.dumps(x['identity_policies'][0]['Statement'][0]['Action']))
for st in case['resource_policy']['Statement']:
    print(st['Effect'], st['Principal'], st['Action'])"
['resource_account', 'resource_policy', 'requests'] 111122223333
X1 arn:aws:iam::111122223333:user/dmitri.volkov 111122223333 s3:PutObject arn:aws:s3:::larkfield-partner/inbox/a.csv
["s3:Get*", "s3:List*", "iam:Get*", "iam:List*", "ec2:Describe*", "cloudtrail:LookupEvents"]
Allow {'AWS': 'arn:aws:iam::444455556666:role/build'} s3:GetObject
Allow {'AWS': 'arn:aws:iam::111122223333:user/dmitri.volkov'} s3:PutObject
Deny * s3:DeleteObject
  • X1: Dmitri writes to inbox/a.csv. His own policy only reads, so the identity side says no. The second statement of the bucket policy names him and allows s3:PutObject on inbox/*. He and the bucket are in the same account, so one Allow is enough: allow.
  • X6: the role build of the other account reads the same file, and the bucket policy names the role. But the role has no identity-based policy at all, and the accounts differ, so both sides must allow: implicit deny.

Your turn

The bucket larkfield-partner has a policy of its own, and partners from the development account 444455556666 use it. The file account/cross.json holds that policy (resource_policy), the account of the bucket (resource_account) and ten requests. Each request names the principal, the account of the principal, and the identity-based policies of that principal.

Two callers, one bucket policy
Account 444455556666Account 111122223333Build roleDmitriPartner bucket12Account 444455556666Account 111122223333Build roleDmitriPartner bucket12
  1. Dmitri → Partner bucket: same account, one Allow is enough
  2. Build role → Partner bucket: other account, both sides must allow

Write a program that decides the ten requests with both kinds of policy:

  • A statement of the resource policy counts only when its Principal names the caller: "*", the ARN of the caller, or the ARN arn:aws:iam::ACCOUNT:root of the caller's account (in this exercise it counts as naming every principal of that account; in real AWS it hands the decision to the policies of that account, see the Field notes).
  • An explicit deny on either side wins.
  • Same account: one Allow, on either side, is enough. Different accounts: both sides must allow.

Import decide and statement_matches from policy_eval.py. A Principal is a plain text, or a dictionary with the key AWS that holds a text or a list. This is the skeleton:

def principal_named(statement, request):
    """True when the Principal names the caller (the three cases above)."""

def decide_cross(case, request):
    # 1. the statements of case["resource_policy"] that name the caller and match the request
    # 2. call decide() twice: with request["identity_policies"], and with a policy that holds the statements of step 1.
    #    An explicit deny on either side wins.
    # 3. same account: one allow is enough. Other account: both sides must allow.

Check yourself

A user has a policy that allows s3:* on every resource. A group of the user has a policy that denies s3:DeleteBucket. Can the user delete a bucket?

No. Both statements match the request, and an explicit deny wins over every allow, wherever the allow comes from. This is why a guard that must hold for everyone is written as a Deny.

An administrator removes every policy from a user. A bucket in the same account has a policy that allows this user to read it. Can the user still read the bucket?

Yes. Inside one account, an allow in the resource-based policy is enough, with no identity-based policy at all. To review who can reach a resource, you must read the policies on both sides. Lesson 5 does that for buckets.

Why does a service control policy that allows everything give a new user no rights?

Because a service control policy never grants. It sets the most that the identities of an account can get. The user still needs an Allow in an identity-based or resource-based policy, and has none.

Field notes

  • At work, test a decision with the provider's own tools, not a home-made evaluator: the IAM policy simulator, and IAM Access Analyzer, which also checks a policy for common mistakes. This evaluator exists so that you understand them.
  • NotAction and NotResource turn a statement around ("everything except"). An Allow with NotAction grants every action that exists and every action that the provider adds next year. Treat it as a wildcard in a review.
  • Read the trust policy of every role as carefully as its permissions. The permissions say what the role can do, and the trust policy says who can become the role.
  • Conditions are where most real policies go wrong: a wrong operator, a missing key, a typing error. A condition that never matches turns an Allow or a Deny into nothing, with no error.
  • Read the current "Policy evaluation logic" in the IAM User Guide for boundaries, session policies and requests between accounts. A Principal of arn:aws:iam::ACCOUNT:root means "this account". It is not "only the root user" and not "everyone in the account": the policies of that account decide who may use the access.