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 03 · 50 minutes

Find policies that give too much and write a smaller one

After this lesson you can
  • Recognise wildcards, administrator rights and escalation paths in a policy
  • Audit the users, roles and policies of an account with a program
  • Replace a broad policy with one that allows only what was used
Lab files of this lesson (6)

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

The map of lesson 1 showed three machines in Sydney that nobody owns. Before you look at the logs, your lead wants to know what is possible: "Which identities of this account could have started them? Who can do more than their job needs? Give me the list, worst first, and then fix the deploy user, because its policy was written in a hurry." A stolen key can do exactly what its policy allows, so the policy is the size of the damage.

Recall

Lesson 2: in which order does AWS decide a request?

Collect every statement that matches. One matching Deny ends it: explicit deny. If no Deny matches and one Allow matches: allow. If nothing matches: implicit deny.

Lesson 2: what is the difference between the permissions of a role and its trust policy?

The permissions say what the role may do. The trust policy is a resource-based policy on the role: it says which principals may assume the role and get its temporary credentials.

The idea

Least privilege means that an identity can do what its task needs and nothing more ("Security fundamentals", lesson 4). In a cloud, a review looks for five patterns.

PatternLooks likeWhy it matters
Administrator"Action": "*" on "Resource": "*"The identity can do everything, including giving rights to others. Few people need it, and no workload should.
Service wildcard"s3:*" on "*"Every action of one service, on everything: read all data, delete all data.
Escalation actioniam:PassRole, iam:CreateAccessKey, iam:AttachUserPolicy on *The identity can raise its own rights. See below.
Wide trustA trust policy with "Principal": {"AWS": "*"} and no conditionAny principal of any account can become the role.
Weak people accountsA console user with no MFA, an account that nobody has used for monthsOne guessed or reused password is enough.

An escalation action does not look dangerous by itself. A defender must know these by name.

ActionWhat it lets the holder do
iam:PassRoleHand a role to a service, for example to a new machine. The machine then acts with that role. With Resource: *, the holder can choose the strongest role of the account.
iam:CreateAccessKey, iam:UpdateLoginProfile, iam:CreateLoginProfileMake a new key or set a new password for a user. On user/*, that includes the administrators.
iam:AttachUserPolicy, iam:AttachRolePolicy, iam:PutUserPolicy, iam:PutRolePolicy, iam:CreatePolicyVersionGive more rights to an identity, or rewrite a policy that many identities share.
iam:UpdateAssumeRolePolicyChange who may assume a role.
iam:AddUserToGroupJoin a group with more rights.
An escalation path in the Larkfield account
InternetLarkfield accountAttackerDeploy keyNew machineAdmin role1234InternetLarkfield accountAttackerDeploy keyNew machineAdmin role1234
  1. Attacker → Deploy key: finds the key of the deploy user
  2. Deploy key → New machine: starts a machine, which it may do
  3. Deploy key → Admin role: passes the role to the machine
  4. New machine → Admin role: acts with every right of the role

The role in the picture is ec2-maintenance, a role for machines that holds an administrator policy.

Nobody gave the deploy user administrator rights. Two harmless-looking decisions, in two different policies, add up to them. A review must follow the chain, not only read each policy alone.

Worked example

1. Read the policy of the deploy user

python3 -c "
import json
iam = json.load(open('account/iam.json'))
print(json.dumps(iam['policies']['DeployFull'], indent=1))" | head -n 20
{
 "Version": "2012-10-17",
 "Statement": [
  {
   "Effect": "Allow",
   "Action": [
    "s3:*",
    "ec2:*",
    "lambda:*"
   ],
   "Resource": "*"
  },
  {
   "Effect": "Allow",
   "Action": "iam:PassRole",
   "Resource": "*"
  }
 ]
}

The first statement holds three service wildcards on every resource. The second is iam:PassRole on *.

2. Save the audit program

iam_audit.py reads iam.json and returns findings, worst first. The function audit_policy judges one policy document. It looks only at Allow statements, because a Deny cannot give too much. It imports as_list and like from the evaluator of lesson 2. Each finding is a dictionary with a severity, a short code, a subject and a text.

def audit_policy(name, policy):
    """The findings of one policy document. Only Allow statements can give too much."""
    out = []
    for st in as_list(policy["Statement"]):
        if st["Effect"] != "Allow":
            continue
        actions, resources = as_list(st["Action"]), as_list(st["Resource"])
        everywhere = "*" in resources
        if "*" in actions and everywhere:
            out.append(finding("medium", "ADMIN", f"policy {name}", "every action on every resource: check who holds it"))
            continue
        for action in actions:
            if action.endswith(":*") and everywhere:
                out.append(finding("high", "WILDCARD", f"policy {name}", f"{action} on every resource"))
            risky = [e for e in ESCALATION if like(action, e)]
            if risky and any("*" in res for res in resources):
                out.append(finding("high", "ESCALATION", f"policy {name}", f"{action} on {', '.join(resources)}"))
    return out

The line with risky asks whether the action of the statement covers one of the escalation actions: like("iam:*", "iam:PassRole") is true, so a wildcard is caught too. The function audit adds the checks on people and roles: a console user without MFA, a user who has not signed in for 90 days or has never signed in, a trust policy for everyone, and a role for a service that holds administrator rights. date.fromisoformat turns a text such as 2026-11-21 into a date, so that two dates can be subtracted. The snapshot was taken on 21 November 2026, and the program uses that date as "today". Open the block and save the file.

The finished file: iam_audit.py

iam_audit.py

"""iam_audit.py: find policies, roles and users that give more access than they should.

    python3 iam_audit.py [folder]              audit folder/iam.json (default folder: account)
    python3 iam_audit.py --policy FILE         audit one policy document
Exit code 1 when a finding is critical or high.
"""
import json
import sys
from datetime import date

from policy_eval import as_list, like

ORDER = ["critical", "high", "medium", "low"]
# Actions that let a principal give itself, or someone else, more access than it has.
ESCALATION = ["iam:PassRole", "iam:CreateAccessKey", "iam:CreateLoginProfile", "iam:UpdateLoginProfile", "iam:AttachUserPolicy",
              "iam:AttachRolePolicy", "iam:PutUserPolicy", "iam:PutRolePolicy", "iam:CreatePolicyVersion",
              "iam:UpdateAssumeRolePolicy", "iam:AddUserToGroup"]


def finding(severity, code, subject, text):
    return {"severity": severity, "code": code, "subject": subject, "text": text}


def audit_policy(name, policy):
    """The findings of one policy document. Only Allow statements can give too much."""
    out = []
    for st in as_list(policy["Statement"]):
        if st["Effect"] != "Allow":
            continue
        actions, resources = as_list(st["Action"]), as_list(st["Resource"])
        everywhere = "*" in resources
        if "*" in actions and everywhere:
            out.append(finding("medium", "ADMIN", f"policy {name}", "every action on every resource: check who holds it"))
            continue
        for action in actions:
            if action.endswith(":*") and everywhere:
                out.append(finding("high", "WILDCARD", f"policy {name}", f"{action} on every resource"))
            risky = [e for e in ESCALATION if like(action, e)]
            if risky and any("*" in res for res in resources):
                out.append(finding("high", "ESCALATION", f"policy {name}", f"{action} on {', '.join(resources)}"))
    return out


def is_admin(iam, names):
    return any(f["code"] == "ADMIN" for n in names for f in audit_policy(n, iam["policies"][n]))


def audit(iam, today="2026-11-21"):
    out = []
    for name, policy in iam["policies"].items():
        out += audit_policy(name, policy)
    group_policies = {g["name"]: g["policies"] for g in iam["groups"]}
    for u in iam["users"]:
        names = u["policies"] + [p for g in u["groups"] for p in group_policies[g]]
        admin = is_admin(iam, names)
        if u["console"] and not u["mfa"]:
            out.append(finding("high" if admin else "medium", "NO-MFA", f"user {u['name']}",
                               "signs in with a password only" + (" and is an administrator" if admin else "")))
        if u["console"] and u["last_login"] is None:
            out.append(finding("medium", "STALE", f"user {u['name']}", "has a password and has never signed in"))
        elif u["console"] and (date.fromisoformat(today) - date.fromisoformat(u["last_login"])).days > 90:
            out.append(finding("medium", "STALE", f"user {u['name']}", f"last sign-in {u['last_login']}"))
    for x in iam["roles"]:
        for st in as_list(x["trust"]["Statement"]):
            principal = st["Principal"]
            callers = as_list(principal.get("AWS", [])) if isinstance(principal, dict) else [principal]
            service = isinstance(principal, dict) and "Service" in principal
            if "*" in callers and "Condition" not in st:
                out.append(finding("critical", "TRUST-ANYONE", f"role {x['name']}", "any principal of any account may assume it"))
            for caller in callers:
                if caller != "*" and iam["account"] not in caller:
                    out.append(finding("low", "TRUST-EXTERNAL", f"role {x['name']}", f"trusts {caller}"))
            if service and is_admin(iam, x["policies"]):
                out.append(finding("high", "WORKLOAD-ADMIN", f"role {x['name']}",
                                   f"a workload of {principal['Service']} gets every action on every resource"))
    return sorted(out, key=lambda f: (ORDER.index(f["severity"]), f["code"], f["subject"]))


def show(findings):
    for f in findings:
        print(f"{f['severity']:8s} {f['code']:14s} {f['subject']:25s} {f['text']}")
    counts = ", ".join(f"{s} {sum(f['severity'] == s for f in findings)}" for s in ORDER)
    print(f"{len(findings)} findings: {counts}")
    return 1 if any(f["severity"] in ("critical", "high") for f in findings) else 0


if __name__ == "__main__":
    if len(sys.argv) > 2 and sys.argv[1] == "--policy":
        with open(sys.argv[2]) as src:
            sys.exit(show(audit_policy(sys.argv[2], json.load(src))))
    with open((sys.argv[1] if len(sys.argv) > 1 else "account") + "/iam.json") as src:
        sys.exit(show(audit(json.load(src))))

3. Audit the account

echo "exit code $?" prints the exit code of the command before it. The audit ends with 1 when a finding is critical or high.

python3 iam_audit.py
echo "exit code $?"
critical TRUST-ANYONE   role support-partner      any principal of any account may assume it
high     ESCALATION     policy DeployFull         iam:PassRole on *
high     ESCALATION     policy HelpdeskKeys       iam:CreateAccessKey on arn:aws:iam::111122223333:user/*
high     ESCALATION     policy HelpdeskKeys       iam:UpdateLoginProfile on arn:aws:iam::111122223333:user/*
high     NO-MFA         user nadia.temp           signs in with a password only and is an administrator
high     WILDCARD       policy DeployFull         s3:* on every resource
high     WILDCARD       policy DeployFull         ec2:* on every resource
high     WILDCARD       policy DeployFull         lambda:* on every resource
high     WILDCARD       policy ReportsRead        logs:* on every resource
high     WORKLOAD-ADMIN role ec2-maintenance      a workload of ec2.amazonaws.com gets every action on every resource
medium   ADMIN          policy AdminAll           every action on every resource: check who holds it
medium   NO-MFA         user ben.okafor           signs in with a password only
medium   STALE          user nadia.temp           last sign-in 2025-08-14
low      TRUST-EXTERNAL role dev-cross-account    trusts arn:aws:iam::444455556666:root
14 findings: critical 1, high 9, medium 3, low 1
exit code 1

Read it from the top. The role support-partner can be assumed by anyone in the world. DeployFull has four findings. HelpdeskKeys lets its holder make a key for any user, administrators included. nadia.temp is an administrator with a password only, who last signed in fifteen months ago. The line TRUST-EXTERNAL is low: the other account belongs to the same company, but the trust must be known.

4. Follow the chain

A finding says what a policy allows. To see what an identity can reach, ask the evaluator. Can the deploy user pass the role ec2-maintenance, and who holds the administrator policy?

python3 -c "
import json
from policy_eval import decide, policies_of, policy_names
iam = json.load(open('account/iam.json'))
me = 'arn:aws:iam::111122223333:user/ci-deploy'
for action, resource in (('iam:PassRole', 'arn:aws:iam::111122223333:role/ec2-maintenance'), ('ec2:RunInstances', '*'), ('iam:CreateUser', '*')):
    print(action, '->', decide(policies_of(iam, me), {'action': action, 'resource': resource}))
print('AdminAll:', [x['name'] for x in iam['users'] + iam['roles'] if 'AdminAll' in policy_names(iam, x['arn'])])"
iam:PassRole -> allow
ec2:RunInstances -> allow
iam:CreateUser -> implicit deny
AdminAll: ['alice.morgan', 'chloe.tan', 'nadia.temp', 'svc-monitor', 'ec2-maintenance', 'ops-admin']

The deploy user cannot create a user. It can start a machine and hand it the role ec2-maintenance, which can. That is the path of the diagram. The last line has a second surprise: the user that had no owner tag in lesson 1 holds AdminAll.

5. Test a policy against what it must and must not allow

policy_test.py reads a policy file and a test file with two lists: requests that the policy must allow and requests that it must not allow. It prints what is missing and what is too much.

policy_test.py

"""policy_test.py: test a policy document against requests that it must allow and requests that it must not allow.

    python3 policy_test.py POLICY.json [TESTS.json]        default tests: account/ci-tests.json
"""
import json
import sys

from policy_eval import decide

with open(sys.argv[1]) as src:
    policy = json.load(src)
with open(sys.argv[2] if len(sys.argv) > 2 else "account/ci-tests.json") as src:
    tests = json.load(src)

missing = [t for t in tests["must_allow"] if decide([policy], t) != "allow"]
too_much = [t for t in tests["must_not_allow"] if decide([policy], t) == "allow"]
for t in missing:
    print(f"MISSING   {t['action']} on {t['resource']}")
for t in too_much:
    print(f"TOO MUCH  {t['action']} on {t['resource']}")
print(f"needed: {len(tests['must_allow']) - len(missing)} of {len(tests['must_allow'])} allowed")
print(f"forbidden: {len(too_much)} of {len(tests['must_not_allow'])} allowed")
print("pass" if not missing and not too_much else "fail")
sys.exit(0 if not missing and not too_much else 1)

Write DeployFull into a file of its own, test it, and audit that one file with the option --policy.

python3 -c "
import json
iam = json.load(open('account/iam.json'))
json.dump(iam['policies']['DeployFull'], open('DeployFull.json', 'w'), indent=1)"
python3 policy_test.py DeployFull.json | tail -n 3
python3 iam_audit.py --policy DeployFull.json | tail -n 1
needed: 6 of 6 allowed
forbidden: 7 of 8 allowed
fail
4 findings: critical 0, high 4, medium 0, low 0

The policy allows everything that the deploy job needs, and seven of the eight things that it must never do.

Your turn

Write the replacement. account/ci-usage.json lists what the deploy user really called in the last 90 days: six actions, each with its resource. Write a policy file DeployLeast.json that allows exactly those and nothing else. Keep the form of a real policy document (Version, Statement, and in each statement Effect, Action, Resource). Then test it with policy_test.py and audit it with iam_audit.py --policy.

One note on the data: ec2:DescribeInstances is listed with the resource *, because that action cannot be limited to single machines. A specific action on * is not a wildcard finding.

Check yourself

Your policy still holds iam:PassRole. Why is that not a finding any more?

Because the resource is one named role, report-lambda-role, and not *. The deploy job must hand that role to the function that it deploys. The danger of iam:PassRole is the choice of role: with one fixed role that has few rights, there is nothing to escalate to.

A role is trusted by ec2.amazonaws.com and holds an administrator policy. Nobody can sign in as that role. Why is it a high finding?

Any identity that may start a machine and pass this role gets a machine with every right, and any program on that machine, including a program with a flaw, can use those rights (lesson 8). A workload should hold the few rights of its task.

The audit prints 0 findings for a policy. Does that prove that the policy follows least privilege?

No. The audit knows a few patterns. A policy that allows s3:GetObject on every bucket of the account passes it, and still gives far more than one job needs. The test of step 5 is the stronger proof: a list of what the job must do, and a list of what it must never do, both decided by the evaluator.

Field notes

  • Build a least-privilege policy from use, not from a guess. IAM records when each service was last used by an identity ("last accessed" information), and IAM Access Analyzer can write a policy from the audit log. Start from that and review it.
  • Remove rights in two steps: first attach a permissions boundary or a Deny and watch the logs for refused calls, then delete the broad policy. A deploy job that fails on a Friday evening makes the next clean-up much harder to get approved.
  • Review trust policies for the names of other accounts. When a role is for a partner, the usual guard is a condition on sts:ExternalId, a value that both sides agreed on.
  • Give people rights through groups or, better, through roles that they assume with MFA. A policy attached straight to one user is the one that everybody forgets when that person changes jobs.
  • The CIS AWS Foundations Benchmark has controls for these findings: no administrator policy on users, MFA for console users, unused credentials removed. Read the current version at the source and map your findings to it.